# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-capability-scoped-aaif-credential-that-verifies-but-is-out-of-scope-for-the-invoked-operation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-capability-scoped-aaif-credential-that-verifies-but-is-out-of-scope-for-the-invoked-operation.warrant.json
# Markdown SHA-256:   85b7abf2990a27c9f3aa424f42e59a809f190d862d9c1ebdd4a005051b7aea3b
# Code AST SHA-256:   7cc86d3049bdd64096a89b4027bc119e717c2abdbe82dd6bb219b4f711ee887d
# Verified Classes:   ScopeViolation, Constraint, CapabilityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet

class ScopeViolation(RuntimeError):
    """Raised when a verified AAIF credential does not authorize the concrete operation."""

@dataclass(frozen=True)
class Constraint:
    kind: str          # "path_prefix" | "host_allowlist" | ...
    value: str

@dataclass(frozen=True)
class CapabilityToken:
    issuer: str
    audience: str
    sub_chain: tuple
    scope: tuple        # tuple of (resource, action, frozenset[Constraint])
    delegation_depth: int
    # NOTE: granted_scope_summary is deliberately absent from this dataclass.
    # It is dropped at deserialization and never reaches the policy engine.

_IMPLEMENTED_CONSTRAINT_KINDS = frozenset({"path_prefix"})

def _canonicalize_path(p: str) -> str:
    import os
    return os.path.realpath(p)

def _evaluate_constraint(c: Constraint, op_args: dict) -> bool:
    if c.kind == "path_prefix":
        target = _canonicalize_path(op_args.get("cwd", ""))
        prefix = _canonicalize_path(c.value)
        return target == prefix or target.startswith(prefix + "/")
    raise ScopeViolation(f"unimplemented constraint kind {c.kind!r}: cannot prove containment, failing closed")

def authorize(token: CapabilityToken, resource: str, action: str, op_args: dict) -> None:
    if token.audience != "org-b/sandbox-gateway":
        raise ScopeViolation(f"audience mismatch: {token.audience!r}")
    # Re-derive effective scope: intersect constraints across the subject chain.
    matching = [(r, a, cs) for (r, a, cs) in token.scope if r == resource and a == action]
    if not matching:
        raise ScopeViolation(f"no scope entry for {resource}:{action}")
    # Every matching entry's constraints must all hold (intersection semantics).
    for (r, a, constraints) in matching:
        for c in constraints:
            if not _evaluate_constraint(c, op_args):
                raise ScopeViolation(
                    f"constraint {c.kind}={c.value!r} not satisfied for {resource}:{action} "
                    f"with args {op_args!r} after local canonicalization"
                )
    # Unimplemented constraint kinds anywhere in the chain are fatal, not skipped.
    for (_, _, constraints) in matching:
        for c in constraints:
            if c.kind not in _IMPLEMENTED_CONSTRAINT_KINDS:
                raise ScopeViolation(f"unknown constraint {c.kind!r} in effective scope")

# Trace of the observed breach, now refused:
tok = CapabilityToken(
    issuer="org-a/control-plane",
    audience="org-b/sandbox-gateway",
    sub_chain=("org-a/planner-7", "org-a/exec-broker"),
    scope=(("sandbox://exec", "run", frozenset({Constraint("path_prefix", "/work/task-42")})),),
    delegation_depth=1,
)
authorize(tok, "sandbox://exec", "run", {"cwd": "/work/task-42/../task-43/steal"})
# -> ScopeViolation: constraint path_prefix='/work/task-42' not satisfied ...
