# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-least-privilege-tool-scopes-when-a-delegated-a2a-warrant-s-scope-set-is-broader-than-the-executing-mcp-server-s-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-least-privilege-tool-scopes-when-a-delegated-a2a-warrant-s-scope-set-is-broader-than-the-executing-mcp-server-s-policy.warrant.json
# Markdown SHA-256:   324bedf12e000a978fd3f1ebbd384eed4671afc1d20d1cfeed82c05a3118de9c
# Code AST SHA-256:   106c32f1d6878d39b135cf682f6944ef61283b960190405d8e5dd94d159e5d1d
# Verified Classes:   ScopeEscalationError, Invocation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ScopeEscalationError(RuntimeError):
    """Raised when a delegated call would exceed the enforceable PaC grant."""


@dataclass(frozen=True)
class Invocation:
    tool: str
    args: dict


def enforce_least_privilege(
    invocation: Invocation,
    warrant_scope: dict,
    pac_grant: dict,
) -> None:
    """Intersect warrant scope against the *evaluated* PaC grant at argument level.

    pac_grant is expected to be parameter-scoped:
        {"db.read": {"table": {"orders", "customers"}}}
    A tool-level grant (no parameter map) cannot constrain arguments and must
    fail closed for any argument not explicitly enumerated.
    """
    rule = pac_grant.get(invocation.tool)
    if rule is None:
        raise ScopeEscalationError(
            f"no PaC grant for tool {invocation.tool!r}; fail-closed deny"
        )

    # Tool-level grant (no parameter map) cannot enforce argument-level scope.
    if not isinstance(rule, dict):
        raise ScopeEscalationError(
            f"PaC grant for {invocation.tool!r} is tool-scoped; "
            f"cannot constrain arguments {invocation.args!r}; deny"
        )

    for param, value in invocation.args.items():
        allowed = rule.get(param)
        if allowed is None:
            raise ScopeEscalationError(
                f"argument {param!r} not covered by PaC grant; fail-closed deny"
            )
        if value not in allowed:
            raise ScopeEscalationError(
                f"argument {param}={value!r} outside PaC grant {allowed!r}"
            )
        # Warrant must also permit it; intersection, not union.
        w_allowed = warrant_scope.get(invocation.tool, {}).get(param)
        if w_allowed is None or value not in w_allowed:
            raise ScopeEscalationError(
                f"argument {param}={value!r} outside warrant scope {w_allowed!r}"
            )
