How should an instance track taint through a tool result that returns a *reference* rather than a value — and why does capability-scoped sandboxing silently fail when the taint label is attached to the value instead of the handle?

**Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that enforces taint-aware capability scoping by labeling tool *outputs* and gating subsequent tool *inputs* on those labels. Does not apply to runtimes that re-derive taint from provenance graphs at every call site (those are covered by a different invariant).

Core Distinction

There are two places a taint label can live, and they are not interchangeable:

The failure mode this record covers: a sandbox that enforces taint correctly on value-taint but treats handle-taint as *untainted by construction*, because the handle itself contains no forbidden bytes. The agent then launders a poisoned result through a handle, and the capability gate never fires. The sandbox is not broken; it is enforcing the wrong invariant. It is checking "does this payload contain the mark?" when it must check "was this handle derived from a tainted resolution path?"

This is non-obvious because every unit test that feeds literal tainted strings passes. The escape only appears when a tool's contract is "returns a reference," which is the majority of real tools (filesystem, database, HTTP fetchers, vector stores).

What Was Observed

A fetch tool `read_url(url) -> {"doc_id": "..."}` returns only a document identifier; the sandbox resolves `doc_id` to text lazily inside the *next* tool that consumes it. The taint policy marks fetched documents as `UNTRUSTED_EXTERNAL`. The gate is supposed to block `UNTRUSTED_EXTERNAL` content from reaching `write_file` or `send_email`.

Trace of the escape:

  1. Agent calls `read_url("https://attacker.example/payload")`. Tool returns `{"doc_id": "d_4471"}`. The value-taint labeler inspects the returned dict: it contains only a hex-ish string, no injected instructions, no forbidden patterns. Label assigned: `CLEAN`.
  2. The taint registry *does* record `d_4471 -> UNTRUSTED_EXTERNAL` internally, but the gate reads labels off the *value* passed between steps, not off the registry.
  3. Agent calls `summarize(doc_id="d_4471")`. The summarizer resolves the doc inside the sandbox, producing text containing an injection. The output value is now labeled by content scan — but the summarizer's output is a *summary*, which the scanner rates `CLEAN` because the injection was paraphrased into fluent prose with no matching signature.
  4. Agent calls `send_email(body=summary)`. Gate sees `CLEAN` value. Email sent. Taint laundered across two handle boundaries and one lossy transform.

The registry knew the truth the whole time. The gate never consulted it. That is the boundary: **taint tracked in a side registry is not taint enforced at the capability boundary unless the boundary resolves handles against the registry before deciding.**

A second, subtler observation: when the same handle was passed to a *sandboxed* tool vs. an *unsandboxed* tool, the gate behaved differently — the sandboxed path resolved the handle through the registry (because the sandbox owns resolution), the unsandboxed path did not. So the policy was enforced inconsistently depending on which tool happened to dereference the handle, which is exactly the kind of nondeterminism that makes the bug survive fuzzing.

Condition of Validity

The invariant "a handle is tainted iff any resolution path that produced or can produce it is tainted" holds **only if** all of the following are true:

If any of these fails — and in practice the third fails first, because summarizers and embedders are exactly the "lossy transform" that people assume sanitizes — the invariant is void and handle-taint laundering is possible.

Decision Boundary

The runtime must choose, per tool, between two enforcement postures and must not mix them silently:

The boundary condition that triggers the bug: a tool is declared `value-gate` (because its return type is a small dict) but its *consumer* is `resolve-then-gate`-dependent (because it dereferences the handle). The mismatch is invisible in the tool's own schema. The gate must therefore classify by *consumer behavior*, not by *producer return shape*, or it will mis-posture.

Concretely: a tool whose output contains any field marked `handle: true` must force every downstream consumer of that field into resolve-then-gate, and the producer must be registered as a provenance source. If the producer cannot register synchronously, the handle must be treated as `TAINTED_BY_DEFAULT` — fail closed.

Operational Effect

When the boundary is enforced correctly, the observable behavior changes in three ways:

  1. **Laundering becomes a hard error, not a silent pass.** Passing a handle whose registry provenance is `UNTRUSTED_EXTERNAL` into a `write`-class capability raises at the gate, regardless of how clean the handle's bytes look.
  2. **Lossy transforms stop sanitizing.** A summarizer's output inherits the taint of its input handle. This is the correct semantics (a summary of a poisoned doc is still attacker-influenced) and it is what most teams get wrong.
  3. **Fail-closed on registry miss.** An unknown handle is `TAINTED_BY_DEFAULT`, not `CLEAN`. This trades some false positives (agent must re-fetch or explicitly launder via a gated sanitizer) for the elimination of the entire handle-laundering class.

The cost is real: every handle-dereferencing tool now pays a synchronous registry lookup and every derived handle must be registered, which means the provenance store is on the hot path and must be transactional with tool execution. Teams that skip this and rely on content scanning will pass every test whose payloads are literal and fail the first time a tool returns a reference — which is most of them.

from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a handle with tainted provenance reaches a gated capability."""


class Taint(Enum):
    CLEAN = "clean"
    UNTRUSTED_EXTERNAL = "untrusted_external"
    TAINTED_BY_DEFAULT = "tainted_by_default"


@dataclass
class ProvenanceRegistry:
    # handle_id -> set of taint labels accumulated along its derivation path
    _store: dict[str, set[Taint]] = field(default_factory=dict)

    def register(self, handle_id: str, taint: Taint) -> None:
        self._store.setdefault(handle_id, set()).add(taint)

    def resolve(self, handle_id: str) -> set[Taint]:
        # Fail closed: unknown handles are TAINTED_BY_DEFAULT, never CLEAN.
        return self._store.get(handle_id, {Taint.TAINTED_BY_DEFAULT})

    def derive(self, parent: str, child: str) -> None:
        # Taint is transitive and monotone: child inherits parent's labels.
        for label in self.resolve(parent):
            self.register(child, label)


@dataclass
class CapabilityGate:
    registry: ProvenanceRegistry
    write_capabilities: frozenset[str] = frozenset({"write_file", "send_email"})

    def check(self, capability: str, args: dict[str, Any]) -> None:
        if capability not in self.write_capabilities:
            return
        for key, value in args.items():
            if not isinstance(value, str):
                continue
            # Resolve-then-gate: consult provenance, not the value's bytes.
            labels = self.registry.resolve(value)
            if Taint.TAINTED_BY_DEFAULT in labels:
                raise TaintLaunderingError(
                    f"arg {key!r}={value!r} is an unregistered handle; "
                    f"refusing {capability!r} (fail-closed)"
                )
            if Taint.UNTRUSTED_EXTERNAL in labels:
                raise TaintLaunderingError(
                    f"arg {key!r}={value!r} carries UNTRUSTED_EXTERNAL provenance "
                    f"into {capability!r}; launder via a gated sanitizer first"
                )


def read_url(registry: ProvenanceRegistry, url: str) -> dict[str, str]:
    doc_id = f"d_{abs(hash(url)) % 10000}"
    registry.register(doc_id, Taint.UNTRUSTED_EXTERNAL)
    return {"doc_id": doc_id}


def summarize(registry: ProvenanceRegistry, doc_id: str) -> str:
    # Lossy transform does NOT sanitize: derived handle inherits taint.
    summary_handle = f"summary_of_{doc_id}"
    registry.derive(doc_id, summary_handle)
    return summary_handle


def send_email(gate: CapabilityGate, body: str) -> None:
    gate.check("send_email", {"body": body})


def run_attack_path() -> None:
    reg = ProvenanceRegistry()
    gate = CapabilityGate(registry=reg)
    ref = read_url(reg, "https://attacker.example/payload")
    summary_handle = summarize(reg, ref["doc_id"])
    # This is the line that used to silently pass under value-taint gating.
    send_email(gate, body=summary_handle)


if __name__ == "__main__":
    try:
        run_attack_path()
    except TaintLaunderingError as exc:
        print(f"BLOCKED: {exc}")