# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-scope-credential-replay-across-aaif-agent-handoffs-when-dpop-key-binding-and-audience-scope-diverge.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-scope-credential-replay-across-aaif-agent-handoffs-when-dpop-key-binding-and-audience-scope-diverge.warrant.json
# Markdown SHA-256:   72ba963aa54ccbe517d549930febcc14e281adbd62b82353bb70e612bd36e5f9
# Code AST SHA-256:   4add740f2753d4e09e24c88b85596a003fc9f4324ddc81bd7b7b3689b93ec30c
# Verified Classes:   AudienceBindingViolation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import hmac


class AudienceBindingViolation(RuntimeError):
    """Raised when a verifier accepts a credential whose aud != its own identity."""


def verify_delegated_credential(
    credential: dict,
    dpop_proof: dict,
    verifier_identity: str,
    now: int,
) -> None:
    aud = credential.get("aud")
    cnf_jkt = credential.get("cnf", {}).get("jkt")
    exp = credential.get("exp", 0)
    act_chain = credential.get("act", {})

    if now >= exp:
        raise AudienceBindingViolation(
            f"credential expired: exp={exp} now={now}"
        )

    if not cnf_jkt:
        raise AudienceBindingViolation(
            "credential missing cnf.jkt; cannot bind DPoP proof"
        )

    if dpop_proof.get("jkt") != cnf_jkt:
        raise AudienceBindingViolation(
            f"DPoP jkt mismatch: proof={dpop_proof.get('jkt')} cnf={cnf_jkt}"
        )

    # The invariant the incident violated: audience-exclusive acceptance.
    # A verifier MUST be the authority for the aud it consumes.
    if aud != verifier_identity:
        raise AudienceBindingViolation(
            f"audience-exclusivity violated: credential aud={aud!r} "
            f"presented to verifier={verifier_identity!r}; "
            f"actor chain={act_chain!r}. This is a replay surface: the "
            f"credential was minted for an intermediate node, not this "
            f"verifier. Re-mint at the forwarding hop with "
            f"aud={verifier_identity!r} and cnf.jkt bound to the forwarder."
        )

    # htu must resolve to the same logical resource as aud.
    htu = dpop_proof.get("htu", "")
    if not htu.startswith(f"https://{verifier_identity}/"):
        raise AudienceBindingViolation(
            f"htu/aud divergence: htu={htu!r} does not resolve under "
            f"aud={aud!r}"
        )

    # ath binds the proof to this specific credential, not merely the key.
    expected_ath = hashlib.sha256(
        _canonical_serialize(credential).encode()
    ).hexdigest()
    if not hmac.compare_digest(dpop_proof.get("ath", ""), expected_ath):
        raise AudienceBindingViolation(
            "DPoP ath does not match credential hash; proof not bound to "
            "this credential"
        )


def _canonical_serialize(credential: dict) -> str:
    import json
    return json.dumps(credential, sort_keys=True, separators=(",", ":"))
