# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-revoked-aaif-delegate-warrants-from-re-entering-a-delegation-chain-through-cached-capability-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-revoked-aaif-delegate-warrants-from-re-entering-a-delegation-chain-through-cached-capability-tokens.warrant.json
# Markdown SHA-256:   5ecaf928819fdd884b3dd729db984018fe97e362ce7db586a779a35a17601b8c
# Code AST SHA-256:   a562352b682590b6de3cfa72ddef6cdc345f13675544bc5afe5847a35a3feb0d
# Verified Classes:   RevocationShadowError, TTLContainmentError, Warrant, CapabilityToken, RevocationAuthority
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationShadowError(RuntimeError):
    """Raised when a capability token is admitted whose chain contains a
    warrant revoked before the admission time (CRI violation)."""
    pass


class TTLContainmentError(ValueError):
    """Raised at mint when a child warrant's TTL exceeds its parent's
    remaining TTL, breaking the bounded-staleness bound."""
    pass


@dataclass(frozen=True)
class Warrant:
    wid: str
    parent: str | None
    issued_at: float
    ttl: float

    @property
    def expires_at(self) -> float:
        return self.issued_at + self.ttl


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    chain: tuple[Warrant, ...]   # root .. leaf
    minted_at: float
    ttl: float


class RevocationAuthority:
    def __init__(self) -> None:
        self._revoked: dict[str, float] = {}

    def revoke(self, wid: str, at: float | None = None) -> None:
        self._revoked[wid] = at if at is not None else time.time()

    def revoked_at(self, wid: str) -> float | None:
        return self._revoked.get(wid)


def mint_token(
    chain: tuple[Warrant, ...],
    now: float,
    delta: float,
) -> CapabilityToken:
    """Mint a capability token enforcing TTL containment.

    child.ttl <= parent.remaining_ttl  and  token.ttl <= delta.
    """
    for parent, child in zip(chain, chain[1:]):
        parent_remaining = parent.expires_at - now
        if child.ttl > parent_remaining + 1e-9:
            raise TTLContainmentError(
                f"child {child.wid} ttl {child.ttl}s exceeds parent "
                f"{parent.wid} remaining {parent_remaining:.3f}s"
            )
    leaf = chain[-1]
    token_ttl = min(delta, leaf.expires_at - now)
    if token_ttl <= 0:
        raise TTLContainmentError(f"leaf {leaf.wid} already expired")
    return CapabilityToken(
        token_id=f"cap-{leaf.wid}-{now:.0f}",
        chain=chain,
        minted_at=now,
        ttl=token_ttl,
    )


def verify_token(
    token: CapabilityToken,
    authority: RevocationAuthority,
    now: float,
    delta: float,
) -> None:
    """Strict CRI verification: chain-global revocation + expiry check.

    Admits only if no ancestor was revoked at or before `now`, and the
    token's staleness bound (delta) has not been exceeded.
    """
    if now > token.minted_at + token.ttl + 1e-9:
        raise RevocationShadowError(
            f"token {token.token_id} stale: minted {token.minted_at:.0f}, "
            f"ttl {token.ttl:.0f}s, now {now:.0f}"
        )
    if now - token.minted_at > delta + 1e-9:
        raise RevocationShadowError(
            f"token {token.token_id} exceeds staleness bound delta={delta:.0f}s"
        )
    for w in token.chain:
        if now >= w.expires_at:
            raise RevocationShadowError(
                f"ancestor warrant {w.wid} expired at {w.expires_at:.0f}"
            )
        r = authority.revoked_at(w.wid)
        if r is not None and r <= now:
            raise RevocationShadowError(
                f"ancestor warrant {w.wid} revoked at {r:.0f}; "
                f"token {token.token_id} must not be admitted at {now:.0f}"
            )
