~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
fix(security): enforce run scope across full-content downloads (#7072)
LearningCircuit037bd6772918
diff --git a/changelog.d/+egress-transport-containment.breaking.md b/changelog.d/+egress-transport-containment.breaking.mdnew file mode 100644index 0000000000..364c3ec535--- /dev/null+++ b/changelog.d/+egress-transport-containment.breaking.md@@ -0,0 +1 @@+Enforce research-run egress scope on every SafeSession redirect and pinned connection target. Full-content extraction now carries that policy through specialized and generic downloaders and stops on a policy denial. JavaScript browser fallback is disabled for Public only, Private only, and Strict runs; static content remains available.diff --git a/changelog.d/6196.security.md b/changelog.d/6196.security.mdindex 247b0047df..c709a8abd2 100644--- a/changelog.d/6196.security.md+++ b/changelog.d/6196.security.md@@ -1 +1 @@-SearXNG full-content fetching (`search.snippets_only` off) can now follow private / loopback result URLs, for example an internal wiki that a self-hosted instance indexes, but only when the instance is already approved for private egress AND the operator sets the new env-only `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH=true`. The flag defaults to off and the bundled `docker-compose.yml` does not set it, so ungated / public instances and existing deployments keep blocking private result URLs. Link-local addresses (`169.254.0.0/16`, `fe80::/10`) and the cloud-metadata literals in `ALWAYS_BLOCKED_METADATA_IPS` stay blocked even with the opt-in. The engine resolves the grant and the search-engine factory hands it to the `FullSearchResults` wrapper it builds (since #6492 the only full-content path), where it applies to the SSRF validation of result URLs; the other engines hold no grant and are unchanged. Whenever a run egress policy restricts hosts by address class (`public_only`, `private_only`, `strict`) the download pipeline, which enforces address classes on redirect hops and browser subresources but does not see the run policy, keeps its strict default regardless of the flag; the grant reaches the pipeline only without a run policy or under the `unprotected` scope. The factory does not yet give the wrapper a run egress context (#6131), so on that path the per-URL scope gate does not run and the pipeline receives the grant; once #6131 threads the context, the default adaptive scope denies private result hosts for SearXNG and the ADR-0007 policy question decides what the flag permits there.+SearXNG full-content fetching (`search.snippets_only` off) can now follow private / loopback result URLs, for example an internal wiki that a self-hosted instance indexes, but only under the `unprotected` egress scope and only when the instance is already approved for private egress AND the operator sets the new env-only `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH=true`. The flag defaults to off and the bundled `docker-compose.yml` does not set it, so ungated / public instances and existing deployments keep blocking private result URLs. Link-local addresses (`169.254.0.0/16`, `fe80::/10`) and the cloud-metadata literals in `ALWAYS_BLOCKED_METADATA_IPS` stay blocked even with the opt-in. The engine resolves the grant and the search-engine factory hands it to the `FullSearchResults` wrapper it builds (since #6492 the only full-content path), where it applies to the SSRF validation of result URLs; the other engines hold no grant and are unchanged. The grant takes effect only under the `unprotected` egress scope: the factory hands the wrapper the run's egress context (#6535), and under every other scope, the default `adaptive` scope included, the wrapper withholds the grant from both the SSRF validation of result URLs and the download pipeline (which enforces the run scope on static redirect hops and pinned connect addresses and disables browser fallback under Public only, Private only, and Strict), so private result URLs stay blocked as if the flag were unset.diff --git a/changelog.d/6535.security.md b/changelog.d/6535.security.mdnew file mode 100644index 0000000000..f61087729a--- /dev/null+++ b/changelog.d/6535.security.md@@ -0,0 +1,32 @@+Full-content search wrappers now reuse the run's validated egress context when+fetching result URLs, so the per-URL egress scope check runs on that path. If+that context is unavailable, the factory returns the snippets-only engine+instead of fetching full content without the run's scope.+`LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` (#6196) therefore takes effect only+under the `unprotected` scope; under every other scope, the default `adaptive`+included, private result URLs are refused before the counted scope check+(by the SSRF check, or, for addresses the SSRF check admits but the egress+policy classifies private such as `198.18.0.0/15` from fake-IP DNS, the+documentation ranges and `240.0.0.0/4`, by the policy's own non-counting+classifier), so they do not count toward the run's denied-fetch quota+(`MAX_DENIED_FETCHES_PER_RUN`) and cannot exhaust it and block public+fetches. The classifier check also runs under `strict`, `private_only` and+`both`, whose scope check admits private hosts, so full-content search no+longer fetches such result URLs there; it covers the result URL itself, while+static redirects and pinned connect addresses also receive the run-scope check.+Browser fallback is disabled under Public only, Private only, and Strict;+when available under Both or Unprotected, its requests retain SSRF checks.+Under `unprotected` without the flag only the SSRF check applies, so those+ranges are fetched there.+Known limitation: with fake-IP DNS (Clash, sing-box, Surge in TUN mode),+public names resolve into `198.18.0.0/15`, which the egress policy classifies+as private. Full-content fetching is then unavailable under every scope except+`unprotected`, and under `strict` / `private_only` the other fetch paths and+the socket guard admit those public hosts as private; see "Known limitations"+in `docs/egress-modes.md` and #7093.+Upgrade note: released v1.x versions never fetched private result URLs, so+nothing changes for them. Operators who ran a development build with the flag+and relied on it for intranet full content must run those researches under+`unprotected` (operator gate `LDR_POLICY_ALLOW_UNPROTECTED_EGRESS`); otherwise+those results arrive without full content, and LDR logs an INFO line naming+the scope that kept the flag from applying.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 572ad5927b..20b154df2e 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -46,7 +46,7 @@ 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_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. The shared_library flag is otherwise user-editable; leaving shared mode user-toggleable would let an account drop its per-user directory boundary. The storage_path is now operator-only, but legacy saved paths remain in place. 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. 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_ALLOW_PRIVATE_RESULT_FETCH` | Boolean | `False` | No | | Allow full-content fetching (search.snippets_only off) to follow the RESULT URLs a PUBLIC search engine returns into private / loopback addresses, e.g. an internal wiki that a self-hosted SearXNG instance indexes. Distinct from, and required in addition to, the instance-URL approval (LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS, LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST or an env-locked instance URL): that approval only covers reaching the engine itself, and because a public engine proxies the public web, extending it to the URLs the engine returns would let a poisoned index turn result fetching into a scan of the LDR host's private network. Environment-only operator gate so it cannot be flipped through the user-writable settings API. Disabled by default and not set by the bundled docker-compose.yml. Link-local addresses (169.254.0.0/16, fe80::/10) and the cloud-metadata endpoints in ALWAYS_BLOCKED_METADATA_IPS stay blocked regardless of this flag. | Security | |+| `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` | Boolean | `False` | No | | Allow full-content fetching (search.snippets_only off) to follow the RESULT URLs a PUBLIC search engine returns into private / loopback addresses, e.g. an internal wiki that a self-hosted SearXNG instance indexes. Distinct from, and required in addition to, the instance-URL approval (LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS, LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST or an env-locked instance URL): that approval only covers reaching the engine itself, and because a public engine proxies the public web, extending it to the URLs the engine returns would let a poisoned index turn result fetching into a scan of the LDR host's private network. Environment-only operator gate so it cannot be flipped through the user-writable settings API. Disabled by default and not set by the bundled docker-compose.yml. Link-local addresses (169.254.0.0/16, fe80::/10) and the cloud-metadata endpoints in ALWAYS_BLOCKED_METADATA_IPS stay blocked regardless of this flag. Takes effect only under the unprotected egress scope: under every other scope, the default adaptive scope included, private result URLs stay blocked even with this flag set. | 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), the discard prefix (100::/64), the deprecated IPv4-Compatible IPv6 form (::/96, except ::1 loopback which follows the loopback/private flags), and the IPv4-Translated/SIIT form (::ffff:0:0:0/96) 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 | |@@ -679,7 +679,7 @@ They are not available in the Web UI because they are needed to start the applic| `security.rate_limit_upload_user` | `LDR_SECURITY_RATE_LIMIT_UPLOAD_USER` | `60 per minute;1000 per hour` | Per-authenticated-user rate limit for file upload endpoints (e.g., RAG collection uploads). Configured via LDR_SECURITY_RATE_LIMIT_UPLOAD_USER environment variable. Multiple limits separated by semicolons (e.g., '60 per minute;1000 per hour'). Requires server restart. | APP || `security.session_remember_me_days` | `LDR_SECURITY_SESSION_REMEMBER_ME_DAYS` | `30` | Number of days a 'Remember Me' session remains valid before requiring re-login. | APP || `security.session_timeout_hours` | `LDR_SECURITY_SESSION_TIMEOUT_HOURS` | `2` | Session timeout in hours for sessions without 'Remember Me' checked. Only applies to internal session validation (browser sessions expire on close). | APP |-| `web.enable_javascript_rendering` | `LDR_WEB_ENABLE_JAVASCRIPT_RENDERING` | `false` | When enabled, falls back to a headless browser (Crawl4AI/Playwright) for pages that need JavaScript to render. Requires Chromium to be installed - the default Docker production image does NOT include it. To enable: install Chromium in the runtime environment (e.g. 'playwright install --with-deps chromium'), then toggle this setting. Note: in our limited (mostly accidental) benchmark comparisons - between dev instances that happened to have Chromium installed and routine Docker runs that did not - JS rendering did not measurably improve research quality, and most of our regular benchmark runs are on Docker without Chromium anyway. Leave disabled unless you have a specific need to scrape JavaScript-only sites. | APP |+| `web.enable_javascript_rendering` | `LDR_WEB_ENABLE_JAVASCRIPT_RENDERING` | `false` | When enabled, falls back to a headless browser (Crawl4AI/Playwright) for pages that need JavaScript to render. Requires Chromium to be installed - the default Docker production image does NOT include it. To enable: install Chromium in the runtime environment (e.g. 'playwright install --with-deps chromium'), then toggle this setting. Note: in our limited (mostly accidental) benchmark comparisons - between dev instances that happened to have Chromium installed and routine Docker runs that did not - JS rendering did not measurably improve research quality, and most of our regular benchmark runs are on Docker without Chromium anyway. Leave disabled unless you have a specific need to scrape JavaScript-only sites. Runs with Public only, Private only, or Strict egress scope use static fetching only because the browser cannot enforce those scopes on its own DNS connections. | APP || `web.host` | `LDR_WEB_HOST` | `127.0.0.1` | The host address to listen on. Configured via LDR_WEB_HOST environment variable. Requires server restart. | APP || `web.port` | `LDR_WEB_PORT` | `5000` | The port to listen on. Configured via LDR_WEB_PORT environment variable. Requires server restart. | APP || `web.use_https` | `LDR_WEB_USE_HTTPS` | `true` | Does not enable HTTPS or configure TLS certificates: the web listener always serves plain HTTP, so terminate TLS at a reverse proxy. While this is true (the default), LDR logs a startup warning saying so; set it to false to silence the warning. Otherwise it only sets the scheme of an internal fallback server URL that nothing currently uses, so no generated link depends on it. Configured via LDR_WEB_USE_HTTPS; requires server restart. | APP |diff --git a/docs/SearXNG-Setup.md b/docs/SearXNG-Setup.mdindex dd4f4e2322..5550684f8d 100644--- a/docs/SearXNG-Setup.md+++ b/docs/SearXNG-Setup.md@@ -230,18 +230,63 @@ This is required *in addition to* one of the three instance-URL options above(the opt-in alone grants nothing), is environment-only (not settable from theweb UI), defaults to off, and is not set by the bundled `docker-compose.yml`.Even with it enabled, link-local addresses (`169.254.0.0/16`, `fe80::/10`) and-the cloud-metadata endpoints stay blocked. The egress-scope policy is-evaluated independently of this flag whenever the wrapper is given a run-context: under the default scope (`adaptive`, which follows SearXNG's public-classification) private result hosts are then denied by policy, and under any-run scope that restricts hosts by address class (`public_only`,-`private_only`, `strict`) the download pipeline keeps its strict default even-with the flag set, because it enforces address classes on redirect hops and-browser subresources but does not see the run policy. The factory does not-yet hand the wrapper a run context (#6131), so today the flag takes effect on-the SSRF axis alone, and how it composes with the scope policy is the pending-ADR-0007 / #6131 decision. See-[`security/egress/README.md`](../src/local_deep_research/security/egress/README.md).+the cloud-metadata endpoints stay blocked.++**The flag takes effect only under the `unprotected` egress scope.** The+search-engine factory hands the full-search wrapper the run's egress context,+and the wrapper applies the flag only when that context's scope places no+address-class restriction on hosts. Under every other scope the flag is+ignored and private result URLs are refused exactly as if it were unset, by+the SSRF check or, for private addresses the SSRF check lets through, by the+wrapper itself (see below):++- the default `adaptive` scope never resolves to `unprotected`: with SearXNG+ (or another public engine) as the primary it resolves to `public_only`,+ which does not permit private hosts, and on a classification fallback to+ `both`, covered next;+- `private_only`, `strict` and `both` retain the policy that full-content+ result URLs must classify as public. The private-result grant does not+ override that rule. Static downloads also enforce the run scope on every+ redirect and pinned connect address.++Under every scope except `unprotected` the wrapper refuses every result URL+whose address the egress policy classifies as private, including ranges the+SSRF check itself lets through (for example `198.18.0.0/15`, which fake-IP+DNS resolvers hand out, the documentation ranges, `240.0.0.0/4` and+`2001:db8::/32`). It asks the policy's own classifier before the counted+scope check, so this also holds under `strict`, `private_only` and `both`,+whose scope check would otherwise admit such private hosts. Refused private+result URLs do not count toward the run's denied-fetch quota, so they cannot+use it up and block later public fetches. The snippets of those results are+still returned, only their full content is missing. These checks apply to the+result URL itself. Static redirects and pinned connect addresses also receive+the run-scope check. Browser fallback is disabled under `public_only`,+`private_only` and `strict`; when available under `both` or `unprotected`,+its requests retain SSRF checks. Under `unprotected` without the flag only the SSRF check+applies, so the ranges it lets through are fetched there.++> **Known limitation: fake-IP DNS.** Proxy tools in fake-IP mode (Clash,+> sing-box, Surge in TUN mode) answer public names with `198.18.0.0/15`+> addresses, which the egress policy classifies as private. Full-content+> fetching is then unavailable under the default `adaptive` scope (which+> resolves to `public_only` with SearXNG) and every other scope except+> `unprotected`, and `strict` treats those public hosts as private on its+> other fetch paths. See+> [Known limitations](egress-modes.md#known-limitations) in the egress modes+> guide.++> **Upgrade note.** Released v1.x versions have no such flag and always block+> private result URLs, so upgrading from them changes nothing: the flag is new+> in v2.0.0 and works as described above. Development builds from #6196 up to+> #6535 gave the wrapper no run context and applied the flag under any scope+> that let SearXNG run, the default `adaptive` scope included, which bypassed+> the run's egress scope. If you ran such a build and relied on the flag for+> intranet full content, the research must now use the **Unprotected** scope+> (which needs the operator gate described under Unprotected in+> [`docs/egress-modes.md`](egress-modes.md)); under any other+> scope those results arrive without full content. When the flag is set but+> the scope keeps it from applying, LDR logs an INFO line naming the scope.+> See [`security/egress/README.md`](../src/local_deep_research/security/egress/README.md).### IPv6-only deployments (NAT64)diff --git a/docs/egress-modes.md b/docs/egress-modes.mdindex 6941f4e251..aee3cc8fab 100644--- a/docs/egress-modes.md+++ b/docs/egress-modes.md@@ -65,7 +65,16 @@ the run behaves like **Private only** (best effort, see the caveats there).**Not recommended — an operator-enabled escape hatch.** This mode is unavailable by default. The server operator must set `LDR_POLICY_ALLOW_UNPROTECTED_EGRESS=true` and restart the application. When enabled, egress-scope restrictions are disabledfor the run: any engine, URL, and LLM/embeddings provider is permitted. The-hard SSRF and cloud-metadata blocks still apply. A loud, non-dismissible banner+hard SSRF and cloud-metadata blocks still apply, so full-content fetching+still refuses the result URLs those SSRF checks block (loopback, RFC 1918,+link-local and the other ranges they list) unless the operator also set+`LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` for an approved engine such as a+self-hosted SearXNG; this is the only mode in which that flag takes effect.+Addresses the SSRF checks do not block are fetched here even when the egress+policy counts them as private, such as `198.18.0.0/15`, the documentation+ranges (`192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24`, `2001:db8::/32`)+and `240.0.0.0/4`. Every other mode refuses them as full-content result URLs.+A loud, non-dismissible bannershows while it is active. Prefer marking a collection **public**, or adding a**trusted inference provider** (`policy.trusted_inference_providers`, whichrelaxes only the run-start check described under Strict) for the specific case,@@ -97,7 +106,8 @@ document store that counts as public is your primary, other public engines canbe queried in the same run, and the agent may build those queries from itsdocuments. URL fetches are normally allowed to public hosts and blocked forprivate ones; the operator opt-in `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH`-described under Strict below is an exception. Inference is whatever you+does not change that here (it takes effect only under Unprotected, see+Strict below). Inference is whatever youconfigured (cloud allowed), but the run-start check described under Strictbelow normally refuses a run whose primary is a document store when the modelis a cloud provider. Use it when you want public research and don't@@ -131,14 +141,22 @@ any other engine at all.Result and document fetches under Strict normally reach neither public norprivate hosts. Private hosts are normally refused because LDR's fetch-time-SSRF checks relax private addresses only under Private only — except when the-operator has set `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` for an approved-public engine such as a self-hosted SearXNG: that engine's result fetches,-including redirects from its result URLs, can then reach private hosts under-any scope that lets the engine run, Strict included, whether or not it is the-primary (link-local and cloud-metadata addresses stay blocked). Public hosts-are normally stopped by the egress policy check or, on fetch paths without-one, by the socket guard described below (best effort).+SSRF checks relax private addresses only under Private only. The operator+opt-in `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` for an approved public engine+such as a self-hosted SearXNG does not change that: the full-content wrapper+applies it only under Unprotected, so under Strict, Public only, Private only,+Both and the default Adaptive that engine's private result URLs stay blocked+(see [SearXNG setup](SearXNG-Setup.md#full-content-fetching-of-private-result-urls)).+That covers every address the egress policy counts as private, including+ranges the SSRF checks let through, such as `198.18.0.0/15`, the+documentation ranges and `240.0.0.0/4`: full-content search refuses those+result URLs itself under every mode except Unprotected. The run policy also+checks each redirect and pinned connect address in the static downloader.+Browser fallback is disabled under Strict, Public only and Private only+because Chromium resolves its own DNS. Other fetch paths may use different+SSRF grants; see [Known limitations](#known-limitations). Public hosts are+normally stopped by the egress policy check or, on fetch paths without one,+by the socket guard described below (best effort).Strict does **not** turn on the *Require local* toggles. A run-start checknormally refuses a run that pairs a private primary source (a private@@ -175,7 +193,9 @@ The guard is a backstop, not a guarantee. Gaps include, among others:opened (some LLM clients share cached HTTP clients process-wide, and reusinga pooled connection opens no new socket for the guard to see);- the headless Chromium used for JavaScript rendering- (`web.enable_javascript_rendering`), which runs as a separate process;+ (`web.enable_javascript_rendering`), which runs as a separate process. Runs+ with Public only, Private only, or Strict scope therefore use static fetching+ only; the browser remains available for runs with Both or Unprotected scope;- worker threads that do not carry the run's egress context.---@@ -245,6 +265,36 @@ and selectable. Switching the scope automatically reconciles the selected engineif the current engine is disallowed under the new scope. Switching the scope or strategy re-evaluates thedropdown state without a page reload. The backend precheck remains the enforcement boundary and second backstop.+## Known limitations++### Fake-IP DNS (Clash, sing-box, Surge in TUN mode)++Proxy tools in "fake-IP" mode answer DNS lookups for public names with+addresses from `198.18.0.0/15` and route the connection through the proxy.+LDR's egress policy classifies that range as private (it follows Python's+`ipaddress.is_private`), so on such a machine every public website looks like+a private host:++- **Public only, and Adaptive when it resolves to Public only** (the default+ with SearXNG or another public primary engine): full-content fetching of+ search results is unavailable, because every result URL is refused as+ private; the snippets are still returned. Other fetches the egress policy+ checks (the content fetcher tool, library downloads) are refused the same+ way.+- **Strict and Private only**: those public hosts are treated as private.+ Full-content search still refuses them (it refuses every private result+ URL under these modes), but the other fetch paths and the socket guard+ admit them, so these modes do not keep such a run off the public internet.+- **Both**: Both admits private and public hosts alike, so the other fetch+ paths are unaffected; full-content search refuses these hosts as private+ result URLs, so it is unavailable here too.++To avoid this, exclude LDR's traffic from fake-IP resolution (for example a+real-IP / `fake-ip-filter` rule for the hosts LDR needs, or run LDR outside the+TUN interface). Classifying `198.18.0.0/15` by the address a fake-IP resolver+maps it to is a known gap in the egress classifier, tracked in+[#7093](https://github.com/LearningCircuit/local-deep-research/issues/7093).+## Audit logChanges to any `policy.*` key, `llm.require_local_endpoint`,diff --git a/src/local_deep_research/content_fetcher/fetcher.py b/src/local_deep_research/content_fetcher/fetcher.pyindex 94a418b8f9..a3dee35816 100644--- a/src/local_deep_research/content_fetcher/fetcher.py+++ b/src/local_deep_research/content_fetcher/fetcher.py@@ -183,8 +183,8 @@ class ContentFetcher:return downloaderdef _apply_egress_policy_to_downloader(self, downloader: Any) -> None:- """Relax a downloader's SafeSession to allow private IPs when the- active scope is PRIVATE_ONLY, mirroring ``policy_aware_validate_url``.+ """Carry the run policy into transport and relax private IPs only for+ PRIVATE_ONLY, mirroring ``policy_aware_validate_url``.Without this, a private/lab URL that ContentFetcher already approved(policy_aware_validate_url + evaluate_url both allow private hosts@@ -197,6 +197,9 @@ class ContentFetcher:"""if downloader is None or self.egress_context is None:return+ session = getattr(downloader, "session", None)+ if session is not None:+ session.egress_context = self.egress_context# Narrow except (not bare Exception): the only things that can throw# here are the policy import and the ctx.scope attribute access. The# failure direction is fail-SAFE — if we don't set allow_private_ips it@@ -212,17 +215,10 @@ class ContentFetcher:logger.debug("content_fetcher.egress_scope_unavailable")returnif scope == EgressScope.PRIVATE_ONLY:- session = getattr(downloader, "session", None)if session is not None and hasattr(session, "allow_private_ips"):session.allow_private_ips = True- # Also thread the relaxation to the JS-render browser path. The- # AutoHTMLDownloader lazily builds a PlaywrightHTMLDownloader- # child that SSRF-validates every browser request (initial nav +- # each redirect hop + subresources) via its own guard, reading- # ``allow_private_ips`` at build time — so setting it here, before- # the child is built, threads PRIVATE_ONLY through to the browser.- # Cloud-metadata IPs stay blocked regardless (validate_url always- # rejects them).+ # The browser path is independently refused for restricted scopes;+ # this flag is retained for the pinned static HTTP path.if hasattr(downloader, "allow_private_ips"):downloader.allow_private_ips = Truediff --git a/src/local_deep_research/defaults/.env.template b/src/local_deep_research/defaults/.env.templateindex 153d953b4f..71b3a1ef80 100644--- a/src/local_deep_research/defaults/.env.template+++ b/src/local_deep_research/defaults/.env.template@@ -48,6 +48,10 @@## The approvals above cover the instance URL only. Fetching full content from# private RESULT URLs (e.g. an internal wiki your SearXNG indexes) needs this-# separate opt-in on top of one of them; link-local and cloud-metadata-# addresses stay blocked either way:+# separate opt-in on top of one of them, AND it takes effect only for research+# run under the "unprotected" egress scope (which itself needs the operator+# gate LDR_POLICY_ALLOW_UNPROTECTED_EGRESS=true). Under every other scope, the+# default "adaptive" included, private result URLs stay blocked even with this+# set (LDR logs an INFO line naming the scope). Link-local and cloud-metadata+# addresses stay blocked either way. See docs/SearXNG-Setup.md.# LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH=truediff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 8cc02ac2ac..ff0444ce5e 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -3354,7 +3354,7 @@},"web.enable_javascript_rendering": {"category": null,- "description": "When enabled, falls back to a headless browser (Crawl4AI/Playwright) for pages that need JavaScript to render. Requires Chromium to be installed - the default Docker production image does NOT include it. To enable: install Chromium in the runtime environment (e.g. 'playwright install --with-deps chromium'), then toggle this setting. Note: in our limited (mostly accidental) benchmark comparisons - between dev instances that happened to have Chromium installed and routine Docker runs that did not - JS rendering did not measurably improve research quality, and most of our regular benchmark runs are on Docker without Chromium anyway. Leave disabled unless you have a specific need to scrape JavaScript-only sites.",+ "description": "When enabled, falls back to a headless browser (Crawl4AI/Playwright) for pages that need JavaScript to render. Requires Chromium to be installed - the default Docker production image does NOT include it. To enable: install Chromium in the runtime environment (e.g. 'playwright install --with-deps chromium'), then toggle this setting. Note: in our limited (mostly accidental) benchmark comparisons - between dev instances that happened to have Chromium installed and routine Docker runs that did not - JS rendering did not measurably improve research quality, and most of our regular benchmark runs are on Docker without Chromium anyway. Leave disabled unless you have a specific need to scrape JavaScript-only sites. Runs with Public only, Private only, or Strict egress scope use static fetching only because the browser cannot enforce those scopes on its own DNS connections.","editable": true,"max_value": null,"min_value": null,diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.pyindex b2aabf2da6..b635f85d6f 100644--- a/src/local_deep_research/research_library/downloaders/arxiv.py+++ b/src/local_deep_research/research_library/downloaders/arxiv.py@@ -14,6 +14,7 @@ from loguru import loggerfrom ...security import redact_url_for_logfrom ...constants import USER_AGENT+from ...security.egress.policy import PolicyDeniedErrorfrom ...utilities.arxiv import extract_arxiv_id, is_arxiv_paper_urlfrom ...utilities.arxiv_api import arxiv_api_request_gatefrom .base import ContentType, DownloadResult@@ -919,6 +920,8 @@ class ArxivDownloader(HTMLDownloader):if api_text is None:error_type = "UnusableFeed"+ except PolicyDeniedError:+ raiseexcept Exception as e:logger.debug(f"Failed to fetch from arXiv API ({type(e).__name__})")error_type = type(e).__name__diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.pyindex a67246d12f..d9e01e107e 100644--- a/src/local_deep_research/research_library/downloaders/base.py+++ b/src/local_deep_research/research_library/downloaders/base.py@@ -15,6 +15,7 @@ from ...web_search_engines.rate_limiting import (AdaptiveRateLimitTracker,)from ...security import SafeSession, safe_requests+from ...security.egress.policy import PolicyDeniedErrorfrom ...utilities.pdf_extraction_limits import (MAX_PDF_EXTRACTED_CHARS,MAX_PDF_EXTRACTION_CPU_SECONDS,@@ -535,6 +536,8 @@ class BaseDownloader(ABC):# connection to the pool instead of leaking it.safe_close(response, "downloader response")+ except PolicyDeniedError:+ raiseexcept (requests.exceptions.Timeout,requests.exceptions.ConnectionError,diff --git a/src/local_deep_research/research_library/downloaders/biorxiv.py b/src/local_deep_research/research_library/downloaders/biorxiv.pyindex 0896b2a383..5cb3616aad 100644--- a/src/local_deep_research/research_library/downloaders/biorxiv.py+++ b/src/local_deep_research/research_library/downloaders/biorxiv.py@@ -10,6 +10,7 @@ import requestsfrom loguru import loggerfrom ...security.ssrf_validator import redact_url_for_log+from ...security.egress.policy import PolicyDeniedErrorfrom .base import BaseDownloader, ContentType, DownloadResult@@ -201,6 +202,8 @@ class BioRxivDownloader(BaseDownloader):)return "\n".join(text_parts)+ except PolicyDeniedError:+ raiseexcept Exception as e:logger.opt(exception=False).debug("Failed to fetch abstract from bioRxiv/medRxiv: {} ({})",diff --git a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py b/src/local_deep_research/research_library/downloaders/extraction/pipeline.pyindex b275e0d330..bed3e44675 100644--- a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py+++ b/src/local_deep_research/research_library/downloaders/extraction/pipeline.py@@ -28,6 +28,7 @@ from .newspaper_extractor import NewspaperExtractorfrom .metadata_extractor import extract_metadata, metadata_to_textfrom ....security.log_sanitizer import failure_reason_for_logfrom ....security.ssrf_validator import redact_url_for_log+from ....security.egress.policy import PolicyDeniedErrorfrom ....utilities.lxml_thread_safety import install_per_thread_html_parsers# Route newspaper4k's and readabilipy's parser-less lxml.html.fromstring calls@@ -422,7 +423,11 @@ class _SpecializedResult(NamedTuple):def _try_specialized_downloader(- url: str, timeout: int = 30+ url: str,+ timeout: int = 30,+ allow_private_ips: bool = False,+ block_link_local: bool = False,+ egress_context: Any = None,) -> _SpecializedResult:"""Try a specialized downloader (arXiv, PubMed, etc.) for the URL.@@ -510,6 +515,11 @@ def _try_specialized_downloader(skip_reason: str | None = Nonetry:+ session = getattr(downloader, "session", None)+ if session is not None:+ session.allow_private_ips = allow_private_ips+ session.block_link_local = block_link_local+ session.egress_context = egress_contextresult = downloader.download_with_result(url, ContentType.TEXT)if result.is_success and result.content:text = result.content.decode("utf-8", errors="replace")@@ -527,6 +537,8 @@ def _try_specialized_downloader(result.skip_reasonor "Specialized downloader returned no usable content")+ except PolicyDeniedError:+ raiseexcept Exception as e:skip_reason = "Specialized downloader failed"logger.opt(exception=False).debug(@@ -556,6 +568,7 @@ def fetch_and_extract(enable_js_rendering: bool = False,allow_private_ips: bool = False,block_link_local: bool = False,+ egress_context: Any = None,) -> Optional[str]:"""Fetch a URL and extract clean text content.@@ -577,24 +590,29 @@ def fetch_and_extract(research-quality improvement from JS rendering, and most regularbenchmark runs are on Docker without Chromium anyway. Theuser-facing toggle is ``web.enable_javascript_rendering``.- allow_private_ips: Whether the generic HTML downloader may access- private IP addresses. Only set True by callers whose parent- engine holds a resolved private result-fetch grant and whose- run egress policy, if any, restricts no host class: the- downloader applies this flag to every destination it reaches- (redirect hops, browser subresources) but never sees that- policy. The cloud-metadata literals in- ``ALWAYS_BLOCKED_METADATA_IPS`` stay blocked regardless.+ allow_private_ips: Whether the downloader may access private IPs+ after SSRF validation. The run policy, when supplied, is also+ checked on each redirect and pinned connect address. Cloud+ metadata remains blocked regardless.block_link_local: Keep the whole link-local range blocked even when``allow_private_ips`` is True (forwarded to the downloader'sstatic-fetch ``SafeSession``). No effect without the grant.+ egress_context: Optional run policy enforced on every transport hop.Returns:Extracted plain text, or None if fetch or extraction failed."""# Try specialized downloader first (arXiv, PubMed, etc.)try:- specialized = _try_specialized_downloader(url, timeout=timeout)+ specialized = _try_specialized_downloader(+ url,+ timeout=timeout,+ allow_private_ips=allow_private_ips,+ block_link_local=block_link_local,+ egress_context=egress_context,+ )+ except PolicyDeniedError:+ raiseexcept Exception as e:logger.opt(exception=False).debug(f"Pipeline: specialized downloader error for "@@ -626,6 +644,7 @@ def fetch_and_extract(block_link_local=block_link_local,)try:+ downloader.session.egress_context = egress_context# download() returns extracted text as UTF-8 bytes (not raw HTML):# AutoHTMLDownloader inherits HTMLDownloader.download() which runs# _fetch_html() → _extract_content() → the full extraction pipeline.@@ -633,6 +652,8 @@ def fetch_and_extract(if result:return result.decode("utf-8", errors="replace")return None+ except PolicyDeniedError:+ raiseexcept Exception as e:# Type name only -- exception texts embed the raw URL and loguru# renders them with any traceback even when diagnose=False.@@ -656,6 +677,7 @@ def batch_fetch_and_extract(allow_private_ips: bool = False,block_link_local: bool = False,progress_callback: Optional[Callable[[int, int], None]] = None,+ egress_context: Any = None,) -> Dict[str, Optional[str]]:"""Fetch multiple URLs and extract clean text from each.@@ -678,17 +700,14 @@ def batch_fetch_and_extract(research-quality improvement from JS rendering, and most regularbenchmark runs are on Docker without Chromium anyway. Theuser-facing toggle is ``web.enable_javascript_rendering``.- allow_private_ips: Whether the generic HTML downloader may access- private IP addresses. Only set True by callers whose parent- engine holds a resolved private result-fetch grant and whose- run egress policy, if any, restricts no host class: the- downloader applies this flag to every destination it reaches- (redirect hops, browser subresources) but never sees that- policy. The cloud-metadata literals in- ``ALWAYS_BLOCKED_METADATA_IPS`` stay blocked regardless.+ allow_private_ips: Whether the downloader may access private IPs+ after SSRF validation. The run policy, when supplied, is also+ checked on each redirect and pinned connect address. Cloud+ metadata remains blocked regardless.block_link_local: Keep the whole link-local range blocked even when``allow_private_ips`` is True (forwarded to the downloader'sstatic-fetch ``SafeSession``). No effect without the grant.+ egress_context: Optional run policy enforced on every transport hop.progress_callback: Optional ``(done, total)`` hook invoked onceup front with ``(0, len(urls))`` and after each URLcompletes. Lets a long serial fetch report liveness (and@@ -734,7 +753,13 @@ def batch_fetch_and_extract(html_urls: List[str] = []for url in urls:try:- specialized = _try_specialized_downloader(url, timeout=timeout)+ specialized = _try_specialized_downloader(+ url,+ timeout=timeout,+ allow_private_ips=allow_private_ips,+ block_link_local=block_link_local,+ egress_context=egress_context,+ )if specialized.content:results[url] = specialized.contentdone += 1@@ -752,6 +777,11 @@ def batch_fetch_and_extract(done += 1_report_progress()continue+ except PolicyDeniedError:+ results[url] = None+ done += 1+ _report_progress()+ continueexcept Exception as e:logger.opt(exception=False).debug(f"Pipeline: specialized downloader error for "@@ -774,6 +804,7 @@ def batch_fetch_and_extract(block_link_local=block_link_local,)try:+ downloader.session.egress_context = egress_contextfor url in html_urls:try:data = downloader.download(url)@@ -781,6 +812,8 @@ def batch_fetch_and_extract(results[url] = data.decode("utf-8", errors="replace")else:results[url] = None+ except PolicyDeniedError:+ results[url] = Noneexcept Exception as e:logger.opt(exception=False).error(f"batch_fetch_and_extract failed for "diff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.pyindex 727760aadc..7aca65646c 100644--- a/src/local_deep_research/research_library/downloaders/html.py+++ b/src/local_deep_research/research_library/downloaders/html.py@@ -26,6 +26,7 @@ from ...security.client_safe_errors import (client_safe_download_message,)from ...security.ssrf_validator import redact_url_for_log+from ...security.egress.policy import PolicyDeniedErrorfrom ...utilities.pdf_extraction_limits import MAX_PDF_EXTRACTION_PAGESfrom ...utilities.resource_utils import safe_close@@ -192,6 +193,8 @@ class HTMLDownloader(BaseDownloader):return None+ except PolicyDeniedError:+ raiseexcept Exception as e:# Log the exception class only (zero-risk: the token already# exposes it to the client). Never log str(e) or the traceback:@@ -268,6 +271,8 @@ class HTMLDownloader(BaseDownloader):is_success=True,)+ except PolicyDeniedError:+ raiseexcept Exception as e:logger.opt(exception=False).error("html.download_result_failed url={url} exc_class={exc_class}",@@ -506,6 +511,11 @@ class HTMLDownloader(BaseDownloader):# body is consumed or the response is closed.safe_close(response, "HTML download response")+ except PolicyDeniedError:+ self._recovery_kind = None+ self._recovery_payload = None+ self._recovery_url = None+ raiseexcept _TerminalTransportError as terminal:return _terminal_failure(terminal.exc, terminal.wait_time, terminal.attempt@@ -547,6 +557,8 @@ class HTMLDownloader(BaseDownloader):allow_redirects=True,stream=True,)+ except PolicyDeniedError:+ raiseexcept (RequestsTimeout, RequestsConnectionError) as e:if attempt >= max_attempts:raise _TerminalTransportError(e, wait_time, attempt) from ediff --git a/src/local_deep_research/research_library/downloaders/playwright_html.py b/src/local_deep_research/research_library/downloaders/playwright_html.pyindex 69a7abced0..73dbf4b3fb 100644--- a/src/local_deep_research/research_library/downloaders/playwright_html.py+++ b/src/local_deep_research/research_library/downloaders/playwright_html.py@@ -23,6 +23,7 @@ from .base import rate_limit_authorityfrom .html import HTMLDownloaderfrom ...constants import BROWSER_USER_AGENTfrom ...security import ssrf_validator+from ...security.egress.policy import Decision, EgressScope, PolicyDeniedErrorfrom ...security.ssrf_validator import redact_url_for_logfrom ...security.safe_requests import (_MAX_REDIRECTS,@@ -105,6 +106,15 @@ SPA_SIGNALS = []+def _browser_transport_allowed(session) -> bool:+ """Native browser DNS cannot enforce a restricted run's pinned scope."""+ context = getattr(session, "egress_context", None)+ return context is None or getattr(context, "scope", None) in (+ EgressScope.BOTH,+ EgressScope.UNPROTECTED,+ )++def _cookie_domain_matches(host: str, cookie_domain: str) -> bool:"""Whether a ``Set-Cookie`` ``Domain=`` attribute may be honored for aresponse served by ``host``.@@ -330,6 +340,9 @@ class PlaywrightHTMLDownloader(HTMLDownloader):registrable domain a later hop redirects to — the same protection thecrawl4ai path applies via ``_reapply_hop_cookies``."""+ if not _browser_transport_allowed(self.session):+ route.abort("blockedbyclient")+ returnrequest = route.requestfirst_url = request.urlscheme = urlparse(first_url).scheme.lower()@@ -466,6 +479,9 @@ class PlaywrightHTMLDownloader(HTMLDownloader):does not stall Crawl4AI's event loop. Installed on each page contextvia the ``on_page_context_created`` hook."""+ if not _browser_transport_allowed(self.session):+ await route.abort("blockedbyclient")+ returnrequest = route.requestfirst_url = request.urlscheme = urlparse(first_url).scheme.lower()@@ -896,6 +912,8 @@ class PlaywrightHTMLDownloader(HTMLDownloader):parser = RobotFileParser()parser.parse(response.text.splitlines())return parser.can_fetch(BROWSER_USER_AGENT, url)+ except PolicyDeniedError:+ raiseexcept Exception:# SafeSession raises ValueError on an SSRF-unsafe hop; network /# parse errors land here too. Fail open for politeness — the@@ -911,6 +929,10 @@ class PlaywrightHTMLDownloader(HTMLDownloader):Tries Crawl4AI first (with robots.txt, shadow DOM, iframes),falls back to plain Playwright."""+ if not _browser_transport_allowed(self.session):+ raise PolicyDeniedError(+ Decision(False, "browser_transport_cannot_enforce_scope"), url+ )# Entry-URL scheme guard (fail-closed). The browser downloader is# reachable via download()/download_with_result(), which do NOT# constrain the scheme themselves — only can_handle() checks it, and@@ -1113,6 +1135,8 @@ class PlaywrightHTMLDownloader(HTMLDownloader):)return None+ except PolicyDeniedError:+ raiseexcept Exception as e:# DEBUG, not ERROR: this except is normal control flow — it# returns None, so _fetch_html falls back to@@ -1246,6 +1270,8 @@ class PlaywrightHTMLDownloader(HTMLDownloader):url=redact_url_for_log(url),)return None+ except PolicyDeniedError:+ raiseexcept Exception as e:# Type name only: Playwright error texts embed the navigated# URL, and loguru renders ``ExcType: str(e)`` with a traceback@@ -1338,6 +1364,11 @@ class AutoHTMLDownloader(HTMLDownloader):allow_private_ips=self.allow_private_ips,block_link_local=self.block_link_local,)+ # The child creates its own SafeSession for robots.txt and other+ # auxiliary requests. Keep it bound to the parent run's policy.+ self._playwright_downloader.session.egress_context = getattr(+ self.session, "egress_context", None+ )return self._playwright_downloader@staticmethod@@ -1378,6 +1409,8 @@ class AutoHTMLDownloader(HTMLDownloader):allow_redirects=True,)self._last_raw_html = response.text+ except PolicyDeniedError:+ raiseexcept Exception:# Expected/routine (403s, challenge pages, network blips) —# keep at DEBUG, not ERROR, to avoid flooding alerting. Still@@ -1417,6 +1450,9 @@ class AutoHTMLDownloader(HTMLDownloader):no_content = result is None or len(result) < self.min_content_lengthif needs_js or no_content:+ if not _browser_transport_allowed(self.session):+ logger.debug("auto_html.js_fallback_scope_refused")+ return resultif not self.enable_js_rendering:logger.debug("auto_html.js_fallback_disabled url={url}",@@ -1479,6 +1515,9 @@ class AutoHTMLDownloader(HTMLDownloader):)if needs_js or no_content:+ if not _browser_transport_allowed(self.session):+ logger.debug("auto_html.js_fallback_scope_refused")+ return resultif not self.enable_js_rendering:logger.debug("auto_html.js_fallback_disabled url={url}",diff --git a/src/local_deep_research/research_library/downloaders/pubmed.py b/src/local_deep_research/research_library/downloaders/pubmed.pyindex ea7aae7bc8..66e63be060 100644--- a/src/local_deep_research/research_library/downloaders/pubmed.py+++ b/src/local_deep_research/research_library/downloaders/pubmed.py@@ -10,6 +10,7 @@ from loguru import loggerfrom ...security import redact_url_for_logfrom .base import BaseDownloader, ContentType, DownloadResult+from ...security.egress.policy import PolicyDeniedErrorclass PubMedDownloader(BaseDownloader):@@ -187,6 +188,8 @@ class PubMedDownloader(BaseDownloader):return DownloadResult(skip_reason=f"Article PMID:{pmid} not found in Europe PMC database")+ except PolicyDeniedError:+ raiseexcept Exception as e:logger.debug(f"Error checking article status ({type(e).__name__})"@@ -311,6 +314,8 @@ class PubMedDownloader(BaseDownloader):)return text+ except PolicyDeniedError:+ raiseexcept Exception as e:logger.debug(f"Failed to fetch text from Europe PMC ({type(e).__name__})"@@ -416,6 +421,8 @@ class PubMedDownloader(BaseDownloader):)return self._download_via_europe_pmc(pmcid)+ except PolicyDeniedError:+ raiseexcept Exception as e:logger.debug(f"Europe PMC API query failed ({type(e).__name__})")@@ -449,6 +456,8 @@ class PubMedDownloader(BaseDownloader):pmc_id_num = linksetdb["links"][0]return f"PMC{pmc_id_num}"+ except PolicyDeniedError:+ raiseexcept Exception as e:logger.debug(f"NCBI E-utilities lookup failed ({type(e).__name__})")@@ -463,6 +472,8 @@ class PubMedDownloader(BaseDownloader):if pmc_match:return pmc_match.group(0)+ except PolicyDeniedError:+ raiseexcept Exception as e:logger.debug(f"PubMed page scraping failed ({type(e).__name__})")diff --git a/src/local_deep_research/security/dns_pinning.py b/src/local_deep_research/security/dns_pinning.pyindex a491f2800e..2c524373e0 100644--- a/src/local_deep_research/security/dns_pinning.py+++ b/src/local_deep_research/security/dns_pinning.py@@ -644,7 +644,7 @@ def pinned_request(allow_localhost: bool = False,allow_private_ips: bool = False,block_link_local: bool = False,-) -> Iterator[None]:+) -> Iterator[Optional[List[tuple]]]:"""Pin DNS for the duration of a single outbound request to ``url``.Resolves the URL host ONCE, validates every returned address against@@ -658,7 +658,9 @@ def pinned_request(answer that moved into ``169.254.0.0/16`` between validation andconnect.- Yields without pinning when the host is an IP literal (no DNS to+ Yields the validated address list so the caller can apply any run-level+ egress scope to the exact addresses that will be connected to. Yields+ ``None`` without pinning when the host is an IP literal (no DNS torebind — the caller's ``validate_url`` already vetted the literal) orwhen the URL host cannot be extracted.@@ -672,7 +674,7 @@ def pinned_request("""host, is_literal = _extract_host(url)if host is None or is_literal:- yield+ yield Nonereturnentry = _resolve_and_validate(@@ -689,7 +691,7 @@ def pinned_request(previous = pins.get(host)pins[host] = entrytry:- yield+ yield entryfinally:if had_previous:pins[host] = previousdiff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.mdindex 5c2e854e32..22a21607a2 100644--- a/src/local_deep_research/security/egress/README.md+++ b/src/local_deep_research/security/egress/README.md@@ -155,7 +155,7 @@ actually enforces the policy":|---|---|---|| Search engine creation | `web_search_engines/search_engine_factory.py` (`create_search_engine`) | `evaluate_engine` / `evaluate_retriever` || LangGraph agent tools | `advanced_search_system/strategies/langgraph_agent_strategy.py` (`_build_tools`) | `evaluate_engine` / `evaluate_retriever` (tool-list filter) |-| Full-content fetch | `web_search_engines/engines/full_search.py` (SSRF validation runs with the parent engine's resolved private result-fetch grant, `egress/validators.resolve_engine_allow_private_result_fetch`, handed over by `web_search_engines/search_engine_factory.py` (`_create_full_search_wrapper`, reading the engine's `allow_private_result_fetch` declared in `web_search_engines/search_engine_base.py`) when it builds the wrapper, and keeps link-local blocked under it) | `evaluate_url` (scope, independent of the grant; runs only when the wrapper is given a run context, which the factory does not supply yet, see #6131); the grant needs the instance approval below AND the env-only opt-in `search.allow_private_result_fetch`, which compose does not set; the download pipeline receives it only without a run context or under the unprotected scope, since it enforces address classes on redirect hops and browser subresources but not the run scope |+| Full-content fetch | `web_search_engines/engines/full_search.py` (SSRF validation runs with the parent engine's resolved private result-fetch grant, `egress/validators.resolve_engine_allow_private_result_fetch`, handed over by `web_search_engines/search_engine_factory.py` (`_create_full_search_wrapper`, reading the engine's `allow_private_result_fetch` declared in `web_search_engines/search_engine_base.py`) when it builds the wrapper, and keeps link-local blocked under it) | `evaluate_url` (scope, independent of the grant; the factory hands the wrapper the run's validated egress context, and without one it returns the snippets-only engine instead of a wrapper, #6535); the grant needs the instance approval below AND the env-only opt-in `search.allow_private_result_fetch`, which compose does not set; the wrapper applies it (to the SSRF validation of result URLs and to the download pipeline) only under the unprotected scope. Static downloads enforce the run scope on every redirect and pinned connect address; browser fallback is disabled under public_only, private_only and strict. Under every other scope a private result URL is refused before `evaluate_url` runs, by the SSRF validation or, for hosts the SSRF validator admits but the policy does not classify public, by the wrapper's check against `policy.host_not_classified_public` (same classifier as `evaluate_url`, records no denial). That check runs under strict, private_only and both too, whose `evaluate_url` would otherwise admit private ranges, so the URL is never fetched, and it does not count toward `MAX_DENIED_FETCHES_PER_RUN`. The wrapper checks see the result URL only; static redirects and pinned connect addresses receive both SSRF and run-scope validation. Browser requests, when allowed under both or unprotected, retain SSRF validation. Under unprotected without the grant only the SSRF validation applies, so the ranges it admits are fetched || Content fetcher tool | `content_fetcher/fetcher.py` | `policy_aware_validate_url` + `evaluate_url` || Library downloads | `research_library/services/download_service.py` | `evaluate_url` at the fetch fire-points || LLM construction | `config/llm_config.py` (`get_llm`) | `evaluate_llm_endpoint` (+ snapshot-less allow-list) |@@ -336,7 +336,7 @@ Each cell is the decision produced by the real `evaluate_*` logic / PEP for that| **Raw socket** (audit hook → `evaluate_url`) | private→ARMED (public BLOCKED, best effort); public→INACTIVE | INACTIVE (passthrough) | INACTIVE (passthrough) | **ARMED** — public-address socket.connect BLOCKED on threads carrying the run's context (best effort, see below) | ARMED — public-address socket.connect BLOCKED on threads carrying the run's context (best effort, see below) || **Cloud-metadata IP** (169.254.169.254 / NAT64) | BLOCKED | BLOCKED | BLOCKED | BLOCKED | BLOCKED |-The URL-fetch rows show the `evaluate_url` decision where that check runs. Under `strict`, search-result and document fetches normally reach neither public nor private hosts. Private hosts are normally refused because LDR's fetch-time SSRF checks relax private addresses only under `private_only` — except when the operator has set `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` for an approved public engine such as a self-hosted SearXNG: that engine's result fetches, including redirects from its result URLs, can then reach private hosts under any scope that lets the engine run, `strict` included, whether or not it is the primary, because the full-content fetch grant does not depend on scope and the factory supplies no run context, so `evaluate_url` does not run there (see the Full-content fetch row above; link-local and cloud metadata stay blocked). Public hosts are normally stopped by the policy check or, on fetch paths without one, by the socket guard (best effort).+The URL-fetch rows show the `evaluate_url` decision where that check runs. Under `strict`, search-result and document fetches normally reach neither public nor private hosts. Private hosts are normally refused because LDR's fetch-time SSRF checks relax private addresses only under `private_only`. `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` for an approved public engine such as a self-hosted SearXNG does not change that under `strict` or any other protected scope: the full-content wrapper applies that grant only under `unprotected` (see the Full-content fetch row above; link-local and cloud metadata stay blocked even there). The SSRF checks do not cover every policy-private range (198.18.0.0/15, the documentation ranges and 240.0.0.0/4 pass them); the full-content wrapper refuses those result URLs itself under every scope but `unprotected`, but on the other fetch paths and at the socket guard `strict` admits them as private hosts. Under fake-IP DNS (Clash, sing-box), which answers public names inside 198.18.0.0/15, that means `strict` admits public hosts there, and `public_only` refuses every such host, full-content search included (see "Known limitations" in `docs/egress-modes.md`). Public hosts are normally stopped by the policy check or, on fetch paths without one, by the socket guard (best effort).### Key invariants (the crystal-clear takeaways)diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.pyindex a48c4c04b6..2723810b65 100644--- a/src/local_deep_research/security/egress/policy.py+++ b/src/local_deep_research/security/egress/policy.py@@ -1626,13 +1626,13 @@ def evaluate_url(url: str, ctx: EgressContext) -> Decision:# (DNS fails) while the client actually connects to the private# 192.168.1.1 — a scope bypass under PUBLIC_ONLY. Classify the# DECODED host so the policy sees the real connect target.- host = unquote(parsed.hostname)# Trailing dots are insignificant to the resolver (getaddrinfo strips# them), so "169.254.169.254." and "metadata.google.internal." must be# classified identically to their bare forms — otherwise a trailing# dot dodges the metadata checks below. Mirrors the SSRF validator's- # rstrip(".").- host = host.rstrip(".")+ # rstrip("."). Shared with ``host_not_classified_public`` via+ # ``_policy_host`` so both classify the same host.+ host = _policy_host(parsed.hostname)# Cloud-metadata endpoints (AWS/GCE/Azure IMDS at 169.254.169.254# etc.) are NEVER permitted, regardless of scope. They classify as@@ -1716,6 +1716,72 @@ def evaluate_url(url: str, ctx: EgressContext) -> Decision:return Decision(False, "internal_error")+def host_not_classified_public(url: str, ctx: EgressContext) -> bool:+ """True when ``url`` is an http(s) URL whose host the policy does NOT+ classify public (private, or unclassifiable), decided WITHOUT recording+ a denial (nothing counts toward ``MAX_DENIED_FETCHES_PER_RUN``).++ Independent of ``ctx.scope``: the caller decides which scopes refuse+ such hosts. Lets a caller that refuses private destinations as a matter+ of course (the full-content search wrapper, whose result URLs come from+ an index it does not control, under every scope but ``unprotected``)+ drop them before ``evaluate_url`` without each one spending the run's+ quota. It uses the SAME host normalisation and the SAME+ ``_classify_host`` (and run-scoped DNS cache) as ``evaluate_url``, so+ the set it returns True for is exactly the set ``evaluate_url`` refuses+ as ``scope_mismatch_public_only`` under ``public_only``, not a second,+ differently defined list. (The SSRF validator's ``PRIVATE_IP_RANGES``+ is narrower: it admits 198.18.0.0/15, the TEST-NETs, 192.0.0.0/24,+ 240.0.0.0/4, 2001:db8::/32 and, with NAT64 allowed, 64:ff9b:1::/48,+ all of which classify private here; so does any hostname a fake-IP DNS+ resolver answers inside 198.18.0.0/15.)++ Returns False for anything ``evaluate_url`` refuses for another reason+ first (malformed URL, non-http(s) scheme, no host); a cloud-metadata+ host classifies public, so it is left to ``evaluate_url``'s+ ``blocked_metadata_ip`` denial. An internal error returns True (fails+ toward refusal, which records no denial either).+ """+ if not isinstance(url, str) or not url:+ return False+ try:+ parsed = urlsplit(url)+ hostname = parsed.hostname+ except Exception: # noqa: silent-exception - malformed, see docstring+ return False+ if parsed.scheme.lower() not in ("http", "https") or not hostname:+ return False+ try:+ return _classify_host(_policy_host(hostname), ctx) is not False+ except Exception: # noqa: silent-exception - fail toward refusal+ return True+++def _policy_host(hostname: str) -> str:+ """The host ``evaluate_url`` classifies: percent-decoded (HTTP clients+ decode it before connecting) and without trailing dots (insignificant+ to the resolver); see the comments at its call site there."""+ return unquote(hostname).rstrip(".")+++def url_host_is_declared_local(url: object, ctx: EgressContext) -> bool:+ """Whether the URL host has the run's operator-declared local status.++ The declared name must retain its classification when DNS pinning checks+ the connect-time address; an address-only URL would lose that override.+ Apply the same hostname normalization as ``evaluate_url``.+ """+ if not ctx.local_hostnames or not isinstance(url, str) or not url:+ return False+ try:+ host = urlsplit(url).hostname+ except Exception:+ return False+ if not host:+ return False+ return _policy_host(host) in ctx.local_hostnames++def _record_denial(ctx: EgressContext, url: object, reason: str) -> Decision:"""Increment the denial counter inside the frozen context's mutable dictand emit a redacted audit log line. Lock guards the read-modify-writediff --git a/src/local_deep_research/security/egress/validators.py b/src/local_deep_research/security/egress/validators.pyindex af0e562cb9..c674c6f3f5 100644--- a/src/local_deep_research/security/egress/validators.py+++ b/src/local_deep_research/security/egress/validators.py@@ -519,8 +519,8 @@ def resolve_engine_allow_private_result_fetch(condition is met by every Docker (compose) deployment. A public engineproxies the public web, so extending the instance grant to the URLsthe engine *returns* would let a poisoned index turn result fetching- into SSRF against the operator's LAN (loopback included). Private- result fetching is therefore permitted only when BOTH hold:+ into SSRF against the operator's LAN (loopback included). This+ returns True (the engine holds the grant) only when BOTH hold:1. the operator set the env-only opt-in``search.allow_private_result_fetch``@@ -529,6 +529,12 @@ def resolve_engine_allow_private_result_fetch(2. the engine is approved for its own instance URL(``resolve_engine_allow_private_ips``).+ Holding the grant is necessary but not sufficient: the full-content+ wrapper applies it only when the run's egress scope is+ ``unprotected`` (``FullSearchResults._effective_allow_private_ips``).+ Under every other scope, the default adaptive scope included, private+ result URLs stay blocked even when this returns True.+Link-local (``169.254.0.0/16``, ``fe80::/10``) and the cloud-metadataliterals in ``ALWAYS_BLOCKED_METADATA_IPS`` stay blocked even whenthis returns True: the full-content fetch path validates withdiff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.pyindex 4d3c7a1493..abb8ef0da0 100644--- a/src/local_deep_research/security/safe_requests.py+++ b/src/local_deep_research/security/safe_requests.py@@ -8,7 +8,7 @@ import datetimeimport email.utilsimport threadingimport time-from typing import Any, Optional+from typing import TYPE_CHECKING, Any, Optionalfrom urllib.parse import urljoinimport requests@@ -19,6 +19,9 @@ from . import ssrf_validatorfrom ..constants import USER_AGENTfrom ..utilities.resource_utils import safe_close+if TYPE_CHECKING:+ from .egress.policy import EgressContext+# Log lines and raised exception texts below carry only scheme://host:port:# the texts flow into caller logs (loguru renders ``ExcType: str(e)``) and# into DB error columns, and the URLs can hold userinfo passwords or@@ -725,6 +728,7 @@ class SafeSession(requests.Session):allow_private_ips: bool = False,block_link_local: bool = False,block_https_downgrade: bool = False,+ egress_context: Optional["EgressContext"] = None,):"""Initialize SafeSession.@@ -750,6 +754,8 @@ class SafeSession(requests.Session):including a downgrade after earlier redirect hops. HTTP-onlystarting URLs remain supported. HTTPS requests must verifytheir certificates when this is enabled.+ egress_context: Optional per-run policy enforced on each initial+ request, redirect hop, and pinned connect-time address."""super().__init__()self.max_redirects = _MAX_REDIRECTS@@ -757,6 +763,7 @@ class SafeSession(requests.Session):self.allow_private_ips = allow_private_ipsself.block_link_local = block_link_localself.block_https_downgrade = block_https_downgrade+ self.egress_context = egress_context# Per-thread, because one session is shared across search engines.self._redirect_local = threading.local()@@ -899,7 +906,7 @@ class SafeSession(requests.Session):def send(self, request: requests.PreparedRequest, **kwargs) -> requests.Response:- """Override send to validate every outgoing request against SSRF.+ """Validate every outgoing request against SSRF and run egress scope.This runs on **all** calls — both the initial request (routedhere by ``requests.Session.request()``) and each redirect hop@@ -936,6 +943,13 @@ class SafeSession(requests.Session):f"SSRF): {_redact(request.url)}")+ if request.url and self.egress_context is not None:+ from .egress.policy import PolicyDeniedError, evaluate_url++ decision = evaluate_url(request.url, self.egress_context)+ if not decision.allowed:+ raise PolicyDeniedError(decision, request.url)+# Pin the validated IP for the connection this send performs. send()# runs for the initial request AND for every redirect hop# (resolve_redirects re-enters here), so each hop is independently@@ -952,7 +966,53 @@ class SafeSession(requests.Session):allow_localhost=self.allow_localhost,allow_private_ips=self.allow_private_ips,block_link_local=self.block_link_local,- ):+ ) as pinned_addresses:+ if pinned_addresses and self.egress_context is not None:+ from .egress.policy import (+ Decision,+ PolicyDeniedError,+ evaluate_url,+ url_host_is_declared_local,+ )++ # The URL-level decision above honors an operator-declared+ # local hostname. Replacing that name with its pinned IP+ # would lose the declaration, so inspect only the+ # unconditional metadata block in that case. Otherwise+ # enforce the run scope on every address that can connect.+ declared_local = url_host_is_declared_local(+ request.url, self.egress_context+ )+ for address_info in pinned_addresses:+ address = str(address_info[4][0])+ if declared_local:+ if ssrf_validator.is_ip_blocked(+ address,+ allow_localhost=True,+ allow_private_ips=True,+ ):+ # The pinning layer normally rejects this+ # first. Audit without incrementing the run's+ # quota: this is one already-refused request,+ # not an additional user URL evaluation.+ logger.bind(policy_audit=True).warning(+ "policy denied URL fetch (pinned address) "+ f"pinned_address={address} "+ "reason=blocked_metadata_ip "+ f"scope={self.egress_context.scope.value} "+ "counted=False"+ )+ raise PolicyDeniedError(+ Decision(False, "blocked_metadata_ip"),+ request.url or "",+ )+ continue+ host = f"[{address}]" if ":" in address else address+ decision = evaluate_url(+ f"http://{host}/", self.egress_context+ )+ if not decision.allowed:+ raise PolicyDeniedError(decision, request.url or "")response = super().send(request, **kwargs)finally:self._redirect_local.preparing_next_only = preparingdiff --git a/src/local_deep_research/settings/env_definitions/security.py b/src/local_deep_research/settings/env_definitions/security.pyindex 6ec3a3d38a..7f23e831a6 100644--- a/src/local_deep_research/settings/env_definitions/security.py+++ b/src/local_deep_research/settings/env_definitions/security.py@@ -156,7 +156,9 @@ SECURITY_SETTINGS = ["docker-compose.yml. Link-local addresses (169.254.0.0/16, ""fe80::/10) and the cloud-metadata endpoints in ""ALWAYS_BLOCKED_METADATA_IPS stay blocked regardless of this "- "flag."+ "flag. Takes effect only under the unprotected egress scope: "+ "under every other scope, the default adaptive scope included, "+ "private result URLs stay blocked even with this flag set."),default=False,),diff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.pyindex c54bacae6a..cd5081a35e 100644--- a/src/local_deep_research/web_search_engines/engines/full_search.py+++ b/src/local_deep_research/web_search_engines/engines/full_search.py@@ -111,8 +111,10 @@ def make_fetch_progress_adapter(progress_callback):# those itself on every destination). Under any other scope the run policy# restricts destinations by address class (PUBLIC_ONLY: no private hosts;# PRIVATE_ONLY / STRICT: no public hosts; BOTH: classified hosts only),-# which the pipeline cannot check per redirect hop or browser subresource,-# so the private-fetch grant is withheld from it there. ADAPTIVE never+# so the operator's private-result grant is withheld there from both result+# URL validation and the pipeline. The pipeline now checks each redirect and+# pinned address against the run policy; browser fallback is disabled for+# restricted scopes because Chromium resolves its own DNS. ADAPTIVE never# reaches this module (resolved at context construction); an unknown scope# fails closed._SCOPES_WITHOUT_HOST_CLASS_RESTRICTION = frozenset({EgressScope.UNPROTECTED})@@ -150,9 +152,11 @@ class FullSearchResults:# ``search.allow_private_result_fetch`` opt-in). When True, SSRF# validation of result URLs may pass private/loopback IPs; the# default stays False so ungated/public engines never fetch internal- # URLs. The download pipeline receives the grant only when the run- # policy imposes no host-class restriction the pipeline could not- # enforce on later destinations (``_downloader_allow_private_ips``).+ # URLs. It applies (to that validation and to the download+ # pipeline) only when the run policy imposes no host-class+ # restriction,+ # i.e. without a run context or under ``unprotected``+ # (``_effective_allow_private_ips``).# Link-local and the cloud-metadata literals in# ALWAYS_BLOCKED_METADATA_IPS stay blocked regardless (issue #2477).self.allow_private_ips = allow_private_ips@@ -165,6 +169,10 @@ class FullSearchResults:# Set by the factory when the parent engine is gated against a# specific scope; used to evaluate per-URL fetches below.self.egress_context = egress_context+ # One operator-visible line per wrapper when the grant is set but+ # the run scope keeps it from applying+ # (``_effective_allow_private_ips``).+ self._grant_withheld_logged = Falsedef set_fetch_progress_callback(self, hook) -> None:"""Late-bind the ``(done, total)`` bulk-fetch hook.@@ -179,18 +187,22 @@ class FullSearchResults:"""Expose provider failures through the optional full-content wrapper."""return engine_failure(self.web_search)- def _downloader_allow_private_ips(self) -> bool:- """The private-fetch grant handed to the download pipeline.-- ``validate_url`` and ``evaluate_url`` in ``run`` /- ``_get_full_content`` only see the result URL. The pipeline applies- its address flags to every destination it actually reaches (redirect- hops, browser subresources) but has no hook for the run's egress- policy, so the grant is forwarded only when that policy restricts- nothing the flags cannot express: no run context at all, or a scope- in ``_SCOPES_WITHOUT_HOST_CLASS_RESTRICTION``. Otherwise the pipeline- runs with the strict default and a hop the policy would deny is- refused by its SSRF check instead of being fetched.+ def _effective_allow_private_ips(self) -> bool:+ """The private result-fetch grant as it applies to this run.++ Used for BOTH the SSRF validation of result URLs in ``run`` /+ ``_get_full_content`` and the download pipeline. The pipeline+ checks each redirect and pinned address against the run scope. The+ private-result grant remains limited to no run context at all,+ or a scope in ``_SCOPES_WITHOUT_HOST_CLASS_RESTRICTION``+ (``unprotected``). Under every other scope the grant is withheld+ from both, so a private result URL is refused by ``validate_url``+ exactly as if the operator had not set the opt-in. That refusal+ happens before ``evaluate_url`` runs, so it does not consume the+ run's ``MAX_DENIED_FETCHES_PER_RUN`` quota. Hosts the SSRF validator+ admits but the policy cannot classify public (including benchmark+ and documentation hosts) are refused uncounted by ``_refuse_private_uncounted`` instead, under+ the same scopes (every scope but ``unprotected``)."""if not self.allow_private_ips:return False@@ -200,13 +212,60 @@ class FullSearchResults:scope = getattr(egress_ctx, "scope", None)if scope in _SCOPES_WITHOUT_HOST_CLASS_RESTRICTION:return True- logger.debug(- "full_search: private result-fetch grant withheld from the "- "download pipeline, which cannot enforce the run's egress "- f"scope on redirect hops or browser subresources: {scope}"- )+ if not getattr(self, "_grant_withheld_logged", False):+ self._grant_withheld_logged = True+ scope_name = getattr(scope, "value", scope)+ logger.info(+ "full_search: private result-fetch grant "+ "(LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH) not applied under "+ f"egress scope {scope_name}; it takes effect only under the "+ "unprotected scope, so private result URLs stay blocked"+ )return False+ @staticmethod+ def _refuse_private_uncounted(url: str, egress_ctx: Any) -> bool:+ """Drop a result URL whose host the policy cannot classify public,+ uncounted, under every scope that withholds the private-fetch grant.++ Private result URLs stay blocked under every scope but+ ``unprotected`` (``_effective_allow_private_ips``). ``validate_url``+ refuses most of them, but its ``PRIVATE_IP_RANGES`` is narrower than+ the policy's classifier: it also admits benchmark, documentation and+ other special-purpose address ranges. ``evaluate_url`` counts+ denials under every scope, so a page of these URLs could exhaust+ the run's ``MAX_DENIED_FETCHES_PER_RUN`` quota and block later public+ fetches. It may admit private hosts under ``strict`` /+ ``private_only`` / ``both``. So they are refused+ here, before ``evaluate_url``, through the policy's own+ non-counting ``host_not_classified_public`` (same host+ classification as ``evaluate_url``), under every scope except the+ ones in ``_SCOPES_WITHOUT_HOST_CLASS_RESTRICTION``; an unknown scope+ fails closed. A URL with an empty host is refused too; an unresolvable+ host or a DNS timeout is classified public (the classifier's fail-safe)+ and is left to ``validate_url`` and ``evaluate_url``.+ This uncounted check covers the result URL. Static redirects and+ pinned connect addresses receive the transport's SSRF and run-scope+ checks. Browser fallback is disabled under restricted scopes; when+ available under Both or Unprotected, it retains SSRF checks.+ """+ scope = getattr(egress_ctx, "scope", None)+ if scope in _SCOPES_WITHOUT_HOST_CLASS_RESTRICTION:+ return False+ from ...security.egress.policy import host_not_classified_public++ if not host_not_classified_public(url, egress_ctx):+ return False+ scope_name = getattr(scope, "value", scope)+ logger.bind(policy_audit=True).warning(+ "full_search URL denied by egress policy (private result host, "+ "not counted toward the denied-fetch quota)",+ url=redact_url_for_log(url),+ scope=scope_name,+ reason=f"private_result_host_{scope_name}",+ )+ return True+def _url_quality_prompt(self, results: List[Dict], query: str) -> str:"""Build the URL-quality prompt shared by the sync and async paths."""now = datetime.now(UTC)@@ -368,6 +427,7 @@ class FullSearchResults:from ...security.egress.policy import evaluate_url as _ev_urlevaluate_url_fn = _ev_url+ allow_private = self._effective_allow_private_ips()safe_urls: List[str] = []for url in urls:if url is None:@@ -379,7 +439,7 @@ class FullSearchResults:# without the grant, where link-local is already blocked.if not validate_url(url,- allow_private_ips=self.allow_private_ips,+ allow_private_ips=allow_private,block_link_local=True,):logger.warning(@@ -387,6 +447,10 @@ class FullSearchResults:f"{redact_url_for_log(url)}.")continue+ if egress_ctx is not None and self._refuse_private_uncounted(+ url, egress_ctx+ ):+ continueif evaluate_url_fn is not None and egress_ctx is not None:url_decision = evaluate_url_fn(url, egress_ctx)if not url_decision.allowed:@@ -423,8 +487,9 @@ class FullSearchResults:enable_js_rendering=_read_js_rendering_setting(self.settings_snapshot),- allow_private_ips=self._downloader_allow_private_ips(),+ allow_private_ips=allow_private,block_link_local=True,+ egress_context=egress_ctx,progress_callback=self.progress_callback,)@@ -446,6 +511,7 @@ class FullSearchResults:from ...security.egress.policy import evaluate_url as _ev_urlevaluate_url_fn = _ev_url+ allow_private = self._effective_allow_private_ips()urls: List[str] = []for item in relevant_items:link = item.get("link")@@ -453,7 +519,7 @@ class FullSearchResults:continueif not validate_url(link,- allow_private_ips=self.allow_private_ips,+ allow_private_ips=allow_private,block_link_local=True,):logger.warning(@@ -461,6 +527,10 @@ class FullSearchResults:f"{redact_url_for_log(link)}.")continue+ if egress_ctx is not None and self._refuse_private_uncounted(+ link, egress_ctx+ ):+ continueif evaluate_url_fn is not None and egress_ctx is not None:url_decision = evaluate_url_fn(link, egress_ctx)if not url_decision.allowed:@@ -485,10 +555,13 @@ class FullSearchResults:enable_js_rendering=_read_js_rendering_setting(self.settings_snapshot),- allow_private_ips=self._downloader_allow_private_ips(),+ allow_private_ips=allow_private,block_link_local=True,+ egress_context=egress_ctx,progress_callback=self.progress_callback,)+ except PolicyDeniedError:+ raiseexcept Exception as e:safe_msg = scrub_error(e)logger.exception(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.pyindex db947b9a4e..94da82dc6c 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@@ -352,10 +352,15 @@ class SearXNGSearchEngine(BaseSearchEngine):# visible trace of it (the closed-gate and policy-denial# paths already log). The factory reads the attribute when# it builds that wrapper (issue #2477).+ # The wrapper applies the grant only under the unprotected+ # egress scope (see ``FullSearchResults.+ # _effective_allow_private_ips``).logger.info(- "SearXNG full-content fetches may reach private result "- "URLs (LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH) for "- f"instance: {redact_url_for_log(self.instance_url)}"+ "SearXNG private result-fetch grant "+ "(LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH) is set for "+ f"instance: {redact_url_for_log(self.instance_url)}; "+ "full-content fetches may reach private result URLs "+ "only under the unprotected egress scope")def _respect_rate_limit(self):diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex e5e396433b..dd10a9f5f7 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -197,7 +197,8 @@ class BaseSearchEngine(ABC):# an engine that holds such a grant resolves it itself in ``__init__``# (SearXNG: instance approval AND the env-only# ``search.allow_private_result_fetch`` opt-in); every other engine keeps- # private result URLs blocked (issue #2477).+ # private result URLs blocked (issue #2477). The wrapper applies the+ # grant only under the run's ``unprotected`` egress scope.allow_private_result_fetch = False# Class attribute to indicate if this is a news search enginediff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.pyindex e5dab2dc43..5f0faf8ae5 100644--- a/src/local_deep_research/web_search_engines/search_engine_factory.py+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py@@ -794,6 +794,7 @@ def create_search_engine(kwargs,username,settings_snapshot,+ egress_context=ctx,)return engine # type: ignore[no-any-return]@@ -821,6 +822,8 @@ def _create_full_search_wrapper(params: Dict[str, Any],username: str | None = None,settings_snapshot: Dict[str, Any] | None = None,+ *,+ egress_context: Any = None,) -> Optional[BaseSearchEngine]:"""Create a full search wrapper for the base engine if supported"""try:@@ -947,6 +950,19 @@ def _create_full_search_wrapper(if "web_search" in wrapper_init_params:wrapper_params["web_search"] = base_engine+ # The factory already validated this run and its primary engine+ # against ``ctx``. Reuse that exact context for result-URL fetches.+ # Without it FullSearchResults skips the per-URL egress scope gate,+ # so keep the snippets-only engine instead of creating a wrapper.+ if "egress_context" in wrapper_init_params:+ if egress_context is None:+ logger.bind(policy_audit=True).warning(+ "full-content wrapper skipped: no run egress context",+ engine=engine_name,+ )+ return base_engine+ wrapper_params["egress_context"] = egress_context+# Always pass settings_snapshot if the wrapper accepts it.# `params` is create_search_engine kwargs and never includes this# separate factory argument, so signature filtering drops it otherwise.@@ -958,7 +974,10 @@ def _create_full_search_wrapper(# unless the engine resolved a grant, e.g. SearXNG from the instance# approval AND the env-only opt-in), never from caller params, so a# stray kwarg cannot open it for an engine that holds no grant- # (issue #2477).+ # (issue #2477). The wrapper applies it only under the run's+ # ``unprotected`` scope (``FullSearchResults.+ # _effective_allow_private_ips``); under every other scope private+ # result URLs stay blocked.if "allow_private_ips" in wrapper_init_params:wrapper_params["allow_private_ips"] = (isinstance(base_engine, BaseSearchEngine)diff --git a/tests/research_library/downloaders/test_extraction_pipeline.py b/tests/research_library/downloaders/test_extraction_pipeline.pyindex 1b1869aea1..f64df9d871 100644--- a/tests/research_library/downloaders/test_extraction_pipeline.py+++ b/tests/research_library/downloaders/test_extraction_pipeline.py@@ -564,7 +564,7 @@ class TestTrySpecializedDownloader:monkeypatch.setattr(pipeline,"_try_specialized_downloader",- lambda url, timeout=30: _specialized(+ lambda url, timeout=30, **kwargs: _specialized(fallback_allowed=False, skip_reason=reason),)@@ -635,7 +635,7 @@ class TestFetchAndExtract:monkeypatch.setattr(pipeline,"_try_specialized_downloader",- lambda url, timeout=30: _specialized(+ lambda url, timeout=30, **kwargs: _specialized("Specialized content from academic source", False),)@@ -646,7 +646,7 @@ class TestFetchAndExtract:monkeypatch.setattr(pipeline,"_try_specialized_downloader",- lambda url, timeout=30: _specialized(),+ lambda url, timeout=30, **kwargs: _specialized(),)mock_downloader = Mock()@@ -666,7 +666,7 @@ class TestFetchAndExtract:monkeypatch.setattr(pipeline,"_try_specialized_downloader",- lambda url, timeout=30: _specialized(),+ lambda url, timeout=30, **kwargs: _specialized(),)mock_downloader = Mock()@@ -685,7 +685,7 @@ class TestFetchAndExtract:monkeypatch.setattr(pipeline,"_try_specialized_downloader",- lambda url, timeout=30: _specialized(),+ lambda url, timeout=30, **kwargs: _specialized(),)mock_downloader = Mock()@@ -705,7 +705,9 @@ class TestFetchAndExtract:monkeypatch.setattr(pipeline,"_try_specialized_downloader",- lambda url, timeout=30: _specialized(fallback_allowed=False),+ lambda url, timeout=30, **kwargs: _specialized(+ fallback_allowed=False+ ),)mock_class = Mock()monkeypatch.setattr(@@ -820,7 +822,7 @@ class TestFetchAndExtract:class TestBatchFetchAndExtract:def test_routes_specialized_and_generic(self, monkeypatch):- def mock_specialized(url, timeout=30):+ def mock_specialized(url, timeout=30, **kwargs):if "arxiv" in url:return _specialized("arXiv paper content", False)return _specialized()@@ -847,7 +849,7 @@ class TestBatchFetchAndExtract:monkeypatch.setattr(pipeline,"_try_specialized_downloader",- lambda url, timeout=30: _specialized(),+ lambda url, timeout=30, **kwargs: _specialized(),)call_count = [0]@@ -876,7 +878,7 @@ class TestBatchFetchAndExtract:monkeypatch.setattr(pipeline,"_try_specialized_downloader",- lambda url, timeout=30: _specialized(),+ lambda url, timeout=30, **kwargs: _specialized(),)results = pipeline.batch_fetch_and_extract([])assert results == {}@@ -1165,7 +1167,7 @@ class TestBatchFetchProgress:overwriting the result with the fallback."""- def mock_specialized(url, timeout=30):+ def mock_specialized(url, timeout=30, **kwargs):if "special" in url:return _specialized("good specialized content", False)return _specialized()@@ -1259,7 +1261,7 @@ class TestFetchAndExtractJSRenderingPlumbing:monkeypatch.setattr(pipeline,"_try_specialized_downloader",- lambda url, timeout=30: _specialized(),+ lambda url, timeout=30, **kwargs: _specialized(),)mock_downloader = Mock()mock_downloader.download.return_value = b"x"@@ -1398,7 +1400,7 @@ class TestFetchAndExtractPrivateIpPlumbing:monkeypatch.setattr(pipeline,"_try_specialized_downloader",- lambda url, timeout=30: _specialized(),+ lambda url, timeout=30, **kwargs: _specialized(),)mock_downloader = Mock()mock_downloader.download.return_value = b"x"diff --git a/tests/research_library/downloaders/test_playwright_html.py b/tests/research_library/downloaders/test_playwright_html.pyindex 74a680ff98..dbe58d9b3f 100644--- a/tests/research_library/downloaders/test_playwright_html.py+++ b/tests/research_library/downloaders/test_playwright_html.py@@ -121,7 +121,7 @@ class TestAutoDownloaderFallbackLogic:mock_response = Mock()mock_response.status_code = 403mock_response.text = spa_html- dl.session = Mock()+ dl.session = Mock(egress_context=None)dl.session.get.return_value = mock_responsemock_pw = Mock()@@ -198,7 +198,7 @@ class TestAutoDownloaderJSRenderingToggle:mock_response = Mock()mock_response.status_code = 403mock_response.text = spa_html- dl.session = Mock()+ dl.session = Mock(egress_context=None)dl.session.get.return_value = mock_responsewith patch.object(@@ -254,7 +254,7 @@ class TestAutoDownloaderJSRenderingToggle:mock_response = Mock()mock_response.status_code = 403mock_response.text = spa_html- dl.session = Mock()+ dl.session = Mock(egress_context=None)dl.session.get.return_value = mock_responsemock_pw = Mock()diff --git a/tests/security/test_egress_fullsearch.py b/tests/security/test_egress_fullsearch.pyindex 8a92473c4c..eda8f67921 100644--- a/tests/security/test_egress_fullsearch.py+++ b/tests/security/test_egress_fullsearch.py@@ -96,22 +96,22 @@ def _engine(results, ctx):)-def test_run_private_only_drops_public_keeps_private(patched_fetch):+def test_run_private_only_drops_public_and_private(patched_fetch):+ """PRIVATE_ONLY: the public URL is denied by ``evaluate_url`` (counted)+ and the private one is refused uncounted before it, because private+ result URLs stay blocked under every scope but ``unprotected`` even+ when the SSRF check admits them (forced True here)."""results = [{"title": "pub", "link": _PUBLIC_URL},{"title": "priv", "link": _PRIVATE_URL},]- engine = _engine(results, _make_ctx(EgressScope.PRIVATE_ONLY))+ ctx = _make_ctx(EgressScope.PRIVATE_ONLY)+ engine = _engine(results, ctx)out = engine.run("q")- # Only the private URL reached the fetcher.- assert patched_fetch["urls"] == [_PRIVATE_URL]- # And only its result carries full content; the denied public one is None.- by_link = {r["link"]: r for r in out}- assert (- by_link[_PRIVATE_URL]["full_content"] == "content-for-" + _PRIVATE_URL- )- assert by_link[_PUBLIC_URL]["full_content"] is None+ assert patched_fetch["calls"] == 0+ assert ctx._fetch_denial_count["count"] == 1+ assert all(r["full_content"] is None for r in out)def test_run_public_only_drops_private_keeps_public(patched_fetch):@@ -162,15 +162,13 @@ def test_get_full_content_gates_per_url(patched_fetch):{"title": "pub", "link": _PUBLIC_URL},{"title": "priv", "link": _PRIVATE_URL},]- engine = _engine(items, _make_ctx(EgressScope.PRIVATE_ONLY))+ engine = _engine(items, _make_ctx(EgressScope.PUBLIC_ONLY))out = engine._get_full_content(items)- assert patched_fetch["urls"] == [_PRIVATE_URL]+ assert patched_fetch["urls"] == [_PUBLIC_URL]by_link = {r["link"]: r for r in out}- assert (- by_link[_PRIVATE_URL]["full_content"] == "content-for-" + _PRIVATE_URL- )- assert by_link[_PUBLIC_URL]["full_content"] is None+ assert by_link[_PUBLIC_URL]["full_content"] == "content-for-" + _PUBLIC_URL+ assert by_link[_PRIVATE_URL]["full_content"] is Nonedef test_denied_url_audit_log_is_redacted(patched_fetch):@@ -305,11 +303,16 @@ def _granted_engine(results, ctx, settings_snapshot=None):def test_redirect_hop_denied_by_scope_is_never_fetched(transport, scope, entry, denied_hop):- """Grant on, run scope restricting hosts by class: the result URL passes- both gates, then redirects to a host the scope denies. The pipeline gets- the strict default, so the hop is refused by its per-hop SSRF check and- never reaches the transport (with the grant forwarded it would be- fetched, since the address flags alone admit it)."""+ """Grant on, run scope restricting hosts by class. Under public_only the+ public result URL passes both gates, then redirects to a private host+ the scope denies: the pipeline gets the strict default, so the hop is+ refused by its per-hop SSRF check and never reaches the transport (with+ the grant forwarded it would be fetched, since the address flags alone+ admit it). Under private_only / strict the grant is withheld from the+ result URL's own SSRF check too, so the private entry is refused before+ any request and the redirect is never reached; for those scopes the+ pipeline-grant rule is pinned by ``test_pipeline_grant_follows_run_scope``.+ """transport["responses"] = {entry: _redirect_to(denied_hop),denied_hop: _html_ok(_ARTICLE_HTML),@@ -403,12 +406,11 @@ def _recording_auto_downloader(children):def test_browser_subresource_denied_by_scope_is_never_fetched(transport, monkeypatch, guard):- """Grant on under ``public_only``, JS rendering on: the public result- page is an SPA shell, so the pipeline falls back to its browser child.- That child is built with the strict default, so a page subresource- aimed at a private host is aborted by both route guards before any- fetch (with the grant forwarded the address flags would admit it). No- browser is launched: the child's own fetch is stubbed out."""+ """Restricted full search keeps static fetches but never opens a browser.++ Even a directly called browser route guard refuses transport before its+ own SSRF checks, since native DNS cannot enforce the run scope.+ """children = []monkeypatch.setattr(pw, "AutoHTMLDownloader", _recording_auto_downloader(children)@@ -426,13 +428,14 @@ def test_browser_subresource_denied_by_scope_is_never_fetched(engine.run("q")assert transport["urls"] and set(transport["urls"]) == {_PUBLIC_URL}- assert len(children) == 1, "the browser fallback should have been built"- child = children[0]+ assert children == [], "restricted runs must keep the static path"+ child = pw.PlaywrightHTMLDownloader(block_link_local=True)+ child.session.egress_context = _make_ctx(EgressScope.PUBLIC_ONLY)assert child.allow_private_ips is Falseassert child.block_link_local is Trueroute = MagicMock()- route.request.url = "http://10.0.0.5/api/data"+ route.request.url = _PUBLIC_URLroute.request.method = "GET"route.request.resource_type = "xhr"if guard == "playwright":@@ -449,6 +452,7 @@ def test_browser_subresource_denied_by_scope_is_never_fetched(route.abort.assert_awaited_once_with("blockedbyclient")route.fulfill.assert_not_awaited()route.fetch.assert_not_called()+ child.close()@pytest.mark.parametrize(@@ -457,16 +461,12 @@ def test_browser_subresource_denied_by_scope_is_never_fetched((None, _PRIVATE_URL, True),(EgressScope.UNPROTECTED, _PRIVATE_URL, True),(EgressScope.PUBLIC_ONLY, _PUBLIC_URL, False),- (EgressScope.PRIVATE_ONLY, _PRIVATE_URL, False),- (EgressScope.STRICT, _PRIVATE_URL, False),- (EgressScope.BOTH, _PRIVATE_URL, False),+ (EgressScope.BOTH, _PUBLIC_URL, False),],ids=["no_context","unprotected","public_only",- "private_only",- "strict","both",],)@@ -479,7 +479,10 @@ def test_pipeline_grant_follows_run_scope(restricts hosts by class, and the internal ``both`` fallback, gets thestrict default. ``block_link_local`` stays on either way. The resultURL is one the scope admits, so the real ``evaluate_url`` lets it- through to the pipeline call."""+ through to the pipeline call. Under ``private_only`` / ``strict`` no+ result URL reaches the pipeline at all (public ones are denied by+ ``evaluate_url``, private ones refused before it), which+ ``test_strict_and_private_only_fetch_no_result_url`` pins."""seen = {}def fake_batch(urls, **kwargs):@@ -530,3 +533,419 @@ def test_pipeline_grant_off_stays_off_under_unprotected(monkeypatch):assert seen["allow_private_ips"] is Falseassert seen["block_link_local"] is True+++# ===========================================================================+# Grant withheld under protected scopes: refused before evaluate_url, so it+# never spends the run's denied-fetch quota (#6535 follow-up)+# ===========================================================================+++ "scope,expected",+ [+ (None, True),+ (EgressScope.UNPROTECTED, True),+ (EgressScope.PUBLIC_ONLY, False),+ (EgressScope.PRIVATE_ONLY, False),+ (EgressScope.STRICT, False),+ (EgressScope.BOTH, False),+ ],+ ids=[+ "no_context",+ "unprotected",+ "public_only",+ "private_only",+ "strict",+ "both",+ ],+)[email protected]("method", ["run", "_get_full_content"])+def test_ssrf_validation_grant_follows_run_scope(+ monkeypatch, scope, expected, method+):+ """The SSRF validation of result URLs gets the same effective grant as+ the pipeline: on only with no run context or under ``unprotected``."""+ seen = []++ def fake_validate(u, allow_private_ips=False, block_link_local=False):+ seen.append((allow_private_ips, block_link_local))+ return False++ monkeypatch.setattr(fs, "validate_url", fake_validate)+ monkeypatch.setattr(+ fs, "batch_fetch_and_extract", MagicMock(return_value={})+ )+ ctx = None if scope is None else _make_ctx(scope)+ items = [{"title": "r", "link": _PRIVATE_URL}]+ engine = _granted_engine(items, ctx)++ if method == "run":+ engine.run("q")+ else:+ engine._get_full_content(items)++ assert seen == [(expected, True)]++[email protected]("method", ["run", "_get_full_content"])+def test_private_results_under_public_only_do_not_spend_denial_quota(+ monkeypatch, method+):+ """Default ADAPTIVE resolves SearXNG to PUBLIC_ONLY. With the grant set,+ private result URLs must be refused by the SSRF check (uncounted), not+ by ``evaluate_url`` (counted): otherwise MAX_DENIED_FETCHES_PER_RUN+ private results exhaust the quota and the public result in the same+ batch is then denied with ``denial_quota_exceeded``. Real+ ``validate_url`` and ``evaluate_url`` on IP literals, no DNS."""+ from local_deep_research.security.egress.policy import (+ MAX_DENIED_FETCHES_PER_RUN,+ )++ fetched = {}++ def fake_batch(urls, **kwargs):+ fetched["urls"] = list(urls)+ fetched["allow_private_ips"] = kwargs["allow_private_ips"]+ return {u: "content" for u in urls}++ monkeypatch.setattr(fs, "batch_fetch_and_extract", fake_batch)+ ctx = _make_ctx(EgressScope.PUBLIC_ONLY)+ items = [+ {"title": f"p{i}", "link": f"http://10.0.{i // 250}.{i % 250 + 1}/"}+ for i in range(MAX_DENIED_FETCHES_PER_RUN + 5)+ ]+ items.append({"title": "pub", "link": _PUBLIC_URL})+ engine = _granted_engine(items, ctx)++ if method == "run":+ out = engine.run("q")+ else:+ out = engine._get_full_content(items)++ assert ctx._fetch_denial_count["count"] == 0+ assert fetched["urls"] == [_PUBLIC_URL]+ assert fetched["allow_private_ips"] is False+ by_link = {r["link"]: r["full_content"] for r in out}+ assert by_link[_PUBLIC_URL] == "content"+ assert all(v is None for k, v in by_link.items() if k != _PUBLIC_URL)+++def test_grant_withheld_is_logged_once_per_wrapper(monkeypatch):+ """Operators who set the flag see why it does not apply: one INFO line+ naming the scope per wrapper, not one per URL or per search."""+ monkeypatch.setattr(+ fs, "batch_fetch_and_extract", MagicMock(return_value={})+ )+ messages = []+ logger.enable("local_deep_research")+ sink_id = logger.add(+ lambda m: messages.append(m.record["message"]), level="INFO"+ )+ try:+ engine = _granted_engine(+ [{"title": "r", "link": _PRIVATE_URL}],+ _make_ctx(EgressScope.PUBLIC_ONLY),+ )+ engine.run("q")+ engine.run("q")+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")++ withheld = [m for m in messages if "not applied under egress scope" in m]+ assert len(withheld) == 1+ assert "public_only" in withheld[0]+ assert "LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH" in withheld[0]+++# ===========================================================================+# Private hosts the SSRF validator admits but the policy classifies private+# are refused uncounted too, under every scope but ``unprotected``: the+# wrapper asks the policy's own classifier (``host_not_classified_public``),+# not a second, narrower list+# ===========================================================================++# Each host passes ``validate_url`` with the grant withheld (the SSRF+# validator's PRIVATE_IP_RANGES does not list it) yet ``_classify_host``+# (``ipaddress.is_private``) classifies it private, so under ``public_only``+# ``evaluate_url`` refuses it as ``scope_mismatch_public_only`` and counts+# it, and under ``strict`` / ``private_only`` / ``both`` ``evaluate_url``+# ADMITS it.+_SSRF_ADMITTED_POLICY_PRIVATE_HOSTS = [+ "198.18.0.7", # benchmarking range; fake-ip DNS (Clash, sing-box)+ "192.0.2.10", # TEST-NET-1+ "198.51.100.7", # TEST-NET-2+ "203.0.113.5", # TEST-NET-3+ "192.0.0.170", # IETF protocol assignments+ "240.0.0.1", # reserved+ "[2001:db8::1]", # IPv6 documentation+]+++def _run_quota_batch(monkeypatch, method, links, scope=EgressScope.PUBLIC_ONLY):+ """Real ``validate_url`` and ``evaluate_url`` under ``scope`` (default+ ``public_only``), grant withheld; returns (ctx, fetched, by_link)."""+ from local_deep_research.security.egress.policy import (+ MAX_DENIED_FETCHES_PER_RUN,+ )++ fetched = {}++ def fake_batch(urls, **kwargs):+ fetched["urls"] = list(urls)+ return {u: "content" for u in urls}++ monkeypatch.setattr(fs, "batch_fetch_and_extract", fake_batch)+ ctx = _make_ctx(scope)+ items = [+ {"title": f"p{i}", "link": links[i % len(links)] + f"p{i}"}+ for i in range(MAX_DENIED_FETCHES_PER_RUN + 5)+ ]+ items.append({"title": "pub", "link": _PUBLIC_URL})+ engine = _granted_engine(items, ctx)+ if method == "run":+ out = engine.run("q")+ else:+ out = engine._get_full_content(items)+ return ctx, fetched, {r["link"]: r["full_content"] for r in out}++[email protected]("host", _SSRF_ADMITTED_POLICY_PRIVATE_HOSTS)[email protected]("method", ["run", "_get_full_content"])+def test_ssrf_admitted_private_results_do_not_spend_denial_quota(+ monkeypatch, host, method+):+ ctx, fetched, by_link = _run_quota_batch(+ monkeypatch, method, [f"http://{host}/"]+ )++ assert ctx._fetch_denial_count["count"] == 0+ assert fetched["urls"] == [_PUBLIC_URL]+ assert by_link[_PUBLIC_URL] == "content"+ assert all(v is None for k, v in by_link.items() if k != _PUBLIC_URL)++[email protected]("method", ["run", "_get_full_content"])+def test_nat64_local_use_results_do_not_spend_denial_quota(monkeypatch, method):+ """With ``LDR_SECURITY_ALLOW_NAT64`` set, a 64:ff9b:1::/48 (RFC 8215)+ wrap of a public IPv4 passes the SSRF validator but classifies private."""+ import ipaddress++ # Python's ``ipaddress`` lists 64:ff9b:1::/48 as private only in newer+ # releases (3.12.4+, 3.13+); where it does not, the policy classifies+ # the address public and there is nothing private to refuse.+ if not ipaddress.ip_address("64:ff9b:1::1").is_private:+ pytest.skip(+ "this Python's ipaddress does not treat 64:ff9b:1::/48 as private"+ )+ monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")+ # 93.184.216.34 embedded at the RFC 6052 /48 byte positions.+ nat64 = "http://[64:ff9b:1:5db8:d8:2200::]/"+ assert fs.validate_url(+ nat64, allow_private_ips=False, block_link_local=True+ )++ ctx, fetched, _ = _run_quota_batch(monkeypatch, method, [nat64])++ assert ctx._fetch_denial_count["count"] == 0+ assert fetched["urls"] == [_PUBLIC_URL]+++def _patch_fake_ip_dns(monkeypatch):+ """Answer every ``*.fakeip.test`` name inside 198.18.0.0/15, as a+ fake-IP resolver (Clash, sing-box, Surge TUN) does for public names."""+ import socket++ real_getaddrinfo = socket.getaddrinfo++ def fake_getaddrinfo(host, *args, **kwargs):+ if isinstance(host, str) and host.endswith(".fakeip.test"):+ return [+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("198.18.3.4", 0))+ ]+ return real_getaddrinfo(host, *args, **kwargs)++ monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo)++[email protected]("method", ["run", "_get_full_content"])+def test_fake_ip_dns_results_do_not_spend_denial_quota(monkeypatch, method):+ """Hostnames that resolve into 198.18.0.0/15 (a fake-ip resolver, or a+ hostile A record) pass the SSRF validator's DNS check and classify+ private through the policy's own DNS path: refused, uncounted."""+ _patch_fake_ip_dns(monkeypatch)++ ctx, fetched, _ = _run_quota_batch(+ monkeypatch,+ method,+ [f"http://h{i}.fakeip.test/" for i in range(3)],+ )++ assert ctx._fetch_denial_count["count"] == 0+ assert fetched["urls"] == [_PUBLIC_URL]+++_SCOPES_ADMITTING_POLICY_PRIVATE_HOSTS = [+ EgressScope.STRICT,+ EgressScope.PRIVATE_ONLY,+ EgressScope.BOTH,+]+++def _fetch_one(monkeypatch, method, link, ctx, grant=True):+ """Run the wrapper on one result URL with the REAL ``validate_url``+ and ``evaluate_url``; returns the URLs handed to the pipeline (None+ when it was never called)."""+ fetched = {"urls": None}++ def fake_batch(urls, **kwargs):+ fetched["urls"] = list(urls)+ return {u: "content" for u in urls}++ monkeypatch.setattr(fs, "batch_fetch_and_extract", fake_batch)+ items = [{"title": "r", "link": link}]+ engine = fs.FullSearchResults(+ llm=None,+ web_search=_FakeWebSearch(items),+ egress_context=ctx,+ allow_private_ips=grant,+ )+ if method == "run":+ engine.run("q")+ else:+ engine._get_full_content(items)+ return fetched["urls"]++[email protected]("grant", [True, False], ids=["grant", "no_grant"])+ "scope", _SCOPES_ADMITTING_POLICY_PRIVATE_HOSTS, ids=lambda s: s.value+)[email protected]("host", _SSRF_ADMITTED_POLICY_PRIVATE_HOSTS)[email protected]("method", ["run", "_get_full_content"])+def test_ssrf_admitted_private_results_stay_blocked_under_protected_scopes(+ monkeypatch, host, scope, grant, method+):+ """``evaluate_url`` ADMITS these policy-private hosts under ``strict``+ / ``private_only`` / ``both``, and the SSRF check admits them too, so+ without the wrapper's own refusal they would be fetched although+ private result URLs stay blocked under every scope but ``unprotected``.+ Refused before ``evaluate_url``, uncounted, with or without the+ (withheld) grant."""+ ctx = _make_ctx(scope)+ link = f"http://{host}/page"+ assert fs.validate_url(link, allow_private_ips=False, block_link_local=True)++ fetched = _fetch_one(monkeypatch, method, link, ctx, grant=grant)++ assert fetched is None+ assert ctx._fetch_denial_count["count"] == 0++[email protected]("method", ["run", "_get_full_content"])+def test_fake_ip_public_hosts_are_not_fetched_under_strict(monkeypatch, method):+ """Under fake-IP DNS a public name resolves into 198.18.0.0/15 and the+ policy classifies it private, so ``evaluate_url`` would ADMIT it under+ ``strict``. The wrapper refuses it (uncounted) instead of fetching the+ public page."""+ _patch_fake_ip_dns(monkeypatch)+ ctx = _make_ctx(EgressScope.STRICT)++ fetched = _fetch_one(monkeypatch, method, "http://news.fakeip.test/a", ctx)++ assert fetched is None+ assert ctx._fetch_denial_count["count"] == 0+++ "scope",+ [EgressScope.STRICT, EgressScope.PRIVATE_ONLY],+ ids=lambda s: s.value,+)[email protected]("method", ["run", "_get_full_content"])+def test_strict_and_private_only_fetch_no_result_url(+ monkeypatch, scope, method+):+ """Under ``strict`` and ``private_only`` the wrapper fetches no result+ URL at all, grant or not: public ones are denied by ``evaluate_url``+ (counted), RFC 1918 ones by the SSRF check and the remaining+ policy-private ones by the wrapper's classifier check (uncounted)."""+ ctx = _make_ctx(scope)+ for link in (_PUBLIC_URL, _PRIVATE_URL, "http://198.18.0.7/"):+ assert _fetch_one(monkeypatch, method, link, ctx) is None+ assert ctx._fetch_denial_count["count"] == 1++[email protected]("method", ["run", "_get_full_content"])+def test_unprotected_without_grant_fetches_ssrf_admitted_ranges(+ monkeypatch, method+):+ """The documented exception: ``unprotected`` lifts the scope's host+ restriction, so without the grant only the SSRF check stands, and it+ admits 198.18.0.0/15 and the other ranges listed above. Pinned so the+ docs that name this exception stay true."""+ link = "http://198.18.0.7/page"++ fetched = _fetch_one(+ monkeypatch,+ method,+ link,+ _make_ctx(EgressScope.UNPROTECTED),+ grant=False,+ )++ assert fetched == [link]+++_CLASSIFIER_PARITY_URLS = [+ _PUBLIC_URL,+ _PRIVATE_URL,+ "http://127.0.0.1/",+ "http://169.254.169.254/latest/meta-data/",+ "http://169.254.10.10/",+ "http://0251.0376.0251.0376/",+ "http://198.18.0.7/",+ "http://192.0.2.10/",+ "http://240.0.0.1/",+ "http://[2001:db8::1]/",+ "http://[::1]/",+ "http://[fd00::1]/",+ "http://10%2e0%2e0%2e1/",+ "http://10.0.0.1./",+ "http://localwiki/",+ "ftp://10.0.0.1/",+ "javascript:alert(1)",+ "http:///nohost",+ "",+]++[email protected]("scope", list(EgressScope))+def test_host_not_classified_public_matches_evaluate_url(scope):+ """The class property: ``host_not_classified_public`` is True exactly+ when ``evaluate_url`` under ``public_only`` denies with+ ``scope_mismatch_public_only``, whatever the probing context's scope,+ and it never records a denial. ``localwiki`` is a declared local+ hostname (no DNS); IP literals need none either."""+ from local_deep_research.security.egress.policy import (+ evaluate_url,+ host_not_classified_public,+ )++ def ctx(s):+ return EgressContext(+ scope=s,+ primary_engine="library",+ require_local_llm=False,+ require_local_embeddings=False,+ local_hostnames=("localwiki",),+ )++ for url in _CLASSIFIER_PARITY_URLS:+ probe = ctx(scope)+ refused = host_not_classified_public(url, probe)+ assert probe._fetch_denial_count["count"] == 0, url+ decision = evaluate_url(url, ctx(EgressScope.PUBLIC_ONLY))+ expected = decision.reason == "scope_mismatch_public_only"+ assert refused is expected, (url, decision.reason)diff --git a/tests/security/test_egress_transport_scope_v2.py b/tests/security/test_egress_transport_scope_v2.pynew file mode 100644index 0000000000..b0203ab3a7--- /dev/null+++ b/tests/security/test_egress_transport_scope_v2.py@@ -0,0 +1,481 @@+"""Run egress policy must hold at redirects, pinned IPs, and browser fallback."""++from contextlib import contextmanager, nullcontext+from unittest.mock import MagicMock, patch++import pytest+import requests++from local_deep_research.content_fetcher import ContentFetcher+from local_deep_research.content_fetcher.url_classifier import URLType+from local_deep_research.research_library.downloaders.playwright_html import (+ AutoHTMLDownloader,+ HTMLDownloader,+ PlaywrightHTMLDownloader,+)+from local_deep_research.research_library.downloaders.pubmed import (+ PubMedDownloader,+)+from local_deep_research.research_library.downloaders.base import DownloadResult+from local_deep_research.research_library.downloaders.extraction import (+ pipeline,+)+from local_deep_research.security.egress.policy import (+ Decision,+ EgressContext,+ EgressScope,+ PolicyDeniedError,+)+from local_deep_research.security.safe_requests import SafeSession+from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+)+++def _context(scope: EgressScope) -> EgressContext:+ return EgressContext(+ scope=scope,+ primary_engine="library",+ require_local_llm=False,+ require_local_embeddings=False,+ )+++ ("source_scheme", "target", "error"),+ [+ ("https", "https://10.0.0.2/next", None),+ ("https", "http://10.0.0.2/next", ValueError),+ ("https", "https://8.8.8.8/next", PolicyDeniedError),+ ("http", "http://10.0.0.2/next", None),+ ],+)+def test_redirect_preserves_both_https_and_run_scope_guards(+ source_scheme, target, error+):+ source = f"{source_scheme}://10.0.0.2/start"+ sent = []++ def transport_send(request, **kwargs):+ sent.append(request.url)+ response = requests.Response()+ response.request = request+ response.url = request.url+ response._content = b""+ response.status_code = 302 if request.url == source else 200+ if response.status_code == 302:+ response.headers["Location"] = target+ return response++ with SafeSession(+ allow_private_ips=True,+ block_https_downgrade=True,+ egress_context=_context(EgressScope.PRIVATE_ONLY),+ ) as session:+ with (+ patch(+ "requests.adapters.HTTPAdapter.send",+ side_effect=transport_send,+ ),+ pytest.raises(error) if error else nullcontext(),+ ):+ response = session.get(source)+ assert response.status_code == 200+ assert sent == ([source] if error else [source, target])++[email protected]("verify", [False, None])+def test_positional_https_guard_still_refuses_unverified_scoped_send(verify):+ # The fourth positional option already belongs to the HTTPS guard on main.+ with SafeSession(+ False,+ True,+ False,+ True,+ egress_context=_context(EgressScope.PRIVATE_ONLY),+ ) as session:+ request = requests.Request("GET", "https://10.0.0.2/").prepare()+ with (+ patch("requests.adapters.HTTPAdapter.send") as transport,+ pytest.raises(ValueError, match="verify=False"),+ ):+ session.send(request, verify=verify)+ transport.assert_not_called()+++def test_private_only_session_refuses_public_redirect_hop_before_transport():+ session = SafeSession(allow_private_ips=True)+ session.egress_context = _context(EgressScope.PRIVATE_ONLY)+ request = requests.Request("GET", "http://8.8.8.8/").prepare()++ with patch("requests.sessions.Session.send") as transport:+ with pytest.raises(PolicyDeniedError):+ session.send(request)+ transport.assert_not_called()+++def test_private_only_redirect_is_stopped_before_second_transport():+ session = SafeSession(allow_private_ips=True)+ session.egress_context = _context(EgressScope.PRIVATE_ONLY)+ source = "http://10.0.0.2/start"+ redirect = requests.Response()+ redirect.status_code = 302+ redirect.headers["Location"] = "http://8.8.8.8/next"+ redirect.url = source+ redirect._content = b""++ def transport_send(request, **kwargs):+ redirect.request = request+ return redirect++ with (+ patch(+ "requests.adapters.HTTPAdapter.send", side_effect=transport_send+ ) as transport,+ pytest.raises(PolicyDeniedError),+ ):+ session.get(source)+ transport.assert_called_once()+++def test_public_only_session_refuses_private_pinned_address():+ session = SafeSession(allow_private_ips=True)+ session.egress_context = _context(EgressScope.PUBLIC_ONLY)+ request = requests.Request("GET", "http://public.example/").prepare()++ @contextmanager+ def pinned_private_answer(*args, **kwargs):+ yield [(None, None, None, None, ("10.0.0.3", 80))]++ with (+ patch(+ "local_deep_research.security.ssrf_validator.validate_url",+ return_value=True,+ ),+ patch(+ "local_deep_research.security.dns_pinning.pinned_request",+ side_effect=pinned_private_answer,+ ),+ patch(+ "local_deep_research.security.egress.policy._resolve_with_timeout",+ return_value=[(None, None, None, None, ("8.8.8.8", 80))],+ ),+ patch("requests.sessions.Session.send") as transport,+ pytest.raises(PolicyDeniedError),+ ):+ session.send(request)+ transport.assert_not_called()+++def test_private_only_session_refuses_public_pinned_address():+ session = SafeSession(allow_private_ips=True)+ session.egress_context = _context(EgressScope.PRIVATE_ONLY)+ request = requests.Request("GET", "http://local.example/").prepare()++ @contextmanager+ def pinned_public_answer(*args, **kwargs):+ yield [(None, None, None, None, ("8.8.8.8", 80))]++ with (+ patch(+ "local_deep_research.security.ssrf_validator.validate_url",+ return_value=True,+ ),+ patch(+ "local_deep_research.security.egress.policy._resolve_with_timeout",+ side_effect=lambda host: [+ (+ None,+ None,+ None,+ None,+ ("10.0.0.3" if host == "local.example" else "8.8.8.8", 80),+ )+ ],+ ),+ patch(+ "local_deep_research.security.dns_pinning.pinned_request",+ side_effect=pinned_public_answer,+ ),+ patch("requests.sessions.Session.send") as transport,+ pytest.raises(PolicyDeniedError),+ ):+ session.send(request)+ transport.assert_not_called()+++def test_declared_local_host_preserves_operator_classification_at_pin():+ session = SafeSession(allow_private_ips=True)+ session.egress_context = EgressContext(+ scope=EgressScope.PRIVATE_ONLY,+ primary_engine="library",+ require_local_llm=False,+ require_local_embeddings=False,+ local_hostnames=("declared.example",),+ )+ request = requests.Request("GET", "http://declared.example/").prepare()++ @contextmanager+ def pinned_public_answer(*args, **kwargs):+ yield [(None, None, None, None, ("8.8.8.8", 80))]++ response = requests.Response()+ response.status_code = 200+ response.headers["Content-Length"] = "2"+ response._content = b"ok"+ with (+ patch(+ "local_deep_research.security.ssrf_validator.validate_url",+ return_value=True,+ ),+ patch(+ "local_deep_research.security.dns_pinning.pinned_request",+ side_effect=pinned_public_answer,+ ),+ patch(+ "requests.sessions.Session.send", return_value=response+ ) as transport,+ ):+ assert session.send(request) is response+ transport.assert_called_once()+++def test_declared_local_host_still_refuses_metadata_pinned_address():+ session = SafeSession(allow_private_ips=True)+ session.egress_context = EgressContext(+ scope=EgressScope.PRIVATE_ONLY,+ primary_engine="library",+ require_local_llm=False,+ require_local_embeddings=False,+ local_hostnames=("declared.example",),+ )+ request = requests.Request("GET", "http://declared.example/").prepare()++ @contextmanager+ def pinned_metadata_answer(*args, **kwargs):+ yield [(None, None, None, None, ("169.254.169.254", 80))]++ with (+ patch(+ "local_deep_research.security.ssrf_validator.validate_url",+ return_value=True,+ ),+ patch(+ "local_deep_research.security.dns_pinning.pinned_request",+ side_effect=pinned_metadata_answer,+ ),+ patch("requests.sessions.Session.send") as transport,+ pytest.raises(PolicyDeniedError) as denied,+ ):+ session.send(request)+ assert denied.value.decision.reason == "blocked_metadata_ip"+ assert session.egress_context._fetch_denial_count["count"] == 0+ transport.assert_not_called()+++def test_content_fetcher_attaches_run_context_to_downloader_session():+ ctx = _context(EgressScope.PRIVATE_ONLY)+ fetcher = ContentFetcher(egress_context=ctx)+ downloader = fetcher._get_downloader(URLType.HTML)+ try:+ assert downloader.session.egress_context is ctx+ finally:+ downloader.close()+++ ("scope", "expected"),+ [+ (EgressScope.PRIVATE_ONLY, b"static"),+ (EgressScope.PUBLIC_ONLY, b"static"),+ (EgressScope.STRICT, b"static"),+ (EgressScope.BOTH, b"rendered"),+ ],+)+def test_browser_fallback_respects_run_scope(scope, expected):+ downloader = AutoHTMLDownloader(enable_js_rendering=True)+ downloader.session.egress_context = _context(scope)+ browser = MagicMock()+ browser.download.return_value = b"rendered"++ try:+ with (+ patch.object(HTMLDownloader, "download", return_value=b"static"),+ patch.object(+ downloader, "_get_playwright_downloader", return_value=browser+ ) as make_browser,+ ):+ result = downloader.download("http://example.test/")+ assert result == expected+ if expected == b"static":+ make_browser.assert_not_called()+ else:+ make_browser.assert_called_once()+ finally:+ downloader.close()+++def test_direct_browser_fetch_refuses_restricted_context():+ downloader = PlaywrightHTMLDownloader()+ downloader.session.egress_context = _context(EgressScope.PRIVATE_ONLY)+ try:+ with (+ patch.object(+ downloader, "_fetch_with_crawl4ai", return_value="rendered"+ ) as browser,+ pytest.raises(PolicyDeniedError),+ ):+ downloader._fetch_html("http://example.test/")+ browser.assert_not_called()+ finally:+ downloader.close()++[email protected]("method", ["download", "download_with_result"])+def test_static_policy_denial_does_not_retry_or_launch_browser(method):+ downloader = AutoHTMLDownloader(enable_js_rendering=True)+ downloader.session.egress_context = _context(EgressScope.PRIVATE_ONLY)+ denial = PolicyDeniedError(Decision(False, "scope_mismatch_private_only"))+ try:+ with (+ patch.object(downloader.session, "get", side_effect=denial) as get,+ patch.object(downloader, "_get_playwright_downloader") as browser,+ pytest.raises(PolicyDeniedError),+ ):+ getattr(downloader, method)("http://private.example/")+ get.assert_called_once()+ browser.assert_not_called()+ finally:+ downloader.close()+++def test_pdf_policy_denial_stops_retries():+ downloader = HTMLDownloader()+ denial = PolicyDeniedError(Decision(False, "scope_mismatch_public_only"))+ try:+ with (+ patch.object(downloader.session, "get", side_effect=denial) as get,+ patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ ),+ pytest.raises(PolicyDeniedError),+ ):+ downloader._download_pdf("http://private.example/paper.pdf")+ get.assert_called_once()+ finally:+ downloader.close()+++def test_pubmed_denial_does_not_try_scraping_fallback():+ downloader = PubMedDownloader()+ denial = PolicyDeniedError(Decision(False, "scope_mismatch_private_only"))+ try:+ with (+ patch.object(downloader.session, "get", side_effect=denial) as get,+ pytest.raises(PolicyDeniedError),+ ):+ downloader._get_pmc_id_from_pmid("12345")+ get.assert_called_once()+ finally:+ downloader.close()+++def test_generic_pipeline_passes_context_and_propagates_denial():+ ctx = _context(EgressScope.PRIVATE_ONLY)+ denial = PolicyDeniedError(Decision(False, "scope_mismatch_private_only"))+ seen = []++ def denied_download(downloader, url, content_type=None):+ seen.append(downloader.session.egress_context)+ raise denial++ with (+ patch.object(+ pipeline,+ "_try_specialized_downloader",+ return_value=pipeline._SpecializedResult(),+ ),+ patch.object(AutoHTMLDownloader, "download", new=denied_download),+ pytest.raises(PolicyDeniedError),+ ):+ pipeline.fetch_and_extract(+ "http://private.example/", egress_context=ctx+ )+ assert seen == [ctx]+++def test_specialized_pipeline_passes_context_to_api_transport():+ ctx = _context(EgressScope.PRIVATE_ONLY)+ seen = []++ def capture_download(downloader, url, content_type):+ seen.append(downloader.session.egress_context)+ return DownloadResult(content=b"x" * 60, is_success=True)++ with patch.object(+ PubMedDownloader, "download_with_result", new=capture_download+ ):+ result = pipeline.fetch_and_extract(+ "https://pubmed.ncbi.nlm.nih.gov/12345/", egress_context=ctx+ )+ assert result == "x" * 60+ assert seen == [ctx]+++def test_batch_contains_denial_without_falling_back_for_that_url():+ denied_url = "http://denied.example/"+ allowed_url = "http://allowed.example/"+ denial = PolicyDeniedError(Decision(False, "scope_mismatch_private_only"))++ ctx = _context(EgressScope.PRIVATE_ONLY)+ contexts = []+ progress = []++ def specialize(url, **kwargs):+ contexts.append(kwargs["egress_context"])+ if url == denied_url:+ raise denial+ return pipeline._SpecializedResult()++ with (+ patch.object(+ pipeline, "_try_specialized_downloader", side_effect=specialize+ ),+ patch.object(+ AutoHTMLDownloader, "download", return_value=b"allowed"+ ) as fetch,+ ):+ result = pipeline.batch_fetch_and_extract(+ [denied_url, allowed_url],+ egress_context=ctx,+ progress_callback=lambda done, total: progress.append(+ (done, total)+ ),+ )+ assert result == {denied_url: None, allowed_url: "allowed"}+ fetch.assert_called_once_with(allowed_url)++ assert contexts == [ctx, ctx]+ assert progress == [(0, 2), (1, 2), (2, 2)]+++ ("scope", "allowed"),+ [+ (EgressScope.PRIVATE_ONLY, False),+ (EgressScope.PUBLIC_ONLY, False),+ (EgressScope.STRICT, False),+ (EgressScope.BOTH, False),+ (EgressScope.UNPROTECTED, True),+ ],+)+def test_full_search_private_grant_only_reaches_unrestricted_scopes(+ scope, allowed+):+ wrapper = FullSearchResults(+ llm=None,+ web_search=MagicMock(),+ allow_private_ips=True,+ egress_context=_context(scope),+ )+ assert wrapper._effective_allow_private_ips() is alloweddiff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex da17fd6f51..a0cf553b9f 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -9774,7 +9774,7 @@},"web.enable_javascript_rendering": {"category": null,- "description": "When enabled, falls back to a headless browser (Crawl4AI/Playwright) for pages that need JavaScript to render. Requires Chromium to be installed - the default Docker production image does NOT include it. To enable: install Chromium in the runtime environment (e.g. 'playwright install --with-deps chromium'), then toggle this setting. Note: in our limited (mostly accidental) benchmark comparisons - between dev instances that happened to have Chromium installed and routine Docker runs that did not - JS rendering did not measurably improve research quality, and most of our regular benchmark runs are on Docker without Chromium anyway. Leave disabled unless you have a specific need to scrape JavaScript-only sites.",+ "description": "When enabled, falls back to a headless browser (Crawl4AI/Playwright) for pages that need JavaScript to render. Requires Chromium to be installed - the default Docker production image does NOT include it. To enable: install Chromium in the runtime environment (e.g. 'playwright install --with-deps chromium'), then toggle this setting. Note: in our limited (mostly accidental) benchmark comparisons - between dev instances that happened to have Chromium installed and routine Docker runs that did not - JS rendering did not measurably improve research quality, and most of our regular benchmark runs are on Docker without Chromium anyway. Leave disabled unless you have a specific need to scrape JavaScript-only sites. Runs with Public only, Private only, or Strict egress scope use static fetching only because the browser cannot enforce those scopes on its own DNS connections.","editable": true,"max_value": null,"min_value": null,diff --git a/tests/web_search_engines/engines/test_search_engine_searxng.py b/tests/web_search_engines/engines/test_search_engine_searxng.pyindex 844f19b80b..0246e0f617 100644--- a/tests/web_search_engines/engines/test_search_engine_searxng.py+++ b/tests/web_search_engines/engines/test_search_engine_searxng.py@@ -15,6 +15,11 @@ from unittest.mock import Mock, call, patchimport pytest+from local_deep_research.security.egress.policy import (+ EgressContext,+ EgressScope,+)+class TestSafeSearchSetting:"""Tests for SafeSearchSetting enum."""@@ -3530,7 +3535,8 @@ class TestFullSearchPrivateIpGate:def _wrap(self, engine):"""Build the wrapper the way ``create_search_engine`` does once fullcontent is on: ``_create_full_search_wrapper`` with the registry's- module/class for searxng and no caller params."""+ module/class for searxng and a run scope that permits private URLs+ through the downloader, including redirect hops."""from local_deep_research.web_search_engines.engines.full_search import (FullSearchResults,)@@ -3539,7 +3545,17 @@ class TestFullSearchPrivateIpGate:)wrapper = _create_full_search_wrapper(- "searxng", engine, dict(self.WRAPPER_CONFIG), engine.llm, {}+ "searxng",+ engine,+ dict(self.WRAPPER_CONFIG),+ engine.llm,+ {},+ egress_context=EgressContext(+ scope=EgressScope.UNPROTECTED,+ primary_engine="searxng",+ require_local_llm=False,+ require_local_embeddings=False,+ ),)assert isinstance(wrapper, FullSearchResults)assert wrapper.web_search is engine@@ -3650,9 +3666,9 @@ class TestFullSearchPrivateIpGate:self, monkeypatch):"""POSITIVE end-to-end against the real ``validate_url`` (the- wrapper carries no run context here, so only the SSRF axis gates):- with both approvals an RFC1918 result URL reaches the downloader,- with the link-local carve-out riding along."""+ wrapper has an UNPROTECTED run scope): with both approvals an RFC1918 result+ URL reaches the downloader, with the link-local carve-out riding+ along."""engine = self._make_engine(monkeypatch, instance_gate=True, result_fetch=True)@@ -3775,19 +3791,29 @@ class TestFullSearchPrivateIpGateFactoryPath:assert wrapper.web_search._allow_private_ips is Trueassert wrapper.allow_private_ips is False- def test_wrapper_gets_no_run_egress_context_today(self, monkeypatch):- """CANARY for #6131 / ADR-0007.-- ``_create_full_search_wrapper`` hands the wrapper neither- ``egress_context`` nor ``settings_snapshot``, so on this path the- per-URL scope gate does not run and the grant reaches the download- pipeline (no run context). Once #6131 threads the context, the- default adaptive scope resolves PUBLIC_ONLY for SearXNG and- ``evaluate_url`` denies a private result URL after SSRF let it- through; revisit this test together with the ADR-0007 answer.- """+ def test_wrapper_uses_the_run_egress_context(self, monkeypatch):+ """Default ADAPTIVE resolves SearXNG to PUBLIC_ONLY, so its private+ result-fetch grant cannot fetch a private result URL for this run."""wrapper = self._get_search(monkeypatch, instance_gate=True, result_fetch=True)- assert wrapper.egress_context is None- assert wrapper._downloader_allow_private_ips() is True+ assert wrapper.egress_context.scope is EgressScope.PUBLIC_ONLY+ assert wrapper._effective_allow_private_ips() is False++ private_url = "http://192.168.1.5/wiki"+ wrapper.web_search = Mock()+ wrapper.web_search.invoke.return_value = [+ {"link": private_url, "title": "Private result"}+ ]+ with (+ patch(+ "local_deep_research.web_search_engines.engines.full_search.QUALITY_CHECK_DDG_URLS",+ False,+ ),+ patch(+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract"+ ) as mock_batch,+ ):+ results = wrapper.run("test query")+ mock_batch.assert_not_called()+ assert results[0]["full_content"] is Nonediff --git a/tests/web_search_engines/test_factory_full_search_wrapper.py b/tests/web_search_engines/test_factory_full_search_wrapper.pyindex e5f4cd8b99..0c9c5c3ca9 100644--- a/tests/web_search_engines/test_factory_full_search_wrapper.py+++ b/tests/web_search_engines/test_factory_full_search_wrapper.py@@ -8,6 +8,10 @@ from unittest.mock import Mock, patchimport pytest+from local_deep_research.security.egress.policy import (+ EgressContext,+ EgressScope,+)from local_deep_research.web_search_engines import search_engine_factoryfrom local_deep_research.web_search_engines.engine_registry import (ENGINE_REGISTRY,@@ -25,6 +29,14 @@ from local_deep_research.web_search_engines.search_engine_factory import ()+_TEST_EGRESS_CONTEXT = EgressContext(+ scope=EgressScope.BOTH,+ primary_engine="searxng",+ require_local_llm=False,+ require_local_embeddings=False,+)++@pytest.fixturedef base_engine():"""Provide a mock base engine."""@@ -279,6 +291,7 @@ class TestWrapperExtractionLanguage:mock_llm,params,settings_snapshot={"search.search_language": {"value": "German"}},+ egress_context=_TEST_EGRESS_CONTEXT,)assert isinstance(result, FullSearchResults)@@ -298,6 +311,7 @@ class TestWrapperExtractionLanguage:engine_config,mock_llm,{"language": "de", "max_results": 10},+ egress_context=_TEST_EGRESS_CONTEXT,)assert isinstance(result, FullSearchResults)@@ -315,6 +329,7 @@ class TestWrapperExtractionLanguage:engine_config,mock_llm,{"language": "xx", "max_results": 10},+ egress_context=_TEST_EGRESS_CONTEXT,)assert isinstance(result, FullSearchResults)@@ -401,6 +416,7 @@ class TestRegistryFullSearchWrapperEndToEnd:)assert isinstance(result.web_search, _MockBaseEngine)assert result.llm is mock_llm+ assert result.egress_context is not None@pytest.mark.parametrize("engine_name", FULL_SEARCH_ENGINES)def test_get_search_snippets_only_true_returns_bare_engine(@@ -675,6 +691,36 @@ class _GrantedEngine(_MockBaseEngine):allow_private_result_fetch = True+class TestWrapperEgressContext:+ def test_missing_context_returns_snippets_only_engine(self, mock_llm):+ engine = _MockBaseEngine(llm=mock_llm, programmatic_mode=True)+ result = _create_full_search_wrapper(+ "searxng", engine, dict(_WRAPPER_CONFIG), mock_llm, {}+ )+ assert result is engine++ def test_caller_params_cannot_supply_or_replace_context(self, mock_llm):+ engine = _MockBaseEngine(llm=mock_llm, programmatic_mode=True)+ forged = object()+ params = {"egress_context": forged}++ without_context = _create_full_search_wrapper(+ "searxng", engine, dict(_WRAPPER_CONFIG), mock_llm, params+ )+ assert without_context is engine++ with_context = _create_full_search_wrapper(+ "searxng",+ engine,+ dict(_WRAPPER_CONFIG),+ mock_llm,+ params,+ egress_context=_TEST_EGRESS_CONTEXT,+ )+ assert isinstance(with_context, FullSearchResults)+ assert with_context.egress_context is _TEST_EGRESS_CONTEXT++class TestWrapperPrivateResultFetchGrant:"""``FullSearchResults.allow_private_ips`` is set from the base engine'sresolved grant only (``BaseSearchEngine.allow_private_result_fetch``),@@ -687,6 +733,7 @@ class TestWrapperPrivateResultFetchGrant:dict(_WRAPPER_CONFIG),mock_llm,params or {},+ egress_context=_TEST_EGRESS_CONTEXT,)def test_engine_without_grant_keeps_wrapper_strict(self, mock_llm):