# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-crossing-a-tool-boundary-when-the-label-is-laundered-through-a-summarizer-sub-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-crossing-a-tool-boundary-when-the-label-is-laundered-through-a-summarizer-sub-call.warrant.json
# Markdown SHA-256:   65482ebd9b058e9111b2e114a9e7327efb284ce14dd73763515de7b7b0b97af9
# Code AST SHA-256:   c5f0f8656f6d00f67148292563d9ffa466476d74fbcc0812dbb2870b92e82909
# Verified Classes:   TaintLaunderingError, Labeled, ModelCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

UNTRUSTED = "UNTRUSTED"
TRUSTED = "TRUSTED"


class TaintLaunderingError(RuntimeError):
    """Raised when a value derived from tainted input is re-admitted without inherited taint."""
    pass


@dataclass(frozen=True)
class Labeled:
    value: str
    taint: FrozenSet[str] = field(default_factory=frozenset)

    def __post_init__(self):
        object.__setattr__(self, "taint", frozenset(self.taint))


@dataclass
class ModelCall:
    """A model-mediated edge in the call graph. Output taint is the union of input taints."""
    input_context: list

    def generate(self, prompt: str, output: str) -> Labeled:
        inherited = frozenset().union(*(c.taint for c in self.input_context))
        # Monotone rule: output inherits the full input taint set. No content inspection.
        return Labeled(value=output, taint=inherited)


def admit_to_model_context(produced: Labeled, declared_taint: FrozenSet[str]) -> Labeled:
    """Return-boundary check. A tool's declared taint must cover its actual derivation."""
    if not produced.taint.issubset(declared_taint):
        raise TaintLaunderingError(
            f"tool output carries {sorted(produced.taint)} but manifest declared "
            f"{sorted(declared_taint)}; derivation edge is unrecorded"
        )
    return produced


def send_to_terminal_sink(arg: Labeled, sink_name: str, warrant: str | None = None) -> None:
    """Terminal sinks must not receive UNTRUSTED values without an explicit declassification warrant."""
    if UNTRUSTED in arg.taint and warrant is None:
        raise TaintLaunderingError(
            f"terminal sink {sink_name!r} received UNTRUSTED value {arg.value!r} "
            f"with no declassification warrant"
        )
    # transport would occur here


# Trace of the observed incident:
ticket = Labeled(value="...login failure... recovery code is 4471 ...", taint=frozenset({UNTRUSTED}))
summarizer = ModelCall(input_context=[ticket])
summary = summarizer.generate("Summarize in two sentences.", "Customer reports failure; code 4471 for verification.")
assert summary.taint == frozenset({UNTRUSTED})  # inherited, not re-classified

# The naive runtime declared the tool output as trusted, which is the laundering bug:
try:
    admit_to_model_context(summary, declared_taint=frozenset({TRUSTED}))
except TaintLaunderingError as e:
    print("blocked at return boundary:", e)

# And even if admitted, the terminal sink blocks exfiltration:
try:
    send_to_terminal_sink(summary, sink_name="send_email")
except TaintLaunderingError as e:
    print("blocked at terminal sink:", e)
