~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat(egress): per-origin private engine-URL allowlist, misconfiguration banners, and docs for the v1.10.3 SearXNG guard (#5604)
LearningCircuit8ade42367a11
diff --git a/README.md b/README.mdindex 34fe680705..7565b85cce 100644--- a/README.md+++ b/README.md@@ -57,10 +57,15 @@ docker exec ollama ollama pull gpt-oss:20bdocker run -d -p 8080:8080 --name searxng searxng/searxng# Step 3: Pull and run Local Deep Research+# (the URL line pins SearXNG's address AND marks it operator-approved —+# private/localhost engine URLs are otherwise blocked by default since+# v1.10.3. The URL becomes read-only in the web UI; docs/SearXNG-Setup.md+# lists the alternatives, e.g. an origin allowlist.)docker run -d --network host \--name local-deep-research \--volume "deep-research:/data" \-e LDR_DATA_DIR=/data \+ -e LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL=http://localhost:8080 \localdeepresearch/local-deep-research```diff --git a/changelog.d/5604.feature.1.md b/changelog.d/5604.feature.1.mdnew file mode 100644index 0000000000..532d0e5510--- /dev/null+++ b/changelog.d/5604.feature.1.md@@ -0,0 +1 @@+New env-only operator setting `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST`: a comma-separated list of exact URL origins (e.g. `http://localhost:8080`) that public search-engine instance URLs (SearXNG) may use even though they are private/loopback/link-local. This is a finer-grained alternative to `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true` — private fetching is enabled only when the engine's configured URL matches a listed origin, instead of for any private address. Consulted at both save time and runtime; cloud-metadata addresses and non-http(s) schemes remain blocked even if listed, and the setting cannot be edited through the web UI.diff --git a/changelog.d/5604.feature.2.md b/changelog.d/5604.feature.2.mdnew file mode 100644index 0000000000..99606eb85b--- /dev/null+++ b/changelog.d/5604.feature.2.md@@ -0,0 +1 @@+The research form now shows a dismissible warning when SearXNG would silently return no results because its private/localhost instance URL has not been approved by the server operator — including the exact environment line to fix it. A mirror-image warning appears when a local document engine (Paperless-ngx, Elasticsearch) points at a host that does not look private, since document-search queries would then leave the machine.diff --git a/changelog.d/5604.misc.md b/changelog.d/5604.misc.mdnew file mode 100644index 0000000000..c6a54f1a5d--- /dev/null+++ b/changelog.d/5604.misc.md@@ -0,0 +1 @@+Clearer guidance when a self-hosted SearXNG URL is blocked by the private-URL guard: the runtime self-disable now logs at ERROR (was WARNING) and both it and the settings-save rejection name all three operator remedies; docs, installation guides, and `.env.template` now document the v1.10.3 guard next to every `localhost:8080` example instead of describing the old allow-by-default behavior.diff --git a/docker-compose.yml b/docker-compose.ymlindex 19e8117cac..dd28949fcf 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -70,7 +70,11 @@ services:# These are required for containers to communicate with each other.# Docker containers cannot use 'localhost' to reach other containers.# These settings override UI configuration for Docker Compose deployments.- # Note: pip/local installs use localhost defaults and are unaffected.+ # Env-locking the SearXNG URL also marks it operator-provisioned, which+ # satisfies the private-engine-URL protection (v1.10.3+). pip/local+ # installs using the localhost default must approve it instead, e.g.+ # LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://localhost:8080 —+ # see docs/SearXNG-Setup.md.# ============================================================================- LDR_LLM_OLLAMA_URL=http://ollama:11434- LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL=http://searxng:8080diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 75f795bf3a..9221b99aaf 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -43,7 +43,8 @@ They are not available in the Web UI because they are needed to start the applic| `LDR_RESEARCH_LIBRARY_ALLOW_FILESYSTEM_PDF_STORAGE` | Boolean | `False` | No | | Allow users to select the UNENCRYPTED 'filesystem' PDF storage mode for library-downloaded PDFs. Disabled by default; this is an environment-only operator gate and cannot be changed through the user-writable settings API. Filesystem mode writes fetched third-party PDFs as PLAINTEXT to a shared library directory (cleartext storage of sensitive information, CWE-312). When off, the 'filesystem' option is withheld from the settings UI and any stored or environment value of 'filesystem' is coerced to the encrypted 'database' mode at write time. Previously-written plaintext files remain readable. Enable only when the library directory lives on an operator-controlled encrypted volume. | Security | || `LDR_RESEARCH_LIBRARY_ALLOW_LEGACY_READ_FALLBACK` | Boolean | `False` | No | | SECURITY RISK — leave DISABLED (default) on any multi-user or untrusted deployment. When ENABLED, library PDF reads that miss in the caller's own per-user directory fall back to a shared root derived from the user-editable 'research_library.storage_path' setting. On a multi-user instance this re-opens a CROSS-TENANT READ: a user can edit their own storage_path to point at another user's library directory, and because per-user autoincrement resource ids collide by construction (e.g. 'pdfs/5.pdf'), a read of their own document id then resolves — via this fallback — to the OTHER user's PDF and returns its contents. The safe state is OFF: with the gate off, reads resolve strictly within the requesting user's own per-user root and the fallback never fires. This is an environment-only operator gate and cannot be enabled through the user-writable settings API. Enable ONLY on a single-user or fully-trusted deployment that needs PDFs downloaded before per-user isolation (issue #5521) to keep loading from the legacy shared location. | Security | || `LDR_RESEARCH_LIBRARY_ALLOW_SHARED_LIBRARY` | Boolean | `False` | No | | Allow shared-library mode, which drops the per-user library directory boundary so all users' downloaded PDFs live in one shared directory. Disabled by default; this is an environment-only operator gate and cannot be enabled through the user-writable settings API. Because both the shared_library flag and the storage_path are otherwise user-editable, leaving shared mode user-toggleable would let a multi-tenant user point their own storage_path at another user's directory and read/overwrite their PDFs. When off, the per-user subdirectory is always enforced regardless of the user's shared_library setting. Enable only on single-tenant or mutually-trusted deployments. | 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_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. To approve only specific origins instead of all private addresses, use the finer-grained LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST. 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_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST` | String | `None` | No | | Comma-separated list of exact URL origins (scheme://host[:port]) that user-editable PUBLIC search-engine URLs (e.g. the SearXNG instance_url) may use even though they are private / loopback / link-local — e.g. 'http://localhost:8080,http://192.168.1.5:8888'. Finer-grained alternative to LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true: private egress is enabled for an engine only when its configured URL matches a listed origin (the engine's request chain, including redirects, then runs with private access — like the blanket flag, but conditional on the match), rather than for any private URL. Matching is exact scheme + host + port (default ports 80/443 implied, host case-insensitive, path/query ignored); no wildcards or CIDR ranges. Entries that fail to parse are ignored. Environment-only operator setting so it cannot be edited through the user-writable settings API. Cloud-metadata endpoints (ALWAYS_BLOCKED_METADATA_IPS) and non-http(s) schemes stay blocked even if listed. | 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 | |@@ -77,9 +78,12 @@ They are not available in the Web UI because they are needed to start the applic| `app.warnings.dismiss_context_below_history` | `LDR_APP_WARNINGS_DISMISS_CONTEXT_BELOW_HISTORY` | `false` | Dismiss warnings when the configured context is below historical usage | APP || `app.warnings.dismiss_context_truncation_history` | `LDR_APP_WARNINGS_DISMISS_CONTEXT_TRUNCATION_HISTORY` | `false` | Dismiss warnings about historical context truncation | APP || `app.warnings.dismiss_egress_policy` | `LDR_APP_WARNINGS_DISMISS_EGRESS_POLICY` | `false` | Permanently hide the 'public search egress enabled' banner (the fresh-install informational one). The critical cloud-LLM and cloud-embeddings banners have their OWN dismiss flags so this can't silently hide them. | APP |+| `app.warnings.dismiss_elasticsearch_public_url` | `LDR_APP_WARNINGS_DISMISS_ELASTICSEARCH_PUBLIC_URL` | `false` | Permanently hide the 'Elasticsearch points at a non-private host' banner that appears when the Elasticsearch engine is active but its hosts (or cloud_id) do not look like private/local addresses (document queries would leave the machine; a private-only egress scope excludes the engine). Dismiss when a hosted endpoint such as Elastic Cloud is intentional. | APP || `app.warnings.dismiss_high_context` | `LDR_APP_WARNINGS_DISMISS_HIGH_CONTEXT` | `false` | Permanently hide the warning shown when your local LLM context window is set above 8,192 tokens, which may cause memory issues on some hardware. | APP || `app.warnings.dismiss_legacy_config` | `LDR_APP_WARNINGS_DISMISS_LEGACY_CONFIG` | `false` | Dismiss warnings about the deprecated server_config.json file | APP || `app.warnings.dismiss_model_mismatch` | `LDR_APP_WARNINGS_DISMISS_MODEL_MISMATCH` | `false` | Permanently hide the warning shown when using a large model (70B+ parameters) with a local provider and high context window, which may exceed available GPU memory. | APP |+| `app.warnings.dismiss_paperless_public_url` | `LDR_APP_WARNINGS_DISMISS_PAPERLESS_PUBLIC_URL` | `false` | Permanently hide the 'Paperless-ngx points at a non-private host' banner that appears when the Paperless engine is active but its API URL does not look like a private/local address (document queries would leave the machine; a private-only egress scope excludes the engine). | APP |+| `app.warnings.dismiss_searxng_private_url` | `LDR_APP_WARNINGS_DISMISS_SEARXNG_PRIVATE_URL` | `false` | Permanently hide the 'SearXNG is disabled: private URL not approved' banner that appears when SearXNG is active (selected as the search engine, or enabled for auto/agent search) but its private/localhost instance URL has no operator approval (allowlist, blanket opt-in, or env-lock) in the server environment. | APP || `app.warnings.dismiss_searxng_recommendation` | `LDR_APP_WARNINGS_DISMISS_SEARXNG_RECOMMENDATION` | `false` | Dismiss recommendations about using more questions instead of iterations with SearXNG | APP || `app.web_interface` | `LDR_APP_WEB_INTERFACE` | `true` | Enable the web interface for the application. When disabled, only CLI and API access is available. Requires server restart to take effect. | APP || `backup.enabled` | `LDR_BACKUP_ENABLED` | `true` | Automatically backup database after successful login. Each backup uses disk space proportional to your database size. Disable this if disk space is limited. | APP |@@ -436,7 +440,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. 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.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 lists its origin in LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST, 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/docs/SearXNG-Setup.md b/docs/SearXNG-Setup.mdindex 615444bb33..2377f087eb 100644--- a/docs/SearXNG-Setup.md+++ b/docs/SearXNG-Setup.md@@ -2,31 +2,68 @@This document explains how to configure and use the SearXNG integration with Local Deep Research.+> **⚠️ Self-hosting on localhost or your LAN? Read this first.**+>+> Since v1.10.3, a SearXNG instance URL that points at a **private, loopback, or+> link-local address** (including the default `http://localhost:8080`) is+> **blocked by default**: it is rejected when saved in the web UI, and the+> engine disables itself at runtime with an error in the logs. This is SSRF+> protection — the URL is editable by any authenticated user, and without the+> block it could be pointed at internal services on your network.+>+> Self-hosted local instances remain fully supported; the **server operator**+> just has to approve them once, in one of three ways (then restart LDR):+>+> ```bash+> # Option A (recommended; needs a release NEWER than v1.10.4 — on older+> # versions use Option B or C): allow ONLY specific URL origins+> LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://localhost:8080+>+> # Option B: pin the URL itself via the environment. An env-locked URL is+> # treated as operator-provisioned and trusted; it becomes read-only in the+> # web UI. The bundled docker-compose.yml does this.+> LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL=http://localhost:8080+>+> # Option C (broadest): allow ALL private/localhost/LAN engine URLs+> LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true+> ```+>+> Cloud-metadata addresses (e.g. `169.254.169.254`) stay blocked under all+> three options. Details in [Network Security](#network-security) below.+## Configuring SearXNG Access-The SearXNG search engine is **disabled by default** until you provide an instance URL. This ensures the system doesn't attempt to use public instances without explicit configuration.+The SearXNG search engine is **disabled by default** until you provide a+reachable instance URL. This ensures the system doesn't attempt to use public+instances without explicit configuration.### Setting Up Access-You have two ways to enable the SearXNG search engine:+(The three options in the callout above answer a different question — how a+*private* URL gets **approved**. The two ways below are simply how the URL+*value* is set; note that option 1 doubles as approval, while a private URL+set via option 2 still needs one of the approvals above.)++You have two ways to configure the SearXNG instance URL:-1. **Environment Variable (Recommended)**:+1. **Environment Variable (Recommended for self-hosted instances)**:```bash- # Add to your .env file or set in your environment- SEARXNG_INSTANCE=http://localhost:8080+ # Add to your .env file or set in the server environment+ LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL=http://localhost:8080# Optional: Set custom delay between requests (in seconds)- SEARXNG_DELAY=2.0+ LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_DELAY_BETWEEN_REQUESTS=2.0```+ Environment variables override and lock the corresponding web UI setting,+ and an env-locked instance URL counts as operator-provisioned — so this+ single line also satisfies the private-URL protection described above.-2. **Configuration Parameter**: Add to your `config.py`:- ```python- # In config.py- SEARXNG_CONFIG = {- "instance_url": "http://localhost:8080",- "delay_between_requests": 2.0- }- ```+2. **Web UI**: *Settings → Search → SearXNG → Endpoint URL*. Note that a+ private/localhost URL entered here additionally requires operator+ approval in the server environment — either its origin listed in+ `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST` or the blanket+ `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true` (see the callout at the top+ of this page).## Self-Hosting SearXNG (Recommended)@@ -77,10 +114,14 @@ If you must use a public instance:Example configuration for a public instance:```bash-SEARXNG_INSTANCE=https://instance.example.com-SEARXNG_DELAY=5.0+LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL=https://instance.example.com+LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_DELAY_BETWEEN_REQUESTS=5.0```+Note that most public instances do not enable the JSON API (`format=json`) and+aggressively rate-limit automated clients, so a self-hosted instance is both+the more reliable and the more ethical choice.+## Checking ConfigurationTo verify if SearXNG is properly configured:@@ -101,17 +142,56 @@ else:## Network Security-SearXNG is designed for self-hosting, so Local Deep Research allows SearXNG to access **private network IPs** by default. This means you can run SearXNG on:+SearXNG is designed for self-hosting, and running it on a private address is+the normal setup:- **Localhost**: `http://127.0.0.1:8080` or `http://localhost:8080`- **LAN IPs**: `http://192.168.1.100:8080`, `http://10.0.0.5:8080`, `http://172.16.0.2:8080`-- **Docker networks**: `http://172.17.0.2:8080`+- **Docker networks**: `http://172.17.0.2:8080` or `http://searxng:8080`- **Local hostnames**: `http://searxng.local:8080` (if configured in DNS/hosts)-This is intentional and secure because:-1. The SearXNG URL is **admin-configured**, not user input-2. Private IPs are only accessible from your local network-3. **Cloud metadata endpoints** (AWS IMDS / ECS, Azure, OCI, DigitalOcean, AlibabaCloud, Tencent Cloud — see `ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS`) are always blocked to prevent credential theft in cloud environments+However, since v1.10.3 such private / loopback / link-local URLs are **not+fetched by default** and are rejected when saved through the web UI. The+instance URL is an editable setting, so without this protection any+authenticated user could point a "public web search" engine at internal+services and use research runs to probe your private network (SSRF). Peer+projects in this space have accumulated a series of SSRF CVEs through exactly+this kind of URL handling, so LDR ships strict-by-default.++A private URL becomes allowed when the **server operator** (someone with+access to the server environment, not just the web UI) approves it in one of+three ways:++1. **Origin allowlist (recommended)** — set+ `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST` to a comma-separated list of+ exact URL origins, e.g.+ `http://localhost:8080,http://192.168.1.5:8888`. Private fetching is+ enabled for the engine only when its configured URL matches a listed+ origin; a non-listed private URL stays blocked. Matching is exact+ `scheme://host:port` (default ports 80/443 implied, host+ case-insensitive, path/query ignored) — no wildcards or CIDR ranges, and+ hostnames are matched as text, so `localhost` and `127.0.0.1` are+ distinct entries (list both if unsure). Prefer IP-literal entries over+ hostnames where practical: a listed hostname grants whatever private+ address it resolves to at fetch time, while an IP entry pins the+ destination. List only origins you control — the grant also covers+ redirects served by the listed origin.+2. **Env-locked URL** — set+ `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL` to the exact+ URL. The setting becomes read-only in the UI and is trusted as+ operator-provisioned; this is what the bundled `docker-compose.yml` does+ (`http://searxng:8080`).+3. **Blanket opt-in** — `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true`. Allows+ *all* private/localhost/LAN engine URLs, including ones entered in the+ web UI. Broadest grant — prefer the allowlist when you can.++Regardless of which option is used:++- **Cloud metadata endpoints** (AWS IMDS / ECS, Azure, OCI, DigitalOcean,+ AlibabaCloud, Tencent Cloud — see+ `ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS`) are always blocked to prevent+ credential theft in cloud environments+- Only `http`/`https` URLs are accepted — other schemes are always refused### IPv6-only deployments (NAT64)@@ -125,7 +205,22 @@ The opt-in is scoped strictly to the two NAT64 prefixes — 6to4 (`2002::/16`),## Troubleshooting-If you encounter errors:+### SearXNG suddenly returns no results after upgrading to v1.10.3+++This is almost always the private-URL protection described above: a+localhost/LAN instance URL is no longer fetched by default. When SearXNG is+your selected search engine, the research form shows a dismissible warning+banner ("SearXNG is disabled: private URL not approved") naming the exact+remedies; the logs carry the same information as an error saying+`SearXNG engine disabled: instance URL … is a private / loopback /+link-local address`. Fix it by adding the URL+origin to `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST` (or env-locking the+URL, or setting `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true`) in the+server environment, then restarting. Note the allowlist variable ships in+a release NEWER than v1.10.4 — on v1.10.3/v1.10.4 use one of the other two+options.++### Other errors1. Check that your instance is running2. Verify the URL is correct in your environment variablesdiff --git a/docs/deployment/unraid.md b/docs/deployment/unraid.mdindex 99bf3312aa..a8069ca93c 100644--- a/docs/deployment/unraid.md+++ b/docs/deployment/unraid.md@@ -151,6 +151,15 @@ Configure these based on your setup:| `LDR_LLM_OLLAMA_URL` | `http://ollama:11434` | Use this if Ollama is on `ldr-network`<br>Use `http://[IP]:11434` for external Ollama || `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL` | `http://searxng:8080` | Use this if SearXNG is on `ldr-network`<br>Configure external search in WebUI otherwise |+> **SearXNG on a private/LAN address (v1.10.3+):** setting the URL via the env+> var above env-locks it and needs no further approval. If you instead enter a+> private address (e.g. `http://192.168.1.100:8080`) in the **WebUI**, it is+> rejected by default (SSRF protection) — also add+> `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://192.168.1.100:8080` (exact+> origin, comma-separate multiple; needs a release newer than v1.10.4, older+> versions use `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true`) to the+> container's environment. See [SearXNG-Setup](../SearXNG-Setup.md).+#### Optional LLM Configuration**Leave these EMPTY** unless you want to **LOCK** the configuration (prevents changes via WebUI):@@ -183,6 +192,10 @@ For multi-container setup (LDR + Ollama + SearXNG):If running LDR alone with external services:- Use bridge network (default)- Point to external services by IP: `http://192.168.1.100:11434`+- For SearXNG on a LAN IP, prefer the env var+ `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL` (trusted as+ operator-provisioned); a LAN URL entered in the WebUI additionally needs+ `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST` (see the note above)## 🎮 Using Local Documentsdiff --git a/docs/faq.md b/docs/faq.mdindex 88df7e098a..3a833c7bdd 100644--- a/docs/faq.md+++ b/docs/faq.md@@ -107,6 +107,15 @@ docker run -d -p 8080:8080 --name searxng searxng/searxngThen set the URL to `http://localhost:8080` in LDR settings.+> **Note (v1.10.3+):** a localhost/LAN instance URL is blocked by default+> (SSRF protection). The server operator must also approve it in the server+> environment: add the origin to+> `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://localhost:8080`+> (recommended; needs a release newer than v1.10.4), env-lock the URL via+> `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL` (as the bundled+> docker-compose does), or set `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true`.+> Only one of these is needed. See [SearXNG-Setup](SearXNG-Setup.md) for details.+### The cookiecutter command fails on WindowsFor Windows users, you can use the generated docker-compose file directly instead of running cookiecutter:@@ -119,7 +128,7 @@ services:ports:- "5000:5000"environment:- - SEARXNG_URL=http://searxng:8080+ - LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL=http://searxng:8080depends_on:- searxng@@ -244,17 +253,29 @@ After installing, restart LDR and re-export the PDF.### SearXNG connection errors-1. **Verify SearXNG is running**:+1. **Localhost/LAN URL blocked (v1.10.3+)?** If the logs say+ `SearXNG engine disabled: instance URL … is a private / loopback /+ link-local address`, the private-URL protection is refusing your+ self-hosted instance. In the server environment, add the origin to+ `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://localhost:8080`+ (recommended), or env-lock the URL via+ `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL`, or set+ `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true`. Only one of these is+ needed; then restart. See [SearXNG-Setup](SearXNG-Setup.md). (The allowlist variable+ ships in a release NEWER than v1.10.4 — on v1.10.3/v1.10.4 use one of the+ other two options.)++2. **Verify SearXNG is running**:```bashdocker ps | grep searxngcurl http://localhost:8080```-2. **For Docker networking issues**:+3. **For Docker networking issues**:- Use `http://searxng:8080` (container name) not `localhost`- Or use `--network host` mode-3. **Check browser access**: Navigate to `http://localhost:8080`+4. **Check browser access**: Navigate to `http://localhost:8080`### Rate limit errors@@ -447,7 +468,7 @@ curl -O https://raw.githubusercontent.com/LearningCircuit/local-deep-research/madocker compose up -d```-**If you want to stay on `docker run`:** drop `--network host`, keep `-p 5000:5000`, and point Ollama/SearXNG at `host.docker.internal` instead of `localhost`. Either set the URLs in **Settings → LLM** and **Settings → Search → SearXNG** after first login, or pass them as env vars on launch:+**If you want to stay on `docker run`:** drop `--network host`, keep `-p 5000:5000`, and point Ollama/SearXNG at `host.docker.internal` instead of `localhost`. Either set the URLs in **Settings → LLM** and **Settings → Search → SearXNG** after first login (the SearXNG URL then also needs operator approval — see the note below), or pass them as env vars on launch:```bashdocker run -d -p 5000:5000 \@@ -460,7 +481,7 @@ docker run -d -p 5000:5000 \localdeepresearch/local-deep-research```-Note: env vars passed on `docker run` always win over values you later change in the Settings UI (the env-var override is checked on every read), so if you plan to manage URLs from the UI, leave the `-e LDR_...` lines off.+Note: env vars passed on `docker run` always win over values you later change in the Settings UI (the env-var override is checked on every read), so if you plan to manage URLs from the UI, leave the `-e LDR_...` lines off. For the SearXNG URL specifically, a private address entered in the UI is blocked by default (v1.10.3+ SSRF protection) — approve it by passing e.g. `-e LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://host.docker.internal:8080` (see [SearXNG-Setup](SearXNG-Setup.md)); the env-locked `-e LDR_SEARCH_ENGINE_..._INSTANCE_URL` form above is already trusted and needs no extra approval.### "Database is locked" errorsdiff --git a/docs/install-pip.md b/docs/install-pip.mdindex a5014948ad..fb38501637 100644--- a/docs/install-pip.md+++ b/docs/install-pip.md@@ -17,12 +17,22 @@ docker run -d -p 8080:8080 --name searxng searxng/searxng# Step 4: Download a modelollama pull gemma3:12b-# Step 5: Start the web interface+# Step 5: Pin the SearXNG URL (which also marks it operator-approved —+# private/localhost engine URLs are otherwise blocked by default since+# v1.10.3) and start the web interface. The URL becomes read-only in the+# web UI; docs/SearXNG-Setup.md lists the alternatives, e.g. an origin+# allowlist.+export LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL=http://localhost:8080ldr-web```Open http://localhost:5000 after a few seconds.+> **SearXNG returns no results?** If the logs show `SearXNG engine disabled:+> instance URL … is a private / loopback / link-local address`, the allowlist+> env var above is missing from the environment running `ldr-web`. See+> [SearXNG-Setup](SearXNG-Setup.md) for all approval options.+## SQLCipher (Database Encryption)diff --git a/docs/installation.md b/docs/installation.mdindex 82cf348ffe..bc8b85c486 100644--- a/docs/installation.md+++ b/docs/installation.md@@ -86,10 +86,15 @@ docker run -d -p 11434:11434 --name ollama ollama/ollamadocker exec ollama ollama pull gpt-oss:20b# Step 3: Pull and run Local Deep Research+# (the URL line pins SearXNG's address AND marks it operator-approved —+# private/localhost engine URLs are otherwise blocked by default since+# v1.10.3. The URL becomes read-only in the web UI; docs/SearXNG-Setup.md+# lists the alternatives, e.g. an origin allowlist.)docker run -d -p 5000:5000 --network host \--name local-deep-research \--volume 'deep-research:/data' \-e LDR_DATA_DIR=/data \+ -e LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL=http://localhost:8080 \localdeepresearch/local-deep-research```@@ -113,7 +118,7 @@ docker run -d -p 5000:5000 \(`--add-host` is a no-op on Mac/Windows where `host.docker.internal` is already auto-injected, but makes the same recipe work on Linux Docker Desktop.)-If you'd rather not pass env vars, you can launch without them and then change the URLs after first login under **Settings → LLM → Ollama URL** and **Settings → Search → SearXNG → Instance URL**. For most users on these platforms, [Docker Compose](#docker-compose-recommended) is simpler — it wires the URLs up automatically via service names.+If you'd rather not env-lock the URLs, you can change the Ollama URL after first login under **Settings → LLM → Ollama URL**. For the SearXNG URL, note that a private address entered in the web UI (**Settings → Search → SearXNG → Instance URL**) is rejected since v1.10.3 unless the operator approves it — pass e.g. `-e LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://host.docker.internal:8080` alongside it (see [SearXNG-Setup](SearXNG-Setup.md)). For most users on these platforms, [Docker Compose](#docker-compose-recommended) is simpler — it wires the URLs up automatically via service names.Open http://localhost:5000 after ~30 seconds.diff --git a/docs/search-engines.md b/docs/search-engines.mdindex dafea8c1c7..3fde2b071d 100644--- a/docs/search-engines.md+++ b/docs/search-engines.md@@ -67,6 +67,13 @@ result = quick_summary(docker run -d -p 8080:8080 --name searxng searxng/searxng```- **Configuration**: Set URL to `http://localhost:8080` in settings+- **Note (v1.10.3+)**: a localhost/LAN URL additionally requires operator+ approval in the server environment — its origin listed in+ `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://localhost:8080`+ (recommended; needs a release newer than v1.10.4), env-locking the URL+ (as the bundled docker-compose does), or the blanket+ `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true` — only one is needed — see+ [SearXNG-Setup](SearXNG-Setup.md)#### DuckDuckGo- **Specialization**: Privacy-focused web search@@ -212,6 +219,11 @@ LDR supports multiple search strategies that determine how queries are processed## Troubleshooting### SearXNG Not Working+- Check the LDR logs for `SearXNG engine disabled: instance URL … is a+ private / loopback / link-local address` — if present, add the URL origin+ to `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST` (or set+ `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true`) in the server environment and+ restart (see [SearXNG-Setup](SearXNG-Setup.md))- Verify container is running: `docker ps | grep searxng`- Check URL in settings: `http://localhost:8080`- Test directly: `curl http://localhost:8080`diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 0a19f98184..eff340e0b0 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -123,22 +123,37 @@ This guide covers common issues and their solutions.**Symptoms:**- "Connection refused"- "404 Not Found"+- No SearXNG results, with `SearXNG engine disabled: instance URL … is a+ private / loopback / link-local address` in the logs**Solutions:**-1. **Verify SearXNG is running:**+1. **Localhost/LAN URL blocked (v1.10.3+)?** If the logs show the+ `SearXNG engine disabled: … private / loopback / link-local` error, the+ private-URL protection is refusing your self-hosted instance. Approve it+ in the server environment and restart: add the origin to+ `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://localhost:8080`+ (recommended), or env-lock the URL via+ `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL`, or set+ `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true`. Only one of these is+ needed. See+ [SearXNG-Setup](SearXNG-Setup.md). (The allowlist variable ships in the+ release NEWER than v1.10.4 — on v1.10.3/v1.10.4 use one of the other two+ options.)++2. **Verify SearXNG is running:**```bashcurl http://localhost:8080/search?q=test&format=json```-2. **Check URL configuration:**+3. **Check URL configuration:**- Settings UI: **Settings → Search → SearXNG → Instance URL**- Setting key: `search.engine.web.searxng.default_params.instance_url`- Env var: `LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL`-3. **Ensure JSON format is enabled** in SearXNG settings+4. **Ensure JSON format is enabled** in SearXNG settings-4. **Docker networking:** From inside the LDR container, `localhost` is the container itself, not your host. Use `http://searxng:8080` if SearXNG is a sibling service in Docker Compose, or `http://host.docker.internal:8080` if SearXNG runs on the host (Mac/Windows/WSL2 — see the [Windows/WSL2 FAQ entry](faq.md#port-5000-not-accessible-on-windows) for the full recipe).+5. **Docker networking:** From inside the LDR container, `localhost` is the container itself, not your host. Use `http://searxng:8080` if SearXNG is a sibling service in Docker Compose, or `http://host.docker.internal:8080` if SearXNG runs on the host (Mac/Windows/WSL2 — see the [Windows/WSL2 FAQ entry](faq.md#port-5000-not-accessible-on-windows) for the full recipe).### API Key Issues for Search Enginesdiff --git a/src/local_deep_research/defaults/.env.template b/src/local_deep_research/defaults/.env.templateindex 0ec268e22e..221aa5fca1 100644--- a/src/local_deep_research/defaults/.env.template+++ b/src/local_deep_research/defaults/.env.template@@ -20,5 +20,15 @@# LDR_SEARCH_ENGINE_WEB_GOOGLE_PSE_ENGINE_ID=your-programmable-search-engine-id-here# SearXNG Configuration+# Setting the instance URL here env-locks it (read-only in the web UI) and marks+# it operator-provisioned, which also permits a private/localhost address:# LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL=http://localhost:8080# LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_DELAY_BETWEEN_REQUESTS=2.0+#+# Self-hosted SearXNG on localhost/LAN, configured via the web UI instead:+# private / loopback / link-local engine URLs are blocked by default (SSRF+# protection) and need operator approval (see docs/SearXNG-Setup.md).+# Recommended: allowlist only the exact URL origins you use, comma-separated:+# LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://localhost:8080+# Or (broadest) allow all private engine URLs:+# LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=truediff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 0d0526fe03..8822626459 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. 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.",+ "description": "The SearXNG API endpoint URL. A private / loopback / link-local URL (including the default http://localhost:8080) is only fetched when the operator lists its origin in LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST, 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,@@ -5445,6 +5445,48 @@"value": false,"visible": true},+ "app.warnings.dismiss_searxng_private_url": {+ "category": "internal",+ "description": "Permanently hide the 'SearXNG is disabled: private URL not approved' banner that appears when SearXNG is active (selected as the search engine, or enabled for auto/agent search) but its private/localhost instance URL has no operator approval (allowlist, blanket opt-in, or env-lock) in the server environment.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Dismiss SearXNG private-URL warning",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "app.warnings.dismiss_paperless_public_url": {+ "category": "internal",+ "description": "Permanently hide the 'Paperless-ngx points at a non-private host' banner that appears when the Paperless engine is active but its API URL does not look like a private/local address (document queries would leave the machine; a private-only egress scope excludes the engine).",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Dismiss Paperless public-URL warning",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "app.warnings.dismiss_elasticsearch_public_url": {+ "category": "internal",+ "description": "Permanently hide the 'Elasticsearch points at a non-private host' banner that appears when the Elasticsearch engine is active but its hosts (or cloud_id) do not look like private/local addresses (document queries would leave the machine; a private-only egress scope excludes the engine). Dismiss when a hosted endpoint such as Elastic Cloud is intentional.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Dismiss Elasticsearch public-URL warning",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },"app.warnings.dismiss_adaptive_scope_info": {"category": "internal","description": "Permanently hide the informational banner that states what the Adaptive egress scope resolves to (public / private / both) for the current primary engine.",diff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.mdindex a5d23c4031..ce593fbcbd 100644--- a/src/local_deep_research/security/egress/README.md+++ b/src/local_deep_research/security/egress/README.md@@ -78,25 +78,29 @@ Vocabulary borrowed from XACML / zero-trust:| `policy.py` | The PDP. `EgressScope`, `EgressContext`, `Decision`, `EngineClassification`, `PolicyDeniedError`, `classify_engine()`, `context_from_snapshot()` (builds the frozen per-run context + resolves Adaptive), and the `evaluate_*()` decision functions. Also host classification (DNS + private-IP, NAT64 metadata, percent-decode), the run-scoped DNS cache, and the denied-fetch quota. || `audit_hook.py` | A process-wide **PEP-578 `sys.audit` hook** on `socket.connect`. The *secondary* net: catches outbound connections from code paths the explicit PEPs don't cover (third-party libs, new contributors using raw `requests`). Inactive until a worker calls `set_active_context(ctx)`; only gates PRIVATE_ONLY / STRICT. || `fetch.py` | `policy_aware_validate_url()` — the egress-scope-aware SSRF wrapper (lets PRIVATE_ONLY reach private lab hosts without disabling SSRF globally; metadata IPs stay blocked). Depends on `../ssrf_validator.py`, not the other way around. |-| `warnings.py` | The three UI banner checks (`check_public_egress_enabled`, `check_cloud_llm_enabled`, `check_cloud_embeddings_enabled`), each with its own dismiss key. Pure functions; the `web/warning_checks` orchestrator calls them. |-| `validators.py` | Settings-save cross-field validators (`validate_allowed_local_hostnames`). Pure functions; the settings write routes call them. |+| `warnings.py` | The UI banner checks, each with its own dismiss key: the egress-posture banners (`check_public_egress_enabled`, `check_unprotected_egress`, `check_effective_scope`, `check_trusted_destinations`, `check_cloud_llm_enabled`, `check_cloud_embeddings_enabled`) plus the engine-URL misconfiguration banners, generic over `validators.guarded_engine_url_descriptors()` (`check_private_engine_url_blocked` — an active public engine has an unapproved private instance URL, with a SearXNG convenience wrapper; `check_local_engine_public_url` — a local document engine points at a non-private-looking host). The `web/warning_checks` orchestrator loops the descriptors and calls them. |+| `validators.py` | Settings-save cross-field validators run via `first_egress_validation_error`: `validate_egress_scope`, `validate_allowed_local_hostnames`, `validate_trusted_search_engines`, and `validate_engine_instance_urls` (refuses a PUBLIC engine's user-editable URL that is or resolves to a private/loopback/link-local or cloud-metadata address, honoring the env-only operator gate `search.allow_private_engine_urls` and per-origin allowlist `search.private_engine_url_allowlist`). Pure functions; the settings write routes call them. || `__init__.py` | Re-exports the public PDP / audit-hook API. |### Public API```pythonfrom local_deep_research.security.egress import (- EgressScope, EgressContext, Decision, EngineClassification, PolicyDeniedError,- classify_engine, # classify an engine as public and/or local- context_from_snapshot, # build the per-run context- evaluate_engine, # may engine X run under this scope?- evaluate_retriever, # … for a registered retriever- evaluate_url, # may this URL be fetched?- evaluate_llm_endpoint, # is this LLM endpoint allowed?- evaluate_embeddings, # is this embeddings provider allowed?- set_active_context, # arm the audit-hook net for this thread+ EgressScope,+ EgressContext,+ Decision,+ EngineClassification,+ PolicyDeniedError,+ classify_engine, # classify an engine as public and/or local+ context_from_snapshot, # build the per-run context+ evaluate_engine, # may engine X run under this scope?+ evaluate_retriever, # … for a registered retriever+ evaluate_url, # may this URL be fetched?+ evaluate_llm_endpoint, # is this LLM endpoint allowed?+ evaluate_embeddings, # is this embeddings provider allowed?+ set_active_context, # arm the audit-hook net for this threadclear_active_context,- active_egress_context, # context manager form+ active_egress_context, # context manager forminstall_audit_hook,)```@@ -124,7 +128,8 @@ actually enforces the policy":| Embeddings | `embeddings/embeddings_config.py`, `…/implementations/sentence_transformers.py`, `web_search_engines/engines/local_embedding_manager.py` | `evaluate_embeddings` / scope-coupled require-local || Journal reputation fetch | `advanced_search_system/filters/journal_reputation_filter.py` | scope skip || Run-start precheck | `web/routes/research_routes.py` (`_precheck_engine_policy`) | `evaluate_engine` (clean 400 at the API boundary) |-| Settings validation | `web/routes/settings_routes.py` (calls `egress/validators.py`) | `validate_allowed_local_hostnames` |+| Settings validation | `web/routes/settings_routes.py` (calls `egress/validators.py`) | `first_egress_validation_error` (scope, local hostnames, trusted engines, public-engine instance URLs) |+| Public-engine instance fetch | `web_search_engines/engines/search_engine_searxng.py` via `egress/validators.resolve_engine_allow_private_ips` (SearXNG wrapper `resolve_searxng_allow_private_ips`; any future public engine with a `url_setting` must call it on its fetch path) | env-only operator gate / per-origin URL allowlist / engine's env-locked URL — a private instance URL is otherwise not fetched (engine self-disables with an ERROR naming the remedies) || Secondary net (all sockets) | `audit_hook.py` (installed at `security/__init__`) | `evaluate_url` on every `socket.connect` |Adjacent (general security utils, not egress-specific — used here but live one level up):diff --git a/src/local_deep_research/security/egress/validators.py b/src/local_deep_research/security/egress/validators.pyindex 2c04022da4..c03daecf4f 100644--- a/src/local_deep_research/security/egress/validators.py+++ b/src/local_deep_research/security/egress/validators.py@@ -1,17 +1,22 @@"""Cross-field egress-policy validators run at settings-save time.-Pure functions: each takes the about-to-be-saved ``form_data`` plus the-current ``all_db_settings`` (key -> setting row with a ``.value``) and returns-a validation-error dict ``{"key", "error"}`` to surface in the save response,-or ``None`` when the combination is fine.+Each validator takes the about-to-be-saved ``form_data`` plus the current+``all_db_settings`` (key -> setting row with a ``.value``) and returns a+validation-error dict ``{"key", "error"}`` to surface in the save response,+or ``None`` when the combination is fine. Most are pure; the engine-URL+guard machinery here (allowlist, operator-approval resolver, descriptor+sweep) additionally reads operator environment state — never the DB — and+the allowlist parser logs dropped entries once per distinct env value.The settings write routes (``web/routes/settings_routes.py``) orchestrate these— they stay in the route layer because they also enforce non-egress concerns —but the egress rules themselves live here next to the policy they encode."""+import functoolsimport ipaddress-from typing import Optional+from dataclasses import dataclass+from typing import Optional, Tuplefrom urllib.parse import unquote, urlsplitfrom ...utilities.type_utils import unwrap_setting@@ -188,9 +193,79 @@ def validate_trusted_search_engines(form_data, all_db_settings):return None-_PUBLIC_ENGINE_URL_SETTINGS_CACHE: Optional[frozenset] = None+@dataclass(frozen=True)+class GuardedEngineUrl:+ """A search engine whose configurable URL participates in the egress+ URL guards, derived from the engine class's own declarations.++ ``is_public`` True → the engine proxies the public internet, so a+ PRIVATE URL is the anomaly (save-time rejection + runtime refusal ++ "private URL not approved" banner). ``is_public`` False → a LOCAL+ document engine, where a PUBLIC-looking URL is the anomaly (advisory+ banner only — a hosted endpoint can be legitimate).++ Per-engine UI conventions derived from ``engine_name``:+ display name setting ``search.engine.web.{name}.display_name``,+ activation flags ``.enabled`` / ``.use_in_auto_search`` /+ ``.agent_enabled``, and dismiss keys+ ``app.warnings.dismiss_{name}_private_url`` (public) /+ ``app.warnings.dismiss_{name}_public_url`` (local) — each dismiss key+ must be registered in ``defaults/default_settings.json`` (pinned by a+ registry-contract test). A future public engine that declares+ ``url_setting`` must also call ``resolve_engine_allow_private_ips``+ on its fetch path, as SearXNG does.+ """++ engine_name: str+ url_setting: str+ is_public: bool++[email protected]_cache(maxsize=1)+def guarded_engine_url_descriptors() -> Tuple[GuardedEngineUrl, ...]:+ """All engines participating in the URL guards, from the registry.++ Derived once from ``ENGINE_REGISTRY`` + engine-class declarations+ (``url_setting`` plus ``is_public``/``is_local``); seeded with SearXNG+ so the canonical guard survives an engine-class import failure.++ COST NOTE: the first call imports every engine module in the registry+ (~1-3 s cold) to read the class declarations; results are cached for+ the process lifetime (``.cache_clear()`` resets, for tests). Callers on+ render paths pay this once per process.+ """+ found = {+ "searxng": GuardedEngineUrl(+ engine_name="searxng",+ url_setting=_SEARXNG_INSTANCE_URL_KEY,+ is_public=True,+ )+ }+ 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+ url_setting = getattr(cls, "url_setting", None)+ if not (isinstance(url_setting, str) and url_setting):+ continue+ if getattr(cls, "is_public", None) is True:+ found[name] = GuardedEngineUrl(+ engine_name=name, url_setting=url_setting, is_public=True+ )+ elif getattr(cls, "is_local", None) is True:+ found[name] = GuardedEngineUrl(+ engine_name=name, url_setting=url_setting, is_public=False+ )+ except Exception: # noqa: silent-exception - seed still guards SearXNG+ pass+ return tuple(found[name] for name in sorted(found))[email protected]_cache(maxsize=1)def _public_engine_url_settings() -> frozenset:"""URL-setting keys belonging to PUBLIC-nature search engines.@@ -202,30 +277,231 @@ def _public_engine_url_settings() -> frozenset:fail-up URL override already reclassifies them public when pointed at anexternal 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.+ Delegates to ``guarded_engine_url_descriptors`` so the save-time guard+ and the banner/orchestrator machinery can never disagree about which+ engines are covered (single registry sweep, single seed).+ """+ return frozenset(+ d.url_setting for d in guarded_engine_url_descriptors() if d.is_public+ )+++# Env-only operator allowlist of exact private engine-URL origins — the+# finer-grained alternative to the blanket search.allow_private_engine_urls+# gate (see env_definitions/security.py for the operator-facing contract).+_ALLOWLIST_SETTING_KEY = "search.private_engine_url_allowlist"++_DEFAULT_PORTS = {"http": 80, "https": 443}+++def _engine_url_origin(value):+ """Parse ``value`` into a comparable ``(scheme, host, port)`` origin.++ Normalization mirrors what actually denotes the same network+ destination and nothing more: scheme and host are lowercased, the host+ is stripped of a trailing dot, an IP-literal host is canonicalized+ through :mod:`ipaddress` (so ``[::1]`` and its long form compare+ equal), and a missing port takes the scheme default (80/443). Path,+ query, fragment, and userinfo are ignored — they don't change the+ destination host.++ Two deliberate refusals keep this parser from ever disagreeing with+ the HTTP client (urllib3) about which host a hostile URL names:+ URLs containing RFC-forbidden characters (backslash, whitespace,+ control chars — the parser-differential class) return ``None``, and+ the host is NOT percent-decoded (urllib3 doesn't decode either, so+ decoding here would match a destination the client never connects+ to). Returns ``None`` for anything that isn't a cleanly parseable+ http(s) URL with a hostname; every failure mode therefore fails+ CLOSED (no allowlist match), never open."""- 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+ text = str(value).strip()+ from ..ssrf_validator import RFC_FORBIDDEN_URL_CHARS_RE++ if RFC_FORBIDDEN_URL_CHARS_RE.search(text):+ return None+ parsed = urlsplit(text)+ scheme = (parsed.scheme or "").lower()+ if scheme not in _DEFAULT_PORTS:+ return None+ host = parsed.hostname+ if not host:+ return None+ host = host.rstrip(".").lower()+ if not host:+ return None+ try:+ host = str(ipaddress.ip_address(host))+ except ValueError:+ pass # not an IP literal — keep the hostname text+ port = parsed.port+ if port is None:+ port = _DEFAULT_PORTS[scheme]+ return (scheme, host, port)+ except Exception:+ return None- 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++def engine_url_origin_text(origin) -> str:+ """Render an ``_engine_url_origin`` tuple back to allowlist-entry text.++ The inverse of ``_engine_url_origin`` for display: IPv6 hosts are+ re-bracketed and a scheme-default port is omitted, so the returned+ string, fed into ``LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST``, is+ guaranteed to match the origin it was rendered from (round-trip by+ construction — pinned by the banner remedy tests). Lives next to the+ parser so the pair can't drift apart.+ """+ scheme, host, port = origin+ host_disp = f"[{host}]" if ":" in host else host+ suffix = "" if port == _DEFAULT_PORTS[scheme] else f":{port}"+ return f"{scheme}://{host_disp}{suffix}"+++# Raw allowlist value we last warned about — the dropped-entry WARNING is+# emitted once per distinct env value, not on every consult (the matcher+# runs on every settings save, engine init, and /api/warnings recompute).+_last_warned_allowlist_raw: Optional[str] = None+++def _private_engine_url_allowlist() -> frozenset:+ """Operator-approved private engine-URL origins from the environment.++ Reads the env-only ``search.private_engine_url_allowlist`` setting and+ parses each comma-separated entry with ``_engine_url_origin``.+ Unparseable entries are dropped (fail-closed) and warned about once per+ distinct env value. Any lookup error yields the empty set — the safe+ posture.+ """+ try:+ from ...settings.env_registry import get_env_setting++ raw = get_env_setting(_ALLOWLIST_SETTING_KEY, None)+ except Exception: # noqa: silent-exception - default to the safe posture+ return frozenset()+ if not raw or not isinstance(raw, str):+ return frozenset()+ origins = set()+ dropped = []+ for entry in raw.split(","):+ entry = entry.strip()+ if not entry:+ continue+ origin = _engine_url_origin(entry)+ if origin is not None:+ origins.add(origin)+ else:+ dropped.append(entry)+ if dropped:+ # An unparseable entry grants nothing (fail-closed), but silently+ # dropping it leaves the operator staring at the same rejection+ # message telling them to add the origin they think they already+ # added — so name what was ignored (once per distinct env value,+ # to keep a permanently-malformed entry from spamming the logs).+ global _last_warned_allowlist_raw+ if raw != _last_warned_allowlist_raw:+ _last_warned_allowlist_raw = raw+ try:+ from ..secure_logging import logger++ logger.warning(+ "Ignoring unparseable entries in "+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST (each entry "+ "must be a full origin like http://localhost:8080): "+ f"{dropped}"+ )+ except Exception: # noqa: silent-exception - best-effort logging+ pass+ return frozenset(origins)+++def engine_url_in_private_allowlist(url) -> bool:+ """True when ``url``'s origin is in the operator's env-only allowlist.++ Grants ONLY the private/loopback/link-local exemption a matching origin+ was listed for — callers consult it strictly in place of the blanket+ ``search.allow_private_engine_urls`` gate, so the cloud-metadata block+ and the http(s)-scheme requirement are unaffected by a listing.+ """+ origin = _engine_url_origin(url)+ if origin is None:+ return False+ return origin in _private_engine_url_allowlist()+++def resolve_engine_allow_private_ips(+ instance_url: str, url_setting: str+) -> bool:+ """Whether a PUBLIC engine may target a private/loopback instance URL.++ A public-nature engine 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 blanket LAN / localhost self-host case), OR+ 2. ``instance_url``'s exact origin is listed in the env-only operator+ allowlist ``search.private_engine_url_allowlist`` (the+ finer-grained alternative to the blanket opt-in), OR+ 3. the engine's own ``url_setting`` is env-locked (its derived+ ``LDR_…`` variable is set — Docker / operator-provisioned,+ trusted).++ All three 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 checkpass- _PUBLIC_ENGINE_URL_SETTINGS_CACHE = frozenset(keys)- return _PUBLIC_ENGINE_URL_SETTINGS_CACHE++ # 2. Operator allowlist: this exact origin was individually approved.+ try:+ if engine_url_in_private_allowlist(instance_url):+ return True+ except Exception: # noqa: silent-exception - fall through to next check+ pass++ # 3. Env-locked instance URL (Docker / operator-provisioned).+ try:+ from ...settings.manager import check_env_setting++ if check_env_setting(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 a public engine 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 a public engine is an+ # OPERATOR decision only — conditions 1–3 above.+ return False+++def resolve_searxng_allow_private_ips(instance_url: str) -> bool:+ """SearXNG-keyed convenience wrapper over+ ``resolve_engine_allow_private_ips`` (kept for the engine and tests)."""+ return resolve_engine_allow_private_ips(+ instance_url, _SEARXNG_INSTANCE_URL_KEY+ )def _engine_url_ssrf_error(key, value, *, allow_private: bool):@@ -326,9 +602,15 @@ def _engine_url_error(key, reason):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."+ "Self-hosted instances on localhost/LAN are still supported, but "+ "the server operator must approve them in the server "+ "environment: add this exact URL origin to "+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST (comma-separated "+ "scheme://host:port entries), or pin the URL via its LDR_ "+ "environment variable (as the bundled docker-compose.yml does), "+ "or set LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true to allow all "+ "private addresses. Only one of these is needed; restart after "+ "changing. See docs/SearXNG-Setup.md.")return {"key": key, "error": message}@@ -444,9 +726,12 @@ def validate_engine_instance_urls(form_data, all_db_settings):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.+ the private-address rejection for genuine LAN self-hosting, and the+ env-only allowlist ``search.private_engine_url_allowlist`` lifts it for+ specific listed origins only; Docker deployments instead env-lock the+ URL, which the route layer honors via ``check_env_setting`` before these+ validators run. Neither mechanism lifts the cloud-metadata or+ non-http(s)-scheme rejections."""guarded = _public_engine_url_settings()present = [k for k in guarded if k in form_data]@@ -471,7 +756,12 @@ def validate_engine_instance_urls(form_data, all_db_settings):# 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)+ err = _engine_url_ssrf_error(+ key,+ value,+ allow_private=allow_private+ or engine_url_in_private_allowlist(value),+ )if err is not None:return errreturn Nonediff --git a/src/local_deep_research/security/egress/warnings.py b/src/local_deep_research/security/egress/warnings.pyindex d048795772..35c3779069 100644--- a/src/local_deep_research/security/egress/warnings.py+++ b/src/local_deep_research/security/egress/warnings.py@@ -1,11 +1,14 @@"""Egress-policy warning checks.-Pure functions: take primitive values, return a warning dict or ``None``.+Check functions: take primitive values, return a warning dict or ``None``.These surface on the research-form banner so users can see at a glance-when their current policy lets data leave the machine.+when their current policy lets data leave the machine — or silently+blocks something they configured. Most checks are pure; the engine-URL+checks additionally read operator environment state (never the DB) and+never resolve DNS, so all of them stay cheap enough for the+page-render hot path.-The audit identified three independent vectors that each deserve their-own banner:+The banners, each with its own dismiss flag:1. **Public search egress enabled** — the active scope permits any publicengine to fire. The default scope ``adaptive`` can resolve to a@@ -17,6 +20,15 @@ own banner:user's full prompt content leaks on every research run.3. **Cloud embeddings enabled** — even worse: indexing a corpus withOpenAI embeddings POSTs every chunk to OpenAI. Critical-severity.+4. **Unprotected egress / effective scope / trusted destinations** —+ posture-transparency banners for the egress-scope machinery.+5. **SearXNG private URL not approved** — the selected public engine's+ private instance URL lacks operator approval, so the engine will+ silently self-disable at run time.+6. **Local engine public URL** — the mirror image: a LOCAL document+ engine (Paperless, Elasticsearch) points at a host that does not look+ private, so document queries would leave the box and a private-only+ scope excludes the engine."""from typing import Optional@@ -191,6 +203,277 @@ def check_effective_scope(}+def check_private_engine_url_blocked(+ display_name: str,+ engine_name: str,+ url_setting: str,+ instance_url: str,+ active: bool,+ acknowledged: bool,+) -> Optional[dict]:+ """Banner when an active PUBLIC engine's instance URL is a+ private/loopback address the egress guard will refuse to fetch.++ Generic over any engine in ``guarded_engine_url_descriptors()`` with+ ``is_public=True`` — the banner type, dismiss key, env-lock variable,+ and settings anchor are all derived from ``engine_name`` /+ ``url_setting``, so a future public engine with a configurable URL is+ covered by declaration, not by new code.++ Without this, the failure mode is quiet: the engine disables itself at+ init with only a log-panel ERROR, and research runs simply return no+ results from it. This banner surfaces the misconfiguration on the+ research form with the exact operator remedies.++ Cheap by design (no DNS on the page-render hot path): a literal-IP host+ is classified with the SSRF validator's own ``is_ip_blocked`` (so CGNAT+ and every other range the gate blocks fire the banner, and metadata /+ always-blocked addresses — which the env remedies would not help — stay+ silent); a hostname is classified with the ``is_private_ip`` known-name+ check. A private-DNS hostname (``searx.internal`` → 10.x) and a+ short-form literal (``127.1``) are therefore missed here — the runtime+ gate still blocks them and logs the remediation; this advisory covers+ the dominant localhost / LAN-literal case, mirroring the+ cloud-embeddings banner's no-DNS tradeoff. Approval state is read via+ the operator-approval resolver (blanket gate / origin allowlist /+ env-locked URL), which reads only environment state. The displayed+ remedy is derived from the SAME parser the allowlist uses+ (``_engine_url_origin``), so the printed line round-trips by+ construction; a URL that parser refuses (malformed port, forbidden+ characters) yields no banner rather than an unusable remedy. Fails+ toward NO banner on any error — advisory, never load-bearing.+ """+ if acknowledged or not active:+ return None+ if not instance_url or not isinstance(instance_url, str):+ return None+ try:+ import ipaddress++ from ..network_utils import is_private_ip+ from ..ssrf_validator import is_ip_blocked+ from .validators import (+ _engine_url_origin,+ engine_url_origin_text,+ resolve_engine_allow_private_ips,+ )++ parsed_origin = _engine_url_origin(instance_url)+ if parsed_origin is None:+ return None+ _scheme, host, _port = parsed_origin++ try:+ ipaddress.ip_address(host)+ is_literal = True+ except ValueError:+ is_literal = False+ if is_literal:+ # Fire only for addresses the gate blocks SOLELY as private —+ # metadata/always-blocked fall out of the loose call.+ strict = is_ip_blocked(+ host, allow_localhost=False, allow_private_ips=False+ )+ loose = is_ip_blocked(+ host, allow_localhost=True, allow_private_ips=True+ )+ if not strict or loose:+ return None+ elif not is_private_ip(host):+ return None++ if resolve_engine_allow_private_ips(instance_url, url_setting):+ return None++ # Origin for the copy-paste remedy — rendered by the allowlist's own+ # inverse formatter, so feeding it back into the allowlist is+ # guaranteed to match; never the raw URL, so userinfo/path/query+ # never appear.+ origin = engine_url_origin_text(parsed_origin)+ env_lock_var = "LDR_" + url_setting.upper().replace(".", "_")+ anchor = "setting-" + url_setting.replace(".", "-")+ except Exception: # noqa: silent-exception - advisory only+ return None++ return {+ "type": f"{engine_name}_private_url_blocked",+ "icon": "🚫",+ "title": f"{display_name} is disabled: private URL not approved",+ "message": (+ f"{display_name} is enabled as a search engine, but its "+ f"instance URL ({origin}) is a private/localhost address, "+ "which is not fetched by default — research runs will return "+ f"no {display_name} results. The server operator must approve "+ "it in the server environment and restart LDR: set "+ f"LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST={origin} "+ f"(recommended), or env-lock the URL via {env_lock_var}, or "+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true to allow all "+ "private URLs. Only one of these is needed."+ ),+ "dismissKey": f"app.warnings.dismiss_{engine_name}_private_url",+ "actionUrl": f"/settings#{anchor}",+ "actionLabel": f"Open {display_name} settings",+ }+++def check_searxng_private_url_blocked(+ primary_engine: str,+ instance_url: str,+ acknowledged: bool,+) -> Optional[dict]:+ """SearXNG-keyed convenience wrapper over+ ``check_private_engine_url_blocked``. Test-facing only — production+ emission goes through the orchestrator's descriptor loop; this wrapper+ exists so focused tests can exercise the SearXNG parameterization+ (active = SearXNG is the selected primary engine) without duplicating+ the declaration constants."""+ return check_private_engine_url_blocked(+ "SearXNG",+ "searxng",+ "search.engine.web.searxng.default_params.instance_url",+ instance_url,+ (primary_engine or "").lower() == "searxng",+ acknowledged,+ )+++def _extract_engine_hosts(urls) -> list:+ """Best-effort host extraction from an engine URL setting value.++ Accepts a single URL string, a list of URL strings, or a JSON/comma+ string of them (settings saved via the web UI may arrive as raw JSON+ text — same class of input ``SearXNGSearchEngine._normalize_list``+ handles). Entries that cannot be parsed are skipped: this feeds an+ advisory banner, so failure means silence, never breakage.+ """+ import json as _json+ from urllib.parse import urlsplit++ if urls is None:+ return []+ if isinstance(urls, str):+ stripped = urls.strip()+ if not stripped:+ return []+ try:+ parsed = _json.loads(stripped)+ urls = parsed if isinstance(parsed, list) else [stripped]+ except (ValueError, RecursionError):+ urls = [u.strip() for u in stripped.split(",") if u.strip()]+ if not isinstance(urls, list):+ return []+ hosts = []+ for entry in urls:+ if not isinstance(entry, str) or not entry.strip():+ continue+ text = entry.strip()+ try:+ host = urlsplit(text).hostname+ if not host and "://" not in text:+ # Bare "host:9200" / "host" forms (Elasticsearch accepts+ # them): urlsplit reads the host as the scheme, so re-parse+ # as a network location.+ host = urlsplit("//" + text).hostname+ if host:+ hosts.append(host)+ except Exception: # noqa: silent-exception - advisory only+ continue+ return hosts+++def check_local_engine_public_url(+ display_name: str,+ engine_name: str,+ urls,+ active: bool,+ acknowledged: bool,+ extra: str = "",+ url_setting: str = "",+) -> Optional[dict]:+ """Banner when a LOCAL document engine (Paperless, Elasticsearch) points+ at a host that does not look private.++ The mirror image of the SearXNG private-URL banner: for a public engine+ a private URL is the anomaly, for a local document store a PUBLIC one+ is — search queries about the user's private documents are sent to that+ host, and the PDP's fail-up reclassifies the engine as exposing, so a+ Private-only egress scope silently excludes it from runs. Both+ consequences are surprising, so surface them.++ Advisory only, never a block: a genuinely-public endpoint can be a+ deliberate choice (e.g. Elastic Cloud). Classification is cheap and+ DNS-free: a host counts as local when the ``is_private_ip`` known-name+ check says so, when it is a dotless single label (a Docker/compose+ service name like ``paperless`` can never be public DNS), or when it+ is an IP literal in a range the egress gate itself treats as private+ (CGNAT and friends, via ``is_ip_blocked``). A multi-label private-DNS+ hostname (``paperless.internal`` → 10.x) is still flagged even though+ nothing would leave the box — the banner over-warns in the safe+ direction and is dismissible. Fails toward silence on any error.+ """+ if acknowledged or not active:+ return None+ try:+ import ipaddress++ from ..network_utils import is_private_ip+ from ..ssrf_validator import is_ip_blocked++ def _looks_local(host: str) -> bool:+ # IP literals FIRST: an IPv6 literal contains no dot, so the+ # dotless-service-name shortcut below would otherwise swallow+ # every IPv6 address, public ones included.+ try:+ ipaddress.ip_address(host)+ except ValueError:+ # Not an IP literal: known-private/localhost names, or a+ # dotless single label (a Docker/compose service name can+ # never be public DNS). Multi-label hostnames can't be+ # verified without DNS and stay flagged.+ return is_private_ip(host) or "." not in host+ # IP literal: defer to the gate's own private classification+ # (covers CGNAT etc. that is_private_ip doesn't know about).+ return is_ip_blocked(+ host, allow_localhost=False, allow_private_ips=False+ ) and not is_ip_blocked(+ host, allow_localhost=True, allow_private_ips=True+ )++ flagged = sorted(+ {h for h in _extract_engine_hosts(urls) if not _looks_local(h)}+ )+ except Exception: # noqa: silent-exception - advisory only+ return None+ labels = flagged + ([extra] if extra else [])+ if not labels:+ return None++ subject = ", ".join(labels)+ action_url = (+ f"/settings#setting-{url_setting.replace('.', '-')}"+ if url_setting+ else "/settings"+ )+ return {+ "type": f"{engine_name}_public_url",+ "icon": "📤",+ "title": f"{display_name} points at a non-private host",+ "message": (+ f"Your {display_name} engine is configured for {subject}, "+ "which does not look like a private/local address. Searches "+ "send queries about your private documents to that host, and "+ "under a Private-only egress scope the engine is excluded from "+ "runs entirely. If this is a deliberate, trusted hosted "+ "endpoint, dismiss this warning. (Multi-label private-DNS "+ "hostnames cannot be verified without a lookup and may be "+ "flagged incorrectly.)"+ ),+ "dismissKey": f"app.warnings.dismiss_{engine_name}_public_url",+ "actionUrl": action_url,+ "actionLabel": f"Review {display_name} settings",+ }++def check_cloud_llm_enabled(provider: str,require_local_endpoint: bool,diff --git a/src/local_deep_research/settings/env_definitions/security.py b/src/local_deep_research/settings/env_definitions/security.pyindex c168ab701e..c4ab52dcc6 100644--- a/src/local_deep_research/settings/env_definitions/security.py+++ b/src/local_deep_research/settings/env_definitions/security.py@@ -99,7 +99,10 @@ SECURITY_SETTINGS = ["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 "+ "your private network. To approve only specific origins instead "+ "of all private addresses, use the finer-grained "+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST. "+ "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 "@@ -107,6 +110,29 @@ SECURITY_SETTINGS = [),default=False,),+ StringSetting(+ key="search.private_engine_url_allowlist",+ description=(+ "Comma-separated list of exact URL origins "+ "(scheme://host[:port]) that user-editable PUBLIC search-engine "+ "URLs (e.g. the SearXNG instance_url) may use even though they "+ "are private / loopback / link-local — e.g. "+ "'http://localhost:8080,http://192.168.1.5:8888'. Finer-grained "+ "alternative to LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true: "+ "private egress is enabled for an engine only when its "+ "configured URL matches a listed origin (the engine's request "+ "chain, including redirects, then runs with private access — "+ "like the blanket flag, but conditional on the match), rather "+ "than for any private URL. Matching is exact scheme + host + port "+ "(default ports 80/443 implied, host case-insensitive, "+ "path/query ignored); no wildcards or CIDR ranges. Entries that "+ "fail to parse are ignored. Environment-only operator setting "+ "so it cannot be edited through the user-writable settings API. "+ "Cloud-metadata endpoints (ALWAYS_BLOCKED_METADATA_IPS) and "+ "non-http(s) schemes stay blocked even if listed."+ ),+ default=None,+ ),BooleanSetting(key="research_library.allow_filesystem_pdf_storage",description=(diff --git a/src/local_deep_research/web/warning_checks/__init__.py b/src/local_deep_research/web/warning_checks/__init__.pyindex b79024df5f..b462a095f5 100644--- a/src/local_deep_research/web/warning_checks/__init__.py+++ b/src/local_deep_research/web/warning_checks/__init__.py@@ -31,6 +31,8 @@ from ...security.egress.warnings import (check_cloud_embeddings_enabled,check_cloud_llm_enabled,check_effective_scope,+ check_local_engine_public_url,+ check_private_engine_url_blocked,check_public_egress_enabled,check_trusted_destinations,check_unprotected_egress,@@ -268,6 +270,98 @@ def calculate_warnings() -> List[dict]:if w:warnings.append(w)+ # Engine-URL misconfiguration banners, driven entirely by the+ # engine declarations (url_setting + is_public/is_local) that+ # guarded_engine_url_descriptors() collects from the registry:+ # - a PUBLIC engine (SearXNG) whose private instance URL lacks+ # operator approval silently self-disables at run time;+ # - a LOCAL document engine (Paperless, Elasticsearch) whose+ # URL looks public would send document queries off-box and+ # is excluded under a private-only scope (fail-up).+ # Display names, activation flags, and dismiss keys follow the+ # per-engine settings conventions, so a future engine is covered+ # by declaring url_setting — not by editing this file.+ # A failure in this loop (settings read, descriptor sweep) must+ # not swallow the later backup/history banners, so it gets its+ # own guard rather than relying on the function-wide except.+ try:+ primary_lower = str(primary_engine or "").lower()+ from ...security.egress.validators import (+ guarded_engine_url_descriptors,+ )++ for desc in guarded_engine_url_descriptors():+ name = desc.engine_name+ base = f"search.engine.web.{name}"+ display = (+ settings_manager.get_setting(f"{base}.display_name", "")+ or name.replace("_", " ").title()+ )+ url_value = settings_manager.get_setting(+ desc.url_setting, ""+ )+ engine_active = primary_lower == name or any(+ bool(+ settings_manager.get_setting(+ f"{base}.{flag}", False+ )+ )+ for flag in (+ "enabled",+ "use_in_auto_search",+ "agent_enabled",+ )+ )+ if desc.is_public:+ w = _safe_check(+ check_private_engine_url_blocked,+ display_name=display,+ engine_name=name,+ url_setting=desc.url_setting,+ instance_url=url_value,+ active=engine_active,+ acknowledged=bool(+ settings_manager.get_setting(+ f"app.warnings.dismiss_{name}_private_url",+ False,+ )+ ),+ )+ else:+ # Engine-specific public-endpoint indicator: an+ # Elasticsearch cloud_id always targets Elastic+ # Cloud, regardless of what the hosts list says.+ extra = ""+ if name == "elasticsearch":+ cloud_id = settings_manager.get_setting(+ f"{base}.default_params.cloud_id", ""+ )+ if str(cloud_id or "").strip():+ extra = "Elastic Cloud (cloud_id)"+ w = _safe_check(+ check_local_engine_public_url,+ display_name=display,+ engine_name=name,+ urls=url_value,+ active=engine_active,+ acknowledged=bool(+ settings_manager.get_setting(+ f"app.warnings.dismiss_{name}_public_url",+ False,+ )+ ),+ extra=extra,+ url_setting=desc.url_setting,+ )+ if w:+ warnings.append(w)+ except Exception:+ # logger.exception, not debug: if the descriptor sweep+ # breaks (e.g. an engine-import regression) the whole+ # banner feature goes dark — that must be visible in+ # production logs, matching _safe_check's severity bar.+ logger.exception("engine-URL warning banners skipped")+# --- Backup checks ---w = _safe_check(check_backup_disabled, backup_enabled, dismiss_backup_disableddiff --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.pyindex f8bd5c0de2..16293efb0d 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,61 +12,15 @@ from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivityfrom ...security.secure_logging import loggerfrom ._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+# The operator-approval resolver lives in security/egress/validators.py next+# to the allowlist matcher it consults (dependency direction: engine →+# security, same as everything else here). Re-exported under the historical+# private name so this module's call sites and the existing test imports+# keep their import path (the signature itself gained the instance-URL+# argument when the resolver was generalized).+from ...security.egress.validators import (+ resolve_searxng_allow_private_ips as _resolve_searxng_allow_private_ips,+)@enum.unique@@ -151,10 +105,11 @@ class SearXNGSearchEngine(BaseSearchEngine):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.+ private/loopback/link-local with no operator approval active+ (no allowlist match, no blanket opt-in, no env-locked URL).- Used to decide whether to surface the- ``LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS`` remediation hint. Detects+ Used to decide whether to surface the operator-remediation hint+ (allowlist / blanket opt-in / env-lock). Detectsthe case precisely so the hint fires for the common localhostself-host misconfiguration but NOT for unrelated failures (DNS /timeout / a genuinely-public URL) nor for an ALWAYS-blocked@@ -236,7 +191,9 @@ class SearXNGSearchEngine(BaseSearchEngine):# 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()+ self._allow_private_ips = _resolve_searxng_allow_private_ips(+ self.instance_url+ )try:# Make sure it's accessible.response = safe_get(@@ -258,21 +215,32 @@ 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."- )+ private_url_hint = self._private_url_blocked_by_gate()+ else:+ private_url_hint = False+ if private_url_hint:+ # The dominant self-host case: default localhost:8080 SearXNG+ # with no operator opt-in. The generic exception above never+ # names the fix, so surface it explicitly on this runtime+ # path — at ERROR, so the actionable message is at least as+ # loud as the generic one preceding it. (Emitted outside the+ # handler: there is no second traceback to attach, and the+ # logger.exception-in-handler rule stays satisfied.)+ logger.error(+ "SearXNG engine disabled: instance URL "+ f"{redact_url_for_log(self.instance_url)} is a private / "+ "loopback / link-local address, which is not fetched by "+ "default. To use a self-hosted SearXNG on localhost/LAN, "+ "the server operator must approve it in the server "+ "environment and restart: add the URL origin to "+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST, or env-lock "+ "the URL via "+ "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL "+ "(as the bundled docker-compose does), or set "+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true. Only one of "+ "these is needed. Cloud-metadata addresses stay blocked "+ "regardless. See docs/SearXNG-Setup.md."+ )# Add debug logging for all parameterslogger.info(diff --git a/tests/security/test_egress_settings_save_validators.py b/tests/security/test_egress_settings_save_validators.pyindex 1cc14ce617..b1cab7969c 100644--- a/tests/security/test_egress_settings_save_validators.py+++ b/tests/security/test_egress_settings_save_validators.py@@ -38,6 +38,7 @@ 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"+ALLOWLIST_ENV = "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST"MODULE = "local_deep_research.web.routes.settings_routes"DECORATOR_MODULE = "local_deep_research.web.utils.route_decorators"@@ -271,6 +272,241 @@ def test_operator_gate_still_rejects_non_http_scheme(monkeypatch):assert err is not None+# ---------------------------------------------------------------------------+# search.private_engine_url_allowlist+# (env-only per-origin alternative to the blanket operator gate)+# ---------------------------------------------------------------------------++# Hermetic DNS: hostname URLs in these tests resolve to loopback via this+# patch, so rejection can never silently flip to the unresolvable-host+# fail-open in a resolver-less sandbox.+LOOPBACK_ADDRINFO = [(2, 1, 6, "", ("127.0.0.1", 0))]+++def test_allowlisted_private_instance_url_is_accepted(monkeypatch):+ """A private URL whose exact origin is operator-allowlisted is accepted+ without the blanket opt-in."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://localhost:8080")+ loopback = [(2, 1, 6, "", ("127.0.0.1", 0))]+ with patch.object(+ validators, "_resolve_with_timeout", return_value=loopback+ ):+ assert (+ validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "http://localhost:8080"}, {}+ )+ is None+ )+++def test_allowlist_is_exact_origin(monkeypatch):+ """Matching is exact scheme+host+port: a different port or host does not+ match, and the rejection names the allowlist variable as a remedy."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://localhost:8080")+ for url in (+ "http://localhost:9090",+ "http://127.0.0.1:8080", # different host TEXT, even if same machine+ "https://localhost:8080", # different scheme+ "http://10.0.0.1:8080",+ ):+ with patch.object(+ validators, "_resolve_with_timeout", return_value=LOOPBACK_ADDRINFO+ ):+ err = validate_engine_instance_urls({SEARXNG_URL_KEY: url}, {})+ assert err is not None, f"expected {url} to be rejected"+ assert ALLOWLIST_ENV in err["error"]+++def test_allowlist_cosmetic_variants_match(monkeypatch):+ """Purely cosmetic URL variation of a listed origin still matches: host+ case, a trailing dot, a trailing slash / path, and an explicit default+ port."""+ monkeypatch.setenv(+ ALLOWLIST_ENV, "http://localhost:8080, https://searx.lan"+ )+ # Every hostname resolves private, so acceptance can ONLY come from the+ # allowlist match — never from the unresolvable-host fail-open.+ loopback = [(2, 1, 6, "", ("127.0.0.1", 0))]+ for url in (+ "HTTP://LOCALHOST:8080",+ "http://localhost.:8080",+ "http://localhost:8080/",+ "http://localhost:8080/searxng",+ "https://searx.lan:443",+ ):+ with patch.object(+ validators, "_resolve_with_timeout", return_value=loopback+ ):+ assert (+ validate_engine_instance_urls({SEARXNG_URL_KEY: url}, {})+ is None+ ), f"expected {url} to match the allowlist"+++def test_allowlist_ipv6_literal_is_canonicalized(monkeypatch):+ """IPv6 textual variants of the same address compare equal."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://[0:0:0:0:0:0:0:1]:8080")+ assert (+ validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "http://[::1]:8080"}, {}+ )+ is None+ )+++def test_allowlist_never_licenses_metadata(monkeypatch):+ """Listing a cloud-metadata origin grants nothing — the always-blocked+ set is checked before the private exemption the allowlist provides."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://169.254.169.254:80")+ 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_allowlist_never_licenses_non_http_scheme(monkeypatch):+ """Non-http(s) entries are unparseable as origins and grant nothing."""+ monkeypatch.setenv(ALLOWLIST_ENV, "gopher://10.0.0.1:70")+ err = validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "gopher://10.0.0.1:70"}, {}+ )+ assert err is not None+++def test_allowlist_malformed_entries_are_ignored(monkeypatch):+ """Junk entries neither grant access nor break parsing of valid ones."""+ monkeypatch.setenv(+ ALLOWLIST_ENV, "not a url,,http://[broken:8080,http://localhost:8080"+ )+ with patch.object(+ validators, "_resolve_with_timeout", return_value=LOOPBACK_ADDRINFO+ ):+ # Hermetic DNS: acceptance must come from the surviving allowlist+ # entry, never from the unresolvable-host fail-open.+ assert (+ validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "http://localhost:8080"}, {}+ )+ is None+ )+ err = validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "http://10.0.0.1:8080"}, {}+ )+ assert err is not None+++def test_allowlist_parser_differential_url_never_matches_or_saves(monkeypatch):+ """A backslash URL that urlsplit and urllib3 read as DIFFERENT hosts+ (GHSA-g23j-2vwm-5c25 shape) must neither match the allowlist nor pass+ the save validator — the RFC-forbidden-chars guard closes the parser+ differential on both layers."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://localhost:8080")+ hostile = "http://evil.internal\\@localhost:8080"+ assert validators.engine_url_in_private_allowlist(hostile) is False+ err = validate_engine_instance_urls({SEARXNG_URL_KEY: hostile}, {})+ assert err is not None+++def test_allowlist_schemeless_entry_grants_nothing(monkeypatch):+ """The most likely operator mistake — omitting the scheme — must not+ grant access (urlsplit reads 'localhost:8080' as scheme 'localhost')."""+ monkeypatch.setenv(ALLOWLIST_ENV, "localhost:8080")+ with patch.object(+ validators, "_resolve_with_timeout", return_value=LOOPBACK_ADDRINFO+ ):+ err = validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "http://localhost:8080"}, {}+ )+ assert err is not None+++def test_allowlist_whitespace_only_env_grants_nothing(monkeypatch):+ monkeypatch.setenv(ALLOWLIST_ENV, " , , ")+ with patch.object(+ validators, "_resolve_with_timeout", return_value=LOOPBACK_ADDRINFO+ ):+ err = validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "http://localhost:8080"}, {}+ )+ assert err is not None+++def test_allowlist_ipv4_mapped_ipv6_is_a_distinct_origin(monkeypatch):+ """Listed 127.0.0.1 must not match the IPv4-mapped IPv6 form and vice+ versa — canonicalization is address-preserving, never widening."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://127.0.0.1:8080")+ err = validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "http://[::ffff:127.0.0.1]:8080"}, {}+ )+ assert err is not None++ monkeypatch.setenv(ALLOWLIST_ENV, "http://[::ffff:127.0.0.1]:8080")+ err = validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "http://127.0.0.1:8080"}, {}+ )+ assert err is not None+++def test_allowlist_ipv6_zone_id_is_part_of_the_origin(monkeypatch):+ """A link-local zone ID distinguishes origins: same zone matches, a+ different zone does not."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://[fe80::1%eth0]:8080")+ assert (+ validators.engine_url_in_private_allowlist("http://[fe80::1%eth0]:8080")+ is True+ )+ assert (+ validators.engine_url_in_private_allowlist("http://[fe80::1%eth1]:8080")+ is False+ )+++def test_allowlist_percent_encoded_host_never_matches_or_saves(monkeypatch):+ """The host is deliberately NOT percent-decoded for allowlist matching+ (urllib3 doesn't decode either), so an encoded 'localhost' neither+ matches the listing nor slips past the save validator (whose own+ classification path decodes and resolves it to loopback)."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://localhost:8080")+ encoded = "http://%6c%6f%63%61%6c%68%6f%73%74:8080"+ assert validators.engine_url_in_private_allowlist(encoded) is False+ with patch.object(+ validators, "_resolve_with_timeout", return_value=LOOPBACK_ADDRINFO+ ):+ err = validate_engine_instance_urls({SEARXNG_URL_KEY: encoded}, {})+ assert err is not None+++def test_allowlist_trailing_dot_after_port_fails_closed(monkeypatch):+ """`:8080.` is not a parseable port — the origin is None, so the URL+ neither matches the listing nor saves (host still resolves loopback)."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://localhost:8080")+ with patch.object(+ validators, "_resolve_with_timeout", return_value=LOOPBACK_ADDRINFO+ ):+ err = validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "http://localhost:8080."}, {}+ )+ assert err is not None+++def test_allowlisted_hostname_matches_textually(monkeypatch):+ """The allowlist matches the origin TEXT the operator listed — a listed+ internal hostname is accepted even though it resolves to a private+ address (that resolution is exactly what the operator approved)."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://searx.internal.example:8080")+ addrinfo = [(2, 1, 6, "", ("10.0.0.5", 0))]+ with patch.object(+ validators, "_resolve_with_timeout", return_value=addrinfo+ ):+ assert (+ validate_engine_instance_urls(+ {SEARXNG_URL_KEY: "http://searx.internal.example:8080"}, {}+ )+ is None+ )++def test_engine_url_guard_runs_via_first_error():"""The new validator is wired into the shared entry point used by everysettings-save route."""diff --git a/tests/security/test_guarded_engine_url_contract.py b/tests/security/test_guarded_engine_url_contract.pynew file mode 100644index 0000000000..4353d02982--- /dev/null+++ b/tests/security/test_guarded_engine_url_contract.py@@ -0,0 +1,130 @@+"""Registry contract for the engine-URL guard/banner machinery.++The whole chain (save-time validator, runtime resolver, warning banners,+orchestrator wiring) is driven by ``guarded_engine_url_descriptors()``,+which derives from engine-class declarations. These tests pin the contract+a NEW engine must satisfy when it declares ``url_setting``: its derived+dismiss key must be registered, and the generic banner must derive all its+identifiers correctly.+"""++import json+from pathlib import Path++from local_deep_research.security.egress.validators import (+ guarded_engine_url_descriptors,+)+from local_deep_research.security.egress.warnings import (+ check_private_engine_url_blocked,+)++DEFAULTS_PATH = (+ Path(__file__).resolve().parents[2]+ / "src"+ / "local_deep_research"+ / "defaults"+ / "default_settings.json"+)++APPROVAL_ENVS = (+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS",+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST",+)+++class TestDescriptorRegistry:+ def test_known_engines_present_with_correct_nature(self):+ by_name = {d.engine_name: d for d in guarded_engine_url_descriptors()}+ assert by_name["searxng"].is_public is True+ assert by_name["paperless"].is_public is False+ assert by_name["elasticsearch"].is_public is False++ def test_every_descriptor_has_registered_dismiss_key(self):+ """A new engine declaring url_setting MUST register its derived+ dismiss key in defaults/default_settings.json — otherwise the+ banner's dismiss button would POST an unknown settings key."""+ defaults = json.loads(DEFAULTS_PATH.read_text())+ missing = []+ for d in guarded_engine_url_descriptors():+ suffix = "private_url" if d.is_public else "public_url"+ key = f"app.warnings.dismiss_{d.engine_name}_{suffix}"+ if key not in defaults:+ missing.append(key)+ assert not missing, (+ "unregistered dismiss keys for guarded engine URLs: "+ f"{missing} — add them to defaults/default_settings.json"+ )++ def test_descriptor_url_settings_are_nonempty_strings(self):+ for d in guarded_engine_url_descriptors():+ assert isinstance(d.url_setting, str) and d.url_setting+++class TestGenericBannerDerivation:+ """The generic banner derives type / dismiss key / env-lock var /+ settings anchor purely from the engine declaration."""++ def test_identifiers_derived_from_declaration(self, monkeypatch):+ for var in APPROVAL_ENVS:+ monkeypatch.delenv(var, raising=False)+ url_setting = "search.engine.web.myengine.default_params.api_url"+ monkeypatch.delenv(+ "LDR_SEARCH_ENGINE_WEB_MYENGINE_DEFAULT_PARAMS_API_URL",+ raising=False,+ )+ w = check_private_engine_url_blocked(+ "MyEngine",+ "myengine",+ url_setting,+ "http://localhost:1234",+ True,+ False,+ )+ assert w is not None+ assert w["type"] == "myengine_private_url_blocked"+ assert w["dismissKey"] == "app.warnings.dismiss_myengine_private_url"+ assert (+ "LDR_SEARCH_ENGINE_WEB_MYENGINE_DEFAULT_PARAMS_API_URL"+ in w["message"]+ )+ assert "MyEngine" in w["title"]+ assert w["actionUrl"] == (+ "/settings#setting-search-engine-web-myengine-"+ "default_params-api_url"+ )++ def test_env_locked_engine_specific_key_silences(self, monkeypatch):+ """The env-lock approval is keyed to the ENGINE'S OWN url_setting,+ not SearXNG's."""+ for var in APPROVAL_ENVS:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv(+ "LDR_SEARCH_ENGINE_WEB_MYENGINE_DEFAULT_PARAMS_API_URL",+ "http://localhost:1234",+ )+ assert (+ check_private_engine_url_blocked(+ "MyEngine",+ "myengine",+ "search.engine.web.myengine.default_params.api_url",+ "http://localhost:1234",+ True,+ False,+ )+ is None+ )++ def test_inactive_engine_is_silent(self, monkeypatch):+ for var in APPROVAL_ENVS:+ monkeypatch.delenv(var, raising=False)+ assert (+ check_private_engine_url_blocked(+ "MyEngine",+ "myengine",+ "search.engine.web.myengine.default_params.api_url",+ "http://localhost:1234",+ False,+ False,+ )+ is None+ )diff --git a/tests/security/test_local_engine_public_url_warning.py b/tests/security/test_local_engine_public_url_warning.pynew file mode 100644index 0000000000..ca2a90bc8a--- /dev/null+++ b/tests/security/test_local_engine_public_url_warning.py@@ -0,0 +1,163 @@+"""Tests for the local-engine public-URL warning banner check.++``check_local_engine_public_url`` is the mirror image of the SearXNG+private-URL banner: for a LOCAL document engine (Paperless, Elasticsearch)+a PUBLIC-looking host is the anomaly — document queries would leave the+machine, and a private-only egress scope silently excludes the engine.+"""++from local_deep_research.security.egress.warnings import (+ _extract_engine_hosts,+ check_local_engine_public_url,+)+++class TestExtractEngineHosts:+ def test_single_url_string(self):+ assert _extract_engine_hosts("http://localhost:8000") == ["localhost"]++ def test_list_of_urls(self):+ assert _extract_engine_hosts(+ ["http://localhost:9200", "https://es.example.com:9200"]+ ) == ["localhost", "es.example.com"]++ def test_json_string_list(self):+ assert _extract_engine_hosts('["http://localhost:9200"]') == [+ "localhost"+ ]++ def test_comma_string(self):+ assert _extract_engine_hosts(+ "http://a.example.com:9200, http://b.example.com:9200"+ ) == ["a.example.com", "b.example.com"]++ def test_bare_host_port_form(self):+ """Elasticsearch accepts bare host:port entries."""+ assert _extract_engine_hosts(["es.example.com:9200"]) == [+ "es.example.com"+ ]++ def test_garbage_is_skipped(self):+ assert _extract_engine_hosts([42, "", None, " "]) == []+ assert _extract_engine_hosts(None) == []+ assert _extract_engine_hosts("") == []+++class TestFires:+ def test_fires_for_public_paperless_url(self):+ w = check_local_engine_public_url(+ "Paperless-ngx",+ "paperless",+ "https://paperless.example.com",+ True,+ False,+ )+ assert w is not None+ assert w["type"] == "paperless_public_url"+ assert w["dismissKey"] == "app.warnings.dismiss_paperless_public_url"+ assert "paperless.example.com" in w["message"]+ assert w["actionUrl"].startswith("/")+ assert not w["actionUrl"].startswith("//")++ def test_fires_for_one_public_host_among_private(self):+ w = check_local_engine_public_url(+ "Elasticsearch",+ "elasticsearch",+ ["http://localhost:9200", "https://es.example.com:9200"],+ True,+ False,+ )+ assert w is not None+ assert w["type"] == "elasticsearch_public_url"+ assert "es.example.com" in w["message"]+ # Only the flagged (non-private) hosts are named, never the private ones.+ assert "localhost" not in w["message"]++ def test_fires_for_public_ipv6_literal(self):+ """IPv6 literals contain no dot — they must not slip through the+ dotless service-name shortcut (regression pinned by review)."""+ w = check_local_engine_public_url(+ "Elasticsearch",+ "elasticsearch",+ ["http://[2600::1]:9200"],+ True,+ False,+ )+ assert w is not None+ assert "2600::1" in w["message"]++ def test_fires_for_cloud_id_even_with_private_hosts(self):+ w = check_local_engine_public_url(+ "Elasticsearch",+ "elasticsearch",+ ["http://localhost:9200"],+ True,+ False,+ extra="Elastic Cloud (cloud_id)",+ )+ assert w is not None+ assert "Elastic Cloud" in w["message"]+++class TestStaysSilent:+ def test_silent_for_private_urls(self):+ for urls in (+ "http://localhost:8000",+ ["http://localhost:9200"],+ ["http://127.0.0.1:9200", "http://10.0.0.5:9200"],+ "http://paperless.local:8000",+ # Dotless single labels: Docker/compose service names can never+ # be public DNS — the standard compose setup must not warn.+ "http://paperless:8000",+ ["http://elasticsearch:9200"],+ # CGNAT (Tailscale / rootless Podman): the egress gate treats+ # 100.64.0.0/10 as private, so the banner must agree.+ "http://100.64.0.5:8000",+ # Private IPv6 ULA — also dotless, must classify as an IP+ # literal, not fall into the service-name shortcut.+ "http://[fd00::1]:9200",+ ):+ assert (+ check_local_engine_public_url(+ "Paperless-ngx", "paperless", urls, True, False+ )+ is None+ ), f"expected silence for {urls}"++ def test_silent_when_inactive(self):+ assert (+ check_local_engine_public_url(+ "Paperless-ngx",+ "paperless",+ "https://paperless.example.com",+ False,+ False,+ )+ is None+ )++ def test_silent_when_acknowledged(self):+ assert (+ check_local_engine_public_url(+ "Paperless-ngx",+ "paperless",+ "https://paperless.example.com",+ True,+ True,+ )+ is None+ )++ def test_silent_for_empty_config(self):+ assert (+ check_local_engine_public_url(+ "Elasticsearch", "elasticsearch", [], True, False+ )+ is None+ )+ assert (+ check_local_engine_public_url(+ "Paperless-ngx", "paperless", "", True, False+ )+ is None+ )diff --git a/tests/security/test_searxng_private_url_warning.py b/tests/security/test_searxng_private_url_warning.pynew file mode 100644index 0000000000..b049bfe0a8--- /dev/null+++ b/tests/security/test_searxng_private_url_warning.py@@ -0,0 +1,246 @@+"""Tests for the SearXNG private-URL warning banner check.++``check_searxng_private_url_blocked`` surfaces, on the research form, the+otherwise-quiet failure where SearXNG is the selected engine but its+private/localhost instance URL has no operator approval, so the engine+self-disables at run time.+"""++from local_deep_research.security.egress.warnings import (+ check_searxng_private_url_blocked,+)++GATE_ENV = "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS"+ALLOWLIST_ENV = "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST"+INSTANCE_URL_ENV = "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL"++APPROVAL_ENVS = (GATE_ENV, ALLOWLIST_ENV, INSTANCE_URL_ENV)+++def _clear_approvals(monkeypatch):+ for var in APPROVAL_ENVS:+ monkeypatch.delenv(var, raising=False)+++class TestFires:+ def test_fires_for_unapproved_localhost_url(self, monkeypatch):+ """The dominant broken case: searxng selected, default localhost URL,+ no operator approval — the banner fires and names all three remedies."""+ _clear_approvals(monkeypatch)+ w = check_searxng_private_url_blocked(+ "searxng", "http://localhost:8080", False+ )+ assert w is not None+ assert w["type"] == "searxng_private_url_blocked"+ assert "http://localhost:8080" in w["message"]+ assert ALLOWLIST_ENV in w["message"]+ assert GATE_ENV in w["message"]+ assert INSTANCE_URL_ENV in w["message"]+ assert w["dismissKey"] == "app.warnings.dismiss_searxng_private_url"++ def test_fires_for_lan_ip(self, monkeypatch):+ _clear_approvals(monkeypatch)+ w = check_searxng_private_url_blocked(+ "searxng", "http://10.0.0.5:8888", False+ )+ assert w is not None++ def test_message_shows_origin_never_userinfo_or_path(self, monkeypatch):+ """The copy-paste remedy is the ORIGIN — credentials, path, and query+ from the raw URL must never appear in the banner."""+ _clear_approvals(monkeypatch)+ w = check_searxng_private_url_blocked(+ "searxng", "http://user:[email protected]:8888/searx?x=1", False+ )+ assert w is not None+ assert "http://192.168.1.5:8888" in w["message"]+ assert "secretpw" not in w["message"]+ assert "user:" not in w["message"]+ assert "/searx" not in w["message"]+++class TestStaysSilent:+ def test_silent_when_acknowledged(self, monkeypatch):+ _clear_approvals(monkeypatch)+ assert (+ check_searxng_private_url_blocked(+ "searxng", "http://localhost:8080", True+ )+ is None+ )++ def test_silent_for_other_primary_engine(self, monkeypatch):+ _clear_approvals(monkeypatch)+ assert (+ check_searxng_private_url_blocked(+ "wikipedia", "http://localhost:8080", False+ )+ is None+ )++ def test_silent_for_public_url(self, monkeypatch):+ """A public hostname is fine — and must not trigger DNS lookups+ (is_private_ip is a literal/known-name check)."""+ _clear_approvals(monkeypatch)+ assert (+ check_searxng_private_url_blocked(+ "searxng", "https://searx.example.com", False+ )+ is None+ )++ def test_silent_for_empty_url(self, monkeypatch):+ _clear_approvals(monkeypatch)+ assert check_searxng_private_url_blocked("searxng", "", False) is None+ assert check_searxng_private_url_blocked("searxng", None, False) is None++ def test_silent_when_blanket_gate_set(self, monkeypatch):+ _clear_approvals(monkeypatch)+ monkeypatch.setenv(GATE_ENV, "true")+ assert (+ check_searxng_private_url_blocked(+ "searxng", "http://localhost:8080", False+ )+ is None+ )++ def test_silent_when_origin_allowlisted(self, monkeypatch):+ _clear_approvals(monkeypatch)+ monkeypatch.setenv(ALLOWLIST_ENV, "http://localhost:8080")+ assert (+ check_searxng_private_url_blocked(+ "searxng", "http://localhost:8080", False+ )+ is None+ )++ def test_fires_when_allowlist_does_not_match(self, monkeypatch):+ """An allowlist for a DIFFERENT origin does not silence the banner."""+ _clear_approvals(monkeypatch)+ monkeypatch.setenv(ALLOWLIST_ENV, "http://localhost:9090")+ assert (+ check_searxng_private_url_blocked(+ "searxng", "http://localhost:8080", False+ )+ is not None+ )++ def test_silent_when_url_env_locked(self, monkeypatch):+ _clear_approvals(monkeypatch)+ monkeypatch.setenv(INSTANCE_URL_ENV, "http://localhost:8080")+ assert (+ check_searxng_private_url_blocked(+ "searxng", "http://localhost:8080", False+ )+ is None+ )++ def test_silent_for_metadata_ip(self, monkeypatch):+ """A cloud-metadata address is blocked unconditionally — the env+ remedies this banner prescribes would not help, so it stays silent."""+ _clear_approvals(monkeypatch)+ assert (+ check_searxng_private_url_blocked(+ "searxng", "http://169.254.169.254", False+ )+ is None+ )++ def test_silent_for_malformed_url(self, monkeypatch):+ """A URL the allowlist parser refuses (unbracketed IPv6 with port,+ unparseable port) yields no banner — better silence than an+ unusable prescribed remedy. The runtime ERROR still covers it."""+ _clear_approvals(monkeypatch)+ for url in ("http://fd00::5:8080", "http://localhost:8080."):+ assert (+ check_searxng_private_url_blocked("searxng", url, False) is None+ ), f"expected no banner for malformed {url}"+++class TestBannerRemedyRoundTrip:+ """The origin the banner prescribes must, fed back into the allowlist,+ silence the banner AND open the runtime gate — the three-layer contract+ in one test."""++ def _prescribed_origin(self, message):+ marker = "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST="+ start = message.index(marker) + len(marker)+ end = message.index(" ", start)+ return message[start:end]++ def _assert_round_trip(self, monkeypatch, url, expected_origin):+ from local_deep_research.security.egress.validators import (+ resolve_searxng_allow_private_ips,+ )++ _clear_approvals(monkeypatch)+ w = check_searxng_private_url_blocked("searxng", url, False)+ assert w is not None, f"expected banner for {url}"+ origin = self._prescribed_origin(w["message"])+ assert origin == expected_origin+ monkeypatch.setenv(ALLOWLIST_ENV, origin)+ assert resolve_searxng_allow_private_ips(url) is True, (+ f"prescribed origin {origin} did not open the gate for {url}"+ )+ assert (+ check_searxng_private_url_blocked("searxng", url, False) is None+ ), f"prescribed origin {origin} did not silence the banner for {url}"++ def test_round_trip_localhost(self, monkeypatch):+ self._assert_round_trip(+ monkeypatch, "http://localhost:8080", "http://localhost:8080"+ )++ def test_round_trip_ipv6_literal(self, monkeypatch):+ """Would have caught the bracket-stripping bug: the prescribed+ origin must be re-bracketed to stay parseable."""+ self._assert_round_trip(+ monkeypatch, "http://[fd00::5]:8080", "http://[fd00::5]:8080"+ )++ def test_round_trip_default_port(self, monkeypatch):+ self._assert_round_trip(+ monkeypatch, "http://localhost", "http://localhost"+ )++ def test_round_trip_with_userinfo_and_path(self, monkeypatch):+ self._assert_round_trip(+ monkeypatch,+ "http://user:[email protected]:8888/searx",+ "http://192.168.1.5:8888",+ )+++class TestGateMirroring:+ def test_fires_for_cgnat_literal(self, monkeypatch):+ """CGNAT (100.64.0.0/10 — Podman/rootless containers) is blocked by+ the gate as private, so the banner must fire for it too."""+ _clear_approvals(monkeypatch)+ assert (+ check_searxng_private_url_blocked(+ "searxng", "http://100.64.0.1:8080", False+ )+ is not None+ )++ def test_fires_for_non_metadata_link_local(self, monkeypatch):+ """Link-local that is NOT in the always-blocked metadata set is+ liftable by the env remedies, so the banner fires."""+ _clear_approvals(monkeypatch)+ assert (+ check_searxng_private_url_blocked(+ "searxng", "http://169.254.42.42:8080", False+ )+ is not None+ )++ def test_action_url_is_renderable(self, monkeypatch):+ """research_form.js only renders action links that start with '/'+ and not '//' — pin the shape so the link never silently vanishes."""+ _clear_approvals(monkeypatch)+ w = check_searxng_private_url_blocked(+ "searxng", "http://localhost:8080", False+ )+ assert w is not None+ assert w["actionUrl"].startswith("/")+ assert not w["actionUrl"].startswith("//")diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 038f121f8a..7a20dde509 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -468,6 +468,20 @@"value": false,"visible": true},+ "app.warnings.dismiss_elasticsearch_public_url": {+ "category": "internal",+ "description": "Permanently hide the 'Elasticsearch points at a non-private host' banner that appears when the Elasticsearch engine is active but its hosts (or cloud_id) do not look like private/local addresses (document queries would leave the machine; a private-only egress scope excludes the engine). Dismiss when a hosted endpoint such as Elastic Cloud is intentional.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Dismiss Elasticsearch public-URL warning",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },"app.warnings.dismiss_high_context": {"category": "warnings","description": "Permanently hide the warning shown when your local LLM context window is set above 8,192 tokens, which may cause memory issues on some hardware.",@@ -510,6 +524,34 @@"value": false,"visible": true},+ "app.warnings.dismiss_paperless_public_url": {+ "category": "internal",+ "description": "Permanently hide the 'Paperless-ngx points at a non-private host' banner that appears when the Paperless engine is active but its API URL does not look like a private/local address (document queries would leave the machine; a private-only egress scope excludes the engine).",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Dismiss Paperless public-URL warning",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "app.warnings.dismiss_searxng_private_url": {+ "category": "internal",+ "description": "Permanently hide the 'SearXNG is disabled: private URL not approved' banner that appears when SearXNG is active (selected as the search engine, or enabled for auto/agent search) but its private/localhost instance URL has no operator approval (allowlist, blanket opt-in, or env-lock) in the server environment.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Dismiss SearXNG private-URL warning",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },"app.warnings.dismiss_searxng_recommendation": {"category": "warnings","description": "Dismiss recommendations about using more questions instead of iterations with SearXNG",@@ -6004,7 +6046,7 @@},"search.engine.web.searxng.default_params.instance_url": {"category": "searxng",- "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.",+ "description": "The SearXNG API endpoint URL. A private / loopback / link-local URL (including the default http://localhost:8080) is only fetched when the operator lists its origin in LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST, 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/warning_checks/test_orchestrator.py b/tests/web/warning_checks/test_orchestrator.pyindex 1d9765a490..35b05ffd18 100644--- a/tests/web/warning_checks/test_orchestrator.py+++ b/tests/web/warning_checks/test_orchestrator.py@@ -651,3 +651,195 @@ class TestCalculateWarningsUnprotectedBannerUsesEffectiveScope:warnings = calculate_warnings()assert "egress_unprotected" in {w["type"] for w in warnings}+++class TestSearxngPrivateUrlWarning:+ """Orchestrator wiring for the SearXNG private-URL banner."""++ APPROVAL_ENVS = (+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS",+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST",+ "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL",+ )++ def _run(self, overrides, monkeypatch):+ for var in self.APPROVAL_ENVS:+ monkeypatch.delenv(var, raising=False)+ from local_deep_research.web.warning_checks import calculate_warnings++ mgr = _make_settings_manager(overrides)+ with _patch_orchestrator(mgr):+ return calculate_warnings()++ def test_banner_emitted_for_unapproved_searxng(self, monkeypatch):+ warnings = self._run(+ {+ "search.tool": "searxng",+ "search.engine.web.searxng.default_params.instance_url": (+ "http://localhost:8080"+ ),+ },+ monkeypatch,+ )+ assert "searxng_private_url_blocked" in {w["type"] for w in warnings}++ def test_banner_respects_dismiss_flag(self, monkeypatch):+ warnings = self._run(+ {+ "search.tool": "searxng",+ "search.engine.web.searxng.default_params.instance_url": (+ "http://localhost:8080"+ ),+ "app.warnings.dismiss_searxng_private_url": True,+ },+ monkeypatch,+ )+ assert "searxng_private_url_blocked" not in {+ w["type"] for w in warnings+ }++ def test_banner_fires_when_enabled_for_auto_search_not_primary(+ self, monkeypatch+ ):+ """Real default settings ship use_in_auto_search=True for SearXNG, so+ the engine is used by the langgraph strategy even when another+ engine is primary — the banner must still fire (it would silently+ self-disable in those runs too)."""+ warnings = self._run(+ {+ "search.tool": "wikipedia",+ "search.engine.web.searxng.use_in_auto_search": True,+ "search.engine.web.searxng.default_params.instance_url": (+ "http://localhost:8080"+ ),+ },+ monkeypatch,+ )+ assert "searxng_private_url_blocked" in {w["type"] for w in warnings}++ def test_no_banner_when_not_primary_and_all_flags_off(self, monkeypatch):+ """Only when SearXNG is neither primary nor enabled by any+ activation flag is the banner silent."""+ warnings = self._run(+ {+ "search.tool": "wikipedia",+ "search.engine.web.searxng.use_in_auto_search": False,+ "search.engine.web.searxng.agent_enabled": False,+ "search.engine.web.searxng.default_params.instance_url": (+ "http://localhost:8080"+ ),+ },+ monkeypatch,+ )+ assert "searxng_private_url_blocked" not in {+ w["type"] for w in warnings+ }++ def test_elasticsearch_cloud_id_reaches_banner(self, monkeypatch):+ """The ES cloud_id branch: a set cloud_id fires the public-URL+ banner even when every listed host is private."""+ for var in self.APPROVAL_ENVS:+ monkeypatch.delenv(var, raising=False)+ from local_deep_research.web.warning_checks import calculate_warnings++ mgr = _make_settings_manager(+ {+ "search.engine.web.elasticsearch.use_in_auto_search": True,+ "search.engine.web.elasticsearch.default_params.hosts": [+ "http://localhost:9200"+ ],+ "search.engine.web.elasticsearch.default_params.cloud_id": (+ "my-deployment:abc123"+ ),+ }+ )+ with _patch_orchestrator(mgr):+ warnings = calculate_warnings()+ es = [w for w in warnings if w["type"] == "elasticsearch_public_url"]+ assert es and "Elastic Cloud" in es[0]["message"]++ def test_no_banner_when_operator_approved(self, monkeypatch):+ for var in self.APPROVAL_ENVS:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv(+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST", "http://localhost:8080"+ )+ from local_deep_research.web.warning_checks import calculate_warnings++ mgr = _make_settings_manager(+ {+ "search.tool": "searxng",+ "search.engine.web.searxng.default_params.instance_url": (+ "http://localhost:8080"+ ),+ }+ )+ with _patch_orchestrator(mgr):+ warnings = calculate_warnings()+ assert "searxng_private_url_blocked" not in {+ w["type"] for w in warnings+ }+++class TestLocalEnginePublicUrlWarnings:+ """Orchestrator wiring for the Paperless / Elasticsearch banners."""++ def test_paperless_banner_when_enabled_with_public_url(self):+ from local_deep_research.web.warning_checks import calculate_warnings++ mgr = _make_settings_manager(+ {+ "search.engine.web.paperless.enabled": True,+ "search.engine.web.paperless.default_params.api_url": (+ "https://paperless.example.com"+ ),+ }+ )+ with _patch_orchestrator(mgr):+ warnings = calculate_warnings()+ assert "paperless_public_url" in {w["type"] for w in warnings}++ def test_paperless_silent_when_disabled(self):+ from local_deep_research.web.warning_checks import calculate_warnings++ mgr = _make_settings_manager(+ {+ "search.engine.web.paperless.enabled": False,+ "search.engine.web.paperless.default_params.api_url": (+ "https://paperless.example.com"+ ),+ }+ )+ with _patch_orchestrator(mgr):+ warnings = calculate_warnings()+ assert "paperless_public_url" not in {w["type"] for w in warnings}++ def test_elasticsearch_banner_for_public_host(self):+ from local_deep_research.web.warning_checks import calculate_warnings++ mgr = _make_settings_manager(+ {+ "search.engine.web.elasticsearch.use_in_auto_search": True,+ "search.engine.web.elasticsearch.default_params.hosts": [+ "https://es.example.com:9200"+ ],+ }+ )+ with _patch_orchestrator(mgr):+ warnings = calculate_warnings()+ assert "elasticsearch_public_url" in {w["type"] for w in warnings}++ def test_elasticsearch_silent_for_default_localhost(self):+ from local_deep_research.web.warning_checks import calculate_warnings++ mgr = _make_settings_manager(+ {+ "search.engine.web.elasticsearch.use_in_auto_search": True,+ "search.engine.web.elasticsearch.default_params.hosts": [+ "http://localhost:9200"+ ],+ }+ )+ with _patch_orchestrator(mgr):+ warnings = calculate_warnings()+ assert "elasticsearch_public_url" not in {w["type"] for w in warnings}diff --git a/tests/web_search_engines/engines/test_search_engine_searxng.py b/tests/web_search_engines/engines/test_search_engine_searxng.pyindex efe9b418e4..c0580178f9 100644--- a/tests/web_search_engines/engines/test_search_engine_searxng.py+++ b/tests/web_search_engines/engines/test_search_engine_searxng.py@@ -1808,6 +1808,7 @@ SEARXNG_MODULE = ()INSTANCE_URL_ENV = "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL"GATE_ENV = "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS"+ALLOWLIST_ENV = "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST"class TestAllowPrivateIpsDerivation:@@ -1826,7 +1827,9 @@ class TestAllowPrivateIpsDerivation:_resolve_searxng_allow_private_ips,)- assert _resolve_searxng_allow_private_ips() is False+ assert (+ _resolve_searxng_allow_private_ips("http://localhost:8080") is False+ )def test_empty_snapshot_refuses_private(self):"""No operator opt-in / env-lock present -> refuses private (False)."""@@ -1834,7 +1837,9 @@ class TestAllowPrivateIpsDerivation:_resolve_searxng_allow_private_ips,)- assert _resolve_searxng_allow_private_ips() is False+ assert (+ _resolve_searxng_allow_private_ips("http://localhost:8080") is False+ )def test_user_scope_never_grants_private(self):"""A user-editable egress scope must NOT grant private egress for a@@ -1847,7 +1852,9 @@ class TestAllowPrivateIpsDerivation:_resolve_searxng_allow_private_ips,)- assert _resolve_searxng_allow_private_ips() is False+ assert (+ _resolve_searxng_allow_private_ips("http://localhost:8080") is False+ )def test_operator_gate_allows_private(self, monkeypatch):"""The env opt-in permits private egress even under PUBLIC_ONLY."""@@ -1856,7 +1863,9 @@ class TestAllowPrivateIpsDerivation:_resolve_searxng_allow_private_ips,)- assert _resolve_searxng_allow_private_ips() is True+ assert (+ _resolve_searxng_allow_private_ips("http://localhost:8080") is True+ )def test_env_locked_instance_url_allows_private(self, monkeypatch):"""An operator-provisioned (env-locked) instance URL is trusted, so@@ -1866,7 +1875,101 @@ class TestAllowPrivateIpsDerivation:_resolve_searxng_allow_private_ips,)- assert _resolve_searxng_allow_private_ips() is True+ assert (+ _resolve_searxng_allow_private_ips("http://localhost:8080") is True+ )++ def test_allowlisted_origin_allows_private(self, monkeypatch):+ """An instance URL whose exact origin is in the operator allowlist is+ permitted private egress without the blanket opt-in."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://localhost:8080")+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ _resolve_searxng_allow_private_ips,+ )++ assert (+ _resolve_searxng_allow_private_ips("http://localhost:8080") is True+ )++ def test_non_allowlisted_origin_refuses_private(self, monkeypatch):+ """The allowlist is exact-origin: a different port does not match."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://localhost:8080")+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ _resolve_searxng_allow_private_ips,+ )++ assert (+ _resolve_searxng_allow_private_ips("http://localhost:9090") is False+ )+ assert (+ _resolve_searxng_allow_private_ips("http://192.168.1.5:8080")+ is False+ )++ def test_schemeless_allowlist_entry_grants_nothing(self, monkeypatch):+ """The most likely operator mistake — omitting the scheme — must not+ grant private egress at runtime either."""+ monkeypatch.setenv(ALLOWLIST_ENV, "localhost:8080")+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ _resolve_searxng_allow_private_ips,+ )++ assert (+ _resolve_searxng_allow_private_ips("http://localhost:8080") is False+ )++ def test_listed_metadata_origin_still_never_fetched(self, monkeypatch):+ """Listing a cloud-metadata origin flips the runtime GATE to True,+ but the downstream SSRF validation still refuses the fetch — the+ engine ends up unavailable regardless. Pins the invariant that the+ allowlist can never license a metadata destination end to end."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://169.254.169.254:80")+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ _resolve_searxng_allow_private_ips,+ )++ assert (+ _resolve_searxng_allow_private_ips("http://169.254.169.254") is True+ )+ # No safe_get mock: validate_url blocks the metadata IP before any+ # network I/O, so this is hermetic.+ engine = SearXNGSearchEngine(instance_url="http://169.254.169.254")+ assert engine._is_available is False+ # The remediation hint must NOT fire — the env flags would not help.+ assert engine._private_url_blocked_by_gate() is False++ def test_hint_silent_on_allowlisted_transport_failure(self, monkeypatch):+ """An allowlisted instance that is merely DOWN (transport error) must+ not surface the private-URL remediation hint — the gate is open; the+ problem is the instance, not the policy."""+ monkeypatch.setenv(ALLOWLIST_ENV, "http://127.0.0.1:8080")+ 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://127.0.0.1:8080")++ assert engine._is_available is False+ assert engine._allow_private_ips is True+ assert engine._private_url_blocked_by_gate() is False+ hints = [+ c.args[0]+ for c in (+ mock_logger.error.call_args_list+ + mock_logger.warning.call_args_list+ )+ if c.args+ ]+ assert not any(GATE_ENV in msg for msg in hints)class TestEngineForwardsDerivedAllowPrivateIps:@@ -1972,9 +2075,9 @@ class TestPrivateUrlBlockedHint:assert engine._allow_private_ips is Trueassert 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."""+ def test_blocked_probe_logs_remediation_error(self):+ """When the availability probe is refused for a gated private URL, an+ ERROR 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,)@@ -1990,14 +2093,16 @@ class TestPrivateUrlBlockedHint: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}"+ errors = [c.args[0] for c in mock_logger.error.call_args_list if c.args]+ assert any(GATE_ENV in msg for msg in errors), (+ f"expected an error naming {GATE_ENV}, got: {errors}")+ # All three remedies must be named — a future reword must not+ # silently drop the allowlist or env-lock options.+ assert any(ALLOWLIST_ENV in msg for msg in errors)+ assert any(INSTANCE_URL_ENV in msg for msg in errors)- def test_public_probe_failure_has_no_remediation_warning(self):+ def test_public_probe_failure_has_no_remediation_error(self):"""A transport failure against a public URL must NOT emit the private-URLremediation hint (precise detection, no spam)."""import requests@@ -2015,9 +2120,14 @@ class TestPrivateUrlBlockedHint: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+ hints = [+ c.args[0]+ for c in (+ mock_logger.error.call_args_list+ + 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}"+ assert not any(GATE_ENV in msg for msg in hints), (+ f"unexpected private-URL hint on a public failure: {hints}")