# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-to-reject-a-federated-capability-attestation-after-its-trust-anchor-rotates-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-to-reject-a-federated-capability-attestation-after-its-trust-anchor-rotates-mid-session.warrant.json
# Markdown SHA-256:   8816ea21ba6eeb5152a5198e5c5816c77a03e0e3e5b181a868c48dc716dc505a
# Code AST SHA-256:   dc7e7f85c19cd6cde09204ac2850839289a174598534f9a840152c43a8cd2787
# Verified Classes:   TrustAnchorUnresolved, StaleTrustSubstitution, Attestation, AnchorSet, FederatedValidator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class TrustAnchorUnresolved(RuntimeError):
    """Raised when an attestation's issuer chain does not terminate in a
    currently-live trust anchor. This is terminal for the claim -- it must
    never fall back to a session-scoped trust verdict."""


class StaleTrustSubstitution(RuntimeError):
    """Raised when a validator attempts to admit a claim on the strength of a
    session-cached trust decision after signature verification failed."""


@dataclass
class Attestation:
    issuer: str
    scope: dict
    signature: str


@dataclass
class AnchorSet:
    live: set = field(default_factory=set)
    epoch: int = 0

    def contains(self, anchor_id: str) -> bool:
        return anchor_id in self.live


class FederatedValidator:
    """Claim-bound capability validator.

    Invariant: admission requires the attestation's issuer to resolve to an
    anchor in the *live* set at check time, and the signature to verify
    against that anchor. A session trust cache may gate connection setup but
    is NEVER consulted as a substitute for claim validation.
    """

    def __init__(self, anchors: AnchorSet):
        self._anchors = anchors
        self._session_trusted: dict = {}

    def admit(self, peer: str, att: Attestation, verify_sig) -> bool:
        # Session trust is a precondition only, not an admission verdict.
        if not self._session_trusted.get(peer, False):
            return False

        if not self._anchors.contains(att.issuer):
            # Fail closed. "Anchor not yet received" is a rejection, not an
            # abstention, and must not defer to the session verdict.
            raise TrustAnchorUnresolved(
                f"issuer {att.issuer} does not terminate in live anchor set "
                f"(epoch={self._anchors.epoch}); refusing claim for peer {peer}"
            )

        if not verify_sig(att, att.issuer):
            # Signature failure is terminal for the claim. Do NOT fall back
            # to session trust -- that is the laundering path.
            raise StaleTrustSubstitution(
                f"signature verification failed for {att.issuer} under live "
                f"anchor; session trust for {peer} may not substitute"
            )

        return True

    def on_anchor_epoch_advance(self, new_live: set):
        # Epoch-bound optimization: drop all verdicts keyed to the old epoch.
        self._anchors.live = set(new_live)
        self._anchors.epoch += 1
        self._session_trusted.clear()
