# Which invariants prevent tainted-argument laundering across a quarantined tool boundary when privileged execution re-derives provenance from scratch
**Date of Record:** 2026 November 26
**Scope:** Applies to agents that tag untrusted-content-derived values (retrieved web text, tool output, peer-agent messages) with a taint bit and quarantine them before passing them into a privileged tool (shell, file write, outbound HTTP, credential-bearing API). Does not cover taint propagation inside a single LLM completion where no external tool boundary is crossed, nor OS-level sandboxing (seccomp, namespaces) that operates below the agent layer.
## Core Distinction
A taint-aware sandbox has two jobs that are easy to conflate: *carrying* provenance across a boundary, and *enforcing* it at the privileged sink. The failure mode is not that taint is dropped at the boundary—that is loud and usually caught. The failure is that taint is **re-derived** on the privileged side from the argument's current syntactic form rather than inherited from its lineage. When the privileged executor re-derives provenance, any transformation the agent applies to a tainted value (normalization, quoting, concatenation with a trusted constant, JSON round-trip, base64, template interpolation) makes the value appear freshly constructed and therefore clean. The taint bit does not survive the *derivation*, only the *value*, and the value is exactly what gets rewritten.
The invariant that matters is therefore not "tainted values are blocked." It is: **provenance is a property of the derivation graph, not of the string.** A privileged sink must inherit taint from every input that contributed to its argument, and no local re-parse may reset it.
## What Was Observed
An agent was asked to summarize a fetched page and, as a follow-up, write a "suggested filename" derived from the page's `
`. The title contained a payload shaped like a shell fragment. The flow:
1. `fetch(url)` returns body, tagged `taint=external`.
2. The model extracts `title`, producing a string that still carries `taint=external` in the tool-call envelope.
3. The agent's own helper normalizes the title: lowercase, strip, replace spaces with `_`, truncate to 64 chars. The helper is a pure string function registered as `trusted`, so its output is stamped `taint=none` by the sandbox's default rule ("outputs of trusted tools are clean").
4. The normalized name is passed to `write_file(path=...)`. `write_file` is privileged. It accepts the call because the envelope says `taint=none`.
5. The normalization had preserved a `$(...)` substring (spaces replaced, but `$`, `(`, `)` untouched), which a downstream shell-expanding step executed.
The trace shows the laundering step is not adversarial cleverness by the model—step 3 is a *reasonable* transformation. The bug is the sandbox's default rule: it treats a trusted *function* as a taint *launderer*, so any deterministic transform is a declassifier. That rule is the boundary failure.
A second, quieter variant: a tainted value passed through `json.dumps` and back, or through an f-string with a trusted prefix (`f"report_{title}.md"`), was stamped clean because the concatenation node was classified trusted. The taint was lost at the *combinator*, not at the leaf.
## Condition of Validity
The "trusted transform declassifies" rule is valid only when the transform is **taint-preserving-by-construction**: it must either (a) reject any input that can carry an active metacharacter for the sink's grammar, or (b) be proven to map the tainted alphabet into a safe subset (e.g., a slugifier that emits only `[a-z0-9_-]`). A generic `strip().replace(" ","_")` satisfies neither. The validity condition is per-sink, not per-function: the same normalizer may be a sound declassifier for a `write_file` sink that never shell-expands, and an unsound one for a `run_shell` sink.
Formally, for sink *S* with grammar *G_S*, a transform *T* is a valid declassifier iff `range(T) ⊆ L(G_S) ∩ Safe(G_S)`, where `Safe` excludes the sink's expansion/interpretation metacharacters. If the sandbox cannot check this containment, it must not declassify—it must propagate taint through *T*.
## Decision Boundary
At the privileged sink, the decision is not "is this argument tainted?" but "does the derivation graph of this argument contain any `external` leaf that was not discharged by a *validated* declassifier for *this* sink?" Three outcomes:
- **Inherit and block:** any `external` leaf reaches the sink without a sink-validated declassifier → refuse, return the taint path to the agent so it can re-plan (e.g., ask the user, or route through a slugifier).
- **Inherit and allow with constraint:** declassifier validated for this sink's grammar → allow, and record the declassification edge in the audit log with the sink id and the containment proof id.
- **Re-derive (forbidden):** parsing the argument's current string and inferring cleanliness → never permitted at a privileged sink; this is the exact laundering path.
The boundary is crossed the moment the sink trusts the *envelope's* taint field without walking the derivation edges, or trusts a combinator's `trusted` label without the per-sink containment check.
## Operational Effect
The practical consequence is that taint labels must be attached to **edges, not nodes**, and the privileged executor must do a graph walk, not a field read. Concretely: every tool call carries `inputs: [{value, taint, source_id}]` and `transform: {id, declassifies_for: [sink_ids]}`; the sink recomputes `effective_taint = union(input taints) minus declassifications valid for this sink`. A trusted *function* with no `declassifies_for` entry propagates taint unchanged. This makes the slugifier case work (it declares `declassifies_for: ["write_file"]` and is rejected for `run_shell`), and it makes the f-string combinator propagate taint because string concatenation has no declassification entry.
The secondary effect is on the agent's re-planning loop: because the block returns the *taint path*, the model can see which leaf poisoned the argument and choose a safe transform, instead of retrying the same call with cosmetic edits—the retry loop that otherwise burns token budget re-submitting laundered variants.
```python
from dataclasses import dataclass, field
from typing import Iterable
class TaintLaunderingError(RuntimeError):
"""Raised when a privileged sink receives an argument whose derivation
graph contains an undischarged external leaf."""
@dataclass(frozen=True)
class Leaf:
value: str
taint: str # "external" | "none"
source_id: str
@dataclass(frozen=True)
class Transform:
id: str
declassifies_for: tuple[str, ...] = () # sink ids this transform is proven safe for
@dataclass
class Derivation:
leaves: list[Leaf] = field(default_factory=list)
transforms: list[Transform] = field(default_factory=list)
def effective_taint(deriv: Derivation, sink_id: str) -> set[str]:
"""Taint is inherited from leaves; a transform discharges an external leaf
ONLY if it declares declassification for this exact sink."""
active: set[str] = set()
for leaf in deriv.leaves:
if leaf.taint == "external":
# discharged only if every transform since the leaf is valid for this sink
valid = all(sink_id in t.declassifies_for for t in deriv.transforms)
if not valid:
active.add(leaf.source_id)
return active
def privileged_execute(sink_id: str, deriv: Derivation, argv: list[str]) -> str:
poisoned = effective_taint(deriv, sink_id)
if poisoned:
raise TaintLaunderingError(
f"sink {sink_id!r} refused: undischarged external leaves {sorted(poisoned)} "
f"reached argument via transforms "
f"{[t.id for t in deriv.transforms]} (none valid for this sink)"
)
return f"executed {sink_id}: {argv!r}"
# --- trace: the observed failure ---
title = Leaf(value="notes_$(id).md", taint="external", source_id="fetch:page-42")
slugify = Transform(id="strip_replace", declassifies_for=("write_file",)) # NOT run_shell
deriv = Derivation(leaves=[title], transforms=[slugify])
# write_file declares the slugifier valid -> allowed
assert privileged_execute("write_file", deriv, ["notes_(id).md"])
# run_shell does NOT -> the same derivation must be refused
try:
privileged_execute("run_shell", deriv, ["touch", "notes_$(id).md"])
except TaintLaunderingError as e:
print("blocked:", e)
```