# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-attestation-replay-from-silently-widening-a-federated-agent-s-trust-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-attestation-replay-from-silently-widening-a-federated-agent-s-trust-envelope.warrant.json
# Markdown SHA-256:   040e1ccd077a33d89266fc8ff61e3f7e2ef4dc9a6b4a2251fbb574bd982576dc
# Code AST SHA-256:   ad3b8291a930380a25743f5429e06a680c095ea806307a9348dd76d77799d4ab
# Verified Classes:   AttestationReplayError, Attestation, BrokerCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttestationReplayError(RuntimeError):
    """Raised when an attestation is served or admitted outside its full binding tuple."""
    pass


@dataclass(frozen=True)
class Attestation:
    issuer: str
    subject: str
    audience: str
    resource_scope: str
    nonce: str
    expires_at: float


def binding_tuple(att: Attestation) -> tuple:
    # The invariant: identity is the FULL tuple, never a projection.
    return (att.issuer, att.subject, att.audience, att.resource_scope, att.nonce)


class BrokerCache:
    def __init__(self) -> None:
        self._store: dict = {}

    def put(self, att: Attestation) -> None:
        self._store[binding_tuple(att)] = att

    def resolve(self, presented: Attestation, target_audience: str, now: float) -> Attestation:
        # Reject any request whose audience does not match the target hop.
        if presented.audience != target_audience:
            raise AttestationReplayError(
                f"audience mismatch: warrant audience={presented.audience!r} "
                f"addressed to {target_audience!r}; refusing cross-audience reuse"
            )
        # Reject expired attestations before any cache interaction.
        if presented.expires_at <= now:
            raise AttestationReplayError(
                f"expired attestation nonce={presented.nonce!r} expires_at={presented.expires_at}"
            )
        key = binding_tuple(presented)
        cached = self._store.get(key)
        if cached is None:
            # A miss on the full tuple is a REJECTION, not a re-fetch:
            # re-fetching would launder a mismatched request into a fresh warrant.
            raise AttestationReplayError(
                f"no attestation matching full binding tuple {key!r}; "
                "partial-tuple cache hit is not admissible"
            )
        return cached


def admit(cache: BrokerCache, presented: Attestation, target_audience: str,
          requested_scope: str, now: float) -> Attestation:
    att = cache.resolve(presented, target_audience, now)
    # Closed-world scope: exact match, absent field is no scope, never wildcard.
    if not att.resource_scope or att.resource_scope != requested_scope:
        raise AttestationReplayError(
            f"scope violation: warrant scope={att.resource_scope!r} "
            f"cannot satisfy requested={requested_scope!r}"
        )
    return att
