# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-still-hold-authority-after-capability-revocation-across-a-federated-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-still-hold-authority-after-capability-revocation-across-a-federated-trust-boundary.warrant.json
# Markdown SHA-256:   faa562ac3d0afb854cbb255b0e885412a695766cf9d84ba0d5d29fc6fa66fc8d
# Code AST SHA-256:   50d64d7fe3c782d855ef2ca04bbd7d967b0773db48219947588704e6035e5829
# Verified Classes:   RevocationPropagationError, CapabilityToken, DecisionCacheEntry, FederatedAuthorizer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class RevocationPropagationError(RuntimeError):
    """Raised when an authorization decision would be served past the staleness contract."""
    pass


@dataclass
class CapabilityToken:
    subject: str
    caps: frozenset
    issued_at: float
    expires_at: float
    signature: bytes

    def token_hash(self) -> str:
        return hashlib.sha256(self.signature + self.subject.encode()).hexdigest()


@dataclass
class DecisionCacheEntry:
    subject: str
    caps: frozenset
    confirmed_standing_at: float
    token_exp: float = field(default=0.0)


class FederatedAuthorizer:
    def __init__(self, staleness_contract_s: float, now=time.monotonic):
        self.staleness_contract_s = staleness_contract_s
        self._cache: dict[str, DecisionCacheEntry] = {}  # keyed on SUBJECT, never token hash
        self._now = now

    def _revocation_known_recently(self, subject: str) -> bool:
        entry = self._cache.get(subject)
        if entry is None:
            return False
        return (self._now() - entry.confirmed_standing_at) <= self.staleness_contract_s

    def authorize(self, token: CapabilityToken, required: frozenset) -> bool:
        if self._now() >= token.expires_at:
            # Expired token: never authorize, regardless of cache.
            raise RevocationPropagationError(
                f"token for {token.subject} expired at {token.expires_at}; "
                "presented after expiry"
            )

        if not self._revocation_known_recently(token.subject):
            # Cache miss or stale standing: must re-confirm with the issuing domain.
            # In production this calls alpha's revocation/status endpoint.
            confirmed = self._reconfirm_standing(token.subject)
            if not confirmed:
                raise RevocationPropagationError(
                    f"subject {token.subject} revoked by issuing domain; "
                    f"authority refused (token hash {token.token_hash()[:12]})"
                )
            self._cache[token.subject] = DecisionCacheEntry(
                subject=token.subject,
                caps=token.caps,
                confirmed_standing_at=self._now(),
                token_exp=token.expires_at,
            )

        entry = self._cache[token.subject]
        if not required.issubset(entry.caps):
            raise RevocationPropagationError(
                f"subject {token.subject} lacks required caps {required - entry.caps}"
            )
        return True

    def _reconfirm_standing(self, subject: str) -> bool:
        # Placeholder: query the issuing domain's revocation set.
        # Returns False if the subject is revoked.
        return True
