# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-delegated-authority-scope-creep-when-a-federated-peer-re-signs-a-capability-it-was-only-authorized-to-attenu.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-delegated-authority-scope-creep-when-a-federated-peer-re-signs-a-capability-it-was-only-authorized-to-attenu.warrant.json
# Markdown SHA-256:   844fb3023676c95b77697cae7ff63cc74593547e5f201310329a9c2ff0feb41b
# Code AST SHA-256:   567edb9be6912ad0d6d6c48ca00d20de7332f0c31636833396df8ff61c0dcab7
# Verified Classes:   DelegationWideningError, Scope, Capability
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class DelegationWideningError(RuntimeError):
    """Raised when a delegated capability is broader than its parent, or drops a parent constraint."""


@dataclass(frozen=True)
class Scope:
    resource: str      # canonical, e.g. "repo/team-a/*"
    verb: str          # e.g. "read"

    def is_subset_of(self, parent: "Scope") -> bool:
        # Lattice inclusion over canonical form. A child resource is a subset
        # only if it is equal to, or a strict descendant of, the parent pattern.
        if self.verb != parent.verb:
            return False
        if parent.resource.endswith("/*"):
            prefix = parent.resource[:-1]  # keep trailing slash
            return self.resource == parent.resource or self.resource.startswith(prefix)
        return self.resource == parent.resource


@dataclass(frozen=True)
class Capability:
    subject: str
    scope: Scope
    constraints: FrozenSet[str]
    parent_hash: Optional[str]   # commitment to parent; None only for anchor-issued roots
    issuer: str
    signature: str


def verify_link(child: Capability, parent: Capability) -> None:
    """Enforce attenuation at one link. Fail closed on any widening or constraint loss."""
    if child.parent_hash is None:
        raise DelegationWideningError(
            f"capability for {child.subject} has no parent commitment; "
            "only the trust anchor may issue root capabilities"
        )
    if not child.scope.is_subset_of(parent.scope):
        raise DelegationWideningError(
            f"scope widening: child {child.scope!r} is not a subset of parent {parent.scope!r}"
        )
    # Constraint monotonicity: child must retain every parent constraint.
    # Absence is a violation, not a default.
    missing = parent.constraints - child.constraints
    if missing:
        raise DelegationWideningError(
            f"constraint loss on delegation to {child.subject}: dropped {sorted(missing)}"
        )
    # no_resign is an attenuation-forbidden flag: if set on parent, child must not exist.
    if "no_resign" in parent.constraints:
        raise DelegationWideningError(
            f"parent forbids re-signing (no_resign); {child.issuer} may not delegate to {child.subject}"
        )


def verify_chain(chain: list[Capability], anchor: str) -> None:
    """Walk to the anchor. Boundary 2: link-only verification is unsound for len > 1."""
    if not chain:
        raise DelegationWideningError("empty delegation chain")
    if chain[0].issuer != anchor or chain[0].parent_hash is not None:
        raise DelegationWideningError(
            f"chain root must be issued by anchor {anchor!r}, got issuer {chain[0].issuer!r}"
        )
    for parent, child in zip(chain, chain[1:]):
        verify_link(child, parent)
