# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-cross-org-agent-fail-attestation-when-its-spiffe-id-is-valid-but-its-svid-rotates-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-cross-org-agent-fail-attestation-when-its-spiffe-id-is-valid-but-its-svid-rotates-mid-handoff.warrant.json
# Markdown SHA-256:   19e03341577746ec835e4cdd2f5f4267990f10a60b016dae4f2e0f3c09749955
# Code AST SHA-256:   e7f41c03bf78dfa68d09e7b2e4357212bf2905dc522e6223b9a8bf2f65d80633
# Verified Classes:   IdentityBindingDivergence, SVID, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class IdentityBindingDivergence(RuntimeError):
    """Raised when a warrant's proof-of-possession binding no longer matches
    the presented SVID, and the mismatch is NOT an authenticated rotation."""
    pass


@dataclass
class SVID:
    spiffe_id: str
    public_key_pem: bytes
    not_after: float

    @property
    def key_fingerprint(self) -> str:
        return hashlib.sha256(self.public_key_pem).hexdigest()


@dataclass
class Warrant:
    sub: str                 # SPIFFE ID asserted
    aud: str
    cnf_key_fingerprint: str # binding at mint time
    not_after: float
    rotation_chain: Optional[list] = None  # [(old_fp, new_fp, signed_at)]


def verify_handoff(warrant: Warrant, peer: SVID, now: Optional[float] = None) -> None:
    now = time.time() if now is None else now

    if warrant.sub != peer.spiffe_id:
        raise IdentityBindingDivergence(
            f"subject mismatch: warrant.sub={warrant.sub} peer={peer.spiffe_id}"
        )

    if now > warrant.not_after:
        # Expiry is a separate, retryable-with-re-mint condition.
        raise IdentityBindingDivergence(
            f"warrant expired at {warrant.not_after}, now={now}"
        )

    if warrant.cnf_key_fingerprint == peer.key_fingerprint:
        return  # binding current; proceed

    # Binding mismatch: only admissible if an authenticated rotation chain
    # connects the minted key to the currently presented key.
    if warrant.rotation_chain:
        chain = {old: new for old, new, _ in warrant.rotation_chain}
        fp = warrant.cnf_key_fingerprint
        seen = set()
        while fp in chain and fp not in seen:
            seen.add(fp)
            fp = chain[fp]
        if fp == peer.key_fingerprint:
            return  # rotation authenticated; binding re-anchored

    # Unauthenticated mismatch: must NOT be retried as transient. Surface it
    # to the agent's reasoning loop as a state-continuity fault.
    raise IdentityBindingDivergence(
        "warrant cnf fingerprint does not match presented SVID and no "
        "authenticated rotation chain bridges them; treating as "
        "key-substitution or unpropagated rotation. Do NOT retry blindly."
    )
