# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-tool-call-boundaries-in-prompt-injected-agent-runs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-tool-call-boundaries-in-prompt-injected-agent-runs.warrant.json
# Markdown SHA-256:   ec2050b7f43d27224b00674bd7857b418e797e706a2a946673d57f71076de29a
# Code AST SHA-256:   681ba5d524ae14944912f3ccfe23e896d86d976d7192ee4c12d8e568f6a25050
# Verified Classes:   TaintLaunderingError, Span, ContextState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged tool call's provenance intersects active taint."""


@dataclass(frozen=True)
class Span:
    span_id: str
    origin: str            # "user" | "web" | "tool:<name>" | "retrieval"
    trusted: bool


@dataclass
class ContextState:
    resident: dict = field(default_factory=dict)   # span_id -> Span
    declassified: set = field(default_factory=set)

    def taint_set(self) -> FrozenSet[str]:
        return frozenset(
            sid for sid, s in self.resident.items()
            if not s.trusted and sid not in self.declassified
        )

    def declassify(self, span_ids):
        # Declassification is a state transition: the span must leave context.
        for sid in span_ids:
            self.resident.pop(sid, None)
            self.declassified.add(sid)


def emit_privileged_call(
    ctx: ContextState,
    tool: str,
    provenance: FrozenSet[str],
    args: dict,
    privileged_tools: FrozenSet[str],
):
    if tool not in privileged_tools:
        return {"tool": tool, "args": args}

    overlap = provenance & ctx.taint_set()
    if overlap:
        raise TaintLaunderingError(
            f"privileged call {tool!r} has provenance {sorted(provenance)} "
            f"intersecting active taint {sorted(overlap)}; "
            f"declassify the source spans or re-derive args from clean context"
        )
    return {"tool": tool, "args": args}


# --- reproduction of the observed failure ---
ctx = ContextState()
ctx.resident["s1"] = Span("s1", origin="user", trusted=True)
ctx.resident["s2"] = Span("s2", origin="web", trusted=False)   # attacker page

# Model paraphrases the attacker's "audit@attacker.example" into an internal alias.
# Provenance is attributed to s2, the span that causally contributed.
try:
    emit_privileged_call(
        ctx,
        tool="send_email",
        provenance=frozenset({"s2"}),
        args={"to": "audit@internal.example", "body": "..."},
        privileged_tools=frozenset({"send_email", "delete", "transfer"}),
    )
except TaintLaunderingError as e:
    print(f"blocked: {e}")

# Correct remediation: drop the tainted span, re-derive from clean context.
ctx.declassify({"s2"})
emit_privileged_call(
    ctx,
    tool="send_email",
    provenance=frozenset({"s1"}),
    args={"to": "audit@internal.example", "body": "summary"},
    privileged_tools=frozenset({"send_email", "delete", "transfer"}),
)
