# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bind-a-federated-peer-s-policy-negotiation-state-to-its-mtls-leaf-identity-when-the-peer-rotates-certificates-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bind-a-federated-peer-s-policy-negotiation-state-to-its-mtls-leaf-identity-when-the-peer-rotates-certificates-mid-handshake.warrant.json
# Markdown SHA-256:   fe14bb083f12f6f9d21ffbf9742ce083446c4fb972e92c5a0c61592f0d8b6572
# Code AST SHA-256:   650f6bc1a8ff6142510a042cd3e6c96cd0c74b6191646f9fe9c8d82fa9f7cfe6
# Verified Classes:   FederationBindingError, PolicyGrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class FederationBindingError(RuntimeError):
    """Raised when a cached PolicyGrant is not cryptographically bound to the
    live peer leaf identity, or when that leaf no longer chains to a pinned
    trust anchor. Fail closed: never authorize on a stale or unvalidated binding."""


@dataclass(frozen=True)
class PolicyGrant:
    grant_id: str
    scopes: tuple
    max_delegation_depth: int
    expires_at: float
    bound_leaf_fingerprint: str  # SHA-256 of peer leaf DER, set at negotiation time


def leaf_fingerprint(peer_leaf_der: bytes) -> str:
    return hashlib.sha256(peer_leaf_der).hexdigest()


def authorize(
    grant: PolicyGrant,
    live_peer_leaf_der: bytes,
    chain_valid_against_pinned_anchors: bool,
    now: float,
) -> tuple:
    """Re-validate grant-to-leaf binding at every authorization decision.

    This must be called on the live TLS session's peer certificate, NOT on a
    cached identity from handshake time, and NOT keyed by connection/session id.
    """
    if now >= grant.expires_at:
        raise FederationBindingError(
            f"grant {grant.grant_id} expired at {grant.expires_at}; "
            "session resumption does not extend grant lifetime"
        )

    live_fp = leaf_fingerprint(live_peer_leaf_der)

    if live_fp != grant.bound_leaf_fingerprint:
        # Peer re-authenticated as a different identity (e.g. cert rotation).
        # Do not rebind in place: the new identity may warrant different scopes.
        raise FederationBindingError(
            f"grant {grant.grant_id} bound to leaf {grant.bound_leaf_fingerprint[:16]} "
            f"but live peer leaf is {live_fp[:16]}; force renegotiation"
        )

    if not chain_valid_against_pinned_anchors:
        # Same leaf, but its chain no longer validates (anchor/intermediate
        # rotation, or resumption bypassed chain validation). Fail closed.
        raise FederationBindingError(
            f"grant {grant.grant_id} leaf {live_fp[:16]} does not chain to a "
            "currently-pinned trust anchor; revoke and re-handshake"
        )

    return grant.scopes
