# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-dpop-bound-delegated-agent-token-whose-proof-of-possession-key-was-silently-rotated-mid-chain-invalidating-downstream.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-dpop-bound-delegated-agent-token-whose-proof-of-possession-key-was-silently-rotated-mid-chain-invalidating-downstream.warrant.json
# Markdown SHA-256:   ca0811b695e56c272ded91d5185519ac1f3f852e25e3499e7457b82991ca2191
# Code AST SHA-256:   2986637a9c0c1fd15c9c9e7c458500329eb7d3d8e9d2c068be3998896b249577
# Verified Classes:   ChainLineageBreak, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ChainLineageBreak(RuntimeError):
    """Raised when a DPoP proof's key does not match the parent-attested
    thumbprint embedded in the delegated warrant, even if the proof is
    otherwise valid against the IdP's current JWKS."""
    pass


@dataclass
class Warrant:
    sub: str
    cnf_jkt: str          # thumbprint the token is bound to
    parent_attested_jkt: str | None  # thumbprint the delegating parent signed over
    exp: int


def _thumbprint(jwk: dict) -> str:
    # RFC 7638 canonical thumbprint
    canon = json.dumps(
        {"crv": jwk["crv"], "kty": jwk["kty"], "x": jwk["x"], "y": jwk["y"]},
        separators=(",", ":"), sort_keys=True,
    )
    return hashlib.sha256(canon.encode()).hexdigest()


def verify_presentation(warrant: Warrant, proof_jwk: dict, now: int) -> None:
    proof_jkt = _thumbprint(proof_jwk)

    if now >= warrant.exp:
        raise ChainLineageBreak(f"warrant expired for sub={warrant.sub}")

    # Conjunct 1: proof key must match the token's cnf.jkt.
    if proof_jkt != warrant.cnf_jkt:
        raise ChainLineageBreak(
            f"proof key {proof_jkt[:12]} != cnf.jkt {warrant.cnf_jkt[:12]} "
            f"for sub={warrant.sub}"
        )

    # Conjunct 3: cnf.jkt must match the parent's mint-time attestation.
    # Absence of attestation is NOT a pass; it is the silent-failure state.
    if warrant.parent_attested_jkt is None:
        raise ChainLineageBreak(
            f"no parent attestation for sub={warrant.sub}; "
            f"lineage unverifiable, refusing state-mutating call"
        )
    if warrant.parent_attested_jkt != warrant.cnf_jkt:
        raise ChainLineageBreak(
            f"lineage break for sub={warrant.sub}: cnf.jkt "
            f"{warrant.cnf_jkt[:12]} != parent-attested "
            f"{warrant.parent_attested_jkt[:12]} (key rotated mid-chain?)"
        )
