# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-delegated-capability-token-whose-revocation-has-not-yet-propagated.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-delegated-capability-token-whose-revocation-has-not-yet-propagated.warrant.json
# Markdown SHA-256:   4c6ed84f77c83fe66aa181517cc212b51bf27a2c217d76b8702f638d6de65a0b
# Code AST SHA-256:   82c05a2dc9e9533647ac3384514c6f4264383ea00e2dd5b192e415cb9a68988a
# Verified Classes:   StaleEpochError, RevocationViolationError, DelegatedToken, RootAttestation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleEpochError(RuntimeError):
    """Raised when a delegated token's revocation epoch cannot be proven fresh
    against the root issuer within the allowed age window."""
    pass


class RevocationViolationError(RuntimeError):
    """Raised when a fresh root epoch shows the delegated grant was revoked."""
    pass


@dataclass(frozen=True)
class DelegatedToken:
    holder: str
    scope: frozenset
    presented_root_epoch: int
    epoch_fetched_at: float
    ttl_expires_at: float


@dataclass(frozen=True)
class RootAttestation:
    root_epoch: int
    revoked_scopes_for: frozenset  # (holder, scope) pairs revoked at this epoch
    fetched_at: float
    signature_valid: bool


MAX_EPOCH_AGE_S = 15.0


def validate_delegated_token(
    token: DelegatedToken,
    root: RootAttestation,
    now: float,
    required_scope: str,
) -> None:
    if not root.signature_valid:
        raise StaleEpochError(f"root attestation for {token.holder} failed signature check")

    epoch_age = now - root.fetched_at
    if epoch_age > MAX_EPOCH_AGE_S:
        # Root unreachable or cache too old: fail closed, do not trust parent epoch.
        raise StaleEpochError(
            f"epoch age {epoch_age:.1f}s exceeds max {MAX_EPOCH_AGE_S}s for {token.holder}"
        )

    if root.root_epoch > token.presented_root_epoch:
        revoked = (token.holder, required_scope) in root.revoked_scopes_for
        if revoked:
            raise RevocationViolationError(
                f"scope {required_scope!r} for {token.holder} revoked at root epoch "
                f"{root.root_epoch} (token presented {token.presented_root_epoch})"
            )
        # Epoch advanced but this scope not revoked: token may continue, but the
        # holder must re-attest; we refuse rather than silently accept a gap.
        raise StaleEpochError(
            f"root epoch advanced to {root.root_epoch}; {token.holder} must re-attest"
        )

    if now >= token.ttl_expires_at:
        raise StaleEpochError(f"token for {token.holder} expired at {token.ttl_expires_at}")

    if required_scope not in token.scope:
        raise RevocationViolationError(
            f"scope {required_scope!r} not granted to {token.holder}"
        )
