# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-mcp-tool-result-before-it-can-be-laundered-into-a-trusted-reasoning-step.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-mcp-tool-result-before-it-can-be-laundered-into-a-trusted-reasoning-step.warrant.json
# Markdown SHA-256:   3a646d3773e173532668c57f621ff902c2ad8aa95221e5a574c4e9386d4828e6
# Code AST SHA-256:   3f5fee480be135efc088c256795343024ed80c2f3791f30c659b9ff1f610ba6a
# Verified Classes:   Taint, Provenance, TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class Taint(Enum):
    NONE = "none"
    UNTRUSTED = "untrusted"


@dataclass(frozen=True)
class Provenance:
    taint: Taint
    sources: FrozenSet[str] = field(default_factory=frozenset)


class TaintLaunderingError(RuntimeError):
    """Raised when a tainted value reaches a privileged sink without declassification."""


PRIVILEGED_SINKS = {"secrets.read", "shell.exec", "summary.write_external"}


def derive_step_output(inputs: list[Provenance]) -> Provenance:
    """Any model-generated output inherits the union of its inputs' taint.

    This is the invariant the naive runtime violates: it treats generated text
    as taint=none because the bytes are not copied. They are derived, so they
    inherit.
    """
    tainted = [p for p in inputs if p.taint is Taint.UNTRUSTED]
    if not tainted:
        return Provenance(Taint.NONE)
    sources: set[str] = set()
    for p in tainted:
        sources |= set(p.sources)
    return Provenance(Taint.UNTRUSTED, frozenset(sources))


def authorize_tool_call(
    tool: str,
    args_provenance: Provenance,
    declassified_by: str | None = None,
) -> None:
    if tool not in PRIVILEGED_SINKS:
        return
    if args_provenance.taint is Taint.UNTRUSTED and declassified_by is None:
        raise TaintLaunderingError(
            f"privileged sink {tool!r} reached from tainted sources "
            f"{sorted(args_provenance.sources)} with no authorized declassifier; "
            f"refusing to execute"
        )
    if declassified_by is not None and declassified_by not in {
        "schema_validator", "human_approval"
    }:
        raise TaintLaunderingError(
            f"declassification of {tool!r} attempted by {declassified_by!r}, "
            f"which is not an authorized declassifier"
        )


# --- trace replay of the observed incident ---
untrusted_file = Provenance(Taint.UNTRUSTED, frozenset({"server:untrusted-fs"}))
planner_scratchpad = derive_step_output([untrusted_file])  # taint propagates
# naive runtime would have produced Provenance(Taint.NONE) here; we do not.
authorize_tool_call("secrets.read", planner_scratchpad)  # raises
