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): SSRF-guard embedding endpoints and refuse redirects in embedding and Ollama clients (#3139)

LearningCircuitcb2c67524b1d
diff --git a/.pre-commit-hooks/check-env-vars.py b/.pre-commit-hooks/check-env-vars.py
index d40d257303..ff2544fdd1 100755
--- a/.pre-commit-hooks/check-env-vars.py
+++ b/.pre-commit-hooks/check-env-vars.py
@@ -57,6 +57,7 @@ ALLOWED_PATH_ENDINGS = (
"/web/fastapi_app.py", # docs_url + secret key init at module load (before SettingsManager)
"/security/rate_limiter.py", # Module-level RATE_LIMIT_FAIL_CLOSED at decorator time
"/security/secure_logging.py", # Diagnose-mode gate must work before/without SettingsManager (same rationale as log_utils.py)
+ "/embeddings/providers/implementations/openai.py", # Validates SDK endpoint env vars and routes OPENAI_PROXY through redirect-refusing clients
)
# System environment variables that are always allowed
diff --git a/SECURITY.md b/SECURITY.md
index 736b9e6fbc..04ade664d7 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -228,6 +228,9 @@ 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.
+
+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.
### Egress Policy Module
diff --git a/changelog.d/3139.security.md b/changelog.d/3139.security.md
new file mode 100644
index 0000000000..fa38df039d
--- /dev/null
+++ b/changelog.d/3139.security.md
@@ -0,0 +1,5 @@
+Custom OpenAI-compatible and Ollama embedding endpoints now reject metadata-service SSRF targets and refuse HTTP redirects; for OpenAI-compatible embedding calls this holds with or without a proxy (the `OPENAI_PROXY` environment variable, or an `openai_proxy` argument, which is now honoured too). The Ollama chat client refuses redirects too. Upgrade note: the SSRF check resolves the endpoint hostname with the local resolver, so a custom embeddings URL whose host only a proxy can resolve is now refused, with a "could not resolve host" error that is distinct from the blocked-host error (also for LLM provider URLs); under a proxy the check is advisory, because the proxy does its own DNS resolution. An endpoint that redirects (for example an http-to-https reverse proxy) now fails instead of being followed. The HTTP clients LDR builds for these endpoints, and embedding resources, are closed on normal and failure paths.
+
+A failed attempt to close an embedding HTTP client now leaves cleanup retryable, including synchronous and asynchronous close paths.
+
+OpenAI embedding endpoint validation and redirect refusal also cover SDK environment fallbacks: `OPENAI_API_BASE` then `OPENAI_BASE_URL` for embedding calls, and `OPENAI_BASE_URL` for model discovery. Explicit embedding URL configuration keeps precedence.
diff --git a/src/local_deep_research/embeddings/providers/implementations/ollama.py b/src/local_deep_research/embeddings/providers/implementations/ollama.py
index 94031b5950..9e24b0fd2e 100644
--- a/src/local_deep_research/embeddings/providers/implementations/ollama.py
+++ b/src/local_deep_research/embeddings/providers/implementations/ollama.py
@@ -9,6 +9,7 @@ from langchain_core.embeddings import Embeddings
from ....config.thread_settings import get_setting_from_snapshot
from ....security.secure_logging import logger
+from ....security.ssrf_validator import assert_base_url_safe
from ....utilities.llm_utils import (
_close_inner_ollama_clients,
get_ollama_base_url,
@@ -64,6 +65,23 @@ class OllamaEmbeddingsProvider(BaseEmbeddingProvider):
if base_url is None:
base_url = get_ollama_base_url(settings_snapshot)
+ # SSRF guard: the availability/discovery probes above route through
+ # safe_get/safe_post, but the embedding traffic itself flows through
+ # the OllamaEmbeddings -> ollama.Client -> httpx path, which never
+ # consults the SSRF policy. Without this, a user-configured
+ # ``embeddings.ollama.url`` pointing at a cloud-metadata endpoint
+ # (169.254.169.254 etc.) would exfiltrate to it on every embed call.
+ # Mirrors the LLM-side Ollama provider, which validates the same way.
+ # allow_localhost/allow_private_ips (inside assert_base_url_safe) keep
+ # the default localhost:11434 and RFC1918 Ollama hosts working; the
+ # ALWAYS_BLOCKED metadata IPs are refused, and so is a hostname the
+ # local resolver cannot resolve at construction time (for example a
+ # Docker service that is not up yet), with a distinct "could not
+ # resolve host" message.
+ base_url = assert_base_url_safe(
+ base_url, setting_key="embeddings.ollama.url"
+ )
+
# Without an explicit num_ctx, Ollama uses the model's modelfile
# default (often 2048). Inputs longer than that return HTTP 500
# ("input length exceeds the context length") rather than being
@@ -98,10 +116,15 @@ class OllamaEmbeddingsProvider(BaseEmbeddingProvider):
)
from ....llm.providers.implementations.ollama import OllamaProvider
+ # follow_redirects=False: ollama.Client defaults it to True, so an
+ # allowed host could otherwise bounce every embed request (and the
+ # bearer header) to a metadata endpoint that the
+ # assert_base_url_safe() check above refuses when named directly.
client_kwargs: Dict[str, Any] = {
"timeout": build_httpx_timeout(
resolve_request_timeout(settings_snapshot), Timeout
- )
+ ),
+ "follow_redirects": False,
}
# An authenticated Ollama instance sits behind the same proxy for
diff --git a/src/local_deep_research/embeddings/providers/implementations/openai.py b/src/local_deep_research/embeddings/providers/implementations/openai.py
index 9d38b3f3a9..5d0aae1398 100644
--- a/src/local_deep_research/embeddings/providers/implementations/openai.py
+++ b/src/local_deep_research/embeddings/providers/implementations/openai.py
@@ -1,5 +1,6 @@
"""OpenAI embedding provider."""
+import os
from typing import Any, Dict, Final, List, Optional
from urllib.parse import urlparse
@@ -8,6 +9,7 @@ from ....security.secure_logging import logger
from ....config.thread_settings import get_setting_from_snapshot
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 BaseEmbeddingProvider, Exposure
@@ -55,15 +57,20 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
Args:
model: Model name (defaults to text-embedding-3-small)
settings_snapshot: Optional settings snapshot
- **kwargs: Additional parameters (api_key, etc.)
+ **kwargs: Additional parameters (api_key, base_url,
+ dimensions, chunk_size, openai_proxy)
Returns:
OpenAIEmbeddings instance
Raises:
- ValueError: If API key is not configured
+ ValueError: If API key is not configured, or if a custom
+ base_url fails SSRF validation (a blocked address, or a
+ host the local resolver cannot resolve -- the check
+ resolves locally even when a proxy is configured)
"""
from langchain_openai import OpenAIEmbeddings
+ from openai import DefaultAsyncHttpxClient, DefaultHttpxClient, Timeout
# Get API key + base_url. Read base_url first so we can decide
# whether a missing api_key is fatal (cloud) or just a keyless
@@ -75,6 +82,13 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
default=None,
settings_snapshot=settings_snapshot,
)
+ if not base_url:
+ # Resolve the same fallbacks as LangChain and then the OpenAI
+ # SDK before validation and client construction. Otherwise an
+ # environment endpoint bypasses the custom-URL protections.
+ base_url = os.environ.get("OPENAI_API_BASE") or os.environ.get(
+ "OPENAI_BASE_URL"
+ )
api_key = kwargs.get("api_key")
if api_key is None:
@@ -131,6 +145,46 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
if chunk_size is None:
chunk_size = _DEFAULT_CHUNK_SIZE
+ embedding_dimensions = None
+ if dimensions and model.startswith("text-embedding-3"):
+ embedding_dimensions = int(dimensions)
+ # Convert early so invalid numeric settings raise before any
+ # custom HTTP client is constructed in the base_url branch below.
+ embedding_chunk_size = int(chunk_size)
+
+ # Same bound as the LLM side: langchain otherwise forwards an
+ # explicit ``timeout=None`` that overrides the SDK default, leaving
+ # embedding reads unbounded, and the SDK's own 2 retries would
+ # multiply the wait. Imported lazily — the ``llm.providers``
+ # package runs provider auto-discovery at import time. Resolved
+ # here, before the base_url branch builds any HTTP client, so a
+ # bad timeout/retry setting cannot leak those clients.
+ from ....llm.providers._helpers import (
+ build_httpx_timeout,
+ resolve_max_retries,
+ resolve_request_timeout,
+ )
+
+ # An SDK ``Timeout`` object, not the chat path's hashable tuple:
+ # ``OpenAIEmbeddings`` never consults langchain's ``@lru_cache``'d
+ # ``_get_default_httpx_client``, so every instance owns its httpx
+ # clients whatever the timeout's type. The object keeps the SDK's
+ # informational ``x-stainless-read-timeout`` header well formed
+ # while the effective bounds stay identical. ``openai.Timeout`` is
+ # the httpx2 flavour the SDK ships; ``httpx.Timeout`` is a
+ # different class and would not be recognised. The SDK applies an
+ # explicit ``timeout`` even when an ``http_client`` is injected.
+ request_timeout = build_httpx_timeout(
+ resolve_request_timeout(settings_snapshot), Timeout
+ )
+ max_retries = resolve_max_retries(settings_snapshot)
+
+ # Proxy precedence matches langchain's own ``openai_proxy`` field:
+ # an explicit kwarg wins, else the ``OPENAI_PROXY`` env var.
+ openai_proxy = kwargs.get("openai_proxy") or os.environ.get(
+ "OPENAI_PROXY"
+ )
+
# Build parameters. Annotated as Dict[str, Any] so the
# heterogeneous values (str for model/key/base_url, int for
# dimensions) and the **params unpack into OpenAIEmbeddings
@@ -140,14 +194,65 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
"openai_api_key": api_key,
}
+ http_client = None
+ http_async_client = None
if base_url:
# Normalize first so a scheme-less entry like "api.openai.com"
# parses to a hostname (urlparse otherwise returns hostname=None
# for bare hosts, which would silently drop the ctx-length guard
# for the real OpenAI endpoint). Mirrors the LLM-side OpenAI
# provider, which already normalizes via the same helper.
- base_url = normalize_url(base_url)
+ base_url = assert_base_url_safe(
+ normalize_url(base_url),
+ setting_key="embeddings.openai.base_url",
+ )
params["openai_api_base"] = base_url
+ from .owned_openai_embeddings import (
+ OwnedOpenAIEmbeddings,
+ close_openai_embedding_clients,
+ )
+
+ # Own the HTTP clients for a custom base_url so redirects are
+ # refused explicitly: the SDK's default client follows them,
+ # which would let an allowed host bounce embedding requests
+ # (and the bearer key) to a metadata endpoint that
+ # assert_base_url_safe() above refuses directly.
+ #
+ # A configured proxy is routed through these same clients
+ # rather than through langchain's ``openai_proxy`` wiring:
+ # langchain raises if ``openai_proxy`` and an explicit
+ # ``http_client`` are both set, and its ``openai_proxy``
+ # field reads ``OPENAI_PROXY`` from the env by default, so it
+ # is pinned to None below. Every custom-base_url instance
+ # therefore gets follow_redirects=False, proxy or not, and
+ # its clients are closed by OwnedOpenAIEmbeddings.close().
+ #
+ # Neither path does DNS pinning -- assert_base_url_safe()
+ # validates once at construction time; like every other LLM
+ # SDK integration (see SECURITY.md "LLM Provider URL
+ # Validation"), the OpenAI SDK's HTTP client re-resolves the
+ # hostname on every call. Egress restriction at the firewall
+ # is the operator-side mitigation for that residual window.
+ # The check also resolves with the LOCAL resolver, so the
+ # host must resolve locally even under a proxy; with a proxy
+ # it is advisory, since the proxy resolves the name itself.
+ client_options: Dict[str, Any] = {"follow_redirects": False}
+ if openai_proxy:
+ client_options["proxy"] = openai_proxy
+ http_client = DefaultHttpxClient(**client_options)
+ try:
+ http_async_client = DefaultAsyncHttpxClient(**client_options)
+ except Exception:
+ try:
+ http_client.close()
+ except Exception:
+ logger.warning(
+ "Failed to close OpenAI embeddings sync httpx client"
+ )
+ raise
+ params["http_client"] = http_client
+ params["http_async_client"] = http_async_client
+ params["openai_proxy"] = None
# Disable client-side context length checks only for non-OpenAI
# hosts (LM Studio, vLLM, llama.cpp, etc.) which may lack tiktoken
# model entries or reject tokenized inputs. Keep the LangChain
@@ -155,49 +260,37 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
# who set base_url explicitly to the real OpenAI endpoint.
if urlparse(base_url).hostname != "api.openai.com":
params["check_embedding_ctx_length"] = False
+ elif openai_proxy:
+ # Fixed public endpoint: langchain builds the proxy-routed
+ # client itself. Forwarded explicitly so a proxy passed as a
+ # kwarg is not dropped (langchain only reads the env var).
+ params["openai_proxy"] = openai_proxy
# For text-embedding-3 models, dimensions can be customized
- if dimensions and model.startswith("text-embedding-3"):
- params["dimensions"] = int(dimensions)
+ if embedding_dimensions is not None:
+ params["dimensions"] = embedding_dimensions
- effective_chunk_size = int(chunk_size)
- if effective_chunk_size <= 0:
+ if embedding_chunk_size <= 0:
logger.warning(
"OpenAI embeddings chunk_size={} is not positive; "
"using safe default chunk_size={}",
chunk_size,
_DEFAULT_CHUNK_SIZE,
)
- effective_chunk_size = _DEFAULT_CHUNK_SIZE
- params["chunk_size"] = effective_chunk_size
-
- # Same bound as the LLM side: langchain otherwise forwards an
- # explicit ``timeout=None`` that overrides the SDK default, leaving
- # embedding reads unbounded, and the SDK's own 2 retries would
- # multiply the wait. Imported lazily — the ``llm.providers``
- # package runs provider auto-discovery at import time.
- from ....llm.providers._helpers import (
- build_httpx_timeout,
- resolve_max_retries,
- resolve_request_timeout,
- )
-
- # An SDK ``Timeout`` object, not the chat path's hashable tuple:
- # ``OpenAIEmbeddings`` never consults langchain's ``@lru_cache``'d
- # ``_get_default_httpx_client``, so every instance owns its httpx
- # clients whatever the timeout's type. The object keeps the SDK's
- # informational ``x-stainless-read-timeout`` header well formed
- # while the effective bounds stay identical. ``openai.Timeout`` is
- # the httpx2 flavour the SDK ships; ``httpx.Timeout`` is a
- # different class and would not be recognised.
- from openai import Timeout
-
- params["request_timeout"] = build_httpx_timeout(
- resolve_request_timeout(settings_snapshot), Timeout
- )
- params["max_retries"] = resolve_max_retries(settings_snapshot)
-
- embeddings = OpenAIEmbeddings(**params)
+ embedding_chunk_size = _DEFAULT_CHUNK_SIZE
+ params["chunk_size"] = embedding_chunk_size
+ params["request_timeout"] = request_timeout
+ params["max_retries"] = max_retries
+
+ embeddings: Embeddings
+ if http_client is not None:
+ try:
+ embeddings = OwnedOpenAIEmbeddings(**params)
+ except Exception:
+ close_openai_embedding_clients(http_client, http_async_client)
+ raise
+ else:
+ embeddings = OpenAIEmbeddings(**params)
logger.info(
"Creating OpenAIEmbeddings with model={}, chunk_size={}",
model,
@@ -261,8 +354,10 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
# Initialized before the try so the except block can redact it
# even if an early statement (e.g. the openai import) raises.
api_key = None
+ http_client = None
+ client_entered = False
try:
- from openai import OpenAI, Timeout
+ from openai import DefaultHttpxClient, OpenAI, Timeout
api_key = get_setting_from_snapshot(
"embeddings.openai.api_key",
@@ -275,6 +370,11 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
settings_snapshot=settings_snapshot,
)
+ if not base_url:
+ # Discovery uses the SDK directly; OPENAI_API_BASE is a
+ # LangChain-only fallback and does not apply here.
+ base_url = os.environ.get("OPENAI_BASE_URL")
+
if not api_key:
if base_url:
# Keyless OpenAI-compatible local server — use a
@@ -285,9 +385,8 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
return []
client_kwargs: Dict[str, Any] = {"api_key": api_key}
- if base_url:
- client_kwargs["base_url"] = normalize_url(base_url)
# Bounded discovery request — mirrors the LLM-side provider.
+ # Resolved before any HTTP client is built below.
from ....llm.providers._helpers import (
MODEL_DISCOVERY_TIMEOUT_SECONDS,
build_httpx_timeout,
@@ -300,8 +399,16 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
MODEL_DISCOVERY_TIMEOUT_SECONDS, Timeout
)
client_kwargs["max_retries"] = 0
- client = OpenAI(**client_kwargs)
- models_response = client.models.list()
+ if base_url:
+ client_kwargs["base_url"] = assert_base_url_safe(
+ normalize_url(base_url),
+ setting_key="embeddings.openai.base_url",
+ )
+ http_client = DefaultHttpxClient(follow_redirects=False)
+ client_kwargs["http_client"] = http_client
+ with OpenAI(**client_kwargs) as client:
+ client_entered = True
+ models_response = client.models.list()
# No name-based filtering — see method docstring (#4195).
models: List[Dict[str, Any]] = []
@@ -321,6 +428,13 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
return models
except Exception as e:
+ if http_client is not None and not client_entered:
+ try:
+ http_client.close()
+ except Exception:
+ logger.warning(
+ "Failed to close OpenAI model discovery httpx client"
+ )
# Use logger.warning rather than logger.exception so the
# exception's cause chain (which may embed the api_key in a
# URL or auth header echoed back in the error body) is not
diff --git a/src/local_deep_research/embeddings/providers/implementations/owned_openai_embeddings.py b/src/local_deep_research/embeddings/providers/implementations/owned_openai_embeddings.py
new file mode 100644
index 0000000000..3d24cbd785
--- /dev/null
+++ b/src/local_deep_research/embeddings/providers/implementations/owned_openai_embeddings.py
@@ -0,0 +1,91 @@
+"""OpenAI embedding clients with explicit, retryable resource cleanup."""
+
+import asyncio
+import threading
+from typing import Any
+
+from langchain_openai import OpenAIEmbeddings
+from pydantic import ConfigDict, PrivateAttr
+
+from ....security.secure_logging import logger
+
+
+async def _aclose_http_clients(
+ http_client: Any, http_async_client: Any
+) -> bool:
+ closed = True
+ try:
+ http_client.close()
+ except Exception:
+ closed = False
+ logger.warning("Failed to close OpenAI embeddings sync httpx client")
+ try:
+ await http_async_client.aclose()
+ except Exception:
+ closed = False
+ logger.warning("Failed to close OpenAI embeddings async httpx client")
+ return closed
+
+
+def close_openai_embedding_clients(
+ http_client: Any, http_async_client: Any
+) -> bool:
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ try:
+ return asyncio.run(
+ _aclose_http_clients(http_client, http_async_client)
+ )
+ except Exception:
+ logger.warning("Failed to close OpenAI embeddings httpx clients")
+ return False
+
+ closed = False
+
+ def _close_in_thread() -> None:
+ nonlocal closed
+ try:
+ closed = asyncio.run(
+ _aclose_http_clients(http_client, http_async_client)
+ )
+ except Exception:
+ logger.warning("Failed to close OpenAI embeddings httpx clients")
+
+ close_thread = threading.Thread(
+ target=_close_in_thread,
+ daemon=True,
+ name="ldr-async-openai-embedding-close",
+ )
+ close_thread.start()
+ close_thread.join(timeout=5)
+ if close_thread.is_alive():
+ logger.warning("OpenAI embeddings async httpx close exceeded 5s")
+ return False
+ return closed
+
+
+class OwnedOpenAIEmbeddings(OpenAIEmbeddings):
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+ http_client: Any
+ http_async_client: Any
+ _closed: bool = PrivateAttr(default=False)
+
+ def close(self) -> None:
+ """Close from synchronous code; use ``aclose`` on the owning loop.
+
+ The fallback for a running loop waits up to five seconds. A client
+ whose transport cannot close on another loop remains retryable.
+ """
+ if self._closed:
+ return
+ if close_openai_embedding_clients(
+ self.http_client, self.http_async_client
+ ):
+ self._closed = True
+
+ async def aclose(self) -> None:
+ if self._closed:
+ return
+ if await _aclose_http_clients(self.http_client, self.http_async_client):
+ self._closed = True
diff --git a/src/local_deep_research/llm/providers/implementations/anthropic.py b/src/local_deep_research/llm/providers/implementations/anthropic.py
index 862369eccd..2621a68830 100644
--- a/src/local_deep_research/llm/providers/implementations/anthropic.py
+++ b/src/local_deep_research/llm/providers/implementations/anthropic.py
@@ -9,6 +9,7 @@ from ....security.secure_logging import logger
# function-local imports at call time.
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 .._helpers import (
MODEL_DISCOVERY_TIMEOUT_SECONDS,
@@ -177,11 +178,12 @@ class AnthropicProvider(OpenAICompatibleProvider):
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"
- )
+ except ValueError as e:
+ # The message carries no URL, only the setting key,
+ # and tells "could not resolve host" from a blocked
+ # host.
+ safe_msg = scrub_error(e)
+ logger.warning("{} {}", cls.provider_name, safe_msg)
return []
from anthropic import Anthropic, Timeout as AnthropicTimeout
diff --git a/src/local_deep_research/llm/providers/implementations/ollama.py b/src/local_deep_research/llm/providers/implementations/ollama.py
index cd07b19fd9..dbf54bc1f5 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 langchain_ollama import ChatOllama
from ....config.thread_settings import get_setting_from_snapshot
from ....security import safe_get
from ....security.secure_logging import logger
+from ....security.log_sanitizer import scrub_error
from ....security.ssrf_validator import assert_base_url_safe
from ....utilities.url_utils import normalize_url
from ..base import BaseLLMProvider, Exposure
@@ -74,11 +75,11 @@ class OllamaProvider(BaseLLMProvider):
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"
- )
+ except ValueError as e:
+ # The message carries no URL, only the setting key, and
+ # distinguishes "could not resolve host" from a blocked host.
+ safe_msg = scrub_error(e)
+ logger.warning("Ollama {}", safe_msg)
return []
# Get authentication headers
@@ -193,10 +194,15 @@ class OllamaProvider(BaseLLMProvider):
# Auth headers go here too: ChatOllama has no ``headers`` field, so
# a top-level ``headers=`` kwarg was silently dropped and the
# Authorization header never reached the wire.
+ # follow_redirects=False: ollama.Client defaults it to True, so an
+ # allowed host could otherwise bounce every chat request (and the
+ # bearer header) to a metadata endpoint that assert_base_url_safe()
+ # refuses when named directly.
client_kwargs = {
"timeout": build_httpx_timeout(
resolve_request_timeout(settings_snapshot), Timeout
- )
+ ),
+ "follow_redirects": False,
}
auth_headers = cls._get_auth_headers(
settings_snapshot=settings_snapshot
@@ -241,11 +247,9 @@ class OllamaProvider(BaseLLMProvider):
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"
- )
+ except ValueError as e:
+ safe_msg = scrub_error(e)
+ logger.warning("Ollama {}", safe_msg)
return False
logger.info(f"Checking Ollama availability at {base_url}/api/tags")
diff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.py
index 72a6cc3cae..25c0119349 100644
--- a/src/local_deep_research/llm/providers/openai_base.py
+++ b/src/local_deep_research/llm/providers/openai_base.py
@@ -9,7 +9,7 @@ from ...security.secure_logging import logger
# (`local_deep_research.config.thread_settings`) are picked up by the
# 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.log_sanitizer import redact_secrets, scrub_error
from ...security.ssrf_validator import assert_base_url_safe
from ...utilities.url_utils import normalize_url
from ._helpers import (
@@ -343,11 +343,12 @@ class OpenAICompatibleProvider(BaseLLMProvider):
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"
- )
+ except ValueError as e:
+ # The message carries no URL, only the setting key,
+ # and tells "could not resolve host" from a blocked
+ # host.
+ safe_msg = scrub_error(e)
+ logger.warning("{} {}", cls.provider_name, safe_msg)
return []
# A fresh client per call, never routed through langchain's
diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.py
index 3192006328..1c7ed617e4 100644
--- a/src/local_deep_research/security/ssrf_validator.py
+++ b/src/local_deep_research/security/ssrf_validator.py
@@ -8,6 +8,7 @@ by blocking requests to internal/private networks and enforcing safe schemes.
import ipaddress
import re
import socket
+from contextvars import ContextVar
from urllib.parse import urlparse
from typing import Optional
from loguru import logger
@@ -24,6 +25,15 @@ from .legacy_ipv4 import (
is_percent_encoded_numeric_ipv4_host,
)
+# Set to True by ``validate_url`` when it refuses a URL ONLY because the
+# local resolver raised ``socket.gaierror`` (every pre-DNS check had already
+# passed). ``assert_base_url_safe`` resets it before calling ``validate_url``
+# and reads it afterwards to choose its error message. It never affects
+# whether a URL is accepted.
+_REFUSED_FOR_UNRESOLVABLE_HOST: ContextVar[bool] = ContextVar(
+ "_REFUSED_FOR_UNRESOLVABLE_HOST", default=False
+)
+
# Cloud-provider metadata endpoints — always blocked, even with
# allow_localhost=True or allow_private_ips=True. These IPs expose IAM /
# instance-role credentials and are never legitimate destinations.
@@ -557,6 +567,7 @@ def validate_url(
logger.warning(
f"Failed to resolve hostname: {redact_url_for_log(url)}"
)
+ _REFUSED_FOR_UNRESOLVABLE_HOST.set(True)
return False
except Exception:
logger.exception("Error during hostname resolution")
@@ -599,8 +610,37 @@ def assert_base_url_safe(base_url: str, *, setting_key: str) -> str:
internals, so the resolve-vs-connect window remains. Egress restriction
at the firewall is the operator-side mitigation. See SECURITY.md
("LLM Provider URL Validation").
+
+ The hostname must resolve through the LOCAL resolver: ``validate_url``
+ fails closed when ``getaddrinfo`` cannot resolve it, even when the
+ eventual request would go through an HTTP(S) proxy that resolves the
+ name itself. That case raises a distinct "could not resolve host"
+ message so it is not mistaken for a blocked destination. The message
+ is chosen only when ``validate_url`` refused SOLELY because its own
+ ``getaddrinfo`` call raised ``socket.gaierror``, after every pre-DNS
+ check (scheme, forbidden characters, encoded or ambiguous numeric
+ IPv4 host, IP literal) had passed; every other refusal keeps the
+ generic "refusing to send" message. No second DNS lookup is made.
+ Under a proxy the check is advisory: the proxy does its own
+ resolution and connects to whatever address it gets, which need not
+ be the one validated here.
"""
- if not validate_url(base_url, allow_localhost=True, allow_private_ips=True):
+ token = _REFUSED_FOR_UNRESOLVABLE_HOST.set(False)
+ try:
+ is_safe = validate_url(
+ base_url, allow_localhost=True, allow_private_ips=True
+ )
+ unresolvable = _REFUSED_FOR_UNRESOLVABLE_HOST.get()
+ finally:
+ _REFUSED_FOR_UNRESOLVABLE_HOST.reset(token)
+ if not is_safe:
+ if unresolvable:
+ raise ValueError(
+ f"base_url failed SSRF validation: could not resolve host "
+ f"for SSRF validation (the host must resolve locally, even "
+ f"when a proxy is configured). Check {setting_key} config "
+ f"and DNS."
+ )
raise ValueError(
f"base_url failed SSRF validation: refusing to send "
f"inference traffic. Check {setting_key} config."
diff --git a/src/local_deep_research/web/routers/notes.py b/src/local_deep_research/web/routers/notes.py
index d2ca06f830..8f3c59fe72 100644
--- a/src/local_deep_research/web/routers/notes.py
+++ b/src/local_deep_research/web/routers/notes.py
@@ -2304,14 +2304,13 @@ def index_note_to_collection(
)
# Get RAG service configured for the collection
- rag_service = get_rag_service(request, username, collection_id)
-
- # Index the note (notes are now documents)
- result = rag_service.index_document(
- document_id=note_id,
- collection_id=collection_id,
- force_reindex=force_reindex,
- )
+ with get_rag_service(request, username, collection_id) as rag_service:
+ # Index the note (notes are now documents)
+ result = rag_service.index_document(
+ document_id=note_id,
+ collection_id=collection_id,
+ force_reindex=force_reindex,
+ )
if result["status"] == "error":
return JSONResponse(
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index 7ab6de0c75..7d8e12a10f 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -769,10 +769,7 @@ async def test_embedding(
status_code=400,
)
- # Import embedding functions
- from ...embeddings.embeddings_config import (
- get_embedding_function,
- )
+ from ...embeddings.embeddings_config import get_embeddings
logger.info(
"Testing embedding with provider={}, model={}",
@@ -792,12 +789,24 @@ async def test_embedding(
else {}
)
start = time.time()
- ef = get_embedding_function(
+ # get_embeddings (not get_embedding_function) so the owning
+ # instance is reachable here for cleanup: the wrapped callable
+ # from get_embedding_function discards it, leaking the
+ # per-instance httpx client(s) built for this one-shot test.
+ embeddings = get_embeddings(
provider=provider,
- model_name=model,
+ model=model,
settings_snapshot=settings_snapshot,
)
- emb = ef([_EMBEDDING_TEST_SENTENCE])[0]
+ try:
+ emb = embeddings.embed_documents([_EMBEDDING_TEST_SENTENCE])[0]
+ finally:
+ from ...utilities.llm_utils import _close_base_llm
+
+ try:
+ _close_base_llm(embeddings)
+ except Exception:
+ logger.warning("Failed to close test embedding resources")
return emb, int((time.time() - start) * 1000)
# run_db_sync (not raw to_thread): the thunk opens a
diff --git a/tests/embeddings/test_ollama_embeddings.py b/tests/embeddings/test_ollama_embeddings.py
index 8bf3abf0fd..b92bf8fbaf 100644
--- a/tests/embeddings/test_ollama_embeddings.py
+++ b/tests/embeddings/test_ollama_embeddings.py
@@ -197,11 +197,11 @@ class TestOllamaEmbeddingsCreate:
OllamaEmbeddingsProvider.create_embeddings(
model="nomic-embed-text",
- base_url="http://custom:8080",
+ base_url="http://127.0.0.1:8080",
)
call_kwargs = mock_ollama.call_args[1]
- assert call_kwargs["base_url"] == "http://custom:8080"
+ assert call_kwargs["base_url"] == "http://127.0.0.1:8080"
def test_create_uses_settings_snapshot(self):
"""Uses settings snapshot when provided."""
@@ -886,3 +886,82 @@ class TestOllamaEmbeddingsAvailableModels:
_, kwargs = mock_fetch.call_args
assert kwargs.get("timeout") is not None
assert kwargs["timeout"] >= 5.0
+
+
+# ── SSRF guard (embedding traffic path) ──────────────────────────────────
+
+
+class TestOllamaEmbeddingsCreateSsrf:
+ """The embedding client itself (OllamaEmbeddings -> ollama.Client ->
+ httpx) never consults the SSRF policy, unlike the safe_get/safe_post
+ availability probes. ``create_embeddings`` must therefore validate the
+ resolved base_url before construction so a user-configured
+ ``embeddings.ollama.url`` cannot direct embedding traffic at a
+ cloud-metadata endpoint. Mirrors the LLM-side Ollama provider.
+ """
+
+ _METADATA_URLS = (
+ "http://169.254.169.254",
+ "http://169.254.170.2",
+ "http://100.100.100.200",
+ )
+
+ def test_rejects_metadata_base_url_before_client_construction(self):
+ """A metadata-service base_url is refused and no client is built."""
+ import pytest
+
+ for base_url in self._METADATA_URLS:
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {"embeddings.ollama.num_ctx": 8192}
+ )
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ with pytest.raises(ValueError):
+ OllamaEmbeddingsProvider.create_embeddings(
+ model="nomic-embed-text",
+ base_url=base_url,
+ )
+ mock_ollama.assert_not_called()
+
+ def test_rejects_metadata_url_from_settings(self):
+ """The gap also closes when the metadata URL arrives via settings
+ (get_ollama_base_url) rather than an explicit kwarg."""
+ import pytest
+
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {"embeddings.ollama.num_ctx": 8192}
+ )
+ with patch(
+ f"{_OLLAMA_MODULE}.get_ollama_base_url",
+ return_value="http://169.254.169.254",
+ ):
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ with pytest.raises(ValueError):
+ OllamaEmbeddingsProvider.create_embeddings(
+ model="nomic-embed-text",
+ )
+ mock_ollama.assert_not_called()
+
+ def test_allows_loopback_base_url(self):
+ """Legitimate local Ollama (loopback / RFC1918) is preserved:
+ allow_localhost/allow_private_ips keep these working."""
+ for base_url in ("http://127.0.0.1:11434", "http://10.0.0.5:11434"):
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {"embeddings.ollama.num_ctx": 8192}
+ )
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_ollama:
+ mock_ollama.return_value = Mock()
+ OllamaEmbeddingsProvider.create_embeddings(
+ model="nomic-embed-text",
+ base_url=base_url,
+ )
+ call_kwargs = mock_ollama.call_args[1]
+ assert call_kwargs["base_url"] == base_url
diff --git a/tests/embeddings/test_openai_embeddings.py b/tests/embeddings/test_openai_embeddings.py
index 796362e0e5..4efe8a5c74 100644
--- a/tests/embeddings/test_openai_embeddings.py
+++ b/tests/embeddings/test_openai_embeddings.py
@@ -154,20 +154,25 @@ class TestOpenAIEmbeddingsProviderCreateEmbeddings:
return_value=None,
):
with patch(
- "langchain_openai.OpenAIEmbeddings",
- return_value=mock_embeddings,
- ) as mock_class:
- OpenAIEmbeddingsProvider.create_embeddings(
- api_key="test-key",
- base_url="https://custom.openai.com",
- )
-
- call_kwargs = mock_class.call_args[1]
- assert (
- call_kwargs["openai_api_base"]
- == "https://custom.openai.com"
- )
- assert call_kwargs["check_embedding_ctx_length"] is False
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings.OwnedOpenAIEmbeddings",
+ return_value=mock_embeddings,
+ ) as mock_class:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ api_key="test-key",
+ base_url="https://custom.openai.com",
+ )
+
+ call_kwargs = mock_class.call_args[1]
+ assert (
+ call_kwargs["openai_api_base"]
+ == "https://custom.openai.com"
+ )
+ assert call_kwargs["check_embedding_ctx_length"] is False
def test_create_embeddings_with_official_openai_base_url_keeps_ctx_check(
self,
@@ -186,7 +191,8 @@ class TestOpenAIEmbeddingsProviderCreateEmbeddings:
return_value=None,
):
with patch(
- "langchain_openai.OpenAIEmbeddings",
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings.OwnedOpenAIEmbeddings",
return_value=mock_embeddings,
) as mock_class:
OpenAIEmbeddingsProvider.create_embeddings(
@@ -219,7 +225,8 @@ class TestOpenAIEmbeddingsProviderCreateEmbeddings:
return_value=None,
):
with patch(
- "langchain_openai.OpenAIEmbeddings",
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings.OwnedOpenAIEmbeddings",
return_value=mock_embeddings,
) as mock_class:
OpenAIEmbeddingsProvider.create_embeddings(
@@ -634,6 +641,7 @@ class TestOpenAIEmbeddingsProviderGetAvailableModels:
mock_response.data = [mock_model1, mock_model2, mock_model3]
mock_client = MagicMock()
+ mock_client.__enter__.return_value = mock_client
mock_client.models.list.return_value = mock_response
def _settings(key, default=None, settings_snapshot=None):
@@ -786,12 +794,17 @@ class TestOpenAIEmbeddingsProviderCompatibleEndpoint:
),
):
with patch(
- "langchain_openai.OpenAIEmbeddings",
- return_value=MagicMock(),
- ) as mock_class:
- OpenAIEmbeddingsProvider.create_embeddings(
- model="nomic-embed-text-v1.5",
- )
+ "local_deep_research.embeddings.providers.implementations.openai.assert_base_url_safe",
+ return_value="http://host.docker.internal:1234/v1",
+ ):
+ with patch(
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings.OwnedOpenAIEmbeddings",
+ return_value=MagicMock(),
+ ) as mock_class:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="nomic-embed-text-v1.5",
+ )
call_kwargs = mock_class.call_args[1]
assert (
@@ -827,6 +840,7 @@ class TestOpenAIEmbeddingsProviderCompatibleEndpoint:
)
fake_client = MagicMock()
+ fake_client.__enter__.return_value = fake_client
fake_client.models.list.return_value = MagicMock(data=[])
with patch(
@@ -896,6 +910,7 @@ class TestOpenAIEmbeddingsProviderLMStudioModelDiscovery:
)
fake_client = MagicMock()
+ fake_client.__enter__.return_value = fake_client
fake_client.models.list.return_value = self._fake_models_response(
["nomic-embed-text-v1.5"]
)
@@ -926,6 +941,7 @@ class TestOpenAIEmbeddingsProviderLMStudioModelDiscovery:
"some-custom-finetune",
]
fake_client = MagicMock()
+ fake_client.__enter__.return_value = fake_client
fake_client.models.list.return_value = self._fake_models_response(ids)
with patch(
diff --git a/tests/embeddings/test_openai_embeddings_ssrf.py b/tests/embeddings/test_openai_embeddings_ssrf.py
new file mode 100644
index 0000000000..1affc1e261
--- /dev/null
+++ b/tests/embeddings/test_openai_embeddings_ssrf.py
@@ -0,0 +1,568 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+_BASE_URL_SETTING = "embeddings.openai.base_url"
+_BASE_URL_SSRF_ERROR = (
+ "base_url failed SSRF validation: refusing to send inference traffic. "
+ "Check embeddings.openai.base_url config."
+)
+_METADATA_BASE_URLS = (
+ "169.254.169.254/latest/meta-data",
+ "http://169.254.170.2/v2/metadata",
+ "http://100.100.100.200/latest/meta-data",
+)
+_CREATE_SETTINGS = {
+ "embeddings.openai.base_url": None,
+ "embeddings.openai.dimensions": None,
+}
+
+
+class TestOpenAIEmbeddingsProviderBaseUrlSsrf:
+ @pytest.mark.parametrize("source", ["argument", "setting", "langchain_env"])
+ def test_safe_endpoint_precedence_over_sdk_environment(
+ self, monkeypatch, source
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+ from local_deep_research.utilities.llm_utils import _close_base_llm
+
+ safe_url = "http://127.0.0.1:1234/v1"
+ blocked_url = "http://169.254.169.254/latest/meta-data"
+ monkeypatch.setenv("OPENAI_API_BASE", blocked_url)
+ monkeypatch.setenv("OPENAI_BASE_URL", blocked_url)
+ settings = dict(_CREATE_SETTINGS)
+ kwargs = {}
+ if source == "argument":
+ kwargs["base_url"] = safe_url
+ settings[_BASE_URL_SETTING] = blocked_url
+ elif source == "setting":
+ settings[_BASE_URL_SETTING] = safe_url
+ else:
+ monkeypatch.setenv("OPENAI_API_BASE", safe_url)
+
+ embeddings = OpenAIEmbeddingsProvider.create_embeddings(
+ api_key="test-key", settings_snapshot=settings, **kwargs
+ )
+ try:
+ assert str(embeddings.client._client.base_url) == safe_url + "/"
+ assert embeddings.http_client.follow_redirects is False
+ assert embeddings.http_async_client.follow_redirects is False
+ finally:
+ _close_base_llm(embeddings)
+
+ @pytest.mark.parametrize("source", ["setting", "sdk_env"])
+ def test_discovery_endpoint_precedence_and_redirect_refusal(
+ self, monkeypatch, source
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ safe_url = "http://127.0.0.1:1234/v1"
+ blocked_url = "http://169.254.169.254/latest/meta-data"
+ monkeypatch.setenv("OPENAI_API_BASE", blocked_url)
+ monkeypatch.setenv(
+ "OPENAI_BASE_URL", blocked_url if source == "setting" else safe_url
+ )
+ settings = {
+ **_CREATE_SETTINGS,
+ "embeddings.openai.api_key": "test-key",
+ _BASE_URL_SETTING: safe_url if source == "setting" else None,
+ }
+ with patch("openai.OpenAI") as client:
+ client.return_value.__enter__.return_value.models.list.return_value.data = []
+ OpenAIEmbeddingsProvider.get_available_models(
+ settings_snapshot=settings
+ )
+ kwargs = client.call_args.kwargs
+ assert kwargs["base_url"] == safe_url
+ assert kwargs["http_client"].follow_redirects is False
+ kwargs["http_client"].close()
+
+ @pytest.mark.parametrize("variable", ["OPENAI_API_BASE", "OPENAI_BASE_URL"])
+ def test_environment_endpoint_is_validated(self, monkeypatch, variable):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ monkeypatch.delenv("OPENAI_API_BASE", raising=False)
+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)
+ monkeypatch.setenv(variable, "http://169.254.169.254/latest/meta-data")
+ with patch("langchain_openai.OpenAIEmbeddings") as client:
+ with pytest.raises(ValueError, match="SSRF validation"):
+ OpenAIEmbeddingsProvider.create_embeddings(
+ api_key="test-key", settings_snapshot=_CREATE_SETTINGS
+ )
+ client.assert_not_called()
+
+ def test_discovery_validates_sdk_environment_endpoint(self, monkeypatch):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ monkeypatch.setenv(
+ "OPENAI_BASE_URL", "http://169.254.169.254/latest/meta-data"
+ )
+ with patch("openai.OpenAI") as client:
+ assert (
+ OpenAIEmbeddingsProvider.get_available_models(
+ settings_snapshot={
+ **_CREATE_SETTINGS,
+ "embeddings.openai.api_key": "test-key",
+ }
+ )
+ == []
+ )
+ client.assert_not_called()
+
+ @pytest.mark.parametrize("variable", ["OPENAI_API_BASE", "OPENAI_BASE_URL"])
+ def test_environment_endpoint_owns_redirect_refusing_clients(
+ self, monkeypatch, variable
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+ from local_deep_research.utilities.llm_utils import _close_base_llm
+
+ monkeypatch.delenv("OPENAI_API_BASE", raising=False)
+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)
+ monkeypatch.setenv(variable, "http://127.0.0.1:1234/v1")
+ embeddings = OpenAIEmbeddingsProvider.create_embeddings(
+ api_key="test-key", settings_snapshot=_CREATE_SETTINGS
+ )
+ try:
+ assert str(embeddings.client._client.base_url) == (
+ "http://127.0.0.1:1234/v1/"
+ )
+ assert embeddings.http_client is not None
+ assert embeddings.http_client.follow_redirects is False
+ assert embeddings.http_async_client.follow_redirects is False
+ finally:
+ _close_base_llm(embeddings)
+
+ @pytest.mark.parametrize(
+ "base_url",
+ _METADATA_BASE_URLS,
+ ids=("aws-imds", "ecs-metadata", "alibaba-metadata"),
+ )
+ def test_create_embeddings_rejects_metadata_url_before_client_construction(
+ self,
+ base_url,
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ with patch("openai.DefaultAsyncHttpxClient") as async_http_client:
+ with patch("openai.DefaultHttpxClient") as http_client:
+ with patch(
+ "langchain_openai.OpenAIEmbeddings"
+ ) as embeddings_class:
+ with pytest.raises(ValueError) as error:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url=base_url,
+ settings_snapshot=_CREATE_SETTINGS,
+ )
+
+ assert str(error.value) == _BASE_URL_SSRF_ERROR
+ async_http_client.assert_not_called()
+ http_client.assert_not_called()
+ embeddings_class.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "base_url",
+ _METADATA_BASE_URLS,
+ ids=("aws-imds", "ecs-metadata", "alibaba-metadata"),
+ )
+ def test_model_discovery_rejects_metadata_url_before_client_construction(
+ self,
+ base_url,
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ with patch("openai.DefaultHttpxClient") as http_client:
+ with patch("openai.OpenAI") as openai_client:
+ models = OpenAIEmbeddingsProvider.get_available_models(
+ settings_snapshot={
+ "embeddings.openai.api_key": "test-key",
+ _BASE_URL_SETTING: base_url,
+ }
+ )
+
+ assert models == []
+ http_client.assert_not_called()
+ openai_client.assert_not_called()
+
+ def test_create_embeddings_proxy_only_dns_host_fails_as_unresolved(
+ self, monkeypatch
+ ):
+ """Under a proxy, a host only the proxy can resolve is refused at
+ construction (the SSRF check resolves locally), with a message that
+ says the host could not be resolved, and no client is built."""
+ import socket
+
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ def _gaierror(*args, **kwargs):
+ raise socket.gaierror(-2, "Name or service not known")
+
+ monkeypatch.setattr(
+ "local_deep_research.security.ssrf_validator.socket.getaddrinfo",
+ _gaierror,
+ )
+ monkeypatch.setenv("OPENAI_PROXY", "http://proxy.corp.internal:3128")
+
+ with patch("openai.DefaultAsyncHttpxClient") as async_http_client:
+ with patch("openai.DefaultHttpxClient") as http_client:
+ with pytest.raises(ValueError) as error:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url="http://embeddings.corp.internal/v1",
+ settings_snapshot=_CREATE_SETTINGS,
+ )
+
+ assert "could not resolve host" in str(error.value)
+ assert _BASE_URL_SETTING in str(error.value)
+ assert "refusing to send" not in str(error.value)
+ async_http_client.assert_not_called()
+ http_client.assert_not_called()
+
+ def test_create_embeddings_disables_redirects_for_custom_base_url(self):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ sync_client = MagicMock()
+ async_client = MagicMock()
+
+ with patch(
+ "openai.DefaultAsyncHttpxClient", return_value=async_client
+ ) as async_http_client:
+ with patch(
+ "openai.DefaultHttpxClient", return_value=sync_client
+ ) as http_client:
+ with patch(
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings.OwnedOpenAIEmbeddings",
+ return_value=MagicMock(),
+ ) as embeddings_class:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url="http://localhost:1234/v1",
+ settings_snapshot=_CREATE_SETTINGS,
+ )
+
+ http_client.assert_called_once_with(follow_redirects=False)
+ async_http_client.assert_called_once_with(follow_redirects=False)
+ kwargs = embeddings_class.call_args.kwargs
+ assert kwargs["http_client"] is sync_client
+ assert kwargs["http_async_client"] is async_client
+
+ def test_create_embeddings_uses_sdk_defaults_without_custom_base_url(self):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ with patch("openai.DefaultAsyncHttpxClient") as async_http_client:
+ with patch("openai.DefaultHttpxClient") as http_client:
+ with patch(
+ "langchain_openai.OpenAIEmbeddings",
+ return_value=MagicMock(),
+ ) as embeddings_class:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ settings_snapshot=_CREATE_SETTINGS,
+ )
+
+ async_http_client.assert_not_called()
+ http_client.assert_not_called()
+ kwargs = embeddings_class.call_args.kwargs
+ assert "http_client" not in kwargs
+ assert "http_async_client" not in kwargs
+
+ @pytest.mark.parametrize(
+ "embedding_kwargs",
+ [
+ {"dimensions": "not-an-integer"},
+ {"chunk_size": "not-an-integer"},
+ ],
+ ids=("dimensions", "chunk-size"),
+ )
+ def test_invalid_numeric_settings_fail_before_custom_client_construction(
+ self, embedding_kwargs
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ with patch("openai.DefaultAsyncHttpxClient") as async_http_client:
+ with patch("openai.DefaultHttpxClient") as http_client:
+ with pytest.raises(ValueError):
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url="http://localhost:1234/v1",
+ settings_snapshot=_CREATE_SETTINGS,
+ **embedding_kwargs,
+ )
+
+ http_client.assert_not_called()
+ async_http_client.assert_not_called()
+
+ def test_model_discovery_disables_redirects_and_closes_custom_client(self):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ sync_client = MagicMock()
+ openai_client = MagicMock()
+ openai_client.__enter__.return_value = openai_client
+ openai_client.models.list.return_value = MagicMock(data=[])
+
+ with patch(
+ "openai.DefaultHttpxClient", return_value=sync_client
+ ) as http_client:
+ with patch(
+ "openai.OpenAI", return_value=openai_client
+ ) as openai_class:
+ models = OpenAIEmbeddingsProvider.get_available_models(
+ settings_snapshot={
+ "embeddings.openai.api_key": "test-key",
+ _BASE_URL_SETTING: "http://localhost:1234/v1",
+ }
+ )
+
+ assert models == []
+ http_client.assert_called_once_with(follow_redirects=False)
+ assert openai_class.call_args.kwargs["http_client"] is sync_client
+ openai_client.__enter__.assert_called_once_with()
+ openai_client.__exit__.assert_called_once_with(None, None, None)
+
+ def test_model_discovery_closes_client_when_openai_construction_fails(self):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ sync_client = MagicMock()
+
+ with patch("openai.DefaultHttpxClient", return_value=sync_client):
+ with patch(
+ "openai.OpenAI",
+ side_effect=RuntimeError("OpenAI construction failed"),
+ ):
+ models = OpenAIEmbeddingsProvider.get_available_models(
+ settings_snapshot={
+ "embeddings.openai.api_key": "test-key",
+ _BASE_URL_SETTING: "http://localhost:1234/v1",
+ }
+ )
+
+ assert models == []
+ sync_client.close.assert_called_once_with()
+
+ def test_model_discovery_closes_client_when_openai_enter_fails(self):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ sync_client = MagicMock()
+ openai_client = MagicMock()
+ openai_client.__enter__.side_effect = RuntimeError(
+ "OpenAI enter failed"
+ )
+
+ with patch("openai.DefaultHttpxClient", return_value=sync_client):
+ with patch("openai.OpenAI", return_value=openai_client):
+ models = OpenAIEmbeddingsProvider.get_available_models(
+ settings_snapshot={
+ "embeddings.openai.api_key": "test-key",
+ _BASE_URL_SETTING: "http://localhost:1234/v1",
+ }
+ )
+
+ assert models == []
+ sync_client.close.assert_called_once_with()
+
+ @pytest.mark.parametrize(
+ ("base_url", "normalized_url"),
+ [
+ ("localhost:1234/v1", "http://localhost:1234/v1"),
+ ("192.168.1.10:1234/v1", "http://192.168.1.10:1234/v1"),
+ ],
+ ids=("localhost", "rfc1918"),
+ )
+ def test_create_embeddings_preserves_safe_base_url_and_chunk_size(
+ self,
+ base_url,
+ normalized_url,
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ with patch(
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings.OwnedOpenAIEmbeddings",
+ return_value=MagicMock(),
+ ) as embeddings_class:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url=base_url,
+ chunk_size=64,
+ settings_snapshot=_CREATE_SETTINGS,
+ )
+
+ call_kwargs = embeddings_class.call_args.kwargs
+ assert call_kwargs["openai_api_base"] == normalized_url
+ assert call_kwargs["chunk_size"] == 64
+
+
+_PROXY_URL = "http://proxy.invalid:3128"
+
+
+class TestOpenAIEmbeddingsProxy:
+ """A configured proxy must neither be dropped nor re-enable redirects.
+
+ langchain refuses ``openai_proxy`` together with an explicit
+ ``http_client``, and its ``openai_proxy`` field defaults to the
+ ``OPENAI_PROXY`` env var. The provider therefore routes the proxy
+ through its own ``follow_redirects=False`` clients and pins langchain's
+ field to None.
+ """
+
+ @pytest.mark.parametrize("source", ["kwarg", "env"])
+ def test_proxy_is_routed_through_owned_redirect_refusing_clients(
+ self, source, monkeypatch
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ monkeypatch.delenv("OPENAI_PROXY", raising=False)
+ extra = {}
+ if source == "env":
+ monkeypatch.setenv("OPENAI_PROXY", _PROXY_URL)
+ else:
+ extra["openai_proxy"] = _PROXY_URL
+
+ with patch(
+ "openai.DefaultAsyncHttpxClient", return_value=MagicMock()
+ ) as async_http_client:
+ with patch(
+ "openai.DefaultHttpxClient", return_value=MagicMock()
+ ) as http_client:
+ with patch(
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings.OwnedOpenAIEmbeddings",
+ return_value=MagicMock(),
+ ) as embeddings_class:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url="http://localhost:1234/v1",
+ settings_snapshot=_CREATE_SETTINGS,
+ **extra,
+ )
+
+ expected = {"follow_redirects": False, "proxy": _PROXY_URL}
+ assert http_client.call_args.kwargs == expected
+ assert async_http_client.call_args.kwargs == expected
+ assert embeddings_class.call_args.kwargs["openai_proxy"] is None
+
+ @pytest.mark.parametrize("source", ["kwarg", "env"])
+ def test_real_instance_with_proxy_refuses_redirects(
+ self, source, monkeypatch
+ ):
+ """No mocks: langchain must accept the instance (no proxy/client
+ collision) and the SDK must use the redirect-refusing clients."""
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+ from local_deep_research.embeddings.providers.implementations.owned_openai_embeddings import (
+ OwnedOpenAIEmbeddings,
+ )
+
+ monkeypatch.delenv("OPENAI_PROXY", raising=False)
+ extra = {}
+ if source == "env":
+ monkeypatch.setenv("OPENAI_PROXY", _PROXY_URL)
+ else:
+ extra["openai_proxy"] = _PROXY_URL
+
+ embeddings = OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url="http://localhost:1234/v1",
+ settings_snapshot=_CREATE_SETTINGS,
+ **extra,
+ )
+ try:
+ assert isinstance(embeddings, OwnedOpenAIEmbeddings)
+ assert embeddings.openai_proxy is None
+ assert embeddings.client._client._client is embeddings.http_client
+ assert (
+ embeddings.async_client._client._client
+ is embeddings.http_async_client
+ )
+ assert embeddings.http_client.follow_redirects is False
+ assert embeddings.http_async_client.follow_redirects is False
+ finally:
+ embeddings.close()
+
+ def test_proxy_kwarg_is_forwarded_without_custom_base_url(
+ self, monkeypatch
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ monkeypatch.delenv("OPENAI_PROXY", raising=False)
+ with patch(
+ "langchain_openai.OpenAIEmbeddings", return_value=MagicMock()
+ ) as embeddings_class:
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ openai_proxy=_PROXY_URL,
+ settings_snapshot=_CREATE_SETTINGS,
+ )
+
+ assert embeddings_class.call_args.kwargs["openai_proxy"] == _PROXY_URL
+
+ def test_bad_timeout_setting_fails_before_custom_client_construction(
+ self,
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ with patch("openai.DefaultAsyncHttpxClient") as async_http_client:
+ with patch("openai.DefaultHttpxClient") as http_client:
+ with patch(
+ "local_deep_research.llm.providers._helpers."
+ "resolve_request_timeout",
+ side_effect=RuntimeError("bad timeout setting"),
+ ):
+ with pytest.raises(RuntimeError):
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url="http://localhost:1234/v1",
+ settings_snapshot=_CREATE_SETTINGS,
+ )
+
+ http_client.assert_not_called()
+ async_http_client.assert_not_called()
diff --git a/tests/embeddings/test_owned_openai_embeddings.py b/tests/embeddings/test_owned_openai_embeddings.py
new file mode 100644
index 0000000000..f1ad3bdad6
--- /dev/null
+++ b/tests/embeddings/test_owned_openai_embeddings.py
@@ -0,0 +1,320 @@
+import asyncio
+import threading
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import httpx
+import pytest
+
+
+_SETTINGS = {
+ "embeddings.openai.base_url": None,
+ "embeddings.openai.dimensions": None,
+}
+
+
+class _FailingClient(httpx.Client):
+ def close(self) -> None:
+ raise RuntimeError("sync close failed")
+
+
+def _build_owned_embeddings():
+ from local_deep_research.embeddings.providers.implementations.owned_openai_embeddings import (
+ OwnedOpenAIEmbeddings,
+ )
+
+ sync_client = httpx.Client()
+ async_client = httpx.AsyncClient()
+ embeddings = OwnedOpenAIEmbeddings(
+ model="text-embedding-3-small",
+ openai_api_key="test-key",
+ openai_api_base="http://localhost:1234/v1",
+ check_embedding_ctx_length=False,
+ http_client=sync_client,
+ http_async_client=async_client,
+ )
+ return embeddings, sync_client, async_client
+
+
+class TestOwnedOpenAIEmbeddings:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("mode", ["sync", "running-loop", "async"])
+ @pytest.mark.parametrize("failing", ["sync", "async"])
+ async def test_failed_cleanup_can_be_retried(self, mode, failing):
+ embeddings, sync_client, async_client = _build_owned_embeddings()
+ sync_close = sync_client.close
+ async_close = async_client.aclose
+ attempts = 0
+
+ def flaky_sync_close():
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise RuntimeError("temporary cleanup failure")
+ sync_close()
+
+ async def flaky_async_close():
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise RuntimeError("temporary cleanup failure")
+ await async_close()
+
+ async def close():
+ if mode == "async":
+ await embeddings.aclose()
+ elif mode == "sync":
+ await asyncio.to_thread(embeddings.close)
+ else:
+ embeddings.close()
+
+ target = sync_client if failing == "sync" else async_client
+ method = "close" if failing == "sync" else "aclose"
+ replacement = (
+ flaky_sync_close if failing == "sync" else flaky_async_close
+ )
+ try:
+ with patch.object(target, method, replacement):
+ await close()
+ assert not target.is_closed
+ await close()
+ assert sync_client.is_closed
+ assert async_client.is_closed
+ assert attempts == 2
+ finally:
+ sync_close()
+ await async_close()
+
+ def test_local_embedding_manager_close_closes_owned_clients(self):
+ from local_deep_research.web_search_engines.engines.local_embedding_manager import (
+ LocalEmbeddingManager,
+ )
+
+ embeddings, sync_client, async_client = _build_owned_embeddings()
+ manager = LocalEmbeddingManager()
+ manager._embeddings = embeddings
+
+ manager.close()
+
+ assert sync_client.is_closed is True
+ assert async_client.is_closed is True
+
+ @pytest.mark.asyncio
+ async def test_aclose_is_idempotent(self):
+ embeddings, sync_client, async_client = _build_owned_embeddings()
+
+ await embeddings.aclose()
+ await embeddings.aclose()
+
+ assert sync_client.is_closed is True
+ assert async_client.is_closed is True
+
+ @pytest.mark.asyncio
+ async def test_close_closes_clients_from_running_event_loop(self):
+ embeddings, sync_client, async_client = _build_owned_embeddings()
+
+ embeddings.close()
+
+ assert sync_client.is_closed is True
+ assert async_client.is_closed is True
+
+ @pytest.mark.asyncio
+ async def test_aclose_logs_client_close_error_and_closes_async_client(
+ self, loguru_caplog
+ ):
+ from local_deep_research.embeddings.providers.implementations.owned_openai_embeddings import (
+ OwnedOpenAIEmbeddings,
+ )
+
+ async_client = httpx.AsyncClient()
+ embeddings = OwnedOpenAIEmbeddings(
+ model="text-embedding-3-small",
+ openai_api_key="test-key",
+ openai_api_base="http://localhost:1234/v1",
+ check_embedding_ctx_length=False,
+ http_client=_FailingClient(),
+ http_async_client=async_client,
+ )
+
+ with loguru_caplog.at_level("WARNING"):
+ await embeddings.aclose()
+
+ assert async_client.is_closed is True
+ assert (
+ "Failed to close OpenAI embeddings sync httpx client"
+ in loguru_caplog.text
+ )
+
+ @pytest.mark.asyncio
+ async def test_close_from_running_loop_bounds_cleanup_thread(
+ self, loguru_caplog
+ ):
+ embeddings, _, _ = _build_owned_embeddings()
+ started = threading.Event()
+ release = threading.Event()
+ captured = {}
+
+ async def slow_aclose(http_client, http_async_client):
+ started.set()
+ await asyncio.get_running_loop().run_in_executor(None, release.wait)
+
+ class _ShortJoinThread(threading.Thread):
+ def join(self, timeout=None):
+ captured["timeout"] = timeout
+ return super().join(timeout=0.2)
+
+ try:
+ with loguru_caplog.at_level("WARNING"):
+ with patch(
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings._aclose_http_clients",
+ slow_aclose,
+ ):
+ with patch(
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings.threading",
+ SimpleNamespace(Thread=_ShortJoinThread),
+ ):
+ embeddings.close()
+ finally:
+ release.set()
+
+ assert started.is_set()
+ assert captured["timeout"] == 5
+ assert (
+ "OpenAI embeddings async httpx close exceeded 5s"
+ in loguru_caplog.text
+ )
+ await embeddings.aclose()
+
+
+class TestOpenAIEmbeddingsProviderRollback:
+ def test_async_client_construction_failure_closes_sync_client(self):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ sync_client = MagicMock()
+
+ with patch("openai.DefaultHttpxClient", return_value=sync_client):
+ with patch(
+ "openai.DefaultAsyncHttpxClient",
+ side_effect=RuntimeError("async client construction failed"),
+ ):
+ with pytest.raises(
+ RuntimeError, match="async client construction failed"
+ ):
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url="http://localhost:1234/v1",
+ settings_snapshot=_SETTINGS,
+ )
+
+ sync_client.close.assert_called_once_with()
+
+ def test_async_client_failure_preserves_original_error_when_cleanup_fails(
+ self, loguru_caplog
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ sync_client = MagicMock()
+ sync_client.close.side_effect = RuntimeError("sync cleanup failed")
+
+ with loguru_caplog.at_level("WARNING"):
+ with patch("openai.DefaultHttpxClient", return_value=sync_client):
+ with patch(
+ "openai.DefaultAsyncHttpxClient",
+ side_effect=RuntimeError(
+ "async client construction failed"
+ ),
+ ):
+ with pytest.raises(
+ RuntimeError, match="async client construction failed"
+ ):
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url="http://localhost:1234/v1",
+ settings_snapshot=_SETTINGS,
+ )
+
+ assert (
+ "Failed to close OpenAI embeddings sync httpx client"
+ in loguru_caplog.text
+ )
+
+ def test_embeddings_construction_failure_closes_both_clients(self):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ sync_client = MagicMock()
+ async_client = AsyncMock()
+
+ with patch("openai.DefaultHttpxClient", return_value=sync_client):
+ with patch(
+ "openai.DefaultAsyncHttpxClient", return_value=async_client
+ ):
+ with patch(
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings.OwnedOpenAIEmbeddings",
+ side_effect=RuntimeError("embeddings construction failed"),
+ ):
+ with pytest.raises(
+ RuntimeError, match="embeddings construction failed"
+ ):
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url="http://localhost:1234/v1",
+ settings_snapshot=_SETTINGS,
+ )
+
+ sync_client.close.assert_called_once_with()
+ async_client.aclose.assert_awaited_once_with()
+
+ def test_embeddings_failure_preserves_original_error_when_cleanup_fails(
+ self, loguru_caplog
+ ):
+ from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+ )
+
+ sync_client = MagicMock()
+ sync_client.close.side_effect = RuntimeError("sync cleanup failed")
+ async_client = AsyncMock()
+ async_client.aclose.side_effect = RuntimeError("async cleanup failed")
+
+ with loguru_caplog.at_level("WARNING"):
+ with patch("openai.DefaultHttpxClient", return_value=sync_client):
+ with patch(
+ "openai.DefaultAsyncHttpxClient", return_value=async_client
+ ):
+ with patch(
+ "local_deep_research.embeddings.providers.implementations."
+ "owned_openai_embeddings.OwnedOpenAIEmbeddings",
+ side_effect=RuntimeError(
+ "embeddings construction failed"
+ ),
+ ):
+ with pytest.raises(
+ RuntimeError, match="embeddings construction failed"
+ ):
+ OpenAIEmbeddingsProvider.create_embeddings(
+ model="text-embedding-3-small",
+ api_key="test-key",
+ base_url="http://localhost:1234/v1",
+ settings_snapshot=_SETTINGS,
+ )
+
+ assert (
+ "Failed to close OpenAI embeddings sync httpx client"
+ in loguru_caplog.text
+ )
+ assert (
+ "Failed to close OpenAI embeddings async httpx client"
+ in loguru_caplog.text
+ )
diff --git a/tests/llm/test_provider_base_url_ssrf.py b/tests/llm/test_provider_base_url_ssrf.py
index 250c17c2c6..5531dfbc41 100644
--- a/tests/llm/test_provider_base_url_ssrf.py
+++ b/tests/llm/test_provider_base_url_ssrf.py
@@ -124,6 +124,194 @@ def test_assert_base_url_safe_error_message_includes_setting_key():
)
+_GETADDRINFO = "local_deep_research.security.ssrf_validator.socket.getaddrinfo"
+
+
+def _raise_gaierror(*args, **kwargs):
+ import socket
+
+ raise socket.gaierror(-2, "Name or service not known")
+
+
+def test_assert_base_url_safe_unresolvable_host_says_could_not_resolve(
+ monkeypatch,
+):
+ """A host the LOCAL resolver cannot resolve (e.g. one only a proxy can
+ resolve) is still refused, but with a message that says so rather than
+ claiming the destination is blocked."""
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ monkeypatch.setattr(_GETADDRINFO, _raise_gaierror)
+ with pytest.raises(ValueError) as excinfo:
+ assert_base_url_safe(
+ "http://embeddings.corp.internal:8080/v1",
+ setting_key="embeddings.openai.base_url",
+ )
+ msg = str(excinfo.value)
+ assert "failed SSRF validation" in msg
+ assert "could not resolve host" in msg
+ assert "refusing to send" not in msg
+ assert "embeddings.openai.base_url" in msg
+
+
+ "url",
+ [
+ # Literal metadata IP: blocked without any DNS lookup.
+ "http://169.254.169.254/",
+ # Non-http(s) scheme: refused before resolution matters.
+ "ftp://unresolvable.example/",
+ # Percent-encoded numeric IPv4 host (169.254.169.254): refused by
+ # the encoded-numeric check before any DNS lookup.
+ "http://%31%36%39.%32%35%34.%31%36%39.%32%35%34/",
+ # Percent-escaped dots in a numeric host: same pre-DNS check.
+ "http://169%2e254%2e169%2e254/",
+ # Ambiguous (octal / hex) numeric IPv4 host: refused pre-DNS.
+ "http://0251.0376.0251.0376/",
+ "http://0xa9.254.169.254/",
+ # RFC-forbidden characters (backslash parser differential, space):
+ # refused by the forbidden-character check before any DNS lookup.
+ "http://evil.invalid\\@169.254.169.254/",
+ "http://ho st.invalid/",
+ ],
+)
+def test_assert_base_url_safe_blocked_host_keeps_generic_message(
+ monkeypatch, url
+):
+ """Refusals that are not a local resolution failure keep the generic
+ 'refusing to send' message, even when DNS would also fail."""
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ monkeypatch.setattr(_GETADDRINFO, _raise_gaierror)
+ with pytest.raises(ValueError) as excinfo:
+ assert_base_url_safe(url, setting_key="llm.x.url")
+ assert "refusing to send" in str(excinfo.value)
+ assert "could not resolve host" not in str(excinfo.value)
+
+
+def test_assert_base_url_safe_name_resolving_to_metadata_is_blocked_not_unresolved(
+ monkeypatch,
+):
+ """A hostname that resolves to a metadata IP is a blocked host, not an
+ unresolvable one."""
+ import socket
+
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ monkeypatch.setattr(
+ _GETADDRINFO,
+ lambda *a, **k: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("169.254.169.254", 0))
+ ],
+ )
+ with pytest.raises(ValueError) as excinfo:
+ assert_base_url_safe(
+ "http://imds.attacker.test/", setting_key="llm.x.url"
+ )
+ assert "refusing to send" in str(excinfo.value)
+ assert "could not resolve host" not in str(excinfo.value)
+
+
+def test_assert_base_url_safe_unresolvable_host_does_one_lookup(monkeypatch):
+ """The "could not resolve host" message comes from validate_url's own
+ failed lookup; no second DNS query is made to pick the message."""
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ calls = []
+
+ def _counting_gaierror(*args, **kwargs):
+ calls.append(args[0])
+ _raise_gaierror()
+
+ monkeypatch.setattr(_GETADDRINFO, _counting_gaierror)
+ with pytest.raises(ValueError, match="could not resolve host"):
+ assert_base_url_safe("http://nx.invalid/", setting_key="llm.x.url")
+ assert calls == ["nx.invalid"]
+
+
+def test_assert_base_url_safe_metadata_then_nxdomain_keeps_generic_message(
+ monkeypatch,
+):
+ """If the validating lookup resolved to a metadata IP, a later NXDOMAIN
+ (e.g. DNS rebinding) cannot relabel the refusal as a DNS problem."""
+ import socket
+
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ )
+
+ answers = iter(
+ [
+ [
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ 6,
+ "",
+ ("169.254.169.254", 0),
+ )
+ ]
+ ]
+ )
+
+ def _metadata_then_gaierror(*args, **kwargs):
+ try:
+ return next(answers)
+ except StopIteration:
+ _raise_gaierror()
+
+ monkeypatch.setattr(_GETADDRINFO, _metadata_then_gaierror)
+ with pytest.raises(ValueError) as excinfo:
+ assert_base_url_safe("http://rebind.test/", setting_key="llm.x.url")
+ assert "refusing to send" in str(excinfo.value)
+ assert "could not resolve host" not in str(excinfo.value)
+
+
+def test_assert_base_url_safe_unresolved_flag_does_not_leak(monkeypatch):
+ """A gaierror refusal from an earlier, unrelated validate_url call in the
+ same context must not relabel a later blocked-host refusal."""
+ from local_deep_research.security.ssrf_validator import (
+ assert_base_url_safe,
+ validate_url,
+ )
+
+ monkeypatch.setattr(_GETADDRINFO, _raise_gaierror)
+ assert validate_url("http://nx.invalid/") is False
+ with pytest.raises(ValueError) as excinfo:
+ assert_base_url_safe("http://169.254.169.254/", setting_key="llm.x.url")
+ assert "refusing to send" in str(excinfo.value)
+ assert "could not resolve host" not in str(excinfo.value)
+
+ # And the reverse: an unresolvable host after a blocked one.
+ with pytest.raises(ValueError, match="could not resolve host"):
+ assert_base_url_safe("http://nx.invalid/", setting_key="llm.x.url")
+
+
+def test_assert_base_url_safe_patched_validate_url_keeps_generic_message(
+ monkeypatch,
+):
+ """Callers that stub validate_url to refuse get the generic message
+ (the label requires validate_url's own resolution failure)."""
+ from local_deep_research.security import ssrf_validator
+
+ monkeypatch.setattr(_GETADDRINFO, _raise_gaierror)
+ monkeypatch.setattr(ssrf_validator, "validate_url", lambda *a, **k: False)
+ with pytest.raises(ValueError) as excinfo:
+ ssrf_validator.assert_base_url_safe(
+ "http://nx.invalid/", setting_key="llm.x.url"
+ )
+ assert "refusing to send" in str(excinfo.value)
+ assert "could not resolve host" not in str(excinfo.value)
+
+
# ---------------------------------------------------------------------
# Per-provider integration tests
# ---------------------------------------------------------------------
diff --git a/tests/notes/test_notes_api.py b/tests/notes/test_notes_api.py
index 991f3a84d2..c4ca9ba427 100644
--- a/tests/notes/test_notes_api.py
+++ b/tests/notes/test_notes_api.py
@@ -627,6 +627,7 @@ class TestIndexNoteToCollectionRoute:
collection_id = str(uuid.uuid4())
rag_service = MagicMock()
+ rag_service.__enter__.return_value = rag_service
rag_service.index_document.return_value = {
"status": "indexed",
"chunks": 3,
@@ -650,6 +651,7 @@ class TestIndexNoteToCollectionRoute:
collection_id=collection_id,
force_reindex=True,
)
+ rag_service.__exit__.assert_called_once_with(None, None, None)
def test_rag_error_result_maps_to_400_not_500(
self, monkeypatch, db_session, note_source_type
@@ -661,6 +663,7 @@ class TestIndexNoteToCollectionRoute:
note = _seed_note(db_session, note_source_type)
rag_service = MagicMock()
+ rag_service.__enter__.return_value = rag_service
rag_service.index_document.return_value = {
"status": "error",
"error": "embedding provider unavailable",
@@ -678,6 +681,7 @@ class TestIndexNoteToCollectionRoute:
assert status == 400
assert payload["success"] is False
assert payload["error"] == "embedding provider unavailable"
+ rag_service.__exit__.assert_called_once_with(None, None, None)
class TestAcceptLinkRouteErrorMapping:
diff --git a/tests/notes/test_notes_router_fastapi.py b/tests/notes/test_notes_router_fastapi.py
index 936441da5a..1798a66f82 100644
--- a/tests/notes/test_notes_router_fastapi.py
+++ b/tests/notes/test_notes_router_fastapi.py
@@ -877,6 +877,12 @@ class TestAIEndpoints:
calls.append(kwargs)
return {"status": "indexed"}
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ return False
+
monkeypatch.setattr(
"local_deep_research.web.routers.rag.get_rag_service",
lambda request, username, collection_id: _FakeRag(),
diff --git a/tests/research_library/routes/test_rag_routes_coverage_main_port.py b/tests/research_library/routes/test_rag_routes_coverage_main_port.py
index c63190ed02..56f9840b40 100644
--- a/tests/research_library/routes/test_rag_routes_coverage_main_port.py
+++ b/tests/research_library/routes/test_rag_routes_coverage_main_port.py
@@ -585,6 +585,47 @@ class TestGetCurrentSettings:
# ---------------------------------------------------------------------------
+class _ClosableEmbeddings:
+ """A real (non-Mock) embeddings stand-in with a class-level ``close()``.
+
+ ``_close_base_llm`` delegates via ``hasattr(type(llm), "close")``, which
+ a bare ``unittest.mock.Mock`` never satisfies -- ``close`` only exists
+ as an auto-generated *instance* attribute on a Mock, not on ``type(m)``.
+ A small real class is required to exercise that delegation path.
+ """
+
+ def __init__(self, error: "Exception | None" = None):
+ self.error = error
+ self.close_calls = 0
+ self.embedded_texts: list = []
+
+ def embed_documents(self, texts):
+ self.embedded_texts.append(list(texts))
+ if self.error is not None:
+ raise self.error
+ return [[0.1, 0.2, 0.3]]
+
+ def close(self):
+ self.close_calls += 1
+
+
+def _distinct_close_error():
+ """A close() failure the route would answer differently from an embed
+ failure: a policy denial maps to a 400 with a ``reason_code``, while a
+ builtin embed error maps to the generic 500. If the route let the
+ close() error escape, the response shape would change and these tests
+ would fail -- a bare RuntimeError would not, since main's CWE-209
+ formatter returns the same fixed text for every builtin exception."""
+ from local_deep_research.security.egress.policy import (
+ Decision,
+ PolicyDeniedError,
+ )
+
+ return PolicyDeniedError(
+ Decision(False, "embeddings_model_not_curated"), target="synthetic"
+ )
+
+
class TestTestEmbedding:
"""Ported from ...::TestTestEmbedding.
@@ -627,12 +668,12 @@ class TestTestEmbedding:
def test_success(self):
from local_deep_research.web.routers.rag import test_embedding
- inner_func = Mock(return_value=[[0.1, 0.2, 0.3]])
- mock_get_ef = Mock(return_value=inner_func)
+ embeddings = _ClosableEmbeddings()
+ mock_get_embeddings = Mock(return_value=embeddings)
with (
_route_env(),
- patch(f"{_EMBEDDINGS}.get_embedding_function", mock_get_ef),
+ patch(f"{_EMBEDDINGS}.get_embeddings", mock_get_embeddings),
):
data = asyncio.run(
test_embedding(
@@ -649,15 +690,147 @@ class TestTestEmbedding:
assert data["success"] is True
assert data["dimension"] == 3
+ def test_success_closes_embedding_owner(self):
+ """``test_embedding`` must close() the embeddings instance it built
+ (via ``_close_base_llm``) after use, success or failure, so the
+ per-instance httpx client(s) created for this one-shot test don't
+ leak. Mirrors the LLM-side pattern in ``_close_base_llm``.
+
+ ``_close_base_llm`` special-cases anything whose CLASS (not just
+ instance) defines ``close()`` and delegates straight to it -- a
+ bare ``Mock()`` does not satisfy that (``type(Mock()).close``
+ doesn't exist; only the auto-generated instance attribute does),
+ hence the small real class below rather than a Mock.
+ """
+ from local_deep_research.web.routers.rag import test_embedding
+
+ embeddings = _ClosableEmbeddings()
+ mock_get_embeddings = Mock(return_value=embeddings)
+
+ with (
+ _route_env(),
+ patch(f"{_EMBEDDINGS}.get_embeddings", mock_get_embeddings),
+ ):
+ data = asyncio.run(
+ test_embedding(
+ _json_request(
+ {
+ "provider": "sentence_transformers",
+ "model": "test-model",
+ }
+ ),
+ username="testuser",
+ )
+ )
+
+ assert data["success"] is True
+ assert embeddings.close_calls == 1
+
+ def test_embed_failure_still_closes_embedding_owner(self):
+ """A failure inside ``embed_documents`` must not skip cleanup."""
+ from local_deep_research.web.routers.rag import test_embedding
+
+ embeddings = _ClosableEmbeddings(error=RuntimeError("provider failed"))
+ mock_get_embeddings = Mock(return_value=embeddings)
+
+ with (
+ _route_env(),
+ patch(f"{_EMBEDDINGS}.get_embeddings", mock_get_embeddings),
+ ):
+ resp = asyncio.run(
+ test_embedding(
+ _json_request(
+ {
+ "provider": "sentence_transformers",
+ "model": "test-model",
+ }
+ ),
+ username="testuser",
+ )
+ )
+
+ assert resp.status_code == 500
+ assert embeddings.close_calls == 1
+
+ def test_close_failure_does_not_mask_successful_response(self):
+ """A broken close() must not turn a successful embed into a 500."""
+ from local_deep_research.web.routers.rag import test_embedding
+
+ embeddings = _ClosableEmbeddings()
+
+ with (
+ _route_env(),
+ patch(
+ f"{_EMBEDDINGS}.get_embeddings",
+ Mock(return_value=embeddings),
+ ),
+ patch(
+ "local_deep_research.utilities.llm_utils._close_base_llm",
+ side_effect=_distinct_close_error(),
+ ),
+ ):
+ data = asyncio.run(
+ test_embedding(
+ _json_request(
+ {
+ "provider": "sentence_transformers",
+ "model": "test-model",
+ }
+ ),
+ username="testuser",
+ )
+ )
+
+ assert data["success"] is True
+ assert data["dimension"] == 3
+
+ def test_close_failure_does_not_mask_embedding_error_response(self):
+ """A broken close() must not clobber the original embed error."""
+ from local_deep_research.web.routers.rag import test_embedding
+
+ embeddings = _ClosableEmbeddings(error=RuntimeError("provider failed"))
+
+ with (
+ _route_env(),
+ patch(
+ f"{_EMBEDDINGS}.get_embeddings",
+ Mock(return_value=embeddings),
+ ),
+ patch(
+ "local_deep_research.utilities.llm_utils._close_base_llm",
+ side_effect=_distinct_close_error(),
+ ),
+ ):
+ resp = asyncio.run(
+ test_embedding(
+ _json_request(
+ {
+ "provider": "sentence_transformers",
+ "model": "test-model",
+ }
+ ),
+ username="testuser",
+ )
+ )
+
+ # The embed error (a builtin RuntimeError) gets the generic 500;
+ # had the close() policy denial replaced it, this would be a 400
+ # carrying a reason_code.
+ assert resp.status_code == 500
+ data = _body(resp)
+ assert "reason_code" not in data
+ assert "unexpected error" in data["error"]
+
def test_uses_server_owned_probe_text(self):
"""Reverting to request test_text sends caller content to the provider."""
from local_deep_research.web.routers.rag import test_embedding
- inner_func = Mock(return_value=[[0.1, 0.2]])
+ embeddings = _ClosableEmbeddings()
with (
_route_env(),
patch(
- f"{_EMBEDDINGS}.get_embedding_function", return_value=inner_func
+ f"{_EMBEDDINGS}.get_embeddings",
+ Mock(return_value=embeddings),
),
patch(f"{MODULE}._EMBEDDING_TEST_SENTENCE", "server-owned"),
):
@@ -673,8 +846,10 @@ class TestTestEmbedding:
username="testuser",
)
)
+
assert data["success"] is True
- inner_func.assert_called_once_with(["server-owned"])
+ assert embeddings.embedded_texts == [["server-owned"]]
+ assert embeddings.close_calls == 1
@pytest.mark.parametrize(
("reason", "expected"),
@@ -722,7 +897,7 @@ class TestTestEmbedding:
denial = PolicyDeniedError(Decision(False, reason), target="synthetic")
with (
_route_env(),
- patch(f"{_EMBEDDINGS}.get_embedding_function", side_effect=denial),
+ patch(f"{_EMBEDDINGS}.get_embeddings", side_effect=denial),
):
response = asyncio.run(
test_embedding(
diff --git a/tests/security/test_api_key_leakage.py b/tests/security/test_api_key_leakage.py
index 14d0f63559..dfe500115d 100644
--- a/tests/security/test_api_key_leakage.py
+++ b/tests/security/test_api_key_leakage.py
@@ -444,9 +444,18 @@ class TestOpenAIEmbeddingProviderKeyLeakage:
raise exc
class _FakeOpenAI:
+ # Context-manager protocol: discovery uses ``with OpenAI(...)``.
+ # Without it the ``with`` raises TypeError before models.list()
+ # and the key-bearing exception below is never logged at all.
def __init__(self, **kwargs):
self.models = _Models()
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc_info):
+ return False
+
with loguru_caplog_full.at_level("DEBUG"):
with patch(
"local_deep_research.embeddings.providers.implementations."
@@ -467,6 +476,8 @@ class TestOpenAIEmbeddingProviderKeyLeakage:
assert (
"Error fetching OpenAI embedding models" in loguru_caplog_full.text
)
+ # Sanity: models.list() was reached and its (redacted) message logged.
+ assert "upstream proxy echoed Authorization" in loguru_caplog_full.text
class TestSearchEngineKeyLeakage:
diff --git a/tests/security/test_library_rag_security_fastapi.py b/tests/security/test_library_rag_security_fastapi.py
index 7237e8bc8f..d37faa83b0 100644
--- a/tests/security/test_library_rag_security_fastapi.py
+++ b/tests/security/test_library_rag_security_fastapi.py
@@ -772,15 +772,18 @@ class TestTestEmbeddingEndpointDoesNotLeak:
malformed-body 400, which returns before ``_format_test_embedding_error``
is reached. This class now pins the HTTP wiring.
- ``get_embedding_function`` is patched at its definition site
- (``embeddings.embeddings_config``) because the route imports it inside the
- handler body, so the patch is picked up per request. Nothing else is
+ ``get_embeddings`` (not ``get_embedding_function``) is patched at its
+ definition site (``embeddings.embeddings_config``) because the route
+ imports it inside the handler body, so the patch is picked up per
+ request. The route calls ``get_embeddings`` directly -- rather than the
+ ``get_embedding_function`` wrapper -- so the returned instance is
+ reachable for ``_close_base_llm`` cleanup after the test embed; see
+ ``local_deep_research.web.routers.rag.test_embedding``. Nothing else is
mocked: real auth, real CSRF, real settings load, real response.
"""
_PATCH_TARGET = (
- "local_deep_research.embeddings.embeddings_config."
- "get_embedding_function"
+ "local_deep_research.embeddings.embeddings_config.get_embeddings"
)
def test_internal_error_does_not_put_a_server_path_in_the_response(
@@ -847,9 +850,11 @@ class TestTestEmbeddingEndpointDoesNotLeak:
"""
client, _, _ = library_client
- with patch(
- self._PATCH_TARGET, return_value=lambda texts: [[0.1, 0.2, 0.3]]
- ):
+ class _FakeEmbeddings:
+ def embed_documents(self, texts):
+ return [[0.1, 0.2, 0.3]]
+
+ with patch(self._PATCH_TARGET, return_value=_FakeEmbeddings()):
resp = client.post(
"/library/api/rag/test-embedding",
json={"provider": "ollama", "model": "nomic-embed-text"},
diff --git a/tests/security/test_ollama_redirects_disabled.py b/tests/security/test_ollama_redirects_disabled.py
new file mode 100644
index 0000000000..4cc9c3ac24
--- /dev/null
+++ b/tests/security/test_ollama_redirects_disabled.py
@@ -0,0 +1,83 @@
+"""Ollama clients must refuse HTTP redirects.
+
+``assert_base_url_safe`` validates the configured Ollama URL once, at
+construction. ``ollama.Client`` defaults ``follow_redirects=True``, so an
+allowed host answering 307 -> ``http://169.254.169.254/...`` would carry
+every request (and the bearer header) to the metadata endpoint the check
+refuses when it is named directly. These tests build the real langchain
+objects (no network: the clients are created eagerly but never used) and
+read the flag off the underlying httpx clients.
+"""
+
+from unittest.mock import patch
+
+from local_deep_research.embeddings.providers.implementations.ollama import (
+ OllamaEmbeddingsProvider,
+)
+from local_deep_research.llm.providers.implementations.ollama import (
+ OllamaProvider,
+)
+from local_deep_research.utilities.llm_utils import _close_base_llm
+
+_EMBED_MODULE = (
+ "local_deep_research.embeddings.providers.implementations.ollama"
+)
+_LLM_MODULE = "local_deep_research.llm.providers.implementations.ollama"
+
+
+def _getter(values):
+ def _get(key, default=None, *args, **kwargs):
+ return values.get(key, default)
+
+ return _get
+
+
+def _assert_inner_clients_refuse_redirects(instance):
+ assert instance._client._client.follow_redirects is False
+ assert instance._async_client._client.follow_redirects is False
+
+
+def test_ollama_embeddings_clients_refuse_redirects():
+ values = {
+ "embeddings.ollama.model": "nomic-embed-text",
+ "embeddings.ollama.num_ctx": 8192,
+ }
+ with (
+ patch(
+ f"{_EMBED_MODULE}.get_setting_from_snapshot",
+ side_effect=_getter(values),
+ ),
+ patch(
+ f"{_EMBED_MODULE}.get_ollama_base_url",
+ return_value="http://localhost:11434",
+ ),
+ ):
+ embeddings = OllamaEmbeddingsProvider.create_embeddings(
+ settings_snapshot=values
+ )
+ try:
+ assert embeddings.client_kwargs["follow_redirects"] is False
+ _assert_inner_clients_refuse_redirects(embeddings)
+ finally:
+ _close_base_llm(embeddings)
+
+
+def test_ollama_chat_clients_refuse_redirects():
+ values = {
+ "llm.ollama.url": "http://localhost:11434",
+ "llm.local_context_window_size": 8192,
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 4096,
+ }
+ with patch(
+ f"{_LLM_MODULE}.get_setting_from_snapshot",
+ side_effect=_getter(values),
+ ):
+ llm = OllamaProvider.create_llm(
+ model_name="llama3.1:8b", settings_snapshot=values
+ )
+ try:
+ assert llm.client_kwargs["follow_redirects"] is False
+ _assert_inner_clients_refuse_redirects(llm)
+ finally:
+ _close_base_llm(llm)
diff --git a/tests/security/test_url_context_redaction.py b/tests/security/test_url_context_redaction.py
index a5ab61781e..4d6927c1e1 100644
--- a/tests/security/test_url_context_redaction.py
+++ b/tests/security/test_url_context_redaction.py
@@ -227,7 +227,17 @@ class TestOllamaBaseUrlRedaction:
def test_create_embeddings_info_redacts_basic_auth(self, loguru_caplog):
cred_url = "https://user:[email protected]"
- with patch(f"{OLLAMA_MODULE}.OllamaEmbeddings") as mock_inner:
+ # This test pins log redaction, not the SSRF gate (which has its own
+ # coverage in test_ollama_embeddings.py). The gate would otherwise
+ # reject the unresolvable ``ollama.example.com`` host before the
+ # redacted info log fires, so stub it to a pass-through here.
+ with (
+ patch(f"{OLLAMA_MODULE}.OllamaEmbeddings") as mock_inner,
+ patch(
+ f"{OLLAMA_MODULE}.assert_base_url_safe",
+ side_effect=lambda url, **_kwargs: url,
+ ),
+ ):
mock_inner.return_value = Mock()
from local_deep_research.embeddings.providers.implementations.ollama import (
OllamaEmbeddingsProvider,
diff --git a/tests/settings/env_vars/test_env_var_usage.py b/tests/settings/env_vars/test_env_var_usage.py
index 36ffe1f41f..6edb042ab9 100755
--- a/tests/settings/env_vars/test_env_var_usage.py
+++ b/tests/settings/env_vars/test_env_var_usage.py
@@ -54,6 +54,7 @@ ALLOWED_PATTERNS = {
"fastapi_app.py", # Reads LDR_EXPOSE_DOCS at module init before SettingsManager is available
"routers/rag.py", # Reads LDR_LOCAL_INDEX_ROOTS for the security path-allowlist check (enforcement path)
"web/app.py", # Reads TRUST_PROXY_HEADERS before uvicorn starts; no SettingsManager available yet
+ "embeddings/providers/implementations/openai.py", # Validates SDK endpoint env vars and routes OPENAI_PROXY through redirect-refusing clients
# Database and migrations
"alembic/",
"migrations/",