# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-tool-call-whose-arguments-are-tainted-but-whose-schema-validates-the-label-laundering-boundary-in-mcp-tool-sandboxing.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-tool-call-whose-arguments-are-tainted-but-whose-schema-validates-the-label-laundering-boundary-in-mcp-tool-sandboxing.warrant.json
# Markdown SHA-256:   d71bde523f683a26672038c815f662a492e5625014d24a08670da8a770dfd9d6
# Code AST SHA-256:   a7162c06bc90553433e2504bd539c1ea76aad568995c3b5ff28f852f3710d461
# Verified Classes:   TaintLabel, PrivilegeClass, TaintLaunderingError, Provenance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TaintLabel(Enum):
    CLEAN = 0
    UNTRUSTED_EXTERNAL = 1
    UNTRUSTED_PEER = 2


class PrivilegeClass(Enum):
    READ_LOCAL = 10
    WRITE_LOCAL = 20
    NETWORK_EGRESS = 30


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged tool call's arguments trace to an untrusted
    source through an unmodeled transformation node, i.e. the taint label was
    dropped at a model.extract / summarize / handoff boundary and the schema
    validator passed the laundered bytes."""


@dataclass
class Provenance:
    source_label: TaintLabel
    path: list[str] = field(default_factory=list)
    declassified_by: Optional[str] = None

    def join(self, other: "Provenance") -> "Provenance":
        worst = max(self.source_label.value, other.source_label.value)
        return Provenance(
            source_label=TaintLabel(worst),
            path=self.path + other.path,
            declassified_by=self.declassified_by or other.declassified_by,
        )

    def is_clean(self) -> bool:
        if self.declassified_by is not None:
            return True
        return self.source_label == TaintLabel.CLEAN


# Transformation nodes that MUST propagate taint. An unmodeled node is a
# laundering site; this registry is the allowlist of known-propagating ops.
PROPAGATING_NODES = {"model.extract", "summarize", "reformat", "schema_coerce",
                     "sub_agent_handoff"}


def evaluate_privileged_call(
    tool_privilege: PrivilegeClass,
    argument_provenance: Provenance,
    transformation_nodes: list[str],
) -> None:
    """Gate a privileged MCP tool call. Raises if the argument's dataflow
    reaches an untrusted source through a node that did not propagate taint."""
    unmodeled = [n for n in transformation_nodes if n not in PROPAGATING_NODES]
    if unmodeled:
        raise TaintLaunderingError(
            f"privileged call to {tool_privilege.name} has argument provenance "
            f"through unmodeled transformation node(s) {unmodeled}; taint label "
            f"was dropped and cannot be trusted. Refusing execution."
        )
    if argument_provenance.is_clean():
        return
    raise TaintLaunderingError(
        f"privileged call to {tool_privilege.name} refused: argument traces to "
        f"{argument_provenance.source_label.name} via "
        f"{argument_provenance.path}, no declassifier invoked."
    )


# --- trigger trace ---
page_prov = Provenance(TaintLabel.UNTRUSTED_EXTERNAL, ["web.fetch:doc_page"])
# model.extract produces a fresh str; if the runtime fails to model it, the
# provenance is lost and the argument looks clean. The gate detects the gap.
try:
    evaluate_privileged_call(
        tool_privilege=PrivilegeClass.READ_LOCAL,
        argument_provenance=Provenance(TaintLabel.CLEAN, ["fs.read:path"]),
        transformation_nodes=["model.extract"],
    )
except TaintLaunderingError as e:
    print(f"REFUSED (laundering site detected): {e}")
