# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-attestation-replay-across-federated-trust-boundaries-when-warrant-caches-outlive-their-issuing-org-s-revocation-ep.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-attestation-replay-across-federated-trust-boundaries-when-warrant-caches-outlive-their-issuing-org-s-revocation-ep.warrant.json
# Markdown SHA-256:   cdd35ab7188d6cf136967673593e03f0e7173794cbf6fb08680c78dbfe8160d1
# Code AST SHA-256:   ca06f27f5bb34cbc431a3162930480e866606e647db804dbd13b6ee8711f3c58
# Verified Classes:   RevocationEpochDesync, Verdict, AttestationCache, FederationGateway
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Tuple
import time


class RevocationEpochDesync(RuntimeError):
    """Raised when a cached attestation verdict is presented against a peer
    whose revocation epoch has advanced past the epoch the verdict was minted under."""
    pass


@dataclass
class Verdict:
    peer: str
    issuer: str
    scope: str
    epoch: int
    minted_at: float
    ttl: float

    def is_expired(self, now: float) -> bool:
        return (now - self.minted_at) > self.ttl


class AttestationCache:
    """Cache keyed on (peer, issuer, scope, epoch). Epoch in the key is the invariant."""

    def __init__(self) -> None:
        self._store: Dict[Tuple[str, str, str, int], Verdict] = {}

    def put(self, v: Verdict) -> None:
        self._store[(v.peer, v.issuer, v.scope, v.epoch)] = v

    def get(self, peer: str, issuer: str, scope: str, epoch: int) -> Verdict:
        return self._store[(peer, issuer, scope, epoch)]


class FederationGateway:
    def __init__(self) -> None:
        self.cache = AttestationCache()
        self._last_seen_epoch: Dict[str, int] = {}

    def observe_epoch(self, issuer: str, epoch: int) -> None:
        # Epoch must be monotonic and locally sourced; never accept a caller-forwarded epoch.
        prev = self._last_seen_epoch.get(issuer, -1)
        if epoch < prev:
            raise RevocationEpochDesync(
                f"epoch regression for {issuer}: saw {epoch} < last {prev}; refusing to pin backward"
            )
        self._last_seen_epoch[issuer] = epoch

    def authorize(
        self,
        peer: str,
        issuer: str,
        scope: str,
        presented_epoch: int,
        current_issuer_epoch: int,
        forwarded_verdict_header: bool,
        now: float,
    ) -> bool:
        # Callee is sole authority on its own epoch. A forwarded cached verdict is advisory only.
        self.observe_epoch(issuer, current_issuer_epoch)

        if presented_epoch != current_issuer_epoch:
            raise RevocationEpochDesync(
                f"verdict epoch {presented_epoch} != issuer epoch {current_issuer_epoch} "
                f"for ({peer},{scope}); cached verdict is stale and must not authorize"
            )

        if forwarded_verdict_header:
            # We re-verify regardless; the header cannot substitute for the epoch check.
            pass

        try:
            v = self.cache.get(peer, issuer, scope, current_issuer_epoch)
        except KeyError:
            return False
        if v.is_expired(now):
            return False
        return True
