Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 4 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions packages/typescript/src/data-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<EnvelopeFields, "runId" | "agentId">}): 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");
Expand Down
9 changes: 7 additions & 2 deletions packages/typescript/src/propagation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -19,6 +20,10 @@ export function injectContext(carrier: Record<string, string>, fields: {runId: s
export function extractContext(carrier: Record<string, string>): 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<string, string>, name: string): string | undefined {const found = header(carrier, name); return found === undefined ? undefined : safe(name, found);}
function value(carrier: Record<string, string>, 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<string, string>, 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;}
16 changes: 16 additions & 0 deletions packages/typescript/test/data-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof classifiedDataFlow>[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"});
Expand Down
52 changes: 51 additions & 1 deletion packages/typescript/test/propagation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<string, string> = {};
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<string, string> = {};
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);
});
12 changes: 12 additions & 0 deletions src/agentrust_telemetry/data_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -64,6 +65,10 @@ def classified_data_flow(
**envelope: Any,
) -> dict[str, Any]:
"""Classify ``value`` and emit only the classifier's closed metadata result."""
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")
Expand All @@ -73,6 +78,13 @@ def classified_data_flow(
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,
Expand Down
14 changes: 9 additions & 5 deletions src/agentrust_telemetry/propagation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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


Expand Down
Loading