# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-scope-widening-delegation-chain-before-it-executes-an-unauthorized-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-scope-widening-delegation-chain-before-it-executes-an-unauthorized-tool-call.warrant.json
# Markdown SHA-256:   cf8136e0de32abf6a59cb74314162978385c226d42ca6f10d748e3094d951387
# Code AST SHA-256:   a97f2e60228ea9a7786e1b26a99f240970c4da93a0141ede1c85c73cb5429c32
# Verified Classes:   DelegationChainError, Token
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import posixpath
from dataclasses import dataclass


class DelegationChainError(RuntimeError):
    """Raised when a delegated capability chain is unsound or unverifiable."""
    pass


@dataclass(frozen=True)
class Token:
    iss: str
    sub: str
    scope: tuple[str, ...]
    parent: "Token | None"


def canonicalize_glob(pattern: str) -> str:
    # Collapse '..' and '.' segments; keep trailing '*' semantics explicit.
    # NOTE: this must be byte-identical in behavior to the tool's own
    # argument canonicalizer, or the whole invariant collapses.
    parts = pattern.split("/")
    out: list[str] = []
    for part in parts:
        if part in ("", "."):
            continue
        if part == "..":
            if not out:
                raise DelegationChainError(f"scope escapes root: {pattern!r}")
            out.pop()
            continue
        out.append(part)
    return "/" + "/".join(out)


def is_subset(child: tuple[str, ...], parent: tuple[str, ...]) -> bool:
    canon_parent = {canonicalize_glob(p) for p in parent}
    for c in child:
        cp = canonicalize_glob(c)
        if not any(cp == pp or cp.startswith(pp.rstrip("*")) for pp in canon_parent):
            return False
    return True


def effective_scope(leaf: Token) -> tuple[str, ...]:
    """Walk the full chain to root; reject any widening hop."""
    chain: list[Token] = []
    node: Token | None = leaf
    depth = 0
    while node is not None:
        chain.append(node)
        node = node.parent
        depth += 1
        if depth > 8:
            raise DelegationChainError("delegation depth exceeds bound; refusing")
    # Verify each hop against its parent, transitively.
    for i in range(len(chain) - 1):
        child, parent = chain[i], chain[i + 1]
        if not is_subset(child.scope, parent.scope):
            raise DelegationChainError(
                f"scope widening at hop {i}: child={child.scope} parent={parent.scope}"
            )
    return tuple(canonicalize_glob(p) for p in chain[0].scope)


def authorize_call(token: Token, tool_path: str) -> None:
    """Bind the canonicalized argument to the canonicalized effective scope."""
    scope = effective_scope(token)
    arg = canonicalize_glob(tool_path)
    if not any(arg == s or arg.startswith(s.rstrip("*")) for s in scope):
        raise DelegationChainError(
            f"argument {arg!r} outside effective scope {scope}"
        )
