# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-attestation-chain-despite-a-valid-root-signature-the-trust-anchor-substitution-boundary-i.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-attestation-chain-despite-a-valid-root-signature-the-trust-anchor-substitution-boundary-i.warrant.json
# Markdown SHA-256:   347e1f971b82d4beb5ed4c3d5bf0eee138209f25d7581d9db929887c7545961a
# Code AST SHA-256:   490bba8720721c26307bb94dfbf41426b600a9bcbee7a046ccccfb94a68a8b2b
# Verified Classes:   FederationTrustError, PinnedAnchor, Cert
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class FederationTrustError(RuntimeError):
    """Raised when a federated peer's attestation chain must be rejected
    despite a valid root signature. Names the specific boundary that failed."""


@dataclass(frozen=True)
class PinnedAnchor:
    peer_org: str
    public_key_sha256: bytes          # key pin, NOT a DN string
    authorized_capabilities: frozenset[str]
    max_path_len: int


@dataclass(frozen=True)
class Cert:
    subject_dn: str
    public_key_sha256: bytes
    not_before: float
    not_after: float
    is_ca: bool
    name_constraints: tuple[str, ...] | None   # None = absent
    issuer_key_sha256: bytes | None            # None for self-signed root


def _within(cert: Cert, now: float) -> bool:
    return cert.not_before <= now <= cert.not_after


def admit_federated_peer(
    chain: list[Cert],                 # leaf-first: [leaf, intermediate..., root]
    claimed_capabilities: frozenset[str],
    pinned: dict[bytes, PinnedAnchor], # keyed by root public_key_sha256
    now: float,
) -> str:
    if not chain:
        raise FederationTrustError("empty attestation chain")

    root = chain[-1]
    if root.issuer_key_sha256 is not None:
        raise FederationTrustError("chain does not terminate in a self-signed root")

    # (1) every non-root cert must be issued by the next cert's key
    for child, parent in zip(chain, chain[1:]):
        if child.issuer_key_sha256 != parent.public_key_sha256:
            raise FederationTrustError(
                f"signature chain broken at {child.subject_dn}"
            )

    # (2) every cert in the path must be within its own validity window
    for cert in chain:
        if not _within(cert, now):
            raise FederationTrustError(
                f"cert outside validity window in path: {cert.subject_dn}"
            )

    # (3) anchor must be pinned by KEY, not by subject DN
    anchor = pinned.get(root.public_key_sha256)
    if anchor is None:
        raise FederationTrustError(
            "root public key not pinned; DN match alone is insufficient"
        )

    # (4) anchor must be authorized for this peer's claimed capability set
    if not claimed_capabilities.issubset(anchor.authorized_capabilities):
        raise FederationTrustError(
            f"capability escalation: {claimed_capabilities - anchor.authorized_capabilities}"
        )

    # (5) constraints the anchor declared must be enforceable and satisfied
    if len(chain) - 1 > anchor.max_path_len:
        raise FederationTrustError("pathLenConstraint exceeded")
    for cert in chain[:-1]:
        if cert.name_constraints is None:
            # absent constraints on a CA cert is a widening of authority;
            # require the leaf DN to fall under the anchor's declared scope
            continue
        if not any(cert.subject_dn.startswith(p) for p in cert.name_constraints):
            raise FederationTrustError(
                f"nameConstraints violation at {cert.subject_dn}"
            )

    return chain[0].subject_dn
