# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-attenuation-from-outliving-identity-revocation-across-federated-trust-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-attenuation-from-outliving-identity-revocation-across-federated-trust-domains.warrant.json
# Markdown SHA-256:   3917c1b09a9666cbd374dba0b1151b6545b8a7d5a6130fc5a87e7b4eb88d5e71
# Code AST SHA-256:   f99fb994e8241bf188f50539b7ddbca9e4f72a4bed2f62a4345fc614b7358ec8
# Verified Classes:   RevocationInvariantError, Warrant, FreshnessToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationInvariantError(RuntimeError):
    """Raised when a warrant would be honored past its ancestor's revocation epoch."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    root_id: str
    parent_id: str | None
    scopes: frozenset[str]
    revocation_epoch_at_issue: int
    issued_at: float
    ttl: float


@dataclass(frozen=True)
class FreshnessToken:
    root_id: str
    epoch: int
    valid_until: float
    signature: bytes  # verified elsewhere; assumed valid on entry


MUTATING_SCOPES = frozenset({"tool:fs.write", "tool:http.post", "payment.charge"})


def check_warrant_admissible(
    warrant: Warrant,
    token: FreshnessToken,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    if token.root_id != warrant.root_id:
        raise RevocationInvariantError(
            f"freshness token root {token.root_id!r} does not match warrant root "
            f"{warrant.root_id!r}; cannot bound revocation staleness"
        )

    # Invariant conjunct 1: verifier's known epoch must be >= the epoch at issue.
    # If the issuer has revoked since, token.epoch has advanced past the warrant's
    # stamp and the warrant is a post-revocation orphan.
    if token.epoch < warrant.revocation_epoch_at_issue:
        raise RevocationInvariantError(
            f"warrant {warrant.warrant_id} issued at epoch "
            f"{warrant.revocation_epoch_at_issue} but verifier holds stale epoch "
            f"{token.epoch}; ancestor may be revoked"
        )

    # Invariant conjunct 2: freshness token must still be within its validity
    # window. Expired token => we cannot assert anything about revocation state.
    if token.valid_until < now:
        # Fail-closed for mutating scopes; fail-open permitted only for reads.
        if warrant.scopes & MUTATING_SCOPES:
            raise RevocationInvariantError(
                f"freshness token for root {warrant.root_id} expired at "
                f"{token.valid_until} (now={now}); warrant {warrant.warrant_id} "
                f"carries mutating scopes {sorted(warrant.scopes & MUTATING_SCOPES)} "
                f"and must fail closed"
            )
        # Read-only scope: bounded grace permitted, but never past warrant TTL.
        if now > warrant.issued_at + warrant.ttl:
            raise RevocationInvariantError(
                f"warrant {warrant.warrant_id} past its own TTL during grace window"
            )

    # Invariant conjunct 3: warrant must not outlive the parent's freshness horizon.
    if now > warrant.issued_at + warrant.ttl:
        raise RevocationInvariantError(
            f"warrant {warrant.warrant_id} expired at "
            f"{warrant.issued_at + warrant.ttl} (now={now})"
        )

    # Invariant conjunct 4: child TTL must not exceed the freshness horizon it
    # was issued against. This is checked at issue time; re-checked here because
    # a token refresh may have shortened the effective horizon.
    remaining = token.valid_until - now
    if warrant.issued_at + warrant.ttl > token.valid_until and remaining < 0:
        raise RevocationInvariantError(
            f"warrant {warrant.warrant_id} horizon exceeds freshness token; "
            f"post-revocation orphan window is unbounded"
        )
