# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-keep-trusting-a-revoked-peer-after-credential-rotation-propagates-the-stale-verifier-window-in-aaif-trust-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-keep-trusting-a-revoked-peer-after-credential-rotation-propagates-the-stale-verifier-window-in-aaif-trust-domains.warrant.json
# Markdown SHA-256:   cc59093a75ddab164fa3463873fd18ab2eec06b908a1ebc19643929490ab4fa2
# Code AST SHA-256:   1d4a75e137f03d99fde020e36b94092a64db90628adf8e9f1eced202b0a895fb
# Verified Classes:   StaleVerifierWindowError, TrustEntry, RevocationState
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleVerifierWindowError(RuntimeError):
    """Raised when a verifier would accept a credential whose trust-chain
    epoch predates the most recent rotation affecting that chain, while the
    revocation list has not been consulted (cache-hit short-circuit)."""


@dataclass
class TrustEntry:
    kid: str
    bundle_epoch: int          # epoch at which this entry was cached
    ttl_seconds: int
    filled_at: float


@dataclass
class RevocationState:
    epoch: int                 # epoch of the RL this verifier last saw
    revoked_kids: frozenset


def verify_handoff(
    kid: str,
    required_epoch: int,        # min bundle epoch required for this chain
    revocation_sla_seconds: int,
    now: float,
    cache: dict[str, TrustEntry],
    rl: Optional[RevocationState],
    cache_ttl_seconds: int,
) -> bool:
    entry = cache.get(kid)

    # Cache hit path: the dangerous short-circuit.
    if entry is not None and (now - entry.filled_at) < entry.ttl_seconds:
        # Invariant 1: epoch gate. A stale entry must not satisfy a newer
        # required_epoch even though its signature is cryptographically valid.
        if entry.bundle_epoch < required_epoch:
            raise StaleVerifierWindowError(
                f"cache hit for kid={kid} at bundle_epoch={entry.bundle_epoch} "
                f"< required_epoch={required_epoch}; superseded key not evicted"
            )
        # Invariant 3: cannot skip RL check unless epoch gate proves freshness.
        if rl is None or rl.epoch < required_epoch:
            raise StaleVerifierWindowError(
                f"kid={kid} accepted on cache hit but revocation state epoch="
                f"{None if rl is None else rl.epoch} < required_epoch={required_epoch}"
            )
        if kid in rl.revoked_kids:
            raise StaleVerifierWindowError(
                f"kid={kid} is revoked in RL epoch={rl.epoch} but was served "
                f"from cache filled at epoch={entry.bundle_epoch}"
            )
        return True

    # Cache miss: must consult RL and respect cache_ttl <= revocation_sla.
    if cache_ttl_seconds > revocation_sla_seconds:
        raise StaleVerifierWindowError(
            f"config invalid: cache_ttl={cache_ttl_seconds}s exceeds "
            f"revocation_sla={revocation_sla_seconds}s; window is unbounded"
        )
    if rl is None:
        raise StaleVerifierWindowError(f"no revocation state for kid={kid}")
    if kid in rl.revoked_kids:
        raise StaleVerifierWindowError(f"kid={kid} revoked at RL epoch={rl.epoch}")
    return True
