# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-attestation-whose-issuer-key-rotated-mid-handoff-the-stale-warrant-re-anchoring-failure-in-cross.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-attestation-whose-issuer-key-rotated-mid-handoff-the-stale-warrant-re-anchoring-failure-in-cross.warrant.json
# Markdown SHA-256:   25706dcfddf4d3e12446def0a0e4b2312c74318c5d3146df1a7d39fcd808ae9d
# Code AST SHA-256:   03ed101c57f85189d267540d96ae82bf9eaa35dcb9f40f989fb69e1c01ded970
# Verified Classes:   StaleAttestationError, Warrant, CachedValidation, IssuerState, FederatedAttestationVerifier
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class StaleAttestationError(RuntimeError):
    """Raised when a federated warrant is consumed on a cached validation
    whose issuer key-epoch is behind the issuer's current epoch, and the
    current revocation state cannot be confirmed."""


@dataclass
class Warrant:
    warrant_id: str
    issuer: str
    issued_at: float
    expires_at: float
    issuer_epoch: int
    scope: str
    parent: Optional["Warrant"] = None


@dataclass
class CachedValidation:
    warrant_id: str
    issuer_epoch: int
    validated_at: float
    valid: bool


@dataclass
class IssuerState:
    current_epoch: int
    # warrant_ids revoked in the current epoch
    revoked: set = field(default_factory=set)
    # max age (seconds) a revocation lookup may be cached
    max_staleness: float = 60.0


class FederatedAttestationVerifier:
    def __init__(self, revocation_fetch, clock=time.time):
        self._fetch_revocations = revocation_fetch  # (issuer, epoch) -> set[str]
        self._cache: dict[str, CachedValidation] = {}
        self._revocation_cache: dict[tuple[str, int], tuple[set, float]] = {}
        self._clock = clock

    def _current_revocations(self, issuer: str, epoch: int) -> set:
        key = (issuer, epoch)
        now = self._clock()
        hit = self._revocation_cache.get(key)
        if hit is not None:
            revoked, fetched_at = hit
            if now - fetched_at <= 60.0:
                return revoked
        try:
            revoked = self._fetch_revocations(issuer, epoch)
        except Exception as exc:
            # Fail closed: we cannot confirm revocation state.
            raise StaleAttestationError(
                f"revocation endpoint unreachable for issuer={issuer} epoch={epoch}: {exc}"
            ) from exc
        self._revocation_cache[key] = (revoked, now)
        return revoked

    def verify(self, w: Warrant, issuer_state: IssuerState, now: Optional[float] = None) -> bool:
        now = self._clock() if now is None else now
        if w.expires_at <= now:
            return False

        cached = self._cache.get(w.warrant_id)
        if cached is not None and cached.valid:
            # INVARIANT: cached validation is reusable only if the issuer
            # epoch has not advanced since the validation was recorded.
            if cached.issuer_epoch != issuer_state.current_epoch:
                # Epoch advanced: cached result is void. Must re-check
                # revocation state in the current epoch.
                revoked = self._current_revocations(w.issuer, issuer_state.current_epoch)
                if w.warrant_id in revoked:
                    self._cache[w.warrant_id] = CachedValidation(
                        w.warrant_id, issuer_state.current_epoch, now, False
                    )
                    return False
                # Also re-check every ancestor in the chain.
                ancestor = w.parent
                while ancestor is not None:
                    anc_revoked = self._current_revocations(
                        ancestor.issuer, issuer_state.current_epoch
                    )
                    if ancestor.warrant_id in anc_revoked:
                        self._cache[w.warrant_id] = CachedValidation(
                            w.warrant_id, issuer_state.current_epoch, now, False
                        )
                        return False
                    ancestor = ancestor.parent
                self._cache[w.warrant_id] = CachedValidation(
                    w.warrant_id, issuer_state.current_epoch, now, True
                )
                return True
            # Same epoch: cached result is still usable within exp.
            return True

        # No cached validation: perform full check.
        revoked = self._current_revocations(w.issuer, issuer_state.current_epoch)
        if w.warrant_id in revoked:
            self._cache[w.warrant_id] = CachedValidation(
                w.warrant_id, issuer_state.current_epoch, now, False
            )
            return False
        self._cache[w.warrant_id] = CachedValidation(
            w.warrant_id, issuer_state.current_epoch, now, True
        )
        return True

    def consume(self, w: Warrant, issuer_state: IssuerState) -> None:
        if not self.verify(w, issuer_state):
            raise StaleAttestationError(
                f"warrant {w.warrant_id} from {w.issuer} rejected: "
                f"stale epoch or revoked in current epoch "
                f"(current_epoch={issuer_state.current_epoch})"
            )
