~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
security: validate custom_endpoint URL at route layer (allow local LLMs) (#4731)
LearningCircuit85fa4c5c73a4
diff --git a/changelog.d/+validate-custom-endpoint-ssrf.security.md b/changelog.d/+validate-custom-endpoint-ssrf.security.mdnew file mode 100644index 0000000000..a5bdd76321--- /dev/null+++ b/changelog.d/+validate-custom-endpoint-ssrf.security.md@@ -0,0 +1 @@+The ``custom_endpoint`` URL supplied to ``/api/start_research``, ``/api/news/subscriptions`` (POST and PUT/PATCH), and ``/api/followup/start`` is now validated for SSRF at the request boundary (rejecting cloud-metadata / link-local targets, always blocked by ``ssrf_validator``) before any research is queued. This is fail-fast defense-in-depth — the OpenAI-compatible provider re-validates the same URL via ``assert_base_url_safe`` before the LangChain client is built — but the route-layer check rejects early, before a DB row is written or a thread is spawned, and keeps the endpoint out of the logs. The endpoint is normalized exactly as the provider normalizes it, so scheme-less local endpoints (``localhost:11434``, ``192.168.1.10:8000``) are accepted; private IPs and localhost still pass, so local LLM providers (Ollama, LM Studio, vLLM) are unaffected.diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.pyindex 73004d6390..38f0bbeae8 100644--- a/src/local_deep_research/followup_research/routes.py+++ b/src/local_deep_research/followup_research/routes.py@@ -10,6 +10,7 @@ from ..exceptions import DuplicateResearchError, SystemAtCapacityErrorfrom ..llm.providers.base import normalize_providerfrom .service import FollowUpResearchServicefrom .models import FollowUpRequest+from ..utilities.url_utils import is_safe_custom_llm_endpointfrom ..security.decorators import require_json_bodyfrom ..web.auth.decorators import login_requiredfrom ..web.auth.password_utils import resolve_user_password@@ -222,6 +223,27 @@ def start_followup():}), 400+ # SSRF pre-flight on the LLM endpoint: reject metadata / link-local+ # targets at the request boundary, before any DB row is written.+ # This is fail-fast defense-in-depth — the OpenAI-compatible provider's+ # assert_base_url_safe re-validates the same URL before the client is+ # built. Private IPs and localhost pass because local LLMs+ # (Ollama / LM Studio / vLLM) live there, including scheme-less+ # endpoints (the helper normalizes exactly as the provider does).+ custom_endpoint = settings_snapshot.get(+ "llm.openai_endpoint.url", {}+ ).get("value")+ if not is_safe_custom_llm_endpoint(custom_endpoint):+ return (+ jsonify(+ {+ "success": False,+ "error": "Invalid custom endpoint URL",+ }+ ),+ 400,+ )+# Generate new research IDresearch_id = str(uuid.uuid4())@@ -272,9 +294,6 @@ def start_followup():search_engine = settings_snapshot.get("search.tool", {}).get("value", "searxng")- custom_endpoint = settings_snapshot.get(- "llm.openai_endpoint.url", {}- ).get("value")# Spawn the research thread. If the spawn fails, the# ResearchHistory row committed above would otherwise bediff --git a/src/local_deep_research/utilities/url_utils.py b/src/local_deep_research/utilities/url_utils.pyindex b4bed91f7b..feedd02aab 100644--- a/src/local_deep_research/utilities/url_utils.py+++ b/src/local_deep_research/utilities/url_utils.py@@ -1,12 +1,21 @@"""URL utility functions for the local deep research application."""from functools import lru_cache+from typing import Optionalfrom urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit+from loguru import logger++from ..security import redact_url_for_log, validate_urlfrom ..security.network_utils import is_private_ip# Re-export for backwards compatibility-__all__ = ["normalize_url", "is_private_ip", "canonical_url_key"]+__all__ = [+ "normalize_url",+ "is_private_ip",+ "canonical_url_key",+ "is_safe_custom_llm_endpoint",+]# Tracking query parameter keys (matched lowercased)._TRACKING_PARAMS = frozenset(@@ -163,3 +172,36 @@ def canonical_url_key(url: str) -> str:path = path.rstrip("/")return urlunsplit((scheme, netloc, path, query_str, ""))+++def is_safe_custom_llm_endpoint(custom_endpoint: Optional[str]) -> bool:+ """SSRF guard for a user-supplied custom LLM endpoint, applied at the+ request boundary as fail-fast defense-in-depth.++ The endpoint is normalized exactly as the OpenAI-compatible provider+ normalizes it (:func:`normalize_url`), so scheme-less local endpoints+ such as ``localhost:11434`` or ``192.168.1.10:8000`` are handled the+ same way the provider handles them, then validated with+ :func:`validate_url` allowing private IPs / localhost. That accepts+ local LLM backends (Ollama / LM Studio / vLLM) while still blocking+ cloud-metadata and link-local targets. An empty / unset endpoint is+ safe (there is nothing to send to). On rejection a redacted warning+ is logged (the raw URL may carry credentials).++ This is not the sole protection: the OpenAI-compatible provider's+ ``assert_base_url_safe`` re-validates the same URL before the+ 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.+ """+ endpoint = (custom_endpoint or "").strip()+ if not endpoint:+ return True+ candidate = normalize_url(endpoint)+ if validate_url(candidate, allow_private_ips=True):+ return True+ logger.warning(+ "SSRF protection: rejected custom_endpoint URL: {}",+ redact_url_for_log(candidate),+ )+ return Falsediff --git a/src/local_deep_research/web/routes/news_routes.py b/src/local_deep_research/web/routes/news_routes.pyindex e5e6befc94..2877073c05 100644--- a/src/local_deep_research/web/routes/news_routes.py+++ b/src/local_deep_research/web/routes/news_routes.py@@ -10,11 +10,32 @@ from loguru import loggerfrom ...news import api as news_apifrom ...news.exceptions import NewsAPIException+from ...utilities.url_utils import is_safe_custom_llm_endpointfrom ...security.decorators import require_json_bodyfrom ..auth.decorators import login_requiredfrom ...security.rate_limiter import limiter+def _reject_custom_endpoint(custom_endpoint):+ """Return a Flask 400 response if ``custom_endpoint`` fails SSRF+ validation, else None.++ Rejects cloud-metadata / link-local targets at the request boundary as+ fail-fast defense-in-depth (the OpenAI-compatible provider re-validates+ the same URL via assert_base_url_safe before the client is built).+ Private IPs and localhost are allowed because local LLMs live there;+ scheme-less endpoints are normalized exactly as the provider does.+ """+ 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:"""Return True if ``value`` parses as a UUID, False otherwise.@@ -128,6 +149,11 @@ def create_subscription():"""Create a new subscription."""user_id = session["username"]data = request.get_json()++ bad_endpoint = _reject_custom_endpoint(data.get("custom_endpoint"))+ if bad_endpoint is not None:+ return bad_endpoint+result = news_api.create_subscription(user_id=user_id,query=data.get("query"),@@ -165,6 +191,9 @@ def get_subscription(subscription_id):def update_subscription(subscription_id):"""Update an existing subscription."""data = request.get_json()+ bad_endpoint = _reject_custom_endpoint(data.get("custom_endpoint"))+ if bad_endpoint is not None:+ return bad_endpointresult = news_api.update_subscription(subscription_id, data)return jsonify(result)diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 03d5bf723d..95771c047f 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -29,6 +29,7 @@ from ...security import (sanitize_filename,strip_settings_snapshot,)+from ...utilities.url_utils import is_safe_custom_llm_endpointfrom ...security.rate_limiter import (upload_rate_limit_ip,upload_rate_limit_user,@@ -539,6 +540,21 @@ def start_research():400,)+ # SSRF pre-flight on the user-supplied LLM endpoint: reject metadata /+ # link-local targets at the request boundary, before any research thread+ # is spawned. This is fail-fast defense-in-depth — the OpenAI-compatible+ # provider's assert_base_url_safe re-validates the same URL before the+ # client is built. Private IPs / localhost are permitted so local LLMs+ # (vLLM, Ollama, LM Studio) work, including scheme-less endpoints+ # (the helper normalizes exactly as the provider does).+ if not is_safe_custom_llm_endpoint(custom_endpoint):+ return (+ jsonify(+ {"status": "error", "message": "Invalid custom endpoint URL"}+ ),+ 400,+ )+if not model:logger.error(f"No model specified or configured. Provider: {model_provider}"diff --git a/tests/followup_research/test_routes_coverage.py b/tests/followup_research/test_routes_coverage.pyindex e8b97fbc59..72d313a89b 100644--- a/tests/followup_research/test_routes_coverage.py+++ b/tests/followup_research/test_routes_coverage.py@@ -436,6 +436,153 @@ class TestStartFollowupModelRequired:mock_run.assert_not_called()+class TestStartFollowupCustomEndpointSSRF:+ """SSRF pre-flight on llm.openai_endpoint.url.++ The endpoint URL is later handed to the OpenAI client (httpx) with no+ SafeSession wrapping, so the route layer is the only place to reject+ cloud-metadata / link-local targets. Like the empty-model guard above,+ the check fires BEFORE any ResearchHistory row is written so a rejected+ request leaves no orphan IN_PROGRESS row.+ """++ _AWS_METADATA = (+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/"+ )++ def _snapshot_with_endpoint(self, url):+ snapshot = _fake_settings_snapshot()+ snapshot["llm.openai_endpoint.url"] = {"value": url}+ return snapshot++ def test_metadata_endpoint_rejected_before_db_write(self, app):+ """Cloud metadata URLs are blocked before ResearchHistory is created."""+ mock_service = Mock()+ mock_service.perform_followup.return_value = {+ "query": "follow-up question",+ "max_iterations": 2,+ "questions_per_iteration": 4,+ "delegate_strategy": "source-based",+ "research_context": {"summary": "context"},+ "parent_research_id": "parent-1",+ }+ mock_sm = Mock()+ mock_sm.get_all_settings.return_value = self._snapshot_with_endpoint(+ self._AWS_METADATA+ )++ with (+ patch(AUTH_DB_MANAGER, _mock_auth()),+ patch(SETTINGS_MANAGER, return_value=mock_sm),+ _mock_db_session_ctx(),+ patch(+ f"{MODULE}.FollowUpResearchService", return_value=mock_service+ ),+ patch(START_RESEARCH) as mock_start,+ patch(RUN_RESEARCH) as mock_run,+ patch(RESEARCH_HISTORY) as mock_history,+ patch(SESSION_PWD_STORE) as mock_pwd_store,+ ):+ mock_pwd_store.retrieve.return_value = "secret-password"+ resp = _authed_post(+ app,+ "/api/followup/start",+ {"parent_research_id": "parent-1", "question": "details?"},+ extra_session={"session_id": "sess-123"},+ )++ assert resp.status_code == 400+ data = resp.get_json()+ assert data["success"] is False+ assert "endpoint" in data["error"].lower()+ mock_history.assert_not_called()+ mock_start.assert_not_called()+ mock_run.assert_not_called()++ def test_garbage_url_rejected_before_db_write(self, app):+ """Malformed URLs are rejected before ResearchHistory is created."""+ mock_service = Mock()+ mock_service.perform_followup.return_value = {+ "query": "q",+ "max_iterations": 1,+ "questions_per_iteration": 1,+ "delegate_strategy": "source-based",+ "research_context": {},+ "parent_research_id": "parent-1",+ }+ mock_sm = Mock()+ mock_sm.get_all_settings.return_value = self._snapshot_with_endpoint(+ "not-a-url"+ )++ with (+ patch(AUTH_DB_MANAGER, _mock_auth()),+ patch(SETTINGS_MANAGER, return_value=mock_sm),+ _mock_db_session_ctx(),+ patch(+ f"{MODULE}.FollowUpResearchService", return_value=mock_service+ ),+ patch(START_RESEARCH) as mock_start,+ patch(RUN_RESEARCH),+ patch(RESEARCH_HISTORY) as mock_history,+ patch(SESSION_PWD_STORE) as mock_pwd_store,+ ):+ mock_pwd_store.retrieve.return_value = "secret-password"+ resp = _authed_post(+ app,+ "/api/followup/start",+ {"parent_research_id": "parent-1", "question": "details?"},+ extra_session={"session_id": "sess-123"},+ )++ assert resp.status_code == 400+ mock_history.assert_not_called()+ mock_start.assert_not_called()++ def test_localhost_endpoint_accepted(self, app):+ """Local LLM endpoints on localhost pass validation and reach the spawn."""+ mock_service = Mock()+ mock_service.perform_followup.return_value = {+ "query": "q",+ "max_iterations": 1,+ "questions_per_iteration": 1,+ "delegate_strategy": "source-based",+ "research_context": {},+ "parent_research_id": "parent-1",+ }+ mock_sm = Mock()+ mock_sm.get_all_settings.return_value = self._snapshot_with_endpoint(+ "http://localhost:11434/v1"+ )++ with (+ patch(AUTH_DB_MANAGER, _mock_auth()),+ patch(SETTINGS_MANAGER, return_value=mock_sm),+ _mock_db_session_ctx(),+ patch(+ f"{MODULE}.FollowUpResearchService", return_value=mock_service+ ),+ patch(START_RESEARCH) as mock_start,+ patch(RUN_RESEARCH),+ patch(RESEARCH_HISTORY),+ patch(+ "uuid.uuid4",+ return_value=Mock(__str__=lambda s: "new-research-id"),+ ),+ patch(SESSION_PWD_STORE) as mock_pwd_store,+ ):+ mock_pwd_store.retrieve.return_value = "secret-password"+ resp = _authed_post(+ app,+ "/api/followup/start",+ {"parent_research_id": "parent-1", "question": "details?"},+ extra_session={"session_id": "sess-123"},+ )++ assert resp.status_code == 200+ mock_start.assert_called_once()++# ---------------------------------------------------------------------------# start_followup: password fallback to g.user_password (lines 251-253)# ---------------------------------------------------------------------------diff --git a/tests/web/routes/test_news_routes.py b/tests/web/routes/test_news_routes.pyindex ab51942428..dd668ec540 100644--- a/tests/web/routes/test_news_routes.py+++ b/tests/web/routes/test_news_routes.py@@ -216,6 +216,121 @@ class TestUpdateSubscription:assert response.status_code == 200+class TestCustomEndpointSSRF:+ """create_subscription and update_subscription must reject custom_endpoint+ URLs that target cloud metadata endpoints or otherwise fail SSRF validation.+ This route-layer check rejects early (before any work is queued) as+ fail-fast defense-in-depth; the OpenAI-compatible provider re-validates the+ same URL via assert_base_url_safe before the client is built.+ """++ _AWS_METADATA = (+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/"+ )++ def test_create_rejects_metadata_endpoint(self, authenticated_client):+ """Cloud metadata endpoints are always blocked."""+ with patch(+ "local_deep_research.web.routes.news_routes.news_api.create_subscription"+ ) as mock_create:+ response = authenticated_client.post(+ "/api/news/subscriptions",+ json={"query": "q", "custom_endpoint": self._AWS_METADATA},+ content_type="application/json",+ )+ assert response.status_code == 400+ mock_create.assert_not_called()++ def test_create_rejects_garbage_url(self, authenticated_client):+ """Malformed URLs are rejected before reaching news_api."""+ with patch(+ "local_deep_research.web.routes.news_routes.news_api.create_subscription"+ ) as mock_create:+ response = authenticated_client.post(+ "/api/news/subscriptions",+ json={"query": "q", "custom_endpoint": "not-a-url"},+ content_type="application/json",+ )+ assert response.status_code == 400+ mock_create.assert_not_called()++ def test_create_accepts_localhost_endpoint(self, authenticated_client):+ """Local LLM endpoints on localhost must pass — local providers+ like Ollama / LM Studio / vLLM live there."""+ with patch(+ "local_deep_research.web.routes.news_routes.news_api.create_subscription"+ ) as mock_create:+ mock_create.return_value = {"id": "sub-1"}+ response = authenticated_client.post(+ "/api/news/subscriptions",+ json={+ "query": "q",+ "custom_endpoint": "http://localhost:11434/v1",+ },+ content_type="application/json",+ )+ assert response.status_code == 201+ mock_create.assert_called_once()++ def test_update_rejects_metadata_endpoint(self, authenticated_client):+ """update_subscription has the same SSRF guard."""+ with patch(+ "local_deep_research.web.routes.news_routes.news_api.update_subscription"+ ) as mock_update:+ response = authenticated_client.put(+ "/api/news/subscriptions/sub-1",+ json={"custom_endpoint": self._AWS_METADATA},+ content_type="application/json",+ )+ assert response.status_code == 400+ mock_update.assert_not_called()++ def test_create_accepts_schemeless_local_endpoint(+ self, authenticated_client+ ):+ """Scheme-less local endpoints (e.g. ``localhost:11434``) must pass.++ The provider normalizes the URL before use (adds ``http://``), so the+ route guard must normalize too — otherwise the exact local-LLM users+ the guard is meant to allow get a spurious 400. Regression test for+ the validate-the-raw-value bug.+ """+ with patch(+ "local_deep_research.web.routes.news_routes.news_api.create_subscription"+ ) as mock_create:+ mock_create.return_value = {"id": "sub-1"}+ response = authenticated_client.post(+ "/api/news/subscriptions",+ json={"query": "q", "custom_endpoint": "localhost:11434"},+ content_type="application/json",+ )+ assert response.status_code == 201+ mock_create.assert_called_once()++ def test_update_accepts_public_endpoint(self, authenticated_client):+ """Public endpoints pass validation.++ validate_url is patched so the assertion never depends on real DNS+ resolution of the public host (avoids offline-runner flake)."""+ with (+ patch(+ "local_deep_research.web.routes.news_routes.news_api.update_subscription"+ ) as mock_update,+ patch(+ "local_deep_research.utilities.url_utils.validate_url",+ return_value=True,+ ),+ ):+ mock_update.return_value = {"id": "sub-1"}+ response = authenticated_client.put(+ "/api/news/subscriptions/sub-1",+ json={"custom_endpoint": "https://api.openai.com/v1"},+ content_type="application/json",+ )+ assert response.status_code == 200+ mock_update.assert_called_once()++class TestDeleteSubscription:"""Tests for delete_subscription endpoint."""diff --git a/tests/web/routes/test_research_routes_start_research_coverage.py b/tests/web/routes/test_research_routes_start_research_coverage.pyindex bd29fe86ec..d2095e9374 100644--- a/tests/web/routes/test_research_routes_start_research_coverage.py+++ b/tests/web/routes/test_research_routes_start_research_coverage.py@@ -343,6 +343,108 @@ class TestStartResearchOpenAINoEndpoint:assert "endpoint" in data["message"].lower()+class TestStartResearchCustomEndpointSSRF:+ """The custom_endpoint URL is later handed to the OpenAI client (httpx)+ with no SafeSession wrapping, so the route layer is the only place to+ reject cloud-metadata / link-local targets before the request goes out.+ Private IPs and localhost pass because local LLMs live there.+ """++ _AWS_METADATA = (+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/"+ )++ def test_metadata_endpoint_rejected(self, client):+ ms = _mock_db_session()+ sm = _make_settings_manager(model="gpt-4")++ with (+ patch(_GET_USER_DB, side_effect=_ctx_factory(ms)),+ patch(_SM_MANAGER, return_value=sm),+ patch(_SM_SETTINGS, return_value=sm),+ patch(f"{MODULE}.start_research_process") as mock_spawn,+ ):+ resp = client.post(+ "/api/start_research",+ json={+ "query": "anything",+ "model": "gpt-4",+ "custom_endpoint": self._AWS_METADATA,+ },+ content_type="application/json",+ )++ assert resp.status_code == 400+ data = resp.get_json()+ assert data["status"] == "error"+ mock_spawn.assert_not_called()++ def test_garbage_url_rejected(self, client):+ ms = _mock_db_session()+ sm = _make_settings_manager(model="gpt-4")++ with (+ patch(_GET_USER_DB, side_effect=_ctx_factory(ms)),+ patch(_SM_MANAGER, return_value=sm),+ patch(_SM_SETTINGS, return_value=sm),+ patch(f"{MODULE}.start_research_process") as mock_spawn,+ ):+ resp = client.post(+ "/api/start_research",+ json={+ "query": "anything",+ "model": "gpt-4",+ "custom_endpoint": "not-a-url",+ },+ content_type="application/json",+ )++ assert resp.status_code == 400+ mock_spawn.assert_not_called()++ def test_localhost_endpoint_accepted(self, client, app):+ # Local LLM providers (Ollama / LM Studio / vLLM) live on localhost;+ # validation must not reject them. Mirrors the happy-path setup in+ # TestStartResearchSettingsFromDb so we exercise the full path past+ # the SSRF check, not just the validation itself.+ ms = _mock_db_session()+ _configure_ms_for_active(ms, active_count=0, max_pos=0)+ sm = _make_settings_manager(model="gpt-4")+ fake_thread = MagicMock(spec=threading.Thread)+ fake_thread.ident = 99++ @app.before_request+ def _inject_g():+ g.db_session = ms++ with (+ patch(_GET_USER_DB, side_effect=_ctx_factory(ms)),+ patch(_SM_MANAGER, return_value=sm),+ patch(_SM_SETTINGS, return_value=sm),+ patch(f"{MODULE}.start_research_process", return_value=fake_thread),+ patch(_SAVE_STRATEGY),+ patch(f"{MODULE}.log_settings"),+ patch(_SESSION_PW_STORE) as mock_sps,+ patch(f"{MODULE}.ResearchHistory"),+ patch(f"{MODULE}.UserActiveResearch"),+ ):+ mock_sps.get_session_password.return_value = "pw"++ resp = client.post(+ "/api/start_research",+ json={+ "query": "anything",+ "model": "gpt-4",+ "custom_endpoint": "http://localhost:11434/v1",+ },+ content_type="application/json",+ )++ assert resp.status_code == 200+ data = resp.get_json()+ assert data["status"] == "success"++class TestStartResearchShouldQueue:"""active_count >= max_concurrent -> research gets queued."""