# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-delegated-capability-token-fail-authority-verification-when-the-delegation-chain-is-cryptographically-valid-but-the-scope-la.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-delegated-capability-token-fail-authority-verification-when-the-delegation-chain-is-cryptographically-valid-but-the-scope-la.warrant.json
# Markdown SHA-256:   2aea858cc53268da717fbce5beaf922e00e44946d94466dd25fd107b578a82ce
# Code AST SHA-256:   92b5f282cc883310fc71575246081ccf8ed2f5990afb66dcfca8a95e3cdb1625
# Verified Classes:   ScopeContainmentError, Scope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeContainmentError(RuntimeError):
    """Raised when a delegation chain's composed scope is not implied by the root grant."""


@dataclass(frozen=True)
class Scope:
    resource: str
    actions: FrozenSet[str]
    # Positive allow-list of source CIDRs; None means "unconstrained".
    allow_cidrs: FrozenSet[str] = field(default_factory=frozenset)
    # Explicit exclusions; these are the soundness hazard.
    deny_cidrs: FrozenSet[str] = field(default_factory=frozenset)


def _cidr_within(child: str, parent: str) -> bool:
    # Placeholder for real CIDR containment (ipaddress.ip_network(child).subnet_of(...)).
    return child == parent or child.startswith(parent.rsplit(".", 1)[0] + ".")


def composed_scope(chain: list[Scope]) -> Scope:
    if not chain:
        raise ScopeContainmentError("empty delegation chain")
    root = chain[0]
    actions = root.actions
    allow = root.allow_cidrs
    deny = root.deny_cidrs
    for link in chain[1:]:
        if link.resource != root.resource:
            raise ScopeContainmentError(
                f"resource drift: {link.resource!r} != {root.resource!r}"
            )
        actions = actions & link.actions
        # Meet of allow-lists: if either side is unconstrained (empty == unconstrained
        # by convention here), take the other; else intersect.
        if not allow:
            allow = link.allow_cidrs
        elif link.allow_cidrs:
            allow = frozenset(
                a for a in allow if any(_cidr_within(a, b) for b in link.allow_cidrs)
            )
        deny = deny | link.deny_cidrs
    return Scope(root.resource, actions, allow, deny)


def verify_chain(root_grant: Scope, chain: list[Scope]) -> Scope:
    """Return the effective scope, or raise if the meet escapes the root grant."""
    composed = composed_scope([root_grant, *chain])
    # Soundness check: no allowed CIDR may fall inside any denied CIDR.
    for cidr in composed.allow_cidrs:
        for denied in composed.deny_cidrs:
            if _cidr_within(cidr, denied):
                raise ScopeContainmentError(
                    f"authority amplification: composed allow {cidr!r} is inside "
                    f"root exclusion {denied!r}; chain is signature-valid but unsound"
                )
    if not composed.actions and root_grant.actions:
        # Empty action set is a valid (null) delegation, not an error, but flag it.
        return composed
    return composed


# Reproduces the observed failure: per-link checks pass, composed check must fail.
root = Scope("bucket/x", frozenset({"read", "list"}), deny_cidrs=frozenset({"10.0.0.0/8"}))
a1 = Scope("bucket/x", frozenset({"read"}), allow_cidrs=frozenset({"10.1.0.0/16"}))
a2 = Scope("bucket/x", frozenset({"read"}))  # "unconstrained read"

# Naive per-link verifier would accept a1 then a2. The sound verifier must not.
verify_chain(root, [a1, a2])  # raises ScopeContainmentError
