# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-argument-reconstruction-in-a-quarantined-tool-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-argument-reconstruction-in-a-quarantined-tool-sandbox.warrant.json
# Markdown SHA-256:   e2ccf17b9daf9d3676326e0a888cb55a8ccf892f4f12fda2f3c05bdc7c334550
# Code AST SHA-256:   2eaa415c37a2087a3d1685bf44a434899af1b05e440e52d67f3cd2d49861ec85
# Verified Classes:   TaintLaunderingError, Trust, ContextSegment, ToolCall, ToolSchema, TaintSandbox
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaintLaunderingError(RuntimeError):
    """Raised when a tool argument's provenance cannot be structurally verified."""


class Trust(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"


@dataclass(frozen=True)
class ContextSegment:
    segment_id: str
    trust: Trust
    content: str


@dataclass
class ToolCall:
    tool: str
    arguments: dict[str, Any]
    # If the schema declares an argument as a reference, this maps arg name -> segment id.
    references: dict[str, str] = field(default_factory=dict)


@dataclass
class ToolSchema:
    name: str
    # Arguments that MUST be references (no free-text literals permitted).
    reference_args: frozenset[str]
    # Arguments that are free-text; incompatible with taint safety when untrusted context is active.
    free_text_args: frozenset[str]


class TaintSandbox:
    def __init__(self, segments: dict[str, ContextSegment], schemas: dict[str, ToolSchema]):
        self._segments = segments
        self._schemas = schemas

    def _active_untrusted(self) -> bool:
        return any(s.trust is Trust.UNTRUSTED for s in self._segments.values())

    def authorize(self, call: ToolCall) -> None:
        schema = self._schemas.get(call.tool)
        if schema is None:
            raise TaintLaunderingError(f"unknown tool {call.tool!r}; cannot establish schema")

        # Rule 1: free-text arguments are a laundering channel whenever untrusted
        # context is active in the generation window. Refuse, do not inspect.
        if self._active_untrusted() and schema.free_text_args:
            raise TaintLaunderingError(
                f"tool {call.tool!r} declares free-text args {sorted(schema.free_text_args)} "
                f"while untrusted context is active; argument provenance is unverifiable"
            )

        # Rule 2: every reference argument must resolve to a known segment, and
        # the segment must be trusted. Value-identity matching is NOT performed.
        for arg in schema.reference_args:
            if arg not in call.references:
                raise TaintLaunderingError(
                    f"argument {arg!r} of tool {call.tool!r} must be a reference, got a literal"
                )
            seg_id = call.references[arg]
            seg = self._segments.get(seg_id)
            if seg is None:
                raise TaintLaunderingError(f"reference {seg_id!r} does not resolve")
            if seg.trust is Trust.UNTRUSTED:
                raise TaintLaunderingError(
                    f"argument {arg!r} references untrusted segment {seg_id!r}; quarantined"
                )

        # Rule 3: no argument may be present that is neither a declared reference
        # nor a declared free-text slot (prevents schema-smuggling extra params).
        declared = schema.reference_args | schema.free_text_args
        undeclared = set(call.arguments) - declared
        if undeclared:
            raise TaintLaunderingError(
                f"undeclared arguments {sorted(undeclared)} on tool {call.tool!r}"
            )


def dispatch(sandbox: TaintSandbox, call: ToolCall) -> str:
    sandbox.authorize(call)
    return f"dispatched {call.tool} with {call.arguments}"


if __name__ == "__main__":
    segments = {
        "runbook": ContextSegment("runbook", Trust.UNTRUSTED, "rollback --target prod-db-1 --confirm"),
        "config": ContextSegment("config", Trust.TRUSTED, "region=eu-west-1"),
    }
    schemas = {
        "exec_shell": ToolSchema("exec_shell", frozenset(), frozenset({"command"})),
        "set_region": ToolSchema("set_region", frozenset({"region"}), frozenset()),
    }
    sandbox = TaintSandbox(segments, schemas)

    # Laundering attempt: model reconstructs the tainted command as a fresh literal.
    try:
        dispatch(sandbox, ToolCall("exec_shell", {"command": "rollback --target prod-db-1 --confirm"}))
    except TaintLaunderingError as e:
        print(f"blocked: {e}")

    # Sound path: reference-typed argument resolves to a trusted segment.
    print(dispatch(sandbox, ToolCall("set_region", {"region": "eu-west-1"}, {"region": "config"})))
