# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-attenuated-capability-token-has-silently-widened-on-re-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-attenuated-capability-token-has-silently-widened-on-re-delegation.warrant.json
# Markdown SHA-256:   467a3fd33389b5bdb1c6db068ee5196b2830922d3bb53b916b6bad53a8452a39
# Code AST SHA-256:   770641476a433fadaa8b76dbe2e3a94d085a3561478c5af658862af49053dbca
# Verified Classes:   AttenuationWidened, Scope, CapToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Callable, Iterable


class AttenuationWidened(RuntimeError):
    """Raised when a delegated token authorizes an operation its ancestor does not."""


@dataclass(frozen=True)
class Scope:
    kind: str          # e.g. "fs:write"
    target: str        # e.g. "/tmp/scratch"


@dataclass(frozen=True)
class CapToken:
    issuer: str
    parent_hash: str | None
    scopes: frozenset[Scope]
    ttl_s: int
    signature: str

    def digest(self) -> str:
        body = f"{self.issuer}|{self.parent_hash}|{sorted((s.kind, s.target) for s in self.scopes)}|{self.ttl_s}"
        return hashlib.sha256(body.encode()).hexdigest()


def canonicalize(raw_path: str) -> str:
    # Single canonicalizer used by BOTH containment proof and enforcement.
    parts: list[str] = []
    for seg in raw_path.split("/"):
        if seg in ("", "."):
            continue
        if seg == "..":
            if parts:
                parts.pop()
            continue
        parts.append(seg)
    return "/" + "/".join(parts)


def authorizes(token: CapToken, op_kind: str, raw_target: str) -> bool:
    target = canonicalize(raw_target)
    for s in token.scopes:
        if s.kind != op_kind:
            continue
        base = canonicalize(s.target)
        # Segment-boundary prefix: /tmp/scratch matches /tmp/scratch/x, not /tmp/scratchy
        if target == base or target.startswith(base + "/"):
            return True
    return False


def verify_chain_and_enforce(
    chain: list[CapToken],
    op_kind: str,
    raw_target: str,
    boundary_probes: Iterable[str],
) -> None:
    """Reconstruct containment root->leaf in the effect domain, then enforce."""
    if not chain:
        raise AttenuationWidened("empty delegation chain")
    root, *descendants = chain
    if root.parent_hash is not None:
        raise AttenuationWidened("chain does not start at a root token")

    # 1. Link integrity: each child must name its parent's digest.
    for parent, child in zip(chain, chain[1:]):
        if child.parent_hash != parent.digest():
            raise AttenuationWidened(
                f"broken link: {child.issuer} does not descend from {parent.issuer}"
            )
        if child.ttl_s > parent.ttl_s:
            raise AttenuationWidened(
                f"ttl widened at {child.issuer}: {child.ttl_s} > {parent.ttl_s}"
            )

    leaf = chain[-1]

    # 2. Semantic containment: every boundary probe the leaf authorizes must
    #    also be authorized by the root under the same canonicalizer.
    for probe in boundary_probes:
        if authorizes(leaf, op_kind, probe) and not authorizes(root, op_kind, probe):
            raise AttenuationWidened(
                f"leaf {leaf.issuer} authorizes {op_kind} {probe!r} that root {root.issuer} does not"
            )

    # 3. Enforce the concrete operation against the leaf; the containment proof
    #    above already bounds it by the root.
    if not authorizes(leaf, op_kind, raw_target):
        raise PermissionError(f"{op_kind} {raw_target!r} not granted by leaf token")


# --- reproduction of the observed incident ---
root = CapToken(
    issuer="O", parent_hash=None,
    scopes=frozenset({Scope("fs:write", "/tmp/*")}),
    ttl_s=3600, signature="sig_O",
)
# Planner mints a syntactically-narrower child; the bug was that enforcement
# canonicalized *after* the prefix check, so /tmp/scratch/../../etc/... passed.
planner = CapToken(
    issuer="P", parent_hash=root.digest(),
    scopes=frozenset({Scope("fs:write", "/tmp/scratch")}),
    ttl_s=1800, signature="sig_P",
)

probes = [
    "/tmp/scratch/../../etc/cron.d/x",  # traversal the old guard missed
    "/tmp/scratchy/evil",               # prefix-collision sibling
    "/tmp/scratch/ok.txt",              # legitimate
]

try:
    verify_chain_and_enforce(
        [root, planner],
        op_kind="fs:write",
        raw_target="/tmp/scratch/../../etc/cron.d/x",
        boundary_probes=probes,
    )
except AttenuationWidened as exc:
    # Traversal canonicalizes to /etc/cron.d/x, which the leaf does not grant;
    # the prefix-collision probe is the one that catches semantic widening.
    print(f"blocked at delegation boundary: {exc}")
