# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-its-own-revocation-when-the-token-it-holds-is-still-cryptographically-valid.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-its-own-revocation-when-the-token-it-holds-is-still-cryptographically-valid.warrant.json
# Markdown SHA-256:   388edfe28091b3eaa8cd759eb81af7b56e08beeb2e66b89a107694aa984322ab
# Code AST SHA-256:   6e014a34be53b80a76952defafdaaf5bc9c11dfa5332c0d5508531d6f90afa88
# Verified Classes:   RevocationUndetectedError, Token, IssuerState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationUndetectedError(RuntimeError):
    """Raised when an agent cannot prove its held token is still authorized
    against the issuer's current revocation epoch."""
    pass


@dataclass
class Token:
    jti: str
    kid: str
    epoch: int
    iat: float
    exp: float
    signature_valid: bool


@dataclass
class IssuerState:
    current_epoch: int
    revoked_jtis: set
    live_kids: set


def verify_for_write(token: Token, issuer: IssuerState, now: float | None = None) -> None:
    """Verify a token for a state-changing action.

    Local signature + exp checks are necessary but NOT sufficient. The token
    must also be bound to the issuer's current revocation epoch, and its jti
    must not be revoked. A token that passes exp but fails epoch is a revoked
    warrant masquerading as a live credential.
    """
    now = time.time() if now is None else now

    if not token.signature_valid:
        # A signature failure on a token the agent believes valid is ambiguous:
        # either stale JWKS (rotation) or tampering. Resolve via kid liveness.
        if token.kid not in issuer.live_kids:
            raise RevocationUndetectedError(
                f"signing key {token.kid!r} no longer live: rotation/revocation epoch "
                f"{issuer.current_epoch}; token epoch {token.epoch}"
            )
        raise RevocationUndetectedError(
            f"signature invalid but kid {token.kid!r} live: tampering or clock skew"
        )

    if now >= token.exp:
        # Ordinary expiry: safe to refresh and retry.
        raise RevocationUndetectedError(
            f"token {token.jti!r} expired at {token.exp}; refresh via normal path"
        )

    if token.epoch < issuer.current_epoch:
        # The invisible revocation: exp is fine, signature is fine, but the
        # warrant was withdrawn in a later epoch. Do NOT retry with backoff.
        raise RevocationUndetectedError(
            f"token {token.jti!r} issued in epoch {token.epoch} < current "
            f"{issuer.current_epoch}: warrant revoked; halt and checkpoint"
        )

    if token.jti in issuer.revoked_jtis:
        raise RevocationUndetectedError(
            f"token {token.jti!r} explicitly revoked in epoch {issuer.current_epoch}"
        )


def guarded_write(token: Token, issuer: IssuerState, apply_write) -> None:
    verify_for_write(token, issuer)
    apply_write()
