# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-peer-s-policy-claim-the-trust-anchor-substitution-failure-in-cross-org-agent-policy-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-peer-s-policy-claim-the-trust-anchor-substitution-failure-in-cross-org-agent-policy-exchange.warrant.json
# Markdown SHA-256:   98957b44edd80d563807f8be15c19af939f143a618327233ea90584d427693b9
# Code AST SHA-256:   aa3e39a50555103eb9fd08679934cbde640c59083e13be7f8e67ea95cbc8826c
# Verified Classes:   TrustAnchorSubstitutionError, PolicyClaim, GrantCacheEntry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class TrustAnchorSubstitutionError(RuntimeError):
    """Raised when a federated policy claim's anchor resolves by name, not pinned key."""


@dataclass(frozen=True)
class PolicyClaim:
    peer_id: str
    tool: str
    scope: str
    leaf_signature: bytes
    signing_key_fingerprint: str      # key that actually produced leaf_signature
    terminal_issuer_name: str         # attacker-writable string
    terminal_issuer_fingerprint: str  # must be in pinned anchor set


@dataclass(frozen=True)
class GrantCacheEntry:
    validating_key_fingerprint: str
    tool: str
    scope: str


def verify_and_cache(
    claim: PolicyClaim,
    pinned_anchors: FrozenSet[str],
    cache: dict,
) -> GrantCacheEntry:
    # Anchor must resolve to pinned key material, never to a name.
    if claim.terminal_issuer_fingerprint not in pinned_anchors:
        raise TrustAnchorSubstitutionError(
            f"anchor {claim.terminal_issuer_name!r} "
            f"(fp={claim.terminal_issuer_fingerprint}) not in pinned set; "
            f"refusing claim from {claim.peer_id}"
        )
    # Leaf must be signed by the anchor key, not merely claim to be.
    if claim.signing_key_fingerprint != claim.terminal_issuer_fingerprint:
        raise TrustAnchorSubstitutionError(
            f"leaf signed by {claim.signing_key_fingerprint} but anchored to "
            f"{claim.terminal_issuer_fingerprint}; chain broken at anchor"
        )
    entry = GrantCacheEntry(
        validating_key_fingerprint=claim.terminal_issuer_fingerprint,
        tool=claim.tool,
        scope=claim.scope,
    )
    # Cache bound to validating key, so rotation evicts precisely these grants.
    cache[(entry.validating_key_fingerprint, entry.tool, entry.scope)] = entry
    return entry


def evict_on_rotation(cache: dict, revoked_fingerprint: str) -> int:
    stale = [k for k in cache if k[0] == revoked_fingerprint]
    for k in stale:
        del cache[k]
    return len(stale)
