# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-per-tool-privilege-bleed-when-an-mcp-server-enforces-authorization-at-the-session-scope-instead-of-the-call-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-per-tool-privilege-bleed-when-an-mcp-server-enforces-authorization-at-the-session-scope-instead-of-the-call-scope.warrant.json
# Markdown SHA-256:   b2f3c7ec7ee2446aed8baa928e4967eea787b5d80395a2e8e5efa2eb2f20a96d
# Code AST SHA-256:   dbd944d065c64cd896eebba12ad20035ce1321c887d7f9c56755052b0dc6f543
# Verified Classes:   PrivilegeBleedError, SessionGrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import posixpath
from dataclasses import dataclass
from typing import Callable


class PrivilegeBleedError(RuntimeError):
    """Raised when a tool call's normalized arguments imply a privilege tier
    the session grant does not cover, or when the tier cannot be proven."""
    pass


@dataclass(frozen=True)
class SessionGrant:
    principal: str
    # tier -> whether the session may exercise it
    tiers: dict[str, bool]


def normalize_path(raw: str, workspace_root: str) -> str:
    # Single normalization routine shared with the server's dispatcher.
    # posixpath.normpath collapses '..' and '.' deterministically; the
    # workspace root is itself normalized first so the prefix check is sound.
    root = posixpath.normpath(workspace_root).rstrip("/") + "/"
    joined = posixpath.normpath(posixpath.join(root, raw))
    return joined


def tier_for_read(normalized: str, workspace_root: str) -> str:
    root = posixpath.normpath(workspace_root).rstrip("/") + "/"
    if normalized == root.rstrip("/") or normalized.startswith(root):
        return "read:workspace"
    return "read:outside"


def pre_dispatch_check(
    tool_name: str,
    arguments: dict,
    grant: SessionGrant,
    workspace_root: str,
    tier_resolver: Callable[[str, str], str],
) -> str:
    """Reconstruct the server's privilege predicate before the call leaves
    the client. Returns the proven tier or raises PrivilegeBleedError."""
    if tool_name != "fs.read":
        raise PrivilegeBleedError(
            f"no argument-level predicate modeled for tool {tool_name!r}; "
            "refusing to dispatch on a name-only grant"
        )
    raw = arguments.get("path")
    if not isinstance(raw, str) or not raw:
        raise PrivilegeBleedError(
            f"fs.read called without a usable path argument: {arguments!r}"
        )
    normalized = normalize_path(raw, workspace_root)
    tier = tier_resolver(normalized, workspace_root)
    if not grant.tiers.get(tier, False):
        raise PrivilegeBleedError(
            f"privilege bleed: principal={grant.principal!r} tool={tool_name!r} "
            f"raw_path={raw!r} normalized={normalized!r} tier={tier!r} "
            f"granted_tiers={sorted(t for t, ok in grant.tiers.items() if ok)}"
        )
    return tier


# Trace of the observed failure, now bounded:
grant = SessionGrant(principal="agent-A", tiers={"read:workspace": True, "read:outside": False})
try:
    pre_dispatch_check(
        "fs.read",
        {"path": "../.env"},
        grant,
        workspace_root="/srv/workspace",
        tier_resolver=tier_for_read,
    )
except PrivilegeBleedError as exc:
    # Halt before dispatch; do not write the (would-be) result into context.
    print(f"BLOCKED: {exc}")
