# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-attestation-replay-from-surviving-an-x-509-trust-anchor-rotation-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-attestation-replay-from-surviving-an-x-509-trust-anchor-rotation-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   40b5219b1962411a386174135d1676d56af1a321dd54033f724863db1135e80f
# Code AST SHA-256:   2c680fbd239cf8b9779ba56aeff41152a1956921588ddb76bae11f4f269637b0
# Verified Classes:   AttestationReplayError, Attestation, CachedResult, EpochBoundAttestationCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AttestationReplayError(RuntimeError):
    """Raised when a cached attestation result is honored across an anchor-epoch
    transition or against a stale revocation view. This is the exact condition
    that let a revoked-root attestation replay survive A-root-1 -> A-root-2."""


@dataclass(frozen=True)
class Attestation:
    leaf_key: str
    asserted_epoch: int          # anchor epoch the presenter signed against
    chain_hash: str


@dataclass
class CachedResult:
    valid: bool
    epoch: int
    revocation_epoch: int
    cached_at: float


class EpochBoundAttestationCache:
    def __init__(self, max_revocation_age_s: float = 60.0):
        self._cache: dict[tuple[str, int, int], CachedResult] = {}
        self._max_revocation_age = max_revocation_age_s
        self.current_epoch: int = 0
        self.revocation_epoch: int = 0

    def _key(self, att: Attestation) -> tuple[str, int, int]:
        # Epoch-bound key: a replay of an old chain produces a key whose
        # asserted_epoch no longer matches current_epoch -> forced revalidation.
        return (att.leaf_key, att.asserted_epoch, self.revocation_epoch)

    def lookup(self, att: Attestation, now: float | None = None) -> bool:
        now = time.monotonic() if now is None else now
        entry = self._cache.get(self._key(att))

        if entry is None:
            return False  # miss -> caller must revalidate

        # Invariant 1: epoch binding. A cached result for an older epoch
        # MUST NOT satisfy a presentation after the anchor set advanced.
        if entry.epoch < self.current_epoch:
            raise AttestationReplayError(
                f"cached attestation for {att.leaf_key} at epoch {entry.epoch} "
                f"presented after anchor advanced to {self.current_epoch}; "
                f"replay of revoked-root chain {att.chain_hash}"
            )

        # Invariant 2: revocation freshness bound. Presence of a positive
        # cache entry is not validity; the revocation view must be fresh.
        if now - entry.cached_at > self._max_revocation_age:
            raise AttestationReplayError(
                f"revocation view stale by {now - entry.cached_at:.1f}s "
                f"(max {self._max_revocation_age}s) for {att.leaf_key}; "
                f"fail-closed on capability-bearing attestation"
            )

        return entry.valid

    def store(self, att: Attestation, valid: bool, now: float | None = None) -> None:
        now = time.monotonic() if now is None else now
        self._cache[self._key(att)] = CachedResult(
            valid=valid,
            epoch=self.current_epoch,
            revocation_epoch=self.revocation_epoch,
            cached_at=now,
        )

    def advance_anchor(self, new_epoch: int) -> None:
        # Invariant 3: monotonic epoch, anti-rollback of the trust anchor itself.
        if new_epoch <= self.current_epoch:
            raise AttestationReplayError(
                f"anchor epoch rollback rejected: {new_epoch} <= {self.current_epoch}; "
                f"possible replay of stale federation metadata document"
            )
        self.current_epoch = new_epoch
