# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-validate-the-a2a-agent-card-s-signatures-jws-payload-against-the-discovered-key-set-rather-than-the-card-s-self-declared-kid-an.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-validate-the-a2a-agent-card-s-signatures-jws-payload-against-the-discovered-key-set-rather-than-the-card-s-self-declared-kid-an.warrant.json
# Markdown SHA-256:   a4c8fe006ebb1488227bdd7a23cd52fd270b9cd1d4bdd75df653e2913cdcb6c6
# Code AST SHA-256:   287fa44a9185faf8b2801e6d1a2cc4255604977b00895fb0421027c74d9d6570
# Verified Classes:   CardVerificationError, TrustAnchor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

class CardVerificationError(RuntimeError):
    """Raised when an A2A agent card fails anchor-bound verification."""

@dataclass(frozen=True)
class TrustAnchor:
    origin: str
    pinned_jwks: dict  # kid -> public key, established at onboarding

def verify_card_at_discovery(card: dict, anchor: TrustAnchor) -> bytes:
    sig = card["signatures"][0]
    header = sig["protected"]
    kid = header["kid"]

    # Invariant: kid may only SELECT within the pinned set, never locate a key.
    if header.get("jwks_uri") or card.get("url", "").split("/")[2] != anchor.origin:
        raise CardVerificationError(
            f"card origin or jwks_uri violates trust anchor for {anchor.origin}"
        )
    key = anchor.pinned_jwks.get(kid)
    if key is None:
        raise CardVerificationError(
            f"kid {kid!r} not present in pinned JWKS for {anchor.origin}"
        )

    body = canonical_bytes(card)  # excludes signatures[] itself
    if not verify_es256(body, sig["signature"], key):
        raise CardVerificationError("signature invalid under pinned key")

    # Pin the exact verified bytes; routing must read only from these.
    return hashlib.sha256(body).digest()

def submit_task(card: dict, pinned_hash: bytes, payload: bytes) -> None:
    if hashlib.sha256(canonical_bytes(card)).digest() != pinned_hash:
        raise CardVerificationError("card mutated between discovery and submission")
    # Only now may endpoint bytes be emitted.
    emit(card["url"], payload)
