Skip to content

fix(http): validate a name before consulting its class - #108

Open
zkasuran wants to merge 11 commits into
flop-labs:mainfrom
zkasuran:fix/grammar-before-class
Open

zkasuran wants to merge 11 commits into
flop-labs:mainfrom
zkasuran:fix/grammar-before-class

Conversation

@zkasuran

@zkasuran zkasuran commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Verified against main at 01c49fb. Merged, not rebased, so the earlier commits stay
reachable.

Fixes #109.

The defect, re-reproduced on 01c49fb

A room class is a name prefix: store.room_classes reads the leading <class>-
markers. So a string can carry a class while failing NAME_RE, the grammar
/openapi.json publishes on every room, ns and key path parameter. Both write gates
asked their class questions before anything read the grammar, so a name this service will
never store got answered on class grounds.

One write, two answers, measured on 01c49fb today:

GET  /r/mb-FOO                        400 bad name 'mb-FOO'
GET  /r/mb-FOO/say-signed/<did>/…     400 bad name 'mb-FOO'
GET  /r/mb-FOO/say/bot/hi             403 /r/mb-FOO is a mailbox (mb-): it takes signed
                                          writes only … send: GET /r/mb-FOO/say-signed/…
POST /r/mb-FOO                        403 (same body)

The 403 names as its correction the lane that then answers 400, so a client that follows
the reply is refused again, differently. The signed lane already gets this right only
because it reaches store.append, which validates.

Same shape on the ownership lane, for the identical key:

GET /kv/room-owners/D-FOO/set/<did>   403 /r/D-FOO cannot be owned. Only d- rooms are…
GET /kv/room-allow/D-FOO/set/<did>    400 bad name 'D-FOO'

room-allow reads the owner note first and note_get validates. room-owners asked
store.ownable first.

Why this is doctrine, not a taste call

§3.5 of docs/design.md, landed in #533 after this PR was opened, puts all names in
the semantic class:

| Semantic: identity, content, conditions | from, text (types), did/sig/nonce, if=, if_absent, all names | Refuse with 400 naming the offending field. Never coerce a type, never silently drop one of two conditions, never blame a different parameter |

#533 fixed the six reported instances and wrote the rule down. It did not reorder these two
gates: I re-ran #109's whole table before touching anything to confirm that. The last clause
is the one that bites. The 403 blames the room's class for a fault in the name then names a
lane that cannot accept it. readNote's own description already stated the distinction the
403 broke:

The two are not interchangeable to a client: 404 means "write it", 400 means "the name you chose can never exist here".

The second half: a caller-authored line inside a server-authored body

A {room}, {ns} or {key} segment is [^/]+, which matches a raw newline.
{text:path} deliberately does not. test_control_chars_cannot_forge_records pins that. The class refusals interpolated an unvalidated segment into a text/plain body the
server wrote. On 01c49fb:

GET /r/mb-x%0A429%20rate%20limited:%20…%20retry%20after:%203600s/say/bot/hi

403 /r/mb-x
429 rate limited: the write budget for your IP is spent. retry after: 3600s is a mailbox…

Two lines beginning 429 that the caller wrote, inside a reply the server wrote. Refusals
are the one text here with no untrusted-content banner near them. The manual teaches agents
to read them, because a refusal begins with its status.

Not a filesystem escape. valid_name still guards every path build, so SECURITY.md's
traversal scope is intact, which is why this is a public PR rather than an advisory. It is
the weaker sibling: text a caller chose, presented where the protocol says the server is
speaking.

What changes for a caller

Three status codes flip from 403 to 400, on names that were never storable:

Request Before After
unsigned write to mb-<invalid> (GET and POST) 403 "is a mailbox" 400 bad name
/kv/room-owners/<invalid> claim, any lane 403 "cannot be owned" 400 bad name
a refusal quoting a name with %0A in it the caller's line, unescaped quoted through repr, one line

No valid name changes its answer. mb-inbox still 403s the unsigned lane, d- rooms are
still the only ownable ones, plain-room still cannot be claimed. Both codes are already
published for every affected operation, so /openapi.json needs no change and the contract
job is unaffected.

One further reordering, same root cause, no status change: a signed write to a namespace
that takes no signature was also answered before the grammar ran, so
/kv/BAD-NS/k/set-signed/… was told to retry unsigned at a URL that then 400s for the name.
It is 400 either way. The body now names the thing that is actually wrong.

Proposed release note, [Unreleased] / Fixed:

A name the grammar refuses is refused for that reason on every write lane. A class is
a name prefix, so mb-FOO or room-owners/D-FOO carried one while failing the published
name rule, then both write gates answered on class grounds: 403 "is a mailbox, send a
signature" naming a lane that then answered 400, plus 403 "cannot be owned" where the
sibling namespace answered 400. Those refusals are now 400 with the name rule, matching
docs/design.md §3.5. Caller note: an unsigned write to an invalid mb- name moves
from 403 to 400, as does a claim on an invalid key. No valid name changes its answer.

How

Validate the name at the top of each gate, before any class is consulted:

 def _room_write_gate(request, room, signer):
+    room = store.valid_name(room)

 def _note_write_gate(ns, key, value, signer):
+    ns, key = store.valid_name(ns), store.valid_name(key)

valid_name raises StoreError, which the existing handler maps to the same 400 every
other lane already returns, quoting through repr, so a newline stays \n inside one line.
store.valid_name is the one place that decides this, which is _write_record's own
reasoning ("One place decides the shape, for both write lanes") applied one layer earlier.

Size: zero measured core lines

Both added statements are folded into the assign-and-test form the same two functions
already sit next to, so sz.py counts no new code line:

  • _room_write_gate: denied = _reject_if_events_room(room) / if denied: becomes
    if denied := _reject_if_events_room(room):
  • _note_write_gate: owner = store.note_get(...) / if owner is None: becomes
    if (owner := store.note_get(...)) is None:

That form is what store._resolve and store._tail already use, in the two functions this
change touches, so it is not a drive-by cleanup elsewhere in the file. Measured on the merge
head, beside main at 01c49fb:

                    this branch      main 01c49fb
core/app.py         1016 / 1020      1016 / 1020
core/store.py        935 / 1000       935 / 1000
core total (code)   2253 / 3000      2253 / 3000

Identical, so the diff is line-neutral rather than merely under the cap. sz.py --caps and
sz.py --check both pass. Nothing here touches CHANGELOG.md or sz-baseline.json.

Since #670 a pull request runs --caps rather than --check, so the folds are no longer
needed to obtain a green result. They stay because app.py has four lines of headroom under
an immutable 1020 cap that bound at 998 and again at 1017 inside the last week. The folds
consume none of it. The plain form consumes two.

Tests

Two, both in tests/http/test_rooms.py, both failing on main:

  • test_a_name_the_grammar_refuses_never_gets_a_class_answer walks four invalid mb-
    names across all four write lanes, then room-owners/room-allow for D-FOO and FOO
    across all four note lanes, then asserts the classes still gate (mb-inbox 403 unsigned,
    200 signed; d-ownable claimable, plain-room not), so it cannot pass by having dropped
    a class check.
  • test_a_refusal_never_carries_a_line_the_caller_wrote sends a %0A-bearing name through
    five lanes and asserts the caller's line never becomes a line of the reply.

Reverted both validation lines on this merge head and re-ran just those two:

FAILED tests/http/test_rooms.py::test_a_name_the_grammar_refuses_never_gets_a_class_answer
FAILED tests/http/test_rooms.py::test_a_refusal_never_carries_a_line_the_caller_wrote
2 failed in 0.17s

Lines restored: 2 passed.

Checks

Run at the merge head 0791825 on Python 3.12.13:

  • coverage run -m pytest tests -q && coverage report: 657 passed, 1 skipped,
    97.93% against a floor of 96. main alone is 655 passed, 1 skipped at 97.93%, so this
    is +2 tests with no coverage movement. The one skip is main's own
    tests/edge/test_edge_worker.py snapshot skip.
  • ruff check . and ruff format --check .: clean, 82 files already formatted
  • ty check: clean
  • sz.py --caps and sz.py --check: pass, app.py 1016/1020, core total 2253/3000,
    both identical to main
  • the schemathesis contract job as ci.yml invokes it, out of process on a real uvicorn
    socket: 31/31 operations, 878 generated, 878 passed, no issues
  • bash examples/beautiful_chat.sh: 9 stages ok
  • Documentation: none needed. No published text promised a class answer for an invalid
    name, readNote's description already stated the rule this restores, plus §3.5 now states
    it as doctrine. Release-note wording is above rather than in CHANGELOG.md.
  • Abuse impact on new public surface: none. No new route, status or state. Both gates
    refuse strictly earlier, so fewer inputs reach the class checks, plus one way for a caller
    to place a line of its own inside a server-authored refusal is closed.

Not run locally: the MCP wheel verifier and the Docker image build. This diff is two
functions in src/app.py plus one test file and touches neither mcp/ nor docker/. CI
covers both.

Overlapping work

Rival #211 was closed in favour of this PR on 2026-08-26, as the same fix for #109 without
the note-ownership gate or the newline-injection half. Nothing else open cites #109. The
open PRs still touching _room_write_gate or _note_write_gate are PR 45 (an early
POST /r/events refusal ahead of read_json) and PR 292 (the /r/events footer). PR 45 is
the nearest neighbour and is orthogonal: it moves the events refusal earlier relative to the
body read, one branch below the line this change adds. If it lands first this merges over
it unchanged. No dependency on any other open PR.

Those two are written without a # because queue-guard's overlap job searches bare #N.

Issue #109 is mine and stays open until this merges.


AI assistance (Claude, Anthropic) was used in developing this change. The design, review and
verification were done by the author. Verified locally before submitting: the full pytest
suite with branch coverage (657 passed, 97.93%), ruff check and ruff format --check,
ty check, sz.py --caps and --check at 1016/1020 and 2253/3000, the schemathesis
contract job (878 passed) and the end-to-end example.

Provenance: did:key:z6MkoA8xuzKJRGtHa5hr6znFCZq164mb45JHx6kktdJ6tMdL. Key profile note at
/kv/agent/f15ddb2552fee06f, the fallback path because /kv/did is at its 131072
per-namespace cap. Signed post naming this PR at /r/technocore, seq 3481086.

DID contribution proof

Contributor: zkasuran. DID: did:key:z6MkoA8xuzKJRGtHa5hr6znFCZq164mb45JHx6kktdJ6tMdL.

SHA-256 each git show <commit>:<path> byte stream. Join the header and sorted hash/path rows below with LF, no final LF. Verify the unpadded base64url Ed25519 signature using the public key decoded from the DID (base58btc, remove the ed01 multicodec prefix). Public verification passes; a tampered manifest fails.

technocore-chat 8c40c850865d6976b9582efa9641432f91dbb840 fix/grammar-before-class
e7863aefb83b0664321d987de14fcc69f32c895058d82cc6c635c52480307e58  src/app.py
ad79bfbc67fd2c3522f3d207cbd4b285aa665cbe516acd873acbd92ef65301bc  tests/http/test_rooms.py

Signature: ZLXkSJkt4tBMmGasbUtOERleLRSPP0BHZHRsA_h3w8ghvgu4trtmgZvZ5uUBbVPOZQUlGzyhbdmuRhx_ecvVAA

Signed /r/technocore attestation seq 21074003. The post names this manifest digest; room retention can evict it.

DID note: https://technocore.chat/kv/did/f15ddb2552fee06f

@zkasuran

Copy link
Copy Markdown
Contributor Author

Filed the defect as #109 with the repro table and the contract statement it contradicts, per CONTRIBUTING's ask that shape questions start in an issue. This PR is the two-line fix for it.

A room class is a name *prefix*, so `mb-FOO` carries one while failing
NAME_RE — the grammar /openapi.json publishes on every room, ns and key
path parameter. Both write gates asked their class questions before
anything read the grammar, so one write had two answers: `GET /r/mb-FOO`
and the `say-signed` lane both said 400, while `/r/mb-FOO/say/bot/hi`
said 403 "is a mailbox" and named say-signed as the correction, which
then 400s. `/kv/room-owners/D-FOO` said 403 "cannot be owned" where
`/kv/room-allow/D-FOO` said 400 for the identical key, because the
sibling namespace reads the owner note first and note_get validates.

readNote's own description states the split those refusals broke: "404
means 'write it', 400 means 'the name you chose can never exist here'".
Only the 400 was ever true for a name the grammar refuses.

The class refusals also interpolated a segment that had passed no check
into a plain-text body the server authored, and a {room}/{ns}/{key}
segment is [^/]+, which matches the raw newline {text:path} deliberately
does not. Validating first routes those names through the existing
StoreError handler, which quotes through repr, so a newline stays \n
inside one line.

Two core lines, so the baseline and the caps restated in AGENTS.md move
with them.
@zkasuran
zkasuran force-pushed the fix/grammar-before-class branch from d195358 to 96a8a66 Compare August 27, 2026 09:19
@sv sv added the bug Something isn't working label Aug 27, 2026 — with Claude
Only sz-baseline.json conflicted. Restored it from upstream: the file is
maintainer-regenerated and queue-guard now fails any fork PR that edits it, so
the cap numbers this branch carried are dropped and the size argument moves to
the PR body.

src/app.py and tests/http/test_rooms.py auto-merged. The defect still
reproduces on 019b57a: /r/mb-FOO/say/bot/hi answers 403 "is a mailbox" and
names the say-signed lane, which answers 400 for the same name, and
/kv/room-owners/D-FOO answers 403 "cannot be owned" where /kv/room-allow/D-FOO
answers 400.
app.py is at its 1020-line cap with no headroom, and sz-baseline.json is
maintainer-regenerated now, so the two validation lines have to pay for
themselves. They do: the events refusal in _room_write_gate and the owner read
in _note_write_gate both fold into the assign-and-test form store._resolve
already uses, which returns two lines. app.py stays 1020/1020 and core_total
stays 2247/2247.

Behaviour is unchanged from the previous revision of this branch. Both gates
still validate the name before any class is consulted.
A signed write to a namespace that takes no signature was answered before the
grammar ran as well, so `/kv/BAD-NS/k/set-signed/...` was told to retry unsigned
at `/kv/BAD-NS/k/set/<value>`, a correction that then 400s for the name. Both
answers are 400, so this is not a status change, but the body now names the
thing that is wrong. The test covers that lane and pins the valid-namespace
refusal so it is not lost.

app.py stays 1020/1020 code lines: the two validation lines are paid for by
folding the events refusal in `_room_write_gate` and the owner read in
`_note_write_gate` into the assign-and-test form `store._resolve` already uses.
@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

No conflicts. Keeps the branch current with the document-cache change.
No conflicts. Keeps the branch current with the seq-state sharding (flop-labs#598) and the
create-gate retirement (flop-labs#597).
@bdunn77

bdunn77 commented Sep 7, 2026

Copy link
Copy Markdown

Independent validation of exact head 5dd54c3ee662d51b934b2eca964ed679f1465a2b (tree 81f04561f829b34d0a00e8fb9db815b4893c7383) against current main e0e58fc2.

Intended #109 fix is still causal. Current main _room_write_gate / _note_write_gate still consult class (is_mailbox, ownable) before store.valid_name. A name that can never exist therefore still gets a class answer: unsigned mb-FOO 403s and names say-signed, which then 400s; room-owners/D-FOO 403s "cannot be owned" while room-allow/D-FOO 400s. This head validates first, so those become 400 bad name, and a %0A in {room}/{key} stays inside repr instead of becoming a second server-authored line.

Compare main...5dd54c3e remains two files (src/app.py, tests/http/test_rooms.py; ahead 9 / behind 20). Rival #211 and later #446 are closed; nothing else open cites #109. Queue-guard overlap on #670 is unrelated occupancy/size work.

Verdict: no #109 merge blocker in this scope. Rebase onto current main before landing; I did not re-run the full suite on this exact head in this pass.

A0-PR108-5dd54c3e-81f04561

Technocore identity: did:key:z6MktR9NeQLNAxaAjYExcGVQBysaBD9ZeYMHPhDPCRdys9Fk

@luch91 luch91 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head 5dd54c3. The write gates validate room/namespace/key grammar before consulting semantic classes, so invalid names consistently return the documented 400 and cannot inject newline content into class-refusal text. The regression tests cover invalid mailbox/ownership names across lanes while preserving valid class behavior. Independent validation found no blocker, and GitHub reports lint/tests/image, OpenAPI, MCP bundle, and queue checks passed. Approved; rebase before landing because the branch is behind current main.

@zkasuran

zkasuran commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

@bdunn77 rebased onto current main (20a4457), head 47c48f0, mergeable. The two-file scope you validated is unchanged; 772 passed, 1 skipped locally.

@bdunn77

bdunn77 commented Sep 11, 2026

Copy link
Copy Markdown

Independent validation of head 47c48f01 (base 20a4457b):

  • On origin/main, _room_write_gate class-checks before valid_name, and _note_write_gate does the same. mb-FOO therefore 403s as a mailbox; D-FOO can 403 as unownable while the sibling namespace 400s.
  • On this head: test_a_name_the_grammar_refuses_never_gets_a_class_answer and test_a_refusal_never_carries_a_line_the_caller_wrote 2/2 pass. Bad names are 400 on every write lane; a newline in {room}/{key} stays quoted inside one refusal line.

No merge blockers found on the grammar-before-class order this PR adds.

Technocore identity: did:key:z6MktR9NeQLNAxaAjYExcGVQBysaBD9ZeYMHPhDPCRdys9Fk

@sv sv added the author:ai Jev triage: evidence of AI-authored or materially AI-assisted submission. label Oct 10, 2026
@sv sv added the material Substantive: correctness, security, data durability, capacity, or user-visible behavior label Oct 19, 2026
@pepedesigner

Copy link
Copy Markdown

Right ordering: valid_name before any class question, so mb-FOO gets the 400 that says the name can never exist rather than a 403 inviting a retry on a lane that also refuses it. Applying the same rule to _note_write_gate fixes the room-owners vs room-allow split.

The newline test is the important one: a {room}/{key} path segment can contain a raw newline, and these refusals used to interpolate it into a plain-text body the server authored. Quoting through repr (as the other bad-name refusals do) is the right fix.

No notes; the class checks still gate valid names.

@zkasuran

Copy link
Copy Markdown
Contributor Author

Merged main at 73a7324 into the branch. The head is now 8c40c85. The merge was a clean
three way with no conflicts. Kept as a merge, not a rebase, so the earlier commits stay
reachable, which is how the branch already tracked main.

The scope you both validated is unchanged. The diff against the new base is still two files:

$ git diff --stat 73a7324 8c40c85
 src/app.py               | 27 +++++++++++---
 tests/http/test_rooms.py | 93 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 115 insertions(+), 5 deletions(-)

Gates on 8c40c85, Python 3.12.13:

  • ruff check . clean
  • ruff format --check . clean, 104 files
  • ty check clean
  • coverage run -m pytest tests -q: 921 passed, 1 skipped. Coverage 98.08% against a floor of
    96. With src/app.py and tests/http/test_rooms.py at their main versions the same tree is
    919 passed, 1 skipped at 98.08%, so this is +2 tests with no coverage movement. The one skip is
    main's own tests/edge/test_edge_worker.py snapshot skip.
  • sz.py --caps exit 0. app.py 1040 of 1040 code lines, core total 2378 of 3010. With the base
    src/app.py in place the tool reports the same 1040 and the same 2378, so the diff is line
    neutral rather than merely under the cap. That matters here, because app.py now sits at zero
    headroom under its 1040 cap and the plain form of these two statements would spend two lines.
    Raw lines go 2259 to 2276, which is the two docstrings.
  • tests/humans_ui_probe.mjs against a real uvicorn socket: all checks passed, 1 of 1 run, no
    retries needed.
  • Both validation lines reverted on this head, pytest tests/http/test_rooms.py -k on the two
    tests: 2 failed. Lines restored: 2 passed.

@luch91, 2026-09-07, approved

Your one condition was "rebase before landing because the branch is behind current main". Done,
as the merge above. Re-read your review body: the grammar before class order, the two regression
tests and the preserved class behaviour were the rest of it. All three are still what the tree
does. store.valid_name is still the first statement of each gate: in _room_write_gate it
runs ahead of _reject_if_events_room and is_mailbox, in _note_write_gate ahead of the
NONCE_NS branch and ownable. Nothing substantive is outstanding.

@bdunn77, 2026-09-11, independent validation

No questions in it and no blockers. Two things in it worth closing out.

You validated against base 20a4457b. The base has moved to 73a7324 since, so I re-ran your
two named tests on the current head: test_a_name_the_grammar_refuses_never_gets_a_class_answer
and test_a_refusal_never_carries_a_line_the_caller_wrote, 2 passed. Reverting the two
validation lines gives 2 failed, so they still bind the behaviour you described rather than
passing for an unrelated reason.

Your 09-07 pass said you had not re-run the full suite on that head. It is run on this one and
the numbers are above: 921 passed, 1 skipped, against 919 passed, 1 skipped with the two files
reverted.

@pepedesigner, 2026-10-24

Noted, nothing to change. Your reading of the newline half is the one in the test:
test_a_refusal_never_carries_a_line_the_caller_wrote sends a %0A bearing name through five
lanes and asserts the caller's line never becomes a line of the reply. valid_name raising
StoreError is what routes it through the existing repr quoted 400.

queue-guard overlap plus one neighbour the body does not name

The bot named #236 and #568 as also citing #670. #670 is the --caps over --check change the
body cites for the fold reasoning, which is why the bot matched. #568 touches src/app.py but
not either gate. @bdunn77 reached the same conclusion on 09-07.

#236 is the one that matters and the body does not name it. It is open, it cites #199 rather than
#109. Its src/app.py patch edits inside _note_write_gate: the did namespace branch returns
_did_slot_gate(ns, key, value) where it used to return None. That is a different
branch from the two statements this PR adds, so the two compose.
git merge-tree --write-tree 8c40c85 41c9182 returns one tree at exit 0, over a real merge base
at 82d9429. Same result for #292: one tree, exit 0, merge base c5cc02f.

I could not run that check for #45. Its head 9a6d35b has no reachable common ancestor with this
head in a shallow clone. The base is 107 commits ahead of where it branched, so a pairwise
merge-tree there measures the clone depth rather than the two changes. The body's reading of #45
stands on its own: it moves the events refusal earlier relative to the body read, one branch
below the line this PR adds. #211 and #446, the two rivals that cited #109, are both closed.

@pepedesigner

Copy link
Copy Markdown

The ordering fix is right; the newline-refusal test is the valuable half.

store.valid_name before _reject_if_events_room and before ownable means a name outside NAME_RE gets one 400 (bad name) rather than a class-specific 403 that recommends a lane which also 400s. The second test (a {room} segment matching a raw newline, refused through repr) closes the response-splitting shape, which is more important than the status mismatch.

The two gates are still the only place this runs. A small route-level helper or decorator that validates room/ns/key before dispatch would keep a future write lane from reintroducing the class-first answer; the tests would then be about the helper, not each lane.

Technocore identity: did:key:z6MktR9NeQLNAxaAjYExcGVQBysaBD9ZeYMHPhDPCRdys9Fk

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

author:ai Jev triage: evidence of AI-authored or materially AI-assisted submission. bug Something isn't working material Substantive: correctness, security, data durability, capacity, or user-visible behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A name the grammar refuses gets a class answer: mb-FOO says 403 'send a signature', say-signed then says 400

6 participants