* refactor(api): one bounded JSON body reader for the API and images.py (#662) images.py kept its own copy of the chunked, capped JSON object reader. Both now use py/api/json_body.py; images.py keeps its 1 MiB cap and its raising form for the thumbnail job. * fix(api): refuse malformed bodies on the legacy prompt routes with a 400 (#662) PUT /prompts/{id}, PUT /prompts/{id}/rating, POST and DELETE /prompts/{id}/tags, POST /prompts/tags, PUT /tags/{tag}, POST /tags/merge and POST /bulk/delete|tags|category read the body with the bounded JSON reader /save uses and check field types, so a body that is not a JSON object, or a field such as {"text": 123}, is a 400 instead of a 500. A prompt id may still be a number or its text, as the legacy page sends it; a boolean is refused (prompt_ids [true] deleted prompt 1). POST /jobs/image-tags refuses a mode that is no text instead of a 500. * refactor(inspect): both resolvers read PROVEN_VALUE_CATEGORIES (#662) proves_value hard-coded the four tables in Python and in the browser. Semantics.proves_value now reads the constant (class-keyed categories by class, the rest by output slot), the browser resolver loops over its mirrored copy in local-resolver-support.mjs, and tests/test_proven_value_parity.py fails when that copy drifts. A test patches the constant to show the resolver follows it. * refactor: remove the write-only preview batch count and the test-only node search (#662) AutoThumbnailWorker set self._batch in four places and never read it. PromptManagerBase._search_prompts had no caller but its own tests: the node UIs search through GET /prompt_manager/search. Prompt search itself stays covered by the database and route tests. * fix(tools): open libraries through the shared read-only URI helper (#662) review_image_links, repair_foreign_links (twice) and workflow_text_digests built their own file: URIs, which SQLite refuses for a library on a Windows network share (file://server/share/...). They now use database/sqlite_uri.readonly_uri; repair_foreign_links opens its own read-write backup by path. The guard in tests/test_sqlite_uri.py scans tools/ too and also catches a conditional ?mode=ro suffix. * ci: bound the publish and Viewer.js update jobs by measured limits (#662) publish.yml and viewerjs-update.yml had no timeout-minutes, and the workflow guard listed only four workflows. The guard now reads every workflow and recomputes both new limits from their comments: publish 5 min from its last three green runs; the Viewer.js update 18 min, from an estimate of its never-run update path (the three measured nightly runs found no release and give the 5-minute floor). * docs: correct the redesign plan's CI and PR rules, renumber the second D205 (#662) docs/application-redesign.md named a Python 3.10-3.13 matrix with macOS, asked for PR screenshots and said Overview links the legacy metadata page. It now names the 3.12 floor and the current Linux/Windows split, asks for visual changes in words, and says the metadata page is reached by address or from the legacy admin page. TESTING.md used D205 for both #431 (saved instructions) and #620 (Library sorts); #620's entry is D206 now.
61 lines
2.0 KiB
Python
61 lines
2.0 KiB
Python
"""The one bounded reader for JSON object request bodies.
|
|
|
|
The body is read in chunks, so an oversized or chunked upload is refused as
|
|
soon as it crosses the cap rather than buffered whole. ``read_json_object``
|
|
raises; ``read_json_body`` answers with the API's ``{"success": false}``
|
|
envelope.
|
|
"""
|
|
|
|
import json
|
|
|
|
from aiohttp import web
|
|
|
|
JSON_BODY_MAX_BYTES = 1_000_000
|
|
_READ_CHUNK = 64 * 1024
|
|
INVALID_JSON = "Request body must be valid JSON"
|
|
NOT_AN_OBJECT = "Request body must be a JSON object"
|
|
|
|
|
|
class BodyTooLarge(Exception):
|
|
"""The request body is longer than the reader's ``max_bytes``."""
|
|
|
|
|
|
def json_error(message, status):
|
|
return web.json_response({"success": False, "error": message}, status=status)
|
|
|
|
|
|
async def read_json_object(request, max_bytes=JSON_BODY_MAX_BYTES):
|
|
"""The request's JSON object body of at most ``max_bytes``.
|
|
|
|
Raises:
|
|
BodyTooLarge: the declared or streamed body crosses ``max_bytes``.
|
|
ValueError: the body is not UTF-8 JSON (``INVALID_JSON``) or not a
|
|
JSON object (``NOT_AN_OBJECT``).
|
|
"""
|
|
declared = request.content_length
|
|
if declared is not None and declared > max_bytes:
|
|
raise BodyTooLarge()
|
|
chunks, size = [], 0
|
|
async for chunk in request.content.iter_chunked(_READ_CHUNK):
|
|
size += len(chunk)
|
|
if size > max_bytes:
|
|
raise BodyTooLarge()
|
|
chunks.append(chunk)
|
|
try:
|
|
data = json.loads(b"".join(chunks).decode("utf-8"))
|
|
except ValueError: # JSONDecodeError and UnicodeDecodeError are ValueErrors
|
|
raise ValueError(INVALID_JSON) from None
|
|
if not isinstance(data, dict):
|
|
raise ValueError(NOT_AN_OBJECT)
|
|
return data
|
|
|
|
|
|
async def read_json_body(request, max_bytes=JSON_BODY_MAX_BYTES):
|
|
"""``(data, None)``, or ``(None, response)`` with a 413 or 400 refusal."""
|
|
try:
|
|
return await read_json_object(request, max_bytes), None
|
|
except BodyTooLarge:
|
|
return None, json_error(f"Request body too large (max {max_bytes} bytes)", 413)
|
|
except ValueError as exc:
|
|
return None, json_error(str(exc), 400)
|