# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-least-privilege-when-a-capability-token-s-scope-is-narrower-than-the-tool-s-declared-schema-the-silent-widening-boundar.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-least-privilege-when-a-capability-token-s-scope-is-narrower-than-the-tool-s-declared-schema-the-silent-widening-boundar.warrant.json
# Markdown SHA-256:   047ff723309aa4f0fd0360ee6d5c720fd70b5707a331289c2a0f363fcf106383
# Code AST SHA-256:   a1e27bb3f55df5f84847192d4f2fa60a21ad3789ec4b678162e180fe31a2e925
# Verified Classes:   ScopeViolation, CapabilityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import os
from dataclasses import dataclass
from typing import Any, Callable


class ScopeViolation(RuntimeError):
    """Raised when the committed argument tuple escapes the capability scope."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    verb: str
    resource_prefix: str
    id_range: tuple[int, int] | None = None
    defaults_forbidden: frozenset[str] = frozenset()


def commit(args: dict[str, Any], schema_defaults: dict[str, Any]) -> dict[str, Any]:
    """Reify the call: inject defaults, canonicalize paths. Must be idempotent."""
    committed = {**schema_defaults, **args}
    if "path" in committed:
        committed["path"] = os.path.realpath(committed["path"])
    return committed


def enforce(token: CapabilityToken, committed: dict[str, Any]) -> None:
    """Enforce on the committed tuple, not the declared one."""
    for field in token.defaults_forbidden:
        if field in committed:
            raise ScopeViolation(
                f"field {field!r} is forbidden by scope but present in committed tuple"
            )
    path = committed.get("path", "")
    if not path.startswith(token.resource_prefix):
        raise ScopeViolation(
            f"committed path {path!r} escapes scope prefix {token.resource_prefix!r}"
        )
    if token.id_range is not None:
        try:
            doc_id = int(path.rsplit("/", 1)[-1].split(".")[0])
        except (ValueError, IndexError) as exc:
            raise ScopeViolation(f"cannot parse id from {path!r}") from exc
        lo, hi = token.id_range
        if not (lo <= doc_id <= hi):
            raise ScopeViolation(f"id {doc_id} outside scoped range [{lo},{hi}]")


def invoke(
    token: CapabilityToken,
    declared_args: dict[str, Any],
    schema_defaults: dict[str, Any],
    tool: Callable[[dict[str, Any]], Any],
) -> Any:
    committed = commit(declared_args, schema_defaults)
    # Idempotence check: a non-fixed-point commit is itself a scope hazard.
    if commit(committed, {}) != committed:
        raise ScopeViolation("commit() is not idempotent; enforcement point is unsound")
    enforce(token, committed)
    return tool(committed)


if __name__ == "__main__":
    token = CapabilityToken(
        verb="read",
        resource_prefix="/srv/billing/invoices/",
        id_range=(1000, 1999),
        defaults_forbidden=frozenset({"follow_symlinks", "recursive"}),
    )
    # Model declares the in-scope call; schema default injects follow_symlinks.
    try:
        invoke(
            token,
            declared_args={"path": "/srv/billing/invoices/1042"},
            schema_defaults={"follow_symlinks": True},
            tool=lambda a: a,
        )
    except ScopeViolation as exc:
        print(f"blocked at commit boundary: {exc}")
