Defend where data changes role
I review my agents for security where data changes role. Reviews found a NaN that became LIMIT NULL and a swapped path check. Boundary-specific checks held where tested—four layers for SQL, with other boundaries still needing attack suites.
By Nelson D’Souza · · 12 min read
- AI Security
- AI Agents
- Production AI
In this note
- A sanitiser for the famous phrases
- What the reviews actually found
- Every finding was a crossing
- Boundary-specific checks
- Into the model's instructions: permit the known good
- Into the agent's context: mark it as data, every time it is read
- From the browser: the server owns tool execution
- Into SQL: layers that each stop something
- Into paths: one validator, at every hop
- Into URLs: block where the server will call
- Into HTML: strict renderers, and no scripts
- Into numbers and keys: parse, then check
- Out to the reader: a redactor that understands streams
- What a boundary cannot stop
My agents read text I don’t control. Alfred, an LLM-maintained knowledge base of mine, ingests tweets, video transcripts, OCR output, PDFs and the articles they link to. Geysera passes customer fields into a DSPy program that optimises marketing offers. The ask agent on this site receives the visitor’s conversation history from the browser and writes its own SQL. Theo Scriptura builds citations from slugs found inside blog posts. Sooner or later each of those values, or something a model wrote after reading it, reaches code that treats it as more than text: a SQL clause, a file path, an object key, a URL the server calls, a page of HTML.
Security reviews of those agents found one bug that involved a dangerous phrase. The rest sat at those crossings, in ordinary code. parseInt turned a bad query parameter into NaN, and SQLite read the resulting LIMIT NULL as no limit. A path-traversal helper was called with its arguments swapped, so the user’s path was never checked. A property test that looked flaky was reporting a real counterexample, the slug constructor. Two of the bugs were in the defence code itself.
Boundary-specific checks held where tested—four layers for the SQL guard, while other boundaries still need dedicated attack suites. I start from one rule: permissions are enforced in code, never left to the prompt.
A sanitiser for the famous phrases#
The usual first defence is to find the dangerous strings and remove them. Geysera’s offer optimiser had exactly that:
def sanitize_for_llm(user_input: str) -> str:
"""Sanitize user input before sending to LLM."""
sanitized = re.sub(r'ignore.*instructions', '', user_input, flags=re.IGNORECASE)
sanitized = re.sub(r'system.*prompt', '', sanitized, flags=re.IGNORECASE)
return sanitized.strip()It reads well, and it catches the attack from every blog post on prompt injection.
What the reviews actually found#
A security review rated it a critical finding, for reasons that apply to every blocklist. Encoding gets past it: a URL-encoded newline, an HTML entity. Unicode gets past it, because a lookalike letter from another alphabet is a different character to a regex and still readable to a model. And paraphrase gets past it. Natural language has endless ways to say “disregard what you were told”, and the attacker only needs one the list doesn’t have.
That was one finding. Reviews of my other agents turned up a longer list, and none of it looked like “ignore previous instructions”. The first three are the ones a code review reads straight past, because each line looks correct on its own:
- A number that was not a number. An Alfred endpoint computed
Math.min(parseInt(limit), 100).parseInt("abc")isNaN,Math.min(NaN, 100)isNaN, and SQLite readsLIMIT NULLas no limit at all. The whole table came back. - A traversal check that never ran. Alfred’s slides endpoint called
ensureWithin(filePath, presDir). The signature is(root, userPath). With the arguments swapped, every request failed with a 400, and the user’s path was never checked at all. - A key that was a prototype. Theo looked up theologians with
TEXTS[slug], where the slug came from post content. The slugconstructorreturnsObject.prototype.constructor, which is truthy, so a function was treated as a source and the citation builder crashed. - Cached content skipped the sanitiser. Alfred sanitised source content once, at extraction, and cached it. When the sanitiser rules changed, every cache hit returned content cleaned by the old rules.
- Forged tool results. The ask agent’s browser sent back the rows each query had returned, so a forged row became something the server’s own model stated as fact.
- Model-generated markup. Alfred renders diagrams and slides that a model writes. The Marp slide renderer had
html: true, which is an XSS (cross-site scripting) surface fed by whatever the model was persuaded to write, and Mermaid’s safe setting was a library default rather than anything the code said. - A callback URL from an agent tool. A Geysera batch tool, callable by agents through MCP, accepted any callback URL. That is server-side request forgery (SSRF): the server can be asked to call its own private network or the cloud metadata endpoint.
- An id that was a path. In Bob the Builder, my delivery-loop CLI,
msg send --task '../../outside'succeeded and wrote outside the intended directory. - A name split across chunks. A redactor that checks each streamed chunk on its own lets a withheld name through when it arrives in two pieces.
Every finding was a crossing#
In each one, data reached a place that treated it as more than data. A customer field became part of the model’s instructions, a tweet part of its context, browser-held rows the server’s evidence, model output HTML. Prompt injection is one case of that general problem, untrusted data crossing into an instruction channel or a capability channel. A regex reads only the surface of the text. The same harmless-looking string is inert in a log line and dangerous in filepath.Join.
Most of these crossings have a classical fix, because a path, a URL, a SQL clause and an object key each have a grammar that code can enforce. The crossing into the model’s context is the exception. There is no parameterised query for a prompt: instructions and data arrive as the same tokens, and nothing in the model is guaranteed to keep them apart. That’s why the boundaries after it carry most of the weight.
So the design question is where each piece of data changes role. Every such place is a boundary, and each gets its own check, written for what that boundary does:
| Data | The role it takes | The check at that boundary |
|---|---|---|
| A customer field (Geysera) | part of the model’s instructions | an allowlist of known values, or a structured parameter |
| A tweet, transcript, OCR result, PDF or article (Alfred) | the agent’s context | the read tool marks it as data; the sanitiser runs on extraction and on retrieval |
| Conversation history from the browser (ask agent) | the server’s evidence | the history carries call ids only; the server re-runs every tool call |
| The model’s SQL (ask agent) | a query | one SELECT or WITH, one prepared subquery, a read-only transaction, a 100-row cap, a 2 s worker timeout |
| A task id (Bob the Builder) or a user path (Alfred) | a path | one allowlist validator at every hop; the trusted root passed first |
| A callback URL from an agent tool (Geysera) | a URL the server calls | scheme, localhost, private, link-local, metadata and internal-host checks, at submit and before the call |
| Model-written markup (Alfred) | HTML | Mermaid strict in code; slides served with script-src 'none' |
| A query parameter (Alfred) or a slug (Theo Scriptura) | a SQL limit, or an object key | check the parse; read keys through Object.hasOwn |
| The model’s answer (ask agent) | text the reader sees | a streaming redactor that holds back a name split across chunks |
Boundary-specific checks#
Into the model’s instructions: permit the known good#
The Geysera fix replaced the sanitiser with an allowlist. A customer segment is one of four values, so the code says so:
VALID_CUSTOMER_SEGMENTS = frozenset({"new", "regular", "vip", "at_risk"})
def validate_customer_segment(segment: str) -> str:
normalized = segment.lower().strip()
if normalized not in VALID_CUSTOMER_SEGMENTS:
raise ValueError(f"Invalid customer segment: {segment!r}")
return normalizedNormalise, check membership, fail closed. An encoded payload, a homoglyph and a paraphrase all fail the same way, because none of them is in the set. Better still is to take structured parameters instead of free text, such as a Literal["professional", "friendly", "formal", "casual"] for tone, and put length and character limits on the few fields that have to stay free text.
The catch is that an allowlist only works where the valid values are few and known. It does nothing for a tweet, which is the next boundary.
Into the agent’s context: mark it as data, every time it is read#
Alfred cannot allowlist a transcript. What it can do is decide where untrusted content gets marked as untrusted, and the decision that held up was the read-tool boundary. Files on disk stay raw and readable. When the agent reads a tweet, transcript, OCR result, PDF or article through its tools, the content is wrapped and marked as data rather than instructions.
The cache bug came from putting the check in the wrong place. Sanitising at extraction runs the check when data enters storage, not when it enters the agent’s context, so a later change to the rules never reaches the cached copy. The fix applies the sanitiser on both the extraction and the retrieval path, so the check now runs where the content becomes context.
None of this makes the model immune to instructions inside a tweet. Marking content as data lowers the odds that the model obeys it, and that’s all. No wrapper, filter or classifier I know of detects injected instructions reliably. It’s why every boundary after this one exists: assume some injected text gets through, and limit what it can reach.
From the browser: the server owns tool execution#
Checking the history’s structure couldn’t catch a forged row, so the browser no longer sends rows and the route re-runs every tool call itself; The server owns an agent’s truth and its money tells that story with its measured cost.
Into SQL: layers that each stop something#
The ask agent writes SQL, so its query tool is a capability boundary of its own. No single check is enough, so there are several, and the review tested each against a real attack.
- SELECT or WITH only? to Error back to the model: “no: INSERT, SET, COPY”
- SELECT or WITH only? to Wrapped as one subquery, prepared: “yes”
- Wrapped as one subquery, prepared to Read-only transaction: “stops data-modifying CTEs, a second statement”
- Read-only transaction to 100-row cap, 2 s worker timeout: “stops set_config, SELECT INTO”
- 100-row cap, 2 s worker timeout to Rows to the model: “100,000 rows become 100; stops pg_sleep”
The results from that test:
ERR insert / set / copy Only a single SELECT or WITH query is allowed.
ERR delete-cte WITH clause containing a data-modifying statement must be at the top level
ERR multi-escape-paren cannot insert multiple commands into a prepared statement
ERR set_config(... 'off') transaction read-write mode must be set before any query
ERR select-into / for update rejected (read-only transaction)
OK rowcount 100000 → 100 rows, truncated=true
roles count after: 8 (unchanged)The third line is my favourite. An attacker who closes the subquery’s parenthesis, adds a DELETE and opens a new one gets a Postgres error about prepared statements, because the extended protocol refuses more than one command per statement. Nothing had to recognise the word DELETE.
The timeout lives in the worker rather than in Postgres, because the in-browser database doesn’t enforce statement_timeout. A 300 ms limit let a 392 ms query finish. With the worker timeout, a 5-second pg_sleep was stopped at 2 seconds, and the next query ran on a fresh worker.
It’s worth being clear about what sits behind this guard: a copy of the site’s own public data. In the browser that copy belongs to the visitor’s tab, so the guard mostly protects their own experience. On the server the copy outlives a single request, and the read-only transaction is what stops one visitor’s query from changing the rows the next visitor’s answer is read from.
Into paths: one validator, at every hop#
Bob’s fix was a single validator for task ids, used everywhere one becomes a path:
var allowed = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$`)Yes, it’s a regex, but an allowlist one. It describes the whole valid string, so there’s nothing left over to bypass. The harder half is “every hop”. Alfred’s tool layer validated paths correctly, but its CLI called existsSync on the joined path before the tool ran, which leaked whether arbitrary files existed. Validation at one layer protects only the code behind that layer.
The swapped ensureWithin arguments are the same lesson from the other side. The function was correct and was called in six places, and one call site passed the trusted root as the user path. It happened to fail closed. The root is an absolute path and the helper rejects absolute user paths, so the feature was broken rather than open, and nothing in the design made that so.
The fix corrected the call. The helper’s signature is still (root: string, userPath: string), two strings that are both paths, which is the shape where a swap gets past the compiler and the reader alike. The better design makes the swap impossible to write: an options object, ensureWithin({ root, userPath }), or a branded type for the trusted root that a request string can’t satisfy. Until then, argument order is something a review has to check.
Into URLs: block where the server will call#
Geysera’s callback guard rejects non-HTTP schemes, localhost, private and link-local ranges, the cloud metadata addresses and internal hostnames. It runs when a job is submitted and again before the callback is sent.
What it doesn’t do is resolve the hostname. It checks the URL as written, so a public name that resolves to a private address passes. DNS rebinding (a name that resolves one way when checked and another way when called) lives in that gap, and so does a public URL that redirects to a private one, if the HTTP client follows redirects. Closing it means resolving the name once, checking the address and connecting to that address, then doing the same for every redirect. It’s still open, and I’d rather write that down than pretend a string check closes it.
Into HTML: strict renderers, and no scripts#
For Alfred’s model-written markup, Mermaid now sets securityLevel: 'strict' in the code instead of trusting a library default to stay strict. The slide renderer still allows HTML, so the protection moved to the response: served slides carry a content security policy, default-src 'self'; script-src 'none'. If injected text persuades the model to write a script tag into a slide, the browser won’t run it, and an image pointed at someone else’s server won’t load.
This site’s ask panel has no HTML sink at all. Every answer, cell and column name renders as a React text node, and a browser test with <img onerror> and <script> in those places rendered everything as text.
Into numbers and keys: parse, then check#
The LIMIT NULL fix checks the parse, Number.isNaN(parsed) ? 20 : parsed, before the value goes anywhere near SQL. The constructor fix is an accessor that checks Object.hasOwn before reading. Any lookup keyed on untrusted input needs hasOwn, a Map or an object with no prototype.
A property-based test that generated random slugs found the constructor case. It failed once and passed on the next run, which looks exactly like a flaky test. Running that one file in a loop failed again on the eighth attempt, with the counterexample [["constructor"]]. When the only randomness is in the input, a flaky property test is a counterexample you haven’t read yet.
Out to the reader: a redactor that understands streams#
The last boundary faces outwards, and its check is the one blocklist I kept: a streaming redactor on the server that withholds one former client’s name, with the story and its numbers in An eval is an instrument.
What a boundary cannot stop#
Boundaries limit what injected text can reach. They don’t stop a model from being persuaded. A tweet can still nudge Alfred’s summary of that tweet, a visitor can still steer the ask agent’s tone within what it’s allowed to say, and persistent or multi-turn context poisoning (such as an injected webpage stored in Alfred’s wiki and retrieved in later turns) remains an open boundary that read-only sinks alone do not eliminate. What the structural fixes change is the question. “Will the model obey?” has no reliable answer. “What’s the worst it can do if it does?” has one you can test, one boundary at a time.
The wider field has reached the same place from the model’s side. Simon Willison’s “lethal trifecta” names the combination to avoid: access to private data, exposure to untrusted content, and a way to send data out. An agent with all three can be talked into leaking, whatever its prompt says, so the dependable fix is to remove a leg. Several fixes above cut the third one. The ask panel renders answers as text nodes, so a model-written image link can’t make the browser fetch a URL with data in it. Alfred’s slides can’t load anything from another origin. The callback guard narrows where an agent can make the server send a request.
Boundaries cost something too. Every boundary is code that has to stay correct, and two of the bugs above were in the defence itself: a swapped argument and a cache that skipped the check. I trust the SQL guard because each of its layers was attacked in a test. The others deserve the same.
The weakest evidence is where I’d attack next: the callback guard’s DNS gap, and a redactor and an injection test set that rest on a handful of answers.
Built in: Theo Scriptura, Bob the Builder, Geysera, Alfred