From 7a749c31515844be9e4c96b5354e8cefca9526d6 Mon Sep 17 00:00:00 2001 From: Raghuvar Karthik Durga <177662415+drk-ram@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:01:39 -0600 Subject: [PATCH 1/3] fix(data_flow,propagation): validate size_bytes/token_count in Python data_flow and reject control chars and conflicting headers in propagation (#104) - Validate DataEndpoint types and non-negative safe-integer size_bytes and token_count in Python classified_data_flow, matching TypeScript classifiedDataFlow. - Reject ASCII control characters and conflicting case-insensitive duplicate headers in Python propagation. Closes #104 Signed-off-by: Raghuvar Karthik Durga <177662415+drk-ram@users.noreply.github.com> --- src/agentrust_telemetry/data_flow.py | 12 ++++++++++++ src/agentrust_telemetry/propagation.py | 14 ++++++++----- tests/test_data_flow.py | 27 ++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/src/agentrust_telemetry/data_flow.py b/src/agentrust_telemetry/data_flow.py index 23512b8..dda4f17 100644 --- a/src/agentrust_telemetry/data_flow.py +++ b/src/agentrust_telemetry/data_flow.py @@ -8,6 +8,7 @@ _IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}") _MEDIA_TYPE = re.compile(r"[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+") +_MAX_SAFE_INTEGER = 9007199254740991 @dataclass(frozen=True) @@ -67,12 +68,23 @@ def classified_data_flow( result = classifier.classify(value) if not isinstance(result, ClassificationResult): raise TypeError("classifier must return ClassificationResult") + if not isinstance(source, DataEndpoint): + raise TypeError("source must be a DataEndpoint") + if not isinstance(destination, DataEndpoint): + raise TypeError("destination must be a DataEndpoint") _identifier(purpose, "purpose") if media_type is not None and ( not isinstance(media_type, str) or _MEDIA_TYPE.fullmatch(media_type) is None or len(media_type) > 255 ): raise ValueError("media_type must be a parameter-free type/subtype identifier") + for field_name, amount in (("size_bytes", size_bytes), ("token_count", token_count)): + if amount is not None and ( + isinstance(amount, bool) + or not isinstance(amount, int) + or not 0 <= amount <= _MAX_SAFE_INTEGER + ): + raise ValueError(f"{field_name} must be a non-negative safe integer") optional = { "content_digest": content_digest, "size_bytes": size_bytes, diff --git a/src/agentrust_telemetry/propagation.py b/src/agentrust_telemetry/propagation.py index eea0bd9..3acd799 100644 --- a/src/agentrust_telemetry/propagation.py +++ b/src/agentrust_telemetry/propagation.py @@ -73,11 +73,13 @@ def extract_context(carrier: MutableMapping[str, str]) -> ExtractedContext: def _header(carrier: MutableMapping[str, str], name: str) -> str | None: - value = carrier.get(name) - if value is None: - # HTTP field names are case-insensitive even when a plain mapping is used. - value = next((item for key, item in carrier.items() if key.lower() == name), None) - return None if value is None else _safe_value(name, value, required=True) + matches = [item for key, item in carrier.items() if isinstance(key, str) and key.lower() == name] + if not matches: + return None + validated = [_safe_value(name, item, required=True) for item in matches] + if len(set(validated)) > 1: + raise PropagationError(f"conflicting duplicate {name} header values") + return validated[0] def _safe_value(name: str, value: Any, *, required: bool) -> str: @@ -89,6 +91,8 @@ def _safe_value(name: str, value: Any, *, required: bool) -> str: raise PropagationError(f"{name} exceeds {_MAX_VALUE_LENGTH} characters") if "\r" in value or "\n" in value: raise PropagationError(f"{name} contains a prohibited line break") + if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in value): + raise PropagationError(f"{name} contains a prohibited control character") return value diff --git a/tests/test_data_flow.py b/tests/test_data_flow.py index 0260a72..7f9bb56 100644 --- a/tests/test_data_flow.py +++ b/tests/test_data_flow.py @@ -149,5 +149,32 @@ def test_structured_agt_classification_is_a_value_error(self): with self.assertRaisesRegex(ValueError, "unsupported AGT data classification"): agt_data_classification(SimpleNamespace(classification=bad)) + def test_data_flow_and_propagation_reject_bool_sizes_control_chars_and_conflicting_headers(self): + from agentrust_telemetry import PropagationError + from agentrust_telemetry.propagation import _header, _safe_value + + classifier = RecordingClassifier( + ClassificationResult("example", "internal", "classifier") + ) + for bad_amount in (True, False, -1, 2**53): + with self.assertRaisesRegex(ValueError, "size_bytes"): + classified_data_flow( + self.factory, + classifier, + "secret", + run_id="run-1", + agent_id="agent-1", + direction="read", + source=DataEndpoint("repository"), + destination=DataEndpoint("agent"), + purpose="review", + size_bytes=bad_amount, + ) + with self.assertRaises(PropagationError): + _safe_value("x-agentrust-run-id", "run\x00bad", required=True) + with self.assertRaises(PropagationError): + _header({"X-Agentrust-Run-Id": "run-1", "x-agentrust-run-id": "run-2"}, "x-agentrust-run-id") + + if __name__ == "__main__": unittest.main() From 194c6f0138685c31a6b7874de3c65cb821774cb9 Mon Sep 17 00:00:00 2001 From: Raghuvar Karthik Durga <177662415+drk-ram@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:01:39 -0600 Subject: [PATCH 2/3] test(data_flow,propagation): split boundary regressions and add valid twins Signed-off-by: Raghuvar Karthik Durga <177662415+drk-ram@users.noreply.github.com> --- tests/test_data_flow.py | 101 ++++++++++++++++++++++++++++++++-------- 1 file changed, 81 insertions(+), 20 deletions(-) diff --git a/tests/test_data_flow.py b/tests/test_data_flow.py index 7f9bb56..394ecd9 100644 --- a/tests/test_data_flow.py +++ b/tests/test_data_flow.py @@ -149,29 +149,90 @@ def test_structured_agt_classification_is_a_value_error(self): with self.assertRaisesRegex(ValueError, "unsupported AGT data classification"): agt_data_classification(SimpleNamespace(classification=bad)) - def test_data_flow_and_propagation_reject_bool_sizes_control_chars_and_conflicting_headers(self): - from agentrust_telemetry import PropagationError - from agentrust_telemetry.propagation import _header, _safe_value - + def test_data_flow_validates_endpoints_and_safe_integer_size_and_token_bounds(self): classifier = RecordingClassifier( ClassificationResult("example", "internal", "classifier") ) - for bad_amount in (True, False, -1, 2**53): - with self.assertRaisesRegex(ValueError, "size_bytes"): - classified_data_flow( - self.factory, - classifier, - "secret", - run_id="run-1", - agent_id="agent-1", - direction="read", - source=DataEndpoint("repository"), - destination=DataEndpoint("agent"), - purpose="review", - size_bytes=bad_amount, - ) - with self.assertRaises(PropagationError): - _safe_value("x-agentrust-run-id", "run\x00bad", required=True) + # Valid boundary twins (0 and 2**53 - 1) succeed + for valid_amount in (0, 2**53 - 1): + ev = classified_data_flow( + self.factory, + classifier, + "secret", + run_id="run-1", + agent_id="agent-1", + direction="read", + source=DataEndpoint("repository"), + destination=DataEndpoint("agent"), + purpose="review", + size_bytes=valid_amount, + token_count=valid_amount, + ) + self.assertEqual(ev["size_bytes"], valid_amount) + self.assertEqual(ev["token_count"], valid_amount) + + with self.assertRaisesRegex(TypeError, "source must be a DataEndpoint"): + classified_data_flow( + self.factory, + classifier, + "secret", + run_id="run-1", + agent_id="agent-1", + direction="read", + source={"kind": "repository"}, # type: ignore[arg-type] + destination=DataEndpoint("agent"), + purpose="review", + ) + with self.assertRaisesRegex(TypeError, "destination must be a DataEndpoint"): + classified_data_flow( + self.factory, + classifier, + "secret", + run_id="run-1", + agent_id="agent-1", + direction="read", + source=DataEndpoint("repository"), + destination={"kind": "agent"}, # type: ignore[arg-type] + purpose="review", + ) + + for field_name in ("size_bytes", "token_count"): + for bad_amount in (True, False, -1, 2**53, "10", 1.5): + with self.subTest(field_name=field_name, bad_amount=bad_amount): + with self.assertRaisesRegex(ValueError, field_name): + classified_data_flow( + self.factory, + classifier, + "secret", + run_id="run-1", + agent_id="agent-1", + direction="read", + source=DataEndpoint("repository"), + destination=DataEndpoint("agent"), + purpose="review", + **{field_name: bad_amount}, + ) + + def test_propagation_rejects_control_characters(self): + from agentrust_telemetry import PropagationError + from agentrust_telemetry.propagation import _safe_value + + self.assertEqual(_safe_value("x-agentrust-run-id", "run-123_ok", required=True), "run-123_ok") + for bad_val in ("run\x00bad", "run\x1fbad", "run\x7fbad", "run\tbad"): + with self.subTest(bad_val=bad_val): + with self.assertRaises(PropagationError): + _safe_value("x-agentrust-run-id", bad_val, required=True) + + def test_propagation_rejects_conflicting_duplicate_headers_and_accepts_identical_duplicates(self): + from agentrust_telemetry import PropagationError + from agentrust_telemetry.propagation import _header + + # Identical case-insensitive duplicate headers are accepted + self.assertEqual( + _header({"X-Agentrust-Run-Id": "run-1", "x-agentrust-run-id": "run-1"}, "x-agentrust-run-id"), + "run-1", + ) + # Conflicting case-insensitive duplicate headers are rejected with self.assertRaises(PropagationError): _header({"X-Agentrust-Run-Id": "run-1", "x-agentrust-run-id": "run-2"}, "x-agentrust-run-id") From 6718497f8f896997ea3e3fafc4a5263572564802 Mon Sep 17 00:00:00 2001 From: Raghuvar Karthik Durga <177662415+drk-ram@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:03:08 -0600 Subject: [PATCH 3/3] fix(propagation,data_flow): bring TypeScript propagation in line with Python and check endpoints before classifying (#104) - TypeScript injectContext/extractContext reject ASCII control characters (U+0000-U+001F, U+007F) in the AgenTrust header values, and extractContext rejects case-insensitive duplicates of the run, workflow and agent headers that carry different values. Identical duplicates are still accepted, as in Python. It used to take the first header it found. - classified_data_flow and classifiedDataFlow check that source and destination are DataEndpoints before calling the caller's classifier, so a malformed endpoint no longer runs it. TypeScript had no such check and failed later with a missing asEventValue. - Cover inject_context and extract_context directly in Python, and the control-character, duplicate-header, length and endpoint-ordering cases in both languages, each with a valid twin. Signed-off-by: Raghuvar Karthik Durga <177662415+drk-ram@users.noreply.github.com> --- CHANGELOG.md | 11 +++ docs/architecture.md | 5 +- packages/typescript/src/data-flow.ts | 2 + packages/typescript/src/propagation.ts | 9 ++- packages/typescript/test/data-flow.test.ts | 16 ++++ packages/typescript/test/propagation.test.ts | 52 ++++++++++++- src/agentrust_telemetry/data_flow.py | 6 +- tests/test_data_flow.py | 42 ++++++++++ tests/test_propagation.py | 81 ++++++++++++++++++++ 9 files changed, 217 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7184fb..fc19bc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,17 @@ now validates `build_digest` / `buildDigest` and policy `bundle_digest` (`algorithm` and `value`) against canonical lowercase `sha256` / `sha384` hex digest syntax before signing. (#101) +- Python and TypeScript propagation now reject ASCII control characters + (`U+0000`-`U+001F`, `U+007F`) in the `x-agentrust-run-id`, + `x-agentrust-workflow-id` and `x-agentrust-agent-id` values, and reject + case-insensitive duplicates of those headers that carry different values + (identical duplicates are accepted). TypeScript previously accepted both and + silently used the first header it found. (#104) +- Python `classified_data_flow` validates `size_bytes` and `token_count` as + non-negative safe integers (booleans refused), and `classified_data_flow` and + `classifiedDataFlow` check that `source` and `destination` are `DataEndpoint`s + before they call the caller's classifier, so a malformed endpoint no longer + runs it. (#104) ### Changed diff --git a/docs/architecture.md b/docs/architecture.md index 6b46ce2..34ba557 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -79,7 +79,10 @@ future TRACE mapping, not proof generated by the accumulator. root span, preserving causal correlation without asserting synchronous parentage. - `x-agentrust-run-id`, `x-agentrust-workflow-id`, and `x-agentrust-agent-id` preserve durable run and agent-delegation metadata alongside standard W3C - `traceparent`/`tracestate`. Extracted metadata is untrusted input. + `traceparent`/`tracestate`. Extracted metadata is untrusted input: each value + is a non-empty string of at most 512 characters with no ASCII control + characters, names match case-insensitively, and duplicates that carry + different values are refused. ## Delivery semantics diff --git a/packages/typescript/src/data-flow.ts b/packages/typescript/src/data-flow.ts index 7437ab4..3dffc3f 100644 --- a/packages/typescript/src/data-flow.ts +++ b/packages/typescript/src/data-flow.ts @@ -15,6 +15,8 @@ export class DataEndpoint { export interface DataClassifier {classify(value: unknown): ClassificationResult} export function classifiedDataFlow(factory: EventFactory, classifier: DataClassifier, value: unknown, options: {runId: string; agentId: string; direction: string; source: DataEndpoint; destination: DataEndpoint; purpose: string; policyDecision?: string; contentDigest?: Digest; sizeBytes?: number; tokenCount?: number; mediaType?: string; transformation?: string; envelope?: Omit}): NormalizedEvent { + if (!(options.source instanceof DataEndpoint)) throw new TypeError("source must be a DataEndpoint"); + if (!(options.destination instanceof DataEndpoint)) throw new TypeError("destination must be a DataEndpoint"); const result = classifier.classify(value); if (!(result instanceof ClassificationResult)) throw new TypeError("classifier must return ClassificationResult"); identifier(options.purpose, "purpose"); diff --git a/packages/typescript/src/propagation.ts b/packages/typescript/src/propagation.ts index 27a6e4c..fedf247 100644 --- a/packages/typescript/src/propagation.ts +++ b/packages/typescript/src/propagation.ts @@ -4,6 +4,7 @@ export const RUN_ID_HEADER = "x-agentrust-run-id"; export const WORKFLOW_ID_HEADER = "x-agentrust-workflow-id"; export const UPSTREAM_AGENT_ID_HEADER = "x-agentrust-agent-id"; const MAX = 512; +const CONTROL = /[\x00-\x1f\x7f]/; export class PropagationError extends Error {} export class ExtractedContext { @@ -19,6 +20,10 @@ export function injectContext(carrier: Record, fields: {runId: s export function extractContext(carrier: Record): ExtractedContext { return new ExtractedContext(propagation.extract(context.active(), carrier, {keys: (c) => Object.keys(c), get: (c, key) => header(c, key)}), value(carrier, RUN_ID_HEADER), value(carrier, WORKFLOW_ID_HEADER), value(carrier, UPSTREAM_AGENT_ID_HEADER)); } -function value(carrier: Record, name: string): string | undefined {const found = header(carrier, name); return found === undefined ? undefined : safe(name, found);} +function value(carrier: Record, name: string): string | undefined { + const found = Object.keys(carrier).filter((key) => key.toLowerCase() === name.toLowerCase() && carrier[key] !== undefined).map((key) => safe(name, carrier[key])); + if (new Set(found).size > 1) throw new PropagationError(`conflicting duplicate ${name} header values`); + return found[0]; +} function header(carrier: Record, name: string): string | string[] | undefined {const key = Object.keys(carrier).find((candidate) => candidate.toLowerCase() === name.toLowerCase()); return key ? carrier[key] : undefined;} -function safe(name: string, value: unknown): string {if (typeof value !== "string" || !value) throw new PropagationError(`${name} must be a non-empty string`); if (value.length > MAX) throw new PropagationError(`${name} exceeds ${MAX} characters`); if (/\r|\n/.test(value)) throw new PropagationError(`${name} contains a prohibited line break`); return value;} +function safe(name: string, value: unknown): string {if (typeof value !== "string" || !value) throw new PropagationError(`${name} must be a non-empty string`); if (value.length > MAX) throw new PropagationError(`${name} exceeds ${MAX} characters`); if (/\r|\n/.test(value)) throw new PropagationError(`${name} contains a prohibited line break`); if (CONTROL.test(value)) throw new PropagationError(`${name} contains a prohibited control character`); return value;} diff --git a/packages/typescript/test/data-flow.test.ts b/packages/typescript/test/data-flow.test.ts index 6d10e30..c17757f 100644 --- a/packages/typescript/test/data-flow.test.ts +++ b/packages/typescript/test/data-flow.test.ts @@ -14,6 +14,22 @@ test("classification boundary rejects arbitrary results and prose identifiers", assert.throws(() => new ClassificationResult("example", "customer secret", "classifier"), /metadata identifier/); assert.throws(() => classifiedDataFlow(factory, {classify: () => new ClassificationResult("example", "internal", "classifier")}, null, {runId: "r", agentId: "a", direction: "read", source: new DataEndpoint("repository"), destination: new DataEndpoint("agent"), purpose: "review", sizeBytes: Number.MAX_SAFE_INTEGER + 1}), /safe integer/); }); +test("invalid source or destination is refused before the classifier runs", () => { + const lookalike = {kind: "repository", id: undefined, asEventValue: () => ({kind: "repository"})}; + for (const field of ["source", "destination"] as const) { + for (const bad of [{kind: "repository"}, lookalike, null, undefined, "repository"]) { + let calls = 0; + const classifier = {classify: () => { calls += 1; return new ClassificationResult("example", "internal", "classifier"); }}; + const endpoints = {source: new DataEndpoint("repository"), destination: new DataEndpoint("agent"), [field]: bad}; + assert.throws(() => classifiedDataFlow(factory, classifier, "secret", {runId: "r", agentId: "a", direction: "read", purpose: "review", ...endpoints} as Parameters[3]), (error) => error instanceof TypeError && error.message === `${field} must be a DataEndpoint`, `${field} ${String(bad)}`); + assert.equal(calls, 0); + } + } + // Valid twin: the same call with real endpoints reaches the classifier. + let calls = 0; + classifiedDataFlow(factory, {classify: () => { calls += 1; return new ClassificationResult("example", "internal", "classifier"); }}, "secret", {runId: "r", agentId: "a", direction: "read", source: new DataEndpoint("repository"), destination: new DataEndpoint("agent"), purpose: "review"}); + assert.equal(calls, 1); +}); test("AGT access maps only tier, decision, agent, and time", () => { const decision = {allowed: false, reason: "SSN 123-45-6789 denied", agent_id: "agent-1", data_label: {classification: 2, categories: ["PII", "customer@example.test"], owner: "alice@example.test", geography: "EU"}, matched_policy: "secret", evaluated_at: "2026-08-18T12:00:00Z"}; const event = agtDataAccessFlow(factory, decision, {runId: "run-1", direction: "read", source: new DataEndpoint("database", "customer-records"), destination: new DataEndpoint("agent", "builder"), purpose: "requirements-analysis"}); diff --git a/packages/typescript/test/propagation.test.ts b/packages/typescript/test/propagation.test.ts index a90daef..e1a5937 100644 --- a/packages/typescript/test/propagation.test.ts +++ b/packages/typescript/test/propagation.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import {context, propagation, trace, TraceFlags} from "@opentelemetry/api"; import {W3CTraceContextPropagator} from "@opentelemetry/core"; -import {extractContext, injectContext, PropagationError} from "../src/index.js"; +import {extractContext, injectContext, PropagationError, RUN_ID_HEADER, UPSTREAM_AGENT_ID_HEADER, WORKFLOW_ID_HEADER} from "../src/index.js"; propagation.setGlobalPropagator(new W3CTraceContextPropagator()); const spanContext = {traceId: "4bf92f3577b34da6a3ce929d0e0e4736", spanId: "00f067aa0ba902b7", traceFlags: TraceFlags.SAMPLED, isRemote: false}; @@ -51,3 +51,53 @@ test("extractContext rejects array-valued and non-string AgenTrust carrier heade parent_agent_id: "", }); }); + +const AGENTRUST_HEADERS = [ + [RUN_ID_HEADER, "runId"], + [WORKFLOW_ID_HEADER, "workflowId"], + [UPSTREAM_AGENT_ID_HEADER, "upstreamAgentId"], +] as const; + +test("injectContext and extractContext reject ASCII control characters in every AgenTrust value", () => { + for (const bad of ["a\x00b", "a\x1fb", "a\x7fb", "a\tb", "a\x0bb"]) { + for (const [field, value] of [["run_id", {runId: bad, agentId: "agent-a"}], ["agent_id", {runId: "run-1", agentId: bad}], ["workflow_id", {runId: "run-1", agentId: "agent-a", workflowId: bad}]] as const) { + assert.throws(() => injectContext({}, value), (error) => error instanceof PropagationError && error.message === `${field} contains a prohibited control character`, `${field} ${JSON.stringify(bad)}`); + } + for (const [header] of AGENTRUST_HEADERS) { + assert.throws(() => extractContext({[header]: bad}), (error) => error instanceof PropagationError && /prohibited control character/.test(error.message), `${header} ${JSON.stringify(bad)}`); + } + } + // Valid twins either side of the rejected range: space and tilde. + const carrier: Record = {}; + injectContext(carrier, {runId: "run 1", agentId: "agent~a", workflowId: "~"}); + assert.deepEqual([carrier[RUN_ID_HEADER], carrier[UPSTREAM_AGENT_ID_HEADER], carrier[WORKFLOW_ID_HEADER]], ["run 1", "agent~a", "~"]); + for (const [header, field] of AGENTRUST_HEADERS) assert.equal(extractContext({[header]: "a b~"})[field], "a b~"); +}); + +test("extractContext rejects conflicting case-insensitive duplicates and accepts identical ones", () => { + for (const [header] of AGENTRUST_HEADERS) { + assert.throws(() => extractContext({[header.toUpperCase()]: "first", [header]: "second"}), (error) => error instanceof PropagationError && error.message === `conflicting duplicate ${header} header values`); + assert.throws(() => extractContext({[header]: "first", [header.toUpperCase()]: "second", "X-Other": "x"}), /conflicting duplicate/); + // Every duplicate is validated, so a bad value cannot hide behind an identical twin. + assert.throws(() => extractContext({[header.toUpperCase()]: "bad\x00", [header]: "bad\x00"}), /prohibited control character/); + } + const extracted = extractContext({"X-AgenTrust-Run-Id": "run-1", "x-agentrust-run-id": "run-1", "X-AGENTRUST-WORKFLOW-ID": "workflow-1", "x-agentrust-workflow-id": "workflow-1", "X-Agentrust-Agent-Id": "agent-a", "x-agentrust-agent-id": "agent-a"}); + assert.deepEqual([extracted.runId, extracted.workflowId, extracted.upstreamAgentId], ["run-1", "workflow-1", "agent-a"]); +}); + +test("AgenTrust values are limited to 512 characters", () => { + const carrier: Record = {}; + injectContext(carrier, {runId: "r".repeat(512), agentId: "a"}); + assert.equal(carrier[RUN_ID_HEADER]!.length, 512); + assert.throws(() => injectContext({}, {runId: "r".repeat(513), agentId: "a"}), /run_id exceeds 512 characters/); + for (const [header, field] of AGENTRUST_HEADERS) { + assert.equal(extractContext({[header]: "v".repeat(512)})[field]!.length, 512); + assert.throws(() => extractContext({[header]: "v".repeat(513)}), /exceeds 512 characters/); + } +}); + +test("extractContext treats an AgenTrust header set to undefined as absent", () => { + const extracted = extractContext({[RUN_ID_HEADER]: undefined as unknown as string, "X-AgenTrust-Run-Id": "run-1"}); + assert.equal(extracted.runId, "run-1"); + assert.equal(extractContext({[RUN_ID_HEADER]: undefined as unknown as string}).runId, undefined); +}); diff --git a/src/agentrust_telemetry/data_flow.py b/src/agentrust_telemetry/data_flow.py index dda4f17..34d45e3 100644 --- a/src/agentrust_telemetry/data_flow.py +++ b/src/agentrust_telemetry/data_flow.py @@ -65,13 +65,13 @@ def classified_data_flow( **envelope: Any, ) -> dict[str, Any]: """Classify ``value`` and emit only the classifier's closed metadata result.""" - result = classifier.classify(value) - if not isinstance(result, ClassificationResult): - raise TypeError("classifier must return ClassificationResult") if not isinstance(source, DataEndpoint): raise TypeError("source must be a DataEndpoint") if not isinstance(destination, DataEndpoint): raise TypeError("destination must be a DataEndpoint") + result = classifier.classify(value) + if not isinstance(result, ClassificationResult): + raise TypeError("classifier must return ClassificationResult") _identifier(purpose, "purpose") if media_type is not None and ( not isinstance(media_type, str) or _MEDIA_TYPE.fullmatch(media_type) is None diff --git a/tests/test_data_flow.py b/tests/test_data_flow.py index 394ecd9..3be6011 100644 --- a/tests/test_data_flow.py +++ b/tests/test_data_flow.py @@ -213,6 +213,48 @@ def test_data_flow_validates_endpoints_and_safe_integer_size_and_token_bounds(se **{field_name: bad_amount}, ) + def test_invalid_endpoint_is_refused_before_the_classifier_runs(self): + class LookalikeEndpoint: + kind = "repository" + id = None + + def as_event_value(self): + return {"kind": self.kind} + + classifier = RecordingClassifier( + ClassificationResult("example", "internal", "classifier") + ) + valid = DataEndpoint("repository") + for field, other in (("source", "destination"), ("destination", "source")): + for bad in ({"kind": "repository"}, None, "repository", LookalikeEndpoint()): + with self.subTest(field=field, bad=bad): + with self.assertRaisesRegex(TypeError, f"{field} must be a DataEndpoint"): + classified_data_flow( + self.factory, + classifier, + "secret", + run_id="run-1", + agent_id="agent-1", + direction="read", + purpose="review", + **{field: bad, other: valid}, # type: ignore[arg-type] + ) + self.assertIsNone(classifier.seen) + + # Valid twin: the same call with real endpoints reaches the classifier. + classified_data_flow( + self.factory, + classifier, + "secret", + run_id="run-1", + agent_id="agent-1", + direction="read", + source=valid, + destination=DataEndpoint("agent"), + purpose="review", + ) + self.assertEqual(classifier.seen, "secret") + def test_propagation_rejects_control_characters(self): from agentrust_telemetry import PropagationError from agentrust_telemetry.propagation import _safe_value diff --git a/tests/test_propagation.py b/tests/test_propagation.py index b184732..8c82b37 100644 --- a/tests/test_propagation.py +++ b/tests/test_propagation.py @@ -81,6 +81,87 @@ def test_link_requires_valid_w3c_context(self): with self.assertRaisesRegex(PropagationError, "no valid remote span"): extract_context({"x-agentrust-run-id": "run-1"}).link() + def test_inject_rejects_control_characters_in_every_agentrust_value(self): + fields = {"run_id": "run-1", "agent_id": "agent-a", "workflow_id": "workflow-1"} + for field in fields: + for bad in ("a\x00b", "a\x1fb", "a\x7fb", "a\tb", "a\x0bb"): + with self.subTest(field=field, bad=bad), self.assertRaisesRegex( + PropagationError, f"{field} contains a prohibited" + ): + inject_context({}, **{**fields, field: bad}) + + # Valid twins sit on both sides of the rejected range: space and tilde. + carrier = {} + inject_context(carrier, run_id="run 1", agent_id="agent~a", workflow_id="~") + self.assertEqual(carrier["x-agentrust-run-id"], "run 1") + self.assertEqual(carrier["x-agentrust-agent-id"], "agent~a") + self.assertEqual(carrier["x-agentrust-workflow-id"], "~") + + def test_extract_rejects_control_characters_in_every_agentrust_header(self): + attributes = { + "x-agentrust-run-id": "run_id", + "x-agentrust-workflow-id": "workflow_id", + "x-agentrust-agent-id": "upstream_agent_id", + } + for header, attribute in attributes.items(): + for bad in ("a\x00b", "a\x1fb", "a\x7fb", "a\tb"): + with self.subTest(header=header, bad=bad), self.assertRaisesRegex( + PropagationError, "prohibited control character" + ): + extract_context({header: bad}) + with self.subTest(header=header, valid="space and tilde"): + self.assertEqual(getattr(extract_context({header: "a b~"}), attribute), "a b~") + + def test_extract_rejects_conflicting_case_insensitive_duplicate_headers(self): + for header in ("x-agentrust-run-id", "x-agentrust-workflow-id", "x-agentrust-agent-id"): + with self.subTest(header=header), self.assertRaisesRegex( + PropagationError, "conflicting duplicate" + ): + extract_context({header.upper(): "first", header: "second"}) + + def test_extract_rejects_empty_and_non_string_values_and_ignores_non_string_keys(self): + for header in ("x-agentrust-run-id", "x-agentrust-workflow-id", "x-agentrust-agent-id"): + with self.subTest(header=header): + with self.assertRaisesRegex(PropagationError, "must not be empty"): + extract_context({header: ""}) + for bad in (7, None, ["a", "b"]): + with self.assertRaisesRegex(PropagationError, "must be a string"): + extract_context({header: bad}) + extracted = extract_context({1: "ignored", "X-AgenTrust-Run-Id": "run-1"}) + self.assertEqual(extracted.run_id, "run-1") + + def test_agentrust_values_are_limited_to_512_characters(self): + carrier = {} + inject_context(carrier, run_id="r" * 512, agent_id="a") + self.assertEqual(len(carrier["x-agentrust-run-id"]), 512) + with self.assertRaisesRegex(PropagationError, "run_id exceeds 512 characters"): + inject_context({}, run_id="r" * 513, agent_id="a") + for header in ("x-agentrust-run-id", "x-agentrust-workflow-id", "x-agentrust-agent-id"): + with self.subTest(header=header): + extract_context({header: "v" * 512}) + with self.assertRaisesRegex(PropagationError, "exceeds 512 characters"): + extract_context({header: "v" * 513}) + + def test_extract_accepts_identical_case_insensitive_duplicate_headers(self): + extracted = extract_context( + { + "X-AgenTrust-Run-Id": "run-1", + "x-agentrust-run-id": "run-1", + "X-AGENTRUST-WORKFLOW-ID": "workflow-1", + "x-agentrust-workflow-id": "workflow-1", + "X-Agentrust-Agent-Id": "agent-a", + "x-agentrust-agent-id": "agent-a", + } + ) + self.assertEqual( + (extracted.run_id, extracted.workflow_id, extracted.upstream_agent_id), + ("run-1", "workflow-1", "agent-a"), + ) + + def test_extract_validates_every_duplicate_before_comparing_them(self): + with self.assertRaisesRegex(PropagationError, "prohibited control character"): + extract_context({"X-AgenTrust-Run-Id": "run-1\x00", "x-agentrust-run-id": "run-1\x00"}) + if __name__ == "__main__": unittest.main()