# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-delegated-aaif-credential-from-surviving-attenuation-scoped-subject-drift-across-a-revocation-epoch-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-delegated-aaif-credential-from-surviving-attenuation-scoped-subject-drift-across-a-revocation-epoch-boundary.warrant.json
# Markdown SHA-256:   aade5ee9205c178411eff0e86cf87ddbff94b8c2f00cf7423b681b605bca97e8
# Code AST SHA-256:   595c7612883988721d7ca8dfe19df9386215a87278ab48f0f61042ac591e9ed5
# Verified Classes:   DelegationEpochDriftError, RevocationSnapshot, DelegatedToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationEpochDriftError(RuntimeError):
    """Raised when a delegated token's subject closure outlives the revocation epoch it was minted in."""


@dataclass(frozen=True)
class RevocationSnapshot:
    epoch: int
    revoked: FrozenSet[str]


@dataclass(frozen=True)
class DelegatedToken:
    subject: str
    may_act_for: FrozenSet[str]
    scope: str
    iat_epoch: int
    exp_epoch: int


def verify_delegated_token(
    token: DelegatedToken,
    snapshot: RevocationSnapshot,
    requested_scope: str,
) -> None:
    # 1. Scope coverage
    if requested_scope not in token.scope and not token.scope.endswith("*"):
        raise DelegationEpochDriftError(
            f"scope {requested_scope!r} not covered by token scope {token.scope!r}"
        )

    # 2. Cryptographic subject revocation
    if token.subject in snapshot.revoked:
        raise DelegationEpochDriftError(
            f"subject {token.subject!r} revoked at epoch {snapshot.epoch}"
        )

    # 3. Binding closure: may_act_for is a first-class subject, not advisory
    stale_principals = token.may_act_for & snapshot.revoked
    if stale_principals:
        raise DelegationEpochDriftError(
            f"may_act_for closure {sorted(stale_principals)} revoked at epoch "
            f"{snapshot.epoch}; token minted at epoch {token.iat_epoch}"
        )

    # 4. Strict-epoch invariant for delegation scopes
    if requested_scope.startswith("delegate:"):
        if snapshot.epoch <= token.iat_epoch:
            raise DelegationEpochDriftError(
                f"delegate scope requires snapshot.epoch > token.iat_epoch "
                f"({snapshot.epoch} <= {token.iat_epoch}); refresh revocation feed"
            )

    # 5. Epoch atomicity: token must not predate the snapshot's coverage window
    if token.iat_epoch > snapshot.epoch:
        raise DelegationEpochDriftError(
            f"token iat_epoch {token.iat_epoch} is ahead of snapshot epoch "
            f"{snapshot.epoch}; clock or feed skew"
        )
