# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-trust-anchor-during-cross-org-agent-federation-when-spiffe-svid-rotation-outpaces-warrant-re-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-trust-anchor-during-cross-org-agent-federation-when-spiffe-svid-rotation-outpaces-warrant-re-issuance.warrant.json
# Markdown SHA-256:   b5fdd19ad1679d78d675d3e0b6bc67dc20d4f0d5b3276a26ca1d3ca18bf1a509
# Code AST SHA-256:   a13c905d4e859b99af498a64ed161eb1d26185852a29d072770f65f3ed29e089
# Verified Classes:   BindingDiscontinuity, SVID, Warrant
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class BindingDiscontinuity(RuntimeError):
    """Raised when a warrant's identity binding no longer resolves to a live SVID."""
    pass


@dataclass
class SVID:
    spiffe_id: str
    public_key: bytes
    epoch: int
    revoked: bool = False

    @property
    def thumbprint(self) -> str:
        return hashlib.sha256(self.public_key).hexdigest()


@dataclass
class Warrant:
    subject_spiffe_id: str
    bound_thumbprint: Optional[str]   # None => binds to SPIFFE ID only
    bound_epoch: Optional[int]        # rotation epoch at issuance
    expiry: float
    signature_valid: bool = True


def verify_federated_call(
    warrant: Warrant,
    presented_svid: SVID,
    now: float,
    revocation_events: list[tuple[str, int]],  # (thumbprint, epoch_revoked)
) -> None:
    # Independent validity checks — all of these pass in the failure case.
    if not warrant.signature_valid:
        raise BindingDiscontinuity("warrant signature invalid")
    if now >= warrant.expiry:
        raise BindingDiscontinuity("warrant expired")
    if presented_svid.revoked:
        raise BindingDiscontinuity("presented SVID revoked")

    if warrant.subject_spiffe_id != presented_svid.spiffe_id:
        raise BindingDiscontinuity(
            f"subject mismatch: warrant={warrant.subject_spiffe_id} "
            f"svid={presented_svid.spiffe_id}"
        )

    # Case 1: key-thumbprint binding (the failure-prone mode).
    if warrant.bound_thumbprint is not None:
        if warrant.bound_thumbprint != presented_svid.thumbprint:
            # This is NOT transient. The warrant names a key the caller no longer holds.
            raise BindingDiscontinuity(
                f"svid thumbprint rotated out from under warrant: "
                f"warrant_bound={warrant.bound_thumbprint} "
                f"presented={presented_svid.thumbprint} "
                f"-> re-issue warrant, do not retry"
            )
        # Even on match, confirm the bound key was never revoked mid-lifetime.
        for thumb, rev_epoch in revocation_events:
            if thumb == warrant.bound_thumbprint and rev_epoch <= presented_svid.epoch:
                raise BindingDiscontinuity(
                    f"bound key {thumb} revoked at epoch {rev_epoch}; "
                    f"warrant is stale"
                )
        return

    # Case 2: SPIFFE-ID + epoch binding (rotation-transparent).
    if warrant.bound_epoch is None:
        raise BindingDiscontinuity("warrant has neither thumbprint nor epoch binding")
    if presented_svid.epoch < warrant.bound_epoch:
        raise BindingDiscontinuity(
            f"presented SVID epoch {presented_svid.epoch} predates warrant epoch "
            f"{warrant.bound_epoch}"
        )
    for thumb, rev_epoch in revocation_events:
        if warrant.bound_epoch <= rev_epoch <= presented_svid.epoch:
            raise BindingDiscontinuity(
                f"revocation event at epoch {rev_epoch} falls inside warrant lifetime"
            )
