# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-honor-a-peer-s-capability-attestation-after-a-federation-re-key.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-honor-a-peer-s-capability-attestation-after-a-federation-re-key.warrant.json
# Markdown SHA-256:   77c485c08dd16e0475f1c85af80d72b1a84deb0b35abf9f191a1c7c13652663a
# Code AST SHA-256:   28af8e4a48a65b8b165d93c3b9276046b4f4990a473a5942f000f88b4e1b5f56
# Verified Classes:   StalePeerBindingError, PeerBinding, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StalePeerBindingError(RuntimeError):
    """Raised when a warrant's signing epoch exceeds the receiver's pinned epoch."""


@dataclass(frozen=True)
class PeerBinding:
    issuer_id: str
    fingerprint: str
    epoch: int
    advanced_at: float  # monotonic timestamp of last registrar-countersigned advance


@dataclass(frozen=True)
class Warrant:
    issuer_id: str
    subject: str
    capability: str
    audience: str
    expiry: float
    epoch: int
    signing_fingerprint: str
    signature_valid: bool


def authorize_call(
    warrant: Warrant,
    binding: Optional[PeerBinding],
    now: float,
    receiver_audience: str,
) -> bool:
    if binding is None:
        # No pinned identity: refuse and force re-federation. Never fall back to JWKS.
        raise StalePeerBindingError(
            f"no pinned binding for issuer={warrant.issuer_id}; re-federation required"
        )

    if not warrant.signature_valid:
        return False
    if warrant.audience != receiver_audience:
        return False
    if warrant.expiry <= now:
        return False

    # Identity is the pinned fingerprint, not whatever the issuer published.
    if warrant.signing_fingerprint != binding.fingerprint:
        if warrant.epoch > binding.epoch:
            raise StalePeerBindingError(
                f"issuer={warrant.issuer_id} presented epoch={warrant.epoch} "
                f"fp={warrant.signing_fingerprint} but pinned epoch={binding.epoch} "
                f"fp={binding.fingerprint}; registrar countersignature absent"
            )
        return False

    if warrant.epoch > binding.epoch:
        # Even matching fingerprint with a forward epoch is a rotation event.
        raise StalePeerBindingError(
            f"issuer={warrant.issuer_id} warrant epoch={warrant.epoch} ahead of "
            f"pinned epoch={binding.epoch}"
        )

    if warrant.epoch < binding.epoch:
        # In-flight drain: honor only if the warrant expires before the pin advanced.
        if warrant.expiry > binding.advanced_at:
            return False

    return True
