Skip to content

fix(agt): implement ACS-Core wire safeguards - #229

Merged
rocklambros merged 16 commits into
GenAI-Security-Project:integrationfrom
jrcrittenden:fix/acs-core-conformance-d1-d10
Dec 3, 2026
Merged

rocklambros merged 16 commits into
GenAI-Security-Project:integrationfrom
jrcrittenden:fix/acs-core-conformance-d1-d10

Conversation

@jrcrittenden

@jrcrittenden jrcrittenden commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

What changed

Implements the concrete D1-D10 wire probes from #184 across the AGT reference Guardian and the shipped Claude Code and OpenCode adapters. This adds authenticated request and response envelopes, replay and timestamp checks, published chain heads, system/ping, handshake negotiation fields, the six-hook minimum, wrapped tools/call, explicit tool_unregistered decisions, adversarial coverage, and reproducible test instructions.

This is intentionally a partial response. Follow-up work remains for replay persistence across Guardian restarts and chain continuity when the bounded session-context store evicts a session (#233).

Envelope log changes

This PR changes packages/guardian/src/server.ts around the envelope-log calls in handleAcsRequest. The envelopeLog.write(...) calls are unchanged, but what they record changes:

  • Response signing (lines 668-689) runs between dispatch and the final envelopeLog.write("response", ...). When hmacSecret is set and the request is validly signed, the logged response carries its signature object.
  • Refusals for a missing handshake (-32003), a replay (-32005), and timestamp skew (-32006) are logged as error responses paired with their requests.
  • Hosts now send handshake/hello before any step, so the log includes hello lines. A host that gets -32003 re-handshakes once and resends, which adds a second hello and a second copy of the step.

Which issue does this implement

Part of #184

Closes #141
Closes #142
Closes #165
Closes #199

  • This is an editorial correction (typo, grammar, link, formatting) with no change in
    meaning, so it needs no issue

Base branch

  • integration, because this touches the specification, schemas, a reference
    implementation, an adapter, tests, or CI
  • main, because every changed path is on the documentation lane allowlist in
    CONTRIBUTING.md

Type of change

  • Specification change (schema, hooks, events, AgBOM)
  • Reference implementation or adapter
  • Documentation
  • Tooling or CI
  • Governance (licensing, security policy, contributor docs)

I tested this

  • I synced my branch with the base branch before opening this
  • uv run pytest -v passes on my machine
  • uv run mkdocs build --strict passes on my machine

Additional AGT checks:

  • bun run typecheck passes.
  • The focused changed-area suite passes 128 tests.
  • The full Bun suite reports 1,124 passes and 1 skip. Its 26 cleanup-related failures are all caused by the documented trash executable not being installed in this environment (bun: command not found: trash).

Checklist

  • Commits are signed off with git commit -s (required by the DCO)
  • Prose follows STYLE.md
  • No secrets, tokens, or internal URLs in the diff

Security

  • This change has no security impact

This change rejects unsigned, incorrectly signed, stale, and replayed envelopes; authenticates non-ping results and errors; and adds adversarial coverage for response substitution and replay-cache saturation. It responds to the already-public conformance report in #184 and does not disclose a separate unreported vulnerability.

@afogel afogel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great first pass! a few requests to improve code quality/reduce footguns, and a few items that might impact correctness down the line

Comment on lines +893 to +895
const requestTimestampMs = Date.parse(envelope.params.timestamp);
const drift = Math.abs(nowMs - requestTimestampMs);
if (drift > SKEW_WINDOW_MS) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix: a leap-second timestamp gets past the skew window (§10.3).

The schema's date-time format accepts 23:59:60, but Date.parse returns NaN for it, and NaN > SKEW_WINDOW_MS is false. I reproduced it against a live Guardian with a signed request:

"2020-01-01T00:00:00Z" → -32006
"2020-12-31T23:59:60Z" → allow

Only a key holder can produce such a request, since the timestamp is signed. But the NaN expiry is also never pruned from the replay store, so each one stays there for good.

Suggested change
const requestTimestampMs = Date.parse(envelope.params.timestamp);
const drift = Math.abs(nowMs - requestTimestampMs);
if (drift > SKEW_WINDOW_MS) {
const requestTimestampMs = Date.parse(envelope.params.timestamp);
const drift = Math.abs(nowMs - requestTimestampMs);
if (!Number.isFinite(drift) || drift > SKEW_WINDOW_MS) {

Why this helps: §10.3's MUST holds for every timestamp the schema accepts, and the replay store can't hold entries that never expire.

@jrcrittenden jrcrittenden Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in beee5b5. Non-finite drift is now rejected with -32006, so a NaN expiry never reaches the replay store. The skew test covers 2020-12-31T23:59:60Z.

Reply drafted with Claude Code.

Comment thread reference-implementations/agt/README.md Outdated
Comment on lines +72 to +74
| Handshake, `handshake/hello` | Served. The Guardian validates ClientHello, rejects unsupported versions (`-32001`), narrows `methods_evaluated` to the intersection with the client's `methods_implemented`, and negotiates `profiles_accepted`. |
| Request and response envelopes, JSON-RPC 2.0 | Implemented. Inbound envelopes are validated against the schemas. Outbound responses are checked and the check is logged, never thrown. |
| Hook taxonomy, minimum of six hooks | Two of nineteen `steps/*` methods are evaluated: `steps/toolCallRequest` and `steps/toolCallResult`. The other four minimum hooks are not evaluated. |
| Five dispositions | `allow`, `deny` and `modify` are complete. `ask` is sent without `ask_details`, so it fails the response schema. `defer` is never produced. |
| SessionContext with published `chain_hash` | The Guardian keeps a hash chain per session and writes it to a log. It does not put `chain_hash` on any response. |
| Replay protection | Not implemented. No timestamp window check. No duplicate `request_id` check. |
| Baseline HMAC-SHA256 signature | Not implemented. Nothing signs or verifies an envelope. |
| Hook taxonomy, minimum of six hooks | All six ACS-Core hooks are dispatched: `steps/toolCallRequest` and `steps/toolCallResult` are policy-evaluated; `steps/sessionStart`, `steps/sessionEnd`, `steps/userMessage` and `steps/agentResponse` are accepted with allow-by-default and recorded in the session chain. |

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix: these two rows state more than the spec supports.

  • Hook minimum. conformance.md lists subagentStart for clients that can start subagents (Claude Code and OpenCode both can), and agentTrigger as an alternative to userMessage. Both return -32011 here. I tested subagentStart.
  • Handshake. Negotiation is correct, but nothing enforces it. A step sent with no handshake gets allow, and so does a method the handshake didn't negotiate, where §17.1 calls for -32003 CAPABILITY_NOT_NEGOTIATED. The PR body lists this as follow-up work. The README should say so too.
Suggested change
| Handshake, `handshake/hello` | Served. The Guardian validates ClientHello, rejects unsupported versions (`-32001`), narrows `methods_evaluated` to the intersection with the client's `methods_implemented`, and negotiates `profiles_accepted`. |
| Request and response envelopes, JSON-RPC 2.0 | Implemented. Inbound envelopes are validated against the schemas. Outbound responses are checked and the check is logged, never thrown. |
| Hook taxonomy, minimum of six hooks | Two of nineteen `steps/*` methods are evaluated: `steps/toolCallRequest` and `steps/toolCallResult`. The other four minimum hooks are not evaluated. |
| Five dispositions | `allow`, `deny` and `modify` are complete. `ask` is sent without `ask_details`, so it fails the response schema. `defer` is never produced. |
| SessionContext with published `chain_hash` | The Guardian keeps a hash chain per session and writes it to a log. It does not put `chain_hash` on any response. |
| Replay protection | Not implemented. No timestamp window check. No duplicate `request_id` check. |
| Baseline HMAC-SHA256 signature | Not implemented. Nothing signs or verifies an envelope. |
| Hook taxonomy, minimum of six hooks | All six ACS-Core hooks are dispatched: `steps/toolCallRequest` and `steps/toolCallResult` are policy-evaluated; `steps/sessionStart`, `steps/sessionEnd`, `steps/userMessage` and `steps/agentResponse` are accepted with allow-by-default and recorded in the session chain. |
| Handshake, `handshake/hello` | Served, not yet enforced. The Guardian validates ClientHello, rejects unsupported versions (`-32001`), narrows `methods_evaluated` to the intersection with the client's `methods_implemented`, and negotiates `profiles_accepted`. Open Core gap: later steps are not checked against the negotiated session, so a step with no prior handshake, or a method the handshake did not negotiate, is evaluated rather than refused with `-32003`. |
| Request and response envelopes, JSON-RPC 2.0 | Implemented. Inbound envelopes are validated against the schemas. Outbound responses are checked and the check is logged, never thrown. |
| Hook taxonomy, minimum hook set | Partial. `steps/toolCallRequest` and `steps/toolCallResult` are policy-evaluated; `steps/sessionStart`, `steps/sessionEnd`, `steps/userMessage` and `steps/agentResponse` are accepted with allow-by-default and recorded in the session chain. Open Core gap: `steps/subagentStart` (required for subagent-capable clients) and `steps/agentTrigger` (the alternative to `userMessage`) return `-32011`. |

Why this helps: the acs-core claim is already described as qualified. This makes the qualification match the spec.

@jrcrittenden jrcrittenden Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied your wording in beee5b5. The handshake row says "served, not yet enforced" (no -32003), and the hook-set row says "Partial" (subagentStart and agentTrigger return -32011).

Reply drafted with Claude Code.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: dd7e3b4 enforces the handshake, so the row now reads "Implemented". Hook traffic without a hello, or for a method the hello did not declare, is refused with -32003.

Reply drafted with Claude Code.

input.tool_name,
]);
return createHash("sha256").update(canonical).digest("hex");
const content = {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: add request_hash so the chain commits to what each step contained (context-entry.json, RECOMMENDED).

This projection now matches §8.2 exactly. Nice: the old array-based hash didn't, and the issue never flagged it. But it drops tool_name, which the old hash included, and doesn't add request_hash. So the chain records which step ran, not what it asked for. A rewritten argument or tool name leaves every published chain_hash unchanged.

context-entry.json defines the field as the lowercase hex SHA-256 of the JCS-canonicalized request params:

type SessionStep = {
  readonly method: string;
  readonly request_id: string;
  readonly tool_name: string;
  readonly request_hash: string;   // sha256(JCS(params)), computed once at the call site
};

const content = {
  entry_id: `${input.session_id}:${input.seq}`,
  step_id: input.request_id,
  step_type: input.method,
  timestamp: input.recorded_at,
  request_hash: input.request_hash,
};

Each appendContextEntry call site already holds envelope.params, so this is one extra field on the way in.

Why this helps: the published head becomes evidence of content, not just order. That's what §8.6's tamper-evidence argument is about.

@jrcrittenden jrcrittenden Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in beee5b5. request_hash = sha256(JCS(params)) is in the committed content at all three append sites. The Inspector's log type and line check now include it, and a test confirms that changing request_hash changes the entry hash.

Reply drafted with Claude Code.


const guardianUrl = process.env.ACS_GUARDIAN_URL ?? DEFAULT_GUARDIAN_URL;
const guardian = createGuardianClient(guardianUrl);
const hmacSecret = process.env.ACS_HMAC_SECRET

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: read ACS_HMAC_SECRET once, through one validator.

The three places that read it disagree:

Where Empty string Not valid base64 Under 32 bytes
guardian/src/main.ts:47 error decoded to garbage error
hosts/claude-code/acs-hook.ts:536 (here) silently unsigned decoded to garbage accepted
hosts/opencode/acs-plugin.ts:1400 silently unsigned decoded to garbage accepted

Buffer.from(s, "base64") never throws, so a typo produces a wrong key and an unexplained SIGNATURE_INVALID.

Let's read the environment once at each entry point into a typed config, and pass that down. buildServerHello(env?) already follows this pattern.

export type Env = Readonly<Record<string, string | undefined>>;

export class ConfigError extends Error {}

const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
const MIN_HMAC_KEY_BYTES = 32;

export function decodeHmacSecret(raw: string | undefined): Buffer | undefined {
  if (raw === undefined || raw === "") return undefined;
  if (raw.length % 4 !== 0 || !BASE64.test(raw)) throw new ConfigError("ACS_HMAC_SECRET is not valid base64");
  const key = Buffer.from(raw, "base64");
  if (key.length < MIN_HMAC_KEY_BYTES) throw new ConfigError(`ACS_HMAC_SECRET must decode to at least ${MIN_HMAC_KEY_BYTES} bytes`);
  return key;
}

export type HostConfig = {
  readonly guardianUrl: URL;
  readonly hmacSecret: Buffer | undefined;
  readonly auditLogPath: string;
};

export function readHostConfig(env: Env = process.env): HostConfig { /* … */ }

The host can't import from the Guardian package (invariants.test.ts). A small shared wire package holding decodeHmacSecret, JCS and HKDF would satisfy that rule and remove the duplicated JCS and HKDF code too. Two related points: a deployment that requires signing should fail loudly when the host has no key, rather than run unsigned. And the Python adapters in #22 also accept ACS_HMAC_SECRET_FILE, which keeps the secret out of child processes' environments, so offering it here keeps the two consistent.

Why this helps:

  • Correctness: one validation rule everywhere.
  • Maintenance: tests pass a plain object instead of changing process.env.
  • Readability: every setting the host reads is visible in one place.

@jrcrittenden jrcrittenden Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on all of this. We're deferring the acs-wire package, the authenticator object, reading the environment through one validator, and single-sourced constants to a follow-up PR, tracked in #230, so this one stays reviewable.

Reply drafted with Claude Code.

export function buildServerHello(env?: { ACS_ON_DECISION_FAILURE?: string }): ServerHello {
/** §10.3: the window this Guardian enforces, declared in the ServerHello so
* the client knows the bound. Matches SKEW_WINDOW_MS in server.ts. */
const SKEW_WINDOW_MS = 300_000;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: give each constant one source, split by who owns it.

This is the same problem as the environment variables: one value defined in several places, kept in sync only by comments.

Value Defined in
Skew window 300_000 Here, and server.ts:125. Only the comment "Matches SKEW_WINDOW_MS in server.ts" keeps them equal, and the ServerHello must declare the exact window the gate enforces.
ACS version "0.1.0" NEGOTIATED_VERSION here, but the version check uses the literal (server.ts:940, :942). Also in deny-on-invalid-envelope.ts, build-envelope.ts and the host's handshake.ts.
Timeout 5000 Here and in host-adapter/src/failure-posture.ts:73
Error codes Some are named (SIGNATURE_INVALID_CODE), but -32006, -32005, -32001 and -32003 are inline literals in server.ts. The host repeats the set in REFUSAL_RPC_CODES.
"HMAC-SHA256" 7 literals across 4 files
Minimum key length 32 main.ts:54 and server.ts:484
Signature type { algorithm; value; key_id } Declared inline 5 times (acs-result.ts, validate-envelope.ts, server.ts, guardian-client.ts, sign-envelope.ts)

There are two kinds of value here, and they belong in two places:

  • Fixed by the spec (version, §17.1 codes, algorithm names, HKDF output length, the signature type): one protocol.ts in a shared wire package that both sides import. The host's REFUSAL_RPC_CODES then becomes a set built from named codes, not a copied list.
    export const ACS_VERSION = "0.1.0";
    export const SIGNATURE_ALGORITHM = "HMAC-SHA256";
    export const AcsError = {
      SessionRefused: -32000, UnsupportedVersion: -32001, ProvenanceRequired: -32002,
      CapabilityNotNegotiated: -32003, SignatureInvalid: -32004, ReplayDetected: -32005,
      TimestampOutOfWindow: -32006, ChainMismatch: -32007,
    } as const;
    export type AcsSignature = { readonly algorithm: typeof SIGNATURE_ALGORITHM; readonly value: string; readonly key_id: string };
  • Chosen by the deployment (skew window, timeouts, replay-store limits, minimum key length): fields of the Guardian's config, read once alongside the environment variables (see my comment on acs-hook.ts:536). buildServerHello and the timestamp gate then both read config.skewWindowMs, so they can't drift apart.

Why this helps:

  • Correctness: the ServerHello always declares what the gates enforce.
  • Maintenance: a spec change to a code or the version is a one-line edit.
  • Readability: AcsError.TimestampOutOfWindow says what -32006 means.

@jrcrittenden jrcrittenden Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on all of this. We're deferring the acs-wire package, the authenticator object, reading the environment through one validator, and single-sourced constants to a follow-up PR, tracked in #230, so this one stays reviewable.

Reply drafted with Claude Code.

if (
hmacSecret &&
extractMethod(raw) !== "system/ping" &&
requestHasValidSignature(raw, Buffer.from(hmacSecret, "base64"))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: put HMAC behind one authenticator object, the same way this codebase already handles sinks and stores.

Why an object fits what this PR adds

  • §10 makes HMAC-SHA256 the baseline of a registry of algorithms. ACS-Crypto adds ECDSA, RSA-PSS and ML-DSA, and keys can come from a TLS exporter instead of a shared secret. Signing is the part of this code the spec already expects to vary, so it belongs behind an interface from the start. The next algorithm then means adding a factory, not editing dispatch.
  • §10 also requires both sides to compute the same canonical input. That argues for one implementation, not one copy per package.
  • It matches the house style: create*() factories that return a role (createGuardianClient, createAuditSink, createReplayProtectionStore), and null objects for disabled features. NULL_ENVELOPE_LOG_SINK says it directly: "a composition root disabling observability gets a value of the same EnvelopeLogSink type, not a special case." HMAC is currently the one special case.

What's duplicated or unnecessary today

What Where
JCS, implemented twice verify-signature.ts:9, host-adapter/src/sign-envelope.ts:11
HKDF key derivation, implemented twice verify-signature.ts:22, sign-envelope.ts:21
Request verification, run twice per request server.ts:864–886, and again in requestHasValidSignature (:1270)
Choosing the response's result vs error to sign, implemented twice verify-signature.ts:41, sign-envelope.ts:76
Decoding the base64 secret, five times main.ts:53, server.ts:484, :658, :662, :880
The 32-byte key-length check, twice main.ts:54, server.ts:484
if (hmacSecret) branches, threaded through startGuardian → handleAcsRequest → dispatch server.ts, 16 mentions
extractSessionId :1252. Only exists so the signing step can rediscover a session id that verification had already found.

Proposed: a small packages/acs-wire workspace package with no dependencies beyond node:crypto, imported by both guardian and host-adapter. The rule that the host never imports the Guardian still holds.

packages/acs-wire/src/
  protocol.ts       ACS_VERSION, AcsError codes, AcsSignature, AcsSignatureAlgorithm
  jcs.ts            canonicalize(): RFC 8785, throws on undefined and non-finite numbers
  authenticator.ts  createHmacAuthenticator(), NULL_AUTHENTICATOR, the two role types
export type Verification =
  | { readonly ok: true; readonly sessionId: string }
  | { readonly ok: false; readonly reason: string };

/** The Guardian's role. */
export interface RequestVerifier {
  readonly algorithms: readonly AcsSignatureAlgorithm[];   // ServerHello signature_algorithms_supported
  verifyRequest(request: JsonObject): Verification;
  signResponse<R extends JsonObject>(response: R, sessionId: string): R;   // returns a signed copy
}

/** The host's role. */
export interface RequestSigner {
  readonly algorithms: readonly AcsSignatureAlgorithm[];   // empty means: claim no acs-core
  signRequest<T extends SignableRequest>(request: T): T & SignedRequest;
  verifyResponse(response: JsonObject, sessionId: string): Verification;
}

/** The secret goes in here and nowhere else. Strict base64, minimum length, per-session HKDF. */
export declare function createHmacAuthenticator(ikm: Buffer): RequestVerifier & RequestSigner;
/** Signing disabled: same type, not a special case. Compatibility tests only. */
export declare const NULL_AUTHENTICATOR: RequestVerifier & RequestSigner;

In the Guardian:

// main.ts: the only place that knows about the environment variable
await startGuardian({ ...options, authenticator: createHmacAuthenticator(config.hmacSecret) });

// dispatch: verify once, and return the result with the response (null for ping, per §13)
const auth = authenticator.verifyRequest(raw);
if (!auth.ok) return { response: errorResponse(rpcId, AcsError.SignatureInvalid, "SIGNATURE_INVALID", { reason: auth.reason }), auth };

// handleAcsRequest: only authenticated requests get signed responses, as now
const { response, auth } = await dispatch(/* … */);
const outgoing = auth?.ok ? authenticator.signResponse(response, auth.sessionId) : response;

That removes the inline checks at :864–886, requestHasValidSignature, extractSessionId, all five decodes, and every if (hmacSecret). buildServerHello reads authenticator.algorithms. The host side is in my comment on govern-step.ts:665.

Why this helps:

  • Encapsulation: one closure holds the secret, and each side depends on a role, not on raw key bytes.
  • Maintenance: adding an algorithm, or fixing canonicalization, is a change in one place.
  • Review: "what is authenticated, and how" has one implementation with its own tests.

@jrcrittenden jrcrittenden Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on all of this. We're deferring the acs-wire package, the authenticator object, reading the environment through one validator, and single-sourced constants to a follow-up PR, tracked in #230, so this one stays reviewable.

Reply drafted with Claude Code.

let envelope: AcsRequestEnvelope;
try {
envelope = buildEnvelope(hookEventName, payload, hookmap);
if (hmacSecret) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: let GuardianClient own signing as well as verifying. This is the host half of my comment on server.ts:658.

Right now GuardianClient.post verifies responses, but governStep (here) and negotiateSessionConfig (handshake.ts:249) sign requests. So the secret is passed into five places, and any new caller of post has to remember to sign, or the Guardian refuses it.

// acs-hook.ts and acs-plugin.ts: construct once, at the composition root
const authenticator = config.hmacSecret ? createHmacAuthenticator(config.hmacSecret) : NULL_AUTHENTICATOR;
const guardian = createGuardianClient(config.guardianUrl, { authenticator });

// guardian-client.ts post(): sign on the way out, verify on the way back (ping exempt, per §13)
const outgoing = envelope.method === "system/ping" ? envelope : authenticator.signRequest(envelope);
// …send, then authenticator.verifyResponse(response, sessionId)

Remove:

  • governStep's hmacSecret option and the signing call (:171–173, :440, :665–667).
  • negotiateSessionConfig's hmacSecret option (handshake.ts:83, :249–251). profiles_supported reads guardian.algorithms.length > 0 instead (:208). The check that the Guardian accepted acs-core stays where it is, because it's about negotiation, not cryptography.
  • OpenCode's Deployment.hmacSecret and its two pass-throughs (acs-plugin.ts:1185, :1327, :1354, :1412).
  • sign-envelope.ts, which moves into acs-wire.

Also, the doc comment at :171 says "Base64-encoded IKM," but the type is a decoded Buffer. Moving the option out of governStep removes the mismatch.

Why this helps:

  • Encapsulation: only the composition root knows a secret exists. governStep goes back to governing steps.
  • Correctness: signing and verifying use the same object, so they can't use different keys, and no caller can forget to sign.

@jrcrittenden jrcrittenden Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on all of this. We're deferring the acs-wire package, the authenticator object, reading the environment through one validator, and single-sourced constants to a follow-up PR, tracked in #230, so this one stays reviewable.

Reply drafted with Claude Code.

@astrogilda

Copy link
Copy Markdown
Collaborator

Thanks, @jrcrittenden: I ran the issue's wire probes, split into 20 MUST requests, and none pass at the base (770f1e0) while 17 pass at this head (beee5b5).

Three remain. The Guardian accepts a replay after a restart, allows a call outside the negotiated methods_implemented where spec section 17.1 lists -32003, and answers a step from a session that never sent handshake/hello, which spec section 4 rules out and your follow-up list omits.

I opened probityai/agent-evidence-vectors#74 with them as an acceptance test, pinned in CI at both commits.

@jrcrittenden

Copy link
Copy Markdown
Collaborator Author

Thanks, @astrogilda. Running these as an acceptance test in probityai/agent-evidence-vectors#74 is very useful.

Two of the three are fixed in dd7e3b4:

  • No handshake (§4). Any hook method from a session that has not sent handshake/hello is refused with -32003 CAPABILITY_NOT_NEGOTIATED. system/ping stays exempt.
  • Method outside methods_implemented (§17.1). A method the session's hello did not declare is refused with -32003. Both shipped hosts follow the recovery action in §17.1: they repeat the handshake once and resend the step under a fresh request_id. If the resend gets no decision, the original refusal stands.

Replay after a restart is still open. The replay store is in memory, so it does not survive a restart. The README now lists this as an Open Core gap, and it is tracked for follow-up.

Reply drafted with Claude Code.

@shivang-sec

Copy link
Copy Markdown

Potential conformance issue: replay-cache capacity exhaustion uses -32005 REPLAY_DETECTED

The replay-protection store distinguishes three outcomes: "fresh", "replay", and "capacity". However, server.ts maps both non-fresh outcomes to JSON-RPC error code -32005:

if (replayStatus !== "fresh") {
  return errorResponse(
    rpcId,
    -32005,
    replayStatus === "replay"
      ? "REPLAY_DETECTED"
      : "REPLAY_PROTECTION_CAPACITY",
  );
}

This means a previously unseen request can receive:

code: -32005
message: REPLAY_PROTECTION_CAPACITY

The concern is that ACS §10.3/§17.1 defines -32005 as REPLAY_DETECTED for duplicate request_id/nonce detection. Replay-cache capacity exhaustion is a different condition: the request may be completely new and has not necessarily been seen before.
This creates a wire-level semantic mismatch. A client interpreting -32005 according to the ACS registry can reasonably treat the request as a replay and regenerate its request_id, even though changing the request ID does not resolve a replay-cache capacity condition.
I checked the existing replay-cache saturation test as well. It correctly verifies the intended fail-closed behavior:

request-1 -> "fresh"
request-2 -> "capacity"
request-1 -> "replay"

So I don't think the fail-closed behavior itself is the issue. The concern is specifically how the "capacity" result is translated into the ACS wire error.
This also appears distinct from the existing replay findings: those concern duplicate request_id handling and replay persistence across restart, whereas this concerns a new request being rejected because the replay store is full.
Could we either:

  1. define/use an appropriate ACS error semantics for replay-cache capacity exhaustion, or
  2. clarify the specification if -32005 is intentionally intended to cover both duplicate replay detection and replay-cache capacity?

If the latter is intentional, it would be useful for the specification to state that explicitly so implementations and clients do not interpret -32005 exclusively as duplicate request_id/nonce detection.

@rocklambros

Copy link
Copy Markdown
Collaborator

Hi @jrcrittenden, I have two small asks here and one question. They come from reviewing #244, the OpenTelemetry trace exporter, which will meet this PR in server.ts.

1. Please put metadata.evaluator on decision responses.
The trace exporter in #244 has to write acs.evaluator on every acs.decision event, because otel-mapping.json requires it. Today this Guardian never sends metadata.evaluator, so the exporter fills in deterministic on its own, and the trace and the envelope log disagree. You already own acs-result.ts and map-verdict.ts in this PR, so I'd like the fix to land here instead of in a third PR touching the same files. The change is to set metadata: { evaluator: "deterministic" } on every AcsResult this Guardian sends. That includes the fail-closed denies from denyOnInvalidEnvelope, because those are deterministic code too. "deterministic" is already in the AcsResult.metadata.evaluator enum in response-envelope.json. Please add one assertion to an existing response test. If you'd rather not grow this PR, tell me and we'll do it as a one-line follow-up right after you merge.

2. Heads-up: protocols/MCP/tools/call and the trace mapping.
This PR adds protocols/MCP/tools/call to METHODS_EVALUATED. otel-mapping.json has no step_to_span entry for it, so after both PRs merge, MCP tool calls would be decided with no span. I've asked #244 to add a test that every evaluated method either has a mapping entry or is listed in a new METHODS_WITHOUT_SPAN record in otel-trace-exporter.ts, with a reason. If #244 lands first, that test fails on your branch until you add a line like this:

"protocols/MCP/tools/call": "no step_to_span entry in otel-mapping.json yet",

If you land first, #244 adds it. Either way the gap stays visible instead of silent. #244 also no longer edits handshake.ts, so you won't get a conflict on the METHODS_EVALUATED line.

3. A question on the signing block in handleAcsRequest.
Everything between dispatch and return response is total today. dispatch sits inside a try, and the checkResponse reporter has its own try. The new HMAC block (requestHasValidSignature, deriveSessionKey, signResponseHmacSha256) runs outside any try. If any of those can throw, for example in canonicalization, the throw escapes handleAcsRequest. Bun then returns an HTML 500, and the host reads the hook as never fired. That's the ungoverned path the comment above handleAcsRequest warns about. Can those three functions throw on a response the Guardian built itself? If they can, please wrap the block the way the checkResponse reporter is wrapped. You decide what an unsigned answer should mean there. After #244, the trace exporter's end call also sits after this block, so a throw there would lose the span as well.

jrcrittenden added a commit to jrcrittenden/ACS that referenced this pull request Oct 12, 2026
A full replay-protection cache answered a brand-new request with -32005
REPLAY_DETECTED. §17.1 recovers from -32005 by regenerating request_id,
which cannot succeed while the cache is full. Return -32000
SESSION_REFUSED with data.reason "replay_protection_capacity" instead:
it is in the §17.1 registry, so every ACS client fails closed on it.

startGuardian takes an optional replayProtectionStore so a server test
can fill the cache.

Reported by @shivang-sec on GenAI-Security-Project#229.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
@jrcrittenden

Copy link
Copy Markdown
Collaborator Author

Thanks, @shivang-sec, this is a real conformance bug. A full replay cache is not a replay. The §17.1 recovery for -32005 (regenerate request_id) can't succeed while the cache stays full, so a client that follows the spec retries into the same error.

Fixed in a4efc16. A full cache now returns -32000 SESSION_REFUSED with data.reason: "replay_protection_capacity". A real replay still returns -32005 REPLAY_DETECTED. I chose -32000 because it's in the §17.1 registry, so any ACS client fails closed on it. A reference-implementation code such as -32020 could fail open in a client that doesn't know it. A new server test fills a one-slot cache and checks the code and reason.

The drawback is that §17.1 says not to retry -32000 without a configuration change, while this condition clears on its own once entries age out of the 5-minute skew window. The registry has no retryable "Guardian at capacity" code, so I've opened #257 to propose one.

@jrcrittenden

Copy link
Copy Markdown
Collaborator Author

Thanks, @rocklambros. All three are addressed in 6e6942d.

1. metadata.evaluator. Done here rather than as a follow-up. finalResult in acs-result.ts builds every AcsResult this Guardian sends, including the fail-closed denies from denyOnInvalidEnvelope, so it now sets metadata: { evaluator: "deterministic" } in that one place. The allow test in server.test.ts and the deny test in deny-on-invalid-envelope.test.ts both assert it.

2. protocols/MCP/tools/call. Understood. If #244 lands first, I'll add the METHODS_WITHOUT_SPAN line on this branch.

3. The signing block. Yes, it could throw, and not only on responses the Guardian built. The request half runs before any signature is verified, on unauthenticated input. Two inputs reproduced an HTML 500: a session_id over 1024 bytes, which makes HKDF throw in deriveSessionKey, and a deeply nested body, which overflows the stack in jcsCanonicalise. Neither needs the key.

The block is now wrapped (server.ts lines 680–711). If it throws, the response goes out unsigned and the failure is reported on stderr. That is what "unsigned" already means here: a request that throws in this block cannot carry a valid signature, so it gets the same unsigned answer as any other unauthenticated request, and a host that requires signatures rejects it. A new test sends both inputs and expects a JSON-RPC answer, not a 500.

Envelope log: this block sits between dispatch and the final envelopeLog.write("response", ...). The log now records a JSON-RPC response for those two inputs where it previously recorded nothing, because the throw escaped before the write. Nothing else it records changes.

jrcrittenden added a commit to jrcrittenden/ACS that referenced this pull request Oct 12, 2026
The HMAC signing block in handleAcsRequest ran outside any try, on
unauthenticated input. A session_id over 1024 bytes makes HKDF throw, and
a deeply nested body overflows the stack in JCS canonicalization. Either
escaped handleAcsRequest as an HTML 500, which a host reads as a hook
that never fired. The block is now wrapped. A request that throws there
cannot carry a valid signature, so its response goes out unsigned, like
any other unauthenticated request's, and the failure is reported on
stderr. The envelope log records the same response it did before, minus
the signature it could never have had.

Every AcsResult now carries metadata.evaluator "deterministic", so the
trace exporter in GenAI-Security-Project#244 reads the evaluator from the wire instead of
assuming it.

Both raised by @rocklambros on GenAI-Security-Project#229.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
A full replay-protection cache answered a brand-new request with -32005
REPLAY_DETECTED. §17.1 recovers from -32005 by regenerating request_id,
which cannot succeed while the cache is full. Return -32000
SESSION_REFUSED with data.reason "replay_protection_capacity" instead:
it is in the §17.1 registry, so every ACS client fails closed on it.

startGuardian takes an optional replayProtectionStore so a server test
can fill the cache.

Reported by @shivang-sec on GenAI-Security-Project#229.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
The HMAC signing block in handleAcsRequest ran outside any try, on
unauthenticated input. A session_id over 1024 bytes makes HKDF throw, and
a deeply nested body overflows the stack in JCS canonicalization. Either
escaped handleAcsRequest as an HTML 500, which a host reads as a hook
that never fired. The block is now wrapped. A request that throws there
cannot carry a valid signature, so its response goes out unsigned, like
any other unauthenticated request's, and the failure is reported on
stderr. The envelope log records the same response it did before, minus
the signature it could never have had.

Every AcsResult now carries metadata.evaluator "deterministic", so the
trace exporter in GenAI-Security-Project#244 reads the evaluator from the wire instead of
assuming it.

Both raised by @rocklambros on GenAI-Security-Project#229.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
Request-signature verification canonicalises the unauthenticated body
before computing the HMAC. A signed body nested past the stack made that
throw, and the throw fell through dispatch to the outer net, which
answers -32020. That code is outside the section 17.1 registry, so a
client branching on registered codes could fail open on it.
verifyHmacSha256 now treats an input it cannot canonicalise as an
invalid signature, so the request gets -32004 SIGNATURE_INVALID like any
other unauthenticated one. The signing-boundary test now asserts the
answer for each of its two inputs.

Raised by @astrogilda on GenAI-Security-Project#229.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
With HMAC on, two host paths turned a deny into an allow.

The client threw on any unverifiable response before reading its code,
so a refusal the Guardian cannot sign (oversize body, -32700, a bad
request signature) became an "unknown" failure and the proceed posture
ran the step. A refusal-coded error with no result is now passed through
unverified: it can only fail the step closed. The refusal codes move to
failure-kinds.ts so the client can read them without an import cycle.

A request too deep to canonicalise threw inside request building and the
posture answered it. Signing is now its own "sign" stage whose failure,
kind "unsignable", blocks regardless of posture.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
A protocols/MCP/tools/call payload carrying both tool/arguments and
params was evaluated on the former while a forwarding server runs the
latter. Both shapes together are now refused as envelope_invalid, and
{value} is unwrapped only in the ACS shape.

The stock rules skip a policy target that is not a string, so an object
or array command was allowed on any tool-call path. The snapshot
assembler now throws on one, which denies with evaluation_failed.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
The host listed the refusal codes it knew, so a code added later, such
as the retryable overload code Discussion GenAI-Security-Project#257 proposes, was classified
error_without_decision and the proceed posture ran the step. The host now
treats -32700 and the whole -32000..-32099 range as a refusal, both when
it accepts an unsigned refusal and when it classifies one. Codes outside
the range, like -32601 or -32603, still keep the posture.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
…he MCP method

handshake/hello, which GenAI-Security-Project#229's Guardian refuses with -32003. postRaw and
the generator now send one first; the hello gets no span.

protocols/MCP/tools/call is evaluated but otel-mapping.json maps only
steps/* and agbom/* methods, so it is named in METHODS_WITHOUT_SPAN with
that reason until the spec gives it a step_to_span entry.

The decision event now carries acs.evaluator, and the response carries a
chain_hash that covers each entry's recorded time. The two tests that
compare a Guardian with export on and off give both the same clock, and
the sample comparison sets the hash's value aside with the timestamps.
The committed sample is regenerated.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
…example

The sample trace was regenerated under GenAI-Security-Project#229's Guardian, whose decision
event now carries acs.evaluator and acs.chain_hash. The example on the
page is checked against the sample, so it is copied again, and the
sentence that lists the event's contents names both.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
PR GenAI-Security-Project#272 defines key_id for HMAC as an opaque label from the deployment's
configuration that names one secret. This tree used the session_id as
key_id and rejected any other value.

The Guardian now requires ACS_HMAC_KEY_ID beside ACS_HMAC_SECRET, with
no default, and verifies a request with the secret its key_id names. An
unknown label is SIGNATURE_INVALID, unsigned, and is never tried against
another secret. A response is signed with the secret, and names the
key_id, of the request it answers.

Both hosts read the same pair, sign with the configured label, and
reject a response that names another. Setting only one of the two is a
configuration error. The OpenCode plugin raises it from each hook rather
than from its factory, because a factory throw unloads the plugin and
leaves every tool ungoverned.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
…hello from failing open

Three places where the keyed host still failed open under `proceed`, from
the 10-29 review:

- A reply whose signature fails verification, or that answers another
  request (its JSON-RPC id or result.request_id does not match), is now
  its own failure kind, signature_invalid. It blocks the step whatever
  the posture, as issue GenAI-Security-Project#308 rules, and becomes an acs.decision.failure
  with class signature_invalid. A stripped signature, a wrong key and a
  replayed earlier allow each end in deny.
- The one retry after REPLAY_DETECTED replaces the refusal only when a
  decision arrives, as the -32003 retry already does. A retry that times
  out leaves the refusal standing.
- A verified ServerHello that this signed host rejects for lacking
  acs-core or HMAC-SHA256 keeps the posture it declared. A hello that
  fails verification carries no posture this host can trust, so every
  failure in that session blocks instead of falling to the ACS default.

The Guardian README says why -32003 and the -32000 capacity refusal are
recorded under the request's ids: both come after the signature.

The tree README now carries the three lines asked for on 10-13: the
agent's shell can read the secret with printenv, neither host sends the
rest of the minimum hook set, and the section 10.3 nonce is not checked.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
PR GenAI-Security-Project#334 makes the Guardian answer -32600 Invalid Request for a JSON-RPC
frame it cannot read. That code sat outside the refusal range, so the
host applied its posture, and under `proceed` the step ran: on a keyless
host, `rm -rf /` came back allow. isRefusalCode now counts -32600 with
-32700 and the -32000..-32099 range, so the step blocks.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
…32603

A host that holds an HMAC key and gets a JSON-RPC error for its
handshake/hello has no verified ServerHello and so no posture. Its session
is now untrusted: every failure in it blocks, rather than falling back to
the default proceed. A wrong key against a Guardian that declares deny
used to allow a step the Guardian did not answer.

D-040: every JSON-RPC error is a refusal except a signed -32603. The
client passes an unsigned error of any code through as a refusal and
throws GuardianInternalError for a -32603 whose signature verified, which
is the one error that follows the posture. -32601 and -32602 no longer
run the step under proceed. isRefusalCode is gone: no code decides it.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
The TypeScript Guardian now refuses to start without an HMAC key and
refuses an unsigned step or one outside a handshaken session, so
record-ts-cases.sh could not record. The script makes a key for the run,
and the recorder sends each case as an Observed Agent does: a hello, then
signed steps, with every answer's signature verified.

Re-recorded at this tree. Every decision now carries
metadata.evaluator. command_not_a_string and fetch_url_not_a_string are
denied, so aheadOfTypeScript is empty and removed. An unregistered tool
is denied with tool_unregistered, where the Go Guardian still answers
AGT's runtime_error:tool_unknown: behindTypeScript names those two cases
and docs/differences.md records it.

Signed-off-by: Jason Crittenden <jrcrittenden@gmail.com>
@jrcrittenden
jrcrittenden force-pushed the fix/acs-core-conformance-d1-d10 branch from 593ac25 to a63ab58 Compare December 2, 2026 05:33
@jrcrittenden

Copy link
Copy Markdown
Collaborator Author

@rocklambros rebased onto integration at b323224, which has #355 and #741, and your three items are in two new commits on top: c86d362 and a63ab58.

Rebase. All 14 commits applied without a conflict this time. I checked the #355 lines by hand anyway. Both hosts create their applied request store and pass appliedRequests to governStep. In govern-step.ts the clear still runs before the -32003 retry and the set still runs after the REPLAY_DETECTED retry. I changed nothing for blocker 3.

1. The refused hello (c86d362). negotiateSessionConfig throws HelloRefusedError when a host that holds an HMAC key gets a JSON-RPC error for its hello. applyFailurePosture treats that session as untrusted, the same as one whose hello failed verification, so every failure in it blocks. That covers the three cases you listed: a refused hello, an unsigned error and an unverifiable answer. It reads any error member as a refusal, error: false included.

The test sits next to the one you pointed at. A wrong-key host meets a Guardian that declares deny, the hello gets -32004, and the step stalls past the timeout. The result is deny, audited as failure.kind: timeout, posture_source: default, outcome: blocked. A second test pins that a keyless host's refused hello still leaves the default posture, so the first can't pass by blocking everything.

A hello that times out or can't connect still follows the posture, as D-040 has it.

4. The D-040 codes (c86d362). Every JSON-RPC error is a refusal except a signed -32603. Only the client knows whether an error verified, so the two part there. An unsigned error of any code passes through and is classified refused. A -32603 whose signature verified is thrown as GuardianInternalError and classified error_without_decision, which follows the posture. isRefusalCode is removed, because no code decides anything now. An error with a missing or non-numeric code is a refusal too, and so is one whose message cannot be printed, such as {"toString": 0}.

The signed -32603 follows the posture only when its id is this request's. One signed for another request fails correlation and blocks, and one with a null id is a refusal, so an old signed -32603 can't be replayed at a step to open it.

Two consequences:

  • An unsigned -32603 blocks.
  • On a host with no key, every error blocks, -32603 included, because nothing that host receives is signed.

A timeout, a transport failure and an HTTP error with no JSON-RPC body keep the posture.

Tests drive the real Claude Code shim. Unsigned -32601, -32602 and -32603 block rm -rf / under proceed. Through a keyed Guardian, a signed -32603 proceeds, and the same error with its signature stripped blocks.

2. The recording script (a63ab58). Exporting the two variables was not enough. The recorder sent unsigned steps with no hello, and this Guardian refuses both. The script now makes a key for the run. The recorder uses the Go observedagent.Client: one hello per case, then signed steps, with each answer's signature verified. I ran it, and it records all 49 cases. The new ts-cases.json is committed, so TestRecordingIsCurrent has a current recording to check.

Besides metadata.evaluator on every decision, the new recording changes four answers:

  • command_not_a_string and fetch_url_not_a_string are now denied. That is the fix aheadOfTypeScript was waiting for, so I removed both entries as its comment says.
  • unregistered_tool and result_unregistered_tool are denied with tool_unregistered, which this PR adds. The Go Guardian answers AGT's runtime_error:tool_unknown. Both deny, for different reasons. I did not change the Go Guardian. The two cases are named in a behindTypeScript map in recorded_cases_test.go, and docs/differences.md has a row for it. I also updated the two rows there that this PR makes untrue: the non-string policy target and the host failure resolution.

Two things I could not check here:

  • I have no Rust toolchain on this machine, so I could not build the agteval tests. go vet -tags agteval ./agtbridge/ and the untagged go test ./... pass. CI on this push is the first run of TestRecordedCases against the new recording.
  • I recorded with bun 1.3.13, not the pinned 1.4.5.

Description. Added the four Closes lines. Part of #184 stays, and #139 is untouched.

Suite: 1503 pass, 4 skip, 0 fail. Typecheck is clean. I broke each fix on purpose and a test failed each time.

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

This pull request's description says it closes #141 #142 #165 #199, which is on the project roadmap. When it merges, GitHub closes that issue and the roadmap counts it as delivered. Please confirm the change delivers the whole issue before merging.

@bar-capsule

Copy link
Copy Markdown
Collaborator

@jrcrittenden the D-040 split reads right to me: every error refuses except a signed -32603 that names this request's id.

One test pins the opposite, though: "leaves a keyless host on the default posture when its hello is refused". The Guardian answers that hello with an unsigned -32004, which D-040 counts as a refusal, so the step should block the same way it does for the wrong-key host. As written, a host that loses its key fails open on every step, the downgrade c86d362 closes for a keyed host. It also differs from your rule that on a host with no key every error blocks. Could the keyless case block too, with that test flipped?

The default proceed and the posture coming from the ServerHello are #722's (D-036, D-045), so I'm not asking for those here.

@rocklambros rocklambros left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Jason. I re-reviewed a63ab58, which sits on the current integration tip.

All four of my asks from 11-30 are closed, and I checked each one by running it:

  • A refused hello now blocks. A wrong key, a wrong key_id, an unsigned error and a tampered ServerHello each end in deny when the step then stalls.
  • record-ts-cases.sh starts the Guardian with a key, and the recording it writes matches the committed ts-cases.json byte for byte.
  • A -32003 retry at a result gate names the retry.
  • Every unsigned error blocks, and so does every signed error except -32603. A signed -32603, a timeout and a 502 with a text body follow the posture, as D-040 says.

The tests pass too. bun test gives 1507 tests with 1 skip and 0 failures, bun run typecheck is clean, and make test in agt-go passes with the AGT runtime, including TestRecordingIsCurrent. The Closes lines are in, and a security scan of the change found nothing.

One thing still blocks the merge. A reply whose signature check throws still follows the posture.

verifyResponseSignature (packages/host-adapter/src/sign-envelope.ts:111) can throw on a value the peer sends. String(fields.algorithm) throws a TypeError when the algorithm is {"toString":0}. jcsCanonicalise (line 122) throws a RangeError on a deeply nested result, and a reply body of JSON null throws a TypeError too. post() in guardian-client.ts:273 lets the throw escape, and classifyDeliveryFailure files it as transport or unknown, so the posture decides.

I added two cases to hosts/claude-code/test/posture.test.ts on your head and ran them:

  1. The step reply carries "signature": {"algorithm": {"toString": 0}}. Result: decision: allow, outcome: proceeded, failure: transport. It should be deny with signature_invalid.
  2. The hello reply carries the same signature, then the step gets a 502. Result: decision: allow, posture_source: default. The session should be untrusted, so the step should be blocked.

The fix:

  1. In post(), wrap the call to verifyResponseSignature in try/catch and rethrow anything it throws as GuardianSignatureError. That covers the hello as well, so untrustedSession sets.
  2. In sign-envelope.ts:111, use printable(fields.algorithm) in place of String(fields.algorithm).
  3. Add both cases above to the "a reply that fails verification blocks the step under proceed" block in posture.test.ts, each expecting deny and signature_invalid.

I'll put the smaller follow-ups in one issue for you once this is approved, as I said on 11-30. Two of them came up this round: a 429 with no JSON-RPC body still follows the posture (D-046, which integration doesn't handle either), and a step blocked by an untrusted session is audited as a timeout. I'll also add the missing test for the -32003 retry on our side, since that code came from PR #741 (keep a result request's applied request record through a rebuild).

@rocklambros rocklambros left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Jason, I'm approving this PR at a63ab58.

You fixed every item from my review on 11-30, and I checked each fix by running it. I'm sorry this took so many rounds. Some of those rounds came from changes we made on our side.

I'm no longer asking you to fix the problem from my review earlier today. When the signature check on a Guardian reply throws an error instead of returning "invalid", the step follows the posture. That problem is real, but it is small: an attacker who can send that malformed reply can also just drop the connection, which already follows the posture. We will fix it ourselves in a separate PR, with the test I already wrote.

This PR will merge into integration in the next batch, together with other PRs for release 0.1.6. You don't need to do anything else.

@rocklambros
rocklambros merged commit 7ae05c4 into GenAI-Security-Project:integration Dec 3, 2026
23 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Done in ACS Project Tracker Dec 3, 2026
@rocklambros rocklambros mentioned this pull request Dec 3, 2026
10 of 15 tasks
e2hln pushed a commit to e2hln/agent-control-standard that referenced this pull request Dec 3, 2026
The exporter already starts a span for any mapped method in methodsEvaluated,
but it had no sources for the attributes the mapping lists on the session and
message spans, so those spans went out without them. This adds sources for
acs.session.reason, acs.content.types, and the session span's optional
acs.tenant_id, acs.user.id and acs.policy_mode.

acs.content.types holds one entry per content item, in wire order, and is not
deduplicated. The mapping does not say whether it is a set; this keeps the
counts, and is a one-line change if the Spec leads prefer a set.

This Guardian does not evaluate the four methods yet, and PR GenAI-Security-Project#229 keeps them
out of methods_evaluated, so the spans do not appear in a live run. The tests
drive them through the exporter's methodsEvaluated option, as GenAI-Security-Project#322 describes.
Provenance on message content items is left for a later slice.

Part of GenAI-Security-Project#322

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Eli Sherman <esherman@credo.ai>
e2hln pushed a commit to e2hln/agent-control-standard that referenced this pull request Dec 3, 2026
PR GenAI-Security-Project#229 makes the Guardian answer -32003 until handshake/hello declares the
method (§4). The drift manifest test from PR GenAI-Security-Project#541 posted its step directly,
so it read no decision. It now calls handshakeFor first, as the other
Guardian tests do.

Signed-off-by: Rock Lambros <rock@rockcyber.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

7 participants