# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-but-cached-capability-warrant-against-a-mid-session-key-rotation-without-halting-in-flight-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-but-cached-capability-warrant-against-a-mid-session-key-rotation-without-halting-in-flight-tool-calls.warrant.json
# Markdown SHA-256:   1ece8dedd72a8e2a1567fbdbb9772697de0524fe0ab7459ff2bc0656b0ebc70c
# Code AST SHA-256:   fe5668aecbe7e22706d379fc1df16dfd6e61d12f4ff6c53ddd8949e816889c82
# Verified Classes:   RevocationStalenessError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationStalenessError(RuntimeError):
    """Raised when a tool call proceeds on a revocation view too old to be sound."""


@dataclass
class Warrant:
    warrant_id: str
    signing_key_id: str
    issued_at: float
    expires_at: float
    revocation_checked_at: float


# Maximum tolerable staleness of the revocation view. Must be strictly
# less than the session TTL, or a revoked warrant can outlive its revocation.
MAX_REVOCATION_STALENESS_S = 30.0


def authorize_tool_call(
    warrant: Warrant,
    now: float,
    trusted_key_ids: frozenset[str],
    revoked_ids: frozenset[str],
    overlap_key_ids: frozenset[str],
) -> None:
    # (a) signature trust: old key may still be trusted during overlap
    if warrant.signing_key_id not in trusted_key_ids:
        raise RevocationStalenessError(
            f"warrant {warrant.warrant_id} signed by untrusted key "
            f"{warrant.signing_key_id}; key removed from trust bundle"
        )

    # rotation is NOT revocation: overlap keys keep signature validity
    # but must never be read as authorization.

    # (b) revocation freshness: independent predicate, independently bounded
    staleness = now - warrant.revocation_checked_at
    if staleness > MAX_REVOCATION_STALENESS_S:
        # fail closed on the next call; do not silently extend
        raise RevocationStalenessError(
            f"revocation view for {warrant.warrant_id} is {staleness:.1f}s stale "
            f"(bound {MAX_REVOCATION_STALENESS_S}s); refresh before proceeding"
        )

    if warrant.warrant_id in revoked_ids:
        raise RevocationStalenessError(
            f"warrant {warrant.warrant_id} is revoked; tool call denied"
        )

    if now >= warrant.expires_at:
        raise RevocationStalenessError(
            f"warrant {warrant.warrant_id} expired at {warrant.expires_at}"
        )

    # Both predicates cleared: signature trusted AND revocation fresh AND clear.
