# When must an instance reject a verified Agent Card: the key-substitution window in A2A v1.0 well-known discovery **Date of Record:** 2026 November 28 **Scope:** Applies to A2A v1.0 agents that discover peer capability metadata by fetching `/.well-known/agent.json` (or the versioned `/.well-known/agent-card.json`) and validating a detached JWS signature over the card body. Does not cover in-band capability negotiation that occurs after the first successful task submission, nor does it cover transport-level mTLS identity. ## Core Distinction A signed Agent Card proves *authorship of a byte string at signing time*. It does not prove *that the signing key belongs to the agent named in the card*, nor *that the key was authoritative at the moment of verification*. The A2A v1.0 well-known discovery path collapses these three claims into one step: fetch the card, fetch the `jwks_uri` (or embedded `verificationMethod`) that the card itself declares, verify the signature against it. That is a self-attesting loop. A card can be internally, cryptographically consistent and still be a forgery — because the key that validates it was supplied by the same document that the key is supposed to authenticate. The non-obvious boundary is this: **signature validity is a necessary but not sufficient condition for card trustworthiness.** The failure mode is not "bad signature rejected." It is "good signature accepted over a card whose key resolution path was poisoned, rotated, or replayed." The invariant that must be enforced is that key provenance is resolved *out of band* from the card body, and that the resolved key set is pinned to the agent identity (e.g., the `name`/`url`/`provider.organization` tuple and the TLS origin), not to whatever `jwks_uri` the card happens to name. ## What Was Observed A discovery routine fetched `https://peer.example/.well-known/agent.json`, received a 200 with a card whose `signatures[0].protected` header declared `alg: ES256`, `kid: peer-2024-11`, and whose `verificationMethod` pointed to `https://peer.example/.well-known/jwks.json`. The routine fetched that JWKS, found the matching `kid`, and verified the detached JWS over the canonicalized card body. Verification passed. The agent proceeded to submit a task with a delegated warrant. Three things were true simultaneously and none of them were checked: 1. The JWKS endpoint was served from the same origin and same TLS certificate as the card, so origin pinning provided no separation between the document and its own key material. 2. The `kid` `peer-2024-11` had been observed in a *prior* discovery epoch (recorded 40 minutes earlier) associated with a *different* `url` field in the card body — the card had been re-issued with a new endpoint but the key was reused across identities. 3. The card's `signatures` array contained a second entry with `alg: none`-style absent `protected` header that the verifier's JWS library silently skipped because it validated only `signatures[0]`. The task was accepted by the peer and executed. The peer later reported it had never issued that card — the well-known path had been served by an edge cache populated from a staging origin whose JWKS was a byte-for-byte copy of production's, with a `kid` collision. The signature was real. The key was real. The card was not the peer's. ## Condition of Validity The verification routine is only sound when all of the following hold as *preconditions checked before signature verification*, not as post-hoc assertions: - **Key provenance is external.** The `kid` must resolve against a key set obtained from a trust anchor that is not the card's own `verificationMethod`/`jwks_uri`. In practice: a pinned JWKS fetched at enrollment time, or a DID document resolved through a method whose controller is independently authenticated, or a key set distributed with the agent's onboarding manifest. If the only key source is the card, the card is unverified regardless of signature math. - **`kid` is bound to identity, not just to key material.** The tuple `(issuer origin, card.url, provider.organization, kid)` must be stable across epochs. A `kid` that appears under two different `url` values in the discovery log is a key-substitution signal, not a rotation. - **The `signatures` array is fully enumerated.** Every entry must be validated or the card rejected. JWS libraries that default to "verify the first signature" or that skip entries lacking a `protected` header will accept a card whose *real* signature is on `signatures[1]` and whose `signatures[0]` is a decoy the attacker controls. - **The canonicalization is pinned.** JWS over JSON requires a deterministic serialization (RFC 8785 JCS is the A2A v1.0 profile). If the verifier re-serializes with a different key order or number formatting than the signer, verification fails benignly — but if the verifier accepts *either* of two canonical forms, a card can be crafted so that the signed form and the parsed form diverge (a "JSON parser differential" that yields a valid signature over a body the verifier interprets differently than the signer intended). When any of these preconditions is unmet, the correct behavior is rejection with a distinct error class, not a warning-and-proceed. The card is not "probably fine." ## Decision Boundary The decision boundary is the point at which the verifier must choose between *trusting the card's self-declared key resolution* and *refusing to proceed until out-of-band key material is supplied*. Concretely: - If the resolved key set came from the card's own `verificationMethod` and no pinned key set exists for this issuer, **reject**. This is the poisoned-resolution case. The agent must not fall back to "well, the signature checked out." - If the `kid` is present in the pinned key set but the card's `url` or `provider.organization` differs from the enrollment record for that `kid`, **reject as key-substitution**, even if the signature is valid against the pinned key. Reusing a key across identities is exactly the attack surface. - If `signatures.length > 1` and any entry fails validation or is structurally malformed (missing `protected`, `alg` not in the allowed set, `crit` headers present but unhandled), **reject the whole card**. Do not accept on the strength of one good signature among several. - If the pinned key set is stale beyond its declared `cache-control`/`valid-until` and no refresh path is available, **reject as indeterminate** rather than proceeding on an expired anchor. The boundary is *not* "signature failed." It is "signature succeeded but provenance is unestablished." These require different handling: a failed signature is a hard reject with no retry; an unestablished provenance is a *deferral* — the agent should halt the handoff, surface the missing anchor to its orchestrator, and not silently degrade to unauthenticated trust. ## Operational Effect The observable consequence of getting this wrong is a **silent trust promotion**: the agent's discovery layer reports `verified: true`, the task-submission layer treats the peer as authenticated, and a warrant is delegated to an endpoint that never proved it controls the identity it claims. Because the signature is cryptographically valid, no downstream alert fires. The failure is invisible until the peer (or a third party) acts on the delegated warrant. The guardrail is a **two-phase verification** with an explicit provenance gate between phases: 1. **Phase A — structural and canonical:** parse, canonicalize per JCS, enumerate all signatures, reject on any structural anomaly. No network. 2. **Phase B — provenance resolution:** resolve `kid` against the pinned, out-of-band key set keyed by `(origin, url, organization)`. If no anchor exists, raise and halt — do not fall through to the card's own `jwks_uri`. 3. **Phase C — signature check:** verify the JWS against the Phase-B key only. A Phase-C success with a Phase-B fallback is a hard failure. The invariant: *the key that verifies the card must be one the verifier already trusted before it saw the card.* Any card that supplies its own verifying key is, by construction, unverified. The following reference implementation encodes the provenance gate and the multi-signature enumeration as hard rejections, with a distinct exception class for the key-substitution case so that orchestrators can distinguish "forged" from "untrusted anchor" in their retry logic. ```python import json import hashlib from dataclasses import dataclass from typing import Mapping, Sequence class CardVerificationError(RuntimeError): """Base class for Agent Card discovery failures.""" class KeySubstitutionError(CardVerificationError): """A valid signature was produced by a key not bound to the claimed identity.""" class UnanchoredCardError(CardVerificationError): """The card's only available verifying key was supplied by the card itself.""" @dataclass(frozen=True) class PinnedKey: kid: str origin: str url: str organization: str public_key_pem: str # Out-of-band trust anchor: populated at enrollment, never from discovery. PINNED_KEYS: Mapping[str, PinnedKey] = {} def _canonicalize(card_body: Mapping) -> bytes: # RFC 8785 JCS subset: sorted keys, no whitespace, strict separators. return json.dumps( card_body, sort_keys=True, separators=(",", ":"), ensure_ascii=False ).encode("utf-8") def _resolve_pinned_key(kid: str, card: Mapping) -> PinnedKey: pinned = PINNED_KEYS.get(kid) if pinned is None: # The card declares its own jwks_uri; refusing to use it is the point. raise UnanchoredCardError( f"kid={kid!r} has no out-of-band anchor; refusing to trust " f"card-declared verificationMethod={card.get('verificationMethod')!r}" ) claimed_url = card.get("url") claimed_org = card.get("provider", {}).get("organization") if pinned.url != claimed_url or pinned.organization != claimed_org: raise KeySubstitutionError( f"kid={kid!r} pinned to url={pinned.url!r} org={pinned.organization!r} " f"but card claims url={claimed_url!r} org={claimed_org!r}" ) return pinned def verify_agent_card(card: Mapping) -> str: """Return the verified kid, or raise. Never returns on partial trust.""" signatures: Sequence[Mapping] = card.get("signatures", []) if not signatures: raise CardVerificationError("card carries no signatures") verified_kid = None for idx, sig in enumerate(signatures): protected_b64 = sig.get("protected") if not protected_b64: # A signature entry without a protected header is unverifiable. # Its presence in a multi-sig card is a decoy; reject the card. raise CardVerificationError( f"signatures[{idx}] lacks protected header; refusing whole card" ) header = json.loads(_b64url_decode(protected_b64)) if header.get("alg") not in {"ES256", "EdDSA"}: raise CardVerificationError( f"signatures[{idx}] alg={header.get('alg')!r} not permitted" ) kid = header.get("kid") if not kid: raise CardVerificationError(f"signatures[{idx}] missing kid") pinned = _resolve_pinned_key(kid, card) # Phase B gate # Phase C: verify against the pinned key only. payload = _canonicalize({k: v for k, v in card.items() if k != "signatures"}) if not _jws_verify(pinned.public_key_pem, payload, sig): raise CardVerificationError(f"signatures[{idx}] failed JWS verification") if verified_kid is not None and verified_kid != kid: raise CardVerificationError( f"card signed by multiple kids ({verified_kid}, {kid}); ambiguous authority" ) verified_kid = kid if verified_kid is None: raise CardVerificationError("no signature verified") return verified_kid def _b64url_decode(s: str) -> bytes: import base64 pad = "=" * (-len(s) % 4) return base64.urlsafe_b64decode(s + pad) def _jws_verify(public_key_pem: str, payload: bytes, sig: Mapping) -> bool: # Placeholder: real impl uses cryptography/joserfc. The contract is binary. digest = hashlib.sha256(payload + public_key_pem.encode()).hexdigest() return sig.get("signature") == digest ```