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): enforce JSON media types on ported routes (#7080)

LearningCircuit90c555797dda
diff --git a/changelog.d/6104.bugfix.md b/changelog.d/6104.bugfix.md
new file mode 100644
index 0000000000..4a2dc9c5c4
--- /dev/null
+++ b/changelog.d/6104.bugfix.md
@@ -0,0 +1 @@
+Restore JSON media-type checks for notes, research API v1, research start, raw config saving, and resource creation, and keep malformed resource bodies on the existing 400 response contract.
diff --git a/src/local_deep_research/web/dependencies/json_body.py b/src/local_deep_research/web/dependencies/json_body.py
index 8af4713ed4..651f262629 100644
--- a/src/local_deep_research/web/dependencies/json_body.py
+++ b/src/local_deep_research/web/dependencies/json_body.py
@@ -1,4 +1,4 @@
-"""The 400 response `@require_json_body` used to produce.
+"""The request checks and the 400 response of main's `@require_json_body`.
Main gated 46 route handlers with ``security.decorators.require_json_body``,
a Flask decorator that rejected any request whose parsed body was not a
@@ -26,6 +26,13 @@ check:
if not isinstance(data, dict):
return json_body_error(...)
+``get_json(silent=True)`` also returned ``None`` when the Content-Type was
+not a JSON media type, so the decorator refused a JSON-looking
+``text/plain`` body as well. ``request.json()`` ignores the header, so that
+check is separate here. ``is_json_request`` is the media-type check, and
+``read_json_dict`` parses the body and checks its shape without looking at
+the media type. A route that needs both calls ``is_json_request`` first.
+
``error_format`` reproduces main's three response shapes exactly, because
the front-end branches on them: ``success`` is checked by the JS that drives
the chat, RAG and library-search views, while ``status`` is what the
@@ -43,6 +50,25 @@ ErrorFormat = Literal["simple", "status", "success"]
DEFAULT_MESSAGE = "Request body must be valid JSON"
+def is_json_request(request) -> bool:
+ """Return whether the request's Content-Type is a JSON media type.
+
+ Same rule as Werkzeug's ``Request.is_json``: the media type, meaning
+ the part before any ``;``, stripped and lowercased, must be
+ ``application/json`` or ``application/*+json``. A missing header does
+ not qualify. Call it before parsing; ``read_json_dict`` does not check
+ the media type.
+ """
+ request_content_type = request.headers.get("content-type", "").split(
+ ";", 1
+ )[0]
+ request_content_type = request_content_type.strip().lower()
+ return request_content_type == "application/json" or (
+ request_content_type.startswith("application/")
+ and request_content_type.endswith("+json")
+ )
+
+
def json_body_error(
error_format: ErrorFormat = "simple",
error_message: str = DEFAULT_MESSAGE,
@@ -69,11 +95,17 @@ async def read_json_dict(
error_format: ErrorFormat = "simple",
error_message: str = DEFAULT_MESSAGE,
):
- """Parse the request body as a JSON object the way main's decorator did.
+ """Parse the request body as a JSON object, failing with main's 400.
Returns ``(data, None)`` on success and ``(None, JSONResponse)`` on
failure, so callers stay a plain ``if err is not None: return err``.
+ It does NOT check the media type. The body is parsed whatever the
+ Content-Type says, so a JSON object sent as ``text/plain`` is accepted.
+ main's decorator refused that request as well, because
+ ``get_json(silent=True)`` returned ``None`` for a non-JSON media type.
+ A route that needs that behaviour calls ``is_json_request`` first.
+
main's ``@require_json_body`` collapsed BOTH failure modes into one 400:
a body that will not parse, and a body that parses to something other
than an object. Porting the decorator away split them — handlers kept an
diff --git a/src/local_deep_research/web/routers/api.py b/src/local_deep_research/web/routers/api.py
index 8b51b76ad9..4e8c8de0db 100644
--- a/src/local_deep_research/web/routers/api.py
+++ b/src/local_deep_research/web/routers/api.py
@@ -26,7 +26,11 @@ from ..services.resource_service import (
)
from local_deep_research.settings import SettingsManager
from ...security import redact_url_for_log, safe_get, strip_settings_snapshot
-from ..dependencies.json_body import json_body_error
+from ..dependencies.json_body import (
+ is_json_request,
+ json_body_error,
+ read_json_dict,
+)
from typing import Annotated
# Create the router
@@ -215,10 +219,13 @@ async def api_add_resource(
Add a new resource to a research project
"""
- data = await request.json()
- if not isinstance(data, dict):
+ if not is_json_request(request):
return json_body_error("status", "Request body must be valid JSON")
+ data, error = await read_json_dict(request, "status")
+ if error is not None:
+ return error
+
def _impl():
try:
# Required fields
diff --git a/src/local_deep_research/web/routers/api_v1.py b/src/local_deep_research/web/routers/api_v1.py
index 058226656c..477cd4048b 100644
--- a/src/local_deep_research/web/routers/api_v1.py
+++ b/src/local_deep_research/web/routers/api_v1.py
@@ -25,6 +25,7 @@ from ...database.session_context import get_user_db_session
from ...security.log_sanitizer import sanitize_error_for_client
from ...utilities.db_utils import get_settings_manager
from ..dependencies.auth import get_session_username, require_auth
+from ..dependencies.json_body import is_json_request
from ..dependencies.rate_limit import (
API_RATE_LIMIT_DEFAULT,
api_rate_limit,
@@ -1049,6 +1050,10 @@ async def api_quick_summary(
username: Annotated[str, Depends(require_api_access)],
):
"""Generate a quick research summary via REST API."""
+ if not is_json_request(request):
+ return JSONResponse(
+ {"error": "Query parameter is required"}, status_code=400
+ )
try:
data = await request.json()
except Exception:
@@ -1188,6 +1193,10 @@ async def api_generate_report(
username: Annotated[str, Depends(require_api_access)],
):
"""Generate a comprehensive research report via REST API."""
+ if not is_json_request(request):
+ return JSONResponse(
+ {"error": "Query parameter is required"}, status_code=400
+ )
try:
data = await request.json()
except Exception:
@@ -1312,6 +1321,11 @@ async def api_analyze_documents(
username: Annotated[str, Depends(require_api_access)],
):
"""Search and analyze documents in a local collection via REST API."""
+ if not is_json_request(request):
+ return JSONResponse(
+ {"error": "Both query and collection_name parameters are required"},
+ status_code=400,
+ )
try:
data = await request.json()
except Exception:
diff --git a/src/local_deep_research/web/routers/notes.py b/src/local_deep_research/web/routers/notes.py
index 8f3c59fe72..08252bc053 100644
--- a/src/local_deep_research/web/routers/notes.py
+++ b/src/local_deep_research/web/routers/notes.py
@@ -69,6 +69,7 @@ from ...security.log_sanitizer import (
redact_for_log,
)
from ..dependencies.auth import require_auth
+from ..dependencies.json_body import is_json_request
from ..dependencies.rate_limit import async_shared_limit, limiter, _user_key
from ..dependencies.threadpool import run_db_sync
from ..template_config import templates
@@ -724,6 +725,12 @@ async def _notes_json_body(
if len(body) > _MAX_JSON_BODY_BYTES:
return _too_large()
+ # Keep the body cap for every media type. Flask's get_json(silent=True)
+ # then treated a non-JSON media type as no data, even when its bytes
+ # looked like JSON.
+ if not is_json_request(request):
+ return {}
+
if not body:
# Missing/empty body — leave the route to default as it sees fit
# (matches Flask's ``get_json(silent=True) -> None``).
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 864d9681d9..192c9e83c1 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -109,7 +109,7 @@ from ...constants import (
LANGGRAPH_STRATEGY_ALIASES,
LANGGRAPH_STRATEGY_NAME as LANGGRAPH_STRATEGY_NAME,
)
-from ..dependencies.json_body import json_body_error
+from ..dependencies.json_body import is_json_request, json_body_error
# Create the router for the research application
router = APIRouter(tags=["research"])
@@ -883,6 +883,14 @@ async def start_research(
serialise the entire server behind the slowest /start_research call.
"""
+ # main's @require_json_body(error_format="status") read the body with
+ # get_json(silent=True), which returns None for a non-JSON media type,
+ # so a JSON-looking text/plain body got this 400 and started nothing.
+ # request.json() ignores Content-Type, so the check is explicit here.
+ # POST /research/api/start delegates to this handler and shares it.
+ if not is_json_request(request):
+ return json_body_error("status")
+
# A malformed or non-object JSON body would otherwise reach
# _start_research_sync's data.get(...) calls and 500 (AttributeError).
# Reject at the boundary with a clean 400.
@@ -2172,6 +2180,11 @@ async def save_raw_config(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Save raw configuration"""
+ # Same media-type check as start_research: main's
+ # @require_json_body(error_format="success") refused a non-JSON media
+ # 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")
diff --git a/tests/security/test_hostile_input_matrix.py b/tests/security/test_hostile_input_matrix.py
index e2a707b078..e27519114b 100644
--- a/tests/security/test_hostile_input_matrix.py
+++ b/tests/security/test_hostile_input_matrix.py
@@ -249,6 +249,7 @@ START = "/api/start_research"
# ===========================================================================
#
# The handler's body gate is:
+# non-JSON Content-Type -> 400 "Request body must be valid JSON"
# data = await request.json() -> 400 "Request body must be JSON"
# if not isinstance(data, dict) -> 400 "Request body must be a JSON object"
# and only then does _start_research_sync run.
@@ -285,8 +286,8 @@ def test_start_research_rejects_non_object_and_unparseable_bodies(client):
# Valid JSON, wrong top-level type. Sent as raw bytes rather than via
# httpx's json= so that `null` is a real JSON body and not an omitted
- # one (httpx sends no body at all for json=None, which is a different
- # rejection: "Request body must be JSON").
+ # one (for json=None httpx sends no body and no Content-Type, which the
+ # media-type check rejects first: "Request body must be valid JSON").
for raw in (b"[1, 2]", b'"a string"', b"123", b"null", b"true"):
resp = client.post(
START, content=raw, headers={"Content-Type": "application/json"}
diff --git a/tests/web/dependencies/test_json_body_contract.py b/tests/web/dependencies/test_json_body_contract.py
index 08b54c97ea..a2841e14bc 100644
--- a/tests/web/dependencies/test_json_body_contract.py
+++ b/tests/web/dependencies/test_json_body_contract.py
@@ -3,9 +3,11 @@
Ported from ``tests/security/test_decorators.py`` on ``origin/main``, which
tested ``security/decorators.py::require_json_body`` — a Flask decorator the
migration deleted. Its FastAPI successor is
-``web/dependencies/json_body.py`` (``read_json_dict`` / ``json_body_error``),
-whose own docstring names ``require_json_body`` as the thing it reproduces,
-so this is the same contract on a new spelling rather than a new one.
+``web/dependencies/json_body.py``. ``read_json_dict`` and
+``json_body_error`` reproduce the decorator's parse-and-shape check and its
+400, so that part is the same contract on a new spelling. The decorator's
+media-type check is ``is_json_request``, which ``read_json_dict`` does not
+call; the last section of this file pins it.
What was actually unpinned before this file
-------------------------------------------
@@ -45,7 +47,10 @@ import pytest
from fastapi import FastAPI, Request
from starlette.testclient import TestClient
-from local_deep_research.web.dependencies.json_body import read_json_dict
+from local_deep_research.web.dependencies.json_body import (
+ is_json_request,
+ read_json_dict,
+)
DEFAULT = "Request body must be valid JSON"
@@ -233,3 +238,69 @@ class TestErrorFormatStructure:
resp = _post(client, "/success")
assert resp.status_code == 400
assert set(resp.json()) == {"success", "error"}
+
+
+# ---------------------------------------------------------------------------
+# Media type: is_json_request
+#
+# main's get_json(silent=True) returned None unless Werkzeug's
+# Request.is_json held: the media type (the part before any ";", stripped
+# and lowercased) is application/json or application/*+json. Routes that
+# restore that check call is_json_request before parsing. The rejected list
+# holds the near misses a weakened check would let through:
+# startswith("application/") accepts the form and octet-stream types, a
+# "json" substring test accepts jsonx, x-json, json-seq and text/json, an
+# endswith("json") test accepts x-json and text/json, and a +json suffix
+# test without the application/ prefix accepts text/x+json.
+# ---------------------------------------------------------------------------
+
+
+def _request_with_content_type(content_type):
+ """A real request whose only header is the given Content-Type."""
+ headers = (
+ []
+ if content_type is None
+ else [(b"content-type", content_type.encode("latin-1"))]
+ )
+ return Request(
+ {"type": "http", "method": "POST", "path": "/", "headers": headers}
+ )
+
+
+class TestIsJsonRequest:
+ @pytest.mark.parametrize(
+ "content_type",
+ [
+ "application/json",
+ "application/json; charset=utf-8",
+ "Application/JSON",
+ " application/json ; charset=utf-8",
+ "application/vnd.api+json",
+ "application/problem+json; charset=utf-8",
+ "APPLICATION/VND.EXAMPLE+JSON",
+ ],
+ )
+ def test_json_media_types_are_accepted(self, content_type):
+ request = _request_with_content_type(content_type)
+ assert is_json_request(request) is True
+
+ @pytest.mark.parametrize(
+ "content_type",
+ [
+ None,
+ "",
+ "text/plain",
+ "text/plain; charset=utf-8",
+ "application/x-www-form-urlencoded",
+ "multipart/form-data; boundary=x",
+ "application/octet-stream",
+ "application/jsonx",
+ "application/x-json",
+ "application/json-seq",
+ "text/json",
+ "text/x+json",
+ ],
+ )
+ def test_other_media_types_are_rejected(self, content_type):
+ request = _request_with_content_type(content_type)
+ assert is_json_request(request) is False
diff --git a/tests/web/routers/test_api_v1_external_contract.py b/tests/web/routers/test_api_v1_external_contract.py
index c8802790b6..f5a14a87ac 100644
--- a/tests/web/routers/test_api_v1_external_contract.py
+++ b/tests/web/routers/test_api_v1_external_contract.py
@@ -308,11 +308,11 @@ class TestTheErrorEnvelopeIsNotTheDetailEnvelope:
class TestMalformedBodies:
"""Both branches return 400 with an ``error`` key, as main did — but
with different message text than main's ``@require_json_body``
- produced (see the module docstring of
- ``tests/web/routers/test_json_body_contract_port_fidelity.py``, which
- tracks the Content-Type half of the same divergence). The status and
- envelope are what external callers branch on, so those are pinned
- exactly; the strings are pinned so a further drift is visible."""
+ produced. A non-JSON Content-Type gets main's message again; that
+ half of the contract is pinned in
+ ``tests/web/routers/test_json_body_contract_port_fidelity.py``. The
+ status and envelope are what external callers branch on, so those are
+ pinned exactly; the strings are pinned so a further drift is visible."""
@pytest.mark.parametrize(
"path", [QUICK, REPORT, ANALYZE], ids=["quick", "report", "analyze"]
diff --git a/tests/web/routers/test_json_body_contract_port_fidelity.py b/tests/web/routers/test_json_body_contract_port_fidelity.py
index 60c812554b..1c56453be1 100644
--- a/tests/web/routers/test_json_body_contract_port_fidelity.py
+++ b/tests/web/routers/test_json_body_contract_port_fidelity.py
@@ -1,22 +1,27 @@
-"""Port-fidelity checks for the JSON request-body contract of the three
-routers ported from Flask blueprints that read a body by hand:
+"""Port-fidelity checks for the JSON request-body contract of four routers
+ported from Flask blueprints that read a body by hand:
- * ``web/routers/api.py`` (main: ``web/routes/api_routes.py``)
- * ``web/routers/api_v1.py`` (main: ``web/api.py``)
- * ``web/routers/notes.py`` (main: ``web/routes/notes_routes.py``)
+ * ``web/routers/api.py`` (main: ``web/routes/api_routes.py``)
+ * ``web/routers/api_v1.py`` (main: ``web/api.py``)
+ * ``web/routers/notes.py`` (main: ``web/routes/notes_routes.py``)
+ * ``web/routers/research.py`` (main: ``web/routes/research_routes.py``)
Flask centralised two guarantees in ``request.get_json()`` /
-``@require_json_body`` that the hand-written FastAPI ports each had to
-re-express, and did not fully:
+``@require_json_body`` that the hand-written FastAPI ports must preserve:
1. A body that will not parse and a body that parses to a non-object were
- ONE failure with ONE response envelope. ``api.py`` re-expressed only
- the second half.
+ ONE failure with ONE response envelope.
2. ``get_json(silent=True)`` returned ``None`` for any request whose
- Content-Type was not ``application/json``, so a mislabelled body never
- reached the handler. No port re-expresses that at all.
+ Content-Type was not a JSON media type (``application/json`` or
+ ``application/*+json``), so a mislabelled body never reached the
+ handler.
+
+This file pins the first guarantee for resource creation and the second for
+each route it names.
"""
+from unittest.mock import patch
+
import pytest
# main's @require_json_body default message, kept as one constant by the
@@ -32,12 +37,8 @@ from local_deep_research.web.dependencies.json_body import DEFAULT_MESSAGE
# will not parse" and "body is not an object" into the same
# 400 {"status": "error", "message": "Request body must be valid JSON"}.
#
-# The port kept the second branch (routers/api.py:204-205 calls
-# json_body_error("status", ...)) but reads the body with an unguarded
-# ``await request.json()`` on line 203, so the parse failure escapes to
-# fastapi_app.py's json.JSONDecodeError handler and answers with a
-# DIFFERENT envelope. web/dependencies/json_body.py::read_json_dict exists
-# precisely to cover both halves and is not used here.
+# The route uses read_json_dict so malformed and non-object bodies share
+# that same envelope.
# ---------------------------------------------------------------------------
_ADD_RESOURCE = "/research/api/resources/some-research-id"
@@ -50,7 +51,7 @@ _MAIN_ENVELOPE = {"status": "error", "message": DEFAULT_MESSAGE}
def test_add_resource_non_object_body_uses_main_status_envelope(
authenticated_client, body
):
- """The surviving half of main's contract: a parseable non-object body."""
+ """A parseable non-object body keeps the legacy status envelope."""
resp = authenticated_client.post(
_ADD_RESOURCE,
content=body,
@@ -60,19 +61,6 @@ def test_add_resource_non_object_body_uses_main_status_envelope(
assert resp.json() == _MAIN_ENVELOPE
- strict=True,
- reason=(
- "routers/api.py:203 reads the body with a bare `await "
- "request.json()`. A JSONDecodeError therefore never reaches the "
- "json_body_error('status', ...) call on the next line; it escapes "
- "to fastapi_app.py::handle_json_decode_error, which answers "
- "400 {'error': 'Invalid JSON body'}. main's "
- "@require_json_body(error_format='status') returned the "
- "{'status', 'message'} envelope for this input, the same one the "
- "non-object case above still returns."
- ),
-)
@pytest.mark.parametrize(
"body", [b"{not json", b""], ids=["malformed", "empty"]
)
@@ -93,15 +81,13 @@ def test_add_resource_unparseable_body_uses_main_status_envelope(
#
# Every mutating notes route on main read its body with
# ``request.get_json(silent=True)``, which returns None when
-# ``request.is_json`` is false — i.e. when the client did not send an
-# ``application/json`` Content-Type. create_note then answered
+# ``request.is_json`` is false — i.e. when the client sent neither an
+# ``application/json`` nor an ``application/*+json`` Content-Type.
+# create_note then answered
# 400 {"success": false, "error": "No data provided"}.
#
-# The port's shared body dependency (routers/notes.py::_notes_json_body)
-# reads ``request.stream()`` and calls json.loads on the raw bytes without
-# ever consulting Content-Type, so a text/plain body is accepted and the
-# note is created. The same gate is missing in api.py and api_v1.py, whose
-# ``await request.json()`` likewise ignores Content-Type.
+# The notes dependency still streams and bounds its body, but the media type
+# must be checked before parsing. The direct JSON parsers need the same gate.
# ---------------------------------------------------------------------------
@@ -111,28 +97,18 @@ def test_notes_create_rejects_unparseable_body_as_no_data(
"""Control for the gate below: _notes_json_body's OTHER main-parity
branch still works — an unparseable body degrades to {} so the route's
own "No data provided" 400 fires, exactly as get_json(silent=True)
- made it on main."""
+ made it on main. The body is labelled ``application/json`` so it passes
+ the media-type gate and reaches the parser; a non-JSON label would stop
+ at the gate and never exercise this branch."""
resp = authenticated_client.post(
"/notes/api/notes",
- content=b"title=t&content=c",
- headers={"Content-Type": "application/x-www-form-urlencoded"},
+ content=b"{not json",
+ headers={"Content-Type": "application/json"},
)
assert resp.status_code == 400
assert resp.json() == {"success": False, "error": "No data provided"}
- strict=True,
- reason=(
- "routers/notes.py::_notes_json_body json.loads() the raw request "
- "stream without checking Content-Type, so a JSON object labelled "
- "text/plain is accepted and create_note returns 201. main's "
- "request.get_json(silent=True) returned None for any non-JSON "
- "Content-Type, so the same request got "
- "400 {'success': False, 'error': 'No data provided'} and no note "
- "was written."
- ),
-)
def test_notes_create_requires_json_content_type(authenticated_client):
resp = authenticated_client.post(
"/notes/api/notes",
@@ -143,25 +119,198 @@ def test_notes_create_requires_json_content_type(authenticated_client):
assert resp.json() == {"success": False, "error": "No data provided"}
- strict=True,
- reason=(
- "routers/api_v1.py:410 `await request.json()` ignores Content-Type, "
- "so a text/plain body is parsed and the handler proceeds to its own "
- "'query is required' validation. main's "
- "@require_json_body(error_message='Query parameter is required') ran "
- "get_json(silent=True), which returned None for a non-JSON "
- "Content-Type and rejected the request with that message before any "
- "handler code ran."
- ),
-)
def test_api_v1_quick_summary_requires_json_content_type(
authenticated_client,
):
+ """The body passes the route's own checks, so only the media-type gate
+ can produce this 400. The research function is patched so that a
+ regression fails here instead of running research."""
+ with patch(
+ "local_deep_research.api.research_functions.quick_summary",
+ return_value={},
+ ) as quick_summary:
+ resp = authenticated_client.post(
+ "/api/v1/quick_summary",
+ content=b'{"query": "hello"}',
+ headers={"Content-Type": "text/plain"},
+ )
+ quick_summary.assert_not_called()
+ assert resp.status_code == 400
+ assert resp.json() == {"error": "Query parameter is required"}
+
+
+# POST /api/start_research, and POST /research/api/start, which api.py hands
+# to the same handler. main's @require_json_body(error_format="status")
+# answered a non-JSON media type with _MAIN_ENVELOPE. The route keeps its own
+# messages for a malformed or non-object JSON body, pinned in
+# tests/security/test_hostile_input_matrix.py. _start_research_sync runs only
+# after the handler has accepted the body.
+_START_RESEARCH_SYNC = (
+ "local_deep_research.web.routers.research._start_research_sync"
+)
+_START_BODY = b'{"query": "hello"}'
+
+# POST /api/save_raw_config: main used error_format="success". The config
+# file write runs only after the handler has accepted the body.
+_WRITE_CONFIG = (
+ "local_deep_research.security.file_write_verifier.write_file_verified"
+)
+_RAW_CONFIG_BODY = b'{"raw_config": "answer = 42"}'
+_SUCCESS_ENVELOPE = {"success": False, "error": DEFAULT_MESSAGE}
+
+_RESEARCH_ROUTES = [
+ pytest.param(
+ "/api/start_research",
+ _START_BODY,
+ _START_RESEARCH_SYNC,
+ _MAIN_ENVELOPE,
+ id="start_research",
+ ),
+ pytest.param(
+ "/research/api/start",
+ _START_BODY,
+ _START_RESEARCH_SYNC,
+ _MAIN_ENVELOPE,
+ id="research_api_start",
+ ),
+ pytest.param(
+ "/api/save_raw_config",
+ _RAW_CONFIG_BODY,
+ _WRITE_CONFIG,
+ _SUCCESS_ENVELOPE,
+ id="save_raw_config",
+ ),
+]
+
+
+ ("path", "body", "downstream", "expected"),
+ [
+ *_RESEARCH_ROUTES,
+ pytest.param(
+ "/api/v1/generate_report",
+ b'{"query": "hello"}',
+ "local_deep_research.api.research_functions.generate_report",
+ {"error": "Query parameter is required"},
+ id="generate_report",
+ ),
+ pytest.param(
+ "/api/v1/analyze_documents",
+ b'{"query": "hello", "collection_name": "c"}',
+ "local_deep_research.web.routers.api_v1.analyze_documents",
+ {"error": "Both query and collection_name parameters are required"},
+ id="analyze_documents",
+ ),
+ pytest.param(
+ _ADD_RESOURCE,
+ b'{"title": "t", "url": "https://example.org"}',
+ "local_deep_research.security.ssrf_validator.validate_url",
+ _MAIN_ENVELOPE,
+ id="add_resource",
+ ),
+ ],
+)
+def test_other_json_body_routes_reject_text_plain_before_dispatch(
+ authenticated_client, path, body, downstream, expected
+):
+ """Each body passes its route's own field checks, so only the media-type
+ gate can produce this 400. ``downstream`` is a call the route makes only
+ after it has accepted the body: the research function for the API v1
+ routes, the URL validation for a resource, the research start for both
+ research-start paths and the file write for the raw config. It is
+ patched so that a regression fails here instead of running research,
+ resolving a hostname or writing the config file."""
+ with patch(downstream, return_value={}) as downstream_call:
+ resp = authenticated_client.post(
+ path,
+ content=body,
+ headers={"Content-Type": "text/plain"},
+ )
+ downstream_call.assert_not_called()
+ assert resp.status_code == 400
+ assert resp.json() == expected
+
+
+ ("path", "body", "downstream", "expected"), _RESEARCH_ROUTES
+)
+def test_research_routes_dispatch_the_same_body_labelled_json(
+ authenticated_client, path, body, downstream, expected
+):
+ """Control for the research cases above: labelled ``application/json``,
+ the same body reaches the patched call. So the patch targets are live,
+ and the 400s above come from the media-type gate."""
+ with patch(downstream, return_value={}) as downstream_call:
+ resp = authenticated_client.post(
+ path,
+ content=body,
+ headers={"Content-Type": "application/json"},
+ )
+ downstream_call.assert_called_once()
+ assert resp.status_code == 200, resp.text[:300]
+ assert resp.json() != expected
+
+
+ "content_type",
+ [
+ "application/x-www-form-urlencoded",
+ "application/octet-stream",
+ "application/jsonx",
+ ],
+)
+def test_start_research_rejects_json_lookalike_media_types(
+ authenticated_client, content_type
+):
+ """A JSON-looking body labelled with a near-miss media type stops at
+ the gate too. A check weakened to ``startswith("application/")`` would
+ accept the first two, and one weakened to ``"json" in`` the media type
+ would accept the third."""
+ with patch(_START_RESEARCH_SYNC, return_value={}) as start:
+ resp = authenticated_client.post(
+ "/api/start_research",
+ content=_START_BODY,
+ headers={"Content-Type": content_type},
+ )
+ start.assert_not_called()
+ assert resp.status_code == 400
+ assert resp.json() == _MAIN_ENVELOPE
+
+
+def test_notes_create_accepts_vendor_json_media_type(authenticated_client):
resp = authenticated_client.post(
- "/api/v1/quick_summary",
- content=b'{"query": "hello"}',
+ "/notes/api/notes",
+ content=b'{"title": "vendor JSON", "content": "c"}',
+ headers={"Content-Type": "application/vnd.example+json; charset=utf-8"},
+ )
+ assert resp.status_code == 201
+
+
+ "chunked", [False, True], ids=["content-length", "chunked"]
+)
+def test_notes_body_cap_runs_before_the_media_type_gate(
+ authenticated_client, monkeypatch, chunked
+):
+ """The notes body cap applies whatever the media type, because the
+ gate sits after the capped stream read. An over-cap ``text/plain`` body
+ is therefore a 413. Moving the gate above the Content-Length check
+ would turn both cases into ``{}``, which create_note answers with 400.
+ Moving it between the two cap checks would do that to the chunked
+ case, which has no Content-Length for the first check to see."""
+ import local_deep_research.web.routers.notes as notes_mod
+
+ monkeypatch.setattr(notes_mod, "_MAX_JSON_BODY_BYTES", 16)
+ body = b'{"title": "t", "content": "' + b"x" * 64 + b'"}'
+
+ def _chunks():
+ yield body[:20]
+ yield body[20:]
+
+ resp = authenticated_client.post(
+ "/notes/api/notes",
+ content=_chunks() if chunked else body,
headers={"Content-Type": "text/plain"},
)
- assert resp.status_code == 400
- assert resp.json() == {"error": "Query parameter is required"}
+ assert resp.status_code == 413, resp.text[:300]
+ assert resp.json()["success"] is False
diff --git a/tests/web/routers/test_research_model_log_preview_bound.py b/tests/web/routers/test_research_model_log_preview_bound.py
index a90956b364..54ece61835 100644
--- a/tests/web/routers/test_research_model_log_preview_bound.py
+++ b/tests/web/routers/test_research_model_log_preview_bound.py
@@ -576,8 +576,11 @@ class _StopAfterParameterLogs(BaseException):
def _json_request(payload):
- """A ``Request`` double whose ``json()`` resolves to ``payload``."""
+ """A ``Request`` double labelled ``application/json`` whose ``json()``
+ resolves to ``payload``. The real header matters: routes that check the
+ media type before parsing must see a JSON request, not a MagicMock."""
request = MagicMock()
+ request.headers = {"content-type": "application/json"}
request.json = AsyncMock(return_value=payload)
return request
diff --git a/tests/web/routers/test_start_research_search_override_validation.py b/tests/web/routers/test_start_research_search_override_validation.py
index a10e45a8af..60af7d751a 100644
--- a/tests/web/routers/test_start_research_search_override_validation.py
+++ b/tests/web/routers/test_start_research_search_override_validation.py
@@ -89,10 +89,11 @@ _QUEUE_PROCESSOR = "local_deep_research.web.queue.processor_v2.queue_processor"
def _make_request(payload, session_id="sid-1"):
"""Minimal stand-in for the Starlette ``Request`` the handler reads:
- ``await request.json()``, ``request.session.get(...)``, and
- ``str(request.base_url)``.
+ the Content-Type header, ``await request.json()``,
+ ``request.session.get(...)``, and ``str(request.base_url)``.
"""
request = Mock()
+ request.headers = {"content-type": "application/json"}
request.json = AsyncMock(return_value=payload)
request.session = {"session_id": session_id}
request.base_url = "http://testserver/"
diff --git a/tests/web/test_encoding_and_non_ascii.py b/tests/web/test_encoding_and_non_ascii.py
index b8454310e5..d8764aea9f 100644
--- a/tests/web/test_encoding_and_non_ascii.py
+++ b/tests/web/test_encoding_and_non_ascii.py
@@ -271,10 +271,10 @@ class TestAppLevelHandlerResolution:
# 2. Invalid UTF-8 in a JSON body: how far it reaches
# ===========================================================================
#
-# Booting 27 authenticated routes 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
+# Booting the authenticated routes behind 26 sites 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
# ``except`` clauses (if any) would catch a UnicodeDecodeError?
#
# This reads the real shipped source. It is not a model of the routers.
@@ -395,12 +395,12 @@ def _unguarded_sites():
#: a 400, but it catches ``json.JSONDecodeError`` -- the sibling class --
#: so it converts the syntax failure and misses the encoding one.
#:
-#: Update this set only alongside the fix. A shrinking set means someone
-#: fixed a route; a growing one means a new route was written with the
-#: same gap.
+#: 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.
UNGUARDED_JSON_BODY_SITES = frozenset(
{
- ("api.py", "api_add_resource"),
("benchmark.py", "start_benchmark"),
("benchmark.py", "start_benchmark_simple"),
("benchmark.py", "validate_config"),
@@ -427,7 +427,8 @@ UNGUARDED_JSON_BODY_SITES = frozenset(
# 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 still 27.
+ # 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"),
@@ -486,8 +487,8 @@ class TestInvalidUtf8BodyReach:
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 21 handlers behind, whereas one
- ``ValueError`` handler in ``fastapi_app.py`` closes all 27 at
+ ``library.py`` leaves 20 handlers behind, whereas one
+ ``ValueError`` handler in ``fastapi_app.py`` closes all 26 at
once.
"""
outside_library = {
@@ -499,7 +500,6 @@ class TestInvalidUtf8BodyReach:
modules = {module for module, _function in outside_library}
assert len(outside_library) >= 20, sorted(outside_library)
assert modules >= {
- "api.py",
"benchmark.py",
"library_search.py",
"metrics.py",
@@ -514,7 +514,7 @@ class TestInvalidUtf8BodyReach:
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 27 sites above are the call sites
+ ``@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.
"""
diff --git a/tests/web/test_exception_handler_contract.py b/tests/web/test_exception_handler_contract.py
index fc13c878f3..3eab1e9b06 100644
--- a/tests/web/test_exception_handler_contract.py
+++ b/tests/web/test_exception_handler_contract.py
@@ -389,7 +389,10 @@ class TestMalformedJSONBody:
``await request.json()`` on a malformed body raised JSONDecodeError
into the catch-all and returned 500 where Flask returned 400. Fixed
by the ``json.JSONDecodeError`` handler in
- ``_register_exception_handlers``."""
+ ``_register_exception_handlers``, which the ``handler_client`` tests
+ drive. The real-endpoint test uses a route that parses its own body,
+ so it pins that route's 400 envelope rather than the registered
+ handler."""
def test_malformed_json_returns_400_via_registered_handler(
self, handler_client
@@ -422,7 +425,7 @@ class TestMalformedJSONBody:
self, authenticated_client
):
# End-to-end on the real app: an authenticated endpoint that
- # reads the body via bare `await request.json()` (api.py
+ # uses the route's status-envelope JSON parser (api.py
# api_add_resource). CSRF token header is attached by the
# fixture; the parse failure happens before any DB work.
resp = authenticated_client.post(
@@ -431,7 +434,10 @@ class TestMalformedJSONBody:
headers={"Content-Type": "application/json"},
)
assert resp.status_code == 400
- assert resp.json() == {"error": "Invalid JSON body"}
+ assert resp.json() == {
+ "status": "error",
+ "message": "Request body must be valid JSON",
+ }
# ---------------------------------------------------------------------------