~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): align egress scope fallbacks with registered default (#4465)
LearningCircuit46839aa1d574
diff --git a/src/local_deep_research/research_library/services/rag_service_factory.py b/src/local_deep_research/research_library/services/rag_service_factory.pyindex 357ad30923..bf0ccbddbf 100644--- a/src/local_deep_research/research_library/services/rag_service_factory.py+++ b/src/local_deep_research/research_library/services/rag_service_factory.py@@ -35,6 +35,7 @@ def _enforce_embeddings_policy("""# Lazy import to avoid pulling the security module on every factory call.from ...security.egress.policy import (+ DEFAULT_EGRESS_SCOPE,Decision,PolicyDeniedError,context_from_snapshot,@@ -44,7 +45,10 @@ def _enforce_embeddings_policy(# We don't have a full settings snapshot here, only a SettingsManager.# Build a minimal snapshot for the policy module — only the keys it# reads for scope coupling + embedding classification matter.- scope = settings_manager.get_setting("policy.egress_scope") or "both"+ scope = (+ settings_manager.get_setting("policy.egress_scope")+ or DEFAULT_EGRESS_SCOPE+ )require_local_flag = to_bool(settings_manager.get_setting("embeddings.require_local") or False)diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.pyindex f8048d6e39..79336956ff 100644--- a/src/local_deep_research/security/egress/policy.py+++ b/src/local_deep_research/security/egress/policy.py@@ -78,6 +78,18 @@ class EgressScope(str, Enum):ADAPTIVE = "adaptive"+# Code-side single source of truth for the default egress scope, used by+# every reader that needs a fallback for a MISSING policy.egress_scope key+# (partial snapshots from the programmatic API, un-bootstrapped settings+# DBs). Import THIS instead of hardcoding a string literal: scattered+# literals are how the registry default ("adaptive") and the code+# fallbacks ("both") drifted apart in the first place. Must match the+# registered default in defaults/default_settings.json — pinned by+# tests/security/test_egress_policy.py::+# test_default_scope_constant_matches_registry.+DEFAULT_EGRESS_SCOPE: str = EgressScope.ADAPTIVE.value++@dataclass(frozen=True)class EgressContext:"""Frozen per-run policy snapshot.@@ -1133,7 +1145,7 @@ def context_from_snapshot()scope_raw = _get_setting_value(- settings_snapshot, "policy.egress_scope", "both"+ settings_snapshot, "policy.egress_scope", DEFAULT_EGRESS_SCOPE)try:scope = EgressScope(str(scope_raw).lower())diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.pyindex 28b2792088..457d52a84f 100644--- a/src/local_deep_research/utilities/search_cache.py+++ b/src/local_deep_research/utilities/search_cache.py@@ -19,6 +19,7 @@ from sqlalchemy.orm import sessionmakerfrom ..config.paths import get_cache_directoryfrom ..database.models import Base, SearchCache as SearchCacheModel+from ..security.egress.policy import DEFAULT_EGRESS_SCOPEfrom .thread_context import get_search_context@@ -113,18 +114,20 @@ class SearchCache:# Get username + scope from thread context for per-user,# per-policy cache isolation.username = ""- # Default scope is "both" (the permissive default) so that- # "no search context" and "context without a policy snapshot"- # hash identically — both represent the no-policy situation.- scope = "both"+ # Default to the registered default scope so that "no search+ # context" and "context without a policy snapshot" hash+ # identically — both represent the no-policy situation.+ scope = DEFAULT_EGRESS_SCOPEcontext = get_search_context()if context:username = context.get("username", "") or ""settings_snapshot = context.get("settings_snapshot") or {}- scope_raw = settings_snapshot.get("policy.egress_scope", "both")+ scope_raw = settings_snapshot.get(+ "policy.egress_scope", DEFAULT_EGRESS_SCOPE+ )if isinstance(scope_raw, dict) and "value" in scope_raw:scope_raw = scope_raw["value"]- scope = str(scope_raw or "both").lower()+ scope = str(scope_raw or DEFAULT_EGRESS_SCOPE).lower()cache_key = f"{username}:{scope}:{search_engine}:{normalized_query}"return hashlib.sha256(cache_key.encode()).hexdigest()diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex 86670efe9e..1fa02a970f 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -19,6 +19,7 @@ from local_deep_research.settings.logger import log_settingsfrom ..utilities.log_utils import InterceptHandlerfrom ..security import SecurityHeaders, get_security_default+from ..security.egress.policy import DEFAULT_EGRESS_SCOPEfrom ..security.rate_limiter import limiterfrom ..security.file_upload_validator import FileUploadValidatorfrom ..security.web_middleware import (@@ -453,9 +454,9 @@ def apply_middleware(app):# Make the active egress scope available to every template so base.html# can render it onto <body data-scope=…>. Scope-aware CSS in styles.css# picks it up to color the research card, chat input, etc. Falls back- # to "both" if anything goes wrong — fail open visually, never crash a- # page render over a styling cue.- scope = "both"+ # to the registered default scope if anything goes wrong — fail open+ # visually, never crash a page render over a styling cue.+ scope = DEFAULT_EGRESS_SCOPEtry:from flask import session as flask_sessionfrom ..database.session_context import get_user_db_session@@ -467,8 +468,10 @@ def apply_middleware(app):if db_session:sm = get_settings_manager(db_session, username)scope = (- sm.get_setting("policy.egress_scope", "both")- or "both"+ sm.get_setting(+ "policy.egress_scope", DEFAULT_EGRESS_SCOPE+ )+ or DEFAULT_EGRESS_SCOPE)except Exception:logger.debug(@@ -629,7 +632,7 @@ def register_blueprints(app):),# Egress policy controls (Stage 1c UI)."policy_egress_scope": settings_manager.get_setting(- "policy.egress_scope", "both"+ "policy.egress_scope", DEFAULT_EGRESS_SCOPE),"llm_require_local_endpoint": settings_manager.get_setting("llm.require_local_endpoint", Falsediff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.pyindex fba227fc61..667491489e 100644--- a/src/local_deep_research/web/routes/metrics_routes.py+++ b/src/local_deep_research/web/routes/metrics_routes.py@@ -2230,12 +2230,15 @@ def api_journal_data_download():# auto-download path is already gated by# JournalReputationFilter._should_skip_journal_fetch_for_scope; this# closes the manual button as the matching entry point.- from ...security.egress.policy import EgressScope+ from ...security.egress.policy import (+ DEFAULT_EGRESS_SCOPE,+ EgressScope,+ )from ...utilities.db_utils import get_settings_managerusername = flask_session.get("username")scope_raw = get_settings_manager(username=username).get_setting(- "policy.egress_scope", "both"+ "policy.egress_scope", DEFAULT_EGRESS_SCOPE)try:scope = EgressScope(str(scope_raw).lower())diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 0e4cd1faf3..7d4604ef67 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -65,6 +65,7 @@ from ...database.encrypted_db import db_managerfrom ...utilities.db_utils import get_settings_managerfrom ...utilities.url_utils import normalize_urlfrom ...security.decorators import require_json_body+from ...security.egress.policy import DEFAULT_EGRESS_SCOPEfrom ...security.egress.validators import (validate_allowed_local_hostnames,validate_strict_meta_combo,@@ -234,7 +235,9 @@ def _model_list_local_only() -> bool:sm = get_settings_manager(db_session, username)if bool(sm.get_setting("llm.require_local_endpoint", False)):return True- scope = str(sm.get_setting("policy.egress_scope", "both")).lower()+ scope = str(+ sm.get_setting("policy.egress_scope", DEFAULT_EGRESS_SCOPE)+ ).lower()if scope == "private_only":return Trueif scope == "adaptive":diff --git a/src/local_deep_research/web/warning_checks/__init__.py b/src/local_deep_research/web/warning_checks/__init__.pyindex 204b1745fc..459e97a2ca 100644--- a/src/local_deep_research/web/warning_checks/__init__.py+++ b/src/local_deep_research/web/warning_checks/__init__.py@@ -26,6 +26,7 @@ from .hardware import (check_legacy_server_config,check_model_mismatch,)+from ...security.egress.policy import DEFAULT_EGRESS_SCOPEfrom ...security.egress.warnings import (check_cloud_embeddings_enabled,check_cloud_llm_enabled,@@ -119,7 +120,7 @@ def calculate_warnings() -> List[dict]:# --- Egress policy checks ---egress_scope = settings_manager.get_setting(- "policy.egress_scope", "both"+ "policy.egress_scope", DEFAULT_EGRESS_SCOPE)require_local_endpoint = bool(settings_manager.get_setting(diff --git a/tests/research_library/routes/test_rag_routes.py b/tests/research_library/routes/test_rag_routes.pyindex 4fbb4f1eea..0dc0a185c1 100644--- a/tests/research_library/routes/test_rag_routes.py+++ b/tests/research_library/routes/test_rag_routes.py@@ -80,6 +80,11 @@ class TestGetRagService:"""Create mock settings manager."""mock = Mock()mock.get_setting.side_effect = lambda key, default=None: {+ # Explicit permissive scope: these tests exercise the settings+ # plumbing with FAKE provider names; the registered default+ # (adaptive) would resolve PRIVATE_ONLY for the library and+ # deny them as provider_unknown.+ "policy.egress_scope": "both","local_search_embedding_model": "test-model","local_search_embedding_provider": "sentence_transformers","local_search_chunk_size": "1000",diff --git a/tests/routes/test_settings_routes.py b/tests/routes/test_settings_routes.pyindex f786ffd46c..1aa526e91b 100644--- a/tests/routes/test_settings_routes.py+++ b/tests/routes/test_settings_routes.py@@ -258,12 +258,15 @@ class TestCalculateWarnings:"app.warnings.dismiss_no_backups": True,"app.warnings.dismiss_backup_disabled": False,# Egress-policy banners (public-egress + cloud-LLM) fire for a- # cloud provider under the default 'both' scope; each banner- # now has its own dismiss flag, so all three must be dismissed- # to keep this "no warnings" scenario genuinely empty.+ # cloud provider under the default scope; each banner has its+ # own dismiss flag, so all must be dismissed to keep this+ # "no warnings" scenario genuinely empty. The registered+ # default scope is now 'adaptive', which additionally shows+ # the informational effective-scope banner."app.warnings.dismiss_egress_policy": True,"app.warnings.dismiss_cloud_llm": True,"app.warnings.dismiss_cloud_embeddings": True,+ "app.warnings.dismiss_adaptive_scope_info": True,"backup.enabled": True,"llm.model": "gpt-4",}.get(key, default)diff --git a/tests/security/test_egress_cache_and_fullsearch.py b/tests/security/test_egress_cache_and_fullsearch.pyindex 308fbb2b41..23eafd44d4 100644--- a/tests/security/test_egress_cache_and_fullsearch.py+++ b/tests/security/test_egress_cache_and_fullsearch.py@@ -137,23 +137,26 @@ def test_query_hash_distinct_per_scope_stable_within_scope(tmp_path):cache.dispose()-def test_no_context_hashes_identically_to_explicit_both(tmp_path):- """Documented invariant: "no policy snapshot" and an explicit BOTH scope- (the permissive default) must hash identically, so unset-context runs and- explicit-BOTH runs share one cache partition rather than fragmenting."""+def test_no_context_hashes_identically_to_explicit_adaptive(tmp_path):+ """Documented invariant: "no policy snapshot" and an explicit ADAPTIVE+ scope (the registered default) must hash identically, so unset-context+ runs and explicit-default runs share one cache partition rather than+ fragmenting."""cache = SearchCache(cache_dir=str(tmp_path))try:# No search context at all.h_none = cache._get_query_hash("topic")- # Explicit BOTH with an empty username (the no-context default).+ # Explicit ADAPTIVE with an empty username (the no-context default).with search_context({"username": "",- "settings_snapshot": {"policy.egress_scope": {"value": "both"}},+ "settings_snapshot": {+ "policy.egress_scope": {"value": "adaptive"}+ },}):- h_both = cache._get_query_hash("topic")- assert h_none == h_both+ h_adaptive = cache._get_query_hash("topic")+ assert h_none == h_adaptivefinally:cache.dispose()diff --git a/tests/security/test_egress_pep_coverage.py b/tests/security/test_egress_pep_coverage.pyindex c82e7a389a..c113b04764 100644--- a/tests/security/test_egress_pep_coverage.py+++ b/tests/security/test_egress_pep_coverage.py@@ -325,12 +325,33 @@ class TestEnforceEmbeddingsPolicy:return _enforce_embeddings_policy(provider, self._mgr(settings), "u")- def test_noop_when_require_local_false(self):- # No restriction => any provider passes (returns None, no raise).+ def test_noop_when_scope_both_and_require_local_false(self):+ # Explicit BOTH scope + no flag => any provider passes (returns+ # None, no raise).assert (- self._enforce("openai", {"embeddings.require_local": False}) is None+ self._enforce(+ "openai",+ {+ "policy.egress_scope": "both",+ "embeddings.require_local": False,+ },+ )+ is None)+ def test_adaptive_default_denies_cloud_for_library(self):+ # A missing scope falls back to the registered default ADAPTIVE.+ # The gate classifies against primary_engine="library" (local+ # nature), so adaptive resolves PRIVATE_ONLY and forces local+ # embeddings — cloud providers are denied even with the+ # require_local flag at its default False.+ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ with pytest.raises(PolicyDeniedError):+ self._enforce("openai", {"embeddings.require_local": False})+def test_ollama_via_llm_url_allowed(self):# Regression: ollama configured ONLY via the shared llm.ollama.url# (embeddings.ollama.url unset) must be classified local. Before thediff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.pyindex ec494805f5..b8c5612bb8 100644--- a/tests/security/test_egress_policy.py+++ b/tests/security/test_egress_policy.py@@ -46,13 +46,42 @@ def make_ctx(# ----------------------------------------------------------------------------def test_context_from_snapshot_defaults_to_both():+def test_default_scope_constant_matches_registry():+ """DEFAULT_EGRESS_SCOPE (the code-side fallback every reader imports)+ must equal the registered default in defaults/default_settings.json.+ This single test replaces scattered fallback-string assertions and is+ what prevents the code/registry drift ('both' vs 'adaptive') that+ motivated this fix from recurring."""+ import json++ from local_deep_research.defaults import DEFAULTS_DIR+ from local_deep_research.security.egress.policy import (+ DEFAULT_EGRESS_SCOPE,+ )++ path = DEFAULTS_DIR / "default_settings.json"+ assert path.exists()+ with open(path, encoding="utf-8-sig") as f:+ registry = json.load(f)+ assert registry["policy.egress_scope"]["value"] == DEFAULT_EGRESS_SCOPE+ # The constant must also be a valid enum member (sanity).+ assert EgressScope(DEFAULT_EGRESS_SCOPE)+++def test_context_from_snapshot_defaults_to_adaptive():+ """A missing policy.egress_scope falls back to the REGISTERED default+ (adaptive), matching what users with a settings DB already get: a+ public primary resolves PUBLIC_ONLY, a meta-picker primary resolves+ BOTH (the permissive pre-policy behavior)."""ctx = context_from_snapshot({}, primary_engine="arxiv")- assert ctx.scope == EgressScope.BOTH+ assert ctx.scope == EgressScope.PUBLIC_ONLYassert ctx.require_local_llm is Falseassert ctx.require_local_embeddings is Falseassert ctx.local_hostnames == ()+ ctx_meta = context_from_snapshot({}, primary_engine="auto")+ assert ctx_meta.scope == EgressScope.BOTH+def _scope_snapshot(scope, tool):return {@@ -911,8 +940,9 @@ def test_rag_factory_allows_openai_pointed_at_local_endpoint():)-def test_rag_factory_passes_through_when_require_local_false():- """When the user hasn't opted in, OpenAI embeddings are permitted."""+def test_rag_factory_passes_through_when_scope_both():+ """Under an explicit BOTH scope with require_local False, OpenAI+ embeddings are permitted."""from unittest.mock import MagicMockfrom local_deep_research.research_library.services import (rag_service_factory,@@ -920,17 +950,44 @@ def test_rag_factory_passes_through_when_require_local_false():fake_settings = MagicMock()fake_settings.get_setting.side_effect = lambda key, *args, **kwargs: {+ "policy.egress_scope": "both","embeddings.require_local": False,"embeddings.openai.base_url": "","embeddings.ollama.url": "",}.get(key)- # Should not raise — policy is opt-in.+ # Should not raise — BOTH imposes no local requirement.rag_service_factory._enforce_embeddings_policy("openai", fake_settings, username="alice")+def test_rag_factory_denies_cloud_under_adaptive_default():+ """A missing scope falls back to the registered default ADAPTIVE. The+ gate classifies against primary_engine='library' (the corpus being+ embedded is local-nature), so adaptive resolves PRIVATE_ONLY and+ forces local embeddings — a cloud provider is denied even with+ embeddings.require_local at its default False. This matches what a+ real settings DB (default value 'adaptive') already produced."""+ from unittest.mock import MagicMock+ from local_deep_research.research_library.services import (+ rag_service_factory,+ )++ fake_settings = MagicMock()+ fake_settings.get_setting.side_effect = lambda key, *args, **kwargs: {+ "embeddings.require_local": False,+ "embeddings.openai.base_url": "",+ "embeddings.ollama.url": "",+ }.get(key)++ with pytest.raises(PolicyDeniedError) as exc_info:+ rag_service_factory._enforce_embeddings_policy(+ "openai", fake_settings, username="alice"+ )+ assert exc_info.value.decision.reason == "provider_cloud"++def test_factory_allows_primary_under_strict():"""Factory permits the user's primary engine under STRICT."""from local_deep_research.web_search_engines.search_engine_factory import (diff --git a/tests/utilities/test_search_cache_high_value.py b/tests/utilities/test_search_cache_high_value.pyindex ddba248584..5e6d979b51 100644--- a/tests/utilities/test_search_cache_high_value.py+++ b/tests/utilities/test_search_cache_high_value.py@@ -119,11 +119,12 @@ class TestGetQueryHashHighValue:def test_hash_matches_manual_sha256(self):"""Hash matches manually computed SHA-256 of'username:scope:engine:normalized_query'. The scope component- (N17) defaults to 'both' when no policy snapshot is in context."""+ (N17) defaults to 'adaptive' (the registered default) when no+ policy snapshot is in context."""cache = _make_cache()result = cache._get_query_hash("Hello World", search_engine="google")- # No search context set: username empty, scope defaults to "both".- expected_input = ":both:google:hello world"+ # No search context set: username empty, scope defaults to "adaptive".+ expected_input = ":adaptive:google:hello world"expected = hashlib.sha256(expected_input.encode()).hexdigest()assert result == expected@@ -131,7 +132,7 @@ class TestGetQueryHashHighValue:"""Default search_engine parameter is 'default'."""cache = _make_cache()result = cache._get_query_hash("test")- expected_input = ":both:default:test"+ expected_input = ":adaptive:default:test"expected = hashlib.sha256(expected_input.encode()).hexdigest()assert result == expecteddiff --git a/tests/web/warning_checks/test_orchestrator.py b/tests/web/warning_checks/test_orchestrator.pyindex 73f58007eb..953be8862c 100644--- a/tests/web/warning_checks/test_orchestrator.py+++ b/tests/web/warning_checks/test_orchestrator.py@@ -290,10 +290,12 @@ class TestCalculateWarningsMultipleWarnings:"context_below_history","context_truncation_history","no_backups",- # The egress policy defaults to scope="both" (unacknowledged),- # so the public-egress banner correctly fires alongside the- # hardware/context warnings.+ # The egress policy defaults to scope="adaptive" (unacknowledged):+ # the public-egress banner fires (adaptive can resolve to a+ # public-allowing scope) alongside the informational banner that+ # states what adaptive resolves to."public_egress_enabled",+ "egress_effective_scope",}