# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-mutates-its-spiffe-svid-mid-task-and-the-peer-s-cached-trust-anchor-silently-outlives-the-bundle-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-mutates-its-spiffe-svid-mid-task-and-the-peer-s-cached-trust-anchor-silently-outlives-the-bundle-rotation.warrant.json
# Markdown SHA-256:   06aaa2a52d35562647f974f6e692815c4de1ee4c17867ee8965686ecc698d7d9
# Code AST SHA-256:   a12f61cf5d8d7eaa8a731b03958ab90645c89633b8d8a2d04053596d0b991d92
# Verified Classes:   StaleFederatedWarrantError, Svids, PeerWarrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleFederatedWarrantError(RuntimeError):
    """Raised when a peer warrant outlives the capability surface it was minted against."""
    pass


@dataclass(frozen=True)
class Svids:
    spiffe_id: str
    svid_serial: int
    bundle_serial: int
    capability_manifest_hash: str


@dataclass(frozen=True)
class PeerWarrant:
    spiffe_id: str
    bundle_serial: int
    capability_manifest_hash: str
    granted_scopes: frozenset


def verify_peer_warrant(
    incoming: Svids,
    cached: Optional[PeerWarrant],
    current_manifest_hash: str,
) -> PeerWarrant:
    if cached is None:
        # No warrant: caller must mint one from a fresh manifest fetch.
        return PeerWarrant(
            spiffe_id=incoming.spiffe_id,
            bundle_serial=incoming.bundle_serial,
            capability_manifest_hash=current_manifest_hash,
            granted_scopes=frozenset(),  # populated by minting flow
        )

    # Invariant 1: bundle serial is a monotonic floor per peer.
    if incoming.bundle_serial < cached.bundle_serial:
        raise StaleFederatedWarrantError(
            f"peer {incoming.spiffe_id} presented bundle_serial "
            f"{incoming.bundle_serial} older than cached {cached.bundle_serial}; "
            f"possible replay or rollback"
        )

    # Invariant 2: warrant must be keyed on the mutable capability surface,
    # not on the stable SPIFFE ID alone.
    if incoming.capability_manifest_hash != cached.capability_manifest_hash:
        raise StaleFederatedWarrantError(
            f"peer {incoming.spiffe_id} capability manifest changed "
            f"({cached.capability_manifest_hash} -> "
            f"{incoming.capability_manifest_hash}); cached warrant is stale, "
            f"re-derive before authorizing"
        )

    # Invariant 3: a bundle advance invalidates the warrant even if the
    # manifest hash happens to match, because rotation implies a workload
    # lifecycle event we have not observed.
    if incoming.bundle_serial > cached.bundle_serial:
        raise StaleFederatedWarrantError(
            f"peer {incoming.spiffe_id} advanced bundle "
            f"{cached.bundle_serial} -> {incoming.bundle_serial}; "
            f"warrant must be re-derived under the new bundle"
        )

    return cached


def authorize_tool_call(
    incoming: Svids,
    cached: Optional[PeerWarrant],
    current_manifest_hash: str,
    requested_scope: str,
) -> None:
    warrant = verify_peer_warrant(incoming, cached, current_manifest_hash)
    if requested_scope not in warrant.granted_scopes:
        raise StaleFederatedWarrantError(
            f"scope {requested_scope!r} not granted to {incoming.spiffe_id} "
            f"under manifest {warrant.capability_manifest_hash}"
        )
