# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scoped-token-revocation-from-leaking-across-federated-agent-trust-anchors.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scoped-token-revocation-from-leaking-across-federated-agent-trust-anchors.warrant.json
# Markdown SHA-256:   fa8d67945338e090e67ce4ca00ee0436ca02a7d714ea578c7b91ebfadfcac3d8
# Code AST SHA-256:   09e45ac15d0c684cbf9be74d4cf150323f4c06a3c722d7f657fd3d77e9f4a7b4
# Verified Classes:   RevocationLeakError, Anchor, ScopedToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class RevocationLeakError(RuntimeError):
    """Raised when a derived capability token survives its root anchor's revocation."""
    pass


@dataclass
class Anchor:
    pubkey: bytes
    epoch: int
    revoked_epochs: set = field(default_factory=set)

    def hash(self) -> bytes:
        return hashlib.sha256(self.pubkey + self.epoch.to_bytes(8, "big")).digest()

    def is_revoked(self, epoch: int) -> bool:
        return epoch in self.revoked_epochs


@dataclass
class ScopedToken:
    subject: str
    scope: frozenset
    anchor_hash: bytes          # commitment to root anchor, NOT issuer identity
    parent_hash: Optional[bytes]
    epoch: int
    not_after: float
    reason: str = "scope_narrow"  # or "compromise"


def validate_chain(token: ScopedToken, anchor: Anchor, now: float,
                   max_cache_age: float, last_poll: float) -> None:
    # 1. Anchor-binding: token must commit to a currently-valid anchor epoch.
    if token.anchor_hash != anchor.hash():
        raise RevocationLeakError(
            f"token anchor_hash {token.anchor_hash.hex()[:8]} does not bind "
            f"to live anchor epoch {anchor.epoch}"
        )

    # 2. Monotonic epoch: effective epoch is the max along the chain.
    effective_epoch = max(token.epoch, anchor.epoch)

    # 3. Typed revocation: compromise-revocation is total and transitive.
    if anchor.is_revoked(effective_epoch):
        raise RevocationLeakError(
            f"anchor epoch {effective_epoch} revoked; descendant token for "
            f"{token.subject} must not execute (reason=compromise)"
        )

    # 4. Staleness bound: cache age must not exceed the denylist poll interval.
    if (now - last_poll) > max_cache_age:
        raise RevocationLeakError(
            f"revocation state stale: {(now - last_poll):.1f}s since poll, "
            f"bound is {max_cache_age:.1f}s"
        )

    # 5. Lifetime bound.
    if now > token.not_after:
        raise RevocationLeakError(f"token expired at {token.not_after:.0f}")


def execute_capability(token: ScopedToken, anchor: Anchor,
                       action: str, now: float) -> str:
    validate_chain(token, anchor, now, max_cache_age=300.0, last_poll=now - 120.0)
    if action not in token.scope:
        raise RevocationLeakError(f"action {action} outside scope {token.scope}")
    return f"executed {action} for {token.subject} under anchor epoch {anchor.epoch}"


if __name__ == "__main__":
    anchor = Anchor(pubkey=b"root-org-A", epoch=41)
    child = ScopedToken(
        subject="org-C", scope=frozenset({"payments:read"}),
        anchor_hash=anchor.hash(), parent_hash=b"T_A-hash",
        epoch=41, not_after=time.time() + 1800,
    )
    # Simulate compromise revocation of the root anchor.
    anchor.revoked_epochs.add(41)
    try:
        execute_capability(child, anchor, "payments:read", now=time.time())
    except RevocationLeakError as e:
        print(f"blocked: {e}")
