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): stop LLM model discovery from following redirects (#7767)

LearningCircuit73a552027955
diff --git a/SECURITY.md b/SECURITY.md
index ab093d9933..3e9c80f0e3 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -242,7 +242,7 @@ 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.
-- **Redirects and embeddings endpoints**: the configured embedding endpoints (`embeddings.openai.base_url`, `embeddings.ollama.url`) get the same pre-flight `assert_base_url_safe` check. The OpenAI embeddings provider builds its own `httpx2` clients with `follow_redirects=False` for a custom `base_url`, both for embedding calls and for its model-discovery call. For embedding calls, a configured proxy (`openai_proxy` argument, else `OPENAI_PROXY`) is routed through those clients instead of langchain's `openai_proxy` wiring, so redirects are refused with or without a proxy. The model-discovery client does not use `openai_proxy`/`OPENAI_PROXY`; it connects directly, or through the standard `HTTP(S)_PROXY` environment variables that the `httpx2` client honours by default (`trust_env`). The pre-flight check resolves the hostname with the local resolver and fails closed if it cannot (the error then says it could not resolve the host rather than that the host is blocked), so a custom embeddings `base_url` must resolve locally even when a proxy is configured. Under a proxy the check is advisory: the proxy does its own DNS resolution and connects to whatever address it gets, which need not be the address validated locally. The Ollama embeddings provider and the Ollama chat provider (`llm.ollama.url`) pass `follow_redirects=False` to `ollama.Client`, whose default is to follow. The other chat providers (`ChatOpenAI`- and `ChatAnthropic`-based, including `llm.lmstudio.url`, `llm.llamacpp.url` and `llm.openai_endpoint.url`) still use langchain's shared default HTTP clients, which follow redirects, so for them the guard blocks only a directly configured metadata URL, not one reached through a redirect. No path does DNS pinning; see the DNS-rebinding caveat above.
+- **Redirects and embeddings endpoints**: the configured embedding endpoints (`embeddings.openai.base_url`, `embeddings.ollama.url`) get the same pre-flight `assert_base_url_safe` check. The OpenAI embeddings provider builds its own `httpx2` clients with `follow_redirects=False` for a custom `base_url`, both for embedding calls and for its model-discovery call. For embedding calls, a configured proxy (`openai_proxy` argument, else `OPENAI_PROXY`) is routed through those clients instead of langchain's `openai_proxy` wiring, so redirects are refused with or without a proxy. The model-discovery client does not use `openai_proxy`/`OPENAI_PROXY`; it connects directly, or through the standard `HTTP(S)_PROXY` environment variables that the `httpx2` client honours by default (`trust_env`). The pre-flight check resolves the hostname with the local resolver and fails closed if it cannot (the error then says it could not resolve the host rather than that the host is blocked), so a custom embeddings `base_url` must resolve locally even when a proxy is configured. Under a proxy the check is advisory: the proxy does its own DNS resolution and connects to whatever address it gets, which need not be the address validated locally. The Ollama embeddings provider and the Ollama chat provider (`llm.ollama.url`) pass `follow_redirects=False` to `ollama.Client`, whose default is to follow. The other chat providers (`ChatOpenAI`- and `ChatAnthropic`-based, including `llm.lmstudio.url`, `llm.llamacpp.url` and `llm.openai_endpoint.url`) still use langchain's shared default HTTP clients for chat calls, which follow redirects, so for them the guard blocks only a directly configured metadata URL, not one reached through a redirect. Their model-discovery calls (`list_models_for_api`, which builds its own `openai.OpenAI` / `anthropic.Anthropic` client) pass the SDK's `DefaultHttpxClient(follow_redirects=False)`, so a 3xx from the configured endpoint fails discovery (an empty model list) instead of being followed. No path does DNS pinning; see the DNS-rebinding caveat above.
OpenAI embeddings apply the same endpoint validation and redirect refusal to SDK environment fallbacks. Embedding calls resolve an explicit `base_url` argument, then `embeddings.openai.base_url`, then `OPENAI_API_BASE`, then `OPENAI_BASE_URL`. Model discovery uses `embeddings.openai.base_url` or the direct SDK's `OPENAI_BASE_URL` fallback; it does not read the LangChain-only `OPENAI_API_BASE` variable. Environment configuration therefore cannot bypass the embedding endpoint guard.
diff --git a/changelog.d/+llm-discovery-no-redirects.security.md b/changelog.d/+llm-discovery-no-redirects.security.md
new file mode 100644
index 0000000000..495356fae8
--- /dev/null
+++ b/changelog.d/+llm-discovery-no-redirects.security.md
@@ -0,0 +1 @@
+LLM model discovery for the OpenAI-compatible and Anthropic providers no longer follows HTTP redirects; an endpoint that answers model listing with a redirect now returns an empty model list.
diff --git a/src/local_deep_research/llm/providers/implementations/anthropic.py b/src/local_deep_research/llm/providers/implementations/anthropic.py
index 2621a68830..c81e06ed5c 100644
--- a/src/local_deep_research/llm/providers/implementations/anthropic.py
+++ b/src/local_deep_research/llm/providers/implementations/anthropic.py
@@ -11,6 +11,7 @@ from ..base import OPTIONAL_API_KEY_PLACEHOLDER, Exposure
from ..openai_base import OpenAICompatibleProvider
from ....security.log_sanitizer import scrub_error
from ....security.ssrf_validator import assert_base_url_safe
+from ....utilities.resource_utils import safe_close
from .._helpers import (
MODEL_DISCOVERY_TIMEOUT_SECONDS,
build_httpx_timeout,
@@ -186,7 +187,11 @@ class AnthropicProvider(OpenAICompatibleProvider):
logger.warning("{} {}", cls.provider_name, safe_msg)
return []
- from anthropic import Anthropic, Timeout as AnthropicTimeout
+ from anthropic import (
+ Anthropic,
+ DefaultHttpxClient,
+ Timeout as AnthropicTimeout,
+ )
# Trim a pasted key the way create_llm's resolve_api_key does.
# Without this a key with surrounding whitespace works for
@@ -199,17 +204,32 @@ class AnthropicProvider(OpenAICompatibleProvider):
# Pass the key explicitly (placeholder when keyless) so the SDK does
# not read ANTHROPIC_API_KEY from the environment and ship a real
# cloud key to a self-hosted endpoint.
- client = Anthropic(
- api_key=api_key or OPTIONAL_API_KEY_PLACEHOLDER,
- base_url=base_url or None,
- timeout=build_httpx_timeout(
- MODEL_DISCOVERY_TIMEOUT_SECONDS, AnthropicTimeout
- ),
- max_retries=0,
- )
+ #
+ # The SDK's default httpx client follows redirects, and the
+ # base_url guard above validates only the configured URL, never
+ # a redirect target, so discovery uses an explicit client with
+ # ``follow_redirects=False`` (same as the OpenAI-compatible
+ # discovery path). ``DefaultHttpxClient`` keeps the SDK's own
+ # limits and environment-proxy behaviour (``trust_env``).
+ http_client = DefaultHttpxClient(follow_redirects=False)
+ try:
+ client = Anthropic(
+ api_key=api_key or OPTIONAL_API_KEY_PLACEHOLDER,
+ base_url=base_url or None,
+ timeout=build_httpx_timeout(
+ MODEL_DISCOVERY_TIMEOUT_SECONDS, AnthropicTimeout
+ ),
+ max_retries=0,
+ http_client=http_client,
+ )
- logger.debug(f"Fetching models from {cls.provider_name}")
- models_response = client.models.list()
+ logger.debug(f"Fetching models from {cls.provider_name}")
+ models_response = client.models.list()
+ finally:
+ # The response is fully read; release the per-call client.
+ safe_close(
+ http_client, "Anthropic model discovery httpx client"
+ )
models = []
for model in models_response.data:
diff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.py
index 28ed44f497..174d6fcb08 100644
--- a/src/local_deep_research/llm/providers/openai_base.py
+++ b/src/local_deep_research/llm/providers/openai_base.py
@@ -11,6 +11,7 @@ from ...security.secure_logging import logger
# be unaffected by patching the source module.
from ...security.log_sanitizer import redact_secrets, scrub_error
from ...security.ssrf_validator import assert_base_url_safe
+from ...utilities.resource_utils import safe_close
from ...security.url_redaction import redact_url_credentials
from ...settings.exceptions import SettingsValueError
from ...utilities.url_utils import normalize_url
@@ -333,7 +334,7 @@ class OpenAICompatibleProvider(BaseLLMProvider):
# Use a dummy key for providers that don't require auth
api_key = api_key or "dummy-key-for-models-list"
- from openai import OpenAI, Timeout
+ from openai import DefaultHttpxClient, OpenAI, Timeout
# Use provided base_url or fall back to class default
if not base_url:
@@ -366,21 +367,35 @@ class OpenAICompatibleProvider(BaseLLMProvider):
# informational ``x-stainless-read-timeout`` header well
# formed. ``openai.Timeout`` is the httpx2 flavour the SDK
# ships; ``httpx.Timeout`` would not be recognised.
- client = OpenAI(
- api_key=api_key,
- base_url=base_url,
- timeout=build_httpx_timeout(
- MODEL_DISCOVERY_TIMEOUT_SECONDS, Timeout
- ),
- max_retries=0,
- )
+ #
+ # The SDK's default httpx client follows redirects, and the
+ # guard above validates only the configured URL, never a
+ # redirect target. An explicit client with
+ # ``follow_redirects=False`` (as the embeddings discovery path
+ # does) makes a 3xx surface as an error instead. The SDK's
+ # ``DefaultHttpxClient`` keeps its own limits and the
+ # environment-proxy behaviour (``trust_env``) of the default.
+ http_client = DefaultHttpxClient(follow_redirects=False)
+ try:
+ client = OpenAI(
+ api_key=api_key,
+ base_url=base_url,
+ timeout=build_httpx_timeout(
+ MODEL_DISCOVERY_TIMEOUT_SECONDS, Timeout
+ ),
+ max_retries=0,
+ http_client=http_client,
+ )
- # Fetch models
- logger.debug(
- f"Fetching models from {cls.provider_name} at "
- f"{redact_url_credentials(base_url) if base_url else None}"
- )
- models_response = client.models.list()
+ # Fetch models
+ logger.debug(
+ f"Fetching models from {cls.provider_name} at "
+ f"{redact_url_credentials(base_url) if base_url else None}"
+ )
+ models_response = client.models.list()
+ finally:
+ # The response is fully read; release the per-call client.
+ safe_close(http_client, "model discovery httpx client")
models = []
for model in models_response.data:
diff --git a/tests/llm/test_provider_base_url_ssrf.py b/tests/llm/test_provider_base_url_ssrf.py
index bc0aad19e2..d1f49544f2 100644
--- a/tests/llm/test_provider_base_url_ssrf.py
+++ b/tests/llm/test_provider_base_url_ssrf.py
@@ -529,7 +529,15 @@ class TestOpenAICompatibleListModelsSsrf:
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."""
+ must pass the guard and reach the SDK client.
+
+ Premise note: production now passes an explicit
+ ``http_client=DefaultHttpxClient(follow_redirects=False)`` to the
+ OpenAI SDK constructor (the redirect-suppression fix), so this fake
+ must accept that kwarg; without it a TypeError is swallowed by the
+ discovery path's broad ``except Exception`` and the capture below
+ stays empty — the call shape changed, the pinned behaviour did not.
+ """
from local_deep_research.llm.providers.openai_base import (
OpenAICompatibleProvider,
)
@@ -547,6 +555,7 @@ class TestOpenAICompatibleListModelsSsrf:
base_url=None,
timeout=None,
max_retries=None,
+ http_client=None,
):
captured["base_url"] = base_url
self.models = _FakeModels()
diff --git a/tests/llm_providers/implementations/test_qwen_provider.py b/tests/llm_providers/implementations/test_qwen_provider.py
index 9e027dc503..b6e8aece22 100644
--- a/tests/llm_providers/implementations/test_qwen_provider.py
+++ b/tests/llm_providers/implementations/test_qwen_provider.py
@@ -67,6 +67,21 @@ class TestQwenCloudProvider:
assert QwenCloudProvider.requires_auth_for_models() is True
def test_model_catalog_sends_key_to_qwencloud_endpoint(self):
+ """The model catalogue request must go to the qwencloud endpoint
+ carrying the user's API key (captured below via a mock transport).
+
+ Premise note: production now passes its own explicit
+ ``http_client=DefaultHttpxClient(follow_redirects=False)`` to the
+ OpenAI SDK constructor (the redirect-suppression fix), so the stub
+ must override that kwarg with this test's request-capturing
+ mock-transport client instead of also passing ``http_client=`` —
+ passing it twice raised "got multiple values for keyword argument
+ 'http_client'", which the discovery path's broad ``except Exception``
+ swallowed into ``[]``. The request capture is unchanged: the stub
+ still builds a real ``OpenAI`` client routed through the capturing
+ transport, so the method/URL/Authorization assertions below observe
+ the actual HTTP request.
+ """
import sys
from openai import DefaultHttpxClient, OpenAI
@@ -105,7 +120,7 @@ class TestQwenCloudProvider:
with patch(
"openai.OpenAI",
side_effect=lambda **kwargs: OpenAI(
- http_client=http_client, **kwargs
+ **{**kwargs, "http_client": http_client}
),
):
models = QwenCloudProvider.list_models_for_api(
diff --git a/tests/llm_providers/test_model_discovery_no_redirects.py b/tests/llm_providers/test_model_discovery_no_redirects.py
new file mode 100644
index 0000000000..56f31a23bf
--- /dev/null
+++ b/tests/llm_providers/test_model_discovery_no_redirects.py
@@ -0,0 +1,230 @@
+"""LLM model discovery must not follow HTTP redirects.
+
+``list_models_for_api`` validates the configured base URL with
+``assert_base_url_safe`` but the openai/anthropic SDKs' default httpx
+clients follow redirects, and a redirect target is never re-validated.
+Discovery therefore hands the SDK an explicit ``DefaultHttpxClient``
+with ``follow_redirects=False``.
+
+Two layers:
+
+* Spy tests patch the SDK client class and inspect the ``http_client``
+ that discovery passes in.
+* Stub-server tests run the real SDK against a loopback HTTP server: a
+ 302 from the configured URL must yield ``[]`` without the redirect
+ target being requested, while a direct 200 (positive control) must
+ still yield the model list.
+"""
+
+import json
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.llm.providers.implementations.anthropic import (
+ AnthropicProvider,
+)
+from local_deep_research.llm.providers.implementations.custom_anthropic_endpoint import (
+ CustomAnthropicEndpointProvider,
+)
+from local_deep_research.llm.providers.implementations.custom_openai_endpoint import (
+ CustomOpenAIEndpointProvider,
+)
+from local_deep_research.llm.providers.implementations.openai import (
+ OpenAIProvider,
+)
+
+_PROXY_ENV = (
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "ALL_PROXY",
+ "http_proxy",
+ "https_proxy",
+ "all_proxy",
+)
+
+
+def _fake_sdk_client(model_id="model-a"):
+ model = MagicMock()
+ model.id = model_id
+ model.display_name = model_id
+ response = MagicMock()
+ response.data = [model]
+ client = MagicMock()
+ client.models.list.return_value = response
+ return client
+
+
+def _passed_http_client(sdk_cls_mock):
+ sdk_cls_mock.assert_called_once()
+ http_client = sdk_cls_mock.call_args.kwargs.get("http_client")
+ assert http_client is not None, (
+ "discovery must pass an explicit http_client; the SDK default "
+ "client follows redirects"
+ )
+ return http_client
+
+
+# ---------------------------------------------------------------------------
+# Spy tests: the http_client handed to the SDK
+# ---------------------------------------------------------------------------
+
+
+class TestOpenAIDiscoveryHttpClient:
+ @pytest.mark.parametrize(
+ "provider, kwargs",
+ [
+ (
+ CustomOpenAIEndpointProvider,
+ {"api_key": None, "base_url": "http://localhost:1234/v1"},
+ ),
+ (OpenAIProvider, {"api_key": "sk-test", "base_url": None}),
+ ],
+ ids=["custom-endpoint", "cloud"],
+ )
+ def test_redirects_disabled_and_client_closed(self, provider, kwargs):
+ with patch(
+ "openai.OpenAI", return_value=_fake_sdk_client()
+ ) as openai_cls:
+ models = provider.list_models_for_api(**kwargs)
+
+ assert models == [{"value": "model-a", "label": "model-a"}]
+ http_client = _passed_http_client(openai_cls)
+ assert http_client.follow_redirects is False
+ assert http_client.is_closed
+
+
+class TestAnthropicDiscoveryHttpClient:
+ @pytest.mark.parametrize(
+ "provider, kwargs",
+ [
+ (
+ CustomAnthropicEndpointProvider,
+ {"api_key": None, "base_url": "http://localhost:9090"},
+ ),
+ (AnthropicProvider, {"api_key": "sk-ant-test", "base_url": None}),
+ ],
+ ids=["custom-endpoint", "cloud"],
+ )
+ def test_redirects_disabled_and_client_closed(self, provider, kwargs):
+ with patch(
+ "anthropic.Anthropic", return_value=_fake_sdk_client()
+ ) as anthropic_cls:
+ models = provider.list_models_for_api(**kwargs)
+
+ assert models == [{"value": "model-a", "label": "model-a"}]
+ http_client = _passed_http_client(anthropic_cls)
+ assert http_client.follow_redirects is False
+ assert http_client.is_closed
+
+
+# ---------------------------------------------------------------------------
+# Stub-server tests: real SDK, loopback server
+# ---------------------------------------------------------------------------
+
+_MODELS_BODY = json.dumps(
+ {
+ "object": "list",
+ "data": [
+ {
+ "id": "redirect-target-model",
+ "object": "model",
+ "type": "model",
+ "display_name": "redirect-target-model",
+ "created_at": "2024-01-01T00:00:00Z",
+ "created": 0,
+ "owned_by": "stub",
+ }
+ ],
+ "has_more": False,
+ "first_id": None,
+ "last_id": None,
+ }
+).encode()
+
+
+def stub_server(monkeypatch):
+ """Loopback server: ``/redirect/...`` answers 302 to ``/target/...``;
+ every other path answers 200 with a one-model list."""
+ for name in _PROXY_ENV:
+ monkeypatch.delenv(name, raising=False)
+
+ paths = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ paths.append(self.path)
+ if self.path.startswith("/redirect/"):
+ target = "/target/" + self.path[len("/redirect/") :]
+ self.send_response(302)
+ self.send_header("Location", target)
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+ return
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(_MODELS_BODY)))
+ self.end_headers()
+ self.wfile.write(_MODELS_BODY)
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield f"http://127.0.0.1:{server.server_address[1]}", paths
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
+class TestDiscoveryAgainstStubServer:
+ def test_openai_compatible_redirect_not_followed(self, stub_server):
+ origin, paths = stub_server
+ models = CustomOpenAIEndpointProvider.list_models_for_api(
+ api_key=None, base_url=f"{origin}/redirect/v1"
+ )
+ assert models == []
+ assert paths, "the configured URL was never requested"
+ assert not any(p.startswith("/target/") for p in paths), paths
+
+ def test_openai_compatible_direct_response_still_listed(self, stub_server):
+ origin, paths = stub_server
+ models = CustomOpenAIEndpointProvider.list_models_for_api(
+ api_key=None, base_url=f"{origin}/direct/v1"
+ )
+ assert models == [
+ {
+ "value": "redirect-target-model",
+ "label": "redirect-target-model",
+ }
+ ]
+ assert paths == ["/direct/v1/models"]
+
+ def test_anthropic_endpoint_redirect_not_followed(self, stub_server):
+ origin, paths = stub_server
+ models = CustomAnthropicEndpointProvider.list_models_for_api(
+ api_key=None, base_url=f"{origin}/redirect"
+ )
+ assert models == []
+ assert paths, "the configured URL was never requested"
+ assert not any(p.startswith("/target/") for p in paths), paths
+
+ def test_anthropic_endpoint_direct_response_still_listed(self, stub_server):
+ origin, paths = stub_server
+ models = CustomAnthropicEndpointProvider.list_models_for_api(
+ api_key=None, base_url=f"{origin}/direct"
+ )
+ assert models == [
+ {
+ "value": "redirect-target-model",
+ "label": "redirect-target-model",
+ }
+ ]
+ assert len(paths) == 1 and paths[0].startswith("/direct/")