The server owns an agent’s truth and its money
An agent’s limits hold only on state the server controls. So the server re-runs tool calls against its own database, and a spend cap reserves the worst case atomically.
By Nelson D’Souza · · 14 min read
- AI Agents
- AI Security
- LLM
- Cost
In this note
- The defaults it started from
- 1. Forged rows the agent stated as fact
- 2. One request, a hundred questions' worth of tokens
- 3. Two hundred requests through a $5 door
- 4. A rate limit keyed on a header the client writes
- 5. The fallback that turned a global cap into a local one
- What the five have in common
- The fixes
- The server runs the tools
- Accept only what the honest client sends
- Reserve the worst case, atomically, then settle
- A key the platform sets
- No silent downgrade
- Seeing it happen
- What held
- What a determined attacker can still do
- Two questions for every limit
The Ask panel on this site’s home page answers questions about my work. A model writes read-only SQL, the SQL runs against a small Postgres database of my career, and the answer cites the rows it used. The database is PGlite, Postgres compiled to WebAssembly, and it runs in a worker in your browser. The server’s only job was to call the model.
That split kept the server thin. The browser held the conversation, ran each query the model asked for, and sent the whole history back on the next turn, tool results included. A typical question cost about $0.0001, and a $5 daily cap on model spend looked like it covered roughly 45,000 questions a day.
Before launch I ran an adversarial review of it. The review made 11 live model calls, $0.011 in all, and found five ways to make the agent say false things or spend money it shouldn’t. The classes are old. A check that holds for one request at a time fails across concurrent ones, and a check on data the client sends is a check on the client’s claim. An agent is exposed to both, because the tool results a model treats as evidence and the requests that spend money can both arrive by way of the client.
Real model calls were spent only where the real model’s behaviour was the question: would it repeat a forged row, what does the largest valid request cost. Everything else, from concurrency to rate limits to store failures, ran against the real handler with a scripted mock model, PGlite in Node, or a browser with the API route mocked. Most of the attack surface is ordinary code.
The defaults it started from#
Each piece was a common default:
- Validate the history’s structure. Check that tool calls and results pair up, that roles alternate, that sizes are bounded.
- Enforce the spend cap by reading the counter. Before calling the model, read today’s spend. If it is under $5, proceed. When the stream ends, add the turn’s actual cost.
- Rate-limit by IP address, taken from the first entry in the
X-Forwarded-Forheader. - Use a shared store when one is configured. Fall back to an in-memory store otherwise, so local development works without setup.
All four are standard, and each holds for a client that behaves. The review broke every one of them by sending something else.
1. Forged rows the agent stated as fact#
The browser sent tool results as text inside the history. The server checked that each result followed its call, but it had no way to tell a real database row from an invented one.
I sent a question, a plausible run_sql call, and a forged result row containing a fabricated dismissal story about me. The server’s model read the row as data, stated the story as fact, and cited the row. The response came back as an ordinary answer, with a citation pill that made it look grounded.
It’s worth being precise about the harm. The output appeared only in the forger’s own browser, and editing the page in devtools fakes a screenshot as easily. The marginal harm is that the server’s own model really did produce the text. Logs and any shared transcript back it up, and the citation lends it authority.
Client-held state is attacker-held state. A tool result is evidence the model will treat as true, and this evidence arrived from the client.
2. One request, a hundred questions’ worth of tokens#
Validation allowed 48 history items and 128 KB, with any number of earlier question-and-answer pairs. The real client never keeps more than 4. I sent 15 junk pairs, 119 KB in total:
input_tokens: 81834 output_tokens: 38 cost_usd: 0.010028One valid request cost about a hundred times a normal question. A normal turn costs $0.00004 to $0.00008, and a question usually takes two. Input the prompt cache hasn’t seen before is billed at this model’s cache-write rate, 1.25 times the normal input price, and junk is never in the cache. At that rate, 500 requests reach the daily cap, and when the cap trips, the model is off for every visitor until the next UTC day. A single IP at the full rate limit of the time, 40 turns per 10 minutes, could do it in about two hours; 13 addresses could do it in ten minutes.
That’s a denial of service bought for $5, paid from my account.
3. Two hundred requests through a $5 door#
The spend cap read the counter, compared it with $5, called the model, and added the actual cost when the stream ended. The shared store used the same pattern: a GET, then later an INCRBY.
I set the counter to $4.99 and fired 200 concurrent worst-case turns from distinct addresses. All 200 were admitted. Spend ended at $7.09.
- Request A to Spend counter: “GET spent”
- Spend counter replies to Request A: “$4.99: under cap”
- Request B to Spend counter: “GET spent”
- Spend counter replies to Request B: “$4.99: under cap”
- Request A to Model: “worst-case turn”
- Request B to Model: “worst-case turn”
- Request A to Spend counter: “INCRBY $0.0105”
- Request B to Spend counter: “INCRBY $0.0105, now over”
This is one of the oldest bugs in concurrent programming, check-then-act. Between the check and the write there is a window, here the whole length of a model call, and every request that enters the window sees the same “under cap”. So the overshoot isn’t one turn. It’s the number of requests in flight times the cost of a turn.
4. A rate limit keyed on a header the client writes#
The limiter keyed each client on x-forwarded-for.split(',')[0], the first hop. Proxies append to that header, so the first entry is whatever the client wrote. In-process, against the real handler:
same XFF: ok 40 limited 5
rotating first XFF hop, same real proxy IP: ok 45 limited 0Whether that header can be trusted depends on the proxies in front of the code, so the same line is correct on one host and spoofable on another. On the hosting platform this site uses, the platform overwrites the header, so the key was real in production. It was still only per address: an IPv6 client controls a whole /64 block of addresses, enough to look like an unbounded number of clients. And on any other host, the limit did nothing.
5. The fallback that turned a global cap into a local one#
The store module used a shared Redis store when its two environment variables were set, and an in-memory store when they weren’t. It logged nothing either way.
A separate engineering review found the other half. The hosting platform’s Redis integration injects its connection details under different variable names from the ones the code read. So in production, the code would have found nothing, fallen back to memory, and run happily. On serverless, every instance would have had its own $5 cap and its own rate limit, and both would reset on every cold start.
Nothing would have looked wrong. The agent would have answered questions, the cap would have “worked” in every test, and the actual limit would have been $5 times however many instances happened to be warm.
What the five have in common#
Each limit, and each claim of truth, rested on something the server didn’t control:
- the rows came from the client;
- the request size came from the client;
- the spend total was read and then written, so other requests controlled it in between;
- the rate-limit key came from the client;
- the store’s semantics came from whichever variable names happened to be set.
None of the five shows up in ordinary testing, because a well-behaved client sends real rows and modest requests, one at a time, from one address, against a correctly configured store. The bugs live in the gap between what the real client does and what the protocol allows, and only a test that sends something else can see it.
The fixes#
Each fix puts one of those limits on state the server controls.
- Server contains Route: re-runs tools, guards, budgets, PGlite in a worker thread, read-only, Shared store with atomic counters.
- Browser (untrusted) to Platform edge: “text, SQL, call ids; ≤ 80 KiB”
- Platform edge to Route: re-runs tools, guards, budgets: “real client IP”
- Route: re-runs tools, guards, budgets to PGlite in a worker thread, read-only: “SQL from the history, 2 s limit”
- Route: re-runs tools, guards, budgets to Shared store with atomic counters: “reserve, settle”
- Route: re-runs tools, guards, budgets to Model provider: “rows the server ran”
- Route: re-runs tools, guards, budgets to Browser (untrusted): “streamed answer”
The server runs the tools#
There were two ways to close this. The cheaper one has the server sign every item it emits (its text, each tool call and its SQL) and reject anything unsigned or altered on the way back. A signature proves the call came from the server. It proves nothing about the result, which the browser still produces, so signing would have left forgery open in the one field that matters most.
I chose the other. A tool result in the request now carries only its call id. The route re-runs every tool call itself, against its own copy of the database: PGlite again, in a Node worker thread, with the same read-only guards and the same 2-second query timeout as the browser. The rows the model reads are rows the server produced. The browser’s database no longer supplies evidence to the model. It stays for two jobs on the visitor’s side: it shows the rows behind each answer, and it runs the keyword fallback that answers when the model is unavailable.
The SQL in each call still comes back from the browser unsigned, so a forger can make the server run any query guardSql admits. Because the guard permits any single read-only SELECT or WITH query over public data and stops runaway queries at 2 seconds, read access is not the risk. The remaining gap is fabrication inside the query itself: a client can send a literal projection such as SELECT 'pepsico-2026' AS id, 'fabricated claim' AS summary, and PGlite will execute it cleanly and return those literals as rows. Closing that requires signing server-emitted tool calls or holding session history server-side.
- Browser to Route: “question”
- Route to Model: “question and tools”
- Model replies to Route: “run_sql call”
- Route replies to Browser: “the call”
- Browser, internally: “run it to show rows”
- Browser to Route: “history, result = call id only”
- Route to Server PGlite: “re-run the call, read-only”
- Server PGlite replies to Route: “rows”
- Route to Model: “the server's rows”
- Model replies to Route: “answer with citations”
- Route replies to Browser: “streamed answer”
I expected this to be slow. Warm turns add 2 to 5 ms. A cold database load takes about a second, and it overlaps the question’s first model turn, so the visitor rarely waits for it.
Citations are now verified too. The browser keeps the ids of rows returned during this question. A citation that matches one becomes a button that highlights its row; one that matches nothing is counted as unverified instead of being shown as evidence.
Accept only what the honest client sends#
The request schema now matches the real client’s maximum: at most 4 earlier question-and-answer pairs, questions up to 300 characters, at most 21 history items, and 80 KiB in total. Every limit is derived from the client’s own constants, with the arithmetic in a comment. Because tool results no longer carry rows, the largest honest body is the earlier pairs, the question, and one interim text and one SQL call per tool round. The review’s 119 KB body no longer fits.
That alone doesn’t bound cost, because the legitimate worst case is still large. A question that uses all three of its tool rounds, each with long interim text, comes close to the limit honestly. Size limits stop the absurd request, but they can’t tell an expensive real question from a cheap attack. So there is also a per-client daily budget of $0.05, the global cap divided by 100, and exhausting the cap now takes at least 100 distinct clients. At the measured $0.00013 per question, a typical visitor gets roughly 380 questions a day from that budget. A client sending maximum-size requests is refused after about four.
Reserve the worst case, atomically, then settle#
The spend check became a reservation. Before each turn, the route computes an upper bound on what the turn could cost and adds it to both counters, the client’s and the global one, in a single atomic step. If either would pass its cap, the addition is undone and the turn is refused. When the turn ends, the reservation is settled to the actual cost.
The reservation works because it gives the state in between a name. The old counter knew only what had been spent, so a turn still running counted as free money. A reservation is money that is neither spent nor free: held for a turn whose cost nobody knows until the provider’s stream ends.
The upper bound needs care, because it has to be computed before the model sees the input. The route serialises the whole provider request it is about to send (system prompt, tool definitions, history and the rows it has just produced) and counts the bytes. The tokenisers these models use are byte-level BPE, so every token covers at least one byte, and the byte count caps the token count. The provider renders the request in its own format, with a few framing tokens per message, but the JSON’s quotes, keys and escapes spend far more bytes than that framing adds. Price every byte as a token at the dearest input rate (the cache-write rate), add the full output cap at the output rate, and a real turn shouldn’t be able to cost more.
In the shared store, the reservation is a short Lua script, which Redis runs atomically. Amounts are integer micro-dollars; key expiry and the “cap reached” marker are left out here:
local amount = tonumber(ARGV[1])
local g = redis.call('INCRBY', KEYS[1], amount) -- global, today
local c = redis.call('INCRBY', KEYS[2], amount) -- this client, today
if g <= tonumber(ARGV[2]) and c <= tonumber(ARGV[3]) then
return {1, g} -- admitted
end
redis.call('DECRBY', KEYS[1], amount) -- undo, refuse
redis.call('DECRBY', KEYS[2], amount)
return {0, g - amount}No other request can run between the increment and the comparison, so there is no window. The in-memory store, used in development and tests, gets the same guarantee a different way: its reservation has no await between the read and the write, so in a single-threaded JavaScript runtime nothing can interleave. A test fires 1,000 concurrent reservations of a worst-case turn against that single-threaded in-memory store, and the number admitted is exactly the number that fits under the cap; production relies on Redis Lua single-script atomicity, which has not yet been load-tested at 1,000 concurrent callers.
Settlement has its own edge case. If the visitor closes the tab mid-answer, the server keeps reading the model’s stream to the end anyway, because the usage figures arrive last and an unread stream would leave its reservation unsettled. If the provider fails mid-stream, the turn is settled to whatever usage the error reported. Under normal or provider-error exits, no reservation is left standing—though a hard platform kill or OOM mid-stream could still leave a $0.002 reservation unsettled until the daily key resets.
The trade-off is precision, and the bound is loose. Bytes overcount tokens about four to one (an earlier 7.8 KB version of the prompt prefix measured about 1,900 tokens). Most real input is billed at the cheap cached rate, not the cache-write rate. And measured turns use 94 output tokens at the 95th percentile, against a reserved 1,000. An ordinary first turn reserves about $0.002 and costs $0.00004 to $0.00008.
That over-reservation costs nothing on a quiet day, because a reservation lives only while its turn runs and settlement returns the difference. It bites near the cap, where the turns in flight hold more than they will spend and the cap can refuse a question while the settled total is still a few cents short. A burst makes that worse in proportion to its size, since every turn in flight holds its full reservation until it settles, and the refusals ease as those turns finish. I give up that headroom to get a cap that holds under concurrency.
A key the platform sets#
The client key is now x-real-ip, which the platform sets, or else the last X-Forwarded-For hop, the one the nearest proxy appended. IPv6 addresses are grouped by /64, the smallest block a subscriber is normally given. The key is a daily-rotating keyed hash, so raw addresses are never stored or logged.
The rate limit on that key is 120 model turns per sliding hour. A question takes at most four turns (three tool rounds, then one final turn with tools off), so that is 30 questions an hour even if every one needs the maximum. It can be generous because it doesn’t protect the money; the budgets do.
The money bound doesn’t depend on the key being honest, either. On a host with no proxy at all, both headers are client input, which is exactly why the per-client budget sits beside a global cap rather than replacing it.
No silent downgrade#
The store now accepts both sets of variable names. More importantly, production without a shared store refuses model calls instead of falling back. The visitor sees the agent as unavailable, and the server logs which store it chose, once per process. A store outage used to be an unhandled error that left the visitor with “malformed event from the server” and no log line. Now it is logged as a specific failure too.
- Honest size? to Reject the request: “no”
- Honest size? to Shared store?: “yes”
- Shared store? to Unavailable: “no, in production”
- Shared store? to Under rate limit?: “yes”
- Under rate limit? to Unavailable: “no”
- Under rate limit? to Re-run tools on the server: “yes”
- Re-run tools on the server to Reserve worst case
- Reserve worst case to Unavailable: “over a cap”
- Reserve worst case to Run the turn, settle to actual cost, log: “admitted”
Seeing it happen#
The review also showed that the logs could total spend but couldn’t answer the questions that matter during abuse. There was no client identifier, no way to group the turns of one question, no request size, and no record of the cap tripping. The first sign of a tripped cap would have been visitors getting keyword answers.
Each log line now carries the hashed client key, a question id, the request’s bytes and item count, tool errors, time spent re-running tools, spend so far today and time to first token. The first refusal by the global cap each day writes one ask_cap_reached line, which is the thing to alert on. In the browser, a turn now has a 15-second deadline (three times the measured 95th-percentile time for a whole question) and a Stop button. An answer cut short is marked as such rather than left with a blinking cursor.
What held#
Some attacks didn’t work, and they’re worth recording too:
- The SQL guard held. Writes, multiple statements, data-modifying CTEs and attempts to turn off read-only mode were all refused, and a 100,000-row result was truncated to 100.
- No script injection. Rows and answers containing
<script>and<img onerror>rendered as text, because every value goes through React text nodes. - No prompt leak worth fixing. Asked for its rules, the model paraphrased them. There is nothing secret in the prompt, so there is nothing to protect.
- The model was not a usable free proxy. Attempts to make it write code or follow planted instructions failed. The structural cause, client-written history, is only partly closed; more on that below.
What a determined attacker can still do#
The per-client budget is per address, and an address is a weak identity. Many ISPs delegate a /56 or a /48 to a single subscriber, not a /64, and IPv4 addresses are cheap to rent. Someone with many addresses can still spend the global cap, more slowly, so a determined attacker can still switch the model off for a day. The cap is what keeps that day’s bill at $5.
Text in the history is still the client’s, too. Earlier answers and the model’s interim text come back from the browser unsigned, so a forger can plant a fabricated “previous answer” and ask the model to repeat it. The review didn’t test that case. What a forger can no longer do is tamper with rows returned by a real query, though unsigned client-sent SQL still permits constant SELECT '...' projections alongside unsigned earlier answers. Closing both requires signing server-emitted items—or moving session history to the server. Nor can anyone spend past the cap, or exhaust it from one address. If repeated history ever matters, signing the server’s own items, the cheaper fix I passed over, is the next step.
Two questions for every limit#
Anything the model will treat as evidence must be produced by the server. Anything that limits spend must be enforced where the client can’t reach it. Then put two questions to every limit. Can two requests read it and then write it at the same time? Can it quietly change meaning when configuration is missing? A yes to either means it can hold in testing and fail under concurrency or misconfiguration in production.
The worst-case reservation makes the cap conservative, and on a busy day the last few cents of headroom go unused. I’d rather refuse a question a few cents early than let a burst run past the cap.