Skip to content

Survive lone surrogates in JSON bodies, id-less server tool calls and oversized Discord ticket numbers - #374

Open
t11z wants to merge 6 commits into
mainfrom
claude/hopeful-newton-xvkwlq
Open

t11z wants to merge 6 commits into
mainfrom
claude/hopeful-newton-xvkwlq

Conversation

@t11z

@t11z t11z commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

What & why

Scheduled crash-fuzzing run. This run targeted surfaces the earlier runs did not reach: the Discord bot driven by hostile events, and the AI tool loop driven by a model that returns adversarial tool calls. The session may push to one branch only, so the fixes share this PR, one commit each. None of them is covered by the open fuzzing PRs (#327, #328, #329, #334, #337, #354, #359, #364, #367, #368, #370).

1. A JSON body with a lone surrogate answers 500

json.loads accepts a lone UTF-16 surrogate, as the escape "\ud800" or as its raw three-byte encoding. The string cannot be encoded as UTF-8, so the first SQLite bind that meets it raises:

UnicodeEncodeError: 'utf-8' codec can't encode character '\ud800': surrogates not allowed
  ticketstore.py  create            (POST /api/tickets  {"title": "x\ud800", ...})
  store.py        ChatHistoryStore.save   (POST /api/chat  {"message": "hi \ud800", ...})
  userstore.py    create_user       (POST /api/users  {"username": "u\ud800", ...})

Every route that stores a body string is affected; there are 31 request.json() call sites.

Fix: one check instead of 31. StorableJsonTextMiddleware (new kenny_server/json_text.py) sits inside the auth gate and answers such a body with 400 before a handler runs, so nothing is half-written. It parses a body only when a cheap byte scan says a surrogate is possible. Surrogate pairs (emoji written as 😀) and ordinary UTF-8 pass unchanged. The MCP endpoint and form posts are not touched.

2. A server tool call without id ends the chat turn

select_agent, agent_health, agent_snapshot and agent_availability read args["id"] directly. The arguments are whatever the model sent; a call with {} raised KeyError. _execute_one turns only ToolError into a tool result, so the turn ended: POST /api/chat answered 502 {"error": "'id'"} and /api/chat/stream emitted an in-band error.

Fix: a missing, empty or non-string id raises ToolError("bad_args", ...), which goes back to the model as an error tool result, and the turn continues.

3. Discord /close or /cancel with a huge ticket number is never answered

The ticket reference is free text from any linked Discord user. "9" * 40 (or KEN-<40 digits>) parses with int() but cannot be bound as a SQLite 64-bit INTEGER:

OverflowError: Python int too large to convert to SQLite INTEGER
  discord_service.py  _own_ticket -> ticketstore.py  get_by_number

The service loop logs the exception and keeps running, but the interaction gets no reply.

Fix: TicketStore.get_by_number returns None for a number outside the 64-bit range, so the user gets the normal "I could not find that ticket."

Regression tests

Fixed inputs only; no fuzz harness is committed.

  • test_hostile_input_no_500.py: lone-surrogate bodies (escape and raw bytes, value and key) on four routes answer 400 and store nothing; surrogate pairs and Korean/emoji UTF-8 still create a ticket; a form post is left alone.
  • test_chat.py: the four server tools with {}, null, a number and an empty string as id feed back a bad_args tool result and the turn finishes.
  • test_ticketstore.py, test_discord_service.py: out-of-range ticket numbers are a miss.

Fuzzing summary

  • Baseline: server pytest 4260 passed, 2 skipped. Agent cargo test 588 passed, including the existing dispatch fuzz tests.
  • Discord service: about 13,500 typed events (messages, slash commands, component clicks with real and mutated custom_ids) found only item 3. A further 8,300 events with a hostile model behind the ticket assistant produced no unhandled exception.
  • Dashboard chat routes: 5,600 requests with an adversarial model found only item 2. A model that breaks the SDK's response shape itself (tool input not an object, a block without name) still ends the turn with a 502; the real SDK does not produce those shapes, so that is not changed here.
  • Windows: the agent's Windows-only code cannot be executed on this Linux runner.

Checklist

  • Tests pass: pytest -q (server): the touched test files pass, full run in progress at the time of writing. cargo test (agent): 588 passed, no agent change
  • Lint/format clean: ruff check on the touched files
  • If the wire contract changed: n/a, no frame or tool shape changed
  • If the change is architectural: n/a, input validation only, no boundary moved
  • Docs updated where relevant: n/a
  • Commits are signed off (DCO: git commit -s): not signed off by the automated run

Generated by Claude Code

Discord's /close and /cancel take a free-text ticket reference. A digit
string that int() parses but SQLite cannot bind as a 64-bit INTEGER
("9" * 40, or KEN-<40 digits>) raised OverflowError in
TicketStore.get_by_number. The service loop logged it and the
interaction was never answered. Such a number names no ticket, so
get_by_number now returns None for it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QcqxZNRZH4CBPzkwebJuYc
select_agent, agent_health, agent_snapshot and agent_availability read
args["id"] directly. The arguments are whatever the model sent, and a
call without id raised KeyError. _execute_one only turns ToolError into
a tool result, so the KeyError ended the turn: POST /api/chat answered
502 and the stream emitted an in-band error. The call is now a bad_args
tool result the model can correct, and the turn continues.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QcqxZNRZH4CBPzkwebJuYc
json.loads accepts a lone UTF-16 surrogate, as the escape "\ud800" or
as its raw three-byte encoding. The string cannot be encoded as UTF-8,
so the first SQLite bind that met it raised UnicodeEncodeError and the
request answered 500 (POST /api/tickets, POST /api/users, POST
/api/chat, and any other route that stores a body string).

StorableJsonTextMiddleware sits inside the auth gate and answers such a
body with 400 before a handler runs. It parses a body only when a cheap
byte scan says a surrogate is possible, and leaves the MCP endpoint and
form posts untouched.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QcqxZNRZH4CBPzkwebJuYc
/var/log/lastlog is sparse and as long as the highest uid that ever
logged in: one login by uid 5,000,000 makes it 1.4 GiB. The Linux
local_accounts collector read it whole on every snapshot to look at
four bytes per account, so resident memory grew by the file's apparent
size, up to an OOM kill on a host with directory-backed uids.

The collector now opens the file and reads the four bytes of each
account's record by position.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QcqxZNRZH4CBPzkwebJuYc
manifest.json, _locales/*/messages.json and Firefox's extensions.json
live in user profiles, so any local user chooses their size, and the
agent read them whole as LocalSystem on every snapshot. A sparse 1.5 GiB
manifest cost the agent 1.5 GiB. The errors list also grew by one entry
per broken manifest, with no limit.

Files over 16 MiB are skipped like unreadable ones, at most one byte
past the cap is ever held, and the errors list stops at 50 entries.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QcqxZNRZH4CBPzkwebJuYc
wait_times_out_while_another_process_runs_target copied /bin/sleep to a
file named kenny-wait-test-<pid> and ran the copy. The Linux CI job fails
that test on every run that reaches it (also on an unrelated dependency
PR): the child is gone before the wait looks for it. Where sleep is an
applet of a multi-call binary, the binary picks the applet by the name it
is run as, so the renamed copy exits at once.

The copy now keeps the name `sleep` inside a private directory, which runs
the same on a standalone sleep and on a multi-call one. Test-only; no
agent behaviour changes. [skip-doc-drift]

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QcqxZNqpHNGk5hJzgn6CWt
Signed-off-by: Claude <noreply@anthropic.com>
(cherry picked from commit 3ab1a26)

t11z commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

The kenny-agent (Rust) job failed on 65155d3 in handlers::agent_update::tests::wait_times_out_while_another_process_runs_target. This PR's diff does not touch that test or agent_update.rs; #364 describes the same failure on the Linux runner for unrelated PRs and carries a test-only fix (3ab1a26, the copied sleep keeps its applet name). I cherry-picked that commit here as 6221eca so this PR's CI can go green. If #364 merges first, the commit drops out as a no-op on merge.


Generated by Claude Code

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants