Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(web): preserve route JSON error envelopes (#7089)

LearningCircuit2c37a2f9862e
diff --git a/.github/workflows/fastapi-migration-quality.yml b/.github/workflows/fastapi-migration-quality.yml
index badaaa8f91..f68cbbadec 100644
--- a/.github/workflows/fastapi-migration-quality.yml
+++ b/.github/workflows/fastapi-migration-quality.yml
@@ -73,6 +73,7 @@ on:
- tests/web/routers/test_news_scheduler_check_now.py
- tests/web/routers/test_error_response_leakage.py
- tests/web/routers/test_fastapi_port_footguns.py
+ - tests/web/routers/test_json_body_error_envelopes.py
- tests/web/routers/test_migration_antipattern_guards.py
- tests/web/routers/test_no_blocking_in_async_routes.py
- tests/web/routers/test_route_ordering.py
@@ -258,6 +259,8 @@ jobs:
tests/web/routers/test_news_scheduler_check_now.py::TestCheckNowEnqueues::test_enqueues_wrapped_overdue_check_for_current_user \
tests/web/routers/test_error_response_leakage.py \
tests/web/routers/test_fastapi_port_footguns.py \
+ tests/web/routers/test_json_body_error_envelopes.py::test_the_scan_tells_a_wrapped_call_from_a_hoisted_one \
+ tests/web/routers/test_json_body_error_envelopes.py::test_no_read_json_dict_caller_wraps_it_in_a_broad_except \
tests/web/routers/test_migration_antipattern_guards.py \
tests/web/routers/test_no_blocking_in_async_routes.py \
tests/web/routers/test_route_ordering.py \
@@ -304,12 +307,14 @@ jobs:
tests/web/test_body_size_limit.py \
tests/web/test_database_middleware_skip_prefixes.py \
tests/web/test_encoding_and_non_ascii.py::TestAppLevelHandlerResolution \
+ tests/web/test_encoding_and_non_ascii.py::TestBroadlyWrappedBodyParses \
tests/web/test_exception_handler_matrix.py \
tests/web/test_middleware_stack_contracts.py \
tests/web/test_research_socketio_delivery_integration.py \
tests/web/test_research_lifecycle_states.py::test_cancel_research_endpoint_leaves_the_flag_for_the_worker \
tests/web/test_research_lifecycle_states.py::test_queue_tick_does_not_start_a_second_run_past_the_cap \
tests/web/test_research_state_registry.py::test_cleanup_research_can_release_the_slot_but_preserve_its_stop_signal \
+ tests/web/test_request_response_boundary_contracts.py::test_invalid_utf8_body_is_a_400_on_the_cost_route \
tests/web/test_request_response_boundary_contracts.py::test_invalid_utf8_body_is_a_400_on_a_bare_request_json_route \
tests/web/test_request_response_boundary_contracts.py::test_unicode_decode_error_handler_is_registered \
tests/web/test_root_route_failure_recovery.py \
diff --git a/changelog.d/5755.bugfix.md b/changelog.d/5755.bugfix.md
new file mode 100644
index 0000000000..704c844dbe
--- /dev/null
+++ b/changelog.d/5755.bugfix.md
@@ -0,0 +1 @@
+Preserve the validation response of the body-required FastAPI routes converted to `read_json_dict`, and of the optional settings cleanup route, when a JSON request body is malformed, matching their existing response for a non-object body. On those routes a deeply nested body or one with an oversized integer now gets that 400 instead of a 500, and on the news and add-resource routes that already used `read_json_dict` a chunked body over the size cap now gets 413 instead of 400. On routes that read their body through `read_json_dict`, a client that disconnects while its request body is still arriving is now logged at info level and answered 499, instead of being reported as a 500 server error (or, on the news and add-resource routes that already used `read_json_dict`, as a malformed body); routes that wrap their own bare `request.json()` in a broad `except` are not converted and still answer such a disconnect with their own error handling.
diff --git a/src/local_deep_research/web/dependencies/json_body.py b/src/local_deep_research/web/dependencies/json_body.py
index 651f262629..965f26dbca 100644
--- a/src/local_deep_research/web/dependencies/json_body.py
+++ b/src/local_deep_research/web/dependencies/json_body.py
@@ -17,14 +17,18 @@ where main returned a clean **400**. That is a real contract change: a
malformed client request now looks like a backend outage, in logs and in
monitoring alike.
-This module supplies the response half. Call sites keep their own
-``await request.json()`` (and whatever ``except`` they already have for a
-*malformed* body, which is a different failure) and add the missing shape
-check:
+``read_json_dict`` is the way to parse a JSON object body. It answers a body
+that will not parse and a body that parses to something other than an
+object with the same 400, so a call site cannot forget the parse failure
+the way the hand-written ports did:
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error(...)
+ data, err = await read_json_dict(request, ...)
+ if err is not None:
+ return err
+
+The call must not sit inside a broad ``except``, which would swallow what
+the helper lets through on purpose: the request-size limit's exception and a
+client disconnect. Its docstring has the details.
``get_json(silent=True)`` also returned ``None`` when the Content-Type was
not a JSON media type, so the decorator refused a JSON-looking
@@ -114,12 +118,31 @@ async def read_json_dict(
on 9 of the 11 news body endpoints. A 500 tells the caller (and paging
alerts) that the server is broken, when the client simply sent bad bytes.
- Never raises: the whole point is that the caller cannot forget the parse
- error the way the hand-written ports did.
+ Only a body the CLIENT got wrong is answered here, so the caller cannot
+ forget the parse error the way the hand-written ports did. That is what
+ ``request.json()`` raises for a body it cannot parse: ``ValueError``
+ (``json.JSONDecodeError`` for bad syntax, ``UnicodeDecodeError`` for
+ undecodable bytes, and the plain ``ValueError`` ``json.loads`` raises for
+ an integer literal past ``sys.get_int_max_str_digits()``) and
+ ``RecursionError`` (nesting deeper than the parser can follow). The
+ optional-body cleanup route in ``routers/settings.py`` catches the same
+ pair around its own parse.
+
+ Everything else propagates, on purpose. ``request.json()`` also reads the
+ request stream, so it is where transport failures surface:
+ ``BodySizeLimitMiddleware`` enforces its JSON cap on a body streamed
+ without a Content-Length by raising from the receive channel, and answers
+ 413 (and logs the rejection) once that exception reaches it; a dropped
+ client surfaces as ``ClientDisconnect``, which the app-level handler in
+ ``fastapi_app.py`` logs at info level and answers 499. A broad
+ ``except Exception`` here turned an over-cap body into the route's 400
+ envelope and kept the rejection out of the log. For the same reason a
+ caller must not wrap this call in a broad ``except`` of its own, which
+ would swallow those exceptions one frame up.
"""
try:
data = await request.json()
- except Exception:
+ except (ValueError, RecursionError):
return None, json_body_error(error_format, error_message)
if not isinstance(data, dict):
return None, json_body_error(error_format, error_message)
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index b4f4fb840f..493cddfd88 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -22,6 +22,7 @@ from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from loguru import logger
from starlette.middleware.sessions import SessionMiddleware
+from starlette.requests import ClientDisconnect
from ..__version__ import __version__
from ..security import get_security_default
@@ -1632,6 +1633,36 @@ def _register_exception_handlers(app: FastAPI) -> None:
)
return JSONResponse({"error": "Invalid JSON body"}, status_code=400)
+ # A client that hangs up before its request body is complete surfaces
+ # from ``await request.json()`` (and ``body()``/``stream()``/``form()``)
+ # as ``ClientDisconnect``. ``read_json_dict`` lets it through on purpose
+ # (its docstring has the reasoning), so without a handler here the
+ # catch-all above reports it as a backend outage: an error-level log
+ # with a traceback and a 500, for something that is the client's doing.
+ #
+ # Info level, no traceback, and a 4xx. 499 is nginx's "Client Closed
+ # Request", the de-facto status for exactly this: unlike a 5xx it is not
+ # counted as a server fault, and unlike 400 it cannot be mistaken for a
+ # malformed body. The client is gone, so uvicorn drops whatever is sent
+ # after the disconnect (and writes no access-log line for it); the
+ # status is only ever seen in-process.
+ #
+ # Registered for ``ClientDisconnect`` alone. The over-cap exception
+ # ``BodySizeLimitMiddleware`` raises is a different class and still
+ # reaches that middleware, which logs the rejection and answers 413.
+ @app.exception_handler(ClientDisconnect)
+ async def handle_client_disconnect(request: Request, exc):
+ from .routers.notes import _log_value_preview
+
+ # Bounded fields only, as the decode-error handler above does. The
+ # path is client-chosen (#6938), so it is bounded too.
+ logger.info(
+ "Client disconnected before the request body was complete: {} {}",
+ request.method,
+ _log_value_preview(request.url.path),
+ )
+ return JSONResponse({"error": "Client disconnected"}, status_code=499)
+
@app.exception_handler(WebAPIException)
async def handle_web_api_exception(request: Request, exc: WebAPIException):
logger.error(
diff --git a/src/local_deep_research/web/routers/benchmark.py b/src/local_deep_research/web/routers/benchmark.py
index 0ac34fa887..a3a8a9e138 100644
--- a/src/local_deep_research/web/routers/benchmark.py
+++ b/src/local_deep_research/web/routers/benchmark.py
@@ -17,7 +17,7 @@ from ...llm.providers.base import normalize_provider
from local_deep_research.settings import SettingsManager
from ...benchmarks.web_api.benchmark_service import benchmark_service
-from ..dependencies.json_body import json_body_error
+from ..dependencies.json_body import read_json_dict
from typing import Annotated
# Benchmark runs spawn full LLM + search loops (expensive enough that
@@ -119,9 +119,11 @@ async def start_benchmark(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Start a new benchmark run."""
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "No data provided")
+ data, body_error = await read_json_dict(
+ request, "simple", "No data provided"
+ )
+ if body_error is not None:
+ return body_error
session_id = request.session.get("session_id")
return await run_db_sync(_start_benchmark_sync, data, username, session_id)
@@ -941,9 +943,11 @@ async def start_benchmark_simple(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Start a benchmark using current database settings."""
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "simple", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
session_id = request.session.get("session_id")
return await run_db_sync(
_start_benchmark_simple_sync, data, username, session_id
diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.py
index 9e4a99944a..9fab98977a 100644
--- a/src/local_deep_research/web/routers/library.py
+++ b/src/local_deep_research/web/routers/library.py
@@ -62,7 +62,7 @@ from ...utilities.db_utils import get_settings_manager
from ...config.paths import get_library_directory
from ...security.log_sanitizer import redact_and_bound_for_log
from ...web.exceptions import AuthenticationRequiredError
-from ..dependencies.json_body import json_body_error
+from ..dependencies.json_body import read_json_dict
from .notes import _log_value_preview
from typing import Annotated
@@ -1004,9 +1004,11 @@ async def download_research_pdfs(
):
"""Queue all PDFs from a research session for download."""
user_password = get_authenticated_user_password(username)
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "simple", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
collection_id = data.get("collection_id")
# `queue_research_downloads` does sync SQLAlchemy work. Keep it off
@@ -1110,9 +1112,11 @@ async def download_bulk(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Download PDFs or extract text from multiple research sessions."""
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "simple", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
research_ids = data.get("research_ids", [])
mode = data.get("mode", "pdf") # pdf or text_only
collection_id = data.get(
@@ -1496,9 +1500,11 @@ async def mark_for_redownload(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Mark documents for re-download."""
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "simple", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
document_ids = data.get("document_ids", [])
if not document_ids:
@@ -1888,9 +1894,11 @@ async def check_downloads(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Check download status for a list of URLs."""
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "simple", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
research_id = data.get("research_id")
urls = data.get("urls", [])
@@ -1944,9 +1952,11 @@ async def download_source(
):
"""Download a single source from a research."""
user_password = get_authenticated_user_password(username)
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "simple", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
research_id = data.get("research_id")
url = data.get("url")
diff --git a/src/local_deep_research/web/routers/library_search.py b/src/local_deep_research/web/routers/library_search.py
index b7258d5987..1610057ce3 100644
--- a/src/local_deep_research/web/routers/library_search.py
+++ b/src/local_deep_research/web/routers/library_search.py
@@ -15,7 +15,7 @@ from ..dependencies.threadpool import run_db_sync
from ...database.models.library import Collection, Document
from ...research_library.utils import handle_api_error
-from ..dependencies.json_body import json_body_error
+from ..dependencies.json_body import json_body_error, read_json_dict
from typing import Annotated
router = APIRouter(prefix="/library", tags=["search"])
@@ -132,9 +132,11 @@ async def convert_all_research(
ResearchHistoryIndexer,
)
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("success", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "success", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
force = data.get("force", False)
if not isinstance(force, bool):
return json_body_error("success", "force must be a boolean")
@@ -184,9 +186,11 @@ async def add_research_to_collection(
collection_id: UUID of the target collection (required)
"""
session_id = request.session.get("session_id")
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("success", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "success", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
return await run_db_sync(
_add_research_to_collection_sync,
data,
@@ -283,9 +287,11 @@ async def search_collection(
limit: Maximum number of results (default 10)
"""
session_id = request.session.get("session_id")
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("success", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "success", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
return await run_db_sync(
_search_collection_sync, data, collection_id, username, session_id
)
diff --git a/src/local_deep_research/web/routers/metrics.py b/src/local_deep_research/web/routers/metrics.py
index 2cf9bb8513..9f0fac72d2 100644
--- a/src/local_deep_research/web/routers/metrics.py
+++ b/src/local_deep_research/web/routers/metrics.py
@@ -40,7 +40,7 @@ from ...metrics.query_utils import (
)
from ...metrics.search_tracker import get_search_tracker
from ...security import redact_url_for_log, url_authority_without_userinfo
-from ..dependencies.json_body import json_body_error
+from ..dependencies.json_body import json_body_error, read_json_dict
from .notes import _log_value_preview
# Create the router for metrics
@@ -1290,13 +1290,13 @@ async def api_save_research_rating(
username: Annotated[str, Depends(require_auth)],
):
"""Save or update rating for a specific research session."""
- # Parsed outside the try/except below: a malformed body must raise
- # json.JSONDecodeError uncaught so it reaches the app's registered
- # handler (-> 400), not the broad `except Exception` further down
- # (which would otherwise turn it into a hardcoded 500).
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("status", "Request body must be valid JSON")
+ # Parse before the broad exception handler so malformed bodies retain
+ # this route's validation envelope instead of becoming server errors.
+ data, body_error = await read_json_dict(
+ request, "status", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
try:
rating_value = data.get("rating")
@@ -1920,13 +1920,13 @@ async def api_cost_calculation(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Calculate cost for token usage."""
- # Parsed outside the try/except below: a malformed body must raise
- # json.JSONDecodeError uncaught so it reaches the app's registered
- # handler (-> 400), not the broad `except Exception` further down
- # (which would otherwise turn it into a hardcoded 500).
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "No data provided")
+ # Parse before the broad exception handler so malformed bodies retain
+ # this route's validation envelope instead of becoming server errors.
+ data, body_error = await read_json_dict(
+ request, "simple", "No data provided"
+ )
+ if body_error is not None:
+ return body_error
try:
model_name = data.get("model_name")
provider = data.get("provider") # Optional provider parameter
@@ -2291,12 +2291,11 @@ async def api_classify_domains(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Trigger classification of a specific domain or batch classification."""
- data = await request.json()
- # `or {}` alone only guards FALSY bodies (None, [], ""); a truthy
- # non-dict (bare string, int, non-empty list/array) would still reach
- # `.get(...)` below and raise AttributeError -> 500.
- if not isinstance(data, dict):
- return json_body_error("status", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "status", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
domain = data.get("domain")
force_update = data.get("force_update", False)
batch_mode = data.get("batch", False)
diff --git a/src/local_deep_research/web/routers/news_flask_api.py b/src/local_deep_research/web/routers/news_flask_api.py
index d979b45c59..7e93d40a71 100644
--- a/src/local_deep_research/web/routers/news_flask_api.py
+++ b/src/local_deep_research/web/routers/news_flask_api.py
@@ -482,15 +482,14 @@ async def create_subscription(
subscription_type: "search" or "topic" (default: "search")
refresh_minutes: Refresh interval in minutes (default: from settings)
"""
- try:
- data, _body_err = await read_json_dict(
- request, "simple", "No JSON data provided"
- )
- if _body_err is not None:
- return _body_err
- except Exception:
- # Handle invalid JSON
- return JSONResponse({"error": "Invalid JSON data"}, status_code=400)
+ # No broad ``except`` around the parse: ``read_json_dict`` answers a
+ # malformed body itself, and anything else it raises (the request-size
+ # limit's 413, a client disconnect) must reach the middleware intact.
+ data, _body_err = await read_json_dict(
+ request, "simple", "No JSON data provided"
+ )
+ if _body_err is not None:
+ return _body_err
try:
validation_error = _validate_subscription_payload(
@@ -585,13 +584,15 @@ async def vote_on_news(
card_id: ID of the news card
vote: "up" or "down"
"""
- try:
- data, _body_err = await read_json_dict(
- request, "simple", "No JSON data provided"
- )
- if _body_err is not None:
- return _body_err
+ # Parsed before the broad ``try`` below, which would turn the
+ # request-size limit's exception into a 500 (see ``read_json_dict``).
+ data, _body_err = await read_json_dict(
+ request, "simple", "No JSON data provided"
+ )
+ if _body_err is not None:
+ return _body_err
+ try:
# Get current user
user_id = username
@@ -635,12 +636,15 @@ async def get_batch_feedback(
JSON body:
card_ids: List of card IDs
"""
+ # Parsed before the broad ``try`` below, which would turn the
+ # request-size limit's exception into a 500 (see ``read_json_dict``).
+ data, _body_err = await read_json_dict(
+ request, "simple", "No JSON data provided"
+ )
+ if _body_err is not None:
+ return _body_err
+
try:
- data, _body_err = await read_json_dict(
- request, "simple", "No JSON data provided"
- )
- if _body_err is not None:
- return _body_err
card_ids = data.get("card_ids", [])
if not isinstance(card_ids, list) or any(
not isinstance(card_id, str) or not card_id.strip()
@@ -702,13 +706,15 @@ async def submit_feedback(
JSON body:
vote: "up" or "down"
"""
- try:
- data, _body_err = await read_json_dict(
- request, "simple", "No JSON data provided"
- )
- if _body_err is not None:
- return _body_err
+ # Parsed before the broad ``try`` below, which would turn the
+ # request-size limit's exception into a 500 (see ``read_json_dict``).
+ data, _body_err = await read_json_dict(
+ request, "simple", "No JSON data provided"
+ )
+ if _body_err is not None:
+ return _body_err
+ try:
# Get current user
user_id = username
vote = data.get("vote")
@@ -867,14 +873,14 @@ async def update_subscription(
username: Annotated[str, Depends(require_auth)],
) -> Any:
"""Update a subscription."""
- try:
- data, _body_err = await read_json_dict(
- request, "simple", "No JSON data provided"
- )
- if _body_err is not None:
- return _body_err
- except Exception:
- return JSONResponse({"error": "Invalid JSON data"}, status_code=400)
+ # No broad ``except`` around the parse: ``read_json_dict`` answers a
+ # malformed body itself, and anything else it raises (the request-size
+ # limit's 413, a client disconnect) must reach the middleware intact.
+ data, _body_err = await read_json_dict(
+ request, "simple", "No JSON data provided"
+ )
+ if _body_err is not None:
+ return _body_err
try:
validation_error = _validate_subscription_payload(data)
@@ -1138,13 +1144,15 @@ async def save_preferences(
request: Request, username: Annotated[str, Depends(require_auth)]
) -> Any:
"""Save user preferences for news."""
- try:
- data, _body_err = await read_json_dict(
- request, "simple", "No JSON data provided"
- )
- if _body_err is not None:
- return _body_err
+ # Parsed before the broad ``try`` below, which would turn the
+ # request-size limit's exception into a 500 (see ``read_json_dict``).
+ data, _body_err = await read_json_dict(
+ request, "simple", "No JSON data provided"
+ )
+ if _body_err is not None:
+ return _body_err
+ try:
# Get current user
user_id = username
preferences = data.get("preferences", {})
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index e948dc4bab..c8d2049a51 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -86,7 +86,7 @@ from ...database.models.queue import TaskMetadata
from ...database.thread_local_session import thread_cleanup
from ...config.paths import get_library_directory
-from ..dependencies.json_body import json_body_error
+from ..dependencies.json_body import json_body_error, read_json_dict
from .notes import _log_value_preview
#: Upper bound on ``page`` -- see context_overflow_api for the rationale.
@@ -2019,9 +2019,11 @@ async def create_collection(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Create a new document collection."""
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("success", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "success", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
return await run_db_sync(_create_collection_sync, data, username)
@@ -2172,9 +2174,11 @@ async def update_collection(
username: Annotated[str, Depends(require_auth)],
):
"""Update a collection's details."""
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("success", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "success", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
return await run_db_sync(
_update_collection_sync, data, collection_id, username
)
@@ -4728,15 +4732,13 @@ async def start_background_index(
username, session_id
)
- # Parse request body. `await request.json()` raising on malformed bytes
- # is left to propagate to the app's registered json.JSONDecodeError ->
- # 400 handler (no local except here to shadow it). A truthy non-dict
- # body (bare string/int/list) is guarded explicitly below — `or {}`
- # alone only catches FALSY bodies (null, [], ""), letting a truthy
- # non-dict reach `.get()` and raise AttributeError -> 500.
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("success", "Request body must be valid JSON")
+ # The shared parser rejects both malformed and non-object bodies before
+ # they reach the indexing controls below.
+ data, body_error = await read_json_dict(
+ request, "success", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
force_reindex = data.get("force_reindex", False)
if not isinstance(force_reindex, bool):
return JSONResponse(
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 79a64b4e81..61d5a21dcf 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -111,7 +111,11 @@ from ...constants import (
LANGGRAPH_STRATEGY_ALIASES,
LANGGRAPH_STRATEGY_NAME as LANGGRAPH_STRATEGY_NAME,
)
-from ..dependencies.json_body import is_json_request, json_body_error
+from ..dependencies.json_body import (
+ is_json_request,
+ json_body_error,
+ read_json_dict,
+)
from ..utils.pagination import OFFSET_LIMIT_ERROR, parse_bounded_offset
# Create the router for the research application
@@ -2275,9 +2279,11 @@ async def save_raw_config(
# type with this 400 before the config file could be written.
if not is_json_request(request):
return json_body_error("success", "Request body must be valid JSON")
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("success", "Request body must be valid JSON")
+ data, body_error = await read_json_dict(
+ request, "success", "Request body must be valid JSON"
+ )
+ if body_error is not None:
+ return body_error
raw_config = data.get("raw_config")
if not raw_config:
diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.py
index 0919495165..9bd76fbf9d 100644
--- a/src/local_deep_research/web/routers/settings.py
+++ b/src/local_deep_research/web/routers/settings.py
@@ -137,7 +137,7 @@ from ...security import safe_get
# therefore does NOT narrow what this merge will restore.
from ...security.data_sanitizer import DataSanitizer, _is_empty_value
from ..warning_checks import calculate_warnings
-from ..dependencies.json_body import json_body_error
+from ..dependencies.json_body import json_body_error, read_json_dict
# Create the router for settings
router = APIRouter(prefix="/settings", tags=["settings"])
@@ -2356,9 +2356,11 @@ async def save_all_settings(
Thin async wrapper that reads the JSON body, then offloads the
entire sync save to a thread so we don't block the event loop.
"""
- form_data = await request.json()
- if not isinstance(form_data, dict):
- return json_body_error("status", "No settings data provided")
+ form_data, body_error = await read_json_dict(
+ request, "status", "No settings data provided"
+ )
+ if body_error is not None:
+ return body_error
if not form_data:
return JSONResponse(
{"status": "error", "message": "No settings data provided"},
@@ -4160,9 +4162,11 @@ async def api_update_search_favorites(
username: Annotated[str, Depends(require_auth)],
):
"""Update the list of favorite search engines for the current user"""
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "No data provided")
+ data, body_error = await read_json_dict(
+ request, "simple", "No data provided"
+ )
+ if body_error is not None:
+ return body_error
def _impl():
try:
@@ -4213,9 +4217,11 @@ async def api_toggle_search_favorite(
username: Annotated[str, Depends(require_auth)],
):
"""Toggle a search engine as favorite"""
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "No data provided")
+ data, body_error = await read_json_dict(
+ request, "simple", "No data provided"
+ )
+ if body_error is not None:
+ return body_error
def _impl():
try:
@@ -4587,17 +4593,24 @@ async def api_cleanup_rate_limiting(
Note: not using @require_json_body because the JSON body is optional
here — the endpoint works with or without a payload (defaults to 30 days).
- ``await request.json()`` is deliberately called outside any broad
- ``except Exception`` so a malformed body reaches the app's registered
- ``json.JSONDecodeError`` -> 400 handler instead of being swallowed here
- and reported as a 500 (see ``web/dependencies/json_body.py``). The
- isinstance check below is the same reasoning as ``@require_json_body``:
+ Parse errors use the same response as a non-object body. The body is
+ optional, so ``read_json_dict`` would reject valid ``null`` and cannot
+ be used here. The isinstance check below has the same reasoning as
+ ``@require_json_body``:
a *valid but truthy non-dict* JSON body (e.g. ``[]`` or a bare number)
would otherwise reach ``data.get(...)`` and raise ``AttributeError``.
+
+ The parse catches exactly what ``read_json_dict`` does: ``ValueError``
+ (bad syntax, undecodable bytes, an oversized integer literal) and
+ ``RecursionError`` (nesting too deep to parse). Anything else, such as
+ the request-size limit's exception, must propagate to its own handler.
"""
content_type = request.headers.get("content-type", "")
is_json = "application/json" in content_type
- data = await request.json() if is_json else None
+ try:
+ data = await request.json() if is_json else None
+ except (ValueError, RecursionError):
+ return json_body_error("simple", "Request body must be a JSON object")
if data is not None and not isinstance(data, dict):
return json_body_error("simple", "Request body must be a JSON object")
days = data.get("days", 30) if data is not None else 30
@@ -5131,9 +5144,11 @@ async def api_update_setting(
username: Annotated[str, Depends(require_auth)],
):
"""Update a setting"""
- data = await request.json()
- if not isinstance(data, dict):
- return json_body_error("simple", "No data provided")
+ data, body_error = await read_json_dict(
+ request, "simple", "No data provided"
+ )
+ if body_error is not None:
+ return body_error
return await run_db_sync(_api_update_setting_sync, data, key, username)
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 45d0ace162..ac0798a9c4 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -7,6 +7,7 @@ This module provides common utilities for tests.
import json
import sys
+import threading
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -249,3 +250,38 @@ class MockCache:
"misses": self.misses,
"size": len(self.cache),
}
+
+
+def nested_json_past_the_scanner_limit() -> bytes:
+ """Arrays nested deeper than ``json.loads`` can follow on this interpreter.
+
+ The depth at which CPython's C scanner gives up and raises
+ ``RecursionError`` depends on the running thread's stack size, not on a
+ language constant, so a hardcoded depth would parse into a valid array on
+ a machine with a roomier stack and quietly stop testing anything. The
+ depth is probed on a plain thread, which is where Starlette's test portal
+ parses a request body, and quadrupled to keep a margin over any
+ difference between the two stacks. Even on a 64 MB thread stack the body
+ stays well inside the app's 16 MB JSON cap.
+ """
+ refused: List[int] = []
+
+ def probe():
+ depth = 10_000
+ for _ in range(8):
+ try:
+ json.loads(b"[" * depth + b"]" * depth)
+ except RecursionError:
+ refused.append(depth)
+ return
+ depth *= 2
+
+ thread = threading.Thread(target=probe)
+ thread.start()
+ thread.join()
+ assert refused, (
+ "no nesting depth up to 1 280 000 made json.loads raise "
+ "RecursionError, so a test built on it would no longer test anything"
+ )
+ depth = refused[0] * 4
+ return b"[" * depth + b"]" * depth
diff --git a/tests/web/dependencies/test_json_body_contract.py b/tests/web/dependencies/test_json_body_contract.py
index a2841e14bc..dfd3e0123b 100644
--- a/tests/web/dependencies/test_json_body_contract.py
+++ b/tests/web/dependencies/test_json_body_contract.py
@@ -41,16 +41,20 @@ endpoint name survived. There is no decorator any more — the guard is a
plain call inside the handler — so there is no wrapper to preserve anything.
"""
+import asyncio
import json
+import sys
import pytest
from fastapi import FastAPI, Request
+from starlette.requests import ClientDisconnect
from starlette.testclient import TestClient
from local_deep_research.web.dependencies.json_body import (
is_json_request,
read_json_dict,
)
+from tests.test_utils import nested_json_past_the_scanner_limit
DEFAULT = "Request body must be valid JSON"
@@ -195,6 +199,129 @@ class TestNonDictJSON:
assert resp.json() == {"error": DEFAULT}
+# ---------------------------------------------------------------------------
+# Every way the parser can refuse a body is the client's 400
+#
+# ``request.json()`` is ``json.loads(await self.body())``. Besides
+# ``json.JSONDecodeError`` it raises ``UnicodeDecodeError`` for undecodable
+# bytes, a plain ``ValueError`` (not a JSONDecodeError) for an integer literal
+# past ``sys.get_int_max_str_digits()``, and ``RecursionError`` (not a
+# ValueError) for nesting deeper than the C scanner can follow. All four are
+# a malformed body. A guard narrowed to the first two would answer the other
+# two with a 500.
+# ---------------------------------------------------------------------------
+def _integer_past_the_digit_limit() -> bytes:
+ limit = sys.get_int_max_str_digits()
+ if limit == 0:
+ pytest.skip("this interpreter does not limit integer literals")
+ return b"1" * (limit + 1)
+
+
+class TestEveryParserRefusalIsTheClientsFourHundred:
+ @pytest.mark.parametrize(
+ ("build_body", "refusal"),
+ [
+ pytest.param(
+ lambda: b"{not json", json.JSONDecodeError, id="bad-syntax"
+ ),
+ pytest.param(
+ lambda: b'{"name": "\xff\xfe"}',
+ UnicodeDecodeError,
+ id="undecodable-bytes",
+ ),
+ pytest.param(
+ _integer_past_the_digit_limit,
+ ValueError,
+ id="integer-past-the-digit-limit",
+ ),
+ pytest.param(
+ nested_json_past_the_scanner_limit,
+ RecursionError,
+ id="nesting-too-deep",
+ ),
+ ],
+ )
+ def test_a_body_the_parser_refuses_gets_the_envelope(
+ self, client, build_body, refusal
+ ):
+ body = build_body()
+
+ # Premise: the body fails in exactly the way it is named for, so the
+ # 400 below cannot be a pass for some other reason.
+ with pytest.raises(refusal) as caught:
+ json.loads(body)
+ assert type(caught.value) is refusal
+
+ resp = _post(client, "/simple", body)
+
+ assert resp.status_code == 400, (
+ f"{refusal.__name__} from the parser was not answered as the "
+ f"client's malformed body: {resp.status_code} {resp.text[:200]}"
+ )
+ assert resp.json() == {"error": DEFAULT}
+
+
+# ---------------------------------------------------------------------------
+# Nothing else is the helper's to answer
+#
+# ``request.json()`` reads the request stream, so failures of the stream
+# surface from it as well: the over-cap exception BodySizeLimitMiddleware
+# raises from its receive wrapper, and a client that disconnects mid-body.
+# Neither is a malformed body, and the helper must not make it one.
+# ---------------------------------------------------------------------------
+def _request_with_receive(receive):
+ return Request(
+ {"type": "http", "method": "POST", "path": "/", "headers": []},
+ receive,
+ )
+
+
+class TestOnlyAMalformedBodyIsAnsweredHere:
+ def test_a_body_delivered_in_pieces_parses(self):
+ """Positive control: the scripted channel below is a working one."""
+ pieces = iter(
+ [
+ {"type": "http.request", "body": b'{"a": ', "more_body": True},
+ {"type": "http.request", "body": b"1}", "more_body": False},
+ ]
+ )
+
+ async def receive():
+ return next(pieces)
+
+ data, err = asyncio.run(read_json_dict(_request_with_receive(receive)))
+
+ assert (data, err) == ({"a": 1}, None)
+
+ def test_a_client_disconnect_propagates(self):
+ async def receive():
+ return {"type": "http.disconnect"}
+
+ with pytest.raises(ClientDisconnect):
+ asyncio.run(read_json_dict(_request_with_receive(receive)))
+
+ def test_an_error_raised_by_the_receive_channel_propagates(self):
+ class _OverTheCap(Exception):
+ """Stands in for BodySizeLimitMiddleware's over-cap exception."""
+
+ reads = []
+
+ async def receive():
+ reads.append(1)
+ if len(reads) == 1:
+ return {
+ "type": "http.request",
+ "body": b'{"padding": "xxxx',
+ "more_body": True,
+ }
+ raise _OverTheCap
+
+ with pytest.raises(_OverTheCap):
+ asyncio.run(read_json_dict(_request_with_receive(receive)))
+
+ assert len(reads) == 2, "the error must come from mid-body, not setup"
+
+
# ---------------------------------------------------------------------------
# Custom error messages
# ---------------------------------------------------------------------------
diff --git a/tests/web/routers/test_json_body_error_envelopes.py b/tests/web/routers/test_json_body_error_envelopes.py
new file mode 100644
index 0000000000..ee88a78d78
--- /dev/null
+++ b/tests/web/routers/test_json_body_error_envelopes.py
@@ -0,0 +1,428 @@
+"""Malformed and non-object JSON must share each route's validation envelope.
+
+The envelope answers a body the CLIENT got wrong. A body that is too large
+for the JSON cap is not the route's to answer: the second half of this file
+pins that it still reaches ``BodySizeLimitMiddleware`` (413) instead of being
+turned into the envelope. A client that disconnects mid-body propagates the
+same way, to the app-level handler: the third section pins that it is logged
+at info level and answered 499, not reported as a 500. That the helper lets
+both through is pinned at the helper, in
+``tests/web/dependencies/test_json_body_contract.py``.
+"""
+
+import ast
+import asyncio
+import json
+from pathlib import Path
+
+import pytest
+
+from local_deep_research import web
+from local_deep_research.web.dependencies.json_body import DEFAULT_MESSAGE
+
+#: The routes this change moved onto ``read_json_dict``, each with the 400
+#: envelope it answers for a body that is not a JSON object. Callers that
+#: already used the helper are listed below only where they also have a broad
+#: ``try``; four (``api.py``'s add-resource route and three news folder and
+#: subscription routes) have no entry in this file.
+ENVELOPES = [
+ (
+ "post",
+ "/settings/save_all_settings",
+ {"status": "error", "message": "No settings data provided"},
+ ),
+ (
+ "put",
+ "/settings/api/search-favorites",
+ {"error": "No data provided"},
+ ),
+ (
+ "post",
+ "/settings/api/search-favorites/toggle",
+ {"error": "No data provided"},
+ ),
+ ("put", "/settings/api/example.key", {"error": "No data provided"}),
+ (
+ "post",
+ "/library/api/download-research/research-id",
+ {"error": DEFAULT_MESSAGE},
+ ),
+ ("post", "/library/api/download-bulk", {"error": DEFAULT_MESSAGE}),
+ ("post", "/library/api/mark-redownload", {"error": DEFAULT_MESSAGE}),
+ ("post", "/library/api/check-downloads", {"error": DEFAULT_MESSAGE}),
+ ("post", "/library/api/download-source", {"error": DEFAULT_MESSAGE}),
+ (
+ "post",
+ "/metrics/api/ratings/research-id",
+ {"status": "error", "message": DEFAULT_MESSAGE},
+ ),
+ (
+ "post",
+ "/metrics/api/cost-calculation",
+ {"error": "No data provided"},
+ ),
+ (
+ "post",
+ "/metrics/api/domain-classifications/classify",
+ {"status": "error", "message": DEFAULT_MESSAGE},
+ ),
+ (
+ "post",
+ "/library/api/research-history/convert-all",
+ {"success": False, "error": DEFAULT_MESSAGE},
+ ),
+ (
+ "post",
+ "/library/api/research/research-id/add-to-collection",
+ {"success": False, "error": DEFAULT_MESSAGE},
+ ),
+ (
+ "post",
+ "/library/api/collections/collection-id/search",
+ {"success": False, "error": DEFAULT_MESSAGE},
+ ),
+ (
+ "post",
+ "/library/api/collections",
+ {"success": False, "error": DEFAULT_MESSAGE},
+ ),
+ (
+ "put",
+ "/library/api/collections/collection-id",
+ {"success": False, "error": DEFAULT_MESSAGE},
+ ),
+ (
+ "post",
+ "/library/api/collections/collection-id/index/start",
+ {"success": False, "error": DEFAULT_MESSAGE},
+ ),
+ ("post", "/benchmark/api/start", {"error": "No data provided"}),
+ ("post", "/benchmark/api/start-simple", {"error": DEFAULT_MESSAGE}),
+ (
+ "post",
+ "/api/save_raw_config",
+ {"success": False, "error": DEFAULT_MESSAGE},
+ ),
+]
+
+
[email protected](("method", "path", "envelope"), ENVELOPES)
+ "body", [b"{bad json", b"[1]"], ids=["malformed", "non-object"]
+)
+def test_json_body_error_envelope(
+ authenticated_client, method, path, envelope, body
+):
+ response = getattr(authenticated_client, method)(
+ path,
+ content=body,
+ headers={"Content-Type": "application/json"},
+ )
+
+ assert response.status_code == 400
+ assert response.json() == envelope
+
+
+# ---------------------------------------------------------------------------
+# A body past the JSON cap is the middleware's to reject, not the route's
+# ---------------------------------------------------------------------------
+#
+# BodySizeLimitMiddleware rejects a declared over-cap Content-Length before
+# any route runs. A body streamed WITHOUT one (chunked transfer) can only be
+# counted as it is read, so the middleware raises from its receive wrapper;
+# the exception surfaces inside ``await request.json()`` and the middleware
+# turns it into the 413 and logs the rejection once it reaches it. A broad
+# ``except`` between the two answers 400 with the route's envelope instead.
+
+#: Routes that call ``read_json_dict`` from a handler that also has a broad
+#: ``try``/``except`` for the work after the parse (news_flask_api.py). The
+#: routes above have none, so these are the ones where a wrapper around the
+#: helper, rather than the helper itself, could still swallow the exception.
+NEWS_ROUTES_WITH_A_BROAD_TRY = [
+ ("post", "/news/api/subscribe"),
+ ("post", "/news/api/vote"),
+ ("post", "/news/api/feedback/batch"),
+ ("post", "/news/api/feedback/card-id"),
+ ("put", "/news/api/subscriptions/subscription-id"),
+ ("post", "/news/api/preferences"),
+]
+
+OVER_CAP_ROUTES = [
+ (method, path) for method, path, _envelope in ENVELOPES
+] + NEWS_ROUTES_WITH_A_BROAD_TRY
+
+
+def _chunks_past_the_json_cap():
+ """A JSON object a little past the 16 MB JSON cap, yielded in pieces.
+
+ A generator body is sent as ``Transfer-Encoding: chunked`` with no
+ Content-Length header, so the middleware's declared-length check has
+ nothing to reject and only the streaming count can.
+ """
+ from local_deep_research.web.fastapi_app import (
+ _DEFAULT_MAX_SMALL_JSON_BODY_SIZE,
+ )
+
+ yield b'{"padding": "'
+ yield b"x" * _DEFAULT_MAX_SMALL_JSON_BODY_SIZE
+ yield b'"}'
+
+
[email protected](("method", "path"), OVER_CAP_ROUTES)
+def test_over_cap_chunked_body_is_a_413_from_the_middleware(
+ authenticated_client, loguru_caplog, method, path
+):
+ with loguru_caplog.at_level("WARNING"):
+ response = getattr(authenticated_client, method)(
+ path,
+ content=_chunks_past_the_json_cap(),
+ headers={"Content-Type": "application/json"},
+ )
+
+ assert response.status_code == 413, (
+ f"{method.upper()} {path} answered {response.status_code} "
+ f"{response.text[:200]!r} for a body streamed past the JSON cap; "
+ "the middleware's 413 was swallowed on the way out"
+ )
+ # Same negotiation as BodySizeLimitMiddleware._send_413: a JSON body
+ # for API paths, the branded page elsewhere.
+ if "/api/" in path:
+ assert response.json() == {"error": "Request too large"}
+ # The 413 came from the middleware's own handler, which is also what
+ # puts the rejection in the log for monitoring.
+ assert "Rejected over-limit request body" in loguru_caplog.text
+
+
+# ---------------------------------------------------------------------------
+# A client that hangs up mid-body is not a server fault
+# ---------------------------------------------------------------------------
+#
+# ``read_json_dict`` lets ``ClientDisconnect`` propagate, as it does the
+# over-cap exception. The over-cap exception has BodySizeLimitMiddleware to
+# receive it; ``ClientDisconnect`` has the app-level handler in
+# fastapi_app.py. Without that handler the catch-all reports the hang-up as a
+# backend outage: an error-level log with a traceback, and a 500.
+
+
+def _hang_up_mid_body(client, method, path):
+ """Start a JSON body at ``path`` through the real stack, then disconnect.
+
+ Returns ``(status, body, raised)``. TestClient cannot hang up
+ mid-request, so the assembled app is called as an ASGI callable. The
+ request is built by the authenticated client, so it carries the session
+ cookie and CSRF header and reaches the route, and it promises more bytes
+ than it sends, as a connection dropped in transit does.
+ """
+ start = b'{"padding": "'
+ request = client.build_request(
+ method.upper(),
+ path,
+ headers={"Content-Type": "application/json", "Content-Length": "4096"},
+ content=start,
+ )
+ scope = {
+ "type": "http",
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
+ "http_version": "1.1",
+ "method": request.method,
+ "scheme": "http",
+ "path": path,
+ "raw_path": path.encode(),
+ "root_path": "",
+ "query_string": b"",
+ "client": ("testclient", 50000),
+ "server": ("testserver", 80),
+ "headers": [(k.lower(), v) for k, v in request.headers.raw],
+ }
+ pending = [
+ {"type": "http.request", "body": start, "more_body": True},
+ {"type": "http.disconnect"},
+ ]
+ sent = []
+
+ async def receive():
+ return pending.pop(0) if pending else {"type": "http.disconnect"}
+
+ async def send(message):
+ sent.append(message)
+
+ async def call():
+ try:
+ await asyncio.wait_for(client.app(scope, receive, send), 30)
+ except Exception as exc: # the catch-all re-raises after its 500
+ return exc
+ return None
+
+ raised = asyncio.run(call())
+ starts = [m for m in sent if m["type"] == "http.response.start"]
+ body = b"".join(
+ m.get("body", b"") for m in sent if m["type"] == "http.response.body"
+ )
+ return (starts[0]["status"] if starts else None), body, raised
+
+
+def _json_or_text(body):
+ try:
+ return json.loads(body)
+ except ValueError:
+ return body.decode("utf-8", "replace")[:200]
+
+
+def test_a_client_hanging_up_mid_body_is_not_a_server_error(
+ authenticated_client, loguru_caplog
+):
+ """On every route that reads its body through ``read_json_dict``, the
+ hang-up is an info line with no traceback and a 499, not an error-level
+ log, a 500 and an exception escaping the app."""
+ expected = {
+ "status": 499,
+ "body": {"error": "Client disconnected"},
+ "raised": None,
+ "error_logs": [],
+ # (level, carries a traceback, names the route)
+ "hang_up_logs": [("INFO", False, True)],
+ }
+
+ wrong = {}
+ for method, path in OVER_CAP_ROUTES:
+ loguru_caplog.clear()
+ status, body, raised = _hang_up_mid_body(
+ authenticated_client, method, path
+ )
+ records = loguru_caplog.records
+ observed = {
+ "status": status,
+ "body": _json_or_text(body),
+ "raised": type(raised).__name__ if raised else None,
+ "error_logs": [
+ r.getMessage()
+ for r in records
+ if r.levelname in ("ERROR", "CRITICAL")
+ ],
+ "hang_up_logs": [
+ (r.levelname, bool(r.exc_info), path in r.getMessage())
+ for r in records
+ if "Client disconnected" in r.getMessage()
+ ],
+ }
+ if observed != expected:
+ wrong[f"{method.upper()} {path}"] = observed
+
+ assert not wrong, (
+ f"{len(wrong)} of {len(OVER_CAP_ROUTES)} routes did not treat a "
+ f"mid-body disconnect as the client's doing; expected {expected}, "
+ f"first: {next(iter(wrong.items()))}"
+ )
+
+
+# --- static half: no route may swallow what the helper now lets through ---
+
+WEB_DIR = Path(web.__file__).resolve().parent
+
+_BROAD_EXCEPTIONS = frozenset({"Exception", "BaseException"})
+
+
+def _handler_is_broad(handler):
+ """A bare ``except``, or one naming ``Exception``/``BaseException``."""
+ if handler.type is None:
+ return True
+ clauses = (
+ handler.type.elts
+ if isinstance(handler.type, ast.Tuple)
+ else [handler.type]
+ )
+ return any(
+ isinstance(clause, ast.Name) and clause.id in _BROAD_EXCEPTIONS
+ for clause in clauses
+ )
+
+
+def _read_json_dict_calls(tree):
+ """``[(lineno, in_a_broad_try)]`` for each ``read_json_dict`` call.
+
+ ``in_a_broad_try`` means the call sits in the BODY of a ``try`` whose
+ handlers include a broad one, within the same function: that handler
+ would catch anything the helper lets propagate.
+ """
+ parents = {
+ child: parent
+ for parent in ast.walk(tree)
+ for child in ast.iter_child_nodes(parent)
+ }
+ calls = []
+ for call in ast.walk(tree):
+ if not isinstance(call, ast.Call):
+ continue
+ name = getattr(call.func, "id", None) or getattr(
+ call.func, "attr", None
+ )
+ if name != "read_json_dict":
+ continue
+ wrapped = False
+ child, node = call, parents.get(call)
+ while node is not None and not isinstance(
+ node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
+ ):
+ if (
+ isinstance(node, ast.Try)
+ and child in node.body
+ and any(_handler_is_broad(h) for h in node.handlers)
+ ):
+ wrapped = True
+ break
+ child, node = node, parents.get(node)
+ calls.append((call.lineno, wrapped))
+ return calls
+
+
+_WRAPPED_CALL = """
+async def handler(request):
+ try:
+ data, err = await read_json_dict(request)
+ except Exception:
+ return None
+"""
+
+_HOISTED_CALL = """
+async def handler(request):
+ data, err = await read_json_dict(request)
+ try:
+ use(data)
+ except Exception:
+ return None
+"""
+
+
+def test_the_scan_tells_a_wrapped_call_from_a_hoisted_one():
+ wrapped = _read_json_dict_calls(ast.parse(_WRAPPED_CALL))
+ hoisted = _read_json_dict_calls(ast.parse(_HOISTED_CALL))
+
+ assert [in_try for _line, in_try in wrapped] == [True]
+ assert [in_try for _line, in_try in hoisted] == [False]
+
+
+def test_no_read_json_dict_caller_wraps_it_in_a_broad_except():
+ """A handler's own ``except Exception`` would undo the helper's contract.
+
+ ``read_json_dict`` lets the size-limit exception and a client disconnect
+ propagate; a ``try``/``except Exception`` around the call in the route
+ catches them one frame up and answers 400 or 500 instead of the
+ middleware's 413. Parse the body before the ``try``.
+ """
+ calls = 0
+ offenders = []
+ for path in sorted(WEB_DIR.rglob("*.py")):
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ for lineno, wrapped in _read_json_dict_calls(tree):
+ calls += 1
+ if wrapped:
+ offenders.append(f"{path.relative_to(WEB_DIR)}:{lineno}")
+
+ assert calls >= 30, (
+ f"only {calls} read_json_dict call sites found; the scan has "
+ "stopped matching the source"
+ )
+ assert offenders == [], (
+ "read_json_dict is called inside a broad except, which swallows the "
+ f"request-size limit's exception: {offenders}"
+ )
diff --git a/tests/web/routers/test_library_port_fidelity.py b/tests/web/routers/test_library_port_fidelity.py
index b3d719068d..4eb345efbf 100644
--- a/tests/web/routers/test_library_port_fidelity.py
+++ b/tests/web/routers/test_library_port_fidelity.py
@@ -37,9 +37,8 @@ permanent passing tests.
and returned 400 whenever the body did not parse to a dict.
``UnicodeDecodeError`` is a ``ValueError`` subclass, so werkzeug's
``get_json`` swallowed it too and the decorator produced its normal 400.
- The port reads the body with a bare ``await request.json()``. Its global
- ``UnicodeDecodeError`` handler now restores the same 400 contract for all
- such call sites, including these routes.
+ The port now uses the shared ``read_json_dict`` parser at these routes,
+ preserving each route's 400 validation envelope for invalid UTF-8 too.
"""
import uuid
@@ -325,12 +324,30 @@ def test_text_not_available_is_html_on_the_page_route(library_client):
# demonstrably answered 400 (the decorator ran before the handler and used
# get_json(silent=True), which swallows UnicodeDecodeError as a ValueError).
REQUIRE_JSON_BODY_ROUTES = [
- "/library/api/download-bulk",
- "/library/api/mark-redownload",
- "/library/api/check-downloads",
- "/library/api/download-source",
- "/library/api/research/some-research-id/add-to-collection",
- "/library/api/collections/some-collection-id/search",
+ (
+ "/library/api/download-bulk",
+ {"error": "Request body must be valid JSON"},
+ ),
+ (
+ "/library/api/mark-redownload",
+ {"error": "Request body must be valid JSON"},
+ ),
+ (
+ "/library/api/check-downloads",
+ {"error": "Request body must be valid JSON"},
+ ),
+ (
+ "/library/api/download-source",
+ {"error": "Request body must be valid JSON"},
+ ),
+ (
+ "/library/api/research/some-research-id/add-to-collection",
+ {"success": False, "error": "Request body must be valid JSON"},
+ ),
+ (
+ "/library/api/collections/some-collection-id/search",
+ {"success": False, "error": "Request body must be valid JSON"},
+ ),
]
# Well-formed JSON structure carrying one invalid UTF-8 byte inside a string.
@@ -342,9 +359,7 @@ NON_UTF8_BODY = b'{"research_ids": ["\xff"]}'
def test_non_utf8_body_is_not_a_json_decode_error():
- """Anchors WHY the app-level handler misses this input, so the six xfails
- below cannot be misread as 'malformed JSON is unhandled' (it is handled --
- see test_malformed_json_bytes_is_400 in test_library_hostile_input.py).
+ """Anchor why route-level parsing must handle more than JSONDecodeError.
Also pins main's side of the contract, read out of the installed werkzeug
3.1.8 rather than restated: get_json(silent=True) -- exactly what
@@ -368,8 +383,8 @@ def test_non_utf8_body_is_not_a_json_decode_error():
assert Request(environ).get_json(silent=True) is None
[email protected]("route", REQUIRE_JSON_BODY_ROUTES)
-def test_non_utf8_body_is_400_not_500(library_client, route):
[email protected](("route", "envelope"), REQUIRE_JSON_BODY_ROUTES)
+def test_non_utf8_body_is_400_not_500(library_client, route, envelope):
client, _, _ = library_client
resp = client.post(
route,
@@ -381,4 +396,4 @@ def test_non_utf8_body_is_400_not_500(library_client, route):
f"{route} answered {resp.status_code} for a body main rejected with "
f"400: {resp.text[:200]}"
)
- assert resp.json() == {"error": "Invalid JSON body"}
+ assert resp.json() == envelope
diff --git a/tests/web/routers/test_rag_hostile_input.py b/tests/web/routers/test_rag_hostile_input.py
index ad99a82a60..7713d87b15 100644
--- a/tests/web/routers/test_rag_hostile_input.py
+++ b/tests/web/routers/test_rag_hostile_input.py
@@ -87,14 +87,9 @@ MALFORMED_BODIES = [
]
_MALFORMED_IDS = [label for label, _ in MALFORMED_BODIES]
-# Same five bodies, minus "malformed_json_bytes". Used for the two routes
-# (index/start, create/update collection) where malformed *bytes* were
-# never routed through a local `except` at all -- `await request.json()`
-# there already propagated straight to the app's registered
-# `json.JSONDecodeError -> 400` handler, unaffected by this fix (that
-# handler answers the app-wide "simple" shape, not this route's
-# "success" shape -- see NON_DECODE_MALFORMED_BODIES tests below for the
-# cases this fix actually touches on those two routes).
+# Same five bodies, minus "malformed_json_bytes". Kept as a separate set
+# because the parsed-but-wrong-type cases exercise the routes' shape guard,
+# while the malformed-bytes cases exercise their shared parser.
NON_DECODE_MALFORMED_BODIES = [
(label, body)
for label, body in MALFORMED_BODIES
@@ -112,10 +107,6 @@ EXPECTED_JSON_ERROR_BODY = {
"error": "Request body must be valid JSON",
}
-# The app-wide handler_json_decode_error's shape (fastapi_app.py), reached
-# whenever a route has no local except around `await request.json()`.
-EXPECTED_GLOBAL_DECODE_ERROR_BODY = {"error": "Invalid JSON body"}
-
@pytest.fixture(scope="module")
def auth_client():
@@ -271,18 +262,13 @@ _INDEX_START_PATH = (
def test_index_start_rejects_malformed_json_bytes_with_400(auth_client):
- """Malformed *bytes* were never routed through a local ``except`` on
- this route -- ``await request.json()`` propagates straight to the
- app's registered ``json.JSONDecodeError -> 400`` handler, which was
- already correct (400, "simple" shape) before this fix and is untouched
- by it. Included for completeness of the acceptance checklist, not as
- evidence of this fix (see the Shape B tests below for that)."""
+ """Malformed bytes use the route's success envelope like non-object JSON."""
resp = auth_client.post(
_INDEX_START_PATH, content=b"{not valid json", headers=_JSON_HEADERS
)
assert resp.status_code == 400, resp.text
- assert resp.json() == EXPECTED_GLOBAL_DECODE_ERROR_BODY, resp.json()
+ assert resp.json() == EXPECTED_JSON_ERROR_BODY, resp.json()
@pytest.mark.parametrize(
@@ -377,18 +363,13 @@ _COLLECTIONS_PATH = "/library/api/collections"
def test_create_collection_rejects_malformed_json_bytes_with_400(auth_client):
- """Like index/start: malformed *bytes* on this route were never
- wrapped by a local ``except`` (``await request.json()`` is a bare
- top-level statement in ``create_collection``), so they already
- propagated to the app's registered ``json.JSONDecodeError -> 400``
- handler pre-fix. Included for completeness, not as evidence of the
- Shape D fix (see the wrong-typed-field tests below for that)."""
+ """Malformed bytes use the collection route's success envelope."""
resp = auth_client.post(
_COLLECTIONS_PATH, content=b"{not valid json", headers=_JSON_HEADERS
)
assert resp.status_code == 400, resp.text
- assert resp.json() == EXPECTED_GLOBAL_DECODE_ERROR_BODY, resp.json()
+ assert resp.json() == EXPECTED_JSON_ERROR_BODY, resp.json()
@pytest.mark.parametrize(
@@ -418,7 +399,7 @@ def test_update_collection_rejects_malformed_json_bytes_with_400(auth_client):
)
assert resp.status_code == 400, resp.text
- assert resp.json() == EXPECTED_GLOBAL_DECODE_ERROR_BODY, resp.json()
+ assert resp.json() == EXPECTED_JSON_ERROR_BODY, resp.json()
@pytest.mark.parametrize(
diff --git a/tests/web/routers/test_research_history_port_fidelity.py b/tests/web/routers/test_research_history_port_fidelity.py
index af2aa8a58d..a911a69b40 100644
--- a/tests/web/routers/test_research_history_port_fidelity.py
+++ b/tests/web/routers/test_research_history_port_fidelity.py
@@ -3,9 +3,8 @@
"""Port-fidelity pins for `routers/research.py` and `routers/history.py`.
Two behaviours that `main`'s Flask blueprints had and the FastAPI port
-does not. Both are currently LIVE-but-wrong, so both are
-``xfail(strict=True)``: they flip to XPASS (a strict-xfail failure) the
-moment the port is fixed, which is what makes them worth keeping.
+initially lost. The HEAD difference remains an ``xfail(strict=True)``;
+the malformed-body response has been restored and is a passing regression.
1. HEAD on a GET route.
``werkzeug.routing.Rule.__init__`` adds ``HEAD`` to ``methods``
@@ -29,18 +28,9 @@ moment the port is fixed, which is what makes them worth keeping.
"success")``, whose ``request.get_json(silent=True)`` collapsed BOTH
failure modes — unparseable body and parsed-but-not-an-object — into
one ``400 {"success": false, "error": "Request body must be valid
- JSON"}``. The port kept only the second: it calls
- ``json_body_error("success", ...)`` after an ``isinstance(data,
- dict)`` check, but leaves ``await request.json()`` unguarded, so a
- malformed body escapes to fastapi_app's ``json.JSONDecodeError``
- handler and comes back as ``400 {"error": "Invalid JSON body"}`` —
- no ``success`` key. Callers that branch on ``data.success`` (the
- shape the ``error_format="success"`` argument exists to produce) read
- ``undefined``.
-
- ``web/dependencies/json_body.py::read_json_dict`` already exists to
- close exactly this gap and its own docstring describes it; this call
- site simply does not use it.
+ JSON"}``. The route now uses ``read_json_dict`` so both invalid-body
+ cases return the same envelope, including the ``success`` key used by
+ callers.
"""
import pytest
@@ -90,15 +80,6 @@ def test_head_is_answered_like_main(client, url):
)
- strict=True,
- reason=(
- "save_raw_config leaves `await request.json()` unguarded, so an "
- "unparseable body escapes to fastapi_app's json.JSONDecodeError "
- "handler and loses the success-envelope that main's "
- "@require_json_body(error_format='success') produced"
- ),
-)
def test_save_raw_config_unparseable_body_keeps_success_envelope(client):
"""An unparseable body gets main's ``success`` envelope, not the generic one."""
resp = client.post(
diff --git a/tests/web/routers/test_settings_news_hostile_input.py b/tests/web/routers/test_settings_news_hostile_input.py
index 05ad1a8a4d..2bcd5d37c6 100644
--- a/tests/web/routers/test_settings_news_hostile_input.py
+++ b/tests/web/routers/test_settings_news_hostile_input.py
@@ -20,10 +20,10 @@ in a log line, followed by ``if not data or not data.get("query")`` -- both
assume dict-shaped data whenever it is truthy, so a truthy non-dict body
raises ``AttributeError`` on ``.keys()``/``.get()``.
-Fix: each site now validates the JSON body's shape (``isinstance(data, dict)``)
-before calling any dict-only method, and ``await request.json()`` runs
-outside any broad ``except Exception`` so a malformed body still reaches the
-app's registered ``json.JSONDecodeError`` -> 400 handler.
+Fix: each site validates the JSON body's shape before calling dict-only
+methods. The cleanup route also maps malformed bytes to its own non-object
+400 response while preserving its optional ``null`` and absent-body defaults;
+other sites can still use the app's JSON decode handler.
test-url gets extra coverage: the fix only changes how the *body's shape* is
validated. The ``service_url`` *value* inside a well-formed dict is passed
@@ -39,6 +39,7 @@ import pytest
from local_deep_research.security.notification_validator import (
NotificationURLValidator,
)
+from tests.test_utils import nested_json_past_the_scanner_limit
CLEANUP_ROUTE = "/settings/api/rate-limiting/cleanup"
TEST_URL_ROUTE = "/settings/api/notifications/test-url"
@@ -58,18 +59,39 @@ TRUTHY_NON_DICT_BODIES = [
# ---------------------------------------------------------------------------
-def test_cleanup_malformed_json_bytes_is_400(authenticated_client):
- """Not even valid JSON. Must hit the app's registered
- json.JSONDecodeError -> 400 handler, not the route's own 500."""
+ "body", [b"{not valid json", b'{"days":"\xff"}'], ids=["syntax", "utf8"]
+)
+def test_cleanup_malformed_json_bytes_is_400(authenticated_client, body):
+ """Invalid JSON bytes share the optional route's non-object envelope."""
resp = authenticated_client.post(
CLEANUP_ROUTE,
- content=b"{not valid json",
+ content=body,
headers={"Content-Type": "application/json"},
)
assert resp.status_code == 400, (
f"expected 400, got {resp.status_code}: {resp.text[:300]}"
)
- assert resp.json() == {"error": "Invalid JSON body"}
+ assert resp.json() == {"error": "Request body must be a JSON object"}
+
+
+def test_cleanup_too_deeply_nested_json_is_400_not_500(authenticated_client):
+ """Nesting past the parser's limit is a malformed body like any other.
+
+ ``json.loads`` raises ``RecursionError`` for it, which is not a
+ ``ValueError``, so a guard that only caught ``ValueError`` let it fall
+ through to the catch-all 500. The body is a few hundred KB, far under the
+ 16 MB JSON cap, so nothing upstream turns it away first.
+ """
+ resp = authenticated_client.post(
+ CLEANUP_ROUTE,
+ content=nested_json_past_the_scanner_limit(),
+ headers={"Content-Type": "application/json"},
+ )
+ assert resp.status_code == 400, (
+ f"expected 400, got {resp.status_code}: {resp.text[:300]}"
+ )
+ assert resp.json() == {"error": "Request body must be a JSON object"}
@pytest.mark.parametrize("body", TRUTHY_NON_DICT_BODIES)
@@ -87,10 +109,7 @@ def test_cleanup_truthy_non_dict_body_is_400_not_500(
assert resp.status_code == 400, (
f"{body!r} -> {resp.status_code}, expected 400: {resp.text[:300]}"
)
- payload = resp.json()
- assert "error" in payload and "success" not in payload, (
- f"expected simple {{'error': ...}} shape, got {payload}"
- )
+ assert resp.json() == {"error": "Request body must be a JSON object"}
def test_cleanup_literal_null_body_still_defaults(authenticated_client):
diff --git a/tests/web/test_encoding_and_non_ascii.py b/tests/web/test_encoding_and_non_ascii.py
index d8764aea9f..92f4baf62d 100644
--- a/tests/web/test_encoding_and_non_ascii.py
+++ b/tests/web/test_encoding_and_non_ascii.py
@@ -47,12 +47,15 @@ import asyncio
import io
import json
import re
+import sys
import uuid
from pathlib import Path
from urllib.parse import quote
import pytest
+from tests.test_utils import nested_json_past_the_scanner_limit
+
SRC_WEB = (
Path(__file__).resolve().parents[2] / "src" / "local_deep_research" / "web"
)
@@ -266,12 +269,37 @@ class TestAppLevelHandlerResolution:
assert resolved is not handlers[Exception]
assert resolved.__name__ == "handle_json_decode_error"
+ def test_a_client_disconnect_does_not_fall_through_to_the_500_catch_all(
+ self,
+ ):
+ """``read_json_dict`` lets ``ClientDisconnect`` propagate; this is
+ its receiver, so a hang-up mid-body is not an error-level 500."""
+ from starlette.requests import ClientDisconnect
+
+ handlers, resolved = self._resolve(ClientDisconnect())
+
+ assert resolved is handlers[ClientDisconnect]
+ assert resolved is not handlers[Exception]
+ assert resolved.__name__ == "handle_client_disconnect"
+
+ def test_the_body_size_exception_is_left_for_its_own_middleware(self):
+ """The other exception ``read_json_dict`` lets through already has a
+ receiver: ``BodySizeLimitMiddleware`` turns it into a logged 413. No
+ handler may claim it first, so it resolves to nothing narrower than
+ the catch-all (which Starlette hands to ``ServerErrorMiddleware``,
+ outside that middleware, not to the router's own handler stack)."""
+ from local_deep_research.web.fastapi_app import _RequestBodyTooLarge
+
+ handlers, resolved = self._resolve(_RequestBodyTooLarge())
+
+ assert resolved is handlers[Exception]
+
# ===========================================================================
# 2. Invalid UTF-8 in a JSON body: how far it reaches
# ===========================================================================
#
-# Booting the authenticated routes behind 26 sites to ask each one the same
+# Booting every authenticated route to ask each one the same
# question is not affordable, and an HTTP sweep only samples whatever it can
# reach past rate limits and path parameters. The AST answer is exact and
# total: for every ``request.json()`` call in the web layer, which enclosing
@@ -315,6 +343,7 @@ _DOES_NOT_CATCH_UNICODE_DECODE_ERROR = frozenset(
"KeyError",
"SQLAlchemyError",
"RuntimeError",
+ "RecursionError",
"OSError",
}
)
@@ -328,14 +357,16 @@ def _handler_names(handler: ast.ExceptHandler) -> list[str]:
return [ast.unparse(handler.type)]
-def _scan_json_body_sites():
+def _scan_json_body_sites(files=None):
"""Every ``request.json()`` call in the web layer, with the exception
names of the ``try`` blocks that actually enclose it.
Returns ``[(module_basename, function_name, frozenset(caught_names))]``.
+ ``files`` replaces the shipped source with other modules, for the
+ controls that show the scan telling the cases apart.
"""
sites = []
- for path in _JSON_BODY_FILES:
+ for path in _JSON_BODY_FILES if files is None else files:
tree = ast.parse(path.read_text(encoding="utf-8"))
parents = {}
for node in ast.walk(tree):
@@ -385,59 +416,79 @@ def _unguarded_sites():
}
-#: Frozen inventory. Each entry reads its body with ``await
-#: request.json()`` under no route-local ``except`` clause that catches
-#: ``UnicodeDecodeError``. The application-level handler converts these
-#: failures to 400; the inventory still detects route-local inconsistency.
-#:
-#: ``library_delete._parse_json_body`` is the odd one out and the clearest
-#: illustration: it was written *specifically* to convert a bad body into
-#: a 400, but it catches ``json.JSONDecodeError`` -- the sibling class --
-#: so it converts the syntax failure and misses the encoding one.
+#: Frozen inventory of the four remaining unguarded ``request.json()`` calls.
+#: The other routes now use ``read_json_dict`` or a route-local parse guard.
#:
-#: Update this set only alongside the fix. The resource-addition route now
-#: uses ``read_json_dict`` and no longer has a bare body parse. A shrinking
-#: set means someone fixed a route; a growing one means a new route was
-#: written with the same gap.
+#: What the application-level handlers do for these four is narrower than
+#: "convert the failure to 400". They answer 400 for two of the four ways
+#: the parser refuses a body: undecodable bytes (``UnicodeDecodeError``) and
+#: bad syntax (``JSONDecodeError``). Nesting past the scanner limit
+#: (``RecursionError``) and an integer literal past
+#: ``sys.get_int_max_str_digits()`` (a plain ``ValueError``) are not
+#: registered app-wide, so on a bare route they reach the catch-all and answer
+#: 500. ``test_only_two_of_the_four_parser_refusals_have_an_app_level_400``
+#: pins exactly that. The inventory detects new unguarded sites; it does not
+#: close the gap.
UNGUARDED_JSON_BODY_SITES = frozenset(
{
- ("benchmark.py", "start_benchmark"),
- ("benchmark.py", "start_benchmark_simple"),
("benchmark.py", "validate_config"),
- ("library.py", "check_downloads"),
- ("library.py", "download_bulk"),
- ("library.py", "download_research_pdfs"),
- ("library.py", "download_source"),
- ("library.py", "mark_for_redownload"),
("library_delete.py", "_parse_json_body"),
- ("library_search.py", "add_research_to_collection"),
- ("library_search.py", "convert_all_research"),
- ("library_search.py", "search_collection"),
- ("metrics.py", "api_classify_domains"),
- ("metrics.py", "api_cost_calculation"),
- ("metrics.py", "api_save_research_rating"),
("news_flask_api.py", "add_search_history"),
- ("rag.py", "create_collection"),
- ("rag.py", "start_background_index"),
- ("rag.py", "update_collection"),
- ("research.py", "save_raw_config"),
- # Was ("settings.py", "api_test_notification_url"). The body parse
- # moved out of the handler and into the `_notification_test_body`
- # route dependency so the rate limiter's exempt_when predicate can
- # see the payload (it runs before slowapi's wrapper). Same single
- # `await request.json()`, same absent UnicodeDecodeError guard, one
- # frame earlier -- a rename, not a route joining or leaving the
- # inventory. The count is now 26 after api_add_resource moved to the
- # shared JSON helper.
("settings.py", "_notification_test_body"),
- ("settings.py", "api_cleanup_rate_limiting"),
- ("settings.py", "api_toggle_search_favorite"),
- ("settings.py", "api_update_search_favorites"),
- ("settings.py", "api_update_setting"),
- ("settings.py", "save_all_settings"),
}
)
+#: Exception names that swallow EVERYTHING a body read can raise, not only a
+#: parse failure. ``request.json()`` reads the request stream, so it is also
+#: where the request-size limit's exception (the receiver is
+#: ``BodySizeLimitMiddleware``, which logs the rejection and answers 413) and
+#: a client disconnect surface. ``""`` is a bare ``except:``.
+_SWALLOWS_EVERYTHING = frozenset({"", "BaseException", "Exception"})
+
+
+def _broadly_wrapped_sites(files=None):
+ return {
+ (module, function)
+ for module, function, caught in _scan_json_body_sites(files)
+ if caught & _SWALLOWS_EVERYTHING
+ }
+
+
+#: Frozen inventory of the bare ``request.json()`` calls that sit inside a
+#: broad ``except``, the third parse idiom. These are invisible to
+#: ``UNGUARDED_JSON_BODY_SITES``, because a broad ``except`` does catch the
+#: encoding error, and to the guard over ``read_json_dict`` callers in
+#: ``tests/web/routers/test_json_body_error_envelopes.py``, which only
+#: polices that helper. At each site an over-cap chunked body is answered by
+#: the route's own error handling (a 400, or a logged 500) instead of the
+#: middleware's logged 413. Not converted here: the set only ever shrinks,
+#: by moving a site onto ``read_json_dict``. ``followup.start_followup`` is
+#: deliberately absent: its ``except ValueError`` lets both exceptions
+#: through, and it answers 413.
+BROADLY_WRAPPED_JSON_BODY_SITES = frozenset(
+ {
+ ("api_v1.py", "api_analyze_documents"),
+ ("api_v1.py", "api_generate_report"),
+ ("api_v1.py", "api_quick_summary"),
+ ("chat.py", "_json_object_body"),
+ ("followup.py", "prepare_followup"),
+ ("metrics.py", "api_journal_data_download"),
+ ("news_flask_api.py", "research_news_item"),
+ ("rag.py", "configure_rag"),
+ ("rag.py", "index_document"),
+ ("rag.py", "remove_document"),
+ ("rag.py", "test_embedding"),
+ ("research.py", "start_research"),
+ }
+)
+
+
+def _integer_past_the_digit_limit() -> bytes:
+ limit = sys.get_int_max_str_digits()
+ if limit == 0:
+ pytest.skip("this interpreter does not limit integer literals")
+ return b"1" * (limit + 1)
+
class TestInvalidUtf8BodyReach:
def test_every_guard_clause_is_classified(self):
@@ -471,9 +522,9 @@ class TestInvalidUtf8BodyReach:
for module, function, _caught in _scan_json_body_sites()
}
- assert ("library.py", "download_bulk") in found
+ assert ("benchmark.py", "validate_config") in found
assert ("json_body.py", "read_json_dict") in found
- assert len(found) >= 30, (
+ assert len(found) >= 19, (
f"only {len(found)} request.json() call sites found; the "
"scanner has stopped matching the source"
)
@@ -485,11 +536,11 @@ class TestInvalidUtf8BodyReach:
def test_the_gap_is_not_confined_to_the_library_router(self):
"""#5761 was filed for six library endpoints. It is app-wide.
- Stated separately from the inventory because it is the claim that
- decides how the issue gets scoped: a per-route patch on
- ``library.py`` leaves 20 handlers behind, whereas one
- ``ValueError`` handler in ``fastapi_app.py`` closes all 26 at
- once.
+ Route-local guards now handle most body parses, but a library-only
+ patch would still leave three unguarded handlers in other modules.
+ At all four remaining sites the application-level handlers answer 400
+ for the encoding and syntax failures; they do not for the other two
+ parser refusals (see ``UNGUARDED_JSON_BODY_SITES``).
"""
outside_library = {
(module, function)
@@ -498,25 +549,80 @@ class TestInvalidUtf8BodyReach:
}
modules = {module for module, _function in outside_library}
- assert len(outside_library) >= 20, sorted(outside_library)
+ assert len(outside_library) >= 3, sorted(outside_library)
assert modules >= {
"benchmark.py",
- "library_search.py",
- "metrics.py",
"news_flask_api.py",
- "rag.py",
- "research.py",
"settings.py",
}, sorted(modules)
+ @pytest.mark.parametrize(
+ ("build_body", "refusal", "has_an_app_level_400"),
+ [
+ pytest.param(
+ lambda: b"{not json",
+ json.JSONDecodeError,
+ True,
+ id="bad-syntax",
+ ),
+ pytest.param(
+ lambda: INVALID_UTF8_JSON_BODY,
+ UnicodeDecodeError,
+ True,
+ id="undecodable-bytes",
+ ),
+ pytest.param(
+ _integer_past_the_digit_limit,
+ ValueError,
+ False,
+ id="integer-past-the-digit-limit",
+ ),
+ pytest.param(
+ nested_json_past_the_scanner_limit,
+ RecursionError,
+ False,
+ id="nesting-too-deep",
+ ),
+ ],
+ )
+ def test_only_two_of_the_four_parser_refusals_have_an_app_level_400(
+ self, build_body, refusal, has_an_app_level_400
+ ):
+ """The most the unguarded inventory can claim, stated exactly.
+
+ ``json.loads`` refuses a body in four ways. A route with no guard of
+ its own gets an application-level 400 for the first two only; the
+ other two reach the catch-all, which answers 500. Resolving the real
+ exception against the real app is what the claim is made of.
+ """
+ with pytest.raises(refusal) as refused:
+ json.loads(build_body())
+ # Premise: the body fails in exactly the way it is named for.
+ assert type(refused.value) is refusal
+
+ handlers, resolved = TestAppLevelHandlerResolution._resolve(
+ refused.value
+ )
+
+ if has_an_app_level_400:
+ assert resolved.__name__ == "handle_json_decode_error"
+ else:
+ assert resolved is handlers[Exception], (
+ f"{refusal.__name__} now has its own app-level handler "
+ "(resolved to "
+ f"{resolved.__name__}); update the claims on "
+ "UNGUARDED_JSON_BODY_SITES"
+ )
+
def test_the_shared_body_helper_is_the_one_that_gets_it_right(self):
"""``read_json_dict`` exists precisely to close this gap.
- It catches bare ``Exception``, so it handles the encoding failure
- and the syntax failure identically -- which is what main's
- ``@require_json_body`` did. The 26 sites above are the call sites
- that did not adopt it. Exercised, not merely read: the helper is
- driven with the real bad bytes through a real Request.
+ It catches ``ValueError`` (the base of both ``UnicodeDecodeError``
+ and ``json.JSONDecodeError``) and ``RecursionError``, so it handles
+ the encoding failure and the syntax failure identically -- which is
+ what main's ``@require_json_body`` did. The four sites above are the
+ call sites that did not adopt it. Exercised, not merely read: the
+ helper is driven with the real bad bytes through a real Request.
"""
from local_deep_research.web.dependencies.json_body import (
read_json_dict,
@@ -536,6 +642,84 @@ class TestInvalidUtf8BodyReach:
}
+class TestBroadlyWrappedBodyParses:
+ """A bare ``request.json()`` inside ``except Exception``: the third idiom.
+
+ ``read_json_dict`` answers a body the CLIENT got wrong and lets the rest
+ propagate to its receiver: the request-size limit's exception to
+ ``BodySizeLimitMiddleware`` (a logged 413) and a client disconnect to the
+ app-level handler. A route that wraps its own bare parse in a broad
+ ``except`` answers both itself, and the middleware's 413 and its log line
+ never happen.
+ """
+
+ def test_broadly_wrapped_body_parse_inventory_is_unchanged(self):
+ """Pin exactly which bare parses sit inside a broad ``except``."""
+ found = _broadly_wrapped_sites()
+
+ added = sorted(found - BROADLY_WRAPPED_JSON_BODY_SITES)
+ assert not added, (
+ "request.json() is now called inside a broad `except` at "
+ f"{added}. That swallows what read_json_dict lets through on "
+ "purpose -- the request-size limit's exception (a logged 413) "
+ "and a client disconnect -- and answers with the route's own "
+ "error instead. Read the body with read_json_dict "
+ "(web/dependencies/json_body.py), outside any broad `except`; "
+ "do not add the site to BROADLY_WRAPPED_JSON_BODY_SITES, which "
+ "only shrinks."
+ )
+ removed = sorted(BROADLY_WRAPPED_JSON_BODY_SITES - found)
+ assert not removed, (
+ f"{removed} no longer wrap request.json() in a broad `except` "
+ "(moved onto read_json_dict?). Delete them from "
+ "BROADLY_WRAPPED_JSON_BODY_SITES."
+ )
+
+ def test_the_scan_tells_a_broad_except_from_a_narrow_or_hoisted_one(
+ self, tmp_path
+ ):
+ """Discrimination control: only the swallowing shapes are counted."""
+ module = tmp_path / "routes.py"
+ module.write_text(
+ "async def swallowed(request):\n"
+ " try:\n"
+ " return await request.json()\n"
+ " except Exception:\n"
+ " return None\n"
+ "async def bare(request):\n"
+ " try:\n"
+ " return await request.json()\n"
+ " except:\n"
+ " return None\n"
+ "async def nested(request):\n"
+ " try:\n"
+ " try:\n"
+ " return await request.json()\n"
+ " except ValueError:\n"
+ " return None\n"
+ " except Exception:\n"
+ " return None\n"
+ "async def narrow(request):\n"
+ " try:\n"
+ " return await request.json()\n"
+ " except ValueError:\n"
+ " return None\n"
+ "async def hoisted(request):\n"
+ " data = await request.json()\n"
+ " try:\n"
+ " return data\n"
+ " except Exception:\n"
+ " return None\n",
+ encoding="utf-8",
+ )
+
+ assert _broadly_wrapped_sites([module]) == {
+ ("routes.py", "swallowed"),
+ ("routes.py", "bare"),
+ ("routes.py", "nested"),
+ }
+
+
class TestNonAsciiSurvivesTheResponseSide:
def test_json_error_bodies_carry_raw_utf8_for_astral_and_rtl(self):
"""The port's own error envelope, driven with hard text.
diff --git a/tests/web/test_request_response_boundary_contracts.py b/tests/web/test_request_response_boundary_contracts.py
index dc7613724b..c99ebbcfc5 100644
--- a/tests/web/test_request_response_boundary_contracts.py
+++ b/tests/web/test_request_response_boundary_contracts.py
@@ -246,17 +246,52 @@ def test_absent_keys_list_defaults_but_an_empty_one_does_not(
# REQUEST BODIES — Content-Type independence
# ---------------------------------------------------------------------------
#
-# Oracle for "did request.json() parse this body?" on
-# POST /metrics/api/cost-calculation, which does a bare `await
-# request.json()` above its try/except. Three outcomes are distinguishable
-# from the response body alone:
+# Oracle for "did request.json() parse this body?". The cost route cannot
+# answer it alone any more: it reads the body through ``read_json_dict``,
+# which gives an unparseable body and a parsed non-object the SAME 400, so
+# only "parsed to a dict" stands apart:
#
-# body did not parse -> 400 {"error": "Invalid JSON body"} (app handler)
-# parsed, but not a dict -> 400 {"error": "No data provided"}
-# parsed to a dict -> 400 {"error": "model_name is required"}
+# body did not parse, or was not a dict -> 400 {"error": "No data provided"}
+# parsed to a dict -> 400 {"error": "model_name is required"}
#
-# The third is reached without touching the pricing calculator, so these
-# tests do no network or model lookup.
+# POST /benchmark/api/validate-config still reads its body with a bare
+# ``await request.json()`` (one of the four sites test_encoding_and_non_ascii
+# pins in UNGUARDED_JSON_BODY_SITES), so it keeps all three outcomes apart:
+#
+# body did not parse -> 400 {"error": "Invalid JSON body"} (app handler)
+# parsed, but not a dict -> 200 {"valid": false, "errors": ["No data provided"]}
+# parsed to a dict -> 200 {"valid": true, "errors": [], ...}
+#
+# Neither route touches the pricing calculator, the network or a model
+# lookup, so these tests do none. If validate-config moves to
+# ``read_json_dict``, point the bare-route tests at another site that is
+# still in that inventory.
+
+VALIDATE_CONFIG_URL = "/benchmark/api/validate-config"
+
+#: A benchmark configuration validate-config reports as valid.
+VALID_BENCHMARK_CONFIG = json.dumps(
+ {
+ "search_config": {
+ "search_tool": "searxng",
+ "search_strategy": "focused_iteration",
+ },
+ "datasets_config": {"simpleqa": {"count": 5}},
+ }
+).encode()
+
+#: What the app-level handler answers for a body ``request.json()`` could not
+#: parse or decode.
+APP_HANDLER_ENVELOPE = {"error": "Invalid JSON body"}
+
+#: Every Content-Type label a client can put on a JSON body.
+DECLARED_CONTENT_TYPES = (
+ "application/json",
+ "text/plain",
+ "multipart/form-data; boundary=----WebKitFormBoundaryXYZ",
+ "application/x-www-form-urlencoded",
+ None, # no Content-Type header at all
+)
def _cost_error(client, body, content_type=None):
@@ -265,6 +300,26 @@ def _cost_error(client, body, content_type=None):
return resp.status_code, resp.json().get("error")
+def _bare_route_outcome(client, body, content_type=None):
+ """What ``request.json()`` made of ``body``, read off validate-config.
+
+ ``"unparsed"``, ``"not-an-object"`` or ``"parsed"``. Anything else comes
+ back as a description of the surprise, so a failing assertion shows it.
+ """
+ headers = {"Content-Type": content_type} if content_type else {}
+ resp = client.post(VALIDATE_CONFIG_URL, content=body, headers=headers)
+ payload = resp.json()
+ if (resp.status_code, payload) == (400, APP_HANDLER_ENVELOPE):
+ return "unparsed"
+ if resp.status_code == 200 and payload.get("errors") == [
+ "No data provided"
+ ]:
+ return "not-an-object"
+ if resp.status_code == 200 and payload.get("valid") is True:
+ return "parsed"
+ return f"unexpected: {resp.status_code} {resp.text[:200]}"
+
+
def test_json_body_parses_regardless_of_the_declared_content_type(
authenticated_client,
):
@@ -280,13 +335,7 @@ def test_json_body_parses_regardless_of_the_declared_content_type(
"""
parsed_dict = b'{"model_name": ""}'
- for content_type in (
- "application/json",
- "text/plain",
- "multipart/form-data; boundary=----WebKitFormBoundaryXYZ",
- "application/x-www-form-urlencoded",
- None, # no Content-Type header at all
- ):
+ for content_type in DECLARED_CONTENT_TYPES:
status, error = _cost_error(
authenticated_client, parsed_dict, content_type
)
@@ -296,44 +345,74 @@ def test_json_body_parses_regardless_of_the_declared_content_type(
)
+def test_a_bare_request_json_route_parses_whatever_the_declared_content_type(
+ authenticated_client,
+):
+ """The same property, asked of ``request.json()`` itself rather than of
+ the helper wrapped around it."""
+ for content_type in DECLARED_CONTENT_TYPES:
+ outcome = _bare_route_outcome(
+ authenticated_client, VALID_BENCHMARK_CONFIG, content_type
+ )
+ assert outcome == "parsed", (
+ f"a JSON body labelled {content_type!r} must still be parsed as "
+ f"JSON; the oracle says {outcome}"
+ )
+
+
def test_the_content_type_oracle_can_actually_say_no(authenticated_client):
- """Discrimination control for the test above.
+ """Discrimination control for the two tests above.
"It parsed" is only meaningful if a body that genuinely cannot parse
produces a different answer through the same code path — otherwise the
- loop above would pass against a route that answered
- "model_name is required" unconditionally.
+ loops above would pass against a route that answered "parsed"
+ unconditionally.
"""
- status, error = _cost_error(
- authenticated_client,
- b"model_name=",
- "application/x-www-form-urlencoded",
- )
- assert (status, error) == (400, "Invalid JSON body"), (
- "a form-encoded (non-JSON) body must NOT parse as JSON; got "
- f"{status} {error!r}"
- )
+ # Cost route: only "parsed to a dict" stands apart. An unparseable body
+ # and a parsed non-object share the route's one envelope by design.
+ for body, content_type in (
+ (b"model_name=", "application/x-www-form-urlencoded"),
+ (b"123", "application/json"),
+ ):
+ status, error = _cost_error(authenticated_client, body, content_type)
+ assert (status, error) == (400, "No data provided"), (
+ f"{body!r} is not a JSON object and must not reach the "
+ f"route's own validation; got {status} {error!r}"
+ )
- status, error = _cost_error(
- authenticated_client, b"123", "application/json"
- )
- assert (status, error) == (400, "No data provided"), (
- f"valid JSON that is not an object must be rejected on shape; got "
- f"{status} {error!r}"
- )
+ # Bare route: all three outcomes apart, through one route and one code
+ # path. A form-encoded body must NOT parse as JSON, and valid JSON that
+ # is not an object is rejected on shape, not on parsing.
+ outcomes = {
+ "form-encoded": _bare_route_outcome(
+ authenticated_client,
+ b"model_name=",
+ "application/x-www-form-urlencoded",
+ ),
+ "malformed": _bare_route_outcome(
+ authenticated_client, b"{nope", "application/json"
+ ),
+ "non-object": _bare_route_outcome(
+ authenticated_client, b"123", "application/json"
+ ),
+ "object": _bare_route_outcome(
+ authenticated_client, VALID_BENCHMARK_CONFIG, "application/json"
+ ),
+ }
+ assert outcomes == {
+ "form-encoded": "unparsed",
+ "malformed": "unparsed",
+ "non-object": "not-an-object",
+ "object": "parsed",
+ }
def test_malformed_json_is_a_400_not_a_500(authenticated_client):
- """Flask parity: ``request.get_json()`` answered 400 for a body that
- would not parse. Here the route lets ``json.JSONDecodeError`` escape on
- purpose so the app-level handler turns it into the same 400 — the
- alternative (the route's own broad ``except Exception``) would report a
- client typo as a backend outage.
- """
+ """Flask parity: malformed JSON uses the route's validation response."""
status, error = _cost_error(
authenticated_client, b"{nope", "application/json"
)
- assert (status, error) == (400, "Invalid JSON body"), (
+ assert (status, error) == (400, "No data provided"), (
f"malformed JSON must be a 400, got {status} {error!r}"
)
@@ -343,15 +422,16 @@ def test_malformed_json_is_a_400_not_a_500(authenticated_client):
# ---------------------------------------------------------------------------
-def test_invalid_utf8_body_is_a_400_on_a_bare_request_json_route(
+def test_invalid_utf8_body_is_a_400_on_the_cost_route(
authenticated_client,
):
"""An undecodable request body is a client error, matching Flask.
``json.loads`` decodes before it parses, so invalid UTF-8 raises
- ``UnicodeDecodeError``. It is not a ``json.JSONDecodeError``, so both
- types must be registered explicitly with the shared application-level
- handler. This route is the representative bare ``request.json()`` site.
+ ``UnicodeDecodeError``. The shared object parser turns it into the
+ route's own validation response, so this route never reaches the
+ application-level handler; that is pinned on a bare ``request.json()``
+ route by the test below.
"""
# Positive control: the same route, same headers, valid UTF-8 -> 400.
# Without it a 500 here could just mean the route is broken outright.
@@ -365,21 +445,52 @@ def test_invalid_utf8_body_is_a_400_on_a_bare_request_json_route(
status, error = _cost_error(
authenticated_client, INVALID_UTF8_JSON, "application/json"
)
- assert (status, error) == (400, "Invalid JSON body"), (
- "an undecodable request body must use the shared client-error "
+ assert (status, error) == (400, "No data provided"), (
+ "an undecodable request body must use the route's client-error "
f"contract; got {status} {error!r}"
)
+def test_invalid_utf8_body_is_a_400_on_a_bare_request_json_route(
+ authenticated_client,
+):
+ """An undecodable request body is a client error, matching Flask.
+
+ It is not a ``json.JSONDecodeError``, so both types must be registered
+ explicitly with the shared application-level handler. validate-config
+ reads its body with a bare ``await request.json()``, so no route-local
+ guard stands between the exception and that handler: this is the HTTP
+ half of ``test_unicode_decode_error_handler_is_registered``.
+ """
+ # Positive control: the same route and headers, valid UTF-8 -> parsed.
+ # Without it a 500 here could just mean the route is broken outright.
+ assert (
+ _bare_route_outcome(
+ authenticated_client, VALID_BENCHMARK_CONFIG, "application/json"
+ )
+ == "parsed"
+ )
+
+ resp = authenticated_client.post(
+ VALIDATE_CONFIG_URL,
+ content=INVALID_UTF8_JSON,
+ headers={"Content-Type": "application/json"},
+ )
+ assert (resp.status_code, resp.json()) == (400, APP_HANDLER_ENVELOPE), (
+ "an undecodable request body must use the shared client-error "
+ f"contract; got {resp.status_code} {resp.text[:300]}"
+ )
+
+
def test_invalid_utf8_is_already_a_400_where_read_json_dict_guards_the_body(
authenticated_client,
):
"""The shared helper retains its route-specific error envelope.
- ``dependencies/json_body.read_json_dict`` wraps the parse in a bare
- ``except Exception``, so it catches ``UnicodeDecodeError`` before the
- global handler and returns the route's configured message. This pins the
- intentional envelope difference while both parsing idioms return 400.
+ ``dependencies/json_body.read_json_dict`` catches ``ValueError`` around
+ the parse, and ``UnicodeDecodeError`` is one, so it answers before the
+ global handler does and returns the route's configured message. This pins
+ the intentional envelope difference while both parsing idioms return 400.
"""
client = authenticated_client
@@ -404,9 +515,8 @@ def test_invalid_utf8_is_already_a_400_where_read_json_dict_guards_the_body(
400,
"Request body must be valid JSON",
), (
- "read_json_dict's `except Exception` must absorb UnicodeDecodeError "
- f"into the same 400 a malformed body gets; got {bad.status_code} "
- f"{bad.text[:300]}"
+ "read_json_dict must absorb UnicodeDecodeError into the same 400 a "
+ f"malformed body gets; got {bad.status_code} {bad.text[:300]}"
)
@@ -432,7 +542,9 @@ def _registered_exception_types():
def test_unicode_decode_error_handler_is_registered():
- """Static companion to the HTTP contract: pin the registration itself.
+ """Static companion to the HTTP contract
+ (``test_invalid_utf8_body_is_a_400_on_a_bare_request_json_route``): pin
+ the registration itself.
Reading the registry rather than the response means the fixer gets
pointed at the one line that has to change, and this guard cannot rot
@@ -548,31 +660,45 @@ def test_the_shipped_read_json_dict_really_absorbs_unicode_decode_error():
}
+class _RetargetTheGuard(ast.NodeTransformer):
+ """Swap the shipped ``except (ValueError, RecursionError)`` for another.
+
+ The clause is matched by its element names, not by unparsing it, because
+ ``ast.unparse`` may or may not parenthesise a tuple here depending on the
+ interpreter. ``hits`` counts the handlers swapped, so a control can
+ insist it changed exactly the one clause it describes.
+ """
+
+ def __init__(self, replacement):
+ self.replacement = replacement
+ self.hits = 0
+
+ def visit_ExceptHandler(self, node):
+ shipped = isinstance(node.type, ast.Tuple) and {
+ getattr(element, "id", None) for element in node.type.elts
+ } == {"ValueError", "RecursionError"}
+ if shipped:
+ self.hits += 1
+ node.type = ast.parse(self.replacement, mode="eval").body
+ return node
+
+
def test_negative_control_a_narrowed_except_clause_lets_the_error_escape(
tmp_path,
):
"""NEGATIVE CONTROL for the two tests above.
- Mutates a COPY of the shipped source — ``except Exception`` becomes
+ Mutates a COPY of the shipped source — the guard's
+ ``except (ValueError, RecursionError)`` becomes
``except json.JSONDecodeError``, which is the idiom the unguarded
``await request.json()`` call sites effectively have — and shows that
- the same exec then lets ``UnicodeDecodeError`` escape. Two things
- follow: the guard test above is not vacuous, and the 500 pinned for
- ``/metrics/api/cost-calculation`` is caused by exactly this narrowing.
+ the same exec then lets ``UnicodeDecodeError`` escape. It follows that
+ the guard test above is not vacuous: it goes red the moment the clause
+ stops covering the encoding failure.
"""
import anyio
- class _NarrowTheExcept(ast.NodeTransformer):
- def __init__(self):
- self.hits = 0
-
- def visit_ExceptHandler(self, node):
- if isinstance(node.type, ast.Name) and node.type.id == "Exception":
- self.hits += 1
- node.type = ast.parse("json.JSONDecodeError", mode="eval").body
- return node
-
- transformer = _NarrowTheExcept()
+ transformer = _RetargetTheGuard("json.JSONDecodeError")
mutated_source = []
def mutate(module):
@@ -581,9 +707,9 @@ def test_negative_control_a_narrowed_except_clause_lets_the_error_escape(
namespace = _exec_json_body_source(mutate=mutate, source_out=mutated_source)
assert transformer.hits == 1, (
- f"expected exactly one `except Exception` to narrow, hit "
- f"{transformer.hits} — the mutation no longer describes the shipped "
- "guard and this control proves nothing"
+ f"expected exactly one `except (ValueError, RecursionError)` to "
+ f"narrow, hit {transformer.hits} — the mutation no longer describes "
+ "the shipped guard and this control proves nothing"
)
# Keep the mutated counterfactual on disk so a failure here is
@@ -592,7 +718,8 @@ def test_negative_control_a_narrowed_except_clause_lets_the_error_escape(
mutant_path.write_text(
"# MUTANT of "
+ str(JSON_BODY_SRC)
- + ": `except Exception` -> `except json.JSONDecodeError`\n"
+ + ": `except (ValueError, RecursionError)` -> "
+ + "`except json.JSONDecodeError`\n"
+ mutated_source[0],
encoding="utf-8",
)
@@ -612,6 +739,41 @@ def test_negative_control_a_narrowed_except_clause_lets_the_error_escape(
anyio.run(narrowed, _RequestRaising(_unicode_decode_error()))
+def test_negative_control_a_broad_except_clause_swallows_what_must_propagate():
+ """NEGATIVE CONTROL for the propagation tests in
+ ``tests/web/dependencies/test_json_body_contract.py`` and for the 413
+ tests in ``tests/web/routers/test_json_body_error_envelopes.py``.
+
+ Mutates a COPY of the shipped source so the guard catches bare
+ ``Exception`` — what it did before an over-cap body streamed without a
+ Content-Length was found coming back as the route's 400 — and shows the
+ mutant answers with the 400 envelope for an exception the shipped guard
+ lets through to ``BodySizeLimitMiddleware``. It follows that those tests
+ are not vacuous: they go red the moment the clause is widened again.
+ """
+ import anyio
+
+ class _OverTheCap(Exception):
+ """Stands in for BodySizeLimitMiddleware's over-cap exception."""
+
+ transformer = _RetargetTheGuard("Exception")
+ widened = _exec_json_body_source(mutate=transformer.visit)["read_json_dict"]
+ assert transformer.hits == 1, (
+ f"expected exactly one `except (ValueError, RecursionError)` to "
+ f"widen, hit {transformer.hits} — the mutation no longer describes "
+ "the shipped guard and this control proves nothing"
+ )
+ shipped = _exec_json_body_source()["read_json_dict"]
+
+ # The mutant turns the over-cap error into the route's validation 400 ...
+ data, err = anyio.run(widened, _RequestRaising(_OverTheCap()))
+ assert data is None and err is not None and err.status_code == 400
+
+ # ... where the shipped guard leaves it for the middleware.
+ with pytest.raises(_OverTheCap):
+ anyio.run(shipped, _RequestRaising(_OverTheCap()))
+
+
# ---------------------------------------------------------------------------
# UNICODE / ENCODING ROUND-TRIPS
# ---------------------------------------------------------------------------