# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-peer-s-federated-identity-mid-key-rotation-and-replays-a-stale-warrant-across-an-aaif-oidc-bridge.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-peer-s-federated-identity-mid-key-rotation-and-replays-a-stale-warrant-across-an-aaif-oidc-bridge.warrant.json
# Markdown SHA-256:   00dc146b3f2dadb3d3bbb2da67376043b42fa0551375736cad822a9a7c35b5e6
# Code AST SHA-256:   b3c9cb71f0d4a00ca941ecc29b5cc117ae0af4861b0dd113b45a5fbcf48fa31d
# Verified Classes:   StaleIdentityEpochError, Warrant, Resolver
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Optional


class StaleIdentityEpochError(RuntimeError):
    """Raised when a warrant is signature-valid but carries an identity epoch
    older than the resolver's high-water mark for that agent_id.

    This is the silent-substitution boundary: the key still verifies against a
    cached JWKS snapshot, but the identity binding it carries has been
    superseded by a rotation or a semantic re-provisioning event.
    """


@dataclass
class Warrant:
    agent_id: str
    kid: str
    epoch: int          # monotonic per agent_id, published by the bridge
    jti: str
    exp: int
    signature_valid: bool


@dataclass
class Resolver:
    # kid -> whether the key is in the *current* JWKS (not a cached snapshot)
    current_jwks: Dict[str, bool]
    # per-agent high-water mark for identity epoch
    epoch_hwm: Dict[str, int] = field(default_factory=dict)
    seen_jti: set = field(default_factory=set)

    def resolve(self, w: Warrant, now: int) -> str:
        if not w.signature_valid:
            raise StaleIdentityEpochError(f"bad signature for {w.jti}")

        # Guard 1: replay protection on jti (necessary, not sufficient)
        if w.jti in self.seen_jti:
            raise StaleIdentityEpochError(f"replayed jti {w.jti}")

        # Guard 2: the key must be in the CURRENT JWKS, not a cached snapshot.
        # A kid that verifies only against a stale snapshot is retired.
        if not self.current_jwks.get(w.kid, False):
            raise StaleIdentityEpochError(
                f"kid {w.kid} not in current JWKS; cached-snapshot verification is not authoritative"
            )

        if w.exp <= now:
            raise StaleIdentityEpochError(f"warrant {w.jti} expired")

        # Guard 3: identity-epoch monotonicity. This is the invariant that
        # catches signature-valid-but-semantically-stale principals.
        hwm = self.epoch_hwm.get(w.agent_id, -1)
        if w.epoch < hwm:
            raise StaleIdentityEpochError(
                f"epoch regression for {w.agent_id}: warrant epoch {w.epoch} < hwm {hwm}"
            )

        # Commit: only after all guards pass
        self.epoch_hwm[w.agent_id] = max(hwm, w.epoch)
        self.seen_jti.add(w.jti)
        return w.agent_id


def handle_handoff(resolver: Resolver, w: Warrant, now: int) -> str:
    try:
        return resolver.resolve(w, now)
    except StaleIdentityEpochError as e:
        # Fail closed: do not execute the tool call, do not pass the baton.
        raise StaleIdentityEpochError(
            f"handoff rejected at identity boundary: {e}"
        ) from e
