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.

feat(security): validate LLM provider base_url against SSRF rules (#3929)

LearningCircuit4916dd5817ac
diff --git a/SECURITY.md b/SECURITY.md
index 4fac56657a..7612b17eab 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -175,6 +175,17 @@ Operators on IPv6-only deployments using DNS64+NAT64 (AWS / GKE / Azure IPv6-onl
URL rejection log lines route through `ssrf_validator.redact_url_for_log` to drop userinfo (RFC 3986 §3.2.1 allows credentials in the URL), path, and query — operators see `scheme://host:port` only. Operators with grep/regex tooling on the rejection log lines will see authority-only strings instead of full URLs.
+### LLM Provider URL Validation
+
+Operator-configured LLM endpoints (`llm.ollama.url`, `llm.lmstudio.url`, `llm.llamacpp.url`, `llm.openai_endpoint.url`) are validated against the same SSRF rules as outbound HTTP via `ssrf_validator.assert_base_url_safe`. Validation runs immediately after `normalize_url` and before the LangChain SDK constructor (`ChatOpenAI` / `ChatOllama`), so a misconfigured or hostile URL fails fast rather than silently routing every inference call at internal services.
+
+The guard uses `allow_localhost=True, allow_private_ips=True` because the legitimate destinations for these providers are localhost (Ollama, LM Studio, llama.cpp) and RFC1918 (Docker / private network deployments). The `ALWAYS_BLOCKED_METADATA_IPS` set still fires under those flags, so cloud-credential endpoints stay blocked regardless of the operator's settings.
+
+Caveats:
+- Settings-write access already implies arbitrary-URL exfil and RFC1918 reachability — the guard prevents only the cloud-credential-endpoint pivot, not exfil to public attacker-controlled hosts (the configured `Authorization: Bearer …` header would still go to the attacker if they swapped the URL).
+- DNS rebinding TOCTOU applies: the guard validates once at provider construction, but the SDK re-resolves the hostname on every inference call. Same accepted-risk rationale as elsewhere in the project — egress restriction at the firewall is the operator-side mitigation.
+- Providers with no operator-configurable URL (`Anthropic`, `OpenAI`, `OpenRouter`, `xAI`, `IONOS`) skip validation by gating on `cls.url_setting`. Their `default_base_url` is hardcoded to a public API endpoint; no SSRF surface to attack.
+
### Egress Policy Module
LDR includes an optional egress-policy subsystem (`security/egress/` — see its [`README.md`](src/local_deep_research/security/egress/README.md) for the full design, the scope table, and the map of every enforcement point) that lets operators constrain where research traffic, LLM calls, and embeddings may go. The module is an **in-process correctness guardrail, NOT a hard security boundary**. It defends against honest misconfiguration, prompt-injection-induced URL fetches, accidental egress, and the LangGraph silent-expansion class of bug. It does **NOT** defend against:
diff --git a/changelog.d/+llm-base-url-ssrf-validation.security.md b/changelog.d/+llm-base-url-ssrf-validation.security.md
new file mode 100644
index 0000000000..ed8ed141e1
--- /dev/null
+++ b/changelog.d/+llm-base-url-ssrf-validation.security.md
@@ -0,0 +1,12 @@
+Operator-configured LLM provider URLs (`llm.ollama.url`, `llm.lmstudio.url`,
+`llm.llamacpp.url`, `llm.openai_endpoint.url`) are now validated against the
+same SSRF rules as outbound HTTP before the LangChain SDK constructor runs.
+Closes an auth-gated SSRF gap where the SDK's internal `httpx` client would
+otherwise bypass the existing `safe_requests` guard.
+
+Follow-up review closed two more sites in the same vuln class: the
+OpenAI-compatible base class's model-listing (`list_models_for_api`, used by
+the custom-endpoint / LM Studio / llama.cpp providers) now validates
+`base_url` before constructing the OpenAI client and returns an empty list on
+a blocked URL, and `OpenAIProvider` now validates `llm.openai.api_base` before
+handing it to `ChatOpenAI`.
diff --git a/src/local_deep_research/llm/providers/implementations/ollama.py b/src/local_deep_research/llm/providers/implementations/ollama.py
index 5b04e7932f..ad56d408b3 100644
--- a/src/local_deep_research/llm/providers/implementations/ollama.py
+++ b/src/local_deep_research/llm/providers/implementations/ollama.py
@@ -7,6 +7,7 @@ from loguru import logger
from ....config.thread_settings import get_setting_from_snapshot
from ....utilities.url_utils import normalize_url
from ....security import safe_get
+from ....security.ssrf_validator import assert_base_url_safe
from ..base import BaseLLMProvider
@@ -63,6 +64,16 @@ class OllamaProvider(BaseLLMProvider):
return []
base_url = normalize_url(base_url)
+ try:
+ base_url = assert_base_url_safe(
+ base_url, setting_key="llm.ollama.url"
+ )
+ except ValueError:
+ logger.warning(
+ "Ollama base_url failed SSRF validation; "
+ "check llm.ollama.url config"
+ )
+ return []
# Get authentication headers
headers = cls._get_auth_headers(api_key=api_key)
@@ -123,6 +134,10 @@ class OllamaProvider(BaseLLMProvider):
"Ollama URL not configured. Please set llm.ollama.url in settings."
)
base_url = normalize_url(raw_base_url)
+ # SSRF guard — let ValueError propagate so the research-query
+ # caller surfaces a clear config error instead of silently
+ # routing inference traffic to a misconfigured target.
+ base_url = assert_base_url_safe(base_url, setting_key="llm.ollama.url")
logger.info(
f"Creating ChatOllama with model={model_name}, base_url={base_url}"
@@ -197,6 +212,19 @@ class OllamaProvider(BaseLLMProvider):
logger.debug("Ollama URL not configured")
return False
base_url = normalize_url(raw_base_url)
+ # Graceful UI degradation: if base_url is unsafe, return
+ # False instead of raising. Surface it as "Ollama unavailable"
+ # in the model-list UI rather than crashing the request.
+ try:
+ base_url = assert_base_url_safe(
+ base_url, setting_key="llm.ollama.url"
+ )
+ except ValueError:
+ logger.warning(
+ "Ollama base_url failed SSRF validation; "
+ "check llm.ollama.url config"
+ )
+ return False
logger.info(f"Checking Ollama availability at {base_url}/api/tags")
# Get authentication headers
diff --git a/src/local_deep_research/llm/providers/implementations/openai.py b/src/local_deep_research/llm/providers/implementations/openai.py
index 07e24fe846..34e3e79a63 100644
--- a/src/local_deep_research/llm/providers/implementations/openai.py
+++ b/src/local_deep_research/llm/providers/implementations/openai.py
@@ -8,6 +8,7 @@ from loguru import logger
# (`local_deep_research.config.thread_settings`) are picked up by the
# function-local import at call time. Module-level binding here would be
# unaffected by the source-module patch.
+from ....security.ssrf_validator import assert_base_url_safe
from ..openai_base import OpenAICompatibleProvider
@@ -76,6 +77,18 @@ class OpenAIProvider(OpenAICompatibleProvider):
settings_snapshot=settings_snapshot,
)
if api_base:
+ # SSRF guard for operator-configurable api_base. OpenAIProvider
+ # has url_setting = None and overrides create_llm without
+ # calling super, so the base-class guard never runs here.
+ # ChatOpenAI uses its own httpx transport that bypasses
+ # safe_requests, so an attacker who can edit llm.openai.api_base
+ # could route inference at internal/cloud-credential endpoints.
+ # Let ValueError propagate (fail-fast) — at inference
+ # construction we fail rather than silently route traffic to a
+ # metadata endpoint, matching ollama.create_llm.
+ api_base = assert_base_url_safe(
+ api_base, setting_key="llm.openai.api_base"
+ )
openai_params["openai_api_base"] = api_base
except NoSettingsContextError:
pass # Optional parameter
diff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.py
index 3dc6921d3b..04d8781cb9 100644
--- a/src/local_deep_research/llm/providers/openai_base.py
+++ b/src/local_deep_research/llm/providers/openai_base.py
@@ -9,6 +9,7 @@ from loguru import logger
# function-local imports at call time. A module-level binding here would
# be unaffected by patching the source module.
from ...security.log_sanitizer import redact_secrets
+from ...security.ssrf_validator import assert_base_url_safe
from ...utilities.url_utils import normalize_url
from .base import BaseLLMProvider
@@ -68,6 +69,16 @@ class OpenAICompatibleProvider(BaseLLMProvider):
base_url = kwargs.get("base_url", cls.default_base_url)
base_url = normalize_url(base_url) if base_url else cls.default_base_url
+ # SSRF guard for operator-configurable base_url. Skip when
+ # url_setting is None (providers like OpenAI/Anthropic with
+ # hardcoded default_base_url have no operator URL to attack).
+ # ALWAYS_BLOCKED_METADATA_IPS still fires under the permissive
+ # flags below, so cloud-credential endpoints stay blocked.
+ if cls.url_setting:
+ base_url = assert_base_url_safe(
+ base_url, setting_key=cls.url_setting
+ )
+
# Build parameters for OpenAI client
llm_params = {
"model": model_name,
@@ -169,6 +180,12 @@ class OpenAICompatibleProvider(BaseLLMProvider):
base_url = kwargs.get("base_url", cls.default_base_url)
base_url = normalize_url(base_url) if base_url else cls.default_base_url
+ # SSRF guard (same posture as create_llm above).
+ if cls.url_setting:
+ base_url = assert_base_url_safe(
+ base_url, setting_key=cls.url_setting
+ )
+
# Get API key from kwargs (caller is responsible for providing it).
# Defensive default uses the unified OPTIONAL_API_KEY_PLACEHOLDER so
# any future direct caller of _create_llm_instance without an
@@ -315,6 +332,26 @@ class OpenAICompatibleProvider(BaseLLMProvider):
if not base_url:
base_url = cls.default_base_url
+ # SSRF guard for operator-configurable base_url, symmetric with
+ # the create_llm guard above. The OpenAI SDK client uses its own
+ # httpx transport that bypasses safe_requests, so an attacker who
+ # can edit cls.url_setting could otherwise point model-listing at
+ # internal/cloud-credential endpoints. Skip when url_setting is
+ # None (providers with a hardcoded default_base_url have no
+ # operator URL to attack). On rejection, degrade gracefully and
+ # return [] — model-listing should not 500.
+ if base_url and cls.url_setting:
+ try:
+ base_url = assert_base_url_safe(
+ base_url, setting_key=cls.url_setting
+ )
+ except ValueError:
+ logger.warning(
+ f"{cls.provider_name} base_url failed SSRF "
+ f"validation; check {cls.url_setting} config"
+ )
+ return []
+
# Create OpenAI client (uses library defaults for timeout)
client = OpenAI(api_key=api_key, base_url=base_url)
diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.py
index 24dbcc353c..2f6ac04e09 100644
--- a/src/local_deep_research/security/__init__.py
+++ b/src/local_deep_research/security/__init__.py
@@ -23,7 +23,13 @@ from .notification_validator import (
)
from .safe_requests import safe_get, safe_post, SafeSession
from .security_headers import SecurityHeaders
-from .ssrf_validator import validate_url, get_safe_url, is_ip_blocked
+from .ssrf_validator import (
+ assert_base_url_safe,
+ get_safe_url,
+ is_ip_blocked,
+ redact_url_for_log,
+ validate_url,
+)
from .url_validator import URLValidator
from .account_lockout import AccountLockoutManager, get_account_lockout_manager
from .password_validator import PasswordValidator
@@ -85,6 +91,8 @@ __all__ = [
"validate_url",
"get_safe_url",
"is_ip_blocked",
+ "assert_base_url_safe",
+ "redact_url_for_log",
"get_safe_module_class",
"ModuleNotAllowedError",
"ALLOWED_MODULES",
diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.py
index 54ccfbd1ca..5889f15292 100644
--- a/src/local_deep_research/security/ssrf_validator.py
+++ b/src/local_deep_research/security/ssrf_validator.py
@@ -319,6 +319,39 @@ def validate_url(
return False
+def assert_base_url_safe(base_url: str, *, setting_key: str) -> str:
+ """Validate an LLM provider base_url. Raises ValueError on SSRF.
+
+ Args:
+ base_url: The URL to validate.
+ setting_key: The settings dot-path that produced this URL
+ (e.g. ``"llm.ollama.url"``). Embedded into the error message
+ so operators know which setting to fix. Pass ``cls.url_setting``
+ from the OpenAI-compat parent or ``"llm.ollama.url"`` from
+ the Ollama provider — NEVER ``cls.provider_name`` which is a
+ display string ("xAI Grok", "llama.cpp") not a settings key.
+
+ Uses ``allow_localhost=True, allow_private_ips=True`` because the
+ legitimate destinations for LLM SDKs are localhost (Ollama, LM Studio,
+ llama.cpp) and RFC1918 (Docker / private network deployments). The
+ ``ALWAYS_BLOCKED_METADATA_IPS`` set still fires under those flags and
+ prevents the auth-gated SSRF that would otherwise reach cloud-credential
+ endpoints (AWS IMDS / ECS, Azure, OCI, DigitalOcean, AlibabaCloud,
+ Tencent).
+
+ Caveat: this guard validates once at provider construction. The SDK
+ re-resolves the hostname on every inference call, so a hostile DNS
+ authority can rebind between guard and connect — same TOCTOU as
+ ``validate_url``. See SECURITY.md for the accepted-risk rationale.
+ """
+ if not validate_url(base_url, allow_localhost=True, allow_private_ips=True):
+ raise ValueError(
+ f"base_url failed SSRF validation: refusing to send "
+ f"inference traffic. Check {setting_key} config."
+ )
+ return base_url
+
+
def get_safe_url(
url: Optional[str], default: Optional[str] = None
) -> Optional[str]:
diff --git a/tests/llm/test_provider_base_url_ssrf.py b/tests/llm/test_provider_base_url_ssrf.py
new file mode 100644
index 0000000000..001fbe97f0
--- /dev/null
+++ b/tests/llm/test_provider_base_url_ssrf.py
@@ -0,0 +1,438 @@
+"""SSRF guard for operator-configured LLM provider base_url.
+
+Even though the SSRF validator (``ssrf_validator.validate_url``) gates
+outbound HTTP through ``safe_requests``, LangChain provider SDKs
+(``ChatOpenAI``, ``ChatOllama``) use their own internal ``httpx`` client
+that bypasses ``safe_requests`` entirely. An authenticated user with
+permission to edit ``llm.<provider>.url`` could otherwise route every
+inference call at internal services / cloud-credential endpoints.
+
+The fix gates ``base_url`` through ``assert_base_url_safe`` immediately
+after ``normalize_url`` and before the SDK constructor. These tests lock
+in:
+
+1. Every IP in ``ALWAYS_BLOCKED_METADATA_IPS`` raises ValueError.
+2. Legitimate localhost / RFC1918 destinations (Ollama / LM Studio /
+ llama.cpp on private networks) keep working.
+3. Validation runs BEFORE the SDK constructor (a future refactor that
+ moved it after would silently regress).
+4. Edge cases like empty / None base_url are rejected.
+"""
+
+from unittest.mock import MagicMock, Mock
+
+import pytest
+
+
+ "ip",
+ [
+ "169.254.169.254", # AWS IMDS / Azure / OCI / DigitalOcean
+ "169.254.170.2", # AWS ECS task metadata v3
+ "169.254.170.23", # AWS ECS task metadata v4
+ "169.254.0.23", # Tencent Cloud
+ "100.100.100.200", # AlibabaCloud
+ ],
+)
+def test_assert_base_url_safe_rejects_all_metadata_ips(ip):
+ """Every cloud-metadata IP in ALWAYS_BLOCKED_METADATA_IPS must
+ raise — this is the load-bearing security property."""
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ with pytest.raises(ValueError, match="failed SSRF validation"):
+ assert_base_url_safe(f"http://{ip}/", setting_key="llm.test.url")
+
+
+def test_assert_base_url_safe_accepts_localhost():
+ """Localhost is the typical Ollama / LM Studio / llama.cpp host."""
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ assert (
+ assert_base_url_safe(
+ "http://localhost:11434/", setting_key="llm.ollama.url"
+ )
+ == "http://localhost:11434/"
+ )
+
+
+def test_assert_base_url_safe_accepts_rfc1918():
+ """Docker / private-network deployments need RFC1918."""
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ assert (
+ assert_base_url_safe(
+ "http://192.168.1.10:11434/", setting_key="llm.ollama.url"
+ )
+ == "http://192.168.1.10:11434/"
+ )
+
+
+def test_assert_base_url_safe_rejects_empty_string():
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ with pytest.raises(ValueError, match="failed SSRF validation"):
+ assert_base_url_safe("", setting_key="llm.x.url")
+
+
+def test_assert_base_url_safe_rejects_none():
+ """isinstance check in validate_url means None returns False, which
+ means assert_base_url_safe raises rather than crashing on .strip()."""
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ with pytest.raises(ValueError, match="failed SSRF validation"):
+ assert_base_url_safe(None, setting_key="llm.x.url")
+
+
+def test_assert_base_url_safe_error_message_includes_setting_key():
+ """Operators see the error and need to know which setting to fix."""
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ with pytest.raises(ValueError, match=r"llm\.lmstudio\.url"):
+ assert_base_url_safe(
+ "http://169.254.169.254/", setting_key="llm.lmstudio.url"
+ )
+
+
+# ---------------------------------------------------------------------
+# Per-provider integration tests
+# ---------------------------------------------------------------------
+
+
+class TestOllamaBaseUrlSsrf:
+ """OllamaProvider gates base_url at three sites: list_models_for_api,
+ create_llm, is_available. Each behaves differently on rejection."""
+
+ def test_create_llm_rejects_aws_metadata(self):
+ """create_llm propagates ValueError so the research-query caller
+ sees a clear config error instead of silent SSRF."""
+ from local_deep_research.llm.providers.implementations.ollama import (
+ OllamaProvider,
+ )
+
+ snapshot = {"llm.ollama.url": "http://169.254.169.254/"}
+ with pytest.raises(ValueError, match="failed SSRF validation"):
+ OllamaProvider.create_llm(
+ model_name="llama3", settings_snapshot=snapshot
+ )
+
+ def test_create_llm_validate_runs_before_chatollama_constructor(
+ self, monkeypatch
+ ):
+ """A future refactor that moved the validate call below the SDK
+ constructor would silently regress (constructor is mocked in
+ tests). Make assert_base_url_safe raise; assert ChatOllama mock
+ has call_count == 0.
+
+ Patch the SYMBOL inside ollama.py — ``from langchain_ollama
+ import ChatOllama`` binds the name locally at import time;
+ patching ``langchain_ollama.ChatOllama`` would not affect that
+ local binding.
+ """
+ from local_deep_research.llm.providers.implementations.ollama import (
+ OllamaProvider,
+ )
+
+ mock_ctor = MagicMock(return_value=Mock())
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama",
+ mock_ctor,
+ )
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.implementations.ollama.assert_base_url_safe",
+ Mock(side_effect=ValueError("simulated SSRF rejection")),
+ )
+
+ with pytest.raises(ValueError):
+ OllamaProvider.create_llm(
+ model_name="llama3",
+ settings_snapshot={"llm.ollama.url": "http://example.com/"},
+ )
+ assert mock_ctor.call_count == 0, (
+ "ChatOllama was instantiated despite SSRF guard raising — "
+ "ordering regression"
+ )
+
+ def test_is_available_returns_false_on_bad_base_url(self):
+ """is_available swallows ValueError and returns False so the
+ model-list UI degrades gracefully."""
+ from local_deep_research.llm.providers.implementations.ollama import (
+ OllamaProvider,
+ )
+
+ snapshot = {"llm.ollama.url": "http://169.254.169.254/"}
+ assert OllamaProvider.is_available(settings_snapshot=snapshot) is False
+
+ def test_list_models_for_api_returns_empty_on_bad_base_url(self):
+ """list_models_for_api swallows ValueError and returns []."""
+ from local_deep_research.llm.providers.implementations.ollama import (
+ OllamaProvider,
+ )
+
+ result = OllamaProvider.list_models_for_api(
+ api_key="test",
+ base_url="http://169.254.169.254/",
+ )
+ assert result == []
+
+
+class TestOpenAICompatibleBaseUrlSsrf:
+ """OpenAICompatibleProvider gates base_url in create_llm and
+ _create_llm_instance, but only when ``cls.url_setting`` is set
+ (subclasses with hardcoded default_base_url skip validation)."""
+
+ def test_subclass_with_url_setting_rejects_metadata(self):
+ """A subclass with cls.url_setting set (e.g. CustomOpenAIEndpoint
+ which uses llm.openai_endpoint.url) must reject metadata IPs."""
+ from local_deep_research.llm.providers.openai_base import (
+ OpenAICompatibleProvider,
+ )
+
+ # Create a temporary subclass to exercise the cls.url_setting gate
+ class _TestProvider(OpenAICompatibleProvider):
+ provider_name = "TestProvider"
+ url_setting = "llm.test.url"
+ api_key_setting = None
+ default_base_url = "http://169.254.169.254/"
+
+ with pytest.raises(ValueError, match="failed SSRF validation"):
+ _TestProvider.create_llm(model_name="test")
+
+ def test_pure_provider_skips_validation(self, monkeypatch):
+ """Providers with ``url_setting = None`` (Anthropic, OpenAI,
+ OpenRouter, xAI, IONOS) must NOT invoke assert_base_url_safe.
+ Their default_base_url is hardcoded; there's no operator URL to
+ attack, so validation would be wasted work."""
+ from local_deep_research.llm.providers.openai_base import (
+ OpenAICompatibleProvider,
+ )
+
+ mock_guard = Mock(return_value="passthrough")
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.openai_base.assert_base_url_safe",
+ mock_guard,
+ )
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI",
+ Mock(),
+ )
+
+ class _PureProvider(OpenAICompatibleProvider):
+ provider_name = "PureProvider"
+ url_setting = None
+ api_key_setting = None
+ default_base_url = "https://api.example.com/v1"
+
+ _PureProvider.create_llm(model_name="test-model")
+ assert mock_guard.call_count == 0, (
+ "Pure-default provider invoked SSRF guard unexpectedly"
+ )
+
+ def test_validate_runs_before_chatopenai_constructor(self, monkeypatch):
+ """Same ordering invariant as the Ollama test, for the OpenAI
+ compat path. Patch the local binding of ChatOpenAI inside
+ openai_base.py."""
+ from local_deep_research.llm.providers.openai_base import (
+ OpenAICompatibleProvider,
+ )
+
+ mock_ctor = MagicMock(return_value=Mock())
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI",
+ mock_ctor,
+ )
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.openai_base.assert_base_url_safe",
+ Mock(side_effect=ValueError("simulated SSRF rejection")),
+ )
+
+ class _GuardedProvider(OpenAICompatibleProvider):
+ provider_name = "GuardedProvider"
+ url_setting = "llm.guarded.url"
+ api_key_setting = None
+ default_base_url = "https://api.example.com/v1"
+
+ with pytest.raises(ValueError):
+ _GuardedProvider.create_llm(model_name="test-model")
+ assert mock_ctor.call_count == 0, (
+ "ChatOpenAI was instantiated despite SSRF guard raising — "
+ "ordering regression"
+ )
+
+
+class TestOpenAICompatibleListModelsSsrf:
+ """OpenAICompatibleProvider.list_models_for_api (used by
+ CustomOpenAIEndpoint / LMStudio / LlamaCpp) gates base_url through the
+ SSRF guard when ``cls.url_setting`` is set. On rejection it must
+ degrade gracefully and return [] (model-listing should NOT 500)."""
+
+ def test_list_models_for_api_returns_empty_on_metadata_url(
+ self, monkeypatch, loguru_caplog
+ ):
+ """A subclass with cls.url_setting set must return [] (and log a
+ warning) when base_url is a blocked metadata endpoint, without ever
+ instantiating the OpenAI SDK client."""
+ from local_deep_research.llm.providers.openai_base import (
+ OpenAICompatibleProvider,
+ )
+
+ # If the guard failed to short-circuit, the SDK client would be
+ # constructed; make that an explicit failure so the test can't pass
+ # for the wrong reason.
+ import openai
+
+ def _boom(*args, **kwargs):
+ raise AssertionError(
+ "OpenAI client constructed despite blocked base_url"
+ )
+
+ monkeypatch.setattr(openai, "OpenAI", _boom)
+
+ class _TestProvider(OpenAICompatibleProvider):
+ provider_name = "TestListProvider"
+ url_setting = "llm.test.url"
+ api_key_setting = None
+ default_base_url = "https://api.example.com/v1"
+
+ @classmethod
+ def requires_auth_for_models(cls):
+ return False
+
+ with loguru_caplog.at_level("WARNING"):
+ result = _TestProvider.list_models_for_api(
+ api_key="test-key",
+ base_url="http://169.254.169.254/",
+ )
+
+ assert result == []
+ assert "SSRF validation" in loguru_caplog.text, (
+ "expected a warning naming SSRF validation"
+ )
+
+ def test_list_models_for_api_allows_localhost(self, monkeypatch):
+ """Legitimate local endpoints (LM Studio / llama.cpp on localhost)
+ must pass the guard and reach the SDK client."""
+ from local_deep_research.llm.providers.openai_base import (
+ OpenAICompatibleProvider,
+ )
+
+ captured = {}
+
+ class _FakeModels:
+ def list(self):
+ return Mock(data=[])
+
+ class _FakeClient:
+ def __init__(self, api_key=None, base_url=None):
+ captured["base_url"] = base_url
+ self.models = _FakeModels()
+
+ import openai
+
+ monkeypatch.setattr(openai, "OpenAI", _FakeClient)
+
+ class _TestProvider(OpenAICompatibleProvider):
+ provider_name = "TestListProvider"
+ url_setting = "llm.test.url"
+ api_key_setting = None
+ default_base_url = "https://api.example.com/v1"
+
+ @classmethod
+ def requires_auth_for_models(cls):
+ return False
+
+ result = _TestProvider.list_models_for_api(
+ api_key="test-key",
+ base_url="http://localhost:1234/v1",
+ )
+ assert result == []
+ assert captured["base_url"] == "http://localhost:1234/v1", (
+ "localhost base_url should reach the SDK client unchanged"
+ )
+
+
+class TestOpenAIProviderApiBaseSsrf:
+ """OpenAIProvider overrides create_llm without calling super and has
+ url_setting = None, so the base-class guard never runs. It gates
+ llm.openai.api_base directly and lets ValueError propagate (fail-fast,
+ matching ollama.create_llm)."""
+
+ def test_create_llm_rejects_metadata_api_base(self, monkeypatch):
+ """A blocked llm.openai.api_base must raise ValueError before the
+ ChatOpenAI constructor runs."""
+ from local_deep_research.llm.providers.implementations.openai import (
+ OpenAIProvider,
+ )
+
+ mock_ctor = MagicMock(return_value=Mock())
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI",
+ mock_ctor,
+ )
+
+ snapshot = {
+ "llm.openai.api_key": "sk-test-key",
+ "llm.openai.api_base": "http://169.254.169.254/v1",
+ }
+ with pytest.raises(ValueError, match="failed SSRF validation"):
+ OpenAIProvider.create_llm(
+ model_name="gpt-4o-mini", settings_snapshot=snapshot
+ )
+ assert mock_ctor.call_count == 0, (
+ "ChatOpenAI was instantiated despite SSRF guard raising"
+ )
+
+ def test_create_llm_allows_localhost_api_base(self, monkeypatch):
+ """A legitimate local api_base (proxy / gateway on localhost) must
+ pass the guard and reach the ChatOpenAI constructor."""
+ from local_deep_research.llm.providers.implementations.openai import (
+ OpenAIProvider,
+ )
+
+ captured = {}
+
+ def _fake_ctor(**kwargs):
+ captured.update(kwargs)
+ return Mock()
+
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI",
+ _fake_ctor,
+ )
+
+ snapshot = {
+ "llm.openai.api_key": "sk-test-key",
+ "llm.openai.api_base": "http://localhost:8080/v1",
+ }
+ OpenAIProvider.create_llm(
+ model_name="gpt-4o-mini", settings_snapshot=snapshot
+ )
+ assert captured["openai_api_base"] == "http://localhost:8080/v1", (
+ "localhost api_base should pass the guard and reach ChatOpenAI"
+ )
+
+
+class TestPublicApi:
+ """assert_base_url_safe and redact_url_for_log are exported from
+ security/__init__.py for downstream importers."""
+
+ def test_assert_base_url_safe_re_exported(self):
+ from local_deep_research.security import assert_base_url_safe
+
+ assert callable(assert_base_url_safe)
+
+ def test_redact_url_for_log_re_exported(self):
+ from local_deep_research.security import redact_url_for_log
+
+ assert callable(redact_url_for_log)
diff --git a/tests/llm_providers/implementations/test_llamacpp_provider.py b/tests/llm_providers/implementations/test_llamacpp_provider.py
index 64c616b752..834bc44855 100644
--- a/tests/llm_providers/implementations/test_llamacpp_provider.py
+++ b/tests/llm_providers/implementations/test_llamacpp_provider.py
@@ -107,12 +107,18 @@ class TestLlamaCppCreateLLM:
assert "8080" in call_kwargs["base_url"]
def test_create_llm_uses_custom_url(self):
- """Uses custom URL from settings."""
+ """Uses custom URL from settings.
+
+ Uses ``localhost`` (legitimate Llama.cpp host) rather than the
+ placeholder ``custom`` so the SSRF guard added in PR-B doesn't
+ trip on DNS resolution. The test is checking propagation of a
+ custom URL into ChatOpenAI, not SSRF semantics.
+ """
with patch(
"local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = _make_setting_side_effect(
- "http://custom:5000/v1"
+ "http://localhost:5000/v1"
)
with patch(
@@ -121,7 +127,7 @@ class TestLlamaCppCreateLLM:
LlamaCppProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
- assert "custom" in call_kwargs["base_url"]
+ assert "localhost" in call_kwargs["base_url"]
assert "5000" in call_kwargs["base_url"]
def test_create_llm_placeholder_api_key_when_unset(self):
diff --git a/tests/llm_providers/implementations/test_lmstudio_provider.py b/tests/llm_providers/implementations/test_lmstudio_provider.py
index bf7f726d8c..6c1d409e1e 100644
--- a/tests/llm_providers/implementations/test_lmstudio_provider.py
+++ b/tests/llm_providers/implementations/test_lmstudio_provider.py
@@ -107,12 +107,18 @@ class TestLMStudioCreateLLM:
assert "1234" in call_kwargs["base_url"]
def test_create_llm_uses_custom_url(self):
- """Uses custom URL from settings."""
+ """Uses custom URL from settings.
+
+ Uses ``localhost`` (legitimate LM Studio host) rather than the
+ placeholder ``custom`` so the SSRF guard added in PR-B doesn't
+ trip on DNS resolution. The test is checking propagation of a
+ custom URL into ChatOpenAI, not SSRF semantics.
+ """
with patch(
"local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = _make_setting_side_effect(
- "http://custom:5000/v1"
+ "http://localhost:5000/v1"
)
with patch(
@@ -121,7 +127,7 @@ class TestLMStudioCreateLLM:
LMStudioProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
- assert "custom" in call_kwargs["base_url"]
+ assert "localhost" in call_kwargs["base_url"]
assert "5000" in call_kwargs["base_url"]
def test_create_llm_uses_placeholder_api_key(self):
diff --git a/tests/llm_providers/implementations/test_openai_provider.py b/tests/llm_providers/implementations/test_openai_provider.py
index 9030317f9c..56a99fa768 100644
--- a/tests/llm_providers/implementations/test_openai_provider.py
+++ b/tests/llm_providers/implementations/test_openai_provider.py
@@ -295,21 +295,31 @@ class TestOpenAICreateLLM:
}
return settings_map.get(key, default)
- with patch(
- "local_deep_research.config.thread_settings.get_setting_from_snapshot"
- ) as mock_get_setting:
- mock_get_setting.side_effect = mock_get_setting_side_effect
-
- with patch(
+ # Patch the SSRF guard to a passthrough so this config-passthrough
+ # test does not depend on live DNS resolution of the placeholder host
+ # (matches tests/test_api_key_configuration.py convention). The guard
+ # is imported at module level into the openai implementation module, so
+ # patch it there.
+ with (
+ patch(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
+ side_effect=mock_get_setting_side_effect,
+ ),
+ patch(
+ "local_deep_research.llm.providers.implementations.openai.assert_base_url_safe",
+ side_effect=lambda url, **_kwargs: url,
+ ),
+ patch(
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
- ) as mock_chat:
- OpenAIProvider.create_llm(model_name="test-model")
-
- call_kwargs = mock_chat.call_args[1]
- assert (
- call_kwargs["openai_api_base"]
- == "https://custom-openai-proxy.com/v1"
- )
+ ) as mock_chat,
+ ):
+ OpenAIProvider.create_llm(model_name="test-model")
+
+ call_kwargs = mock_chat.call_args[1]
+ assert (
+ call_kwargs["openai_api_base"]
+ == "https://custom-openai-proxy.com/v1"
+ )
def test_create_llm_passes_organization_when_set(self):
"""Passes OpenAI organization when configured."""
diff --git a/tests/test_api_key_configuration.py b/tests/test_api_key_configuration.py
index efa1b09fdf..abd43a5691 100644
--- a/tests/test_api_key_configuration.py
+++ b/tests/test_api_key_configuration.py
@@ -194,9 +194,18 @@ class TestAPIKeyConfiguration:
self, settings_snapshot_with_openai_endpoint
):
"""Test that OpenAI endpoint (OpenRouter) API key can be configured and used."""
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_openai:
+ # Patch the openai_base SSRF guard to a passthrough so this config
+ # test does not depend on live DNS resolution of the endpoint host
+ # (matches tests/llm/test_provider_base_url_ssrf.py convention).
+ with (
+ patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_openai,
+ patch(
+ "local_deep_research.llm.providers.openai_base.assert_base_url_safe",
+ side_effect=lambda url, **_kwargs: url,
+ ),
+ ):
# Create a mock LLM instance
mock_llm_instance = _llm_mock()
mock_openai.return_value = mock_llm_instance
@@ -266,9 +275,17 @@ class TestAPIKeyConfiguration:
)
# Test OpenAI Endpoint
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_openai_endpoint:
+ # Patch the openai_base SSRF guard to a passthrough so this config
+ # test does not depend on live DNS resolution of the endpoint host.
+ with (
+ patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_openai_endpoint,
+ patch(
+ "local_deep_research.llm.providers.openai_base.assert_base_url_safe",
+ side_effect=lambda url, **_kwargs: url,
+ ),
+ ):
mock_openai_endpoint.return_value = _llm_mock()
get_llm(settings_snapshot=settings_snapshot_with_openai_endpoint)
assert mock_openai_endpoint.called
@@ -287,9 +304,17 @@ class TestAPIKeyConfiguration:
"""Test that research can use LLM with configured API key."""
from local_deep_research.api.research_functions import quick_summary
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_openai:
+ # Patch the openai_base SSRF guard to a passthrough so this config
+ # test does not depend on live DNS resolution of the endpoint host.
+ with (
+ patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_openai,
+ patch(
+ "local_deep_research.llm.providers.openai_base.assert_base_url_safe",
+ side_effect=lambda url, **_kwargs: url,
+ ),
+ ):
# Setup mock LLM
mock_llm_instance = _llm_mock()
mock_response = Mock()
@@ -476,9 +501,23 @@ class TestLLMIntegration:
}
)
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_openai:
+ # This test verifies config passthrough (the configured URL/api_key
+ # reach the ChatOpenAI constructor), not SSRF enforcement. The
+ # ``custom-llm-provider.com`` placeholder host does not resolve, so
+ # the openai_base SSRF guard (assert_base_url_safe) would fail-closed
+ # on its live DNS lookup. Patch the guard to a passthrough — the same
+ # convention as tests/llm/test_provider_base_url_ssrf.py — so the
+ # passthrough assertions stay deterministic and offline. SSRF
+ # enforcement itself is covered by test_provider_base_url_ssrf.py.
+ with (
+ patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_openai,
+ patch(
+ "local_deep_research.llm.providers.openai_base.assert_base_url_safe",
+ side_effect=lambda url, **_kwargs: url,
+ ),
+ ):
mock_openai.return_value = _llm_mock()
get_llm(settings_snapshot=settings_snapshot)