# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mtls-bound-token-exchange-from-silently-degrading-federation-trust-when-an-agent-s-certificate-rotates-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mtls-bound-token-exchange-from-silently-degrading-federation-trust-when-an-agent-s-certificate-rotates-mid-handoff.warrant.json
# Markdown SHA-256:   789ae2d40238f77c557b01ac62ab164c71a29b48904e217987283baed5507ad6
# Code AST SHA-256:   cda5c82b52f0ca865d60af6a42d5d652075bab65dae5d343eb1246885a85ebc4
# Verified Classes:   FederationBindingError, SessionCert, ExchangedToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class FederationBindingError(RuntimeError):
    """Raised when mTLS session cert and token cnf claim disagree."""
    pass


@dataclass
class SessionCert:
    der: bytes
    issuer_org: str

    def thumbprint_s256(self) -> str:
        return hashlib.sha256(self.der).hexdigest()


@dataclass
class ExchangedToken:
    cnf_x5t_s256: str
    issuer_org: str
    active: bool


def verify_federated_handoff(
    session_cert: SessionCert,
    token: ExchangedToken,
    trusted_orgs: set[str],
) -> None:
    # 1. Token must be active per introspection.
    if not token.active:
        raise FederationBindingError("token inactive per introspection")

    # 2. Issuing org must be a trusted federation peer.
    if token.issuer_org not in trusted_orgs:
        raise FederationBindingError(
            f"issuer org {token.issuer_org!r} not in trusted federation set"
        )

    # 3. Trust-anchor scoping: the session cert must come from the SAME org
    #    that issued the token. A cert from org Y cannot authenticate a
    #    token minted by org X, even if both are federated.
    if session_cert.issuer_org != token.issuer_org:
        raise FederationBindingError(
            f"session cert org {session_cert.issuer_org!r} != "
            f"token issuer org {token.issuer_org!r}"
        )

    # 4. The binding invariant: recompute the live thumbprint and compare
    #    byte-for-byte to the token's confirmation claim. This is the check
    #    that catches mid-handoff certificate rotation.
    live_thumbprint = session_cert.thumbprint_s256()
    if live_thumbprint != token.cnf_x5t_s256:
        raise FederationBindingError(
            "cnf.x5t#S256 mismatch: token bound to "
            f"{token.cnf_x5t_s256!r} but session presents {live_thumbprint!r} "
            "(likely cert rotated after token issuance)"
        )
