~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(searxng): honor the private-IP gate in full search and the download pipeline (#6196)
Sebastian Cao04670ad164d9
diff --git a/changelog.d/6196.security.md b/changelog.d/6196.security.mdnew file mode 100644index 0000000000..247b0047df--- /dev/null+++ b/changelog.d/6196.security.md@@ -0,0 +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.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex bcc4c82d2b..1f068e6cd1 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -44,6 +44,7 @@ They are not available in the Web UI because they are needed to start the applic| `LDR_RESEARCH_LIBRARY_ALLOW_LEGACY_READ_FALLBACK` | Boolean | `False` | No | | SECURITY RISK — leave DISABLED (default) on any multi-user or untrusted deployment. When ENABLED, library PDF reads that miss in the caller's own per-user directory fall back to a shared root derived from the user-editable 'research_library.storage_path' setting. On a multi-user instance this re-opens a CROSS-TENANT READ: a user can edit their own storage_path to point at another user's library directory, and because per-user autoincrement resource ids collide by construction (e.g. 'pdfs/5.pdf'), a read of their own document id then resolves — via this fallback — to the OTHER user's PDF and returns its contents. The safe state is OFF: with the gate off, reads resolve strictly within the requesting user's own per-user root and the fallback never fires. This is an environment-only operator gate and cannot be enabled through the user-writable settings API. Enable ONLY on a single-user or fully-trusted deployment that needs PDFs downloaded before per-user isolation (issue #5521) to keep loading from the legacy shared location. | Security | || `LDR_RESEARCH_LIBRARY_ALLOW_SHARED_LIBRARY` | Boolean | `False` | No | | Allow shared-library mode, which drops the per-user library directory boundary so all users' downloaded PDFs live in one shared directory. Disabled by default; this is an environment-only operator gate and cannot be enabled through the user-writable settings API. Because both the shared_library flag and the storage_path are otherwise user-editable, leaving shared mode user-toggleable would let a multi-tenant user point their own storage_path at another user's directory and read/overwrite their PDFs. When off, the per-user subdirectory is always enforced regardless of the user's shared_library setting. Enable only on single-tenant or mutually-trusted deployments. | Security | || `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS` | Boolean | `False` | No | | Allow user-editable PUBLIC search-engine URLs (e.g. the SearXNG instance_url) to point at private / loopback / link-local addresses. Environment-only operator gate so it cannot be flipped through the user-writable settings API. Disabled by default: a public-nature engine (its data source is the public internet) pointed at an internal host lets any authenticated user turn a research run into an internal port scan / service probe, breaking the PUBLIC_ONLY egress promise. Enable only when you self-host SearXNG on localhost/LAN and accept that engine fetches may reach your private network. 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_PRIVATE_ENGINE_URL_ALLOWLIST` | String | `None` | No | | Comma-separated list of exact URL origins (scheme://host[:port]) that user-editable PUBLIC search-engine URLs (e.g. the SearXNG instance_url) may use even though they are private / loopback / link-local — e.g. 'http://localhost:8080,http://192.168.1.5:8888'. Finer-grained alternative to LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true: private egress is enabled for an engine only when its configured URL matches a listed origin (the engine's request chain, including redirects, then runs with private access — like the blanket flag, but conditional on the match), rather than for any private URL. Matching is exact scheme + host + port (default ports 80/443 implied, host case-insensitive, path/query ignored); no wildcards or CIDR ranges. Entries that fail to parse are ignored. Environment-only operator setting so it cannot be edited through the user-writable settings API. Cloud-metadata endpoints (ALWAYS_BLOCKED_METADATA_IPS) and non-http(s) schemes stay blocked even if listed. | Security | || `LDR_SECURITY_ALLOW_NAT64` | Boolean | `False` | No | | Allow outbound traffic to NAT64 prefixes (64:ff9b::/96 RFC 6052 well-known and 64:ff9b:1::/48 RFC 8215 local-use). Disabled by default to close the IPv6-wrapped SSRF bypass class — on hosts configured with NAT64 routes, attacker-supplied URLs can wrap cloud-metadata or RFC1918 destinations through these prefixes. Enable only on IPv6-only deployments (DNS64+NAT64) where outbound IPv4 traffic is synthesized through this prefix and the operator has accepted the residual SSRF risk. 6to4 (2002::/16), Teredo (2001::/32), and the discard prefix (100::/64) remain unconditionally blocked because they have no live legitimate use in 2026. The cloud-metadata block (ALWAYS_BLOCKED_METADATA_IPS) still applies via embedded-IPv4 extraction — see SECURITY.md. | Security | || `LDR_SECURITY_CORS_ALLOWED_ORIGINS` | String | `None` | No | | Allowed CORS origins for API routes (comma-separated). Use '*' for all origins, empty for same-origin only. Example: 'https://example.com,https://app.example.com' | Security | |diff --git a/docs/SearXNG-Setup.md b/docs/SearXNG-Setup.mdindex 7012ad527c..2fb1669aea 100644--- a/docs/SearXNG-Setup.md+++ b/docs/SearXNG-Setup.md@@ -207,6 +207,41 @@ Regardless of which option is used:`ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS`) are always blocked to preventcredential theft in cloud environments- Only `http`/`https` URLs are accepted — other schemes are always refused+- The approval covers the **instance URL only**. It does not let full-content+ fetching follow the *result* URLs SearXNG returns into your private network;+ that needs the separate opt-in below.++### Full-content fetching of private result URLs++With full content enabled (`search.snippets_only` off), LDR fetches the page+behind each result through the full-search wrapper the search-engine factory+builds around the engine. Private / loopback result URLs (say an internal wiki at+`http://192.168.1.50/wiki` that your instance indexes) are blocked by default+even on an approved instance: SearXNG proxies the public web, so a poisoned or+malicious index could otherwise turn result fetching into a scan of the LDR+host's LAN, loopback included. To fetch their full content, the server+operator must additionally set:++```bash+LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH=true+```++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 the+web 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).### IPv6-only deployments (NAT64)diff --git a/src/local_deep_research/defaults/.env.template b/src/local_deep_research/defaults/.env.templateindex 4a03488c9d..153d953b4f 100644--- a/src/local_deep_research/defaults/.env.template+++ b/src/local_deep_research/defaults/.env.template@@ -45,3 +45,9 @@# LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST=http://localhost:8080# Or (broadest) allow all private engine URLs:# LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true+#+# 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:+# LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH=truediff --git a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py b/src/local_deep_research/research_library/downloaders/extraction/pipeline.pyindex 80dee18c1d..3912ef7a18 100644--- a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py+++ b/src/local_deep_research/research_library/downloaders/extraction/pipeline.py@@ -530,6 +530,8 @@ def fetch_and_extract(timeout: int = 30,language: str = "English",enable_js_rendering: bool = False,+ allow_private_ips: bool = False,+ block_link_local: bool = False,) -> Optional[str]:"""Fetch a URL and extract clean text content.@@ -551,6 +553,17 @@ 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.+ block_link_local: Keep the whole link-local range blocked even when+ ``allow_private_ips`` is True (forwarded to the downloader's+ static-fetch ``SafeSession``). No effect without the grant.Returns:Extracted plain text, or None if fetch or extraction failed.@@ -578,6 +591,8 @@ def fetch_and_extract(timeout=timeout,language=language,enable_js_rendering=enable_js_rendering,+ allow_private_ips=allow_private_ips,+ block_link_local=block_link_local,)try:# download() returns extracted text as UTF-8 bytes (not raw HTML):@@ -602,6 +617,8 @@ def batch_fetch_and_extract(timeout: int = 30,language: str = "English",enable_js_rendering: bool = False,+ allow_private_ips: bool = False,+ block_link_local: bool = False,) -> Dict[str, Optional[str]]:"""Fetch multiple URLs and extract clean text from each.@@ -624,6 +641,17 @@ 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.+ block_link_local: Keep the whole link-local range blocked even when+ ``allow_private_ips`` is True (forwarded to the downloader's+ static-fetch ``SafeSession``). No effect without the grant.Returns:Dict mapping URL → extracted text (or None if failed).@@ -659,6 +687,8 @@ def batch_fetch_and_extract(timeout=timeout,language=language,enable_js_rendering=enable_js_rendering,+ allow_private_ips=allow_private_ips,+ block_link_local=block_link_local,)try:for url in html_urls:diff --git a/src/local_deep_research/research_library/downloaders/playwright_html.py b/src/local_deep_research/research_library/downloaders/playwright_html.pyindex 3c80198577..c165f423bd 100644--- a/src/local_deep_research/research_library/downloaders/playwright_html.py+++ b/src/local_deep_research/research_library/downloaders/playwright_html.py@@ -268,6 +268,8 @@ class PlaywrightHTMLDownloader(HTMLDownloader):wait_until: str = "networkidle",block_resources: bool = True,allow_private_ips: bool = False,+ *,+ block_link_local: bool = False,**kwargs,):super().__init__(timeout=timeout, language=language)@@ -280,11 +282,19 @@ class PlaywrightHTMLDownloader(HTMLDownloader):# (``ssrf_validator`` always rejects them). Mirrors the static# SafeSession path's ``allow_private_ips`` handling.self.allow_private_ips = allow_private_ips+ # Link-local carve-out inside the private-IP grant (see+ # AutoHTMLDownloader): both route guards validate every hop with it,+ # so a redirect into the link-local range is refused on the JS route+ # exactly as the static route refuses it. No effect without+ # ``allow_private_ips``.+ self.block_link_local = block_link_local# The guarded robots.txt check (below) reuses this SafeSession, whose# send() SSRF-validates every hop; keep its policy in lockstep with# the browser guard so both honour the same egress scope.if hasattr(self.session, "allow_private_ips"):self.session.allow_private_ips = allow_private_ips+ if hasattr(self.session, "block_link_local"):+ self.session.block_link_local = block_link_local# Plain Playwright fallback stateself._playwright = Noneself._browser = None@@ -358,7 +368,9 @@ class PlaywrightHTMLDownloader(HTMLDownloader):cookie_header_override = Nonefor _ in range(_MAX_REDIRECTS + 1):if not ssrf_validator.validate_url(- current, allow_private_ips=self.allow_private_ips+ current,+ allow_private_ips=self.allow_private_ips,+ block_link_local=self.block_link_local,):# Log scheme://host:port only — a request URL may carry# credentials in userinfo / query params (RFC 3986 §3.2.1).@@ -494,6 +506,7 @@ class PlaywrightHTMLDownloader(HTMLDownloader):ssrf_validator.validate_url,current,allow_private_ips=self.allow_private_ips,+ block_link_local=self.block_link_local,),)if not ok:@@ -1245,6 +1258,7 @@ class AutoHTMLDownloader(HTMLDownloader):# explicitly when constructing the downloader.enable_js_rendering: bool = False,allow_private_ips: bool = False,+ block_link_local: bool = False,**kwargs,):super().__init__(timeout=timeout, language=language)@@ -1254,6 +1268,20 @@ class AutoHTMLDownloader(HTMLDownloader):# JS-render browser path honours the active egress scope. Default# strict; ContentFetcher relaxes to True under PRIVATE_ONLY.self.allow_private_ips = allow_private_ips+ # Keep the static-fetch SafeSession in lockstep with the browser+ # path so both routes honour the same private-egress gate (mirrors+ # PlaywrightHTMLDownloader.__init__).+ if hasattr(self.session, "allow_private_ips"):+ self.session.allow_private_ips = allow_private_ips+ # Link-local carve-out inside the private-IP grant: cloud metadata+ # lives in the link-local range beyond the always-blocked literals+ # and no legitimate page does. Off by default; full_search sets it+ # alongside allow_private_ips. The SafeSession forwards it to every+ # hop of the static fetch and the Playwright child to both of its+ # route guards.+ self.block_link_local = block_link_local+ if hasattr(self.session, "block_link_local"):+ self.session.block_link_local = block_link_localself._playwright_downloader = Nonedef _get_playwright_downloader(self) -> PlaywrightHTMLDownloader:@@ -1263,6 +1291,7 @@ class AutoHTMLDownloader(HTMLDownloader):timeout=self.timeout,language=self.language,allow_private_ips=self.allow_private_ips,+ block_link_local=self.block_link_local,)return self._playwright_downloaderdiff --git a/src/local_deep_research/security/dns_pinning.py b/src/local_deep_research/security/dns_pinning.pyindex 630a2e6336..0379c0a0a4 100644--- a/src/local_deep_research/security/dns_pinning.py+++ b/src/local_deep_research/security/dns_pinning.py@@ -644,6 +644,7 @@ def pinned_request(url: str,allow_localhost: bool = False,allow_private_ips: bool = False,+ block_link_local: bool = False,) -> Iterator[None]:"""Pin DNS for the duration of a single outbound request to ``url``.@@ -652,6 +653,12 @@ def pinned_request(``requests`` / ``urllib3`` inside this context cannot be steered to arebind target: the address validated here is the address connected to.+ ``block_link_local`` is forwarded to the connect-time validation so a+ caller that keeps link-local blocked under ``allow_private_ips`` (e.g.+ ``SafeSession(block_link_local=True)``) is not undone by a resolver+ answer that moved into ``169.254.0.0/16`` between validation and+ connect.+Yields 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.@@ -669,7 +676,12 @@ def pinned_request(yieldreturn- entry = _resolve_and_validate(host, allow_localhost, allow_private_ips)+ entry = _resolve_and_validate(+ host,+ allow_localhost,+ allow_private_ips,+ block_link_local=block_link_local,+ )pins = _get_pins()# Save/restore any prior pin for this host so nested contexts (e.g. adiff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.mdindex 336dee79f1..1c9f2c3d1c 100644--- a/src/local_deep_research/security/egress/README.md+++ b/src/local_deep_research/security/egress/README.md@@ -145,7 +145,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` | `evaluate_url` |+| 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 || 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) |@@ -153,7 +153,7 @@ actually enforces the policy":| Journal reputation fetch | `advanced_search_system/filters/journal_reputation_filter.py` | scope skip || Run-start precheck | `web/routers/research.py` (`_precheck_engine_policy`) | `evaluate_engine` (clean 400 at the API boundary) || Settings validation | `web/routers/settings.py` (calls `egress/validators.py`) | `first_egress_validation_error` (scope, local hostnames, trusted engines, public-engine instance URLs) |-| Public-engine instance fetch | `web_search_engines/engines/search_engine_searxng.py` via `egress/validators.resolve_engine_allow_private_ips` (SearXNG wrapper `resolve_searxng_allow_private_ips`; any future public engine with a `url_setting` must call it on its fetch path) | env-only operator gate / per-origin URL allowlist / engine's env-locked URL — a private instance URL is otherwise not fetched (engine self-disables with an ERROR naming the remedies) |+| Public-engine instance fetch | `web_search_engines/engines/search_engine_searxng.py` via `egress/validators.resolve_engine_allow_private_ips` (SearXNG wrapper `resolve_searxng_allow_private_ips`; any future public engine with a `url_setting` must call it on its fetch path) | env-only operator gate / per-origin URL allowlist / engine's env-locked URL — a private instance URL is otherwise not fetched (engine self-disables with an ERROR naming the remedies). Covers the instance URL only: private RESULT URLs additionally need `search.allow_private_result_fetch` (see the full-content fetch row) || Model discovery | `web/routers/settings.py` (`_resolve_model_discovery_policy`, `_model_discovery_provider_allowed`) | resolves scope **before** the model cache is read or any provider is contacted; fails closed || Journal-data download | `web/routers/metrics.py` | scope check (refuses when scope is unresolved) || RAG embeddings | `web/routers/rag.py` | `evaluate_embeddings` |diff --git a/src/local_deep_research/security/egress/validators.py b/src/local_deep_research/security/egress/validators.pyindex c66159f972..c12127b742 100644--- a/src/local_deep_research/security/egress/validators.py+++ b/src/local_deep_research/security/egress/validators.py@@ -504,6 +504,53 @@ def resolve_searxng_allow_private_ips(instance_url: str) -> bool:)+def resolve_engine_allow_private_result_fetch(+ instance_url: str, url_setting: str+) -> bool:+ """Whether full-content fetches of a PUBLIC engine's RESULT URLs may+ reach private / loopback hosts.++ Distinct from, and strictly narrower than,+ ``resolve_engine_allow_private_ips``: that grant answers "may this+ engine reach its configured *instance* URL", and its env-locked-URL+ condition is met by every Docker (compose) deployment. A public engine+ proxies the public web, so extending the instance grant to the URLs+ the 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:++ 1. the operator set the env-only opt-in+ ``search.allow_private_result_fetch``+ (``LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH=true``), which the+ bundled ``docker-compose.yml`` does not set, AND+ 2. the engine is approved for its own instance URL+ (``resolve_engine_allow_private_ips``).++ Link-local (``169.254.0.0/16``, ``fe80::/10``) and the cloud-metadata+ literals in ``ALWAYS_BLOCKED_METADATA_IPS`` stay blocked even when+ this returns True: the full-content fetch path validates with+ ``block_link_local=True``. Fails CLOSED (False) on any error.+ """+ try:+ from ...settings.env_registry import get_env_setting++ if not bool(+ get_env_setting("search.allow_private_result_fetch", False)+ ):+ return False+ except Exception: # noqa: silent-exception - fail closed+ return False+ return resolve_engine_allow_private_ips(instance_url, url_setting)+++def resolve_searxng_allow_private_result_fetch(instance_url: str) -> bool:+ """SearXNG-keyed convenience wrapper over+ ``resolve_engine_allow_private_result_fetch``."""+ return resolve_engine_allow_private_result_fetch(+ instance_url, _SEARXNG_INSTANCE_URL_KEY+ )++def _engine_url_ssrf_error(key, value, *, allow_private: bool):"""Return an error dict for a public-engine URL that must be refused.diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.pyindex 08749a04c8..f1dce89009 100644--- a/src/local_deep_research/security/safe_requests.py+++ b/src/local_deep_research/security/safe_requests.py@@ -573,7 +573,10 @@ class SafeSession(requests.Session):"""def __init__(- self, allow_localhost: bool = False, allow_private_ips: bool = False+ self,+ allow_localhost: bool = False,+ allow_private_ips: bool = False,+ block_link_local: bool = False,):"""Initialize SafeSession.@@ -587,11 +590,20 @@ class SafeSession(requests.Session):Note: cloud metadata endpoints (AWS / Azure / OCI / DigitalOcean /AlibabaCloud / Tencent / ECS) are ALWAYS blocked — see``ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS``.+ block_link_local: Keep the whole link-local range (IPv4+ ``169.254.0.0/16``, IPv6 ``fe80::/10`` and their NAT64-wrapped+ forms) blocked EVEN under ``allow_private_ips=True``, on the+ initial request, every redirect hop, and the connect-time DNS+ re-validation. Set it when relaxing ``allow_private_ips`` for a+ trusted target that is never link-local (cloud metadata lives+ there beyond the always-blocked literals). No effect without+ ``allow_private_ips``; forwarded to ``validate_url``."""super().__init__()self.max_redirects = _MAX_REDIRECTSself.allow_localhost = allow_localhostself.allow_private_ips = allow_private_ips+ self.block_link_local = block_link_local# Per-thread, because one session is shared across search engines.self._redirect_local = threading.local()@@ -687,6 +699,7 @@ class SafeSession(requests.Session):url,allow_localhost=self.allow_localhost,allow_private_ips=self.allow_private_ips,+ block_link_local=self.block_link_local,):raise ValueError(f"URL failed security validation (possible SSRF): {url}"@@ -725,6 +738,7 @@ class SafeSession(requests.Session):request.url,allow_localhost=self.allow_localhost,allow_private_ips=self.allow_private_ips,+ block_link_local=self.block_link_local,):logger.warning(f"Request to {request.url} blocked by SSRF validation"@@ -751,6 +765,7 @@ class SafeSession(requests.Session):request.url or "",allow_localhost=self.allow_localhost,allow_private_ips=self.allow_private_ips,+ block_link_local=self.block_link_local,):response = super().send(request, **kwargs)finally:diff --git a/src/local_deep_research/settings/env_definitions/security.py b/src/local_deep_research/settings/env_definitions/security.pyindex c4ab52dcc6..ae1464737f 100644--- a/src/local_deep_research/settings/env_definitions/security.py+++ b/src/local_deep_research/settings/env_definitions/security.py@@ -133,6 +133,31 @@ SECURITY_SETTINGS = [),default=None,),+ BooleanSetting(+ key="search.allow_private_result_fetch",+ description=(+ "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."+ ),+ default=False,+ ),BooleanSetting(key="research_library.allow_filesystem_pdf_storage",description=(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 a5aa3063df..ed4db35704 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@@ -7,7 +7,7 @@ from ...config.search_config import QUALITY_CHECK_DDG_URLSfrom ...research_library.downloaders.extraction import (batch_fetch_and_extract,)-from ...security.egress.policy import PolicyDeniedError+from ...security.egress.policy import EgressScope, PolicyDeniedErrorfrom ...security.log_sanitizer import scrub_errorfrom ...security.secure_logging import loggerfrom ...security.ssrf_validator import redact_url_for_log, validate_url@@ -22,6 +22,19 @@ class _Invokable(Protocol):def invoke(self, query: str) -> Any: ...+# Egress scopes whose ``evaluate_url`` admits every http(s) host the SSRF+# validator admits (UNPROTECTED lifts only the scope restriction; the hard+# SSRF and cloud-metadata blocks stay and the download pipeline enforces+# 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+# reaches this module (resolved at context construction); an unknown scope+# fails closed.+_SCOPES_WITHOUT_HOST_CLASS_RESTRICTION = frozenset({EgressScope.UNPROTECTED})++class FullSearchResults:def __init__(self,@@ -35,6 +48,7 @@ class FullSearchResults:safesearch: str | int = "Moderate",settings_snapshot: Optional[Dict] = None,egress_context: Optional[Any] = None,+ allow_private_ips: bool = False,):self.llm = llmself.output_format = output_format@@ -45,10 +59,51 @@ class FullSearchResults:self.safesearch = safesearchself.web_search = web_searchself.settings_snapshot = settings_snapshot+ # The parent engine's resolved result-fetch grant, handed over by+ # the factory when it builds this wrapper+ # (``BaseSearchEngine.allow_private_result_fetch``; e.g. SearXNG:+ # instance approved for private egress AND the env-only+ # ``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``).+ # Link-local and the cloud-metadata literals in+ # ALWAYS_BLOCKED_METADATA_IPS stay blocked regardless (issue #2477).+ self.allow_private_ips = allow_private_ips# 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+ 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.+ """+ if not self.allow_private_ips:+ return False+ egress_ctx = self.egress_context+ if egress_ctx is None:+ return True+ 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}"+ )+ return False+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)@@ -191,7 +246,16 @@ class FullSearchResults:for url in urls:if url is None:continue- if not validate_url(url):+ # block_link_local=True is the carve-out inside the private-IP+ # grant: the rest of the link-local range hosts provider metadata+ # beyond ALWAYS_BLOCKED_METADATA_IPS (Scaleway's endpoint, for+ # one) and no legitimate result page lives there. No effect+ # without the grant, where link-local is already blocked.+ if not validate_url(+ url,+ allow_private_ips=self.allow_private_ips,+ block_link_local=True,+ ):logger.warning("SSRF validation blocked URL from full content fetch: "f"{redact_url_for_log(url)}."@@ -230,6 +294,8 @@ class FullSearchResults:enable_js_rendering=_read_js_rendering_setting(self.settings_snapshot),+ allow_private_ips=self._downloader_allow_private_ips(),+ block_link_local=True,)nr_full_text = sum(1 for v in url_to_content.values() if v)@@ -255,7 +321,11 @@ class FullSearchResults:link = item.get("link")if link is None:continue- if not validate_url(link):+ if not validate_url(+ link,+ allow_private_ips=self.allow_private_ips,+ block_link_local=True,+ ):logger.warning("SSRF validation blocked URL from full content fetch: "f"{redact_url_for_log(link)}."@@ -285,6 +355,8 @@ class FullSearchResults:enable_js_rendering=_read_js_rendering_setting(self.settings_snapshot),+ allow_private_ips=self._downloader_allow_private_ips(),+ block_link_local=True,)except Exception as e:safe_msg = scrub_error(e)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 48c48a80f8..0649462049 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@@ -20,6 +20,7 @@ from ._searxng_rate_limiter import respect_rate_limit# argument when the resolver was generalized).from ...security.egress.validators import (resolve_searxng_allow_private_ips as _resolve_searxng_allow_private_ips,+ resolve_searxng_allow_private_result_fetch,)@@ -218,6 +219,20 @@ class SearXNGSearchEngine(BaseSearchEngine):self._allow_private_ips = _resolve_searxng_allow_private_ips(self.instance_url)+ # Whether full-content fetches may follow this instance's RESULT+ # URLs into private/loopback hosts (e.g. an internal wiki it+ # indexes). Deliberately a separate, narrower grant than the+ # instance gate above: that one is satisfied by every env-locked+ # (Docker) deployment, and a public engine proxies the public web,+ # so it must not by itself license fetching whatever private URLs+ # the index returns. Requires the instance gate AND the env-only+ # ``LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH`` opt-in; see+ # ``resolve_engine_allow_private_result_fetch``. Overrides the+ # ``BaseSearchEngine`` default (False); the factory hands it to the+ # full-search wrapper it builds around this engine (issue #2477).+ self.allow_private_result_fetch = (+ resolve_searxng_allow_private_result_fetch(self.instance_url)+ )try:# Make sure it's accessible.response = safe_get(@@ -321,6 +336,16 @@ class SearXNGSearchEngine(BaseSearchEngine):# wrapper fetches pages via ``batch_fetch_and_extract`` and# populates ``full_content`` on each result; the inner engine# only emits snippets from ``_get_previews``.+ if self.allow_private_result_fetch:+ # The grant is an allow, not a deny, so leave an operator-+ # 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).+ 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)}"+ )def _respect_rate_limit(self):"""Apply self-imposed rate limiting between requests.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 d4ef743b73..05cbf93d8d 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@@ -164,6 +164,16 @@ class BaseSearchEngine(ABC):egress_sensitivity = Sensitivity.SENSITIVEegress_exposure = Exposure.EXPOSING+ # Whether full-content fetches of this engine's RESULT URLs may reach+ # private / loopback hosts. The search-engine factory reads it when it+ # builds the FullSearchResults wrapper (the only full-content path) and+ # hands it over as the wrapper's ``allow_private_ips``. Default False:+ # 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).+ allow_private_result_fetch = False+# Class attribute to indicate if this is a news search engine# News engines specialize in news articles and current eventsis_news = False@@ -1367,6 +1377,11 @@ class BaseSearchEngine(ABC):safesearch=safe_search,settings_snapshot=self.settings_snapshot,egress_context=egress_context,+ # Same hand-over as the factory's+ # ``_create_full_search_wrapper``: the engine's own+ # explicit boolean grant, nothing else, so an engine+ # built through this seam does not lose it silently.+ allow_private_ips=self.allow_private_result_fetch is True,)except ImportError:logger.warning(diff --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 24f9096b32..dbcf625431 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@@ -914,6 +914,19 @@ def _create_full_search_wrapper(if "web_search" in wrapper_init_params:wrapper_params["web_search"] = base_engine+ # Private result-fetch grant for the wrapper's SSRF validation and+ # download pipeline. Taken from the base engine's own resolution+ # only (``BaseSearchEngine.allow_private_result_fetch``, False+ # 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).+ if "allow_private_ips" in wrapper_init_params:+ wrapper_params["allow_private_ips"] = (+ isinstance(base_engine, BaseSearchEngine)+ and base_engine.allow_private_result_fetch is True+ )+logger.debug(f"Creating full search wrapper for {engine_name} with filtered parameters: {wrapper_params.keys()}")diff --git a/tests/research_library/downloaders/test_extraction_pipeline.py b/tests/research_library/downloaders/test_extraction_pipeline.pyindex cd6c5e23b0..8ad5c9f3b5 100644--- a/tests/research_library/downloaders/test_extraction_pipeline.py+++ b/tests/research_library/downloaders/test_extraction_pipeline.py@@ -1172,3 +1172,78 @@ class TestFlattenHtml:assert len(lines) == 50_000assert set(lines) == {"x"}+++class TestFetchAndExtractPrivateIpPlumbing:+ """The ``allow_private_ips`` flag must be forwarded into the+ ``AutoHTMLDownloader`` constructor and default to blocked."""++ def _patched_downloader(self, monkeypatch):+ monkeypatch.setattr(+ pipeline,+ "_try_specialized_downloader",+ lambda url, timeout=30: _specialized(),+ )+ mock_downloader = Mock()+ mock_downloader.download.return_value = b"x"+ mock_downloader.close = Mock()+ mock_class = Mock(return_value=mock_downloader)+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",+ mock_class,+ )+ return mock_class++ def test_fetch_and_extract_forwards_explicit_private_ip_opt_in(+ self, monkeypatch+ ):+ mock_class = self._patched_downloader(monkeypatch)+ pipeline.fetch_and_extract(+ "https://example.com", allow_private_ips=True+ )+ assert mock_class.call_args.kwargs.get("allow_private_ips") is True++ def test_fetch_and_extract_defaults_private_ips_to_blocked(+ self, monkeypatch+ ):+ mock_class = self._patched_downloader(monkeypatch)+ pipeline.fetch_and_extract("https://example.com")+ assert mock_class.call_args.kwargs.get("allow_private_ips") is False+ assert mock_class.call_args.kwargs.get("block_link_local") is False++ def test_fetch_and_extract_forwards_block_link_local(self, monkeypatch):+ mock_class = self._patched_downloader(monkeypatch)+ pipeline.fetch_and_extract(+ "https://example.com",+ allow_private_ips=True,+ block_link_local=True,+ )+ assert mock_class.call_args.kwargs.get("block_link_local") is True++ def test_batch_fetch_and_extract_forwards_explicit_private_ip_opt_in(+ self, monkeypatch+ ):+ mock_class = self._patched_downloader(monkeypatch)+ pipeline.batch_fetch_and_extract(+ ["https://example.com"], allow_private_ips=True+ )+ assert mock_class.call_args.kwargs.get("allow_private_ips") is True++ def test_batch_fetch_and_extract_defaults_private_ips_to_blocked(+ self, monkeypatch+ ):+ mock_class = self._patched_downloader(monkeypatch)+ pipeline.batch_fetch_and_extract(["https://example.com"])+ assert mock_class.call_args.kwargs.get("allow_private_ips") is False+ assert mock_class.call_args.kwargs.get("block_link_local") is False++ def test_batch_fetch_and_extract_forwards_block_link_local(+ self, monkeypatch+ ):+ mock_class = self._patched_downloader(monkeypatch)+ pipeline.batch_fetch_and_extract(+ ["https://example.com"],+ allow_private_ips=True,+ block_link_local=True,+ )+ assert mock_class.call_args.kwargs.get("block_link_local") is Truediff --git a/tests/research_library/downloaders/test_playwright_html.py b/tests/research_library/downloaders/test_playwright_html.pyindex 3a8e1ab354..74a680ff98 100644--- a/tests/research_library/downloaders/test_playwright_html.py+++ b/tests/research_library/downloaders/test_playwright_html.py@@ -5,8 +5,10 @@ Playwright browser tests are not run here (require browser install);these test the logic around when to use Playwright."""-from unittest.mock import Mock, patch+import asyncio+from unittest.mock import AsyncMock, MagicMock, Mock, patch+import pytestfrom local_deep_research.research_library.downloaders.playwright_html import (AutoHTMLDownloader,@@ -275,3 +277,98 @@ class TestAutoDownloaderJSRenderingToggle:dl = AutoHTMLDownloader(timeout=5)assert dl.enable_js_rendering is Falsedl.close()+++class TestAutoDownloaderPrivateIpSessionSync:+ """AutoHTMLDownloader must keep its static-fetch SafeSession in+ lockstep with the ``allow_private_ips`` gate (the browser child+ already receives it)."""++ def test_forwards_private_ip_opt_in_to_session(self):+ dl = AutoHTMLDownloader(allow_private_ips=True)+ try:+ assert dl.session.allow_private_ips is True+ finally:+ dl.close()++ def test_session_blocks_private_ips_by_default(self):+ dl = AutoHTMLDownloader()+ try:+ assert dl.session.allow_private_ips is False+ finally:+ dl.close()++ def test_forwards_block_link_local_to_session(self):+ """The link-local carve-out reaches the static-fetch SafeSession+ so a redirect hop into 169.254.0.0/16 is refused under the grant."""+ dl = AutoHTMLDownloader(allow_private_ips=True, block_link_local=True)+ try:+ assert dl.block_link_local is True+ assert dl.session.block_link_local is True+ finally:+ dl.close()++ def test_session_block_link_local_off_by_default(self):+ dl = AutoHTMLDownloader()+ try:+ assert dl.block_link_local is False+ assert dl.session.block_link_local is False+ finally:+ dl.close()+++class _RedirectHop:+ """Stand-in for the Playwright APIResponse of a 302 hop, with the+ attributes the route guards read (status, headers, headers_array)."""++ def __init__(self, location: str):+ self.status = 302+ self.headers = {"location": location}+ self.headers_array = [{"name": "location", "value": location}]+++class TestAutoDownloaderBlockLinkLocalReachesJsRoute:+ """``block_link_local`` must reach the lazily-built Playwright child and+ both of its route guards, so under an open grant the JS-rendering+ fallback refuses a redirect hop into the link-local range exactly like+ the static SafeSession route does. Real validator, no browser: the entry+ hop is an RFC1918 literal (allowed under the grant, no DNS) that 302s to+ a link-local address outside ``ALWAYS_BLOCKED_METADATA_IPS``, so only+ the threaded flag can refuse it."""++ ENTRY_URL = "http://10.0.0.5/wiki"+ LINK_LOCAL_URL = "http://169.254.42.42/latest/meta-data"++ @pytest.mark.parametrize("guard", ["playwright", "crawl4ai"])+ def test_js_route_refuses_redirect_into_link_local_under_open_grant(+ self, guard+ ):+ dl = AutoHTMLDownloader(allow_private_ips=True, block_link_local=True)+ try:+ child = dl._get_playwright_downloader()+ assert child.allow_private_ips is True+ assert child.block_link_local is True++ hop = _RedirectHop(self.LINK_LOCAL_URL)+ route = MagicMock()+ route.request.url = self.ENTRY_URL+ route.request.method = "GET"+ route.request.resource_type = "document"+ if guard == "playwright":+ route.fetch = MagicMock(return_value=hop)+ child._playwright_route_guard(route)+ route.abort.assert_called_once_with("blockedbyclient")+ route.fulfill.assert_not_called()+ else:+ route.fetch = AsyncMock(return_value=hop)+ route.fulfill = AsyncMock()+ route.abort = AsyncMock()+ route.fallback = AsyncMock()+ asyncio.run(child._crawl4ai_route_guard(route))+ route.abort.assert_awaited_once_with("blockedbyclient")+ route.fulfill.assert_not_awaited()+ finally:+ dl.close()+ # The entry hop was fetched once; the link-local hop was refused+ # before it was fetched.+ assert route.fetch.call_count == 1diff --git a/tests/security/test_egress_fullsearch.py b/tests/security/test_egress_fullsearch.pyindex 4580ab620f..8a92473c4c 100644--- a/tests/security/test_egress_fullsearch.py+++ b/tests/security/test_egress_fullsearch.py@@ -14,9 +14,17 @@ literals, so no DNS / network is required.from __future__ import annotations+import asyncio+from unittest.mock import AsyncMock, MagicMock+import pytest+import requestsfrom loguru import logger+from requests.structures import CaseInsensitiveDict+from local_deep_research.research_library.downloaders import (+ playwright_html as pw,+)from local_deep_research.security.egress.policy import (EgressContext,EgressScope,@@ -72,7 +80,11 @@ def patched_fetch(monkeypatch):return {u: "content-for-" + u for u in urls}monkeypatch.setattr(fs, "batch_fetch_and_extract", fake_batch)- monkeypatch.setattr(fs, "validate_url", lambda u: True)+ monkeypatch.setattr(+ fs,+ "validate_url",+ lambda u, allow_private_ips=False, block_link_local=False: True,+ )return captured@@ -198,3 +210,323 @@ def test_denied_url_audit_log_is_redacted(patched_fetch):assert "SUPERSECRET" not in rec["message"]assert "/secret" not in logged_urlassert rec["extra"]["reason"] == "scope_mismatch_private_only"+++# ===========================================================================+# The private-fetch grant on the downloader path under a run policy+# ===========================================================================+#+# The two gates above only ever see the result URL. The download pipeline+# (``batch_fetch_and_extract`` -> ``AutoHTMLDownloader``) applies its address+# flags to every destination it actually reaches, redirect hops and browser+# subresources included, but it never sees the run's egress policy. So+# ``FullSearchResults`` may hand it the private-fetch grant only when that+# policy restricts no host class (no run context, or the ``unprotected``+# scope); under ``public_only`` / ``private_only`` / ``strict`` the pipeline+# runs with the strict default. The tests below drive the REAL pipeline with+# the HTTP transport faked at the ``requests`` adapter (no network, no DNS:+# IP literals only) and assert that a destination the policy denies is never+# fetched.++_PRIVATE_HOP = "http://10.0.0.5/internal"+_PUBLIC_HOP = "http://93.184.216.34/next"+_ARTICLE_HTML = (+ "<html><head><title>Wiki page</title></head><body><article><p>"+ "This page documents the deployment procedure for the internal wiki. "+ "It describes how the service is provisioned, how backups are rotated "+ "every night, how the on-call engineer restores a snapshot, and which "+ "dashboards to watch after a release. Each section lists the commands "+ "to run and the expected output so the procedure can be followed step "+ "by step without prior knowledge of the system."+ "</p></article></body></html>"+).encode("utf-8")+_SPA_SHELL_HTML = (+ '<html><body><div id="root"></div>'+ "<noscript>You need to enable JavaScript to run this app.</noscript>"+ "</body></html>"+).encode("utf-8")+++def _html_ok(body: bytes):+ return (200, {"Content-Type": "text/html; charset=utf-8"}, body)+++def _redirect_to(location: str):+ return (302, {"Location": location}, b"")+++def transport(monkeypatch):+ """Fake the bottom of ``requests``: serve scripted responses per URL and+ record every URL the pipeline actually tried to fetch. Patching the+ adapter (not the downloader) keeps ``SafeSession`` and its per-hop+ redirect validation in the loop, which is what is under test."""+ state = {"responses": {}, "urls": []}++ def fake_send(_adapter, request, **_kwargs):+ state["urls"].append(request.url)+ status, headers, body = state["responses"].get(+ request.url, (404, {}, b"")+ )+ response = requests.Response()+ response.status_code = status+ response.headers = CaseInsensitiveDict(+ {"Content-Length": str(len(body)), **headers}+ )+ response._content = body+ response.encoding = "utf-8"+ response.url = request.url+ response.request = request+ return response++ monkeypatch.setattr(requests.adapters.HTTPAdapter, "send", fake_send)+ return state+++def _granted_engine(results, ctx, settings_snapshot=None):+ return fs.FullSearchResults(+ llm=None,+ web_search=_FakeWebSearch(results),+ settings_snapshot=settings_snapshot,+ egress_context=ctx,+ allow_private_ips=True,+ )+++ "scope,entry,denied_hop",+ [+ (EgressScope.PUBLIC_ONLY, _PUBLIC_URL, _PRIVATE_HOP),+ (EgressScope.PRIVATE_ONLY, _PRIVATE_URL, _PUBLIC_HOP),+ (EgressScope.STRICT, _PRIVATE_URL, _PUBLIC_HOP),+ ],+ ids=["public_only", "private_only", "strict"],+)+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)."""+ transport["responses"] = {+ entry: _redirect_to(denied_hop),+ denied_hop: _html_ok(_ARTICLE_HTML),+ }+ engine = _granted_engine([{"title": "r", "link": entry}], _make_ctx(scope))++ out = engine.run("q")++ assert denied_hop not in transport["urls"]+ assert out[0]["full_content"] is None+ if scope is EgressScope.PUBLIC_ONLY:+ # The public entry itself was fetched, so the pipeline really ran+ # and the hop, not the initial gate, is what was refused.+ assert entry in transport["urls"]+ else:+ # A private entry under the strict default is refused before the+ # first request goes out: nothing is fetched at all.+ assert transport["urls"] == []+++ "ctx",+ [None, _make_ctx(EgressScope.UNPROTECTED)],+ ids=["no_context", "unprotected"],+)+def test_permitted_fetch_reaches_private_result_with_grant(transport, ctx):+ """CONTROL: with no run policy, or one that restricts no host class, the+ grant reaches the pipeline and an RFC1918 result page is fetched and+ extracted end to end."""+ transport["responses"] = {_PRIVATE_URL: _html_ok(_ARTICLE_HTML)}+ engine = _granted_engine([{"title": "r", "link": _PRIVATE_URL}], ctx)++ out = engine.run("q")++ assert _PRIVATE_URL in transport["urls"]+ assert out[0]["full_content"]+ assert "deployment procedure" in out[0]["full_content"]+++def test_grant_off_blocks_private_result_before_any_fetch(transport):+ """CONTROL: without the grant the strict ``validate_url`` in full_search+ rejects the private result URL even under ``unprotected``, so the fetch+ in the test above is due to the grant and nothing else."""+ transport["responses"] = {_PRIVATE_URL: _html_ok(_ARTICLE_HTML)}+ engine = fs.FullSearchResults(+ llm=None,+ web_search=_FakeWebSearch([{"title": "r", "link": _PRIVATE_URL}]),+ egress_context=_make_ctx(EgressScope.UNPROTECTED),+ )++ out = engine.run("q")++ assert transport["urls"] == []+ assert out[0]["full_content"] is None+++def test_link_local_result_stays_blocked_with_grant_and_no_policy(transport):+ """CONTROL: the link-local carve-out survives the grant on the path+ where the grant does reach the pipeline (no run context)."""+ link_local = "http://169.254.42.42/latest/meta-data"+ transport["responses"] = {link_local: _html_ok(_ARTICLE_HTML)}+ engine = _granted_engine([{"title": "r", "link": link_local}], None)++ out = engine.run("q")++ assert transport["urls"] == []+ assert out[0]["full_content"] is None+++class _TerminalHop:+ """Stand-in for the Playwright APIResponse of a 200 hop, with the+ attributes the route guards read."""++ status = 200+ headers: dict = {}+ headers_array: list = []+++def _recording_auto_downloader(children):+ class _Recording(pw.AutoHTMLDownloader):+ def _get_playwright_downloader(self):+ child = super()._get_playwright_downloader()+ if child not in children:+ children.append(child)+ return child++ return _Recording++[email protected]("guard", ["playwright", "crawl4ai"])+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."""+ children = []+ monkeypatch.setattr(+ pw, "AutoHTMLDownloader", _recording_auto_downloader(children)+ )+ monkeypatch.setattr(+ pw.PlaywrightHTMLDownloader, "_fetch_html", lambda self, url: None+ )+ transport["responses"] = {_PUBLIC_URL: _html_ok(_SPA_SHELL_HTML)}+ engine = _granted_engine(+ [{"title": "r", "link": _PUBLIC_URL}],+ _make_ctx(EgressScope.PUBLIC_ONLY),+ settings_snapshot={"web.enable_javascript_rendering": True},+ )++ 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 child.allow_private_ips is False+ assert child.block_link_local is True++ route = MagicMock()+ route.request.url = "http://10.0.0.5/api/data"+ route.request.method = "GET"+ route.request.resource_type = "xhr"+ if guard == "playwright":+ route.fetch = MagicMock(return_value=_TerminalHop())+ child._playwright_route_guard(route)+ route.abort.assert_called_once_with("blockedbyclient")+ route.fulfill.assert_not_called()+ else:+ route.fetch = AsyncMock(return_value=_TerminalHop())+ route.fulfill = AsyncMock()+ route.abort = AsyncMock()+ route.fallback = AsyncMock()+ asyncio.run(child._crawl4ai_route_guard(route))+ route.abort.assert_awaited_once_with("blockedbyclient")+ route.fulfill.assert_not_awaited()+ route.fetch.assert_not_called()+++ "scope,url,expected",+ [+ (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),+ ],+ ids=[+ "no_context",+ "unprotected",+ "public_only",+ "private_only",+ "strict",+ "both",+ ],+)[email protected]("method", ["run", "_get_full_content"])+def test_pipeline_grant_follows_run_scope(+ monkeypatch, scope, url, expected, method+):+ """Pin the rule at both call sites: the pipeline is handed the grant+ only with no run context or under ``unprotected``; every scope that+ restricts hosts by class, and the internal ``both`` fallback, gets the+ strict default. ``block_link_local`` stays on either way. The result+ URL is one the scope admits, so the real ``evaluate_url`` lets it+ through to the pipeline call."""+ seen = {}++ def fake_batch(urls, **kwargs):+ seen.update(kwargs)+ return {u: "content" for u in urls}++ monkeypatch.setattr(fs, "batch_fetch_and_extract", fake_batch)+ monkeypatch.setattr(+ fs,+ "validate_url",+ lambda u, allow_private_ips=False, block_link_local=False: True,+ )+ ctx = None if scope is None else _make_ctx(scope)+ items = [{"title": "r", "link": url}]+ engine = _granted_engine(items, ctx)++ if method == "run":+ engine.run("q")+ else:+ engine._get_full_content(items)++ assert seen["allow_private_ips"] is expected+ assert seen["block_link_local"] is True+++def test_pipeline_grant_off_stays_off_under_unprotected(monkeypatch):+ """CONTROL for the pin above: the permissive scope never manufactures a+ grant the engine does not hold."""+ seen = {}++ def fake_batch(urls, **kwargs):+ seen.update(kwargs)+ return {u: "content" for u in urls}++ monkeypatch.setattr(fs, "batch_fetch_and_extract", fake_batch)+ monkeypatch.setattr(+ fs,+ "validate_url",+ lambda u, allow_private_ips=False, block_link_local=False: True,+ )+ engine = fs.FullSearchResults(+ llm=None,+ web_search=_FakeWebSearch([{"title": "r", "link": _PRIVATE_URL}]),+ egress_context=_make_ctx(EgressScope.UNPROTECTED),+ )++ engine.run("q")++ assert seen["allow_private_ips"] is False+ assert seen["block_link_local"] is Truediff --git a/tests/security/test_safe_requests.py b/tests/security/test_safe_requests.pyindex 4a515cb896..a03aba9783 100644--- a/tests/security/test_safe_requests.py+++ b/tests/security/test_safe_requests.py@@ -551,6 +551,7 @@ class TestSafeSession:"http://localhost:8080",allow_localhost=True,allow_private_ips=False,+ block_link_local=False,)def test_passes_allow_private_ips_to_validate(self):@@ -568,6 +569,7 @@ class TestSafeSession:"http://192.168.1.1",allow_localhost=False,allow_private_ips=True,+ block_link_local=False,)diff --git a/tests/security/test_ssrf_debug_hardening.py b/tests/security/test_ssrf_debug_hardening.pyindex b4d99e16e0..f8c69b8307 100644--- a/tests/security/test_ssrf_debug_hardening.py+++ b/tests/security/test_ssrf_debug_hardening.py@@ -216,7 +216,9 @@ class TestFullSearchSSRFValidation:):mock_validate.return_value = Falsefs.run("test")- mock_validate.assert_called_once_with(raw_url)+ mock_validate.assert_called_once_with(+ raw_url, allow_private_ips=False, block_link_local=True+ )def test_all_urls_blocked_returns_results_without_content(self):"""When all URLs are blocked, results are returned with full_content=None.diff --git a/tests/security/test_ssrf_dns_pinning.py b/tests/security/test_ssrf_dns_pinning.pyindex 32de642ba9..59ab577f21 100644--- a/tests/security/test_ssrf_dns_pinning.py+++ b/tests/security/test_ssrf_dns_pinning.py@@ -575,3 +575,27 @@ def test_reload_does_not_make_the_shim_call_itself():finally:# Re-establish a clean, self-consistent module state for later tests.importlib.reload(dns_pinning)+++def test_pinned_request_forwards_block_link_local():+ """``block_link_local`` reaches the connect-time re-validation: a host+ whose answer sits in 169.254.0.0/16 is refused under+ ``allow_private_ips`` when the caller keeps link-local blocked, and is+ pinned as before when it does not."""+ resolver = _Resolver({"ll.example": [["169.254.42.42"]]})+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):+ with pytest.raises(ValueError, match="SSRF|security validation"):+ with dns_pinning.pinned_request(+ "http://ll.example/",+ allow_private_ips=True,+ block_link_local=True,+ ):+ pass+ assert "ll.example" not in dns_pinning._get_pins()++ resolver = _Resolver({"ll.example": [["169.254.42.42"]]})+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):+ with dns_pinning.pinned_request(+ "http://ll.example/", allow_private_ips=True+ ):+ assert "ll.example" in dns_pinning._get_pins()diff --git a/tests/security/test_ssrf_redirect_bypass.py b/tests/security/test_ssrf_redirect_bypass.pyindex cf32a09909..8bdb020a63 100644--- a/tests/security/test_ssrf_redirect_bypass.py+++ b/tests/security/test_ssrf_redirect_bypass.py@@ -1359,3 +1359,62 @@ class TestSafeSessionBodyScopeThroughSend:assert isinstance(first, requests.Response)assert first.status_code == 200assert adapter.sent == ["http://127.0.0.1:5000/next"]+++class TestSafeSessionBlockLinkLocal:+ """``SafeSession(block_link_local=True)`` keeps the whole link-local+ range blocked under ``allow_private_ips=True``, on the initial request+ (``request``) and on every redirect hop (``send``). Real validator; the+ allow/deny pairs prove the flag is what decides."""++ LINK_LOCAL_URL = "http://169.254.42.42/latest/meta-data"++ @staticmethod+ def _prepared(url):+ prep = requests.PreparedRequest()+ prep.prepare_url(url, {})+ prep.prepare_method("GET")+ return prep++ def test_send_blocks_link_local_under_private_ips_when_set(self):+ session = SafeSession(allow_private_ips=True, block_link_local=True)++ with patch.object(+ requests.Session, "send", return_value=_make_response(200)+ ) as mock_send:+ with pytest.raises(ValueError, match="SSRF"):+ session.send(self._prepared(self.LINK_LOCAL_URL))+ mock_send.assert_not_called()++ def test_send_allows_link_local_under_private_ips_by_default(self):+ """Control: without the flag ``allow_private_ips=True`` keeps its+ existing behaviour (link-local reachable), so the block above is the+ flag's doing and callers that need today's semantics are unaffected.+ """+ session = SafeSession(allow_private_ips=True)++ with patch.object(+ requests.Session, "send", return_value=_make_response(200)+ ) as mock_send:+ session.send(self._prepared(self.LINK_LOCAL_URL))+ mock_send.assert_called_once()++ def test_request_blocks_link_local_when_set(self):+ session = SafeSession(allow_private_ips=True, block_link_local=True)++ with patch.object(+ requests.Session, "request", return_value=_make_response(200)+ ) as mock_request:+ with pytest.raises(ValueError, match="SSRF"):+ session.request("GET", self.LINK_LOCAL_URL)+ mock_request.assert_not_called()++ def test_rfc1918_still_allowed_with_block_link_local(self):+ """The carve-out must not take back the private grant itself."""+ session = SafeSession(allow_private_ips=True, block_link_local=True)++ with patch.object(+ requests.Session, "send", return_value=_make_response(200)+ ) as mock_send:+ session.send(self._prepared("http://192.168.1.1/api"))+ mock_send.assert_called_once()diff --git a/tests/settings/test_shipped_defaults_contracts.py b/tests/settings/test_shipped_defaults_contracts.pyindex 72c952ef59..1def87b13a 100644--- a/tests/settings/test_shipped_defaults_contracts.py+++ b/tests/settings/test_shipped_defaults_contracts.py@@ -573,6 +573,7 @@ class TestSecureByDefault:"research_library.allow_legacy_read_fallback","research_library.allow_shared_library","search.allow_private_engine_urls",+ "search.allow_private_result_fetch","security.allow_nat64",):assert key in by_key, f"{key} is no longer registered"diff --git a/tests/test_config_env_var_contracts.py b/tests/test_config_env_var_contracts.pyindex 7a79290dc8..a93345f4d1 100644--- a/tests/test_config_env_var_contracts.py+++ b/tests/test_config_env_var_contracts.py@@ -202,6 +202,7 @@ def test_registry_inventory_is_populated_and_holds_the_security_gates():"LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS","LDR_POLICY_ALLOW_UNPROTECTED_EGRESS","LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS",+ "LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH","LDR_SECURITY_ALLOW_NAT64","LDR_SECURITY_CORS_ALLOWED_ORIGINS","LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS",diff --git a/tests/web_search_engines/engines/test_full_search.py b/tests/web_search_engines/engines/test_full_search.pyindex 403a9ff1e2..626b6f5d34 100644--- a/tests/web_search_engines/engines/test_full_search.py+++ b/tests/web_search_engines/engines/test_full_search.py@@ -684,3 +684,305 @@ class TestFullSearchResultsClose:for call in mock_warn.call_args_list:assert "has no close() method" not in str(call)mock_web_search.close.assert_called_once()+++class TestAllowPrivateIps:+ """``FullSearchResults`` must accept an ``allow_private_ips`` flag and+ forward it to every ``validate_url`` call and to the download pipeline,+ so an engine holding a private result-fetch grant (e.g. a gated+ self-hosted SearXNG with the operator opt-in) is not blocked when+ fetching full content from internal result URLs, while ungated engines+ keep the strict default (issue #2477). Link-local stays blocked under+ the grant (``block_link_local=True`` on every call).+ """++ def test_default_is_false(self):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ engine = FullSearchResults(llm=Mock(), web_search=Mock())+ assert engine.allow_private_ips is False++ def test_stores_flag(self):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ engine = FullSearchResults(+ llm=Mock(), web_search=Mock(), allow_private_ips=True+ )+ assert engine.allow_private_ips is True++ def test_run_forwards_flag_to_validate_url(self):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_web_search = Mock()+ mock_web_search.invoke.return_value = [+ {"link": "http://192.168.1.5/wiki", "title": "Internal"},+ ]++ 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.validate_url",+ return_value=True,+ ) as mock_validate,+ patch(+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",+ return_value={"http://192.168.1.5/wiki": "content"},+ ),+ ):+ engine = FullSearchResults(+ llm=Mock(),+ web_search=mock_web_search,+ allow_private_ips=True,+ )+ engine.run("test query")++ assert mock_validate.call_args is not None+ assert mock_validate.call_args.kwargs.get("allow_private_ips") is True+ assert mock_validate.call_args.kwargs.get("block_link_local") is True++ def test_run_defaults_flag_false_to_validate_url(self):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_web_search = Mock()+ mock_web_search.invoke.return_value = [+ {"link": "https://example.com/1", "title": "Result 1"},+ ]++ 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.validate_url",+ return_value=True,+ ) as mock_validate,+ patch(+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",+ return_value={"https://example.com/1": "content"},+ ),+ ):+ engine = FullSearchResults(llm=Mock(), web_search=mock_web_search)+ engine.run("test query")++ assert mock_validate.call_args.kwargs.get("allow_private_ips") is False+ assert mock_validate.call_args.kwargs.get("block_link_local") is True++ def test_run_with_default_flag_blocks_private_url(self):+ """NEGATIVE: without the opt-in, a private result URL is rejected by+ the real ``validate_url`` and never reaches the download pipeline."""+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_web_search = Mock()+ mock_web_search.invoke.return_value = [+ {"link": "http://192.168.1.5/wiki", "title": "Internal"},+ ]++ 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,+ ):+ engine = FullSearchResults(llm=Mock(), web_search=mock_web_search)+ results = engine.run("test query")++ mock_batch.assert_not_called()+ assert results[0]["full_content"] is None++ def test_run_forwards_private_ip_opt_in_to_batch_fetch(self):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_web_search = Mock()+ mock_web_search.invoke.return_value = [+ {"link": "http://192.168.1.5/wiki", "title": "Internal"},+ ]++ 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.validate_url",+ return_value=True,+ ),+ patch(+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",+ return_value={"http://192.168.1.5/wiki": "content"},+ ) as mock_batch,+ ):+ engine = FullSearchResults(+ llm=Mock(),+ web_search=mock_web_search,+ allow_private_ips=True,+ )+ engine.run("test query")++ assert mock_batch.call_args.kwargs.get("allow_private_ips") is True+ assert mock_batch.call_args.kwargs.get("block_link_local") is True++ def test_get_full_content_forwards_flag_to_validate_url(self):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ with (+ patch(+ "local_deep_research.web_search_engines.engines.full_search.validate_url",+ return_value=True,+ ) as mock_validate,+ patch(+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",+ return_value={"http://192.168.1.5/wiki": "content"},+ ),+ ):+ engine = FullSearchResults(+ llm=Mock(),+ web_search=Mock(),+ allow_private_ips=True,+ )+ engine._get_full_content(+ [{"link": "http://192.168.1.5/wiki", "title": "Internal"}]+ )++ assert mock_validate.call_args is not None+ assert mock_validate.call_args.kwargs.get("allow_private_ips") is True+ assert mock_validate.call_args.kwargs.get("block_link_local") is True++ def test_get_full_content_defaults_private_ips_to_blocked_in_batch_fetch(+ self,+ ):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ with (+ patch(+ "local_deep_research.web_search_engines.engines.full_search.validate_url",+ return_value=True,+ ),+ patch(+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",+ return_value={"https://example.com/1": "content"},+ ) as mock_batch,+ ):+ engine = FullSearchResults(llm=Mock(), web_search=Mock())+ engine._get_full_content(+ [{"link": "https://example.com/1", "title": "Result 1"}]+ )++ assert mock_batch.call_args.kwargs.get("allow_private_ips") is False+ assert mock_batch.call_args.kwargs.get("block_link_local") is True++ def test_run_with_flag_fetches_rfc1918_url_with_real_validator(self):+ """POSITIVE against the real ``validate_url`` (IP literal, no DNS):+ with the grant an RFC1918 result URL reaches the download pipeline,+ so the link-local carve-out below does not take back the grant."""+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_web_search = Mock()+ mock_web_search.invoke.return_value = [+ {"link": "http://192.168.1.5/wiki", "title": "Internal"},+ ]++ 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",+ return_value={"http://192.168.1.5/wiki": "content"},+ ) as mock_batch,+ ):+ engine = FullSearchResults(+ llm=Mock(),+ web_search=mock_web_search,+ allow_private_ips=True,+ )+ results = engine.run("test query")++ mock_batch.assert_called_once()+ assert mock_batch.call_args.args[0] == ["http://192.168.1.5/wiki"]+ assert results[0]["full_content"] == "content"++ def test_run_with_flag_still_blocks_link_local_url(self):+ """NEGATIVE: even with the grant, the rest of 169.254.0.0/16 (provider+ metadata outside ``ALWAYS_BLOCKED_METADATA_IPS``, e.g. Scaleway's+ 169.254.42.42) is rejected by the real ``validate_url`` via+ ``block_link_local=True``; the downloader is never invoked."""+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_web_search = Mock()+ mock_web_search.invoke.return_value = [+ {"link": "http://169.254.42.42/latest/meta-data", "title": "M"},+ ]++ 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,+ ):+ engine = FullSearchResults(+ llm=Mock(),+ web_search=mock_web_search,+ allow_private_ips=True,+ )+ results = engine.run("test query")++ mock_batch.assert_not_called()+ assert results[0]["full_content"] is None++ def test_get_full_content_with_flag_still_blocks_link_local_url(self):+ """NEGATIVE for the second call site: ``_get_full_content`` applies+ the same link-local carve-out under the grant."""+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ with patch(+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",+ ) as mock_batch:+ engine = FullSearchResults(+ llm=Mock(),+ web_search=Mock(),+ allow_private_ips=True,+ )+ items = engine._get_full_content(+ [+ {+ "link": "http://169.254.42.42/latest/meta-data",+ "title": "M",+ }+ ]+ )++ mock_batch.assert_not_called()+ assert items[0]["full_content"] is Nonediff --git a/tests/web_search_engines/engines/test_full_search_coverage.py b/tests/web_search_engines/engines/test_full_search_coverage.pyindex f31a90f677..fa7ae93397 100644--- a/tests/web_search_engines/engines/test_full_search_coverage.py+++ b/tests/web_search_engines/engines/test_full_search_coverage.py@@ -118,7 +118,9 @@ class TestGetFullContent:{"link": "http://192.168.1.1/bad", "title": "Bad"},]- def mock_validate(url):+ def mock_validate(url, allow_private_ips=False, block_link_local=False):+ assert allow_private_ips is False+ assert block_link_local is Truereturn "example.com" in urlwith patch(diff --git a/tests/web_search_engines/engines/test_search_engine_searxng.py b/tests/web_search_engines/engines/test_search_engine_searxng.pyindex dba81cd289..329d303c80 100644--- a/tests/web_search_engines/engines/test_search_engine_searxng.py+++ b/tests/web_search_engines/engines/test_search_engine_searxng.py@@ -3104,6 +3104,7 @@ SEARXNG_MODULE = (INSTANCE_URL_ENV = "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL"GATE_ENV = "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS"ALLOWLIST_ENV = "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST"+RESULT_FETCH_ENV = "LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH"class TestAllowPrivateIpsDerivation:@@ -3267,6 +3268,67 @@ class TestAllowPrivateIpsDerivation:assert not any(GATE_ENV in msg for msg in hints)+class TestAllowPrivateResultFetchDerivation:+ """The private RESULT-URL fetch grant is a separate, narrower opt-in:+ it needs the env-only ``LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH`` flag AND+ the instance approval, never either one alone (issue #2477).++ The instance approval is satisfied by every env-locked (compose)+ deployment, and a public engine proxies the public web, so the instance+ grant alone must not extend to whatever private URLs the index returns.+ """++ @staticmethod+ def _resolve(url="http://localhost:8080"):+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ resolve_searxng_allow_private_result_fetch,+ )++ return resolve_searxng_allow_private_result_fetch(url)++ def test_default_refuses_private_result_fetch(self):+ assert self._resolve() is False++ def test_opt_in_alone_grants_nothing(self, monkeypatch):+ """Without any instance approval the engine may not even reach its+ own private instance; the result-fetch opt-in cannot open more."""+ monkeypatch.setenv(RESULT_FETCH_ENV, "true")+ assert self._resolve() is False++ def test_blanket_instance_gate_alone_grants_nothing(self, monkeypatch):+ monkeypatch.setenv(GATE_ENV, "true")+ assert self._resolve() is False++ def test_env_locked_instance_alone_grants_nothing(self, monkeypatch):+ """The bundled docker-compose case: an env-locked instance URL+ approves the instance itself, not private result URLs."""+ monkeypatch.setenv(INSTANCE_URL_ENV, "http://searxng:8080")+ assert self._resolve() is False++ def test_opt_in_with_blanket_instance_gate_grants(self, monkeypatch):+ monkeypatch.setenv(GATE_ENV, "true")+ monkeypatch.setenv(RESULT_FETCH_ENV, "true")+ assert self._resolve() is True++ def test_opt_in_with_env_locked_instance_grants(self, monkeypatch):+ monkeypatch.setenv(INSTANCE_URL_ENV, "http://searxng:8080")+ monkeypatch.setenv(RESULT_FETCH_ENV, "true")+ assert self._resolve() is True++ def test_opt_in_with_allowlisted_origin_grants_for_that_origin(+ self, monkeypatch+ ):+ monkeypatch.setenv(ALLOWLIST_ENV, "http://localhost:8080")+ monkeypatch.setenv(RESULT_FETCH_ENV, "true")+ assert self._resolve("http://localhost:8080") is True+ assert self._resolve("http://localhost:9090") is False++ def test_opt_in_false_value_refuses(self, monkeypatch):+ monkeypatch.setenv(GATE_ENV, "true")+ monkeypatch.setenv(RESULT_FETCH_ENV, "false")+ assert self._resolve() is False++class TestEngineForwardsDerivedAllowPrivateIps:"""The engine forwards the DERIVED flag to safe_get (not a hard-coded True)."""@@ -3426,3 +3488,306 @@ class TestPrivateUrlBlockedHint:assert not any(GATE_ENV in msg for msg in hints), (f"unexpected private-URL hint on a public failure: {hints}")+++class TestFullSearchPrivateIpGate:+ """The factory's full-search wrapper, the only full-content path, gets+ the engine's resolved RESULT-URL fetch grant (instance approval AND the+ env-only ``LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH`` opt-in) as its+ ``allow_private_ips``, never a hardcoded value and never the instance+ gate alone (issue #2477)."""++ FULL_SEARCH_MODULE = (+ "local_deep_research.web_search_engines.engines.full_search"+ )+ # What search_config() injects for searxng from the engine registry.+ WRAPPER_CONFIG = {+ "full_search_module": ".engines.full_search",+ "full_search_class": "FullSearchResults",+ }++ def _make_engine(self, monkeypatch, *, instance_gate, result_fetch):+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ for env, enabled in (+ (GATE_ENV, instance_gate),+ (RESULT_FETCH_ENV, result_fetch),+ ):+ if enabled:+ monkeypatch.setenv(env, "true")+ else:+ monkeypatch.delenv(env, raising=False)++ with patch(f"{SEARXNG_MODULE}.safe_get") as mock_get:+ mock_get.return_value = Mock(status_code=200)+ return SearXNGSearchEngine(+ instance_url="http://localhost:8080",+ llm=Mock(),+ )++ def _wrap(self, engine):+ """Build the wrapper the way ``create_search_engine`` does once full+ content is on: ``_create_full_search_wrapper`` with the registry's+ module/class for searxng and no caller params."""+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )+ from local_deep_research.web_search_engines.search_engine_factory import (+ _create_full_search_wrapper,+ )++ wrapper = _create_full_search_wrapper(+ "searxng", engine, dict(self.WRAPPER_CONFIG), engine.llm, {}+ )+ assert isinstance(wrapper, FullSearchResults)+ assert wrapper.web_search is engine+ return wrapper++ def _run_full_search(self, wrapper, link):+ """Run the wrapper on one result URL with the REAL ``validate_url``;+ return the results and the mocked downloader."""+ wrapper.web_search = Mock()+ wrapper.web_search.invoke.return_value = [+ {"link": link, "title": "Result"},+ ]+ with (+ patch(f"{self.FULL_SEARCH_MODULE}.QUALITY_CHECK_DDG_URLS", False),+ patch(+ f"{self.FULL_SEARCH_MODULE}.batch_fetch_and_extract",+ return_value={link: "content"},+ ) as mock_batch,+ ):+ results = wrapper.run("test query")+ return results, mock_batch++ def test_gated_instance_with_opt_in_propagates_private_result_fetch(+ self, monkeypatch+ ):+ engine = self._make_engine(+ monkeypatch, instance_gate=True, result_fetch=True+ )+ assert engine._allow_private_ips is True+ assert engine.allow_private_result_fetch is True+ assert self._wrap(engine).allow_private_ips is True++ def test_env_locked_instance_without_opt_in_keeps_result_fetch_strict(+ self, monkeypatch+ ):+ """NEGATIVE (the bundled docker-compose case): an env-locked+ instance URL approves the instance itself but must NOT extend to+ fetching private result URLs without the explicit opt-in."""+ monkeypatch.setenv(INSTANCE_URL_ENV, "http://searxng:8080")+ engine = self._make_engine(+ monkeypatch, instance_gate=False, result_fetch=False+ )+ assert engine._allow_private_ips is True+ assert engine.allow_private_result_fetch is False+ assert self._wrap(engine).allow_private_ips is False++ def test_opt_in_without_instance_gate_grants_nothing(self, monkeypatch):+ """NEGATIVE: the opt-in alone (ungated / public instance) opens+ nothing."""+ engine = self._make_engine(+ monkeypatch, instance_gate=False, result_fetch=True+ )+ assert engine._allow_private_ips is False+ assert engine.allow_private_result_fetch is False+ assert self._wrap(engine).allow_private_ips is False++ def test_ungated_instance_does_not_get_private_ip_trust(self, monkeypatch):+ """NEGATIVE: a default/public (ungated) instance must NOT have its+ full-content fetches trusted with private IPs."""+ engine = self._make_engine(+ monkeypatch, instance_gate=False, result_fetch=False+ )+ assert engine.allow_private_result_fetch is False+ assert self._wrap(engine).allow_private_ips is False++ def test_engine_holds_the_grant_but_does_not_self_wrap(self, monkeypatch):+ """The engine only resolves the grant; it builds no ``full_search``+ of its own and ``_get_full_content`` stays a pass-through, so the+ factory wrapper is the sole fetcher the grant can reach."""+ engine = self._make_engine(+ monkeypatch, instance_gate=True, result_fetch=True+ )+ assert not hasattr(engine, "full_search")+ items = [{"title": "T", "link": "http://192.168.1.5/wiki"}]+ assert engine._get_full_content(items) is items++ def test_ungated_instance_full_search_blocks_private_url(self, monkeypatch):+ """NEGATIVE end-to-end: with the grant closed, the real+ ``validate_url`` still rejects a private result URL, so the+ downloader is never invoked for it."""+ engine = self._make_engine(+ monkeypatch, instance_gate=False, result_fetch=False+ )+ results, mock_batch = self._run_full_search(+ self._wrap(engine), "http://192.168.1.5/wiki"+ )+ mock_batch.assert_not_called()+ assert results[0]["full_content"] is None++ def test_env_locked_instance_full_search_blocks_private_url(+ self, monkeypatch+ ):+ """NEGATIVE end-to-end for the compose case: instance approved via+ the env-lock, no opt-in, so a private result URL is still rejected+ by the real ``validate_url``."""+ monkeypatch.setenv(INSTANCE_URL_ENV, "http://searxng:8080")+ engine = self._make_engine(+ monkeypatch, instance_gate=False, result_fetch=False+ )+ assert engine._allow_private_ips is True+ results, mock_batch = self._run_full_search(+ self._wrap(engine), "http://192.168.1.5/wiki"+ )+ mock_batch.assert_not_called()+ assert results[0]["full_content"] is None++ def test_granted_instance_full_search_fetches_private_url(+ 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."""+ engine = self._make_engine(+ monkeypatch, instance_gate=True, result_fetch=True+ )+ results, mock_batch = self._run_full_search(+ self._wrap(engine), "http://192.168.1.5/wiki"+ )+ mock_batch.assert_called_once()+ assert mock_batch.call_args.args[0] == ["http://192.168.1.5/wiki"]+ assert mock_batch.call_args.kwargs.get("allow_private_ips") is True+ assert mock_batch.call_args.kwargs.get("block_link_local") is True+ assert results[0]["full_content"] == "content"++ def test_gated_instance_still_blocks_cloud_metadata_url(self, monkeypatch):+ """Even with both approvals, the ``ALWAYS_BLOCKED_METADATA_IPS``+ literals stay hard-blocked."""+ engine = self._make_engine(+ monkeypatch, instance_gate=True, result_fetch=True+ )+ results, mock_batch = self._run_full_search(+ self._wrap(engine), "http://169.254.169.254/latest/meta-data"+ )+ mock_batch.assert_not_called()+ assert results[0]["full_content"] is None++ def test_gated_instance_still_blocks_link_local_url(self, monkeypatch):+ """Even with both approvals, the rest of 169.254.0.0/16 (provider+ metadata outside the six literals, e.g. Scaleway's 169.254.42.42)+ stays blocked via ``block_link_local=True``."""+ engine = self._make_engine(+ monkeypatch, instance_gate=True, result_fetch=True+ )+ results, mock_batch = self._run_full_search(+ self._wrap(engine), "http://169.254.42.42/latest/meta-data"+ )+ mock_batch.assert_not_called()+ assert results[0]["full_content"] is None++ def test_open_grant_logs_redacted_instance(+ self, monkeypatch, loguru_caplog+ ):+ """An open grant is an allow, so it leaves one INFO line naming the+ opt-in and the redacted instance origin."""+ with loguru_caplog.at_level("INFO"):+ self._make_engine(+ monkeypatch, instance_gate=True, result_fetch=True+ )+ assert RESULT_FETCH_ENV in loguru_caplog.text+ assert "http://localhost:8080" in loguru_caplog.text++ def test_closed_grant_logs_nothing(self, monkeypatch, loguru_caplog):+ """Instance approved but no opt-in: no grant line."""+ with loguru_caplog.at_level("INFO"):+ self._make_engine(+ monkeypatch, instance_gate=True, result_fetch=False+ )+ assert RESULT_FETCH_ENV not in loguru_caplog.text+++class TestFullSearchPrivateIpGateFactoryPath:+ """End to end through ``get_search``: with snippets-only off the factory+ wraps the real engine in ``FullSearchResults`` and the grant travels+ with it (issue #2477, on the path #6492 made the only one)."""++ def _get_search(self, monkeypatch, *, instance_gate, result_fetch):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )+ from local_deep_research.web_search_engines.search_engine_factory import (+ get_search,+ )++ for env, enabled in (+ (GATE_ENV, instance_gate),+ (RESULT_FETCH_ENV, result_fetch),+ ):+ if enabled:+ monkeypatch.setenv(env, "true")+ else:+ monkeypatch.delenv(env, raising=False)++ # The same snapshot shape as the factory's own wrapper end-to-end+ # tests: search_config() registers an engine only when the snapshot+ # carries a key for it.+ settings_snapshot = {+ "search.tool": {"value": "searxng"},+ "search.engine.web.searxng.supports_full_search": {+ "value": True,+ "ui_element": "checkbox",+ },+ }+ with patch(f"{SEARXNG_MODULE}.safe_get") as mock_get:+ mock_get.return_value = Mock(status_code=200)+ wrapper = get_search(+ search_tool="searxng",+ llm_instance=Mock(),+ search_snippets_only=False,+ settings_snapshot=settings_snapshot,+ programmatic_mode=True,+ )+ assert isinstance(wrapper, FullSearchResults)+ assert isinstance(wrapper.web_search, SearXNGSearchEngine)+ return wrapper++ def test_gated_instance_with_opt_in_reaches_the_wrapper(self, monkeypatch):+ wrapper = self._get_search(+ monkeypatch, instance_gate=True, result_fetch=True+ )+ assert wrapper.web_search.allow_private_result_fetch is True+ assert wrapper.allow_private_ips is True++ def test_env_locked_instance_without_opt_in_stays_strict(self, monkeypatch):+ """NEGATIVE (compose case) on the production path."""+ monkeypatch.setenv(INSTANCE_URL_ENV, "http://searxng:8080")+ wrapper = self._get_search(+ monkeypatch, instance_gate=False, result_fetch=False+ )+ assert wrapper.web_search._allow_private_ips is True+ assert 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.+ """+ wrapper = self._get_search(+ monkeypatch, instance_gate=True, result_fetch=True+ )+ assert wrapper.egress_context is None+ assert wrapper._downloader_allow_private_ips() is Truediff --git a/tests/web_search_engines/test_factory_full_search_wrapper.py b/tests/web_search_engines/test_factory_full_search_wrapper.pyindex 5e175e3541..bf3c045a61 100644--- a/tests/web_search_engines/test_factory_full_search_wrapper.py+++ b/tests/web_search_engines/test_factory_full_search_wrapper.py@@ -533,3 +533,85 @@ class TestRegistryFullSearchWrapperEndToEnd:assert isinstance(result, FullSearchResults)assert result.language == "German"assert result.web_search.language == "de"+++# ---------------------------------------------------------------------------+# Tests: the private result-fetch grant on the wrapper (#2477)+# ---------------------------------------------------------------------------++_WRAPPER_CONFIG = {+ "full_search_module": ".engines.full_search",+ "full_search_class": "FullSearchResults",+}+++class _GrantedEngine(_MockBaseEngine):+ """Engine stub that resolved a private result-fetch grant, the way+ SearXNG does from the instance approval plus the env-only opt-in."""++ allow_private_result_fetch = True+++class TestWrapperPrivateResultFetchGrant:+ """``FullSearchResults.allow_private_ips`` is set from the base engine's+ resolved grant only (``BaseSearchEngine.allow_private_result_fetch``),+ defaults to False, and cannot be opened from caller params."""++ def _wrap(self, base_engine, mock_llm, params=None):+ return _create_full_search_wrapper(+ "test_engine",+ base_engine,+ dict(_WRAPPER_CONFIG),+ mock_llm,+ params or {},+ )++ def test_engine_without_grant_keeps_wrapper_strict(self, mock_llm):+ engine = _MockBaseEngine(llm=mock_llm, programmatic_mode=True)+ wrapper = self._wrap(engine, mock_llm)+ assert isinstance(wrapper, FullSearchResults)+ assert wrapper.allow_private_ips is False++ def test_engine_grant_reaches_wrapper(self, mock_llm):+ engine = _GrantedEngine(llm=mock_llm, programmatic_mode=True)+ wrapper = self._wrap(engine, mock_llm)+ assert isinstance(wrapper, FullSearchResults)+ assert wrapper.web_search is engine+ assert wrapper.allow_private_ips is True++ def test_caller_params_cannot_open_the_grant(self, mock_llm):+ """The signature filter would otherwise forward a stray+ ``allow_private_ips`` kwarg; the engine's own resolution is the+ only source."""+ engine = _MockBaseEngine(llm=mock_llm, programmatic_mode=True)+ wrapper = self._wrap(engine, mock_llm, {"allow_private_ips": True})+ assert wrapper.allow_private_ips is False++ @pytest.mark.parametrize(+ "grant", ["true", 1, None], ids=["str", "int", "none"]+ )+ def test_non_bool_grant_fails_closed(self, mock_llm, grant):+ engine = _MockBaseEngine(llm=mock_llm, programmatic_mode=True)+ engine.allow_private_result_fetch = grant+ assert self._wrap(engine, mock_llm).allow_private_ips is False++ def test_non_engine_base_fails_closed(self, mock_llm):+ """A base that is not a BaseSearchEngine (attribute access on a+ Mock yields a truthy Mock) hands over no grant."""+ assert self._wrap(Mock(), mock_llm).allow_private_ips is False++ def test_registry_engines_hold_no_grant_by_default(self):+ """Only an engine that resolves a grant in ``__init__`` (SearXNG)+ can hand one over; the class default everywhere else stays False,+ so the other wrapped engines are untouched."""+ from local_deep_research.security.module_whitelist import (+ get_safe_module_class,+ )++ assert BaseSearchEngine.allow_private_result_fetch is False+ for name in FULL_SEARCH_ENGINES:+ entry = ENGINE_REGISTRY[name]+ engine_class = get_safe_module_class(+ entry.module_path, entry.class_name+ )+ assert engine_class.allow_private_result_fetch is False, namediff --git a/tests/web_search_engines/test_search_engine_base.py b/tests/web_search_engines/test_search_engine_base.pyindex 1660726b80..951feb0e66 100644--- a/tests/web_search_engines/test_search_engine_base.py+++ b/tests/web_search_engines/test_search_engine_base.py@@ -1186,6 +1186,50 @@ class TestInitFullSearchForwardsSettingsSnapshot:assert snap is None or snap == {}+class TestInitFullSearchForwardsPrivateResultFetchGrant:+ """Issue #2477: ``_init_full_search`` must hand the engine's own+ ``allow_private_result_fetch`` to ``FullSearchResults`` the same way+ the factory's ``_create_full_search_wrapper`` does, so an engine built+ through this seam does not lose the grant silently. Only the explicit+ boolean ``True`` opens it."""++ def _construction_kwargs(self, **class_attrs):+ from unittest.mock import patch++ from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )++ class _Engine(BaseSearchEngine):+ def _get_previews(self, query):+ return []++ def _get_full_content(self, items):+ return items++ for name, value in class_attrs.items():+ setattr(_Engine, name, value)+ engine = _Engine(llm=Mock(), include_full_content=True)+ with patch(+ "local_deep_research.web_search_engines.engines.full_search.FullSearchResults"+ ) as mock_full_search:+ engine._init_full_search(web_search=Mock())+ return mock_full_search.call_args.kwargs++ def test_default_engine_hands_over_no_grant(self):+ kwargs = self._construction_kwargs()+ assert kwargs.get("allow_private_ips") is False++ def test_granted_engine_hands_the_grant_over(self):+ kwargs = self._construction_kwargs(allow_private_result_fetch=True)+ assert kwargs.get("allow_private_ips") is True++ @pytest.mark.parametrize("grant", ["true", 1, None])+ def test_only_an_explicit_boolean_true_opens_it(self, grant):+ kwargs = self._construction_kwargs(allow_private_result_fetch=grant)+ assert kwargs.get("allow_private_ips") is False++# =============================================================================# Runtime egress scope verification tests# =============================================================================