# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-continues-signing-a2a-warrants-with-a-rotated-out-key-because-revocation-is-checked-at-handoff-not-at-signature-verifica.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-continues-signing-a2a-warrants-with-a-rotated-out-key-because-revocation-is-checked-at-handoff-not-at-signature-verifica.warrant.json
# Markdown SHA-256:   36bcbe0e7b6017cb5cf1a4f2c098c2d264b5cb5646ba3281e60b4bb8d521805f
# Code AST SHA-256:   a0d43ebc6b8210d6bd55d8f1aecfc82f517b29172975b11c60fa14c56f94261d
# Verified Classes:   WarrantRevokedError, Warrant, MeshVerifier
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class WarrantRevokedError(RuntimeError):
    """Raised when a warrant's signature is valid but its issuer has revoked the key.

    This is distinct from expiry and from unknown-key: the holder must stop
    using the warrant and re-issue, not retry.
    """


@dataclass
class Warrant:
    kid: str
    tenant: str
    nbf: float
    exp: float
    signature: bytes


class MeshVerifier:
    def __init__(self, jwks_cache_ttl: float, revocation_cache_ttl: float,
                 revocation_propagation_delay: float):
        # The invariant: revocation cache must not outlive key propagation.
        if revocation_cache_ttl > revocation_propagation_delay:
            raise WarrantRevokedError(
                "revocation_cache_ttl exceeds propagation delay; "
                "verifier would accept signatures over revoked keys"
            )
        self.jwks_cache_ttl = jwks_cache_ttl
        self.revocation_cache_ttl = revocation_cache_ttl
        self._jwks = {}          # kid -> (public_key, fetched_at)
        self._revoked = {}       # kid -> revoked_at
        self._revoked_fetched = 0.0

    def _refresh_revocation(self, now: float) -> None:
        if now - self._revoked_fetched > self.revocation_cache_ttl:
            self._revoked = self._fetch_revocation_list()
            self._revoked_fetched = now

    def _fetch_revocation_list(self) -> dict:
        # Stand-in for the issuer's revocation endpoint.
        return dict(self._revoked)

    def verify(self, w: Warrant, now: float) -> None:
        # Signature validity and revocation are evaluated together, atomically,
        # at the point of use -- never inherited from a handoff channel.
        self._refresh_revocation(now)

        if w.kid in self._revoked:
            raise WarrantRevokedError(
                f"kid={w.kid} tenant={w.tenant} revoked at "
                f"{self._revoked[w.kid]}; stop using and re-issue"
            )

        entry = self._jwks.get(w.kid)
        if entry is None:
            # Cache miss on kid must be a hard reject, not a soft retry.
            raise WarrantRevokedError(
                f"kid={w.kid} absent from JWKS; treat as revoked, re-issue"
            )

        pubkey, fetched_at = entry
        if now - fetched_at > self.jwks_cache_ttl:
            raise WarrantRevokedError(
                f"kid={w.kid} JWKS entry stale; re-fetch before use"
            )

        if not self._check_signature(w, pubkey):
            raise WarrantRevokedError(f"kid={w.kid} signature invalid")

        if not (w.nbf <= now <= w.exp):
            raise WarrantRevokedError(f"kid={w.kid} outside validity window")

    def _check_signature(self, w: Warrant, pubkey) -> bool:
        return bool(w.signature)


def handle_intra_task_rpc(verifier: MeshVerifier, w: Warrant, now: float) -> None:
    # Every RPC re-verifies; the handoff boundary is not privileged.
    verifier.verify(w, now)
