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(security): return fixed validation messages instead of str(exception) in news update routes (#8185) (#6875)

LearningCircuita6bcc8abe286
diff --git a/src/local_deep_research/news/constants.py b/src/local_deep_research/news/constants.py
index dadcebb0ae..cb5db0c6d5 100644
--- a/src/local_deep_research/news/constants.py
+++ b/src/local_deep_research/news/constants.py
@@ -57,7 +57,13 @@ COMPACT_SUBSCRIPTION_READONLY_ECHO_FIELDS = (
)
-def normalize_compact_subscription_update(data):
+def compact_subscription_update_error(data):
+ """Return the validation message for a compact subscription update, or None.
+
+ Routes return this string to the client directly rather than echoing
+ ``str()`` of a caught exception, so only these fixed messages can ever
+ reach the response body.
+ """
unsupported_fields = (
set(data)
- COMPACT_SUBSCRIPTION_INPUT_FIELDS
@@ -65,16 +71,16 @@ def normalize_compact_subscription_update(data):
)
if unsupported_fields:
fields = ", ".join(sorted(unsupported_fields))
- raise ValueError(f"Unsupported subscription update fields: {fields}")
+ return f"Unsupported subscription update fields: {fields}"
if "is_active" in data and type(data["is_active"]) is not bool:
- raise ValueError("is_active must be a boolean")
+ return "is_active must be a boolean"
if "status" in data and (
type(data["status"]) is not str
or data["status"] not in COMPACT_SUBSCRIPTION_STATUSES
):
- raise ValueError("status must be 'active' or 'paused'")
+ return "status must be 'active' or 'paused'"
if "refresh_interval_minutes" in data and (
type(data["refresh_interval_minutes"]) is not int
@@ -82,7 +88,7 @@ def normalize_compact_subscription_update(data):
<= data["refresh_interval_minutes"]
<= NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES
):
- raise ValueError(
+ return (
"refresh_interval_minutes must be an integer between "
f"{NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES} and "
f"{NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES}"
@@ -94,7 +100,7 @@ def normalize_compact_subscription_update(data):
and data[field] is not None
and type(data[field]) is not str
):
- raise ValueError(f"{field} must be a string or null")
+ return f"{field} must be a string or null"
# ``name`` is user-editable through the full ``PUT /subscriptions/{id}``
# route's ``field_mapping`` (web/routers/news_flask_api.py) and shares
@@ -104,11 +110,19 @@ def normalize_compact_subscription_update(data):
and isinstance(data["name"], str)
and len(data["name"]) > COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH
):
- raise ValueError(
+ return (
"name exceeds maximum length of "
f"{COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH} characters"
)
+ return None
+
+
+def normalize_compact_subscription_update(data):
+ error = compact_subscription_update_error(data)
+ if error is not None:
+ raise ValueError(error)
+
update_data = {
field: data[field]
for field in COMPACT_SUBSCRIPTION_DIRECT_FIELDS
@@ -145,6 +159,47 @@ FOLDER_READONLY_ECHO_FIELDS = (
)
+def folder_update_error(data):
+ """Return the validation message for a folder update, or None.
+
+ See :func:`normalize_folder_update` for the rules. Like
+ :func:`compact_subscription_update_error`, this lets routes return a
+ fixed message without echoing ``str()`` of a caught exception.
+ """
+ unsupported_fields = (
+ set(data) - FOLDER_UPDATABLE_FIELDS - FOLDER_READONLY_ECHO_FIELDS
+ )
+ if unsupported_fields:
+ fields = ", ".join(sorted(unsupported_fields))
+ return f"Unsupported folder update fields: {fields}"
+
+ # ``name`` is NOT NULL on the SubscriptionFolder model (database/models/
+ # news.py), so unlike description/color/icon it cannot accept a null.
+ if "name" in data and type(data["name"]) is not str:
+ return "name must be a string"
+
+ for field in ("description", "color", "icon"):
+ if (
+ field in data
+ and data[field] is not None
+ and type(data[field]) is not str
+ ):
+ return f"{field} must be a string or null"
+
+ if "is_default" in data and type(data["is_default"]) is not bool:
+ return "is_default must be a boolean"
+
+ # ``type(x) is not int`` (rather than ``isinstance``) also rejects a
+ # bool masquerading as an int -- ``type(True) is bool``, not ``int`` --
+ # matching the convention already used above for ``is_default`` and by
+ # ``normalize_compact_subscription_update`` for ``is_active``/
+ # ``refresh_interval_minutes``.
+ if "sort_order" in data and type(data["sort_order"]) is not int:
+ return "sort_order must be an integer"
+
+ return None
+
+
def normalize_folder_update(data):
"""Validate a folder update payload against the allowlisted fields.
@@ -175,36 +230,9 @@ def normalize_folder_update(data):
``FOLDER_UPDATABLE_FIELDS``, so none of them ever reaches ``setattr`` --
this only changes whether *mentioning* them 400s the whole request.
"""
- unsupported_fields = (
- set(data) - FOLDER_UPDATABLE_FIELDS - FOLDER_READONLY_ECHO_FIELDS
- )
- if unsupported_fields:
- fields = ", ".join(sorted(unsupported_fields))
- raise ValueError(f"Unsupported folder update fields: {fields}")
-
- # ``name`` is NOT NULL on the SubscriptionFolder model (database/models/
- # news.py), so unlike description/color/icon it cannot accept a null.
- if "name" in data and type(data["name"]) is not str:
- raise ValueError("name must be a string")
-
- for field in ("description", "color", "icon"):
- if (
- field in data
- and data[field] is not None
- and type(data[field]) is not str
- ):
- raise ValueError(f"{field} must be a string or null")
-
- if "is_default" in data and type(data["is_default"]) is not bool:
- raise ValueError("is_default must be a boolean")
-
- # ``type(x) is not int`` (rather than ``isinstance``) also rejects a
- # bool masquerading as an int -- ``type(True) is bool``, not ``int`` --
- # matching the convention already used above for ``is_default`` and by
- # ``normalize_compact_subscription_update`` for ``is_active``/
- # ``refresh_interval_minutes``.
- if "sort_order" in data and type(data["sort_order"]) is not int:
- raise ValueError("sort_order must be an integer")
+ error = folder_update_error(data)
+ if error is not None:
+ raise ValueError(error)
return {
field: data[field] for field in FOLDER_UPDATABLE_FIELDS if field in data
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 9943aeddc7..4529ef9011 100644
--- a/src/local_deep_research/web/routers/news_flask_api.py
+++ b/src/local_deep_research/web/routers/news_flask_api.py
@@ -25,8 +25,9 @@ from ...news import api
from ...news.constants import (
NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES,
NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES,
+ compact_subscription_update_error,
+ folder_update_error,
normalize_compact_subscription_update,
- normalize_folder_update,
)
from ...news.exceptions import NewsAPIException
from ...news.folder_manager import FolderManager
@@ -1774,7 +1775,7 @@ async def update_folder(
Restricted to an explicit allowlist (``name``, ``description``,
``color``, ``icon``, ``is_default``, ``sort_order``) via
- :func:`normalize_folder_update` -- ``FolderManager.update_folder`` used
+ :func:`folder_update_error` -- ``FolderManager.update_folder`` used
to run a blind ``hasattr``-gated ``setattr`` loop, which is true for
SQLAlchemy internals (``_sa_instance_state``) and the bound ``to_dict``
method too, not just real columns. Validate before dispatching to the
@@ -1785,26 +1786,21 @@ async def update_folder(
)
if _body_err is not None:
return _body_err
- try:
- normalize_folder_update(data)
- except ValueError as error:
- return _subscription_validation_error(str(error))
+ error = folder_update_error(data)
+ if error is not None:
+ return _subscription_validation_error(error)
def _impl():
- # Defense in depth: normalize_folder_update already rejected
- # unsupported fields above (route level, before dispatch to this
- # DB thread), but FolderManager.update_folder validates again, so
- # any caller reaching it directly still gets the same 400 (named
- # field). Run that check here too, but BEFORE opening the DB
- # session/transaction below -- narrowly scoped to just this call
- # so it can never catch an unrelated ValueError raised by the
- # DB/ORM layer inside the ``with`` block and echo its message as
- # if it were a validation error (wrong status code, and a
- # potential internal-detail leak).
- try:
- normalize_folder_update(data)
- except ValueError as e:
- return _subscription_validation_error(str(e))
+ # Defense in depth: the route already validated above (before
+ # dispatch to this DB thread), but FolderManager.update_folder
+ # validates again, so run the same check here BEFORE opening the DB
+ # session so it returns the same 400 (named field). Using the
+ # message-returning helper rather than catching ValueError means an
+ # unrelated DB/ORM exception can never be echoed as a validation
+ # error.
+ error = folder_update_error(data)
+ if error is not None:
+ return _subscription_validation_error(error)
try:
with get_user_db_session(username) as session:
@@ -1904,7 +1900,7 @@ async def update_subscription_folder(
Restricted to an explicit allowlist (``folder``, ``folder_id``,
``name``, ``notes``, ``refresh_interval_minutes``, ``is_active``,
- ``status``) via :func:`normalize_compact_subscription_update` -- the
+ ``status``) via :func:`compact_subscription_update_error` -- the
blind ``setattr`` loop this route used to run wrote any matching
column, so a request body could reach protected or privileged columns
(``custom_endpoint`` included, a third write path alongside
@@ -1918,10 +1914,9 @@ async def update_subscription_folder(
)
if _body_err is not None:
return _body_err
- try:
- normalize_compact_subscription_update(data)
- except ValueError as error:
- return _subscription_validation_error(str(error))
+ error = compact_subscription_update_error(data)
+ if error is not None:
+ return _subscription_validation_error(error)
return await run_db_sync(
_update_subscription_folder_sync, data, subscription_id, username
)
@@ -1929,10 +1924,13 @@ async def update_subscription_folder(
def _update_subscription_folder_sync(data, subscription_id, username):
try:
- try:
- update_data = normalize_compact_subscription_update(data)
- except ValueError as error:
- return _subscription_validation_error(str(error))
+ error = compact_subscription_update_error(data)
+ if error is not None:
+ return _subscription_validation_error(error)
+ # The payload is unchanged after validation above. The normalizer
+ # repeats that check to preserve its contract for non-route callers;
+ # unexpected failures fall through to the scrubbed 500 below.
+ update_data = normalize_compact_subscription_update(data)
logger.info(
f"Updating subscription {subscription_id} with data: {update_data}"
diff --git a/tests/news/test_news_update_validation_messages.py b/tests/news/test_news_update_validation_messages.py
new file mode 100644
index 0000000000..d8a437d9ef
--- /dev/null
+++ b/tests/news/test_news_update_validation_messages.py
@@ -0,0 +1,107 @@
+"""The news update validators' message helpers and their raising wrappers.
+
+Routes return ``compact_subscription_update_error`` /
+``folder_update_error`` output to the client directly instead of echoing
+``str()`` of a caught exception (CodeQL py/stack-trace-exposure, alert
+#8185), so the helpers and the ``normalize_*`` wrappers must agree.
+"""
+
+import re
+
+import pytest
+
+from local_deep_research.news.constants import (
+ COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH,
+ NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES,
+ NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES,
+ compact_subscription_update_error,
+ folder_update_error,
+ normalize_compact_subscription_update,
+ normalize_folder_update,
+)
+
+
+ ("data", "message"),
+ [
+ ({"bogus": 1}, "Unsupported subscription update fields: bogus"),
+ # The allowlist check runs first, so a mass-assignment attempt is
+ # reported as such even when another field is also invalid.
+ (
+ {"custom_endpoint": "x", "is_active": "yes"},
+ "Unsupported subscription update fields: custom_endpoint",
+ ),
+ ({"is_active": "yes"}, "is_active must be a boolean"),
+ ({"status": "gone"}, "status must be 'active' or 'paused'"),
+ ({"notes": 3}, "notes must be a string or null"),
+ *[
+ pytest.param(
+ {"refresh_interval_minutes": value},
+ "refresh_interval_minutes must be an integer between "
+ f"{NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES} and "
+ f"{NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES}",
+ id=label,
+ )
+ for label, value in (
+ ("below-minimum", NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES - 1),
+ ("above-maximum", NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES + 1),
+ ("boolean-interval", True),
+ )
+ ],
+ (
+ {"name": "x" * (COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH + 1)},
+ "name exceeds maximum length of "
+ f"{COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH} characters",
+ ),
+ ],
+)
+def test_compact_subscription_update_messages(data, message):
+ assert compact_subscription_update_error(data) == message
+ with pytest.raises(ValueError, match=f"^{re.escape(message)}$"):
+ normalize_compact_subscription_update(data)
+
+
+def test_compact_subscription_update_valid():
+ data = {"name": "n", "is_active": False, "id": 1}
+ assert compact_subscription_update_error(data) is None
+ assert normalize_compact_subscription_update(data) == {
+ "name": "n",
+ "status": "paused",
+ }
+
+
+ ("status", "is_active"), [("paused", True), ("active", False)]
+)
+def test_compact_subscription_explicit_status_takes_precedence(
+ status, is_active
+):
+ data = {"status": status, "is_active": is_active}
+ assert compact_subscription_update_error(data) is None
+ assert normalize_compact_subscription_update(data) == {"status": status}
+
+
+ ("data", "message"),
+ [
+ ({"bogus": 1}, "Unsupported folder update fields: bogus"),
+ (
+ {"to_dict": "x", "sort_order": True},
+ "Unsupported folder update fields: to_dict",
+ ),
+ ({"name": None}, "name must be a string"),
+ ({"color": 1}, "color must be a string or null"),
+ ({"is_default": 1}, "is_default must be a boolean"),
+ ({"sort_order": True}, "sort_order must be an integer"),
+ ],
+)
+def test_folder_update_messages(data, message):
+ assert folder_update_error(data) == message
+ with pytest.raises(ValueError, match=f"^{re.escape(message)}$"):
+ normalize_folder_update(data)
+
+
+def test_folder_update_valid():
+ data = {"name": "n", "sort_order": 2, "id": 7}
+ assert folder_update_error(data) is None
+ assert normalize_folder_update(data) == {"name": "n", "sort_order": 2}
diff --git a/tests/security/test_news_error_scrub_wiring.py b/tests/security/test_news_error_scrub_wiring.py
index 62b4681922..d751c50235 100644
--- a/tests/security/test_news_error_scrub_wiring.py
+++ b/tests/security/test_news_error_scrub_wiring.py
@@ -41,7 +41,15 @@ SCRUBBER_FN = MODULE.safe_error_message
SCRUBBER = SCRUBBER_FN.__name__
# Builders whose first positional argument becomes the response body.
-_RESPONSE_BUILDERS = {"JSONResponse", "HTMLResponse", "PlainTextResponse"}
+# ``_subscription_validation_error`` wraps its message in a JSONResponse, so it
+# counts too: the ``_subscription_validation_error(str(error))`` call sites that
+# CodeQL flagged (alert #8185) slipped past this check while it was missing.
+_RESPONSE_BUILDERS = {
+ "JSONResponse",
+ "HTMLResponse",
+ "PlainTextResponse",
+ MODULE._subscription_validation_error.__name__,
+}
# A handler count far below the real one would mean the walk stopped finding
# things — see test_detector_is_not_scanning_an_empty_module.
@@ -161,6 +169,7 @@ class TestDetectorIsNotVacuous:
'return JSONResponse({"error": str(e)}, status_code=500)',
'return JSONResponse({"error": f"failed: {e}"}, status_code=500)',
'return {"error": str(e)}',
+ "return _subscription_validation_error(str(e))",
],
)
def test_detector_catches_a_planted_leak(self, planted):
diff --git a/tests/security/test_news_router_ssrf.py b/tests/security/test_news_router_ssrf.py
index 719483a8c2..363a759432 100644
--- a/tests/security/test_news_router_ssrf.py
+++ b/tests/security/test_news_router_ssrf.py
@@ -39,6 +39,7 @@ from fastapi import FastAPI
from starlette.testclient import TestClient
from local_deep_research.web.dependencies.auth import require_auth
+from local_deep_research.web.routers import news_flask_api
from local_deep_research.web.routers.news_flask_api import (
_is_valid_uuid,
_reject_custom_endpoint,
@@ -425,6 +426,27 @@ class TestUpdateFolderRouteRejectsMassAssignment:
assert "_sa_instance_state" in response.json()["error"]
live.db_session.assert_not_called()
+ def test_invalid_body_is_rejected_before_offload(self, live):
+ """The route validates before dispatching to the DB thread.
+
+ ``_impl`` re-validates too, so dropping the route-level check would
+ still 400 -- but only after handing an invalid body to
+ ``run_db_sync``. Pin the early rejection, as the compact
+ subscription route's tests do.
+ """
+ with patch.object(news_flask_api, "run_db_sync") as offload:
+ response = live.client.put(
+ "/news/api/subscription/folders/folder-1",
+ json={"to_dict": "x"},
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 400
+ assert response.json() == {
+ "error": "Unsupported folder update fields: to_dict"
+ }
+ offload.assert_not_called()
+
def test_allowlisted_field_is_still_accepted(self, live):
"""The allowlist narrows the route, it does not break it.