Skip to content
Open
11 changes: 6 additions & 5 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
from functools import lru_cache
from pathlib import Path

import orjson
from starlette.applications import Starlette
from starlette.concurrency import run_in_threadpool
from starlette.middleware import Middleware
Expand All @@ -37,6 +36,7 @@
import limit
import manifest
import store
import strictjson
from store import StoreConflictError, StoreError

# The CHAT_* knobs are read from the environment exactly once, in config — the only
Expand Down Expand Up @@ -464,7 +464,7 @@ def respond(request: Request, view: dict, body_text: str | None = None, note: st
# caller-supplied integer in a view must be clamped the same way. The published
# documents keep stdlib and indent=1 (`read_json` says why).
return Response(
orjson.dumps(view, option=orjson.OPT_APPEND_NEWLINE),
strictjson.dumps(view, option=strictjson.OPT_APPEND_NEWLINE),
media_type="application/json",
headers={"Cache-Control": "no-store", "X-Robots-Tag": "noindex"},
)
Expand Down Expand Up @@ -1439,9 +1439,10 @@ async def read_json(request: Request) -> dict | Response:
# orjson here, stdlib json for the three documents below. orjson is ~4.7x on the
# parse and, on a service whose whole job is hostile input, refuses the
# `NaN`/`Infinity` literals stdlib accepts — the same non-finite tokens
# config._finite_env already refuses to boot with. The documents keep stdlib
# because they are published with indent=1 and orjson only offers indent 2.
payload = orjson.loads(bytes(raw) if raw else b"{}")
# config._finite_env already refuses to boot with. strictjson retains that decoder
# and refuses repeated object names before it; the documents keep stdlib because
# they are published with indent=1 and orjson only offers indent 2.
payload = strictjson.loads(bytes(raw) if raw else b"{}")
except ValueError as exc:
return text(
f"400 body must be JSON, and this did not parse: {exc}.\n"
Expand Down
3 changes: 2 additions & 1 deletion src/manual.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ they are clamped or defaulted, never refused, so junk is silently replaced with
something sane — limit and since fall back to __DEFAULT_LIMIT__ / no cursor, limit
then clamps to 1..__MAX_LIMIT__, wait clamps to 0..__MAX_WAIT__, and any format other than the literal
json leaves the reply as text/plain. Read count and Content-Type off the reply
rather than assuming the value you sent survived. Semantic (from, text, value,
rather than assuming the value you sent survived. A JSON object cannot name the same field
twice: an ambiguous body is refused rather than choosing one value. Semantic (from, text, value,
did, sig, nonce, if, if_absent, and every <name>) decide what is stored, who it
is from and whether a write happens at all: these are REFUSED with a 400 whose
first line names the field, e.g. `400 bad from: must be a string`. Nothing is
Expand Down
24 changes: 24 additions & 0 deletions src/strictjson.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""orjson's wire behavior, with unambiguous object names on hostile input."""

from __future__ import annotations

import json
from typing import Any

import orjson

OPT_APPEND_NEWLINE = orjson.OPT_APPEND_NEWLINE
dumps = orjson.dumps


def _check_root_names(value: bytes) -> None:
pairs = json.loads(value, object_pairs_hook=list)
if len(dict(pairs)) != len(pairs):
raise ValueError("duplicate JSON key")


def loads(value: bytes) -> Any:
payload = orjson.loads(value)
if isinstance(payload, dict) and value.count(b":") > len(payload):
_check_root_names(value)
return payload
33 changes: 33 additions & 0 deletions tests/unit/test_json_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,36 @@ def test_the_body_parser_refuses_the_non_finite_literals_stdlib_allowed(client)
# …and ordinary JSON still works, or the above would pass against a parser that
# rejects everything.
assert client.post("/r/lobby", json={"from": "bot", "text": "fine"}).status_code in (200, 201)


def test_duplicate_json_keys_are_refused_before_either_write_lane(client) -> None:
"""Repeated semantic names have no single intended value. A parser choosing the last
one would store a different write from a first-value parser, so both shared-parser lanes
must refuse before touching their room or note."""
room = client.post(
"/r/duplicate-body",
content=b'{"from":"first","from":"second","text":"safe","\\u0074ext":"chosen"}',
headers={"content-type": "application/json"},
)
assert room.status_code == 400
assert "duplicate JSON key" in room.text
assert client.get("/r/duplicate-body?format=json").json()["messages"] == []

note = client.post(
"/kv/audit/value",
content=b'{"value":"first","value":"second"}',
headers={"content-type": "application/json"},
)
assert note.status_code == 400
assert "duplicate JSON key" in note.text
assert client.get("/kv/audit/value").status_code == 404

valid = client.post("/r/duplicate-body", json={"from": "bot", "text": "key:value"})
assert valid.status_code in (200, 201)

nested = client.post(
"/r/duplicate-body",
content=b'{"from":"bot","text":"nested ok","meta":{"a":1,"a":2}}',
headers={"content-type": "application/json"},
)
assert nested.status_code in (200, 201)
Loading