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): validate custom_endpoint and subscription_id on the live news API (#5603)

LearningCircuit50b19c0afbae
diff --git a/changelog.d/+news-live-blueprint-ssrf.security.md b/changelog.d/+news-live-blueprint-ssrf.security.md
new file mode 100644
index 0000000000..90db54a6e5
--- /dev/null
+++ b/changelog.d/+news-live-blueprint-ssrf.security.md
@@ -0,0 +1,30 @@
+Closed an SSRF hole in the news subscription API. A custom LLM endpoint
+(`custom_endpoint`) supplied when creating or updating a subscription is
+fetched server-side, and the `/news/api` blueprint — the one the app actually
+calls — accepted it without validation. The guard existed only on the
+`/api/news` blueprint, which nothing routes to; it is now applied where
+requests actually arrive, on both `POST /news/api/subscribe` and
+`PUT /news/api/subscriptions/<id>`, before anything is written or any research
+thread is spawned. A wrong-typed `custom_endpoint` (a number, a list) is now a
+400 rather than a 500 or a silently stored value.
+
+The guard is a denylist, not an allowlist: it blocks cloud metadata,
+link-local addresses and non-HTTP schemes, but loopback and private-network
+addresses stay allowed on purpose, because that is how people point this at
+Ollama, LM Studio or vLLM. Other internal targets — including the app's own
+admin port and a Docker daemon on the bridge address — therefore remain
+reachable through this field by design. The check also validates the
+submitted URL only: it does not pin the resolved IP, and a redirect from an
+allowed host to a metadata address would still be followed by the LLM client,
+which is the one case the metadata denylist is meant to stop.
+
+`GET /news/api/feed` additionally rejects a `subscription_id` that is neither
+a UUID nor the documented `all` sentinel, and
+`GET /news/api/subscriptions/<id>/history` rejects a path id that is not a
+UUID. Those are the two ids that reach a LIKE pattern rather than an equality
+filter. Both checks are defence in depth rather than fixes: the LIKE queries
+already escape `%` and `_` with an explicit escape character, so neither was
+exploitable. Subscription ids are generated as UUID4s, and the sibling
+`/api/news` blueprint has always applied the same check to its history route.
+The remaining subscription routes match their path id by equality, so they
+need no such check.
diff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.py
index 77745e39dc..0c0903f01e 100644
--- a/src/local_deep_research/news/flask_api.py
+++ b/src/local_deep_research/news/flask_api.py
@@ -3,6 +3,7 @@ Flask API endpoints for news system.
Converted from FastAPI to match LDR's Flask architecture.
"""
+import uuid as _uuid
from functools import wraps
from typing import Any
from flask import Blueprint, request, jsonify
@@ -16,8 +17,13 @@ from ..database.session_context import get_user_db_session
from ..settings.env_registry import get_env_setting
from ..utilities.db_utils import get_settings_manager
from ..llm.providers.base import normalize_provider
+from ..utilities.url_utils import is_safe_custom_llm_endpoint
from ..security.decorators import require_json_body
+# ``news/api.py`` treats this subscription_id as "do not filter by
+# subscription" (:140, :423), so it is a valid value that is not a UUID.
+NO_SUBSCRIPTION_FILTER = "all"
+
# Hard ceiling for user-supplied ``limit`` query params on the news
# endpoints in this module. Matches the ``max_value`` of the
# ``news.feed.default_limit`` setting so a direct API caller cannot request a
@@ -195,6 +201,44 @@ def get_user_id():
return username
+def _reject_custom_endpoint(custom_endpoint):
+ """400 if ``custom_endpoint`` fails SSRF validation, else None.
+
+ A user-supplied LLM base URL is fetched server-side, so an unvalidated
+ value is a straight SSRF into the deployment's network.
+
+ The underlying check is a *denylist*: it blocks cloud-metadata and
+ link-local addresses and non-HTTP schemes, but deliberately permits
+ loopback and RFC1918 targets because that is how people point this at
+ Ollama / LM Studio / vLLM. Other internal hosts therefore remain
+ reachable by design.
+ """
+ if is_safe_custom_llm_endpoint(custom_endpoint):
+ return None
+ return (
+ jsonify({"success": False, "error": "Invalid custom endpoint URL"}),
+ 400,
+ )
+
+
+def _is_valid_uuid(value: str) -> bool:
+ """True if ``value`` parses as a UUID.
+
+ Defence in depth, not a fix for a live hole: subscription ids reach
+ LIKE-pattern queries in ``news/api.py``, but every one of those already
+ wraps the value in ``escape_like()`` and pairs it with an explicit LIKE
+ escape character (``api.py`` :148-150, :531-542, :761-766), so ``%`` and
+ ``_`` are neutralised before they reach SQL. This rejects malformed ids
+ at the boundary so a future call site that forgets to escape does not
+ become one.
+ """
+ try:
+ _uuid.UUID(str(value))
+ return True
+ except (ValueError, AttributeError, TypeError):
+ return False
+
+
@news_api_bp.route("/feed", methods=["GET"])
@login_required
def get_news_feed() -> Any:
@@ -222,6 +266,17 @@ def get_news_feed() -> Any:
strategy = request.args.get("strategy")
focus = request.args.get("focus")
subscription_id = request.args.get("subscription_id")
+ # ``news/api.py`` (:140, :423) documents "all" as the "no
+ # subscription filter" sentinel, so it must survive the UUID check
+ # or external clients using it start getting 400s.
+ if (
+ subscription_id
+ and subscription_id != NO_SUBSCRIPTION_FILTER
+ and not _is_valid_uuid(subscription_id)
+ ):
+ return jsonify(
+ {"success": False, "error": "Invalid subscription_id"}
+ ), 400
logger.info(
f"News feed params: limit={limit}, subscription_id={subscription_id}, focus={focus}"
@@ -301,6 +356,9 @@ def create_subscription() -> Any:
model = data.get("model")
search_strategy = data.get("search_strategy", "news_aggregation")
custom_endpoint = data.get("custom_endpoint")
+ endpoint_rejection = _reject_custom_endpoint(custom_endpoint)
+ if endpoint_rejection:
+ return endpoint_rejection
# Extract additional fields
name = data.get("name")
@@ -553,6 +611,13 @@ def update_subscription(subscription_id: str) -> Any:
update_data = {}
# Map fields from request to storage format
+ if "custom_endpoint" in data:
+ endpoint_rejection = _reject_custom_endpoint(
+ data.get("custom_endpoint")
+ )
+ if endpoint_rejection:
+ return endpoint_rejection
+
field_mapping = {
"query": "query_or_topic",
"name": "name",
@@ -733,6 +798,18 @@ def run_subscription_now(subscription_id: str) -> Any:
@login_required
def get_subscription_history(subscription_id: str) -> Any:
"""Get research history for a subscription."""
+ # This path id is the one other route parameter that reaches a LIKE
+ # pattern rather than an equality filter: ``api.get_subscription_history``
+ # builds ``%"subscription_id": "<id>"%`` and runs it through
+ # ``ResearchHistory.research_meta.like(...)`` (api.py :530-542). It is
+ # already ``escape_like``-wrapped with an explicit escape character, so
+ # this is the same defence in depth the feed route applies to its query
+ # parameter -- and it matches the sibling blueprint, which has always
+ # checked this id (web/routes/news_routes.py :213).
+ if not _is_valid_uuid(subscription_id):
+ return jsonify(
+ {"success": False, "error": "Invalid subscription_id"}
+ ), 400
try:
settings_manager = get_settings_manager()
default_limit = settings_manager.get_setting("news.feed.default_limit")
@@ -1437,6 +1514,17 @@ def update_subscription_folder(subscription_id):
"""Update a subscription (mainly for folder assignment)"""
try:
data = request.json
+ # This route's blind setattr loop below writes any matching column,
+ # so ``custom_endpoint`` reaches storage here too -- a third write
+ # path alongside create_subscription / update_subscription. Validate
+ # it at the boundary (before the unredacted log line) so this route
+ # cannot persist an SSRF endpoint the sibling routes reject.
+ if "custom_endpoint" in data:
+ endpoint_rejection = _reject_custom_endpoint(
+ data.get("custom_endpoint")
+ )
+ if endpoint_rejection:
+ return endpoint_rejection
logger.info(
f"Updating subscription {subscription_id} with data: {data}"
)
diff --git a/src/local_deep_research/security/url_builder.py b/src/local_deep_research/security/url_builder.py
index 5c0d9c7320..6f5a947c61 100644
--- a/src/local_deep_research/security/url_builder.py
+++ b/src/local_deep_research/security/url_builder.py
@@ -183,6 +183,16 @@ def mask_sensitive_url(url: str) -> str:
Returns:
URL with sensitive parts replaced with ***
"""
+ # A non-string never reaches the masking logic usefully: urlparse(None)
+ # and urlparse([]) do NOT raise, they return empty byte-ish parts, so the
+ # function used to emit nonsense like "b''://b''b''" -- unmasked and
+ # meaningless. Non-strings also broke the except-branch, which does
+ # url.split(':') and raises AttributeError from inside the very helper
+ # that exists to make logging an unexpected value safe. There is no
+ # scheme worth preserving here, so mask the whole thing.
+ if not isinstance(url, str):
+ return "***"
+
try:
parsed = urlparse(url)
@@ -210,5 +220,11 @@ def mask_sensitive_url(url: str) -> str:
return masked
except Exception:
- # If parsing fails, just return generic mask
- return f"{url.split(':')[0]}://***"
+ # If parsing fails, return a generic mask. ``url`` is a str by the
+ # time it reaches here -- non-strings returned "***" above -- so the
+ # split cannot itself raise. That matters: this handler exists to
+ # make logging an unexpected value safe, so it must never be the
+ # thing that fails. A value with no scheme masks entirely rather
+ # than emitting a bare "://***".
+ scheme = url.split(":", 1)[0]
+ return f"{scheme}://***" if scheme else "***"
diff --git a/src/local_deep_research/utilities/url_utils.py b/src/local_deep_research/utilities/url_utils.py
index 5d8fe2b319..d0ac702afa 100644
--- a/src/local_deep_research/utilities/url_utils.py
+++ b/src/local_deep_research/utilities/url_utils.py
@@ -550,8 +550,27 @@ def is_safe_custom_llm_endpoint(custom_endpoint: Optional[str]) -> bool:
LangChain client is constructed. This guard simply rejects early —
before any DB row is written or research thread is spawned — and
keeps the endpoint out of the logs.
+
+ Scope: this validates the *submitted* URL only. Nothing pins the IP
+ the host later resolves to, and ``assert_base_url_safe`` re-checks the
+ same base URL rather than a redirect target, so a 302 from an allowed
+ host to ``http://169.254.169.254/`` still reaches the metadata service
+ if the LLM client follows redirects.
+
+ Callers hand this whatever a JSON body contained, so a non-string
+ (other than ``None``) is rejected rather than coerced: it cannot be a
+ usable endpoint, and coercing it would either raise inside ``strip()``
+ or silently treat ``[]`` / ``{}`` as "unset" and persist them.
"""
- endpoint = (custom_endpoint or "").strip()
+ if custom_endpoint is None:
+ return True
+ if not isinstance(custom_endpoint, str):
+ logger.warning(
+ "SSRF protection: rejected non-string custom_endpoint of type {}",
+ type(custom_endpoint).__name__,
+ )
+ return False
+ endpoint = custom_endpoint.strip()
if not endpoint:
return True
candidate = normalize_url(endpoint)
diff --git a/tests/news/test_flask_api_coverage.py b/tests/news/test_flask_api_coverage.py
index 7f2b2ac192..b13028ab02 100644
--- a/tests/news/test_flask_api_coverage.py
+++ b/tests/news/test_flask_api_coverage.py
@@ -664,6 +664,10 @@ class TestGetCurrentUserSubscriptions:
class TestSubscriptionHistory:
+ # The history path id reaches a LIKE pattern in ``news/api.py``, so the
+ # route rejects a non-UUID id with a 400 before the service layer.
+ SUB_ID = "11111111-1111-4111-8111-111111111111"
+
def _ms(self):
m = MagicMock()
m.get_setting.return_value = 20
@@ -678,7 +682,7 @@ class TestSubscriptionHistory:
return_value={"history": []},
),
):
- resp = client.get("/news/api/subscriptions/s1/history")
+ resp = client.get(f"/news/api/subscriptions/{self.SUB_ID}/history")
assert resp.status_code == 200
def test_error_in_result(self, client):
@@ -690,7 +694,7 @@ class TestSubscriptionHistory:
return_value={"error": "fail"},
),
):
- resp = client.get("/news/api/subscriptions/s1/history")
+ resp = client.get(f"/news/api/subscriptions/{self.SUB_ID}/history")
assert resp.status_code == 500
diff --git a/tests/news/test_flask_api_deep_coverage.py b/tests/news/test_flask_api_deep_coverage.py
index 055039a366..8d910649f6 100644
--- a/tests/news/test_flask_api_deep_coverage.py
+++ b/tests/news/test_flask_api_deep_coverage.py
@@ -129,7 +129,7 @@ class TestGetNewsFeed:
mock_sm.return_value = mock_sm_instance
resp = authed_client.get(
- "/news/api/feed?limit=5&strategy=latest&subscription_id=sub1&focus=tech"
+ "/news/api/feed?limit=5&strategy=latest&subscription_id=11111111-1111-4111-8111-111111111111&focus=tech"
)
assert resp.status_code == 200
@@ -139,7 +139,7 @@ class TestGetNewsFeed:
use_cache=True,
focus="tech",
search_strategy="latest",
- subscription_id="sub1",
+ subscription_id="11111111-1111-4111-8111-111111111111",
)
def test_use_cache_false(self, authed_client):
@@ -932,6 +932,10 @@ class TestDeleteSubscription:
class TestGetSubscriptionHistory:
"""Tests for the /subscriptions/<id>/history endpoint."""
+ # The history path id reaches a LIKE pattern in ``news/api.py``, so the
+ # route rejects a non-UUID id with a 400 before the service layer.
+ SUB_ID = "11111111-1111-4111-8111-111111111111"
+
def test_returns_history(self, authed_client):
patches = _auth_patches()
mock_result = {
@@ -953,11 +957,13 @@ class TestGetSubscriptionHistory:
mock_sm_instance.get_setting.return_value = 20
mock_sm.return_value = mock_sm_instance
- resp = authed_client.get("/news/api/subscriptions/s1/history")
+ resp = authed_client.get(
+ f"/news/api/subscriptions/{self.SUB_ID}/history"
+ )
assert resp.status_code == 200
data = resp.get_json()
assert len(data["history"]) == 2
- mock_hist.assert_called_once_with("s1", 20)
+ mock_hist.assert_called_once_with(self.SUB_ID, 20)
def test_custom_limit(self, authed_client):
patches = _auth_patches()
@@ -976,10 +982,10 @@ class TestGetSubscriptionHistory:
mock_sm.return_value = mock_sm_instance
resp = authed_client.get(
- "/news/api/subscriptions/s1/history?limit=5"
+ f"/news/api/subscriptions/{self.SUB_ID}/history?limit=5"
)
assert resp.status_code == 200
- mock_hist.assert_called_once_with("s1", 5)
+ mock_hist.assert_called_once_with(self.SUB_ID, 5)
def test_error_in_result(self, authed_client):
patches = _auth_patches()
@@ -997,7 +1003,9 @@ class TestGetSubscriptionHistory:
mock_sm_instance.get_setting.return_value = 20
mock_sm.return_value = mock_sm_instance
- resp = authed_client.get("/news/api/subscriptions/s1/history")
+ resp = authed_client.get(
+ f"/news/api/subscriptions/{self.SUB_ID}/history"
+ )
assert resp.status_code == 500
diff --git a/tests/security/test_news_live_blueprint_ssrf.py b/tests/security/test_news_live_blueprint_ssrf.py
new file mode 100644
index 0000000000..fb9cc680eb
--- /dev/null
+++ b/tests/security/test_news_live_blueprint_ssrf.py
@@ -0,0 +1,438 @@
+"""The LIVE news blueprint must validate custom_endpoint and subscription_id.
+
+An SSRF guard was added to ``web/routes/news_routes.py`` (mounted at
+``/api/news``) but never to ``news/flask_api.py`` (mounted at ``/news/api``).
+The frontend only ever calls ``/news/api``, so the fix landed on the copy
+nobody uses while the live path kept accepting ``custom_endpoint``
+unvalidated -- a user-supplied LLM base URL that the server fetches, i.e. a
+straight SSRF into the deployment's network (cloud metadata, internal admin
+ports, sibling containers).
+
+The ``subscription_id`` UUID check is defence in depth, not a fix for a live
+hole: every LIKE in ``news/api.py`` already wraps the value in
+``escape_like()`` and pairs it with an explicit LIKE escape character, so
+``%`` and ``_`` are neutralised before they reach SQL.
+
+Because the defect being fixed was a *working* guard on a blueprint nobody
+routes to, the call sites are pinned by driving real HTTP requests through
+the blueprint the app actually mounts. Testing the helpers alone would
+reproduce exactly that mistake, and asserting that the guard's name appears
+in ``inspect.getsource()`` would survive deleting the ``return`` that is the
+only thing making the guard do anything.
+"""
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.news.flask_api import (
+ _is_valid_uuid,
+ _reject_custom_endpoint,
+)
+
+# A syntactically valid subscription id, for cases where the UUID guard is
+# not the thing under test.
+A_UUID = "11111111-1111-4111-8111-111111111111"
+
+# The canonical SSRF target: EC2 / GCP / Azure instance metadata.
+METADATA_URL = "http://169.254.169.254/"
+
+
+def app_ctx():
+ """A bare Flask app context.
+
+ ``_reject_custom_endpoint`` builds its 400 with ``jsonify``, which needs
+ one. The validation itself is context-free; this is only scaffolding.
+ """
+ from flask import Flask
+
+ with Flask(__name__).app_context():
+ yield
+
+
+class TestCustomEndpointSSRF:
+ @pytest.mark.parametrize(
+ "endpoint",
+ [
+ "http://169.254.169.254/latest/meta-data/", # cloud metadata
+ "http://[fd00:ec2::254]/", # IPv6 metadata
+ "file:///etc/passwd", # non-HTTP scheme
+ "gopher://example.com/",
+ ],
+ )
+ def test_internal_and_non_http_targets_are_rejected(
+ self, endpoint, app_ctx
+ ):
+ rejected = _reject_custom_endpoint(endpoint)
+
+ assert rejected is not None, (
+ f"{endpoint!r} was accepted as a custom LLM endpoint -- the "
+ "server would fetch it, which is SSRF"
+ )
+ body, status = rejected
+ assert status == 400
+
+ def test_absent_endpoint_is_allowed(self, app_ctx):
+ """custom_endpoint is optional; omitting it must not 400."""
+ assert _reject_custom_endpoint(None) is None
+
+ @pytest.mark.parametrize(
+ "endpoint",
+ [
+ "https://api.openai.com/v1",
+ "http://127.0.0.1:11434", # Ollama
+ "http://192.168.1.10:8000", # LM Studio / vLLM on the LAN
+ "localhost:11434", # scheme-less, as the provider normalises it
+ ],
+ )
+ def test_local_llm_backends_stay_allowed(self, endpoint, app_ctx):
+ """The guard must not break the feature it protects.
+
+ Private IPs and localhost are allowed DELIBERATELY -- that is how
+ people point this at Ollama / LM Studio / vLLM. The guard is a
+ metadata / non-HTTP-scheme denylist, not a private-IP allowlist, so
+ other internal targets on the deployment's own network stay
+ reachable by design.
+ """
+ assert _reject_custom_endpoint(endpoint) is None
+
+ @pytest.mark.parametrize("endpoint", [123, b"http://x", [], {}, 1.5])
+ def test_non_string_endpoint_is_rejected_not_crashed(
+ self, endpoint, app_ctx
+ ):
+ """A JSON body can carry any type, so the guard must not assume str.
+
+ Before this was handled, ``123`` raised ``AttributeError`` and
+ ``b"..."`` a ``TypeError`` inside the validator (surfacing as a 500),
+ while ``[]`` and ``{}`` were treated as "unset" and persisted.
+ """
+ rejected = _reject_custom_endpoint(endpoint)
+
+ assert rejected is not None
+ body, status = rejected
+ assert status == 400
+
+
+class TestSubscriptionIdValidation:
+ @pytest.mark.parametrize(
+ "value",
+ ["%", "_", "%%", "a%b", "' OR 1=1 --", "", "not-a-uuid", None, 123],
+ )
+ def test_non_uuid_values_are_rejected(self, value):
+ assert _is_valid_uuid(value) is False
+
+ def test_real_uuid_is_accepted(self):
+ import uuid
+
+ assert _is_valid_uuid(str(uuid.uuid4())) is True
+
+
+class TestMaskSensitiveUrlNeverRaises:
+ """The masker is what makes logging an unexpected value safe, so it must
+ not be the thing that raises on one."""
+
+ @pytest.mark.parametrize("value", [12345, None, object(), b"bytes", []])
+ def test_non_string_input_is_masked_not_raised(self, value):
+ from local_deep_research.security.url_builder import (
+ mask_sensitive_url,
+ )
+
+ masked = mask_sensitive_url(value)
+
+ assert isinstance(masked, str)
+ assert "***" in masked
+
+ def test_password_is_still_masked(self):
+ from local_deep_research.security.url_builder import (
+ mask_sensitive_url,
+ )
+
+ masked = mask_sensitive_url("https://user:[email protected]/hook")
+
+ assert "hunter2" not in masked
+
+
+# ---------------------------------------------------------------------------
+# The guards must be wired into the blueprint the app actually mounts.
+#
+# These go over HTTP through the real routes, real decorators and real
+# guards; only the service layer below the guards is stubbed, so nothing
+# reaches a network or a database. Deleting either guard's ``return`` -- the
+# exact regression that produced this bug -- fails these.
+# ---------------------------------------------------------------------------
+
+
+def news_app():
+ """A Flask app with the live news blueprint at its real mount point."""
+ from flask import Flask
+
+ from local_deep_research.news.flask_api import news_api_bp
+
+ app = Flask(__name__)
+ app.config["SECRET_KEY"] = "test-secret-key"
+ app.config["WTF_CSRF_ENABLED"] = False
+ app.config["TESTING"] = True
+ app.register_blueprint(news_api_bp, url_prefix="/news/api")
+ return app
+
+
+def live(news_app):
+ """Authenticated client over the live blueprint.
+
+ Auth plumbing and the ``news.api`` service layer are stubbed so that a
+ request which gets past the guards succeeds; that way a non-400 response
+ proves the guard let the value through rather than that something else
+ happened to fail.
+ """
+ client = news_app.test_client()
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+
+ with (
+ patch("local_deep_research.web.auth.decorators.db_manager") as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.get_user_id",
+ return_value="testuser",
+ ),
+ patch(
+ "local_deep_research.news.flask_api.get_settings_manager"
+ ) as mock_settings,
+ patch("local_deep_research.news.flask_api.api") as mock_api,
+ ):
+ mock_db.is_user_connected.return_value = True
+ mock_settings.return_value.get_setting.return_value = 20
+ mock_api.get_news_feed.return_value = {"news_items": [], "total": 0}
+ mock_api.create_subscription.return_value = {
+ "id": A_UUID,
+ "status": "active",
+ }
+ mock_api.update_subscription.return_value = {"id": A_UUID}
+ mock_api.get_subscription_history.return_value = {
+ "subscription_id": A_UUID,
+ "history": [],
+ }
+ yield SimpleNamespace(client=client, api=mock_api)
+
+
+class TestSubscribeRouteRejectsSSRF:
+ """POST /news/api/subscribe -- the route the frontend really calls."""
+
+ def test_metadata_endpoint_returns_400(self, live):
+ response = live.client.post(
+ "/news/api/subscribe",
+ json={"query": "AI news", "custom_endpoint": METADATA_URL},
+ )
+
+ assert response.status_code == 400, (
+ f"POST /news/api/subscribe accepted {METADATA_URL!r} "
+ f"(HTTP {response.status_code}) -- the server would fetch cloud "
+ "metadata on the subscription's behalf"
+ )
+ live.api.create_subscription.assert_not_called()
+
+ def test_ollama_endpoint_is_not_rejected(self, live):
+ """The guard must not break pointing a subscription at a local LLM."""
+ response = live.client.post(
+ "/news/api/subscribe",
+ json={
+ "query": "AI news",
+ "custom_endpoint": "http://localhost:11434/v1",
+ },
+ )
+
+ assert response.status_code != 400
+ live.api.create_subscription.assert_called_once()
+
+ def test_non_string_endpoint_returns_400_not_500(self, live):
+ """A wrong-typed endpoint is a client error, not a server crash."""
+ response = live.client.post(
+ "/news/api/subscribe",
+ json={"query": "AI news", "custom_endpoint": 123},
+ )
+
+ assert response.status_code == 400
+ live.api.create_subscription.assert_not_called()
+
+
+class TestUpdateSubscriptionRouteRejectsSSRF:
+ """PUT /news/api/subscriptions/<id> is the second write path."""
+
+ def test_metadata_endpoint_returns_400(self, live):
+ response = live.client.put(
+ f"/news/api/subscriptions/{A_UUID}",
+ json={"custom_endpoint": METADATA_URL},
+ )
+
+ assert response.status_code == 400, (
+ "PUT /news/api/subscriptions/<id> accepted a metadata URL -- an "
+ "existing subscription can be repointed at it"
+ )
+ live.api.update_subscription.assert_not_called()
+
+ def test_ollama_endpoint_is_not_rejected(self, live):
+ response = live.client.put(
+ f"/news/api/subscriptions/{A_UUID}",
+ json={"custom_endpoint": "http://localhost:11434/v1"},
+ )
+
+ assert response.status_code != 400
+ live.api.update_subscription.assert_called_once()
+
+
+class TestUpdateSubscriptionFolderRouteRejectsSSRF:
+ """PUT /news/api/subscription/subscriptions/<id> is the third write path.
+
+ It was added in the last commit of this PR and, unlike the other two
+ write paths, persists through a blind ``setattr`` loop straight to a DB
+ session rather than through the ``news.api`` module -- so it is stubbed
+ at ``get_user_db_session`` instead of the ``api`` mock the ``live``
+ fixture already sets up. Deleting this route's guard call would leave
+ every other test in this file green; that is exactly the failure mode
+ this PR exists to prevent, so the wiring has to be pinned here too.
+ """
+
+ @staticmethod
+ def _stub_subscription():
+ return SimpleNamespace(
+ id=A_UUID,
+ name="test",
+ status="active",
+ folder_id=None,
+ refresh_interval_minutes=60,
+ next_refresh=None,
+ last_refresh=None,
+ custom_endpoint=None,
+ updated_at=None,
+ )
+
+ def test_metadata_endpoint_returns_400(self, live):
+ with patch(
+ "local_deep_research.news.flask_api.get_user_db_session"
+ ) as mock_get_session:
+ response = live.client.put(
+ f"/news/api/subscription/subscriptions/{A_UUID}",
+ json={"custom_endpoint": METADATA_URL},
+ )
+
+ assert response.status_code == 400, (
+ "PUT /news/api/subscription/subscriptions/<id> accepted a "
+ f"metadata URL (HTTP {response.status_code}) through the "
+ "folder-update route's blind setattr loop"
+ )
+ mock_get_session.assert_not_called()
+
+ def test_ollama_endpoint_is_not_rejected(self, live):
+ sub = self._stub_subscription()
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = sub
+
+ with patch(
+ "local_deep_research.news.flask_api.get_user_db_session"
+ ) as mock_get_session:
+ mock_get_session.return_value.__enter__.return_value = mock_session
+ response = live.client.put(
+ f"/news/api/subscription/subscriptions/{A_UUID}",
+ json={"custom_endpoint": "http://localhost:11434/v1"},
+ )
+
+ assert response.status_code != 400
+ mock_get_session.assert_called_once()
+
+
+class TestFeedRouteValidatesSubscriptionId:
+ """GET /news/api/feed takes subscription_id from the query string."""
+
+ def test_non_uuid_returns_400(self, live):
+ response = live.client.get("/news/api/feed?subscription_id=not-a-uuid")
+
+ assert response.status_code == 400, (
+ "GET /news/api/feed accepted a non-UUID subscription_id "
+ f"(HTTP {response.status_code}) -- the value reaches the query "
+ "layer unvalidated"
+ )
+ live.api.get_news_feed.assert_not_called()
+
+ def test_like_wildcard_returns_400(self, live):
+ response = live.client.get("/news/api/feed?subscription_id=%25")
+
+ assert response.status_code == 400
+ live.api.get_news_feed.assert_not_called()
+
+ def test_uuid_is_accepted(self, live):
+ response = live.client.get(f"/news/api/feed?subscription_id={A_UUID}")
+
+ assert response.status_code == 200
+ assert (
+ live.api.get_news_feed.call_args.kwargs["subscription_id"] == A_UUID
+ )
+
+ def test_all_sentinel_is_accepted(self, live):
+ """``news/api.py`` documents "all" as "no subscription filter".
+
+ It is not a UUID, so the guard has to allow it explicitly or every
+ external client using the documented sentinel starts getting 400s.
+ """
+ response = live.client.get("/news/api/feed?subscription_id=all")
+
+ assert response.status_code == 200
+ assert (
+ live.api.get_news_feed.call_args.kwargs["subscription_id"] == "all"
+ )
+
+ def test_omitted_subscription_id_is_accepted(self, live):
+ response = live.client.get("/news/api/feed")
+
+ assert response.status_code == 200
+ assert (
+ live.api.get_news_feed.call_args.kwargs["subscription_id"] is None
+ )
+
+
+class TestHistoryRouteValidatesSubscriptionId:
+ """GET /news/api/subscriptions/<id>/history takes its id from the URL
+ path, but that id still reaches a LIKE rather than an equality filter.
+
+ ``api.get_subscription_history`` (news/api.py :530-542) interpolates it
+ into ``%"subscription_id": "<id>"%`` and runs it through
+ ``ResearchHistory.research_meta.like(..., escape="\\\\")``. The value is
+ ``escape_like``-wrapped, so this was never exploitable -- but it is the
+ same shape as the feed query parameter and gets the same guard. The
+ sibling blueprint (web/routes/news_routes.py :213) has always checked it.
+ """
+
+ def test_non_uuid_returns_400(self, live):
+ response = live.client.get("/news/api/subscriptions/not-a-uuid/history")
+
+ assert response.status_code == 400, (
+ "GET /news/api/subscriptions/<id>/history accepted a non-UUID "
+ f"path id (HTTP {response.status_code}) -- the value reaches a "
+ "LIKE pattern unvalidated"
+ )
+ live.api.get_subscription_history.assert_not_called()
+
+ def test_like_wildcard_returns_400(self, live):
+ response = live.client.get("/news/api/subscriptions/%25/history")
+
+ assert response.status_code == 400
+ live.api.get_subscription_history.assert_not_called()
+
+ def test_all_sentinel_is_not_a_history_target(self, live):
+ """``all`` is the feed's "no filter" sentinel, not a subscription.
+
+ The history route resolves one subscription, so it takes no sentinel
+ and the plain UUID check applies.
+ """
+ response = live.client.get("/news/api/subscriptions/all/history")
+
+ assert response.status_code == 400
+ live.api.get_subscription_history.assert_not_called()
+
+ def test_uuid_is_accepted(self, live):
+ response = live.client.get(f"/news/api/subscriptions/{A_UUID}/history")
+
+ assert response.status_code == 200
+ assert live.api.get_subscription_history.call_args.args[0] == A_UUID