# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-trust-agent-card-discovery-in-a2a-v1-0-signed-task-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-trust-agent-card-discovery-in-a2a-v1-0-signed-task-delegation.warrant.json
# Markdown SHA-256:   c7875ee1e4e28c92ca443fd0a1903b76ba6541192db4091715dff08d8c7e9a17
# Code AST SHA-256:   b817b823117fb69cc6dae43f2f6f1e27ac7db66e4bac5b0351608b636ee7835a
# Verified Classes:   AgentCardProvenanceError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac


class AgentCardProvenanceError(RuntimeError):
    """Raised when a signed delegation envelope is cryptographically valid
    but its Agent Card provenance cannot be bound to the transport origin."""


def verify_delegation_envelope(envelope: dict, fetched_card: dict, card_origin: str) -> bool:
    """
    envelope: parsed JWS payload with keys: iss, kid, aud, card_digest, origin, exp
    fetched_card: the card bytes fetched *this call* from card_origin (never from cache)
    card_origin: the TLS-authenticated origin the envelope arrived over
    """
    if envelope.get("origin") != card_origin:
        raise AgentCardProvenanceError(
            f"envelope origin {envelope.get('origin')!r} != transport origin {card_origin!r}"
        )

    recomputed = hashlib.sha256(
        _canonical_card_bytes(fetched_card)
    ).hexdigest()

    if not hmac.compare_digest(recomputed, envelope.get("card_digest", "")):
        raise AgentCardProvenanceError(
            "card_digest mismatch: cached or substituted card cannot authorize envelope"
        )

    if fetched_card.get("id") != envelope.get("iss"):
        raise AgentCardProvenanceError("iss does not match fetched card id")

    if envelope.get("kid") not in fetched_card.get("publicKeys", {}):
        raise AgentCardProvenanceError("kid not present in fetched card key set")

    return True


def _canonical_card_bytes(card: dict) -> bytes:
    import json
    return json.dumps(card, sort_keys=True, separators=(",", ":")).encode("utf-8")
