# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-but-cached-aaif-warrant-after-short-lived-credential-rotation-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-but-cached-aaif-warrant-after-short-lived-credential-rotation-mid-handoff.warrant.json
# Markdown SHA-256:   20314085059ff990d2060df4af71d478c2f4745de3533aeed9bf8a4937a68b39
# Code AST SHA-256:   217ac114013297b9c5de23d1d6c4e5a54a079cfbb05292fdb545fc9390b3abb7
# Verified Classes:   WarrantStaleError, IdentityCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class WarrantStaleError(RuntimeError):
    """Raised when a cached (JWKS, epoch) pair is too old to authorize a warrant."""


@dataclass
class IdentityCache:
    issuer: str
    jwks_epoch: int
    rev_epoch: int
    fetched_at: float


def authorize(warrant, cache: IdentityCache, issuer_feed, now: float | None = None) -> bool:
    now = now or time.time()
    age = now - cache.fetched_at
    ttl_remaining = warrant.exp - now

    # Invariant: cache may never outlive the warrant it is used to verify.
    if age > ttl_remaining:
        raise WarrantStaleError(
            f"cache age {age:.1f}s exceeds warrant ttl_remaining {ttl_remaining:.1f}s "
            f"for issuer {cache.issuer}; refusing to verify on stale keys"
        )

    # Signature miss is an integrity problem, never a latency problem.
    if not verify_sig(warrant, cache.jwks_epoch):
        raise WarrantStaleError(
            f"signature miss against JWKS@{cache.jwks_epoch}; rotation vs forgery "
            f"indistinguishable locally — authoritative re-fetch required"
        )

    # Revocation epoch must be re-read, not trusted from cache.
    if warrant.rev_epoch < issuer_feed.current_epoch(cache.issuer):
        raise WarrantStaleError(
            f"warrant epoch {warrant.rev_epoch} behind issuer epoch "
            f"{issuer_feed.current_epoch(cache.issuer)}; subject revoked"
        )
    return True
