# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-federation-trust-anchor-when-the-revocation-proof-is-younger-than-its-own-cache-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-federation-trust-anchor-when-the-revocation-proof-is-younger-than-its-own-cache-epoch.warrant.json
# Markdown SHA-256:   d2ab4d2a958d176ea88fe0ea1ba5969146ce94a1cf6059230339791435102d6a
# Code AST SHA-256:   6edb914a7855abfc14bff7df9a890bfb7b2614937db828839acfaf0c79a6df6b
# Verified Classes:   RevocationProofUnverifiable, AnchorBundle, RevocationProof, FederatedVerifier
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationProofUnverifiable(RuntimeError):
    """Raised when a revocation proof cannot be validated against the local anchor cache.

    This is a fail-closed condition: unverifiability MUST NOT be treated as
    'no revocation applies'.
    """


@dataclass(frozen=True)
class AnchorBundle:
    epoch: int
    issued_at: float
    not_after: float
    revocation_key_id: str


@dataclass(frozen=True)
class RevocationProof:
    subject: str
    revoked_at: float | None
    min_anchor_epoch: int
    revocation_key_id: str


class FederatedVerifier:
    def __init__(self, cached: AnchorBundle, skew: float = 15.0):
        self.cached = cached
        self.skew = skew
        self.last_fetch = time.time()

    def _is_fresh(self, now: float) -> bool:
        return now <= self.cached.not_after - self.skew

    def _refresh(self) -> None:
        # In production: synchronous fetch of the latest signed bundle.
        # Here we simulate the issuer having published epoch+1 with the revocation key.
        self.cached = AnchorBundle(
            epoch=self.cached.epoch + 1,
            issued_at=time.time(),
            not_after=time.time() + 90.0,
            revocation_key_id="rev-key-" + str(self.cached.epoch + 1),
        )
        self.last_fetch = time.time()

    def verify_revocation(self, proof: RevocationProof, now: float | None = None) -> bool:
        now = now if now is not None else time.time()

        # Guardrail 1: proof must be verifiable against the *current* anchor epoch.
        if proof.min_anchor_epoch > self.cached.epoch:
            # Cannot validate: fail closed and force refresh.
            raise RevocationProofUnverifiable(
                f"proof requires anchor epoch {proof.min_anchor_epoch} "
                f"but cache holds {self.cached.epoch}"
            )

        # Guardrail 2: local freshness is time-bound, not presenter-bound.
        if not self._is_fresh(now):
            self._refresh()
            if proof.min_anchor_epoch > self.cached.epoch:
                raise RevocationProofUnverifiable(
                    "post-refresh anchor still older than proof requirement"
                )

        # Guardrail 3: proof key must match the cached anchor's revocation key.
        if proof.revocation_key_id != self.cached.revocation_key_id:
            raise RevocationProofUnverifiable(
                "proof signed under a revocation key not in the active anchor set"
            )

        return proof.revoked_at is None


def admit_cross_org_action(verifier: FederatedVerifier, proof: RevocationProof) -> bool:
    try:
        clean = verifier.verify_revocation(proof)
    except RevocationProofUnverifiable as exc:
        # Fail closed: deny privileged action, surface for audit.
        raise RevocationProofUnverifiable(
            f"denying privileged action: {exc}"
        ) from exc
    return clean
