# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-credential-whose-aaif-attestation-chain-validates-but-whose-delegation-depth-exceeds-the-wa.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-credential-whose-aaif-attestation-chain-validates-but-whose-delegation-depth-exceeds-the-wa.warrant.json
# Markdown SHA-256:   b80935086c0c5e533d36e97480318ad2dbc42ffb6bd474206fd53e48cba37e91
# Code AST SHA-256:   d759a035a989f4fe4bf71829099387b7e14fc4ae4c136c856dcf9c3fce7e6aaf
# Verified Classes:   TransitiveClosureViolation, Attestation, RootWarrant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TransitiveClosureViolation(RuntimeError):
    """Raised when an AAIF attestation chain is cryptographically valid but
    exceeds the delegation authority granted by its root warrant."""
    pass


@dataclass
class Attestation:
    issuer: str
    subject: str
    scope: frozenset
    signature_valid: bool
    revoked: bool
    not_after_ok: bool
    declared_max_depth: Optional[int] = None   # policy this link imposes on children
    re_delegable: bool = True
    parent_depth: int = 0                       # depth of this link in the chain


@dataclass
class RootWarrant:
    issuer: str
    scope: frozenset
    max_depth: int
    re_delegable: bool
    policy_version: str


def evaluate_federated_credential(
    root: RootWarrant,
    chain: list[Attestation],
    trusted_root_issuers: set[str],
) -> bool:
    # 1. Cryptographic / freshness gate (necessary, not sufficient).
    if root.issuer not in trusted_root_issuers:
        raise TransitiveClosureViolation(f"untrusted root issuer {root.issuer}")
    for i, att in enumerate(chain):
        if not att.signature_valid:
            raise TransitiveClosureViolation(f"link {i} signature invalid")
        if att.revoked:
            raise TransitiveClosureViolation(f"link {i} revoked")
        if not att.not_after_ok:
            raise TransitiveClosureViolation(f"link {i} expired")

    # 2. Transitive-closure gate (the part everyone forgets).
    effective_max_depth = root.max_depth
    effective_re_delegable = root.re_delegable
    parent_scope = root.scope

    for i, att in enumerate(chain):
        depth = i + 1  # this link sits at depth i+1 below the root warrant

        if not effective_re_delegable:
            raise TransitiveClosureViolation(
                f"link {i} ({att.issuer}->{att.subject}) violates "
                f"re_delegable=false at an ancestor"
            )
        if depth > effective_max_depth:
            raise TransitiveClosureViolation(
                f"link {i} ({att.issuer}->{att.subject}) at depth {depth} "
                f"exceeds root max_depth {effective_max_depth}"
            )
        if not att.scope.issubset(parent_scope):
            raise TransitiveClosureViolation(
                f"link {i} scope {set(att.scope)} not subset of parent "
                f"{set(parent_scope)} (authority amplification attempt)"
            )

        # Attenuate: downstream policy can only tighten, never widen.
        if att.declared_max_depth is not None:
            effective_max_depth = min(effective_max_depth, att.declared_max_depth)
        effective_re_delegable = effective_re_delegable and att.re_delegable
        parent_scope = att.scope

    return True


def accept_peer_credential(
    root: RootWarrant,
    chain: list[Attestation],
    trusted_root_issuers: set[str],
) -> None:
    try:
        evaluate_federated_credential(root, chain, trusted_root_issuers)
    except TransitiveClosureViolation as exc:
        # Distinct handling: this is a trust event, not a retryable error.
        # Do NOT downgrade to "insufficient scope"; flag the issuing peer.
        raise TransitiveClosureViolation(
            f"rejecting peer credential: {exc}. "
            f"Chain authentic but authority does not exist under "
            f"warrant policy v{root.policy_version}. "
            f"Treat presenting peer as potentially compromised."
        ) from exc
