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.

harden(search): validate engine instance URLs against egress scope (#5560)

LearningCircuita961ce5760f2
diff --git a/changelog.d/+harden-searxng-url-egress-guard.security.md b/changelog.d/+harden-searxng-url-egress-guard.security.md
new file mode 100644
index 0000000000..57362f14e1
--- /dev/null
+++ b/changelog.d/+harden-searxng-url-egress-guard.security.md
@@ -0,0 +1,3 @@
+Harden user-editable public search-engine instance URLs against SSRF. A public engine URL (e.g. the SearXNG `instance_url`) that points at a private, loopback, or link-local address is now rejected at save time, and by default such an instance is no longer fetched at runtime. Whether the engine may reach a private instance is an operator decision only (the opt-in / env-locked cases below); it is deliberately never granted by the user-editable `policy.egress_scope` setting. Operators who self-host SearXNG on localhost/LAN can opt back in with `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true`; Docker deployments that env-lock the URL are unaffected, and cloud-metadata endpoints remain blocked regardless.
+
+**Upgrade note:** the default `http://localhost:8080` SearXNG instance is a loopback URL, so after this change it is refused unless you opt in. If your self-hosted SearXNG stops returning results, set `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true` (or env-lock the URL). The engine now logs a warning naming that flag when it disables itself for this reason.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 642192d782..8e05afb064 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -40,6 +40,7 @@ They are not available in the Web UI because they are needed to start the applic
| `LDR_NOTIFICATIONS_ALLOW_OUTBOUND` | Boolean | `False` | No | | Master switch for outbound notification webhooks (Apprise). Disabled by default because Apprise re-resolves DNS at send time, leaving a DNS-rebinding TOCTOU window that cannot be closed in code (Apprise exposes no Session/DNS hook). See SECURITY.md 'Notification Webhook SSRF' for details. Set to true only after reviewing the residual risk. Distinct from the per-user notifications.enabled toggle in the settings UI: this is the server-level operator gate, env-only so it cannot be flipped via the user-writable settings API. | Security | |
| `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS` | Boolean | `False` | No | | Allow notification webhooks to target private/local IP addresses. Environment-only to prevent SSRF bypass via the user-writable settings API. Only enable this if your notification endpoints are on a trusted local network. | Security | |
| `LDR_POLICY_ALLOW_UNPROTECTED_EGRESS` | Boolean | `False` | No | | Allow users to select the UNPROTECTED egress scope. Disabled by default; this is an environment-only operator gate and cannot be changed through the user-writable settings API. Hard SSRF and cloud-metadata protections remain active when enabled. | Security | |
+| `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS` | Boolean | `False` | No | | Allow user-editable PUBLIC search-engine URLs (e.g. the SearXNG instance_url) to point at private / loopback / link-local addresses. Environment-only operator gate so it cannot be flipped through the user-writable settings API. Disabled by default: a public-nature engine (its data source is the public internet) pointed at an internal host lets any authenticated user turn a research run into an internal port scan / service probe, breaking the PUBLIC_ONLY egress promise. Enable only when you self-host SearXNG on localhost/LAN and accept that engine fetches may reach your private network. Docker deployments instead pin the URL directly via LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL, which is trusted as operator-provisioned. Cloud-metadata endpoints (ALWAYS_BLOCKED_METADATA_IPS) stay blocked regardless of this flag. | Security | |
| `LDR_SECURITY_ALLOW_NAT64` | Boolean | `False` | No | | Allow outbound traffic to NAT64 prefixes (64:ff9b::/96 RFC 6052 well-known and 64:ff9b:1::/48 RFC 8215 local-use). Disabled by default to close the IPv6-wrapped SSRF bypass class — on hosts configured with NAT64 routes, attacker-supplied URLs can wrap cloud-metadata or RFC1918 destinations through these prefixes. Enable only on IPv6-only deployments (DNS64+NAT64) where outbound IPv4 traffic is synthesized through this prefix and the operator has accepted the residual SSRF risk. 6to4 (2002::/16), Teredo (2001::/32), and the discard prefix (100::/64) remain unconditionally blocked because they have no live legitimate use in 2026. The cloud-metadata block (ALWAYS_BLOCKED_METADATA_IPS) still applies via embedded-IPv4 extraction — see SECURITY.md. | Security | |
| `LDR_SECURITY_CORS_ALLOWED_ORIGINS` | String | `None` | No | | Allowed CORS origins for API routes (comma-separated). Use '*' for all origins, empty for same-origin only. Example: 'https://example.com,https://app.example.com' | Security | |
| `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` | String | `None` | No | | Allowed origins for WebSocket/Socket.IO connections (comma-separated). Unset or empty means same-origin only (default); use '*' to allow all origins. Example: 'https://example.com,https://app.example.com' | Security | |
@@ -116,7 +117,7 @@ They are not available in the Web UI because they are needed to start the applic
| `langgraph_agent.include_sub_research` | `LDR_LANGGRAPH_AGENT_INCLUDE_SUB_RESEARCH` | `true` | Enable parallel subagent research. When enabled, the agent can decompose complex questions into subtopics and research them simultaneously using separate subagents. | SEARCH |
| `langgraph_agent.max_iterations` | `LDR_LANGGRAPH_AGENT_MAX_ITERATIONS` | `50` | Maximum number of agent reasoning cycles (each cycle = one LLM call + one tool call). Higher values let the agent search more thoroughly but use more tokens. The agent typically needs 10-20 cycles for simple queries and 30-50 for complex multi-faceted research. | SEARCH |
| `langgraph_agent.max_sub_iterations` | `LDR_LANGGRAPH_AGENT_MAX_SUB_ITERATIONS` | `8` | Maximum reasoning cycles per subagent when researching subtopics in parallel. Each subagent investigates one aspect of the question independently. | SEARCH |
-| `langgraph_agent.max_subagent_workers` | `LDR_LANGGRAPH_AGENT_MAX_SUBAGENT_WORKERS` | `4` | Maximum number of subagents that may run in parallel when the lead agent fans out subtopics via research_subtopic. Each worker thread serves one subagent at a time; any surplus subtopics queue and start as workers free up (a queued subagent keeps its own per-task budget — it is NOT killed by a shared loop timer). Tune this to match what your LLM backend can sustain in parallel (Ollama / LMStudio / llama.cpp `OLLAMA_NUM_PARALLEL`, an OpenAI tier limit, etc.). Lower values reduce load; higher values increase parallelism at the cost of more concurrent LLM/search traffic. | SEARCH |
+| `langgraph_agent.max_subagent_workers` | `LDR_LANGGRAPH_AGENT_MAX_SUBAGENT_WORKERS` | `4` | Maximum number of subagents that may run in parallel when the lead agent fans out subtopics via research_subtopic. The effective pool is capped at the preferred per-call size of 5; values above 5 do not increase concurrency. Each worker thread serves one subagent at a time; any surplus subtopics queue and start as workers free up (a queued subagent keeps its own per-task budget — it is NOT killed by a shared loop timer). Tune this to match what your LLM backend can sustain in parallel (Ollama / LMStudio / llama.cpp `OLLAMA_NUM_PARALLEL`, an OpenAI tier limit, etc.). Lower values reduce load; higher values up to 5 increase parallelism at the cost of more concurrent LLM/search traffic. | SEARCH |
| `llm.allowed_local_hostnames` | `LDR_LLM_ALLOWED_LOCAL_HOSTNAMES` | ``[]`` | Hostnames the policy will treat as local in addition to loopback / RFC1918 / link-local. Use for self-hosted services on custom hostnames (e.g. 'ollama.lan'). Public hostnames added here are rejected at save time. | LLM |
| `llm.anthropic.api_key` | `LDR_LLM_ANTHROPIC_API_KEY` | `` | Your Anthropic API key for Claude models. Get one at console.anthropic.com. Required when using the Anthropic provider. | LLM |
| `llm.anthropic_endpoint.api_key` | `LDR_LLM_ANTHROPIC_ENDPOINT_API_KEY` | `` | Optional API key for your Anthropic-compatible endpoint. Leave blank for self-hosted servers that don't require authentication. | LLM |
@@ -432,7 +433,7 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.searxng.default_params.categories` | `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_CATEGORIES` | ``["general"]`` | SearXNG search categories to use (general, images, videos, news, music, files, etc.). | SEARCH |
| `search.engine.web.searxng.default_params.delay_between_requests` | `SEARXNG_DELAY` | `0` | Seconds to wait between SearXNG requests. Set higher values to avoid rate limiting on public instances. | SEARCH |
| `search.engine.web.searxng.default_params.include_full_content` | `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INCLUDE_FULL_CONTENT` | `true` | Fetch full webpage content for SearXNG results, not just snippets. | SEARCH |
-| `search.engine.web.searxng.default_params.instance_url` | `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL` | `http://localhost:8080` | The SearXNG API endpoint URL. | SEARCH |
+| `search.engine.web.searxng.default_params.instance_url` | `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL` | `http://localhost:8080` | The SearXNG API endpoint URL. A private / loopback / link-local URL (including the default http://localhost:8080) is only fetched when the operator sets LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true or env-locks this URL via LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL; otherwise the engine disables itself. Cloud-metadata addresses are always blocked. | SEARCH |
| `search.engine.web.searxng.default_params.language` | `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_LANGUAGE` | `en` | Language code for SearXNG results (e.g., 'en', 'de', 'fr'). | SEARCH |
| `search.engine.web.searxng.default_params.max_results` | `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_MAX_RESULTS` | `15` | Maximum number of results to retrieve from SearXNG per search. | SEARCH |
| `search.engine.web.searxng.default_params.result_format` | `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_RESULT_FORMAT` | `html` | Response format to request from SearXNG. Use 'json' for instances that enable the JSON API but disable HTML output; 'html' scrapes the results page. | SEARCH |
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 800797df43..0f250239c4 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -2631,7 +2631,7 @@
},
"search.engine.web.searxng.default_params.instance_url": {
"category": "searxng",
- "description": "The SearXNG API endpoint URL.",
+ "description": "The SearXNG API endpoint URL. A private / loopback / link-local URL (including the default http://localhost:8080) is only fetched when the operator sets LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true or env-locks this URL via LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL; otherwise the engine disables itself. Cloud-metadata addresses are always blocked.",
"editable": true,
"max_value": null,
"min_value": null,
diff --git a/src/local_deep_research/security/egress/validators.py b/src/local_deep_research/security/egress/validators.py
index 6e34a69b61..7d3bdbe939 100644
--- a/src/local_deep_research/security/egress/validators.py
+++ b/src/local_deep_research/security/egress/validators.py
@@ -10,6 +10,11 @@ The settings write routes (``web/routes/settings_routes.py``) orchestrate these
but the egress rules themselves live here next to the policy they encode.
"""
+import ipaddress
+from typing import Optional
+from urllib.parse import unquote, urlsplit
+
+from ...utilities.type_utils import unwrap_setting
from .policy import (
EgressContext,
EgressScope,
@@ -19,6 +24,12 @@ from .policy import (
parse_user_egress_scope,
)
+# The SearXNG instance URL is the canonical exploitable case and is always
+# guarded even if dynamic engine-class enumeration fails below.
+_SEARXNG_INSTANCE_URL_KEY = (
+ "search.engine.web.searxng.default_params.instance_url"
+)
+
def validate_egress_scope(form_data, _all_db_settings):
"""Validate the scope and enforce the operator-controlled escape hatch."""
@@ -177,6 +188,294 @@ def validate_trusted_search_engines(form_data, all_db_settings):
return None
+_PUBLIC_ENGINE_URL_SETTINGS_CACHE: Optional[frozenset] = None
+
+
+def _public_engine_url_settings() -> frozenset:
+ """URL-setting keys belonging to PUBLIC-nature search engines.
+
+ These are the engine URLs a save-time SSRF check must guard: a public
+ engine (SearXNG) proxies the public web, so a private/loopback
+ ``instance_url`` is only ever an internal-network probe target, never a
+ legitimate data source. LOCAL engines (Elasticsearch, Paperless) are
+ deliberately EXCLUDED — a private URL is their whole purpose, and the PDP's
+ fail-up URL override already reclassifies them public when pointed at an
+ external host.
+
+ Derived once from the engine registry so any future public engine with a
+ configurable URL is covered automatically; seeded with the SearXNG key so
+ the guard holds even if class loading breaks.
+ """
+ global _PUBLIC_ENGINE_URL_SETTINGS_CACHE
+ if _PUBLIC_ENGINE_URL_SETTINGS_CACHE is not None:
+ return _PUBLIC_ENGINE_URL_SETTINGS_CACHE
+ keys = {_SEARXNG_INSTANCE_URL_KEY}
+ try:
+ from ...web_search_engines.engine_registry import ENGINE_REGISTRY
+ from .policy import _get_engine_class
+
+ for name in ENGINE_REGISTRY:
+ cls = _get_engine_class(name)
+ if cls is None:
+ continue
+ if getattr(cls, "is_public", None) is True:
+ url_setting = getattr(cls, "url_setting", None)
+ if isinstance(url_setting, str) and url_setting:
+ keys.add(url_setting)
+ except Exception: # noqa: silent-exception - seed set still guards SearXNG
+ pass
+ _PUBLIC_ENGINE_URL_SETTINGS_CACHE = frozenset(keys)
+ return _PUBLIC_ENGINE_URL_SETTINGS_CACHE
+
+
+def _engine_url_ssrf_error(key, value, *, allow_private: bool):
+ """Return an error dict for a public-engine URL that must be refused.
+
+ Rejects:
+ - a non-http(s) scheme (never a valid engine URL — refused even when the
+ operator opt-in is set),
+ - a host that IS or RESOLVES TO a cloud-metadata / always-blocked
+ address (refused regardless of the operator opt-in), and
+ - unless ``allow_private`` is set, a host that IS or RESOLVES TO a
+ private / loopback / link-local address.
+
+ Reuses ``ssrf_validator.is_ip_blocked`` for the classification: the
+ ``allow_localhost=True, allow_private_ips=True`` form isolates the
+ always-blocked cloud-metadata set, so metadata stays refused even under the
+ operator opt-in. Returns ``None`` when the value is not a URL string (type
+ validation handles that elsewhere).
+
+ Fail-open on transient resolution failure (DNS down / split-horizon): only
+ names that actually resolve to a blocked address are rejected, so a
+ legitimate public host stays saveable during a DNS hiccup — mirroring
+ ``validate_allowed_local_hostnames``.
+ """
+ if not isinstance(value, str) or not value.strip():
+ return None
+ url = value.strip()
+
+ from ..ssrf_validator import RFC_FORBIDDEN_URL_CHARS_RE, is_ip_blocked
+
+ if RFC_FORBIDDEN_URL_CHARS_RE.search(url):
+ return {
+ "key": key,
+ "error": f"{key} contains illegal URL characters",
+ }
+ try:
+ parsed = urlsplit(url)
+ except Exception:
+ return {"key": key, "error": f"{key} is not a valid URL"}
+
+ if (parsed.scheme or "").lower() not in ("http", "https"):
+ return {
+ "key": key,
+ "error": f"{key} must be an http:// or https:// URL",
+ }
+
+ host = parsed.hostname
+ if not host:
+ return {"key": key, "error": f"{key} has no hostname"}
+ host = unquote(host)
+ if host.startswith("[") and host.endswith("]"):
+ host = host[1:-1]
+ host = host.rstrip(".")
+
+ def _block_reason(ip_str) -> Optional[str]:
+ # Cloud-metadata / always-blocked set: refused regardless of opt-in.
+ if is_ip_blocked(ip_str, allow_localhost=True, allow_private_ips=True):
+ return "metadata"
+ # Private / loopback / link-local: refused unless operator opted in.
+ if not allow_private and is_ip_blocked(
+ ip_str, allow_localhost=False, allow_private_ips=False
+ ):
+ return "private"
+ return None
+
+ try:
+ ipaddress.ip_address(host)
+ is_literal_ip = True
+ except ValueError:
+ is_literal_ip = False
+
+ if is_literal_ip:
+ reason = _block_reason(host)
+ return _engine_url_error(key, reason) if reason else None
+
+ addr_info = _resolve_with_timeout(host)
+ if not addr_info:
+ return None # fail-open on unresolvable host
+ for entry in addr_info:
+ try:
+ ip_str = entry[4][0]
+ except (IndexError, TypeError):
+ continue
+ reason = _block_reason(ip_str)
+ if reason:
+ return _engine_url_error(key, reason)
+ return None
+
+
+def _engine_url_error(key, reason):
+ if reason == "metadata":
+ message = (
+ f"{key} points at a cloud-metadata / always-blocked address, "
+ "which is never a permitted destination."
+ )
+ else:
+ message = (
+ f"{key} points at a private, loopback, or link-local address. A "
+ "public search engine proxies the internet, so an internal URL is "
+ "refused to prevent it being used to reach your private network. "
+ "To self-host on localhost/LAN, set the "
+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS operator environment "
+ "variable."
+ )
+ return {"key": key, "error": message}
+
+
+# Sentinel marking a guarded key that has no stored value yet — treated as a
+# genuine change so a brand-new setting is still validated.
+_NO_STORED_VALUE = object()
+
+
+def _stored_engine_url_value(all_db_settings, key):
+ """Return the currently-stored value for ``key`` in ``all_db_settings``.
+
+ Entries are ``Setting`` ORM rows exposing the value via ``.value`` in the
+ live save routes (``_filter_editable_settings`` builds ``{key: Setting}``),
+ but some callers hand plain ``{"value": ...}`` dicts. Normalize both to the
+ scalar with ``unwrap_setting`` — the dict form directly, an ORM/attribute
+ row via its ``.value``. Returns ``_NO_STORED_VALUE`` when the key is absent.
+ """
+ if not all_db_settings or key not in all_db_settings:
+ return _NO_STORED_VALUE
+ entry = all_db_settings[key]
+ if not isinstance(entry, dict):
+ entry = getattr(entry, "value", _NO_STORED_VALUE)
+ if entry is _NO_STORED_VALUE:
+ return _NO_STORED_VALUE
+ return unwrap_setting(entry)
+
+
+def _normalize_engine_url_for_comparison(value):
+ """Parse ``value`` into a tuple of URL parts for cosmetic-variant
+ comparison, or ``None`` if it cannot be parsed as a URL.
+
+ Collapses only variation that denotes the exact SAME url:
+ - scheme and host case (``HTTP://LOCALHOST`` == ``http://localhost``),
+ - a single trailing slash on the path (``rstrip("/")`` also makes an
+ empty path and ``"/"`` compare equal).
+
+ Everything that could denote a DIFFERENT destination is preserved
+ verbatim and NOT normalized away: the host itself, the port, any path
+ beyond a bare trailing slash, the query, the fragment, and any userinfo
+ (unusual in an ``instance_url``, but kept rather than risk folding two
+ distinct credentials together). In particular this never strips the
+ host, resolves DNS, or drops the port — so a genuine change to a
+ different host/port/scheme still fails to compare equal here.
+
+ Returns ``None`` on any parse failure (e.g. a non-numeric port, a
+ malformed IPv6 literal) so the caller falls back to the exact
+ string comparison — fail toward validating, never toward skipping.
+ """
+ try:
+ parsed = urlsplit(str(value).strip())
+ return (
+ (parsed.scheme or "").lower(),
+ parsed.username,
+ parsed.password,
+ (parsed.hostname or "").lower(),
+ parsed.port,
+ (parsed.path or "").rstrip("/"),
+ parsed.query,
+ parsed.fragment,
+ )
+ except Exception:
+ return None
+
+
+def _engine_url_is_unchanged(submitted_value, all_db_settings, key):
+ """True when the submitted engine URL equals the currently-stored one.
+
+ The frontend "All Settings" tab resubmits every rendered input, including a
+ shipped default the user never touched (e.g. the SearXNG
+ ``instance_url = http://localhost:8080`` loopback default). Validating an
+ unchanged value would 400 an otherwise-unrelated save, so only a genuine
+ change is validated. A brand-new key with no stored value is treated as
+ changed.
+
+ Both sides are first string-normalized so a metadata-wrapped vs scalar
+ representation of the same value is not misread as a change. If that
+ exact match fails, both sides are also compared via
+ ``_normalize_engine_url_for_comparison`` so a purely cosmetic resubmit —
+ different scheme/host case, or a trailing slash — of the SAME url is
+ still recognized as unchanged (e.g. resubmitting the stored
+ ``http://localhost:8080`` as ``HTTP://LOCALHOST:8080`` or
+ ``http://localhost:8080/``). This only ever widens what counts as
+ UNCHANGED (and is therefore skipped from validation); it never narrows
+ it, so it cannot make two genuinely different hosts compare equal. If
+ either side fails to parse, that comparison is skipped and the exact
+ match above is the only thing that can call it unchanged.
+ """
+ stored = _stored_engine_url_value(all_db_settings, key)
+ if stored is _NO_STORED_VALUE:
+ return False
+ submitted_str = str(submitted_value).strip()
+ stored_str = str(stored).strip()
+ if submitted_str == stored_str:
+ return True
+ submitted_norm = _normalize_engine_url_for_comparison(submitted_value)
+ stored_norm = _normalize_engine_url_for_comparison(stored)
+ if submitted_norm is None or stored_norm is None:
+ return False
+ return submitted_norm == stored_norm
+
+
+def validate_engine_instance_urls(form_data, all_db_settings):
+ """Reject a PUBLIC search-engine URL that targets a private address.
+
+ SearXNG (and any future public-nature engine with a configurable URL) is
+ user-editable through the settings API. Because such an engine proxies the
+ public web, a private / loopback / link-local ``instance_url`` is only ever
+ an internal-network probe target — so at save time we refuse it under the
+ default posture, closing the SSRF where any authenticated user turns a
+ research run into an internal port scan. Non-http(s) schemes are refused
+ outright.
+
+ The operator opt-in ``search.allow_private_engine_urls`` (env-only) lifts
+ the private-address rejection for genuine LAN self-hosting; Docker
+ deployments instead env-lock the URL, which the route layer honors via
+ ``check_env_setting`` before these validators run.
+ """
+ guarded = _public_engine_url_settings()
+ present = [k for k in guarded if k in form_data]
+ if not present:
+ return None
+
+ allow_private = False
+ try:
+ from ...settings.env_registry import get_env_setting
+
+ allow_private = bool(
+ get_env_setting("search.allow_private_engine_urls", False)
+ )
+ except Exception: # noqa: silent-exception - default to the safe posture
+ allow_private = False
+
+ for key in present:
+ value = unwrap_setting(form_data[key])
+ # Validate-on-change: skip an UNCHANGED value (e.g. the shipped default
+ # loopback ``instance_url`` resubmitted untouched by the All-Settings
+ # tab) so it can't block an unrelated save. The runtime
+ # allow_private_ips=False backstop still blocks the actual fetch.
+ if _engine_url_is_unchanged(value, all_db_settings, key):
+ continue
+ err = _engine_url_ssrf_error(key, value, allow_private=allow_private)
+ if err is not None:
+ return err
+ return None
+
+
# The cross-field egress validators every settings-write route must run. Keep
# the *list* here (single source of truth) so adding one doesn't require a
# lockstep edit at each save route; each route only supplies its own response
@@ -185,6 +484,7 @@ EGRESS_SETTINGS_VALIDATORS = (
validate_egress_scope,
validate_allowed_local_hostnames,
validate_trusted_search_engines,
+ validate_engine_instance_urls,
)
diff --git a/src/local_deep_research/settings/env_definitions/security.py b/src/local_deep_research/settings/env_definitions/security.py
index ddfdd500e1..c168ab701e 100644
--- a/src/local_deep_research/settings/env_definitions/security.py
+++ b/src/local_deep_research/settings/env_definitions/security.py
@@ -87,6 +87,26 @@ SECURITY_SETTINGS = [
),
default=False,
),
+ BooleanSetting(
+ key="search.allow_private_engine_urls",
+ description=(
+ "Allow user-editable PUBLIC search-engine URLs (e.g. the SearXNG "
+ "instance_url) to point at private / loopback / link-local "
+ "addresses. Environment-only operator gate so it cannot be flipped "
+ "through the user-writable settings API. Disabled by default: a "
+ "public-nature engine (its data source is the public internet) "
+ "pointed at an internal host lets any authenticated user turn a "
+ "research run into an internal port scan / service probe, breaking "
+ "the PUBLIC_ONLY egress promise. Enable only when you self-host "
+ "SearXNG on localhost/LAN and accept that engine fetches may reach "
+ "your private network. Docker deployments instead pin the URL "
+ "directly via LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_"
+ "INSTANCE_URL, which is trusted as operator-provisioned. "
+ "Cloud-metadata endpoints (ALWAYS_BLOCKED_METADATA_IPS) stay "
+ "blocked regardless of this flag."
+ ),
+ default=False,
+ ),
BooleanSetting(
key="research_library.allow_filesystem_pdf_storage",
description=(
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
index c54c9d03f1..f8bd5c0de2 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
@@ -12,6 +12,62 @@ from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
from ...security.secure_logging import logger
from ._searxng_rate_limiter import respect_rate_limit
+# The env-lock / operator-gate key for the user-editable SearXNG instance URL.
+_INSTANCE_URL_SETTING = "search.engine.web.searxng.default_params.instance_url"
+
+
+def _resolve_searxng_allow_private_ips() -> bool:
+ """Whether SearXNG may target a private/loopback/link-local instance URL.
+
+ SearXNG is a PUBLIC-nature engine — it proxies the public web — so a
+ private ``instance_url`` is only legitimate when an OPERATOR chose it,
+ never when an arbitrary authenticated user smuggled an internal host in as
+ an SSRF probe. Private egress to the configured instance is therefore
+ permitted only when:
+
+ 1. the operator opt-in ``search.allow_private_engine_urls`` is set
+ (env-only; the LAN / localhost self-host case), OR
+ 2. the instance URL is env-locked via
+ ``LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL``
+ (Docker / operator-provisioned — trusted).
+
+ Both are OPERATOR-controlled. The run's egress scope
+ (``policy.egress_scope``) deliberately does NOT grant it: that setting is a
+ user-editable dropdown (STRICT included), so relaxing on it would be a
+ self-service SSRF bypass. By default private IPs are refused, so a
+ tampered instance URL cannot reach an internal host. Cloud-metadata / link-local metadata IPs stay blocked
+ regardless (ALWAYS_BLOCKED_METADATA_IPS in the SSRF validator's probe
+ path). Fails CLOSED (False) on any error: a genuinely-public instance is
+ unaffected — only private egress is withheld.
+ """
+ # 1. Operator opt-in (LAN self-host).
+ try:
+ from ...settings.env_registry import get_env_setting
+
+ if bool(get_env_setting("search.allow_private_engine_urls", False)):
+ return True
+ except Exception: # noqa: silent-exception - fall through to next check
+ pass
+
+ # 2. Env-locked instance URL (Docker / operator-provisioned).
+ try:
+ from ...settings.manager import check_env_setting
+
+ if check_env_setting(_INSTANCE_URL_SETTING) is not None:
+ return True
+ except Exception: # noqa: silent-exception - fall through to next check
+ pass
+
+ # Otherwise: withhold private egress. We deliberately DO NOT relax this
+ # based on the run's resolved egress scope. ``policy.egress_scope`` is a
+ # user-editable, self-service setting (STRICT is a plain dropdown option,
+ # not operator-gated), and SearXNG is a static PUBLIC engine that always
+ # queries the internet. Letting a user-chosen scope grant private-IP
+ # access would be a self-service SSRF bypass (set scope=strict, then
+ # point the instance URL at an internal host). Private egress for this
+ # engine is an OPERATOR decision only — conditions 1 and 2 above.
+ return False
+
@enum.unique
class SafeSearchSetting(enum.IntEnum):
@@ -93,6 +149,34 @@ class SearXNGSearchEngine(BaseSearchEngine):
return True
+ def _private_url_blocked_by_gate(self) -> bool:
+ """Whether the instance URL was refused *only* because it is
+ private/loopback/link-local and the operator opt-in is OFF.
+
+ Used to decide whether to surface the
+ ``LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS`` remediation hint. Detects
+ the case precisely so the hint fires for the common localhost
+ self-host misconfiguration but NOT for unrelated failures (DNS /
+ timeout / a genuinely-public URL) nor for an ALWAYS-blocked
+ cloud-metadata address — which the operator opt-in would never lift,
+ so pointing at that flag would be misleading.
+
+ Returns True when the URL is blocked under the current (gate-OFF)
+ posture yet WOULD pass with private egress allowed: that difference
+ is exactly the private-URL gate, and the opt-in is the fix. Fails
+ CLOSED (False) on any error so hint detection can never break init.
+ """
+ if self._allow_private_ips:
+ return False
+ try:
+ from ...security.ssrf_validator import validate_url
+
+ return not validate_url(
+ self.instance_url, allow_private_ips=False
+ ) and validate_url(self.instance_url, allow_private_ips=True)
+ except Exception: # noqa: silent-exception - hint detection is best-effort
+ return False
+
def __init__(
self,
max_results: int = 15,
@@ -145,11 +229,20 @@ class SearXNGSearchEngine(BaseSearchEngine):
logger.info(
f"SearXNG initialized with instance URL: {redact_url_for_log(self.instance_url)}"
)
+ # Whether this instance's private/loopback URL may be reached. Derived
+ # from the operator opt-in (``LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS``)
+ # or an env-locked instance URL only — NOT from the user-editable
+ # egress scope — rather than hard-coded True, so under the default
+ # PUBLIC_ONLY posture a user-editable instance_url pointed at an
+ # internal host is NOT fetched. Cloud-metadata IPs remain blocked
+ # either way. See ``_resolve_searxng_allow_private_ips`` for the rules.
+ self._allow_private_ips = _resolve_searxng_allow_private_ips()
try:
# Make sure it's accessible.
- # allow_private_ips=True since SearXNG is typically self-hosted on local network
response = safe_get(
- self.instance_url, timeout=5, allow_private_ips=True
+ self.instance_url,
+ timeout=5,
+ allow_private_ips=self._allow_private_ips,
)
if response.status_code == 200:
logger.info("SearXNG instance is accessible.")
@@ -165,6 +258,21 @@ class SearXNGSearchEngine(BaseSearchEngine):
logger.exception(
f"Error while trying to access SearXNG instance at {redact_url_for_log(self.instance_url)} ({type(e).__name__}): {safe_msg}"
)
+ if self._private_url_blocked_by_gate():
+ # The dominant self-host case: default localhost:8080 SearXNG
+ # with no operator opt-in. The generic error above never names
+ # the fix, so surface it explicitly on this runtime path.
+ logger.warning(
+ "SearXNG instance URL "
+ f"{redact_url_for_log(self.instance_url)} is a private / "
+ "loopback / link-local address and the operator opt-in is "
+ "OFF, so it was not fetched (engine disabled). If you "
+ "self-host SearXNG on localhost/LAN, set "
+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true to allow it; "
+ "Docker deployments can instead env-lock the URL via "
+ "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL. "
+ "Cloud-metadata addresses stay blocked regardless."
+ )
# Add debug logging for all parameters
logger.info(
@@ -271,7 +379,7 @@ class SearXNGSearchEngine(BaseSearchEngine):
self.instance_url,
headers=initial_headers,
timeout=10,
- allow_private_ips=True,
+ allow_private_ips=self._allow_private_ips,
)
cookies = initial_response.cookies
except Exception as e:
@@ -316,7 +424,7 @@ class SearXNGSearchEngine(BaseSearchEngine):
headers=headers,
cookies=cookies,
timeout=15,
- allow_private_ips=True,
+ allow_private_ips=self._allow_private_ips,
)
if response.status_code == 200:
diff --git a/tests/security/test_egress_settings_save_validators.py b/tests/security/test_egress_settings_save_validators.py
index a39810100a..99e964aef8 100644
--- a/tests/security/test_egress_settings_save_validators.py
+++ b/tests/security/test_egress_settings_save_validators.py
@@ -29,12 +29,15 @@ from flask import Flask
from local_deep_research.security.egress import validators
from local_deep_research.security.egress.validators import (
validate_allowed_local_hostnames,
+ validate_engine_instance_urls,
)
from local_deep_research.web.routes.settings_routes import settings_bp
HOSTS_KEY = "llm.allowed_local_hostnames"
SCOPE_KEY = "policy.egress_scope"
ENGINE_KEY = "search.tool"
+SEARXNG_URL_KEY = "search.engine.web.searxng.default_params.instance_url"
+GATE_ENV = "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS"
MODULE = "local_deep_research.web.routes.settings_routes"
DECORATOR_MODULE = "local_deep_research.web.utils.route_decorators"
@@ -148,6 +151,136 @@ def test_hosts_key_absent_returns_none():
assert validate_allowed_local_hostnames({"other.key": "x"}, {}) is None
+# ---------------------------------------------------------------------------
+# validate_engine_instance_urls
+# (a PUBLIC engine's user-editable URL may not point at a private host)
+# ---------------------------------------------------------------------------
+
+
+def test_searxng_private_instance_url_is_rejected():
+ """RFC1918 instance_url is an internal-probe target and is refused."""
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://10.0.0.1:8080"}, {}
+ )
+ assert err is not None
+ assert err["key"] == SEARXNG_URL_KEY
+ assert GATE_ENV in err["error"]
+
+
+def test_searxng_loopback_instance_url_is_rejected():
+ """Loopback instance_url is refused under the default posture."""
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://127.0.0.1:8080"}, {}
+ )
+ assert err is not None
+ assert err["key"] == SEARXNG_URL_KEY
+
+
+def test_searxng_link_local_instance_url_is_rejected():
+ """Link-local (169.254.0.0/16, non-metadata) instance_url is refused."""
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://169.254.10.20"}, {}
+ )
+ assert err is not None
+
+
+def test_searxng_metadata_instance_url_is_rejected():
+ """A cloud-metadata IP is refused (and flagged as always-blocked)."""
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://169.254.169.254"}, {}
+ )
+ assert err is not None
+ assert "metadata" in err["error"].lower()
+
+
+def test_searxng_public_instance_url_is_accepted():
+ """Allow side: a public instance_url is a legitimate SearXNG target."""
+ assert (
+ validate_engine_instance_urls({SEARXNG_URL_KEY: "http://8.8.8.8"}, {})
+ is None
+ )
+
+
+def test_searxng_non_http_scheme_is_rejected():
+ """A non-http(s) scheme is never a valid engine URL."""
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "file:///etc/passwd"}, {}
+ )
+ assert err is not None
+ assert "http" in err["error"].lower()
+
+
+def test_searxng_hostname_resolving_private_is_rejected():
+ """A hostname that resolves to a private address is refused."""
+ addrinfo = [(2, 1, 6, "", ("10.0.0.5", 0))]
+ with patch.object(
+ validators, "_resolve_with_timeout", return_value=addrinfo
+ ):
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://searx.internal.example"}, {}
+ )
+ assert err is not None
+
+
+def test_searxng_unresolvable_host_is_accepted_fail_open():
+ """A name that does not resolve is accepted (fail-open on DNS hiccups);
+ runtime allow_private_ips derivation still gates the actual fetch."""
+ with patch.object(validators, "_resolve_with_timeout", return_value=None):
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://searx.public.example"}, {}
+ )
+ is None
+ )
+
+
+def test_searxng_key_absent_returns_none():
+ """The guard is inert when no guarded engine-URL key is part of the save."""
+ assert validate_engine_instance_urls({"other.key": "x"}, {}) is None
+
+
+def test_operator_gate_allows_private_instance_url(monkeypatch):
+ """With the operator opt-in set, a private instance_url is accepted
+ (the legitimate LAN self-host case)."""
+ monkeypatch.setenv(GATE_ENV, "true")
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://10.0.0.1:8080"}, {}
+ )
+ is None
+ )
+
+
+def test_operator_gate_still_rejects_metadata(monkeypatch):
+ """Deny counterpart: the opt-in relaxes private IPs but NOT the
+ always-blocked cloud-metadata set."""
+ monkeypatch.setenv(GATE_ENV, "true")
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://169.254.169.254"}, {}
+ )
+ assert err is not None
+ assert "metadata" in err["error"].lower()
+
+
+def test_operator_gate_still_rejects_non_http_scheme(monkeypatch):
+ """The opt-in never licenses a non-http(s) scheme."""
+ monkeypatch.setenv(GATE_ENV, "true")
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "gopher://10.0.0.1"}, {}
+ )
+ assert err is not None
+
+
+def test_engine_url_guard_runs_via_first_error():
+ """The new validator is wired into the shared entry point used by every
+ settings-save route."""
+ err = validators.first_egress_validation_error(
+ {SEARXNG_URL_KEY: "http://127.0.0.1:8080"}, {}
+ )
+ assert err is not None
+ assert err["key"] == SEARXNG_URL_KEY
+
+
# ---------------------------------------------------------------------------
# Route-level wiring: api_update_setting PUT surfaces the validator errors
# ---------------------------------------------------------------------------
@@ -274,5 +407,313 @@ def test_route_accepts_strict_scope_with_db_concrete_engine():
assert "error" not in resp.get_json()
+def test_route_rejects_private_searxng_instance_url():
+ """PUT the SearXNG instance_url = private IP -> 400 with the policy error."""
+ settings = [_make_setting(SEARXNG_URL_KEY, "http://localhost:8080")]
+ with _routed_client(settings) as client:
+ resp = client.put(
+ f"/settings/api/{SEARXNG_URL_KEY}",
+ json={"value": "http://10.0.0.1:8080"},
+ )
+ assert resp.status_code == 400
+ assert GATE_ENV in resp.get_json()["error"]
+
+
+def test_route_accepts_public_searxng_instance_url():
+ """Allow counterpart: a public instance_url passes and is saved (200)."""
+ settings = [_make_setting(SEARXNG_URL_KEY, "http://localhost:8080")]
+ with _routed_client(settings) as client:
+ resp = client.put(
+ f"/settings/api/{SEARXNG_URL_KEY}",
+ json={"value": "http://8.8.8.8"},
+ )
+ assert resp.status_code == 200
+ assert "error" not in resp.get_json()
+
+
+def test_route_accepts_private_searxng_url_with_operator_gate(monkeypatch):
+ """With the operator opt-in, the route accepts a private instance_url."""
+ monkeypatch.setenv(GATE_ENV, "true")
+ settings = [_make_setting(SEARXNG_URL_KEY, "http://localhost:8080")]
+ with _routed_client(settings) as client:
+ resp = client.put(
+ f"/settings/api/{SEARXNG_URL_KEY}",
+ json={"value": "http://192.168.1.50:8080"},
+ )
+ assert resp.status_code == 200
+ assert "error" not in resp.get_json()
+
+
+# ---------------------------------------------------------------------------
+# validate_engine_instance_urls — validate-on-change
+#
+# Regression: the shipped default ``instance_url`` is a loopback URL that the
+# "All Settings" tab resubmits untouched with every save. Validating an
+# UNCHANGED value 400'd otherwise-unrelated saves. Only a genuine change (or a
+# brand-new key with no stored value) is validated; the runtime
+# allow_private_ips=False backstop still gates the actual fetch.
+# ---------------------------------------------------------------------------
+
+DEFAULT_SEARXNG_URL = "http://localhost:8080"
+
+
+def test_unchanged_default_loopback_instance_url_is_accepted():
+ """Regression repro: a full-form save carrying the shipped loopback
+ ``instance_url`` default untouched, plus unrelated keys, is accepted when
+ the same value is already stored — both directly and via the shared entry
+ point every save route calls."""
+ form_data = {
+ "llm.temperature": 0.7,
+ "search.iterations": 2,
+ SEARXNG_URL_KEY: DEFAULT_SEARXNG_URL,
+ }
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, DEFAULT_SEARXNG_URL),
+ }
+ assert validate_engine_instance_urls(form_data, all_db_settings) is None
+ assert (
+ validators.first_egress_validation_error(form_data, all_db_settings)
+ is None
+ )
+
+
+def test_unchanged_default_loopback_accepted_with_dict_shaped_stored_value():
+ """Robustness: the stored entry may be a ``{"value": ...}`` dict rather than
+ an ORM row; an unchanged value is still recognized and accepted."""
+ all_db_settings = {SEARXNG_URL_KEY: {"value": DEFAULT_SEARXNG_URL}}
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: DEFAULT_SEARXNG_URL}, all_db_settings
+ )
+ is None
+ )
+
+
+def test_changing_instance_url_to_private_is_rejected():
+ """Deny counterpart: changing the stored (public) URL to a private one is a
+ genuine change and is validated -> rejected."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, "http://8.8.8.8"),
+ }
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://10.0.0.1:8080"}, all_db_settings
+ )
+ assert err is not None
+ assert err["key"] == SEARXNG_URL_KEY
+
+
+def test_changing_stored_loopback_to_different_private_is_rejected():
+ """Even when the stored value is itself loopback, changing it to a
+ different private address is a real change and must be validated."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, DEFAULT_SEARXNG_URL),
+ }
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://10.0.0.1:8080"}, all_db_settings
+ )
+ assert err is not None
+ assert GATE_ENV in err["error"]
+
+
+def test_changing_instance_url_to_public_is_accepted():
+ """Allow counterpart: changing the stored URL to a public one is fine."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, DEFAULT_SEARXNG_URL),
+ }
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://8.8.8.8"}, all_db_settings
+ )
+ is None
+ )
+
+
+def test_new_instance_url_key_with_no_stored_value_is_validated():
+ """A key with no stored entry counts as changed -> validated, so a private
+ value is still rejected (no stored value to compare against)."""
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://10.0.0.1:8080"}, {}
+ )
+ is not None
+ )
+ # Also when other settings exist but not this one.
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://127.0.0.1:8080"},
+ {"other.key": _make_setting("other.key", "x")},
+ )
+ is not None
+ )
+
+
+def test_unchanged_private_instance_url_under_operator_gate_is_accepted(
+ monkeypatch,
+):
+ """Under the operator opt-in an unchanged private value is fine — the
+ skip-on-unchanged path and the opt-in both leave it accepted."""
+ monkeypatch.setenv(GATE_ENV, "true")
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, DEFAULT_SEARXNG_URL),
+ }
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: DEFAULT_SEARXNG_URL}, all_db_settings
+ )
+ is None
+ )
+
+
+# ---------------------------------------------------------------------------
+# validate_engine_instance_urls — cosmetic-variant "unchanged" comparison
+#
+# The All-Settings tab resubmits the stored value verbatim, but a user who
+# merely reformats it (different case, an added/removed trailing slash)
+# without changing the actual destination should not have that cosmetic
+# resubmit treated as a genuine change. ``_engine_url_is_unchanged`` now
+# also compares scheme/host case-insensitively and ignores a trailing slash
+# on the path. This must only ever widen "unchanged" — a real change to a
+# different host/port/path still has to be validated (and rejected when
+# private).
+# ---------------------------------------------------------------------------
+
+
+def test_unchanged_instance_url_different_scheme_and_host_case_is_accepted():
+ """A cosmetic resubmit with a different scheme/host CASE of the exact
+ same stored url is recognized as unchanged -> no SSRF validation -> no
+ 400."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, DEFAULT_SEARXNG_URL),
+ }
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "HTTP://LOCALHOST:8080"}, all_db_settings
+ )
+ is None
+ )
+
+
+def test_unchanged_instance_url_trailing_slash_is_accepted():
+ """A cosmetic resubmit adding a bare trailing slash to the stored url is
+ recognized as unchanged."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, DEFAULT_SEARXNG_URL),
+ }
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://localhost:8080/"}, all_db_settings
+ )
+ is None
+ )
+
+
+def test_instance_url_with_added_path_is_a_genuine_change():
+ """Deny counterpart: appending an actual path segment (not just a bare
+ trailing slash) is a real change and must still be validated ->
+ rejected, since the stored/submitted host is private."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, DEFAULT_SEARXNG_URL),
+ }
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://localhost:8080/foo"}, all_db_settings
+ )
+ assert err is not None
+ assert err["key"] == SEARXNG_URL_KEY
+
+
+def test_cosmetic_variant_of_a_different_private_host_is_still_rejected():
+ """Security-preservation: normalizing case/trailing-slash must never fold
+ a genuinely DIFFERENT host onto the stored one. A different private host
+ (still cosmetically upper-cased) is a real change and is rejected."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, DEFAULT_SEARXNG_URL),
+ }
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "HTTP://192.168.1.5:8080/"}, all_db_settings
+ )
+ assert err is not None
+ assert err["key"] == SEARXNG_URL_KEY
+
+
+def test_genuine_public_change_still_accepted():
+ """A real change to a different, public host is still a change (goes
+ through validation) and is accepted since it's public."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, DEFAULT_SEARXNG_URL),
+ }
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "HTTP://EXAMPLE.COM:8080/"}, all_db_settings
+ )
+ is None
+ )
+
+
+def test_unparseable_stored_or_submitted_value_falls_back_to_exact_match():
+ """If cosmetic-normalization parsing fails on either side (e.g. a
+ non-numeric port), the comparison falls back to the exact
+ ``str.strip()`` match rather than raising or silently treating it as
+ unchanged."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, "http://localhost:abc"),
+ }
+ # Different value than stored, and unparseable -> falls back to exact
+ # string compare, which does not match -> a genuine change -> validated.
+ # The submitted value is also unparseable-as-strict-URL, so the SSRF
+ # validator itself will refuse it as not-a-valid-URL rather than skip it
+ # as "unchanged".
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://localhost:xyz"}, all_db_settings
+ )
+ assert err is not None
+ # Identical unparseable strings still match on the exact-string
+ # fallback, so they are correctly recognized as unchanged.
+ assert (
+ validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://localhost:abc"}, all_db_settings
+ )
+ is None
+ )
+
+
+# ---------------------------------------------------------------------------
+# Decimal / hex loopback literals — confirm save-time rejection when
+# submitted as a genuine change. These numeric forms are not recognized by
+# ``ipaddress.ip_address`` as literal IPs, so ``_engine_url_ssrf_error``
+# routes them through hostname resolution (``_resolve_with_timeout`` ->
+# ``socket.getaddrinfo``) instead of the literal-IP branch. The C library
+# resolves bare-integer / 0x-hex notation to 127.0.0.1 purely locally (no
+# network I/O — verified offline against the real resolver), so these are
+# still caught and rejected, independent of anything in the cosmetic
+# "unchanged" normalization above.
+# ---------------------------------------------------------------------------
+
+
+def test_decimal_loopback_literal_instance_url_is_rejected_as_a_change():
+ """``2130706433`` is the decimal encoding of 127.0.0.1. Submitted as a
+ change from the stored public url, it must resolve and be rejected."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, "http://8.8.8.8"),
+ }
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://2130706433:8080"}, all_db_settings
+ )
+ assert err is not None
+ assert err["key"] == SEARXNG_URL_KEY
+
+
+def test_hex_loopback_literal_instance_url_is_rejected_as_a_change():
+ """``0x7f000001`` is the hex encoding of 127.0.0.1. Submitted as a
+ change from the stored public url, it must resolve and be rejected."""
+ all_db_settings = {
+ SEARXNG_URL_KEY: _make_setting(SEARXNG_URL_KEY, "http://8.8.8.8"),
+ }
+ err = validate_engine_instance_urls(
+ {SEARXNG_URL_KEY: "http://0x7f000001:8080"}, all_db_settings
+ )
+ assert err is not None
+ assert err["key"] == SEARXNG_URL_KEY
+
+
if __name__ == "__main__": # pragma: no cover
raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 1403be3edd..1508e748d8 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -6004,7 +6004,7 @@
},
"search.engine.web.searxng.default_params.instance_url": {
"category": "searxng",
- "description": "The SearXNG API endpoint URL.",
+ "description": "The SearXNG API endpoint URL. A private / loopback / link-local URL (including the default http://localhost:8080) is only fetched when the operator sets LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true or env-locks this URL via LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL; otherwise the engine disables itself. Cloud-metadata addresses are always blocked.",
"editable": true,
"max_value": null,
"min_value": null,
diff --git a/tests/web_search_engines/engines/test_search_engine_searxng.py b/tests/web_search_engines/engines/test_search_engine_searxng.py
index 3c3b0d3ae7..efe9b418e4 100644
--- a/tests/web_search_engines/engines/test_search_engine_searxng.py
+++ b/tests/web_search_engines/engines/test_search_engine_searxng.py
@@ -1801,3 +1801,223 @@ class TestResultFormat:
)
assert engine.result_format == "html"
+
+
+SEARXNG_MODULE = (
+ "local_deep_research.web_search_engines.engines.search_engine_searxng"
+)
+INSTANCE_URL_ENV = "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL"
+GATE_ENV = "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS"
+
+
+class TestAllowPrivateIpsDerivation:
+ """The instance URL's allow_private_ips flag is DERIVED, not hard-coded.
+
+ A public-nature SearXNG pointed at an internal host is an SSRF vector; the
+ engine must NOT be permitted to reach a private instance URL unless an
+ operator explicitly opted in (env gate) or provisioned the URL themselves
+ (env-lock). A user-editable egress scope never grants it.
+ """
+
+ def test_public_only_default_refuses_private(self):
+ """With no operator opt-in and no env-locked instance URL, private
+ egress to the instance URL is withheld by default (allow_private=False)."""
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ _resolve_searxng_allow_private_ips,
+ )
+
+ assert _resolve_searxng_allow_private_ips() is False
+
+ def test_empty_snapshot_refuses_private(self):
+ """No operator opt-in / env-lock present -> refuses private (False)."""
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ _resolve_searxng_allow_private_ips,
+ )
+
+ assert _resolve_searxng_allow_private_ips() is False
+
+ def test_user_scope_never_grants_private(self):
+ """A user-editable egress scope must NOT grant private egress for a
+ static public engine. ``policy.egress_scope`` is a self-service
+ dropdown (STRICT included), so relaxing on it would be a self-service
+ SSRF bypass (scope=strict + internal instance URL). Only the operator
+ env gate / env-lock may permit private egress -> stays False
+ regardless of scope (the resolver no longer takes a scope input)."""
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ _resolve_searxng_allow_private_ips,
+ )
+
+ assert _resolve_searxng_allow_private_ips() is False
+
+ def test_operator_gate_allows_private(self, monkeypatch):
+ """The env opt-in permits private egress even under PUBLIC_ONLY."""
+ monkeypatch.setenv(GATE_ENV, "true")
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ _resolve_searxng_allow_private_ips,
+ )
+
+ assert _resolve_searxng_allow_private_ips() is True
+
+ def test_env_locked_instance_url_allows_private(self, monkeypatch):
+ """An operator-provisioned (env-locked) instance URL is trusted, so
+ Docker's private container URL keeps working under PUBLIC_ONLY."""
+ monkeypatch.setenv(INSTANCE_URL_ENV, "http://searxng:8080")
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ _resolve_searxng_allow_private_ips,
+ )
+
+ assert _resolve_searxng_allow_private_ips() is True
+
+
+class TestEngineForwardsDerivedAllowPrivateIps:
+ """The engine forwards the DERIVED flag to safe_get (not a hard-coded True)."""
+
+ def test_probe_uses_false_under_public_only(self):
+ """Default PUBLIC_ONLY posture -> the availability probe is made with
+ allow_private_ips=False."""
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ SearXNGSearchEngine,
+ )
+
+ with patch(f"{SEARXNG_MODULE}.safe_get") as mock_get:
+ mock_get.return_value = Mock(status_code=200)
+ engine = SearXNGSearchEngine(
+ instance_url="http://localhost:8080",
+ settings_snapshot={"search.tool": "searxng"},
+ )
+
+ assert engine._allow_private_ips is False
+ assert mock_get.call_args.kwargs["allow_private_ips"] is False
+
+ def test_probe_uses_true_with_operator_gate(self, monkeypatch):
+ """Operator opt-in -> probe made with allow_private_ips=True."""
+ monkeypatch.setenv(GATE_ENV, "true")
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ SearXNGSearchEngine,
+ )
+
+ with patch(f"{SEARXNG_MODULE}.safe_get") as mock_get:
+ mock_get.return_value = Mock(status_code=200)
+ engine = SearXNGSearchEngine(
+ instance_url="http://localhost:8080",
+ settings_snapshot={"search.tool": "searxng"},
+ )
+
+ assert engine._allow_private_ips is True
+ assert mock_get.call_args.kwargs["allow_private_ips"] is True
+
+ def test_search_forwards_derived_flag(self):
+ """The search request path forwards the same derived flag."""
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ SearXNGSearchEngine,
+ )
+
+ with patch(f"{SEARXNG_MODULE}.safe_get") as mock_get:
+ mock_get.return_value = Mock(
+ status_code=200, text="<html></html>", cookies=None
+ )
+ engine = SearXNGSearchEngine(
+ instance_url="http://localhost:8080",
+ settings_snapshot={"search.tool": "searxng"},
+ )
+ engine._is_available = True
+ engine.search_url = "http://localhost:8080/search"
+ mock_get.reset_mock()
+ engine._get_search_results("hello")
+
+ # Every safe_get in the search path used the derived flag (False here).
+ assert mock_get.call_count >= 1
+ for c in mock_get.call_args_list:
+ assert c.kwargs.get("allow_private_ips") is False
+
+
+class TestPrivateUrlBlockedHint:
+ """The engine surfaces the operator opt-in when it disables itself solely
+ because the instance URL is a gated private/loopback address (FIX 2)."""
+
+ @staticmethod
+ def _make_engine(instance_url):
+ """Build an engine with a mocked (always-OK) probe, so
+ ``_private_url_blocked_by_gate`` can be exercised in isolation."""
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ SearXNGSearchEngine,
+ )
+
+ with patch(f"{SEARXNG_MODULE}.safe_get") as mock_get:
+ mock_get.return_value = Mock(status_code=200)
+ return SearXNGSearchEngine(instance_url=instance_url)
+
+ def test_loopback_url_is_flagged(self):
+ """A loopback instance URL with the gate OFF is flagged."""
+ engine = self._make_engine("http://127.0.0.1:8080")
+ assert engine._allow_private_ips is False
+ assert engine._private_url_blocked_by_gate() is True
+
+ def test_public_url_is_not_flagged(self):
+ """A genuinely-public instance URL is never flagged."""
+ engine = self._make_engine("http://8.8.8.8:8080")
+ assert engine._private_url_blocked_by_gate() is False
+
+ def test_metadata_url_is_not_flagged(self):
+ """Cloud-metadata addresses stay blocked even with the opt-in, so the
+ hint (which points at that opt-in) must NOT be offered for them."""
+ engine = self._make_engine("http://169.254.169.254:8080")
+ assert engine._private_url_blocked_by_gate() is False
+
+ def test_gate_on_is_not_flagged(self, monkeypatch):
+ """With the operator opt-in ON, private egress is allowed, so there is
+ nothing to remediate."""
+ monkeypatch.setenv(GATE_ENV, "true")
+ engine = self._make_engine("http://127.0.0.1:8080")
+ assert engine._allow_private_ips is True
+ assert engine._private_url_blocked_by_gate() is False
+
+ def test_blocked_probe_logs_remediation_warning(self):
+ """When the availability probe is refused for a gated private URL, a
+ WARNING naming the opt-in env var is logged on the runtime path."""
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ SearXNGSearchEngine,
+ )
+
+ with (
+ patch(f"{SEARXNG_MODULE}.safe_get") as mock_get,
+ patch(f"{SEARXNG_MODULE}.logger") as mock_logger,
+ ):
+ mock_get.side_effect = ValueError(
+ "URL failed security validation (possible SSRF): "
+ "http://localhost:8080"
+ )
+ engine = SearXNGSearchEngine(instance_url="http://127.0.0.1:8080")
+
+ assert engine._is_available is False
+ warnings = [
+ c.args[0] for c in mock_logger.warning.call_args_list if c.args
+ ]
+ assert any(GATE_ENV in msg for msg in warnings), (
+ f"expected a warning naming {GATE_ENV}, got: {warnings}"
+ )
+
+ def test_public_probe_failure_has_no_remediation_warning(self):
+ """A transport failure against a public URL must NOT emit the private-URL
+ remediation hint (precise detection, no spam)."""
+ import requests
+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (
+ SearXNGSearchEngine,
+ )
+
+ with (
+ patch(f"{SEARXNG_MODULE}.safe_get") as mock_get,
+ patch(f"{SEARXNG_MODULE}.logger") as mock_logger,
+ ):
+ mock_get.side_effect = requests.RequestException(
+ "connection refused"
+ )
+ engine = SearXNGSearchEngine(instance_url="http://8.8.8.8:8080")
+
+ assert engine._is_available is False
+ warnings = [
+ c.args[0] for c in mock_logger.warning.call_args_list if c.args
+ ]
+ assert not any(GATE_ENV in msg for msg in warnings), (
+ f"unexpected private-URL hint on a public failure: {warnings}"
+ )