# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-an-mcp-tool-boundary-and-why-provenance-labels-alone-do-not-bound-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-an-mcp-tool-boundary-and-why-provenance-labels-alone-do-not-bound-it.warrant.json
# Markdown SHA-256:   a3e5883be7d44e3534e9876b41cf087afdf9a8a91e22d8c542fd44ffe727edfd
# Code AST SHA-256:   dbe13c1c2a00ff62c70b0487d79a1e61093effbbc6c5a84805857493a01be8ca
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a privileged tool parameter cannot be attributed to a trusted origin
    and the sink is not confined. Indicates derivation-taint, not containment-taint."""
    pass


PRIVILEGED_SINKS = {"write_file": ["path"], "exec": ["cmd"], "http_get": ["url"]}


def admit_tool_call(call: dict, trusted_spans: list[str], untrusted_read_this_episode: bool,
                    workspace_root: str) -> None:
    tool = call.get("tool")
    args = call.get("args", {})
    if tool not in PRIVILEGED_SINKS:
        return  # non-privileged sink: attribution gate does not apply

    for param in PRIVILEGED_SINKS[tool]:
        value = args.get(param)
        if value is None:
            continue

        # (1) provenance by containment: value literally present in a trusted span
        if any(value in span for span in trusted_spans):
            continue

        # (2) unattributable value + untrusted read in episode => derivation-taint suspect
        if untrusted_read_this_episode:
            # (3) confinement check: is the sink clamped to the workspace?
            if tool == "write_file" and not _within(value, workspace_root):
                raise TaintLaunderingError(
                    f"privileged param {param!r}={value!r} is unattributable to trusted "
                    f"context, appeared after an untrusted MCP read, and escapes "
                    f"workspace root {workspace_root!r}; refusing admission"
                )


def _within(path: str, root: str) -> bool:
    import os
    try:
        return os.path.commonpath([os.path.abspath(path), os.path.abspath(root)]) == os.path.abspath(root)
    except ValueError:
        return False
