# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-federated-agent-warrant-replay-across-trust-anchor-rotation-boundaries-in-spiffe-vc-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-federated-agent-warrant-replay-across-trust-anchor-rotation-boundaries-in-spiffe-vc-handoffs.warrant.json
# Markdown SHA-256:   6f2ba571d65319a3b21adcb87d072d813d79bfc18a8283e4b638dc583b63dc0e
# Code AST SHA-256:   c799c9114ddb41ea9b665beef6cad34e162873ac8621eddb5e593c0422cb331d
# Verified Classes:   WarrantBindingError, AnchorEpoch, Warrant, FederationVerifier
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class WarrantBindingError(RuntimeError):
    """Raised when a federated warrant's subject/epoch binding is violated."""
    pass


@dataclass(frozen=True)
class AnchorEpoch:
    trust_domain: str
    chain_hash: str
    epoch: int


@dataclass(frozen=True)
class Warrant:
    subject_id: str          # spiffe://a.example/agent/orchestrator
    audience: str            # spiffe://b.example/agent/executor
    nonce: str
    issuer_chain_hash: str
    issued_at_epoch: int
    privileged: bool


class FederationVerifier:
    def __init__(self, nonce_ledger: set, current: AnchorEpoch,
                 in_flight_grace: int = 0):
        self._ledger = nonce_ledger          # shared, trust-domain scoped
        self._current = current
        self._grace = in_flight_grace

    def verify(self, w: Warrant, presented_svid: str) -> bool:
        # 1. Subject binding must match the LIVE SVID, not the VC's claim.
        if w.subject_id != presented_svid:
            raise WarrantBindingError(
                f"subject drift: warrant={w.subject_id} svid={presented_svid}")

        # 2. Audience must match the executing workload's own SVID.
        if w.audience != self._current.trust_domain and \
           not w.audience.startswith("spiffe://"):
            raise WarrantBindingError(f"audience mismatch: {w.audience}")

        # 3. Chain must resolve under the CURRENT anchor epoch, or be an
        #    explicitly bounded in-flight degraded warrant.
        epoch_delta = self._current.epoch - w.issued_at_epoch
        if w.issuer_chain_hash != self._current.chain_hash:
            if not (w.privileged is False and 0 <= epoch_delta <= self._grace):
                raise WarrantBindingError(
                    f"stale chain across rotation: issued@{w.issued_at_epoch} "
                    f"current@{self._current.epoch}")

        # 4. Nonce replay check scoped to (trust_domain, subject, nonce).
        key = (self._current.trust_domain, w.subject_id, w.nonce)
        if key in self._ledger:
            raise WarrantBindingError(f"warrant replay: nonce={w.nonce}")
        self._ledger.add(key)
        return True


def execute_federated_action(verifier, warrant, presented_svid):
    try:
        verifier.verify(warrant, presented_svid)
    except WarrantBindingError as e:
        # Fail closed: never fall back to a cached/stale warrant.
        raise WarrantBindingError(f"federation boundary rejected: {e}")
    return "executed"
