# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-per-tool-least-privilege-at-an-mcp-policy-enforcement-point-when-a-single-tool-call-straddles-two-privilege-scopes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-per-tool-least-privilege-at-an-mcp-policy-enforcement-point-when-a-single-tool-call-straddles-two-privilege-scopes.warrant.json
# Markdown SHA-256:   89e6a5d002846230c7bc5906441c2c0dc94ca54fe467b057e5b9de4a0a8cdb16
# Code AST SHA-256:   70a013df4899d48f8f21eff25403d36a55c6f571c7b424a7a0403ffc8b0a78bf
# Verified Classes:   ScopeResolutionError, ToolDescriptor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import os
from dataclasses import dataclass
from typing import Literal


class ScopeResolutionError(RuntimeError):
    """Raised when a PEP cannot soundly authorize a tool call."""


@dataclass(frozen=True)
class ToolDescriptor:
    name: str
    scope_kind: Literal["name", "argument", "opaque"]
    granted_scope: str | None
    resource_arg: str | None = None


def canonicalize_path(raw: str) -> str:
    # realpath resolves '..' and symlinks; both are required for containment.
    return os.path.realpath(raw)


def authorize_call(desc: ToolDescriptor, args: dict, scope_root: str) -> str:
    if desc.scope_kind == "opaque":
        # A scope entry on an opaque tool is unenforceable; refuse rather than lie.
        if desc.granted_scope is not None:
            raise ScopeResolutionError(
                f"opaque tool {desc.name!r} carries scope {desc.granted_scope!r} "
                "that the PEP cannot enforce; confine it in the runtime instead"
            )
        raise ScopeResolutionError(
            f"opaque tool {desc.name!r} requires runtime confinement, not scope authz"
        )

    if desc.scope_kind == "name":
        if desc.granted_scope is None:
            raise ScopeResolutionError(f"tool {desc.name!r} has no granted scope")
        return desc.granted_scope

    # argument-scoped: resolve-then-authorize
    if desc.resource_arg is None:
        raise ScopeResolutionError(
            f"argument-scoped tool {desc.name!r} missing resource_arg binding"
        )
    raw = args.get(desc.resource_arg)
    if not isinstance(raw, str):
        raise ScopeResolutionError(
            f"tool {desc.name!r} arg {desc.resource_arg!r} not a string path"
        )
    resolved = canonicalize_path(raw)
    root = canonicalize_path(scope_root)
    if resolved != root and not resolved.startswith(root + os.sep):
        raise ScopeResolutionError(
            f"tool {desc.name!r} path escape: raw={raw!r} resolved={resolved!r} "
            f"outside scope root={root!r}"
        )
    return desc.granted_scope


def handle_tools_call(desc: ToolDescriptor, args: dict, scope_root: str) -> None:
    # PEP entry point: resolve before forwarding, record both raw and resolved.
    scope = authorize_call(desc, args, scope_root)
    _forward(desc.name, args, scope)


def _forward(name: str, args: dict, scope: str) -> None:
    pass


# Trace: fs.read with /workspace/../.ssh/id_ed25519 must be denied, not allowed on name.
desc = ToolDescriptor("fs.read", "argument", "read:workspace", resource_arg="path")
try:
    handle_tools_call(desc, {"path": "/workspace/../.ssh/id_ed25519"}, "/workspace")
except ScopeResolutionError as e:
    print("denied:", e)
