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(research): validate string request field types (#7060)

LearningCircuita7a12e78783e
diff --git a/changelog.d/+provider-request-validation.bugfix.md b/changelog.d/+provider-request-validation.bugfix.md
new file mode 100644
index 0000000000..01bd8f2ce4
--- /dev/null
+++ b/changelog.d/+provider-request-validation.bugfix.md
@@ -0,0 +1 @@
+`POST /api/start_research` (and `POST /research/api/start`, which delegates to it) now rejects a non-string `model_provider`, `search_engine`, `search_tool` or `strategy` with a 400 that names the field (for example `search_engine must be a string`), before any database work. Such values could previously reach string methods and fail with a 500, and falsy ones (`0`, `false`, `[]`, `{}`) were silently treated as unset. JSON `null` and empty strings are still treated as unset.
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 40ba354b8b..2d561d4a0c 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -204,13 +204,56 @@ def history_page(
)
+# Request-body fields the start-research path uses with str methods:
+# ``model_provider`` goes through ``normalize_provider`` (``.lower()``), the
+# engine (``search_engine``, or its ``search_tool`` alias) through
+# ``_precheck_collection_agent_enabled`` (``.startswith``), and ``strategy``
+# through that precheck's ``.lower()``. JSON null and "" still count as
+# unset, so the usual fallbacks apply; any other non-string is a client
+# error. The async ``start_research`` wrapper rejects it before dispatch,
+# and ``_extract_research_params`` rejects it again for in-process callers
+# that skip the wrapper (the news run-now and overdue paths).
+_STRING_REQUEST_FIELDS = (
+ "model_provider",
+ "search_engine",
+ "search_tool",
+ "strategy",
+)
+
+
+def _string_field_error(field):
+ """Return the client-facing 400 message for a non-string ``field``."""
+ return f"{field} must be a string"
+
+
+def _non_string_request_field(data):
+ """Return the first ``_STRING_REQUEST_FIELDS`` name in ``data`` whose
+ value is not null and not a ``str``, or None when there is none."""
+ for field in _STRING_REQUEST_FIELDS:
+ value = data.get(field)
+ if value is not None and not isinstance(value, str):
+ return field
+ return None
+
+
def _extract_research_params(data, settings_manager):
"""Extract and resolve research parameters from request data and settings.
Returns a dict with keys: model_provider, model, custom_endpoint,
ollama_url, search_engine, max_results, time_period, iterations,
- questions_per_iteration, strategy.
+ questions_per_iteration, strategy, policy_egress_scope,
+ llm_require_local_endpoint, embeddings_require_local.
+
+ Raises ``ValueError`` when a ``_STRING_REQUEST_FIELDS`` value is neither
+ null nor a string (checked first, before any settings lookup), when a
+ string ``custom_endpoint`` (from the request or the saved setting) fails
+ the SSRF guard, or when ``iterations`` / ``questions_per_iteration`` is
+ not an integer in range. ``_start_research_sync`` maps each to a fixed
+ 400 message.
"""
+ bad_field = _non_string_request_field(data)
+ if bad_field is not None:
+ raise ValueError(_string_field_error(bad_field))
model_provider = data.get("model_provider")
if not model_provider:
model_provider = settings_manager.get_setting("llm.provider", "ollama")
@@ -860,16 +903,29 @@ async def start_research(
{"status": "error", "message": "query must be a string"},
status_code=400,
)
+ # The string fields (``_STRING_REQUEST_FIELDS``) are used with str
+ # methods after dispatch, so any JSON type other than a string or null
+ # is a 400 here, before any database work. Null and "" still count as
+ # unset in ``_extract_research_params``.
+ bad_field = _non_string_request_field(data)
+ if bad_field is not None:
+ return JSONResponse(
+ {"status": "error", "message": _string_field_error(bad_field)},
+ status_code=400,
+ )
metadata = data.get("metadata", {})
if not isinstance(metadata, dict):
return JSONResponse(
{"status": "error", "message": "metadata must be an object"},
status_code=400,
)
- # Missing query outranks parameter validation so a body with no
- # query and an invalid iterations value reports "Query is required"
- # (the more useful message when both are wrong). Mirrors the early
- # return in _start_research_sync and the api_v1 query-first order.
+ # A missing query outranks the override range checks below, so a body
+ # with no query and an invalid iterations value reports "Query is
+ # required" (the more useful message when both are wrong). Mirrors the
+ # early return in _start_research_sync and the api_v1 query-first
+ # order. The JSON type checks above (query, the string fields,
+ # metadata) still run first, so a wrong-typed field is reported even
+ # when the query is missing.
if not query:
return JSONResponse(
{"status": "error", "message": "Query is required"}, status_code=400
@@ -956,7 +1012,21 @@ def _start_research_sync(
# instead of an unhandled 500. Map to explicit error messages to
# avoid exposing internal exception details (CodeQL py/stack-trace-exposure).
msg = str(exc)
- if "iterations" in msg:
+ # A string-field type error keeps its own message, rebuilt from
+ # the constant field list rather than echoed from ``exc``. Only
+ # in-process callers that skip start_research's identical check
+ # (the news run-now and overdue paths) can reach it.
+ bad_field = next(
+ (
+ field
+ for field in _STRING_REQUEST_FIELDS
+ if msg == _string_field_error(field)
+ ),
+ None,
+ )
+ if bad_field is not None:
+ error_msg = _string_field_error(bad_field)
+ elif "iterations" in msg:
error_msg = f"iterations must be an integer between {ITERATIONS_MIN} and {ITERATIONS_MAX}"
elif "questions_per_iteration" in msg:
error_msg = (
diff --git a/tests/llm/test_provider_adapter_contracts.py b/tests/llm/test_provider_adapter_contracts.py
index 3743a4da03..6a8ce30a3d 100644
--- a/tests/llm/test_provider_adapter_contracts.py
+++ b/tests/llm/test_provider_adapter_contracts.py
@@ -678,19 +678,6 @@ class TestNormalizeProvider:
assert chat.call_count == 1
assert wrapped.base_llm is fake
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT: normalize_provider is None-safe but not type-safe, and "
- "sits directly on an unvalidated request field. "
- "_extract_research_params does normalize_provider("
- "data.get('model_provider')), so a JSON body carrying a "
- "non-string model_provider raises AttributeError and escapes as "
- "a 500 — while start_research already validates the body's "
- "*shape* for exactly this reason, and the sibling failure (a bad "
- "custom_endpoint) is caught as ValueError -> clean 400."
- ),
- )
def test_non_string_model_provider_is_a_client_error(self):
from local_deep_research.web.routers.research import (
_extract_research_params,
diff --git a/tests/web/routers/test_extract_research_params_provider.py b/tests/web/routers/test_extract_research_params_provider.py
index d0ef185e25..f1315a8e7a 100644
--- a/tests/web/routers/test_extract_research_params_provider.py
+++ b/tests/web/routers/test_extract_research_params_provider.py
@@ -7,6 +7,8 @@ values stored in settings / sent by the UI — silently skipping the
ollama_url and custom_endpoint settings fallbacks.
"""
+import pytest
+
from unittest.mock import Mock
from local_deep_research.web.routers.research import (
@@ -76,3 +78,15 @@ def test_custom_endpoint_only_for_openai_endpoint_provider():
sm,
)
assert params["custom_endpoint"] is None
+
+
+ "value", [123, 0, True, False, [], ["ollama"], {}, {"provider": "ollama"}]
+)
+def test_non_string_request_provider_is_rejected_before_settings_fallback(
+ value,
+):
+ sm = _settings_manager({})
+ with pytest.raises(ValueError, match="model_provider must be a string"):
+ _extract_research_params({"model_provider": value}, sm)
+ sm.get_setting.assert_not_called()
diff --git a/tests/web/routers/test_provider_request_types.py b/tests/web/routers/test_provider_request_types.py
new file mode 100644
index 0000000000..0de2dbaceb
--- /dev/null
+++ b/tests/web/routers/test_provider_request_types.py
@@ -0,0 +1,240 @@
+"""JSON types of the research-start string fields are checked before use.
+
+``model_provider``, ``search_engine``, its ``search_tool`` alias and
+``strategy`` are used with str methods once a start request is dispatched
+(``normalize_provider``'s ``.lower()``, and ``.startswith`` / ``.lower()``
+in ``_precheck_collection_agent_enabled``), so any other JSON type except
+null is a 400 that names the field:
+
+* at the async ``start_research`` boundary, before ``run_db_sync``
+ dispatches any database work, and ahead of the missing-query check
+ (the same order as the query and metadata shape checks);
+* in ``_extract_research_params``, before any settings lookup, for the
+ in-process callers that skip that boundary (the news run-now and
+ overdue paths call ``_start_research_sync`` directly), where
+ ``_start_research_sync`` returns the same message instead of its
+ ``Invalid custom endpoint URL`` fallback.
+
+Null and "" still reach dispatch unchanged and are treated as unset, so
+the saved settings apply (for ``search_engine``, after its ``search_tool``
+alias).
+"""
+
+from contextlib import contextmanager
+import json
+from unittest.mock import AsyncMock, MagicMock, Mock, patch
+
+from fastapi import FastAPI
+from fastapi.responses import JSONResponse
+from fastapi.testclient import TestClient
+import pytest
+from starlette.middleware.sessions import SessionMiddleware
+
+from local_deep_research.web.dependencies.auth import require_auth
+from local_deep_research.web.dependencies.rate_limit import limiter
+from local_deep_research.web.routers import research
+
+# Local (inside-function) import in ``_start_research_sync``: patch it at
+# its source module.
+_SETTINGS_MANAGER = "local_deep_research.settings.SettingsManager"
+
+_STRING_FIELDS = ("model_provider", "search_engine", "search_tool", "strategy")
+_NON_STRINGS = [123, 0, 1.5, True, False, [], ["x"], {}, {"k": "v"}]
+_VALID_STRINGS = {
+ "model_provider": ["OLLAMA", "openai_endpoint"],
+ "search_engine": ["searxng", "collection_abc"],
+ "search_tool": ["tavily"],
+ "strategy": ["source-based", "langgraph-agent"],
+}
+_SETTINGS = {
+ "llm.provider": "anthropic",
+ "llm.model": "gpt-4",
+ "search.tool": "searxng",
+ "search.iterations": 5,
+ "search.questions_per_iteration": 5,
+ "search.search_strategy": "source-based",
+}
+
+
+def _type_error(field):
+ return {"status": "error", "message": f"{field} must be a string"}
+
+
+def _settings_manager():
+ sm = Mock()
+ sm.get_setting.side_effect = lambda key, default=None: _SETTINGS.get(
+ key, default
+ )
+ # Not a dict, so _precheck_engine_policy skips (its documented
+ # behaviour for test doubles).
+ sm.get_settings_snapshot.return_value = Mock()
+ return sm
+
+
+def client_and_dispatch(monkeypatch):
+ app = FastAPI()
+ app.add_middleware(SessionMiddleware, secret_key="provider-types-test")
+ app.include_router(research.router)
+ app.dependency_overrides[require_auth] = lambda: "owner"
+ monkeypatch.setattr(limiter, "enabled", False)
+ dispatch = AsyncMock(return_value=JSONResponse({"status": "accepted"}))
+ monkeypatch.setattr(research, "run_db_sync", dispatch)
+ with TestClient(app) as client:
+ yield client, dispatch
+
+
+# ---------------------------------------------------------------------------
+# The async boundary: start_research
+# ---------------------------------------------------------------------------
+
+
[email protected]("value", _NON_STRINGS)
[email protected]("field", _STRING_FIELDS)
+def test_non_string_field_returns_400_without_dispatch(
+ client_and_dispatch, field, value
+):
+ client, dispatch = client_and_dispatch
+ response = client.post(
+ "/api/start_research", json={"query": "q", field: value}
+ )
+ assert response.status_code == 400
+ assert response.json() == _type_error(field)
+ dispatch.assert_not_awaited()
+
+
+ ("field", "value"),
+ [
+ (field, value)
+ for field in _STRING_FIELDS
+ for value in [None, "", *_VALID_STRINGS[field]]
+ ],
+)
+def test_null_empty_and_string_values_reach_dispatch(
+ client_and_dispatch, field, value
+):
+ client, dispatch = client_and_dispatch
+ response = client.post(
+ "/api/start_research", json={"query": "q", field: value}
+ )
+ assert response.status_code == 200
+ assert response.json() == {"status": "accepted"}
+ dispatch.assert_awaited_once()
+ assert dispatch.await_args.args[1][field] == value
+
+
[email protected]("field", _STRING_FIELDS)
+def test_type_error_is_reported_before_a_missing_query(
+ client_and_dispatch, field
+):
+ client, dispatch = client_and_dispatch
+ response = client.post("/api/start_research", json={field: 5})
+ assert response.status_code == 400
+ assert response.json() == _type_error(field)
+ dispatch.assert_not_awaited()
+
+
+def test_missing_query_is_reported_before_override_range_errors(
+ client_and_dispatch,
+):
+ """Control for the order above: the range checks run after the
+ missing-query check, so an invalid ``iterations`` with no query still
+ reports the query."""
+ client, dispatch = client_and_dispatch
+ response = client.post("/api/start_research", json={"iterations": 0})
+ assert response.status_code == 400
+ assert response.json() == {
+ "status": "error",
+ "message": "Query is required",
+ }
+ dispatch.assert_not_awaited()
+
+
+# ---------------------------------------------------------------------------
+# In-process callers: _extract_research_params / _start_research_sync
+# ---------------------------------------------------------------------------
+
+
[email protected]("value", _NON_STRINGS)
[email protected]("field", _STRING_FIELDS)
+def test_extract_rejects_non_string_field_before_settings_lookup(field, value):
+ sm = _settings_manager()
+ with pytest.raises(ValueError, match=f"^{field} must be a string$"):
+ research._extract_research_params({field: value}, sm)
+ sm.get_setting.assert_not_called()
+
+
[email protected]("empty", [None, ""])
+ ("field", "param", "expected"),
+ [
+ ("model_provider", "model_provider", "anthropic"),
+ ("search_engine", "search_engine", "searxng"),
+ ("search_tool", "search_engine", "searxng"),
+ ("strategy", "strategy", "source-based"),
+ ],
+)
+def test_extract_null_and_empty_fields_fall_back_to_settings(
+ field, param, expected, empty
+):
+ params = research._extract_research_params(
+ {field: empty}, _settings_manager()
+ )
+ assert params[param] == expected
+
+
+@contextmanager
+def _session_ctx(*args, **kwargs):
+ yield MagicMock()
+
+
+def _start_in_process(body):
+ """Call ``_start_research_sync`` the way the news paths do.
+
+ The query-length gate is forced to refuse, so a body that gets past
+ parameter extraction stops right after the log lines with "Query too
+ long" and no database or thread work.
+ """
+ with (
+ patch.object(research, "get_user_db_session", _session_ctx),
+ patch(_SETTINGS_MANAGER, return_value=_settings_manager()),
+ patch.object(
+ research,
+ "validate_research_query_length",
+ return_value="Query too long",
+ ),
+ patch.object(research, "start_research_process") as spawn,
+ ):
+ response = research._start_research_sync(
+ body, "owner", "http://testserver/", None
+ )
+ spawn.assert_not_called()
+ return response.status_code, json.loads(response.body)
+
+
[email protected]("value", [5, {"k": "v"}])
[email protected]("field", _STRING_FIELDS)
+def test_in_process_start_reports_the_field_type_error(field, value):
+ """A collection engine sends the non-string ``strategy`` down the path
+ where the collection precheck's ``.lower()`` used to raise."""
+ body = {"query": "q", field: value}
+ if field == "strategy":
+ body["search_engine"] = "collection_abc"
+ assert _start_in_process(body) == (400, _type_error(field))
+
+
+ ("field", "value"),
+ [
+ (field, value)
+ for field in _STRING_FIELDS
+ for value in [None, "", _VALID_STRINGS[field][0]]
+ ],
+)
+def test_in_process_start_accepts_null_empty_and_string_values(field, value):
+ """Control: the same harness observes a body that passes extraction."""
+ assert _start_in_process({"query": "q", field: value}) == (
+ 400,
+ {"status": "error", "message": "Query too long"},
+ )
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 5a9c8c7140..9f65d42eb0 100644
--- a/tests/web/routers/test_research_model_log_preview_bound.py
+++ b/tests/web/routers/test_research_model_log_preview_bound.py
@@ -41,9 +41,15 @@ No HTTP client / DB needed: the source guards run against the imported
modules directly, and the call-path probes mock the per-user session and
the settings manager at their import seams (the idiom of
``test_start_research_ssrf.py``), so everything stays fast and
-deterministic. Every call-path probe feeds a wide value to EVERY body
-field the function logs, so (W1) at any one of those sites, not just the
-named ones, fails the probe and not only a source guard.
+deterministic. Together the call-path probes feed a wide value to every
+value behind a bounded call in ``_BOUNDED_BODY_VALUE_CALLS`` on each line
+they reach, except ``iterations`` and ``questions_per_iteration`` on the
+``Additional parameters`` line: ``_extract_research_params`` range-checks
+both before that line, so the below-return probe sends valid ints. So
+(W1) for any other value at a site a probe reaches, not just the named
+ones, fails that probe and not only a source guard. The ``No model
+specified or configured`` line runs only when no model resolves, which no
+probe reaches, so only its source guard pins it.
"""
import asyncio
@@ -135,15 +141,19 @@ def _wide(n: int = 50_000) -> dict:
class WideNameValue(dict):
"""A wide dict body value for the two fields the code treats as names.
- ``model_provider`` goes through ``normalize_provider`` (``.lower()``)
- and ``search_engine`` through the collection prechecks
- (``.startswith``) BEFORE either reaches its log lines, so a plain wide
- dict posted for them raises first and never exercises the log sites.
- This double duck-types the two calls the path makes on a name (as
- ``None``-ish results) so the real code carries it to the log lines
- unchanged. It is still a ``dict`` to the preview's bounding walk, which
- copies it into a plain 11-entry dict before ``reprlib`` sees it, so
- only an eager ``repr``/f-string of the value stringifies every entry.
+ The request-type guard (``research._non_string_request_field``) rejects
+ any non-string ``model_provider`` or ``search_engine`` before either is
+ logged, so the below-return probe patches it out. Past the guard,
+ ``normalize_provider`` calls ``.lower()`` on ``model_provider`` (after
+ its ``Using model_provider from request`` line) and the collection
+ precheck calls ``.startswith`` on ``search_engine``, both before the
+ ``Starting research with provider`` line, so a plain wide dict would
+ raise there and never reach that log site. This double answers both
+ calls (``.lower()`` returns the value itself, ``.startswith`` returns
+ False) so the real code carries it to the log lines unchanged. It is
+ still a ``dict`` to the preview's bounding walk, which copies it into a
+ plain 11-entry dict before ``reprlib`` sees it, so only an eager
+ ``repr``/f-string of the value stringifies every entry.
"""
def lower(self):
@@ -273,11 +283,11 @@ class TestBodyValueLogSites:
The body carries a 50,000-entry dict for EVERY raw value the
function logs (``model``, logged three times along the path,
- ``model_provider`` twice, ``search_engine``, the three unvalidated
+ ``model_provider`` twice, ``search_engine``, the three
``Additional parameters`` values and the news-search
- ``triggered_by``; the two name fields as ``WideNameValue`` so the
- name-shaped code before the log lines lets them through) and no
- ``query``. Since #6517 the missing-query 400 lives at the top of
+ ``triggered_by``; the two name fields as ``WideNameValue``, as in
+ the below-return probe) and no ``query``. Since #6517 the
+ missing-query 400 lives at the top of
``_start_research_sync`` (before ``_extract_research_params``), so
this probe only exercises the two log sites above that return
(``Request data keys``, news ``triggered_by``) and then returns
@@ -327,15 +337,19 @@ class TestBodyValueLogSites:
so the ``Extracted model value``, ``Starting research with
provider``, and ``Additional parameters`` lines never run there (a
planted eager ``repr()`` below the return escapes it). This probe
- posts a query plus wide unvalidated values (``strategy`` is the
- unvalidated ``Additional parameters`` field; ``iterations`` /
- ``questions_per_iteration`` stay valid ints so validation passes)
- and forces the query-length gate to refuse right after the log
- lines, so every below-return preview runs and nothing heavier does.
- Measured: ~70 element reprs with the bounded preview (10 per log
- of a wide value), 250,000+ with the eager f-strings; one eager
- stringification of any single below-return value (e.g. ``_audit =
- repr(strategy)``) adds 50,000.
+ posts a query plus wide ``model_provider``, ``model``,
+ ``search_engine`` and ``strategy`` values (``iterations`` /
+ ``questions_per_iteration`` stay valid ints because
+ ``_extract_research_params`` range-checks them) and forces the
+ query-length gate to refuse right after the log lines, so every
+ below-return preview runs and nothing heavier does. The request-type
+ guard ``_non_string_request_field`` would reject the wide provider,
+ engine and strategy before any of those lines, so it is patched out
+ here; ``test_provider_request_types.py`` tests the guard itself.
+ Measured: ~70 element reprs with the bounded preview (10 per log of
+ a wide value), 250,000+ with the eager f-strings; one eager
+ stringification of any single wide below-return value (e.g.
+ ``_audit = repr(search_engine)``) adds 50,000.
"""
body = {
"query": "probe query",
@@ -355,6 +369,9 @@ class TestBodyValueLogSites:
with (
patch.object(research_module, "get_user_db_session", _session_ctx),
patch(_SETTINGS_MANAGER, return_value=_settings_manager()),
+ patch.object(
+ research_module, "_non_string_request_field", return_value=None
+ ),
patch.object(
research_module,
"validate_research_query_length",