# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-capability-token-scope-creep-during-aaif-credential-re-delegation-across-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-capability-token-scope-creep-during-aaif-credential-re-delegation-across-agent-hops.warrant.json
# Markdown SHA-256:   5c43053b6d84b50b3ed726181e7df5ad8a88e077e140152a43631d8141d31b73
# Code AST SHA-256:   33b2c953b1139cba935bde2833c22e606be92f387298bfb1efdd2723dea804d7
# Verified Classes:   ScopeCanonicalizationError, CapabilityToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import FrozenSet


class ScopeCanonicalizationError(RuntimeError):
    """Raised when a delegation chain's canonical scope digests diverge."""


@dataclass(frozen=True)
class CapabilityToken:
    issuer: str
    subject: str
    canonical_resources: FrozenSet[str]  # already normalized by the issuer
    scope_digest: str                    # sha256 over sorted canonical set
    parent_digest: str | None            # digest of the token this one attenuates


def compute_scope_digest(canonical_resources: FrozenSet[str]) -> str:
    payload = "\n".join(sorted(canonical_resources)).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def verify_delegation_chain(chain: list[CapabilityToken]) -> None:
    """
    Enforce: each token's canonical scope is a subset of its parent's,
    and the digest chain is internally consistent. Canonicalization is
    assumed already performed by each issuer; this verifier only checks
    the committed digests and the subset relation over canonical sets.
    """
    if not chain:
        raise ScopeCanonicalizationError("empty delegation chain")

    root = chain[0]
    if root.parent_digest is not None:
        raise ScopeCanonicalizationError(
            f"root token {root.issuer} must not declare a parent_digest"
        )
    if compute_scope_digest(root.canonical_resources) != root.scope_digest:
        raise ScopeCanonicalizationError(
            f"root token {root.issuer} scope_digest does not match canonical set"
        )

    for parent, child in zip(chain, chain[1:]):
        if child.parent_digest != parent.scope_digest:
            raise ScopeCanonicalizationError(
                f"child {child.issuer}->{child.subject} parent_digest "
                f"{child.parent_digest!r} != parent scope_digest {parent.scope_digest!r}"
            )
        if compute_scope_digest(child.canonical_resources) != child.scope_digest:
            raise ScopeCanonicalizationError(
                f"child {child.issuer}->{child.subject} scope_digest does not "
                f"match its own canonical set"
            )
        # Subset over canonical sets — NOT string prefixes.
        if not child.canonical_resources.issubset(parent.canonical_resources):
            leaked = child.canonical_resources - parent.canonical_resources
            raise ScopeCanonicalizationError(
                f"scope creep at hop {child.issuer}->{child.subject}: "
                f"resources {sorted(leaked)} not covered by parent {parent.issuer}"
            )
