# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-attestation-whose-signing-chain-is-valid-but-whose-delegation-depth-exceeds-the-manifest-s-declared.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-attestation-whose-signing-chain-is-valid-but-whose-delegation-depth-exceeds-the-manifest-s-declared.warrant.json
# Markdown SHA-256:   433140c73ca2c00d4c9391c63dad2abd61354ff2a0ec37a431a4eb543675fd9c
# Code AST SHA-256:   f11ce57370f1610458a6f102601c97854165793cd79eb484143505f0376a0d81
# Verified Classes:   DelegationDepthExceeded, Manifest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class DelegationDepthExceeded(RuntimeError):
    """Raised when a federated attestation chain's composed depth exceeds the pinned root's declared limit."""


@dataclass(frozen=True)
class Manifest:
    issuer: str
    subject: str
    scope: frozenset
    max_delegation_depth: int  # absolute depth from root, per corrected schema
    signature_valid: bool


def verify_federated_chain(chain: list[Manifest], anchor: Manifest) -> None:
    """chain[0] is the presented leaf; chain[-1] must be issued by the anchor."""
    if not chain:
        raise DelegationDepthExceeded("empty attestation chain")

    # 1. Anchor pinning: the terminal link must be issued by the pinned anchor.
    if chain[-1].issuer != anchor.subject:
        raise DelegationDepthExceeded(
            f"chain terminates at {chain[-1].issuer!r}, not pinned anchor {anchor.subject!r}"
        )

    # 2. Per-link signature and scope monotonicity (leaf -> root).
    for i in range(len(chain) - 1):
        child, parent = chain[i], chain[i + 1]
        if not child.signature_valid or not parent.signature_valid:
            raise DelegationDepthExceeded(f"invalid signature at link {i}")
        if not child.scope <= parent.scope:
            raise DelegationDepthExceeded(f"scope widened at link {i}: {child.scope} !<= {parent.scope}")
        # Absolute-depth monotonicity: child may not raise the bound.
        if child.max_delegation_depth > parent.max_delegation_depth:
            raise DelegationDepthExceeded(
                f"link {i} raises depth bound {child.max_delegation_depth} > {parent.max_delegation_depth}"
            )

    # 3. Composed-depth fold against the pinned anchor — the load-bearing check.
    composed_depth = len(chain) - 1
    if composed_depth > anchor.max_delegation_depth:
        raise DelegationDepthExceeded(
            f"composed depth {composed_depth} exceeds anchor limit {anchor.max_delegation_depth}"
        )
