# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-fence-a-revoked-peer-credential-across-a-trust-domain-boundary-before-accepting-a-delegated-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-fence-a-revoked-peer-credential-across-a-trust-domain-boundary-before-accepting-a-delegated-warrant.warrant.json
# Markdown SHA-256:   68da78d28aa692396bd108bacfdc03e91289d817b60165b809da6d9f492d3d5c
# Code AST SHA-256:   7fb71a790ff0f6ca9184dd811fc8df663862f9f1325cb6cb179d8cb98b98a8b0
# Verified Classes:   StaleCredentialFenced, Warrant, FreshnessProof, RevocationFencer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleCredentialFenced(RuntimeError):
    """Raised when a signature-valid warrant cannot be bound to a fresh revocation epoch."""
    pass


@dataclass
class Warrant:
    issuer_domain: str
    subject_id: str
    warrant_id: str
    issuer_epoch: int
    expires_at: float


@dataclass
class FreshnessProof:
    issuer_domain: str
    issuer_epoch: int
    this_update: float


class RevocationFencer:
    def __init__(self, max_staleness: float):
        self.max_staleness = max_staleness
        # Durable high-water mark per issuer; must survive restarts.
        self._epoch_floor: dict[str, int] = {}
        self._last_proof: dict[str, FreshnessProof] = {}

    def observe_proof(self, proof: FreshnessProof) -> None:
        floor = self._epoch_floor.get(proof.issuer_domain, -1)
        if proof.issuer_epoch < floor:
            # Rollback attempt: refuse to lower the floor.
            raise StaleCredentialFenced(
                f"rollback proof for {proof.issuer_domain}: "
                f"epoch {proof.issuer_epoch} < floor {floor}"
            )
        self._epoch_floor[proof.issuer_domain] = proof.issuer_epoch
        self._last_proof[proof.issuer_domain] = proof

    def authorize(self, warrant: Warrant, now: float, privileged: bool) -> bool:
        floor = self._epoch_floor.get(warrant.issuer_domain, -1)
        if floor < 0:
            if privileged:
                raise StaleCredentialFenced(
                    f"no observed epoch for {warrant.issuer_domain}; "
                    f"cannot authorize privileged warrant {warrant.warrant_id}"
                )
            return True  # read-only fail-open is permitted
        if floor < warrant.issuer_epoch:
            if privileged:
                raise StaleCredentialFenced(
                    f"verifier epoch {floor} behind warrant epoch "
                    f"{warrant.issuer_epoch} for {warrant.warrant_id}"
                )
            return True
        proof = self._last_proof.get(warrant.issuer_domain)
        if proof is None or (now - proof.this_update) > self.max_staleness:
            if privileged:
                raise StaleCredentialFenced(
                    f"freshness proof stale for {warrant.issuer_domain}; "
                    f"warrant {warrant.warrant_id} fenced"
                )
            return True
        if now > warrant.expires_at:
            return False
        return True
