~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(policy): use static engine class flags for egress scope decisions (#4471)
LearningCircuit7f9266c712f8
diff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.mdindex 5a80d6da52..5868107d83 100644--- a/src/local_deep_research/security/egress/README.md+++ b/src/local_deep_research/security/egress/README.md@@ -27,10 +27,10 @@ engines/destinations are permitted.| Scope | Meaning ||---|---|-| `adaptive` *(default)* | **Follow the primary engine.** A private primary → behaves PRIVATE_ONLY; a public primary → PUBLIC_ONLY; a meta-picker (`auto`/`parallel`/`meta`) or unclassifiable primary → BOTH. Resolved to a concrete scope at run start. |+| `adaptive` *(default)* | **Follow the primary engine.** A private primary → behaves PRIVATE_ONLY; a public primary → PUBLIC_ONLY; a meta-picker (`auto`/`parallel`/`meta`) or unclassifiable primary → BOTH. Resolved to a concrete scope at run start. Classification uses the engine's **static class flags** (e.g. SearXNG is always public because it queries the internet), not the network location of its server — with one asymmetric **fail-up** exception: a local-nature engine (Elasticsearch, Paperless) whose configured URL resolves to a *public* host is reclassified public, because querying it sends data off the box. The override only ever tightens. || `both` | Any classified engine (the pre-policy behaviour). || `public_only` | Only public web/academic engines. Local collections excluded. |-| `private_only` | Only local engines (library, collections, local SearXNG/Ollama). **Forces local LLM + embeddings inference** so nothing leaves the box. |+| `private_only` | Only local engines (library, collections, Ollama). **Forces local LLM + embeddings inference** so nothing leaves the box. Note: a locally-hosted SearXNG is still treated as *public* because it proxies to internet search engines — only its *connection target* is local, not its *data source*. || `strict` | Only the user's *primary* engine; no expansion at all. Incompatible with a meta-picker primary. |Two independent toggles refine inference locality (and are **implied** under@@ -267,8 +267,22 @@ Each cell is the decision produced by the real `evaluate_*` logic / PEP for that|---|---|| **private_only blocks ALL external data egress** | engine selection (`evaluate_engine` → `scope_mismatch_private_only`), URL/library/webhook fetch (`evaluate_url` PRIVATE_ONLY branch), LLM (`require_local_llm` forced in `context_from_snapshot` → `provider_cloud_only`), embeddings (`require_local_embeddings` forced → `provider_cloud`), and the raw-socket audit-hook net armed for PRIVATE_ONLY (`audit_hook.py`). No vector permits a public destination. || **public_only stays open to public sources** | public engines pass `evaluate_engine` (private collections BLOCKED via `scope_mismatch_public_only`); `evaluate_url` allows public hosts, blocks private; inference is NOT scope-forced (toggles still apply); the audit hook stays INACTIVE (only PRIVATE_ONLY/STRICT arm it) so legitimate local infra traffic — local Ollama, settings DB — is never falsely blocked. |-| **adaptive just matches the primary engine** | `_resolve_adaptive_scope`: private primary → PRIVATE_ONLY, public primary → PUBLIC_ONLY, meta-picker/unknown → BOTH. A registered local retriever primary also resolves PRIVATE_ONLY. Resolved once at run start; the stored `EgressContext` carries the concrete scope, not ADAPTIVE. |+| **adaptive just matches the primary engine** | `_resolve_adaptive_scope`: private primary → PRIVATE_ONLY, public primary → PUBLIC_ONLY, meta-picker/unknown → BOTH. A registered local retriever primary also resolves PRIVATE_ONLY. Uses the engine's **static class flags** (`is_public`/`is_local` on the Python class), not the network location of the engine's server — so a locally-hosted SearXNG (class `is_public=True`) resolves to PUBLIC_ONLY. Resolved once at run start; the stored `EgressContext` carries the concrete scope, not ADAPTIVE. || **A private RAG collection as ADAPTIVE primary pulls the whole run local** | `_resolve_collection_is_public` defaults private → `_engine_bucket` returns local → adaptive resolves PRIVATE_ONLY → forces local LLM + embeddings. Mark the collection `is_public` to opt into cloud inference. || **Cloud-metadata is never reachable, under any scope** | `evaluate_url` runs `is_ip_blocked(..., allow_private_ips=True)` before scope logic; `_classify_host` applies the same metadata block on BOTH the literal-IP and DNS-resolved paths; NAT64-wrapped metadata is reclassified PUBLIC. |+### Advisory candidate pre-filter++The meta/parallel engines call `filter_candidates_by_egress(names,+snapshot)`, which handles the snapshot plumbing (scope/primary extraction,+context build, fail-open on any error) and delegates to+`filter_engines_by_egress(names, ctx, snapshot)`, which strips engines the scope+**actively denies** (scope mismatches, STRICT violations, unclassified+registry engines) from meta/parallel LLM candidate lists, so selection+slots aren't wasted on engines the factory would refuse. It is advisory,+not enforcement: names unknown to the static registry are KEPT (they may+be retriever-backed or dynamically injected engines the factory evaluates+via its own path) — the pre-filter is never stricter than the factory PEP+it fronts.+> **Notification footnote.** The notification PEP (`notifications/manager.py` `_filter_urls_by_egress_policy`) gates **http/https** webhook URLs through `evaluate_url`. Apprise vendor schemes (`slack://`, `discord://`, `telegram://`, `mailto://`, …) dispatch to external vendor APIs: under **PRIVATE_ONLY** (incl. Adaptive-private) they are **refused outright** (we can't verify a vendor token is local — fail closed; address a self-hosted notifier by its `http(s)://` URL, which `evaluate_url` allows as a private host). Under the other scopes they pass the URL gate (the modeled threat there is internal-http SSRF, not vendor APIs); the audit-hook net is an additional backstop for the actual connection when armed.diff --git a/src/local_deep_research/security/egress/__init__.py b/src/local_deep_research/security/egress/__init__.pyindex f272f1f343..8d053f6314 100644--- a/src/local_deep_research/security/egress/__init__.py+++ b/src/local_deep_research/security/egress/__init__.py@@ -24,6 +24,8 @@ from .policy import (evaluate_llm_endpoint,evaluate_retriever,evaluate_url,+ filter_candidates_by_egress,+ filter_engines_by_egress,)from .audit_hook import (active_egress_context,@@ -47,6 +49,8 @@ __all__ = ["evaluate_llm_endpoint","evaluate_retriever","evaluate_url",+ "filter_candidates_by_egress",+ "filter_engines_by_egress",# audit hook / process-wide PEP"active_egress_context","clear_active_context",diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.pyindex 79336956ff..cbfffda2bc 100644--- a/src/local_deep_research/security/egress/policy.py+++ b/src/local_deep_research/security/egress/policy.py@@ -401,12 +401,22 @@ def _engine_bucket(metadata: Optional[dict] = None,allow_dns: bool = True,):- """Return the ``(is_public, is_local)`` tri-state for an engine, WITHOUT- any scope logic. Shared by ``evaluate_engine`` (for the bucket check)- and adaptive-scope resolution (to classify the primary engine).-- - Static engines: read declared ``is_public``/``is_local`` flags, with- a configurable-URL override classified by DNS.+ """Return the ``(is_public, is_local)`` classification for an engine based+ on its **Python class flags**, with a fail-up URL override.++ The class-level ``is_public`` / ``is_local`` flags express the engine's+ *nature* — whether it queries the public internet or searches local data —+ regardless of where the engine's server happens to be hosted. This is used+ by ``evaluate_engine`` and ``_resolve_adaptive_scope`` so that e.g. a+ locally-hosted SearXNG (which proxies to Google/Bing) is still treated as+ a public engine.++ The URL override is asymmetric and can only make the classification+ MORE restrictive: a local-nature engine whose ``url_setting`` resolves+ to a public host is reclassified public (queries would leave the box),+ while a public-nature engine on a local URL stays public.++ - Static engines: read declared ``is_public``/``is_local`` flags directly.- ``library`` / ``collection_<uuid>``: per-collection ``is_public``flag (from ``metadata`` when the caller has the engine config, else adirect DB lookup), defaulting private.@@ -434,20 +444,125 @@ def _engine_bucket(return is_public, Truereturn None, Noneis_public, is_local, url_setting = _engine_flags(engine_cls)- # Dynamic URL classification overrides static flags when the engine- # exposes a user-configurable URL (searxng instance, Elasticsearch host).- if url_setting:+ # Fail-up URL override (asymmetric, only ever MORE restrictive): a+ # local-data engine (Elasticsearch, Paperless) whose configured URL+ # resolves to a PUBLIC host is reclassified as public — querying it+ # sends the user's queries off the box, so PRIVATE_ONLY must deny it+ # at selection time (matching pre-static-flags behavior). The reverse+ # direction is deliberately NOT applied: a public-nature engine+ # (SearXNG) hosted on localhost stays public, because its data source+ # is the internet regardless of where the proxy runs.+ if url_setting and is_local is True and is_public is not True:host_classification = _classify_engine_url(url_setting, settings_snapshot, ctx, allow_dns=allow_dns)- if host_classification is True:- return False, Trueif host_classification is False:+ # False from _classify_engine_url == "connect target is a+ # PUBLIC host" -> fail up to public.return True, False- # None → fall back to static flagsreturn is_public, is_local+# Denial reasons that justify dropping an engine from an LLM candidate+# list. Only ACTIVE policy denials qualify — see filter_engines_by_egress.+_PREFILTER_STRIP_REASONS = frozenset(+ {+ "scope_mismatch_public_only",+ "scope_mismatch_private_only",+ "strict_not_primary",+ "strict_with_meta_picker",+ # Registered engine without classification flags: the factory's+ # evaluate_engine call fails it closed too, so stripping matches+ # enforcement exactly.+ "unclassified",+ }+)+++def filter_engines_by_egress(+ engine_names: list[str],+ ctx: EgressContext,+ settings_snapshot: dict,+) -> list[str]:+ """ADVISORY pre-filter for a candidate engine list: remove engines the+ egress scope actively denies so the LLM doesn't waste selection slots+ on them. Uses the engine's static class flags (``is_public`` /+ ``is_local``) — a locally-hosted SearXNG is still treated as public+ because it queries the internet.++ This is a UX optimization in FRONT of the factory PEP, not an+ enforcement point — so it must never be STRICTER than the factory.+ Names unknown to the static registry (``engine_unknown``) are KEPT+ (except under STRICT, where the not-the-primary gate fires before the+ registry lookup — exactly as it does in the factory):+ they may be retriever-backed or dynamically injected engines that the+ factory evaluates via its own retriever path; dropping them here would+ silently hide legitimate engines from meta/parallel selection. The+ factory still denies anything truly disallowed at instantiation.++ Callers: parallel/meta engine candidate lists, LangGraph tool builder,+ or any code that builds a selection set before presenting it to an LLM.+ """+ allowed: list[str] = []+ for name in engine_names:+ decision = evaluate_engine(+ name, ctx, settings_snapshot=settings_snapshot+ )+ if decision.allowed or decision.reason not in _PREFILTER_STRIP_REASONS:+ allowed.append(name)+ return allowed+++def filter_candidates_by_egress(+ engine_names: list[str],+ settings_snapshot: Optional[dict],+) -> list[str]:+ """Best-effort scope pre-filter for an LLM candidate list.++ Wraps ``filter_engines_by_egress`` with the snapshot plumbing the meta+ and parallel engines share: read ``policy.egress_scope`` /+ ``search.tool`` from the snapshot (flat or ``{"value": ...}`` shaped),+ build the context, filter. Returns the input list unchanged when the+ snapshot is missing, the scope is BOTH (nothing to strip), or anything+ fails — the factory PEP still enforces at child instantiation, so this+ helper must never break engine selection.+ """+ if not settings_snapshot:+ return engine_names+ try:+ scope_raw = str(+ _get_setting_value(+ settings_snapshot, "policy.egress_scope", DEFAULT_EGRESS_SCOPE+ )+ or DEFAULT_EGRESS_SCOPE+ ).lower()+ # BOTH (or an unrecognized value) strips nothing at selection time;+ # adaptive is included because it can RESOLVE to a restrictive scope.+ if scope_raw not in (+ "private_only",+ "public_only",+ "strict",+ "adaptive",+ ):+ return engine_names+ primary = (+ _get_setting_value(settings_snapshot, "search.tool", "auto")+ or "auto"+ )+ ctx = context_from_snapshot(+ settings_snapshot,+ primary,+ username=settings_snapshot.get("_username"),+ )+ return filter_engines_by_egress(engine_names, ctx, settings_snapshot)+ except Exception: # noqa: silent-exception - advisory pre-filter only+ logger.bind(policy_audit=True).debug(+ "egress candidate pre-filter failed; "+ "factory PEP still enforces at child instantiation"+ )+ return engine_names++def evaluate_engine(engine_name: str,ctx: EgressContext,@@ -1060,6 +1175,11 @@ def _resolve_adaptive_scope() -> EgressScope:"""Map ADAPTIVE to a concrete scope by classifying the primary engine.+ Uses the engine's **static class flags** (plus ``_engine_bucket``'s+ fail-up URL override) so that e.g. a locally-hosted SearXNG is still+ treated as a public engine, and a remote-hosted Elasticsearch resolves+ public rather than pulling the run into PRIVATE_ONLY.+private primary => PRIVATE_ONLY, public primary => PUBLIC_ONLY,meta-picker / unknown / classification-error => BOTH (adaptive'sdocumented permissive fallback, equivalent to pre-policy behavior, so adiff --git a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py b/src/local_deep_research/web_search_engines/engines/meta_search_engine.pyindex f8207f3b95..09396aa508 100644--- a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py+++ b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py@@ -3,7 +3,10 @@ from typing import Any, Dict, List, Optionalfrom loguru import loggerfrom ...config.search_config import get_setting_from_snapshot-from ...security.egress.policy import PolicyDeniedError+from ...security.egress.policy import (+ PolicyDeniedError,+ filter_candidates_by_egress,+)from ...utilities.thread_context import get_search_contextfrom ...web.services.socket_service import SocketIOServicefrom ..search_engine_base import BaseSearchEngine@@ -156,7 +159,12 @@ class MetaSearchEngine(BaseSearchEngine):logger.error(error_msg)raise RuntimeError(error_msg)- return list(available.keys())+ names = list(available.keys())++ # Egress scope pre-filter so the LLM doesn't pick engines that+ # would be denied at instantiation (advisory only; the factory+ # PEP enforces at child instantiation).+ return filter_candidates_by_egress(names, self.settings_snapshot)def analyze_query(self, query: str) -> List[str]:"""diff --git a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.pyindex 75f3eeb157..527a8ae284 100644--- a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py+++ b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py@@ -8,7 +8,10 @@ from loguru import loggerfrom ...config.search_config import get_setting_from_snapshotfrom ...database.thread_local_session import cleanup_current_thread-from ...security.egress.policy import PolicyDeniedError+from ...security.egress.policy import (+ PolicyDeniedError,+ filter_candidates_by_egress,+)from ...utilities.enums import SearchModefrom ...utilities.json_utils import extract_json, get_llm_response_textfrom ...utilities.thread_context import (@@ -253,7 +256,12 @@ class ParallelSearchEngine(BaseSearchEngine):available.append(name)- return available+ # Egress scope pre-filter: remove engines that would be denied at+ # instantiation so the LLM doesn't waste selection slots on them+ # (advisory only; the factory PEP enforces at child instantiation).+ return filter_candidates_by_egress(+ available, self.settings_snapshot+ )def _get_available_generic_engines(self) -> List[str]:"""Get list of available generic search engines that pass API key checks"""diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.pyindex 2be34d295e..2569aa6f3e 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py@@ -15,11 +15,14 @@ class ElasticsearchSearchEngine(BaseSearchEngine):is_local = Trueis_lexical = Trueneeds_llm_relevance_filter = True- # Dynamic URL classification so a user who reconfigures hosts to a public- # Elastic Cloud endpoint isn't still treated as local. The PDP supports- # list-typed settings ("any public wins"). cloud_id (which is NOT a host- # the PDP can classify) is handled separately in __init__: it is rejected- # when the effective scope forbids public egress.+ # url_setting feeds the PDP's fail-up URL override: when the configured+ # hosts resolve to a PUBLIC endpoint (e.g. Elastic Cloud), the engine is+ # reclassified public so PRIVATE_ONLY denies it at selection time —+ # queries would leave the box even though the DATA is "local" in nature.+ # A localhost ES keeps the static is_local classification above.+ # cloud_id (which is NOT a host the PDP can classify) is handled+ # separately in __init__: it is rejected when the effective scope forbids+ # public egress.url_setting = "search.engine.web.elasticsearch.default_params.hosts"@staticmethoddiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py b/src/local_deep_research/web_search_engines/engines/search_engine_paperless.pyindex 7939a20d7d..8093c7d091 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py@@ -24,10 +24,11 @@ class PaperlessSearchEngine(BaseSearchEngine):is_local = Trueis_lexical = Trueneeds_llm_relevance_filter = True- # Dynamic URL classification: the configured api_url is the source of truth.- # If a user points paperless at a remote host, the egress policy will- # reclassify it via DNS resolution instead of trusting the static- # is_local flag.+ # url_setting feeds the PDP's fail-up URL override: if the configured+ # api_url resolves to a PUBLIC host, the engine is reclassified public+ # so PRIVATE_ONLY denies it at selection time (queries would leave the+ # box). A local api_url keeps the static is_local classification —+ # the override only ever tightens, never relaxes.url_setting = "search.engine.web.paperless.default_params.api_url"# Class constants for magic numbersdiff --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 ec0ca440d5..593a361c65 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@@ -34,9 +34,10 @@ class SearXNGSearchEngine(BaseSearchEngine):is_public = True# Mark as generic search engine (general web search)is_generic = True- # Dynamic URL classification: self-hosted SearXNG on localhost should be- # treated as private under PRIVATE_ONLY scope. The egress policy reads- # the live instance_url and reclassifies via DNS resolution.+ # The egress engine-selection gate uses the static is_public flag above —+ # SearXNG always queries the internet regardless of where it's hosted, so+ # a localhost instance_url does NOT reclassify it as private (the PDP's+ # URL override is fail-up only and never relaxes a public nature).url_setting = "search.engine.web.searxng.default_params.instance_url"@staticmethoddiff --git a/tests/security/test_egress_adaptive_resolution_followup.py b/tests/security/test_egress_adaptive_resolution_followup.pyindex d16c1e97bb..86c3c0fdcd 100644--- a/tests/security/test_egress_adaptive_resolution_followup.py+++ b/tests/security/test_egress_adaptive_resolution_followup.py@@ -336,28 +336,37 @@ def test_adaptive_allow_dns_false_skips_dns_and_uses_static_flags():def test_adaptive_allow_dns_true_uses_dns_resolution():- """Contrast: with allow_dns=True the same private-resolving hostname IS- DNS-resolved (via _resolve_with_timeout), classifying searxng as LOCAL ->- PRIVATE_ONLY. Proves allow_dns toggles the DNS path, not a no-op."""+ """Contrast: with allow_dns=True the fail-up URL override DOES DNS-+ resolve (via _resolve_with_timeout) — for a LOCAL-nature engine. A+ paperless primary whose configured api_url resolves to a PUBLIC host is+ reclassified public, so ADAPTIVE resolves PUBLIC_ONLY instead of+ PRIVATE_ONLY. Proves allow_dns toggles the DNS path, not a no-op.++ NB: searxng no longer exercises DNS here — engine nature comes from+ static class flags and the URL override is fail-up only (it never+ relaxes a public engine to private), so a localhost searxng stays+ PUBLIC_ONLY with or without DNS."""snap = _adaptive_snapshot(- "searxng",+ "paperless",**{- "search.engine.web.searxng.default_params.instance_url": (- "http://searx.internal.lab:8080"+ "search.engine.web.paperless.default_params.api_url": (+ "http://paperless.example.org:8930")},)- private_addrinfo = [(None, None, None, None, ("192.168.50.10", 0))]+ # NB: a real public IP — the RFC 5737 documentation ranges+ # (192.0.2.x / 198.51.100.x / 203.0.113.x) classify as PRIVATE under+ # Python's ipaddress.is_private and would defeat the fail-up here.+ public_addrinfo = [(None, None, None, None, ("93.184.216.34", 0))]with patch("local_deep_research.security.egress.policy._resolve_with_timeout",- return_value=private_addrinfo,+ return_value=public_addrinfo,) as mock_resolve:ctx = context_from_snapshot(- snap, primary_engine="searxng", allow_dns=True+ snap, primary_engine="paperless", allow_dns=True)mock_resolve.assert_called()- assert ctx.scope == EgressScope.PRIVATE_ONLY- # And the DNS-driven PRIVATE_ONLY still triggers the local-inference- # coupling.- assert ctx.require_local_llm is True- assert ctx.require_local_embeddings is True+ assert ctx.scope == EgressScope.PUBLIC_ONLY+ # A public-resolving primary does NOT force the local-inference coupling.+ assert ctx.require_local_llm is False+ assert ctx.require_local_embeddings is Falsediff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.pyindex b8c5612bb8..1a75aa9d20 100644--- a/tests/security/test_egress_policy.py+++ b/tests/security/test_egress_policy.py@@ -17,6 +17,7 @@ from local_deep_research.security.egress.policy import (evaluate_embeddings,evaluate_llm_endpoint,evaluate_url,+ filter_engines_by_egress,)@@ -354,13 +355,26 @@ def test_evaluate_engine_paperless_is_local():# ----------------------------------------------------------------------------def test_evaluate_engine_searxng_localhost_classified_local():- """SearXNG pointed at localhost should pass PRIVATE_ONLY."""+def test_evaluate_engine_searxng_localhost_denied_under_private_only():+ """SearXNG is is_public=True regardless of where it's hosted — a local+ SearXNG still queries the internet, so PRIVATE_ONLY must deny it."""ctx = make_ctx(scope=EgressScope.PRIVATE_ONLY)snapshot = {"search.engine.web.searxng.default_params.instance_url": "http://localhost:8080"}decision = evaluate_engine("searxng", ctx, settings_snapshot=snapshot)+ assert not decision.allowed+ assert decision.reason == "scope_mismatch_private_only"+++def test_evaluate_engine_searxng_localhost_allowed_under_public_only():+ """SearXNG is is_public=True, so PUBLIC_ONLY allows it even when+ hosted on localhost — the engine-selection gate uses static flags."""+ ctx = make_ctx(scope=EgressScope.PUBLIC_ONLY)+ snapshot = {+ "search.engine.web.searxng.default_params.instance_url": "http://localhost:8080"+ }+ decision = evaluate_engine("searxng", ctx, settings_snapshot=snapshot)assert decision.allowed@@ -380,6 +394,324 @@ def test_evaluate_engine_searxng_remote_classified_public():assert not decision.allowed+# ---------------------------------------------------------------------------+# Engine nature classification — static class flags are authoritative+# ---------------------------------------------------------------------------+++# Engines that can be loaded in CI (no optional deps needed).+_PUBLIC_ENGINES = [+ "brave",+ "ddg",+ "exa",+ "github",+ "google_pse",+ "guardian",+ "gutenberg",+ "mojeek",+ "nasa_ads",+ "openalex",+ "openlibrary",+ "pubchem",+ "pubmed",+ "scaleserp",+ "searxng",+ "semantic_scholar",+ "serpapi",+ "serper",+ "stackexchange",+ "tavily",+ "wayback",+ "wikinews",+ "wikipedia",+ "zenodo",+]++_LOCAL_ENGINES = [+ "paperless",+]++[email protected]("engine_name", _PUBLIC_ENGINES)+def test_public_engine_denied_under_private_only(engine_name):+ """Every is_public=True engine must be denied under PRIVATE_ONLY,+ regardless of its configured URL. Engine nature (queries the+ internet) is determined by the Python class flag, not by where the+ engine happens to be hosted."""+ ctx = make_ctx(scope=EgressScope.PRIVATE_ONLY)+ decision = evaluate_engine(engine_name, ctx, settings_snapshot={})+ assert not decision.allowed+ assert decision.reason == "scope_mismatch_private_only"++[email protected]("engine_name", _PUBLIC_ENGINES)+def test_public_engine_allowed_under_public_only(engine_name):+ """Every is_public=True engine must pass PUBLIC_ONLY."""+ ctx = make_ctx(scope=EgressScope.PUBLIC_ONLY)+ decision = evaluate_engine(engine_name, ctx, settings_snapshot={})+ assert decision.allowed++[email protected]("engine_name", _PUBLIC_ENGINES)+def test_public_engine_allowed_under_both(engine_name):+ """Every is_public=True engine must pass BOTH."""+ ctx = make_ctx(scope=EgressScope.BOTH)+ decision = evaluate_engine(engine_name, ctx, settings_snapshot={})+ assert decision.allowed++[email protected]("engine_name", _LOCAL_ENGINES)+def test_local_engine_allowed_under_private_only(engine_name):+ """Every is_local=True engine must pass PRIVATE_ONLY."""+ ctx = make_ctx(scope=EgressScope.PRIVATE_ONLY)+ decision = evaluate_engine(engine_name, ctx, settings_snapshot={})+ assert decision.allowed++[email protected]("engine_name", _LOCAL_ENGINES)+def test_local_engine_denied_under_public_only(engine_name):+ """Every is_local=True engine (without is_public) must be denied under+ PUBLIC_ONLY."""+ ctx = make_ctx(scope=EgressScope.PUBLIC_ONLY)+ decision = evaluate_engine(engine_name, ctx, settings_snapshot={})+ assert not decision.allowed+ assert decision.reason == "scope_mismatch_public_only"++[email protected]("engine_name", _LOCAL_ENGINES)+def test_local_engine_allowed_under_both(engine_name):+ """Every is_local=True engine must pass BOTH."""+ ctx = make_ctx(scope=EgressScope.BOTH)+ decision = evaluate_engine(engine_name, ctx, settings_snapshot={})+ assert decision.allowed+++def test_searxng_local_url_still_public_nature():+ """SearXNG with a localhost URL must still be classified as public —+ it proxies to internet search engines regardless of where it's hosted."""+ ctx_pub = make_ctx(scope=EgressScope.PUBLIC_ONLY)+ ctx_priv = make_ctx(scope=EgressScope.PRIVATE_ONLY)+ snapshot = {+ "search.engine.web.searxng.default_params.instance_url": "http://localhost:8080"+ }+ assert evaluate_engine(+ "searxng", ctx_pub, settings_snapshot=snapshot+ ).allowed+ assert not evaluate_engine(+ "searxng", ctx_priv, settings_snapshot=snapshot+ ).allowed+++def test_paperless_local_url_still_local_nature():+ """Paperless with a localhost URL is is_local=True — allowed under+ PRIVATE_ONLY, denied under PUBLIC_ONLY."""+ ctx_pub = make_ctx(scope=EgressScope.PUBLIC_ONLY)+ ctx_priv = make_ctx(scope=EgressScope.PRIVATE_ONLY)+ snapshot = {+ "search.engine.web.paperless.default_params.api_url": "http://localhost:8930"+ }+ assert not evaluate_engine(+ "paperless", ctx_pub, settings_snapshot=snapshot+ ).allowed+ assert evaluate_engine(+ "paperless", ctx_priv, settings_snapshot=snapshot+ ).allowed+++def test_paperless_public_host_denied_under_private_only():+ """Fail-up URL override: a local-nature engine whose configured URL+ points at a PUBLIC host is reclassified public — querying it sends the+ user's queries off the box, so PRIVATE_ONLY denies it at selection+ time (not just at the audit-hook socket net)."""+ ctx = make_ctx(scope=EgressScope.PRIVATE_ONLY)+ snapshot = {+ # Public literal IP so classification needs no real DNS in CI.+ "search.engine.web.paperless.default_params.api_url": "http://93.184.216.34:8930"+ }+ decision = evaluate_engine("paperless", ctx, settings_snapshot=snapshot)+ assert not decision.allowed+ assert decision.reason == "scope_mismatch_private_only"+++def test_paperless_public_host_allowed_under_public_only():+ """The fail-up reclassification makes a remote-hosted local-data+ engine eligible under PUBLIC_ONLY (pre-static-flags behavior)."""+ ctx = make_ctx(scope=EgressScope.PUBLIC_ONLY)+ snapshot = {+ "search.engine.web.paperless.default_params.api_url": "http://93.184.216.34:8930"+ }+ decision = evaluate_engine("paperless", ctx, settings_snapshot=snapshot)+ assert decision.allowed+++def test_paperless_public_host_adaptive_resolves_public_only():+ """ADAPTIVE with a remote-hosted Paperless primary must NOT resolve to+ PRIVATE_ONLY (which would imply 'nothing leaves the box' while every+ query goes to a public host)."""+ snap = {+ "policy.egress_scope": {"value": "adaptive"},+ "search.tool": {"value": "paperless"},+ "search.engine.web.paperless.default_params.api_url": "http://93.184.216.34:8930",+ }+ ctx = context_from_snapshot(snap, primary_engine="paperless")+ assert ctx.scope == EgressScope.PUBLIC_ONLY+++def test_searxng_adaptive_resolves_to_public_only():+ """ADAPTIVE with SearXNG (is_public=True) as primary must resolve to+ PUBLIC_ONLY even when the instance URL points to localhost."""+ snap = {+ "policy.egress_scope": {"value": "adaptive"},+ "search.tool": {"value": "searxng"},+ "search.engine.web.searxng.default_params.instance_url": "http://localhost:8080",+ }+ ctx = context_from_snapshot(snap, primary_engine="searxng")+ assert ctx.scope == EgressScope.PUBLIC_ONLY+ assert ctx.require_local_llm is False+++def test_paperless_adaptive_resolves_to_private_only():+ """ADAPTIVE with Paperless (is_local=True) as primary must resolve to+ PRIVATE_ONLY and force local inference."""+ snap = {+ "policy.egress_scope": {"value": "adaptive"},+ "search.tool": {"value": "paperless"},+ }+ ctx = context_from_snapshot(snap, primary_engine="paperless")+ assert ctx.scope == EgressScope.PRIVATE_ONLY+ assert ctx.require_local_llm is True+ assert ctx.require_local_embeddings is True+++# ---------------------------------------------------------------------------+# filter_engines_by_egress+# ---------------------------------------------------------------------------+++def test_filter_engines_removes_public_under_private_only():+ """filter_engines_by_egress must strip all public engines under+ PRIVATE_ONLY."""+ ctx = make_ctx(scope=EgressScope.PRIVATE_ONLY)+ result = filter_engines_by_egress(+ ["wikipedia", "github", "searxng", "paperless"],+ ctx,+ settings_snapshot={},+ )+ assert result == ["paperless"]+++def test_filter_engines_removes_local_under_public_only():+ """filter_engines_by_egress must strip local engines under PUBLIC_ONLY."""+ ctx = make_ctx(scope=EgressScope.PUBLIC_ONLY)+ result = filter_engines_by_egress(+ ["wikipedia", "github", "searxng", "paperless"],+ ctx,+ settings_snapshot={},+ )+ assert "paperless" not in result+ assert "wikipedia" in result+++def test_filter_engines_keeps_all_under_both():+ """filter_engines_by_egress keeps everything under BOTH."""+ ctx = make_ctx(scope=EgressScope.BOTH)+ result = filter_engines_by_egress(+ ["wikipedia", "paperless"],+ ctx,+ settings_snapshot={},+ )+ assert "wikipedia" in result+ assert "paperless" in result+++def test_filter_engines_unknown_engine_kept():+ """Names unknown to the static registry are KEPT by the advisory+ pre-filter: they may be retriever-backed or dynamically injected+ engines that the factory PEP evaluates via its own path. The+ pre-filter must never be stricter than the enforcement point it+ fronts — the factory still denies anything truly disallowed."""+ ctx = make_ctx(scope=EgressScope.BOTH)+ result = filter_engines_by_egress(+ ["wikipedia", "totally_made_up"],+ ctx,+ settings_snapshot={},+ )+ assert result == ["wikipedia", "totally_made_up"]+++def test_filter_engines_strict_keeps_only_primary_and_unknown():+ """Under STRICT, non-primary registry engines are stripped+ (strict_not_primary, matching the factory); the primary survives.+ NB: under STRICT an unknown name is also stripped — the STRICT gate+ fires before the registry lookup, exactly as it does in the factory."""+ ctx = make_ctx(scope=EgressScope.STRICT, primary="paperless")+ result = filter_engines_by_egress(+ ["paperless", "wikipedia", "totally_made_up"],+ ctx,+ settings_snapshot={},+ )+ assert result == ["paperless"]+++def test_filter_candidates_helper_strips_by_snapshot_scope():+ """filter_candidates_by_egress does the full snapshot plumbing:+ scope/primary extraction, context build, filter."""+ from local_deep_research.security.egress.policy import (+ filter_candidates_by_egress,+ )++ snap = {+ "policy.egress_scope": {"value": "private_only"},+ "search.tool": {"value": "paperless"},+ }+ result = filter_candidates_by_egress(+ ["wikipedia", "paperless", "totally_made_up"], snap+ )+ assert "wikipedia" not in result+ assert "paperless" in result+ assert "totally_made_up" in result+++def test_filter_candidates_helper_noop_without_snapshot_or_under_both():+ from local_deep_research.security.egress.policy import (+ filter_candidates_by_egress,+ )++ names = ["wikipedia", "paperless"]+ assert filter_candidates_by_egress(names, None) == names+ assert filter_candidates_by_egress(names, {}) == names+ snap = {"policy.egress_scope": {"value": "both"}}+ assert filter_candidates_by_egress(names, snap) == names+++def test_filter_candidates_helper_failopen_on_corrupt_scope():+ """A corrupted scope string must not break engine selection — the+ helper returns the list unchanged (the unrecognized value falls out+ of the scope gate before any context is built) and the factory PEP+ remains the enforcement point."""+ from local_deep_research.security.egress.policy import (+ filter_candidates_by_egress,+ )++ names = ["wikipedia", "paperless"]+ snap = {"policy.egress_scope": {"value": "garbage_scope"}}+ assert filter_candidates_by_egress(names, snap) == names+++def test_filter_engines_strips_scope_denials_keeps_unknown():+ """Under PRIVATE_ONLY a public engine is stripped (active scope+ denial) while an unknown name survives for the factory to judge."""+ ctx = make_ctx(scope=EgressScope.PRIVATE_ONLY)+ result = filter_engines_by_egress(+ ["wikipedia", "totally_made_up", "paperless"],+ ctx,+ settings_snapshot={},+ )+ assert "wikipedia" not in result+ assert "totally_made_up" in result+ assert "paperless" in result++# ---------------------------------------------------------------------------# evaluate_llm_endpoint# ---------------------------------------------------------------------------