# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-peer-s-attestation-chain-at-the-trust-anchor-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-peer-s-attestation-chain-at-the-trust-anchor-boundary.warrant.json
# Markdown SHA-256:   d3cf8d29499520d03aec7ffc8399378085d8eb48af83385a213cec99c4ab7955
# Code AST SHA-256:   15a918561020db73796fc5467373f86160fd70349b85a00ccd6a6fe6d3fc85a5
# Verified Classes:   FederatedAttestationError, TrustAnchor, ChainLink, Handoff
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class FederatedAttestationError(RuntimeError):
    """Raised when a presenter's attestation chain fails anchor-boundary validation."""


@dataclass(frozen=True)
class TrustAnchor:
    org: str
    key_id: str
    permitted_capabilities: frozenset
    max_delegation_depth: int
    state_version: int
    revoked: bool


@dataclass(frozen=True)
class ChainLink:
    issuer_key: str
    subject_key: str
    granted_capabilities: frozenset
    depth: int
    expired: bool


@dataclass(frozen=True)
class Handoff:
    claimed_org: str
    chain: tuple            # tuple[ChainLink, ...], root-first
    asserted_capability: str
    anchor_state_version_seen: int


def verify_federated_handoff(
    handoff: Handoff,
    pinned_anchors: dict,   # key_id -> TrustAnchor
    current_anchor_state_version: int,
) -> TrustAnchor:
    if not handoff.chain:
        raise FederatedAttestationError("empty attestation chain")

    root = handoff.chain[0]
    anchor: Optional[TrustAnchor] = pinned_anchors.get(root.issuer_key)

    # (a) anchor must be pinned AND authoritative for the claimed org
    if anchor is None or anchor.org != handoff.claimed_org:
        raise FederatedAttestationError(
            f"chain root {root.issuer_key!r} is not a pinned anchor for "
            f"claimed org {handoff.claimed_org!r}"
        )

    # (d) anchor must not be revoked
    if anchor.revoked:
        raise FederatedAttestationError(
            f"anchor {anchor.key_id!r} is revoked; presenter is out of federation"
        )

    # (e) trust decision must not be derived from a stale anchor state
    if handoff.anchor_state_version_seen != current_anchor_state_version:
        raise FederatedAttestationError(
            f"stale anchor state: decision derived from v{handoff.anchor_state_version_seen}, "
            f"current v{current_anchor_state_version}"
        )

    # (b) each link's scope must be a subset of its parent's, and depth bounded
    parent_caps = anchor.permitted_capabilities
    for i, link in enumerate(handoff.chain):
        if link.expired:
            raise FederatedAttestationError(f"link {i} expired")
        if link.depth > anchor.max_delegation_depth:
            raise FederatedAttestationError(
                f"link {i} depth {link.depth} exceeds anchor max {anchor.max_delegation_depth}"
            )
        if not link.granted_capabilities.issubset(parent_caps):
            raise FederatedAttestationError(
                f"link {i} scope {link.granted_capabilities} exceeds parent {parent_caps}"
            )
        parent_caps = link.granted_capabilities

    # (c) terminal asserted capability must be within the leaf's signed scope
    leaf_caps = handoff.chain[-1].granted_capabilities
    if handoff.asserted_capability not in leaf_caps:
        raise FederatedAttestationError(
            f"asserted capability {handoff.asserted_capability!r} not covered by "
            f"leaf scope {leaf_caps}; unsigned envelope claim cannot extend chain"
        )

    return anchor
