# 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-policy-bundle-when-its-trust-anchor-chain-validates-but-its-capability-claims-exceed-the.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-policy-bundle-when-its-trust-anchor-chain-validates-but-its-capability-claims-exceed-the.warrant.json
# Markdown SHA-256:   ef3866219fda2b64db6718a8a414e18714473442f1e8394413fb2b976917531d
# Code AST SHA-256:   99871a4ee9e0e4b64095bb12b5c2af4bcbcd7750e763fc7fd74fd4f88527adac
# Verified Classes:   ScopeViolation, AnchorDelegation, PolicyBundle
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class ScopeViolation(RuntimeError):
    """Raised when a federated policy bundle is cryptographically valid
    but exceeds the delegated scope of its trust anchor."""
    pass


@dataclass(frozen=True)
class AnchorDelegation:
    anchor_id: str
    permitted_capabilities: FrozenSet[str]      # glob patterns, e.g. "fs.*"
    max_delegation_depth: int
    data_labels: FrozenSet[str]
    max_quota_per_min: int


@dataclass(frozen=True)
class PolicyBundle:
    peer_id: str
    signer_chain_valid: bool                    # result of X.509/policy chain check
    policy_delegation_depth: int                # counted over policy-delegation records
    capabilities: FrozenSet[str]
    data_labels: FrozenSet[str]
    quota_per_min: int


def _matches_any(cap: str, patterns: FrozenSet[str]) -> bool:
    for p in patterns:
        if p == cap:
            return True
        if p.endswith(".*") and cap.startswith(p[:-1]):
            return True
    return False


def admit_federated_bundle(
    anchor: Optional[AnchorDelegation],
    bundle: PolicyBundle,
) -> None:
    # Chain validity is necessary, never sufficient.
    if not bundle.signer_chain_valid:
        raise ScopeViolation(f"chain invalid for peer {bundle.peer_id}")

    # Fail-closed on missing anchor or missing constraint fields.
    if anchor is None:
        raise ScopeViolation(f"no trust anchor resolved for peer {bundle.peer_id}")
    if not anchor.permitted_capabilities:
        raise ScopeViolation("anchor declares empty permitted_capabilities; denying by default")

    if bundle.policy_delegation_depth > anchor.max_delegation_depth:
        raise ScopeViolation(
            f"policy delegation depth {bundle.policy_delegation_depth} exceeds "
            f"anchor max {anchor.max_delegation_depth}"
        )

    out_of_scope = [c for c in bundle.capabilities
                    if not _matches_any(c, anchor.permitted_capabilities)]
    if out_of_scope:
        raise ScopeViolation(
            f"capabilities outside anchor scope: {sorted(out_of_scope)} "
            f"(anchor permits {sorted(anchor.permitted_capabilities)})"
        )

    bad_labels = bundle.data_labels - anchor.data_labels
    if bad_labels:
        raise ScopeViolation(f"data labels outside anchor scope: {sorted(bad_labels)}")

    if bundle.quota_per_min > anchor.max_quota_per_min:
        raise ScopeViolation(
            f"quota {bundle.quota_per_min}/min exceeds anchor max {anchor.max_quota_per_min}/min"
        )
    # Admission granted; caller may now register the peer's capabilities.
