~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): enforce consistent egress checks across provider paths (#7145)
LearningCircuit12b50152e9ac
diff --git a/changelog.d/+egress-primary-context-consistency.security.md b/changelog.d/+egress-primary-context-consistency.security.mdnew file mode 100644index 0000000000..1bb3cc43ad--- /dev/null+++ b/changelog.d/+egress-primary-context-consistency.security.md@@ -0,0 +1 @@+Normalize saved primary search-engine names across egress context builders so padded values cannot widen adaptive scope in search, downloads, notifications, news, MCP, RAG, and warning checks. Require a usable saved primary under STRICT so cached engines cannot authorize themselves through a fallback, including when an operator enforces STRICT and the settings snapshot is missing or malformed.diff --git a/changelog.d/7258.security.md b/changelog.d/7258.security.mdnew file mode 100644index 0000000000..6417c9a514--- /dev/null+++ b/changelog.d/7258.security.md@@ -0,0 +1 @@+Resolve notification egress policy using the notification owner's identity, including queue snapshots without username metadata and private retrievers that share a name with another user's or a shared retriever.diff --git a/changelog.d/7259.security.md b/changelog.d/7259.security.mdnew file mode 100644index 0000000000..c00333f897--- /dev/null+++ b/changelog.d/7259.security.md@@ -0,0 +1 @@+Check egress policy before embedding provider availability probes and model discovery. Show policy-blocked providers separately from unreachable providers in embedding settings while keeping their configuration accessible.diff --git a/changelog.d/7260.security.md b/changelog.d/7260.security.mdnew file mode 100644index 0000000000..035246897b--- /dev/null+++ b/changelog.d/7260.security.md@@ -0,0 +1 @@+Recheck runtime egress policy in Guardian and Paperless search overrides before provider work, and preserve policy denials through SearXNG's error handling.diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.pyindex 14329e6c02..88d085eb8f 100644--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py@@ -38,7 +38,6 @@ from loguru import loggerfrom sqlalchemy import or_from sqlalchemy.orm import Session-from ...utilities.type_utils import unwrap_settingfrom ...config.llm_config import get_llmfrom ...constants import VALID_QUALITY_SCORESfrom ...database.models import Journal@@ -58,7 +57,6 @@ from ...utilities.resource_utils import safe_closefrom ...utilities.thread_context import get_search_contextfrom ...web_search_engines.search_engine_factory import create_search_enginefrom .base_filter import BaseFilter-from ...constants import DEFAULT_SEARCH_TOOLfrom ...utilities.llm_utils import invoke_llm_sync@@ -366,33 +364,31 @@ class JournalReputationFilter(BaseFilter):EgressScope,PolicyDeniedError,context_from_snapshot,+ resolve_run_primary_engine,)from ...search_system import username_from_snapshot- primary_raw = unwrap_setting(- snapshot.get("search.tool", DEFAULT_SEARCH_TOOL)- )# Thread username so a per-user private retriever primary# resolves PRIVATE_ONLY and the public journal fetch is skipped.ctx = context_from_snapshot(snapshot,- primary_raw or DEFAULT_SEARCH_TOOL,+ resolve_run_primary_engine(snapshot),username=username_from_snapshot(snapshot),)return ctx.scope in (EgressScope.PRIVATE_ONLY, EgressScope.STRICT)- except PolicyDeniedError:- # Corrupt/unknown scope value — we cannot certify that a public+ except (PolicyDeniedError, ValueError):+ # Corrupt scope or missing primary — we cannot certify that a public# journal fetch is permitted, so SKIP the fetch (fail closed).# This matches the hardened sibling# notifications.manager._filter_urls_by_egress_policy, which also# refuses rather than proceeds when the policy is unevaluable.logger.bind(policy_audit=True).warning("journal fetch skipped: egress policy unevaluable "- "(corrupt scope) — failing closed"+ "(scope or primary) — failing closed")return Trueexcept Exception:- # Other errors (missing key, snapshot shape) — fail open; the+ # Other unexpected errors — fail open; the# per-URL runtime check still gates each individual fetch.return Falsediff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.pyindex fc7fc85475..ce95429cdf 100644--- a/src/local_deep_research/mcp/server.py+++ b/src/local_deep_research/mcp/server.py@@ -47,7 +47,6 @@ from local_deep_research.api.settings_utils import create_settings_snapshotfrom local_deep_research.search_system_factory import (get_available_strategies,)-from ..utilities.type_utils import unwrap_settingfrom ..constants import DEFAULT_SEARCH_TOOLfrom ..security.egress.policy import PolicyDeniedError@@ -799,6 +798,7 @@ def _egress_audit_net(settings: Dict[str, Any]):from local_deep_research.security.egress.policy import (PolicyDeniedError,context_from_snapshot,+ resolve_run_primary_engine,)except Exception:return nullcontext()@@ -806,12 +806,9 @@ def _egress_audit_net(settings: Dict[str, Any]):if not settings or get_active_context() is not None:return nullcontext()try:- primary = unwrap_setting(- settings.get("search.tool", DEFAULT_SEARCH_TOOL)- )ctx = context_from_snapshot(settings,- primary or DEFAULT_SEARCH_TOOL,+ resolve_run_primary_engine(settings),username=settings.get("_username"),)except (PolicyDeniedError, ValueError):diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.pyindex ac7f3a90b3..13083256ca 100644--- a/src/local_deep_research/news/api.py+++ b/src/local_deep_research/news/api.py@@ -28,7 +28,6 @@ from ..utilities.request_context import (get_current_session_id,get_current_username,)-from ..constants import DEFAULT_SEARCH_TOOL# Removed welcome feed import - no placeholders# get_db_setting not available in merged codebase@@ -1047,18 +1046,18 @@ def _validate_subscription_policy(context_from_snapshot,evaluate_engine,evaluate_llm_endpoint,+ resolve_run_primary_engine,)settings_manager = get_settings_manager(db_session, user_id)snapshot = settings_manager.get_settings_snapshot()if not isinstance(snapshot, dict):return None- primary = settings_manager.get_setting(- "search.tool", DEFAULT_SEARCH_TOOL- )try:ctx = context_from_snapshot(- snapshot, primary or DEFAULT_SEARCH_TOOL, username=user_id+ snapshot,+ resolve_run_primary_engine(snapshot),+ username=user_id,)except PolicyDeniedError as exc:return f"egress policy refused: {exc.decision.reason}"diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.pyindex 9c6e2e243a..f99269ca90 100644--- a/src/local_deep_research/notifications/manager.py+++ b/src/local_deep_research/notifications/manager.py@@ -13,6 +13,7 @@ import threadingfrom loguru import loggerfrom ..security.notification_validator import parse_notification_url_list+from ..constants import DEFAULT_SEARCH_TOOLfrom ..security.ssrf_validator import redact_url_for_logfrom ..security.notification_destination import (NotificationDestinationError,@@ -28,8 +29,6 @@ from .exceptions import (ServiceError,SecurityBlockError,)-from ..utilities.type_utils import unwrap_setting-from ..constants import DEFAULT_SEARCH_TOOLclass NotificationReason(str, Enum):@@ -707,6 +706,7 @@ class NotificationManager:PolicyDeniedError,context_from_snapshot,evaluate_url,+ resolve_run_primary_engine,)except ImportError:logger.debug(@@ -715,16 +715,15 @@ class NotificationManager:)return service_urls- from ..search_system import username_from_snapshot-- primary_raw = unwrap_setting(- snapshot.get("search.tool", DEFAULT_SEARCH_TOOL)- )try:ctx = context_from_snapshot(snapshot,- primary_raw or DEFAULT_SEARCH_TOOL,- username=username_from_snapshot(snapshot),+ resolve_run_primary_engine(+ snapshot, default=DEFAULT_SEARCH_TOOL+ ),+ # Queue snapshots need not carry identity metadata. Resolve+ # private retrievers in the notification owner's namespace.+ username=self._user_id,)except (PolicyDeniedError, ValueError) as exc:# Snapshot present but policy cannot be evaluated. Thediff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex ec33cf00eb..da2b92448a 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -27,7 +27,7 @@ import pdfplumberfrom pypdf import PdfReaderfrom ...utilities.arxiv import extract_arxiv_id, is_arxiv_paper_url-from ...utilities.type_utils import unwrap_setting+from ...constants import DEFAULT_SEARCH_TOOLfrom ...utilities.url_utils import canonical_url_keyfrom ...constants import FILE_PATH_SENTINELS, FILE_PATH_TEXT_ONLYfrom ...database.models.download_tracker import (@@ -96,7 +96,6 @@ from ..extraction_catalog import (ExtractionMethodExtra,ExtractionSourceExtra,)-from ...constants import DEFAULT_SEARCH_TOOL# Extraction ceilings live in ``utilities.pdf_extraction_limits`` so that# the base downloader shares one definition without importing this module.@@ -380,8 +379,8 @@ class DownloadService:the pre-policy behavior (back-compat with non-scheduler callers).Sets ``self._policy_locked = True`` when a snapshot WAS supplied- but the policy itself cannot be evaluated (corrupt scope- value). The check_url method honors+ but the policy itself cannot be evaluated (corrupt scope or+ missing primary). The check_url method honorsthis flag and fails closed — the previous code returned None onPolicyDeniedError and check_url then returned ``(True,"no_context")``, which silently allowed every download under a@@ -398,6 +397,7 @@ class DownloadService:from ...security.egress.policy import (PolicyDeniedError,context_from_snapshot,+ resolve_run_primary_engine,)except ImportError:logger.debug(@@ -406,13 +406,12 @@ class DownloadService:)return None- primary_raw = unwrap_setting(- settings_snapshot.get("search.tool", DEFAULT_SEARCH_TOOL)- )try:return context_from_snapshot(settings_snapshot,- primary_raw or DEFAULT_SEARCH_TOOL,+ resolve_run_primary_engine(+ settings_snapshot, default=DEFAULT_SEARCH_TOOL+ ),username=self.username,)except (PolicyDeniedError, ValueError) as exc:diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex c4f53aca4b..a2a79ec9e9 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -404,6 +404,7 @@ class AdvancedSearchSystem:from .security.egress.policy import (PolicyDeniedError,context_from_snapshot,+ resolve_run_primary_engine,)except Exception:return False@@ -414,12 +415,9 @@ class AdvancedSearchSystem:return Falsetry:- primary = unwrap_setting(- self.settings_snapshot.get("search.tool", DEFAULT_SEARCH_TOOL)- )ctx = context_from_snapshot(self.settings_snapshot,- primary or DEFAULT_SEARCH_TOOL,+ resolve_run_primary_engine(self.settings_snapshot),username=self.username,)except (PolicyDeniedError, ValueError):diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.pyindex 2afaf28649..a48c4c04b6 100644--- a/src/local_deep_research/security/egress/policy.py+++ b/src/local_deep_research/security/egress/policy.py@@ -1862,12 +1862,10 @@ def _retriever_is_local(# Bounded, thread-safe, PER-USER dedup for the ADAPTIVE fail-open WARNING-# emitted below. ``context_from_snapshot`` runs at every research-run start-# AND at every per-URL fetch-gate check (``BaseSearchEngine.-# _build_full_search_egress_context``, called once per fetched URL), so an-# unclassifiable primary would otherwise emit one identical WARNING per-# fetched URL -- potentially hundreds per run. We remember, PER USER, which-# (sanitized) primary engines have already warned, so a genuinely new+# emitted below. Multiple run setup paths build contexts for the same+# (user, primary) pair, so an unclassifiable primary would otherwise emit+# repeated warnings. We remember, PER USER, which (sanitized) primary+# engines have already warned, so a genuinely new# (user, primary) combination still logs once while repeats are silent.## The dedup MUST be keyed on the actual user identity (a stable hash of the@@ -2332,14 +2330,23 @@ def resolve_run_primary_engine(``filter_candidates_by_egress``) pass none and fail closed — the workerrefuses the run; advisory filters degrade to unfiltered with the factoryPEP still enforcing.- * the search-engine factory passes ``default=engine_name`` because it is- evaluating that one specific engine, so deriving the scope from it is- meaningful rather than arbitrary.+ * the search-engine factory and per-engine checks pass+ ``default=engine_name`` outside STRICT because they evaluate that one+ specific engine. Under STRICT they require the saved primary so an+ engine cannot authorize itself by becoming the fallback.Raises:- ValueError: ``search.tool`` is missing/blank/non-string and no truthy+ ValueError: The snapshot is neither a dictionary nor None, or+ ``search.tool`` is missing/blank/non-string and no truthy``default`` is given."""+ if settings_snapshot is not None and not isinstance(+ settings_snapshot, dict+ ):+ raise ValueError(+ "settings_snapshot must be a dict, got "+ f"{type(settings_snapshot).__name__}"+ )primary = (_get_setting_value(settings_snapshot, "search.tool", None)if settings_snapshotdiff --git a/src/local_deep_research/utilities/type_utils.py b/src/local_deep_research/utilities/type_utils.pyindex 757033edc2..e22580914a 100644--- a/src/local_deep_research/utilities/type_utils.py+++ b/src/local_deep_research/utilities/type_utils.py@@ -137,7 +137,7 @@ _RUNTIME_SETTING_MAP = ()-def _is_strict_scope(snapshot: dict) -> bool:+def _is_strict_scope(snapshot: dict | None) -> bool:"""Best-effort STRICT-scope detection on a settings snapshot.Returns True when ``policy.egress_scope`` resolves to ``strict``,@@ -162,6 +162,8 @@ def _is_strict_scope(snapshot: dict) -> bool:env_scope = check_env_setting("policy.egress_scope")if env_scope:return str(env_scope).strip().lower() == "strict"+ if not isinstance(snapshot, dict):+ return Falseraw = snapshot.get("policy.egress_scope")if isinstance(raw, dict) and "value" in raw:raw = raw["value"]diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.pyindex 8313b23034..7ab6de0c75 100644--- a/src/local_deep_research/web/routers/rag.py+++ b/src/local_deep_research/web/routers/rag.py@@ -86,7 +86,6 @@ from ...database.models.queue import TaskMetadatafrom ...database.thread_local_session import thread_cleanupfrom ...config.paths import get_library_directory-from ...constants import DEFAULT_SEARCH_TOOLfrom ..dependencies.json_body import json_body_errorfrom .notes import _log_value_preview@@ -917,49 +916,27 @@ def get_available_models(# Get provider classesprovider_classes = _get_provider_classes()- # Egress policy: fetching a cloud provider's model list opens a- # connection that carries the API key off-machine. Under an effective+ # Egress policy: availability checks and model discovery can open+ # connections to a provider. Under an effective# local-only embeddings posture (PRIVATE_ONLY / adaptive-private) we# must NOT probe remote-classified providers — mirror the PEP in- # embeddings_config.get_embeddings(). Build the run context once and- # fail closed (skip remote model fetches) if the policy can't evaluate.+ # embeddings_config.get_embeddings(). Fail closed before either+ # provider call if the policy can't evaluate.def _embeddings_model_fetch_allowed(provider_key: str) -> bool:try:from ...security.egress.policy import (context_from_snapshot,evaluate_embeddings,+ resolve_run_primary_engine,)- from ...config.thread_settings import (- get_setting_from_snapshot,- )- from ...search_system import username_from_snapshot- primary = (- get_setting_from_snapshot(- "search.tool",- default=DEFAULT_SEARCH_TOOL,- settings_snapshot=settings_snapshot,- )- or DEFAULT_SEARCH_TOOL- )# Thread username so a per-user private retriever primary# resolves PRIVATE_ONLY (forcing local embeddings) and this# route can't probe a remote embedder for that user.ctx = context_from_snapshot(settings_snapshot,- primary,- # `session.get(...)` here was a leftover Flask global --- # undefined in this module, so this line raised NameError- # on EVERY call (the snapshot never carries `_username`:- # only ensure_snapshot_username injects it, and this route- # does not call it). The enclosing `except Exception` failed- # closed and returned False, so the model-list probe was- # skipped for every provider and the embeddings dropdown- # was permanently empty for every user. `username` is the- # route's authenticated user, closed over from- # get_available_models.- username=username_from_snapshot(settings_snapshot)- or username,+ resolve_run_primary_engine(settings_snapshot),+ username=username,)if not ctx.require_local_embeddings:return True@@ -996,7 +973,10 @@ def get_available_models(providers = {}for provider_key, provider_class in provider_classes.items():- available = provider_class.is_available(settings_snapshot)+ policy_allowed = _embeddings_model_fetch_allowed(provider_key)+ available = policy_allowed and provider_class.is_available(+ settings_snapshot+ )# Always show the provider in the dropdown so users can# configure its settings (e.g. fix a wrong Ollama URL).@@ -1005,13 +985,12 @@ def get_available_models("value": provider_key,"label": provider_labels.get(provider_key, provider_key),"available": available,+ "policy_allowed": policy_allowed,})- # Only fetch models when the provider is reachable AND egress- # policy permits probing it (cloud providers are skipped under a- # local-only posture).- if available and _embeddings_model_fetch_allowed(provider_key):+ # Availability is checked only after the policy permits probing.+ if available:models = provider_class.get_available_models(settings_snapshot)providers[provider_key] = [{diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.jsindex 981edc7fea..d4aa0c6dcd 100644--- a/src/local_deep_research/web/static/js/embedding_settings.js+++ b/src/local_deep_research/web/static/js/embedding_settings.js@@ -721,9 +721,12 @@ function populateProviders() {providerOptions.forEach(provider => {const option = document.createElement('option');option.value = provider.value;- option.textContent = provider.available === false- ? provider.label + ' (unavailable)'- : provider.label;+ option.textContent = provider.label;+ if (provider.policy_allowed === false) {+ option.textContent += ' (blocked by egress policy)';+ } else if (provider.available === false) {+ option.textContent += ' (unavailable)';+ }providerSelect.appendChild(option);});@@ -757,10 +760,12 @@ function updateModelOptions() {warning.id = 'provider-unavailable-warning';warning.className = 'ldr-alert ldr-alert-danger';warning.style.marginTop = '8px';- // bearer:disable javascript_lang_dangerous_insert_html- warning.innerHTML = '<i class="fas fa-exclamation-triangle"></i> ' +- escapeHtml(providerInfo.label) +- ' is not reachable. Check the URL or service and try again.';+ const icon = document.createElement('i');+ icon.className = 'fas fa-exclamation-triangle';+ warning.append(icon, ' ' + providerInfo.label ++ (providerInfo.policy_allowed === false+ ? ' model discovery is blocked by your egress policy. Availability has not been checked.'+ : ' is not reachable. Check the URL or service and try again.'));const providerSelect = document.getElementById('embedding-provider');providerSelect.parentNode.insertBefore(warning, providerSelect.nextSibling);}@@ -908,7 +913,7 @@ function updateProviderInfo() {// Add provider-specific noteslet providerNote = '';- if (providerKey === 'ollama') {+ if (providerKey === 'ollama' && provider.policy_allowed !== false) {const embeddingCount = models.filter(function(m) { return m.is_embedding === true; }).length;providerNote = `<div class="ldr-alert ldr-alert-info" style="margin-top: 10px; padding: 8px 12px; font-size: 0.85em;">@@ -931,7 +936,11 @@ function updateProviderInfo() {}let statusIcon, statusText, statusClass;- if (provider.available === false) {+ if (provider.policy_allowed === false) {+ statusIcon = 'fa-ban';+ statusText = 'Blocked by egress policy';+ statusClass = 'ldr-provider-status-unavailable';+ } else if (provider.available === false) {statusIcon = 'fa-exclamation-triangle';statusText = 'Not reachable';statusClass = 'ldr-provider-status-unavailable';diff --git a/src/local_deep_research/web/warning_checks/__init__.py b/src/local_deep_research/web/warning_checks/__init__.pyindex 22ff644c2f..30bf10c0f3 100644--- a/src/local_deep_research/web/warning_checks/__init__.py+++ b/src/local_deep_research/web/warning_checks/__init__.py@@ -170,7 +170,10 @@ def calculate_warnings(username: Optional[str] = None) -> List[dict]:effective_require_local_endpoint = require_local_endpointeffective_require_local_embeddings = require_local_embeddingstry:- from ...security.egress.policy import context_from_snapshot+ from ...security.egress.policy import (+ context_from_snapshot,+ resolve_run_primary_engine,+ )_snap = settings_manager.get_settings_snapshot()if isinstance(_snap, dict):@@ -182,7 +185,7 @@ def calculate_warnings(username: Optional[str] = None) -> List[dict]:# classification — accuracy here is best-effort by design._eff_ctx = context_from_snapshot(_snap,- primary_engine or DEFAULT_SEARCH_TOOL,+ resolve_run_primary_engine(_snap),username=username,allow_dns=False,)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 8f1a6d687b..d63db1460e 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@@ -51,18 +51,13 @@ class ElasticsearchSearchEngine(BaseSearchEngine):from ...security.egress.policy import (EgressScope,context_from_snapshot,+ resolve_run_primary_engine,)- from ...config.thread_settings import get_setting_from_snapshotfrom ...search_system import username_from_snapshotsnapshot = settings_snapshot or {}- primary = (- get_setting_from_snapshot(- "search.tool",- default=DEFAULT_SEARCH_TOOL,- settings_snapshot=snapshot,- )- or DEFAULT_SEARCH_TOOL+ primary = resolve_run_primary_engine(+ snapshot, default=DEFAULT_SEARCH_TOOL)ctx = context_from_snapshot(snapshot, primary, username=username_from_snapshot(snapshot)diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.pyindex 5aa630ff74..b70e47c787 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py@@ -551,6 +551,9 @@ ONE WORD ONLY:"""Returns:List of search results"""+ # Recheck cached engines before provider work; policy denials must+ # escape the search-error handler below.+ self._verify_egress_scope()logger.info("---Execute a search using The Guardian (enhanced)---")# Additional safety check for None querydiff --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 cbfab60113..4480c5d583 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@@ -730,6 +730,8 @@ IMPORTANT: Output ONLY the search query. No explanations, no additional text."""Returns:List of search results in LDR format"""+ # Keep policy denials outside the search-error handler.+ self._verify_egress_scope()try:# Get previewspreviews = self._get_previews(query)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 4226997595..db947b9a4e 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@@ -6,6 +6,7 @@ import requestsfrom langchain_core.language_models import BaseLLMfrom ...security import redact_url_for_log+from ...security.egress.policy import PolicyDeniedErrorfrom ...security.safe_requests import safe_getfrom ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity@@ -860,6 +861,8 @@ https://searxng.github.io/searxng/admin/installation.htmlresults = super().run(query, research_context=research_context)logger.info(f"SearXNG search completed with {len(results)} results")return results+ except PolicyDeniedError:+ raiseexcept Exception as e:safe_msg = self._scrub_error(e)logger.exception(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 0f276c708d..ee6e2303b4 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@@ -14,7 +14,7 @@ from tenacity import (from tenacity.wait import wait_basefrom ..advanced_search_system.filters.base_filter import BaseFilter-from ..utilities.type_utils import unwrap_setting+from ..utilities.type_utils import _is_strict_scope, unwrap_settingfrom ..config.constants import DEFAULT_MAX_FILTERED_RESULTSfrom ..config.thread_settings import get_setting_from_snapshotfrom ..security.log_sanitizer import sanitize_error_message, scrub_error@@ -28,7 +28,6 @@ from .engine_availability import (is_query_error,retry_after_from_error,)-from ..constants import DEFAULT_SEARCH_TOOLif TYPE_CHECKING:from ..advanced_search_system.filters.journal_reputation_filter import (@@ -591,7 +590,8 @@ class BaseSearchEngine(ABC):scope in ``self.settings_snapshot`` before executing a search.No-op when ``settings_snapshot`` is missing or empty (programmatic- API callers) or when ``_engine_name`` has not been set. Raises+ API callers) unless the operator enforces STRICT, or when+ ``_engine_name`` has not been set. Raises``PolicyDeniedError`` when the policy denies the engine; any otherinternal error in the policy evaluation is logged and ignored so abroken backstop never takes down searches the factory PEP already@@ -599,11 +599,10 @@ class BaseSearchEngine(ABC):This is a defense-in-depth check behind the factory PEP, thestrategy-level filters, and the audit hook. It covers engines that- bypassed the factory (direct instantiation with a snapshot). Note- the limit: the snapshot is the one captured at construction, so a- scope change AFTER construction is only caught if the caller also- refreshes ``settings_snapshot`` (assigns a NEW dict — in-place- mutation of the existing dict is not detected, see below).+ bypassed the factory (direct instantiation with a snapshot).+ Changes to the captured scope or primary are caught both when the+ caller refreshes ``settings_snapshot`` and when it edits those+ keys in place.The verification is memoized per snapshot IDENTITY plus thepolicy-relevant VALUES (scope, primary): the full policy inputs@@ -615,7 +614,7 @@ class BaseSearchEngine(ABC):scope/primary keys in place invalidates the memo and re-verifies.Denials are never memoized (they raise)."""- if not self.settings_snapshot:+ if not self.settings_snapshot and not _is_strict_scope(None):returnif not self._engine_name:# A snapshot WITHOUT a stamped engine name means a direct@@ -632,7 +631,8 @@ class BaseSearchEngine(ABC):)returnif (- self.settings_snapshot is self._egress_verified_snapshot+ self._egress_verified_snapshot is not None+ and self.settings_snapshot is self._egress_verified_snapshotand self._egress_policy_key() == self._egress_verified_policy_key):return@@ -680,20 +680,36 @@ class BaseSearchEngine(ABC):"""Inner helper so the raise is not inside the except handler(ruff TRY301). Raises PolicyDeniedError on scope mismatch."""from ..security.egress.policy import (+ Decision,PolicyDeniedError,context_from_snapshot,evaluate_engine,+ resolve_run_primary_engine,)from ..search_system import username_from_snapshot- primary = unwrap_setting(- self.settings_snapshot.get("search.tool", self._engine_name)- )- ctx = context_from_snapshot(- self.settings_snapshot,- primary or self._engine_name,- username=username_from_snapshot(self.settings_snapshot),- )+ try:+ # Match the factory: STRICT requires the saved primary and must+ # never let this engine approve itself as a fallback.+ primary_default = (+ None+ if _is_strict_scope(self.settings_snapshot)+ else self._engine_name+ )+ ctx = context_from_snapshot(+ self.settings_snapshot,+ resolve_run_primary_engine(+ self.settings_snapshot, default=primary_default+ ),+ username=username_from_snapshot(self.settings_snapshot),+ )+ except ValueError as exc:+ # The backstop propagates policy denials but ignores other+ # errors; invalid configuration must stop a cached engine too.+ raise PolicyDeniedError(+ Decision(False, "invalid_policy_config"),+ target=self._engine_name,+ ) from excdecision = evaluate_engine(self._engine_name,ctx,@@ -1352,12 +1368,21 @@ class BaseSearchEngine(ABC):unevaluable, we now turn full-content fetching off for thisengine instead."""- if not getattr(self, "settings_snapshot", None):+ snapshot = getattr(self, "settings_snapshot", None)+ if not snapshot and not _is_strict_scope(None):+ return None+ if not isinstance(snapshot, dict):+ logger.bind(policy_audit=True).warning(+ "Disabling include_full_content: settings snapshot "+ "is missing or malformed"+ )+ self.include_full_content = Falsereturn Nonetry:from ..security.egress.policy import (PolicyDeniedError,context_from_snapshot,+ resolve_run_primary_engine,)except ImportError:logger.debug(@@ -1368,18 +1393,18 @@ class BaseSearchEngine(ABC):from ..search_system import username_from_snapshot- primary_raw = unwrap_setting(- self.settings_snapshot.get("search.tool", DEFAULT_SEARCH_TOOL)- )try:# Thread username so a per-user private retriever primary# resolves PRIVATE_ONLY here too; otherwise the per-URL fetch# gate would fall back to BOTH and allow public hosts under a# run whose posture is private.+ primary_default = (+ None if _is_strict_scope(snapshot) else self._engine_name+ )return context_from_snapshot(- self.settings_snapshot,- primary_raw or DEFAULT_SEARCH_TOOL,- username=username_from_snapshot(self.settings_snapshot),+ snapshot,+ resolve_run_primary_engine(snapshot, default=primary_default),+ username=username_from_snapshot(snapshot),)except (PolicyDeniedError, ValueError) as exc:safe_msg = self._scrub_error(exc)diff --git a/tests/js/embedding-settings-runtime.test.js b/tests/js/embedding-settings-runtime.test.jsindex 65b994dd43..194779b1fa 100644--- a/tests/js/embedding-settings-runtime.test.js+++ b/tests/js/embedding-settings-runtime.test.js@@ -356,6 +356,46 @@ it('hydrates the real form from the migrated models and settings endpoints', asyexpect(document.getElementById('ollama-num-ctx').value).toBe('16384');});+it.each([+ [false, 'blocked by egress policy', 'Blocked by egress policy'],+ [true, 'unavailable', 'Not reachable'],+])('distinguishes provider policy denial from reachability (allowed=%s)', async (policyAllowed, optionStatus, cardStatus) => {+ const catalog = {+ ...MODELS,+ provider_options: [...MODELS.provider_options, {+ value: 'ollama', label: 'Ollama', available: false,+ policy_allowed: policyAllowed,+ }],+ providers: { ...MODELS.providers, ollama: [] },+ };+ const defaultFetch = installFetch();+ const fetchMock = vi.fn((url, options = {}) => (+ url === '/library/api/rag/models'+ ? Promise.resolve(jsonResponse(catalog))+ : defaultFetch(url, options)+ ));+ await loadPage(fetchMock);++ const provider = document.getElementById('embedding-provider');+ const option = Array.from(provider.options).find(item => item.value === 'ollama');+ expect(option.textContent).toBe(`Ollama (${optionStatus})`);+ expect(option.disabled).toBe(false);+ provider.value = 'ollama';+ provider.dispatchEvent(new Event('change'));+ await vi.waitFor(() => {+ const warning = document.getElementById('provider-unavailable-warning');+ expect(warning.textContent).toContain(+ policyAllowed ? 'not reachable' : 'blocked by your egress policy',+ );+ if (!policyAllowed) {+ expect(warning.textContent).not.toContain('not reachable');+ }+ });+ const card = Array.from(document.querySelectorAll('#provider-info .ldr-stat-card'))+ .find(item => item.querySelector('h4').textContent === 'Ollama');+ expect(card.querySelector('.ldr-provider-status').textContent).toContain(cardStatus);+});+it('ignores an older model catalog before reading its response body', async () => {const olderRequest = deferred();const olderResponse = {diff --git a/tests/mcp/test_egress_audit_net.py b/tests/mcp/test_egress_audit_net.pyindex 00da0a8329..3eb2074af7 100644--- a/tests/mcp/test_egress_audit_net.py+++ b/tests/mcp/test_egress_audit_net.py@@ -43,6 +43,27 @@ def test_arms_context_for_private_only():assert get_active_context() is None+def test_adaptive_padded_private_primary_arms_private_context():+ settings = {+ "policy.egress_scope": "adaptive",+ "search.tool": " library ",+ "_username": "tester",+ }+ with _egress_audit_net(settings):+ context = get_active_context()+ assert context is not None+ assert context.scope == EgressScope.PRIVATE_ONLY+ assert context.primary_engine == "library"+ assert get_active_context() is None+++def test_blank_primary_does_not_arm_an_invented_public_context():+ with _egress_audit_net(+ {"policy.egress_scope": "adaptive", "search.tool": " "}+ ):+ assert get_active_context() is None++def test_empty_settings_is_noop():with _egress_audit_net({}):assert get_active_context() is Nonediff --git a/tests/news/test_subscription_policy.py b/tests/news/test_subscription_policy.pyindex bfab972f16..58992a73cc 100644--- a/tests/news/test_subscription_policy.py+++ b/tests/news/test_subscription_policy.py@@ -16,7 +16,13 @@ from local_deep_research.news.api import _validate_subscription_policydef _mgr(snapshot, primary="arxiv"):m = Mock()- m.get_settings_snapshot.return_value = snapshot+ # Production snapshots include the saved primary. The policy now reads it+ # from that snapshot, rather than from a separate get_setting() call.+ m.get_settings_snapshot.return_value = (+ {"search.tool": primary, **snapshot}+ if isinstance(snapshot, dict)+ else snapshot+ )m.get_setting.side_effect = lambda key, default=None: (primary if key == "search.tool" else default)diff --git a/tests/research_library/routes/test_rag_routes_core_main_port.py b/tests/research_library/routes/test_rag_routes_core_main_port.pyindex ccc475c949..bca682aaba 100644--- a/tests/research_library/routes/test_rag_routes_core_main_port.py+++ b/tests/research_library/routes/test_rag_routes_core_main_port.py@@ -645,7 +645,7 @@ class TestEmbeddingProviderAvailability:from local_deep_research.web.routers.rag import get_available_modelssettings = Mock()- settings.get_all_settings.return_value = {}+ settings.get_all_settings.return_value = {"search.tool": "searxng"}with (patch(f"{_DB_CTX}.get_user_db_session") as mock_ctx,diff --git a/tests/research_library/routes/test_rag_routes_coverage_main_port.py b/tests/research_library/routes/test_rag_routes_coverage_main_port.pyindex 6cf2fe03fa..c63190ed02 100644--- a/tests/research_library/routes/test_rag_routes_coverage_main_port.py+++ b/tests/research_library/routes/test_rag_routes_coverage_main_port.py@@ -776,13 +776,16 @@ class TestGetAvailableModels:]with (- _route_env(),+ _route_env() as route_env,_allow_all_egress(),patch(f"{_EMBEDDINGS}._get_provider_classes",return_value={"sentence_transformers": mock_provider_class},),):+ route_env.settings.get_all_settings.return_value = {+ "search.tool": "searxng"+ }data = get_available_models(_fake_request(), username="testuser")assert data["success"] is Truediff --git a/tests/security/test_credential_leak_phase3.py b/tests/security/test_credential_leak_phase3.pyindex 147150670f..36e7070567 100644--- a/tests/security/test_credential_leak_phase3.py+++ b/tests/security/test_credential_leak_phase3.py@@ -15,6 +15,10 @@ from unittest.mock import Mock, patchimport pytestimport requests+from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+)+_LEAKED_KEY = "sk-phase3-sentinel-DO-NOT-APPEAR-IN-LOGS-9999"_LEAKED_TOKEN = "tok-paperless-sentinel-DO-NOT-APPEAR-8888"@@ -318,6 +322,7 @@ def _paperless_engine():)engine = mod.PaperlessSearchEngine.__new__(mod.PaperlessSearchEngine)+ BaseSearchEngine.__init__(engine, programmatic_mode=True)engine.api_token = _LEAKED_TOKENengine.api_url = "http://localhost:8000"engine.headers = {"Authorization": f"Token {_LEAKED_TOKEN}"}@@ -391,9 +396,12 @@ class TestPaperlessEngineKeyLeakage:exc = RuntimeError(f"Error: token={_LEAKED_TOKEN}")with loguru_caplog_full.at_level("DEBUG"):- with patch.object(engine, "_get_previews", side_effect=exc):+ with patch.object(+ engine, "_get_previews", side_effect=exc+ ) as previews:result = engine.run("query")+ previews.assert_called_once_with("query")assert result == []for encoding in _all_encodings_of(_LEAKED_TOKEN):assert encoding not in loguru_caplog_full.text@@ -597,6 +605,7 @@ def _guardian_engine():)engine = mod.GuardianSearchEngine.__new__(mod.GuardianSearchEngine)+ BaseSearchEngine.__init__(engine, programmatic_mode=True)engine.api_key = _LEAKED_KEYengine.engine_type = "test_engine"engine.rate_tracker = _stub_rate_tracker()@@ -629,7 +638,9 @@ class TestGuardianKeyLeakage:exc = RuntimeError(f"Unexpected error: key={_LEAKED_KEY}")with loguru_caplog_full.at_level("DEBUG"):- with patch.object(engine, "_get_previews", side_effect=exc):+ with patch.object(+ engine, "_get_previews", side_effect=exc+ ) as previews:engine._original_date_params = {"from_date": None,"to_date": None,@@ -639,6 +650,7 @@ class TestGuardianKeyLeakage:engine.programmatic_mode = Falseresult = engine.run("test query")+ previews.assert_called_once_with("test query")assert result == []for encoding in _all_encodings_of(_LEAKED_KEY):assert encoding not in loguru_caplog_full.textdiff --git a/tests/security/test_egress_adaptive_resolution_followup.py b/tests/security/test_egress_adaptive_resolution_followup.pyindex eec8b99c4f..b65a8bbce2 100644--- a/tests/security/test_egress_adaptive_resolution_followup.py+++ b/tests/security/test_egress_adaptive_resolution_followup.py@@ -310,11 +310,10 @@ def test_resolve_adaptive_classified_private_retriever_does_not_warn():# ---------------------------------------------------------------------------# The fail-open warning must be DEDUPED (log-spam guard): context_from_snapshot-# fires on every research-run start AND on every per-URL fetch-gate check-# (BaseSearchEngine._build_full_search_egress_context is called once per-# fetched URL), so an unclassifiable primary would otherwise emit one-# identical WARNING per fetched URL. It must fire at most once per unique-# (primary, username-presence) pair in the process, and must scrub a+# can run in multiple setup paths for the same research run, so an+# unclassifiable primary would otherwise emit repeated warnings. It must+# fire at most once per unique+# (primary, user) pair in the process, and must scrub a# log-injection payload embedded in the (user-controlled) primary name.# ---------------------------------------------------------------------------diff --git a/tests/security/test_egress_engine_run_overrides.py b/tests/security/test_egress_engine_run_overrides.pynew file mode 100644index 0000000000..9dc1f3cd2c--- /dev/null+++ b/tests/security/test_egress_engine_run_overrides.py@@ -0,0 +1,101 @@+"""Factory-created engines enforce policy through their public run methods."""++from copy import deepcopy+from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.security.egress.audit_hook import clear_active_context+from local_deep_research.security.egress.policy import PolicyDeniedError+from local_deep_research.web_search_engines.search_engine_factory import (+ create_search_engine,+)+++ params=["guardian", "paperless", "searxng", "arxiv", "wikipedia"]+)+def engine(request, monkeypatch):+ name = request.param+ monkeypatch.delenv("LDR_POLICY_EGRESS_SCOPE", raising=False)+ clear_active_context()+ snapshot = {+ "policy.egress_scope": "strict",+ "search.tool": name,+ f"search.engine.web.{name}.display_name": name,+ f"search.engine.web.{name}.api_key": "test-provider-key",+ "search.engine.web.paperless.default_params.api_url": "http://127.0.0.1:8000",+ "search.engine.web.searxng.default_params.instance_url": "https://93.184.216.34",+ }+ # SearXNG checks its instance during construction; never contact a server.+ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get",+ return_value=MagicMock(status_code=200),+ ):+ instance = create_search_engine(+ name,+ settings_snapshot=snapshot,+ programmatic_mode=True,+ use_full_search=False,+ )+ assert instance is not None+ assert instance._engine_name == name+ try:+ yield instance+ finally:+ instance.close()+ clear_active_context()++[email protected]("changed_primary", ["blank", "different", "malformed"])[email protected]("wrapped", [False, True], ids=["flat", "wrapped"])+ "refresh", [False, True], ids=["in-place", "refreshed"]+)+def test_cached_run_denies_before_provider_work(+ engine, changed_primary, wrapped, refresh+):+ original = deepcopy(engine.settings_snapshot)+ if wrapped:+ engine.settings_snapshot["search.tool"] = {"value": engine._engine_name}+ with patch.object(engine, "_get_previews", return_value=[]) as provider:+ assert engine.run("test query") == []+ assert provider.called # Warm the public entry point and guard memo.++ if refresh:+ engine.settings_snapshot = deepcopy(engine.settings_snapshot)+ primary = {+ "blank": " ",+ "different": "wikipedia" if engine._engine_name == "arxiv" else "arxiv",+ "malformed": [engine._engine_name],+ }[changed_primary]+ engine.settings_snapshot["search.tool"] = (+ {"value": primary} if wrapped else primary+ )++ with patch.object(engine, "_get_previews", return_value=[]) as provider:+ for _ in range(2):+ with pytest.raises(PolicyDeniedError):+ engine.run("test query")+ provider.assert_not_called()+ with pytest.raises(PolicyDeniedError):+ create_search_engine(+ engine._engine_name,+ settings_snapshot=engine.settings_snapshot,+ programmatic_mode=True,+ use_full_search=False,+ )++ engine.settings_snapshot = original+ with patch.object(engine, "_get_previews", return_value=[]) as provider:+ assert engine.run("test query") == []+ assert (+ provider.called+ ) # Denials must not poison a restored valid policy.+++def test_programmatic_run_without_snapshot_retains_behavior(engine):+ engine.settings_snapshot = None+ with patch.object(engine, "_get_previews", return_value=[]) as provider:+ assert engine.run("test query") == []+ assert provider.calleddiff --git a/tests/security/test_egress_news_subscription_callsite.py b/tests/security/test_egress_news_subscription_callsite.pyindex f996c856ec..99e792312b 100644--- a/tests/security/test_egress_news_subscription_callsite.py+++ b/tests/security/test_egress_news_subscription_callsite.py@@ -58,7 +58,11 @@ STRAY_META_PRIMARY = {"policy.egress_scope": "strict", "search.tool": "auto"}def _settings_manager(snapshot, primary="arxiv"):"""Fake SettingsManager exposing the snapshot + search.tool primary."""sm = MagicMock()- sm.get_settings_snapshot.return_value = snapshot+ sm.get_settings_snapshot.return_value = (+ {"search.tool": primary, **snapshot}+ if isinstance(snapshot, dict)+ else snapshot+ )sm.get_setting.side_effect = lambda key, default=None: (primary if key == "search.tool" else default)diff --git a/tests/security/test_egress_notification_owner.py b/tests/security/test_egress_notification_owner.pynew file mode 100644index 0000000000..ba21653fdd--- /dev/null+++ b/tests/security/test_egress_notification_owner.py@@ -0,0 +1,134 @@+"""Notification policy uses the owner passed by production queue callers."""++from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.notifications.manager import (+ NotificationManager,+ NotificationReason,+)+from local_deep_research.notifications import queue_helpers+from local_deep_research.web_search_engines import (+ retriever_registry as registry_module,+)+++def registry(monkeypatch):+ monkeypatch.delenv("LDR_POLICY_EGRESS_SCOPE", raising=False)+ monkeypatch.setenv("LDR_NOTIFICATIONS_ALLOW_OUTBOUND", "true")+ monkeypatch.setattr(NotificationManager, "_shared_rate_limiter", None)+ registry = registry_module.RetrieverRegistry()+ monkeypatch.setattr(registry_module, "retriever_registry", registry)+ return registry+++def _snapshot(wrapped):+ policy = {+ "policy.egress_scope": "adaptive",+ "search.tool": " owner-corpus ",+ }+ if wrapped:+ policy = {key: {"value": value} for key, value in policy.items()}+ return {+ **policy,+ "notifications.service_url": "slack://test-notification",+ "notifications.on_research_completed": True,+ "notifications.on_research_failed": True,+ }+++def _send_from_session(monkeypatch, snapshot, owner, event):+ """Keep the queue caller, manager and policy real; replace storage and send."""+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = (+ SimpleNamespace(query="test research")+ )+ settings = MagicMock()+ settings.get_settings_snapshot.return_value = snapshot+ results = []+ original_send = NotificationManager.send_notification++ def capture_result(manager, *args, **kwargs):+ result = original_send(manager, *args, **kwargs)+ results.append(result)+ return result++ monkeypatch.setattr(+ NotificationManager, "send_notification", capture_result+ )+ with (+ patch(+ "local_deep_research.settings.SettingsManager",+ return_value=settings,+ ),+ patch("local_deep_research.storage.get_report_storage") as storage,+ patch(+ "local_deep_research.notifications.url_builder.build_notification_url",+ return_value="/research/test-research",+ ),+ patch(+ "local_deep_research.notifications.service.NotificationService.send_event",+ return_value=True,+ ) as dispatch,+ ):+ storage.return_value.get_report.return_value = "test report"+ if event == "completed":+ queue_helpers.send_research_completed_notification_from_session(+ owner, "test-research", session+ )+ else:+ queue_helpers.send_research_failed_notification_from_session(+ owner, "test-research", "test failure", session+ )+ assert len(results) == 1, "the real manager must complete its policy check"+ return results[0], dispatch++[email protected]("event", ["completed", "failed"])[email protected]("wrapped", [False, True], ids=["flat", "wrapped"])[email protected]("namespace", ["alice", None], ids=["owned", "shared"])[email protected]("is_local", [False, True], ids=["public", "private"])+def test_queue_notification_uses_owner_without_snapshot_metadata(+ monkeypatch, registry, event, wrapped, namespace, is_local+):+ registry.register(+ "owner-corpus", MagicMock(), is_local=is_local, username=namespace+ )+ snapshot = _snapshot(wrapped)+ assert "_username" not in snapshot++ result, dispatch = _send_from_session(monkeypatch, snapshot, "alice", event)++ if is_local:+ assert result.reason is NotificationReason.EGRESS_DENIED+ dispatch.assert_not_called()+ else:+ assert result.reason is NotificationReason.SENT+ dispatch.assert_called_once()++[email protected]("owner", ["alice", "bob"])[email protected]("wrapped", [False, True], ids=["flat", "wrapped"])+def test_owner_namespace_wins_over_shared_and_stale_snapshot_identity(+ monkeypatch, registry, owner, wrapped+):+ registry.register("owner-corpus", MagicMock(), is_local=False)+ registry.register(+ "owner-corpus", MagicMock(), is_local=True, username="alice"+ )+ snapshot = _snapshot(wrapped)+ snapshot["_username"] = "bob" if owner == "alice" else "alice"++ result, dispatch = _send_from_session(+ monkeypatch, snapshot, owner, "completed"+ )++ if owner == "alice":+ assert result.reason is NotificationReason.EGRESS_DENIED+ dispatch.assert_not_called()+ else:+ assert result.reason is NotificationReason.SENT+ dispatch.assert_called_once()diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.pyindex ba3c155654..bc3c45b7c2 100644--- a/tests/security/test_egress_policy.py+++ b/tests/security/test_egress_policy.py@@ -3146,6 +3146,21 @@ class TestResolveRunPrimaryEngine:def test_custom_default_used_when_missing(self):assert resolve_run_primary_engine({}, default="arxiv") == "arxiv"+ def test_custom_default_used_without_snapshot(self):+ assert resolve_run_primary_engine(None, default="arxiv") == "arxiv"++ @pytest.mark.parametrize(+ "snapshot", [[], ["pubmed"], False, 5, "", "invalid-snapshot"]+ )+ @pytest.mark.parametrize("default", [None, "arxiv"])+ def test_malformed_snapshot_cannot_select_a_default(+ self, snapshot, default+ ):+ with pytest.raises(+ ValueError, match="settings_snapshot must be a dict"+ ):+ resolve_run_primary_engine(snapshot, default=default)+def test_custom_default_used_when_empty(self):assert (resolve_run_primary_engine({"search.tool": ""}, default="arxiv")diff --git a/tests/security/test_egress_primary_builder_consistency.py b/tests/security/test_egress_primary_builder_consistency.pynew file mode 100644index 0000000000..d25925df81--- /dev/null+++ b/tests/security/test_egress_primary_builder_consistency.py@@ -0,0 +1,194 @@+"""A padded saved primary must not weaken secondary egress gates (#6575)."""++from contextlib import contextmanager+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.security.egress.audit_hook import (+ clear_active_context,+ get_active_context,+)+from local_deep_research.security.egress.policy import (+ EgressScope,+ PolicyDeniedError,+)+++PRIVATE_RUN = {"policy.egress_scope": "adaptive", "search.tool": " library "}+++def test_research_backstop_arms_private_context_for_padded_primary():+ from local_deep_research.search_system import AdvancedSearchSystem++ system = SimpleNamespace(settings_snapshot=PRIVATE_RUN, username="alice")+ clear_active_context()+ try:+ assert AdvancedSearchSystem._arm_egress_backstop(system)+ assert get_active_context().scope == EgressScope.PRIVATE_ONLY+ assert get_active_context().primary_engine == "library"+ finally:+ clear_active_context()+++def test_research_backstop_does_not_invent_primary_for_blank_setting():+ from local_deep_research.search_system import AdvancedSearchSystem++ system = SimpleNamespace(+ settings_snapshot={**PRIVATE_RUN, "search.tool": " "},+ username="alice",+ )+ clear_active_context()+ assert not AdvancedSearchSystem._arm_egress_backstop(system)+ assert get_active_context() is None+++def test_download_service_refuses_public_url_under_padded_private_primary():+ from local_deep_research.research_library.services.download_service import (+ DownloadService,+ )++ service = SimpleNamespace(username="alice", _policy_locked=False)+ context = DownloadService._build_egress_context(service, PRIVATE_RUN)+ assert context.scope == EgressScope.PRIVATE_ONLY+ service._egress_context = context+ allowed, _ = DownloadService._check_url_against_policy(+ service, "https://93.184.216.34/paper.pdf"+ )+ assert not allowed++ default_context = DownloadService._build_egress_context(+ service, {**PRIVATE_RUN, "search.tool": " "}+ )+ assert default_context.scope == EgressScope.PUBLIC_ONLY+ assert not service._policy_locked+++def test_notifications_refuse_vendor_url_under_padded_private_primary():+ from local_deep_research.notifications.manager import NotificationManager++ manager = SimpleNamespace(_settings_snapshot=PRIVATE_RUN, _user_id="alice")+ assert (+ NotificationManager._filter_urls_by_egress_policy(+ manager, "slack://token"+ )+ == ""+ )+ manager._settings_snapshot = {**PRIVATE_RUN, "search.tool": " "}+ assert (+ NotificationManager._filter_urls_by_egress_policy(+ manager, "http://127.0.0.1/webhook"+ )+ == ""+ )+++def test_journal_fetch_is_skipped_for_padded_or_blank_private_primary():+ from local_deep_research.advanced_search_system.filters.journal_reputation_filter import (+ JournalReputationFilter,+ )++ journal = SimpleNamespace(+ _JournalReputationFilter__settings_snapshot=PRIVATE_RUN+ )+ assert JournalReputationFilter._should_skip_journal_fetch_for_scope(journal)+ journal._JournalReputationFilter__settings_snapshot = {+ **PRIVATE_RUN,+ "search.tool": " ",+ }+ assert JournalReputationFilter._should_skip_journal_fetch_for_scope(journal)+++def test_news_subscription_rejects_public_engine_for_padded_private_primary():+ from local_deep_research.news.api import _validate_subscription_policy++ settings = MagicMock()+ settings.get_settings_snapshot.return_value = PRIVATE_RUN+ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=settings,+ ):+ reason = _validate_subscription_policy(+ MagicMock(), "alice", search_engine="arxiv", model_provider=None+ )+ assert reason is not None+ assert "not permitted" in reason++ settings.get_settings_snapshot.return_value = {+ **PRIVATE_RUN,+ "search.tool": " ",+ }+ assert (+ _validate_subscription_policy(+ MagicMock(), "alice", search_engine="arxiv", model_provider=None+ )+ == "egress policy is misconfigured"+ )+ settings.get_setting.assert_not_called()+++def test_elasticsearch_cloud_id_refused_under_padded_private_primary():+ from local_deep_research.web_search_engines.engines.search_engine_elasticsearch import (+ ElasticsearchSearchEngine,+ )++ assert ElasticsearchSearchEngine._cloud_id_forbidden_by_scope(PRIVATE_RUN)+ assert not ElasticsearchSearchEngine._cloud_id_forbidden_by_scope(+ {**PRIVATE_RUN, "search.tool": " searxng "}+ )+++def test_engine_backstop_and_full_content_share_private_scope():+ from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )++ engine = SimpleNamespace(+ settings_snapshot=PRIVATE_RUN,+ _engine_name="arxiv",+ include_full_content=True,+ )+ with pytest.raises(PolicyDeniedError):+ BaseSearchEngine._check_egress_policy(engine)++ context = BaseSearchEngine._build_full_search_egress_context(engine)+ assert context.scope == EgressScope.PRIVATE_ONLY+ assert context.primary_engine == "library"+++def test_rag_model_list_does_not_probe_cloud_under_padded_private_primary():+ from local_deep_research.web.routers.rag import get_available_models++ @contextmanager+ def fake_session(_username):+ yield MagicMock()++ settings = MagicMock()+ settings.get_all_settings.return_value = PRIVATE_RUN+ cloud_provider = MagicMock()+ cloud_provider.is_available.return_value = True+ cloud_provider.get_available_models.return_value = [+ {"value": "cloud-model", "label": "Cloud model"}+ ]++ with (+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ fake_session,+ ),+ patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=settings,+ ),+ patch(+ "local_deep_research.embeddings.embeddings_config._get_provider_classes",+ return_value={"openai": cloud_provider},+ ),+ ):+ response = get_available_models(request=MagicMock(), username="alice")++ assert response["success"]+ assert response["providers"]["openai"] == []+ cloud_provider.is_available.assert_not_called()+ cloud_provider.get_available_models.assert_not_called()diff --git a/tests/security/test_egress_rag_model_probes.py b/tests/security/test_egress_rag_model_probes.pynew file mode 100644index 0000000000..02549bf7b6--- /dev/null+++ b/tests/security/test_egress_rag_model_probes.py@@ -0,0 +1,108 @@+"""RAG policy precedes both real Ollama discovery requests (#7259)."""++import json+from unittest.mock import MagicMock, patch++import pytest+import requests++from local_deep_research.embeddings.providers.implementations.ollama import (+ OllamaEmbeddingsProvider,+)+from local_deep_research.security.egress.audit_hook import clear_active_context+from local_deep_research.web.routers.rag import get_available_models++[email protected](autouse=True)+def isolated_policy(monkeypatch):+ for name in (+ "LDR_POLICY_EGRESS_SCOPE",+ "LDR_EMBEDDINGS_REQUIRE_LOCAL",+ "LDR_EMBEDDINGS_OLLAMA_URL",+ "LDR_LLM_OLLAMA_URL",+ ):+ monkeypatch.delenv(name, raising=False)+ clear_active_context()+ yield+ clear_active_context()++[email protected]("wrapped", [False, True], ids=["flat", "wrapped"])+ "scope,primary,url,allowed",+ [+ ("adaptive", "library", "https://93.184.216.34:11434", False),+ ("adaptive", " library ", "https://93.184.216.34:11434", False),+ ("adaptive", "library", "http://127.0.0.1:11434", True),+ ("adaptive", "wikipedia", "https://93.184.216.34:11434", True),+ ("private_only", "wikipedia", "https://93.184.216.34:11434", False),+ ("invalid", "library", "https://93.184.216.34:11434", False),+ ("adaptive", "", "https://93.184.216.34:11434", False),+ ],+)+def test_policy_precedes_availability_and_model_enumeration(+ wrapped, scope, primary, url, allowed+):+ snapshot = {+ "policy.egress_scope": scope,+ "search.tool": primary,+ "embeddings.ollama.url": url,+ }+ if wrapped:+ snapshot = {key: {"value": value} for key, value in snapshot.items()}+ settings = MagicMock()+ settings.get_all_settings.return_value = snapshot++ def transport(_adapter, request, **kwargs):+ response = requests.Response()+ response.status_code = 200+ response.url = request.url+ response.request = request+ if request.method == "GET" and request.url == url + "/api/tags":+ payload = {"models": [{"name": "test-embedding"}]}+ elif request.method == "POST" and request.url == url + "/api/show":+ payload = {"capabilities": ["embedding"]}+ else:+ pytest.fail(+ f"Unexpected provider request: {request.method} {request.url}"+ )+ response._content = json.dumps(payload).encode()+ response.headers["Content-Length"] = str(len(response._content))+ response.encoding = "utf-8"+ return response++ with (+ patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ),+ patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=settings,+ ),+ patch(+ "local_deep_research.embeddings.embeddings_config._get_provider_classes",+ return_value={"ollama": OllamaEmbeddingsProvider},+ ),+ patch(+ "requests.adapters.HTTPAdapter.send",+ autospec=True,+ side_effect=transport,+ ) as outbound,+ ):+ response = get_available_models(MagicMock(), username="alice")++ assert response["success"] is True+ assert len(response["provider_options"]) == 1+ provider = response["provider_options"][0]+ assert provider["value"] == "ollama"+ if allowed:+ assert outbound.call_count == 3 # Availability, catalog, capabilities.+ assert provider["available"] is True+ assert provider["policy_allowed"] is True+ assert response["providers"]["ollama"][0]["value"] == "test-embedding"+ assert response["providers"]["ollama"][0]["is_embedding"] is True+ else:+ outbound.assert_not_called()+ assert provider["available"] is False+ assert provider["policy_allowed"] is False+ assert response["providers"]["ollama"] == []diff --git a/tests/security/test_egress_strict_engine_primary.py b/tests/security/test_egress_strict_engine_primary.pynew file mode 100644index 0000000000..bcf718bfa7--- /dev/null+++ b/tests/security/test_egress_strict_engine_primary.py@@ -0,0 +1,216 @@+"""STRICT runtime checks must agree with the factory on saved primaries."""++from copy import deepcopy+from unittest.mock import patch++import pytest++from local_deep_research.security.egress.audit_hook import clear_active_context+from local_deep_research.security.egress.policy import (+ EgressScope,+ PolicyDeniedError,+)+from local_deep_research.web_search_engines.search_engine_factory import (+ create_search_engine,+)+++MISSING = object()+INVALID_PRIMARIES = [+ pytest.param(MISSING, id="missing"),+ pytest.param(None, id="null"),+ pytest.param("", id="empty"),+ pytest.param(" ", id="spaces"),+ pytest.param("\t\n", id="tabs-newline"),+ pytest.param(5, id="integer"),+ pytest.param(["wikipedia"], id="list"),+ pytest.param({"other": "wikipedia"}, id="dictionary"),+]+INVALID_SNAPSHOTS = [+ pytest.param({}, id="empty-dictionary"),+ pytest.param(None, id="null"),+ pytest.param([], id="empty-list"),+ pytest.param(5, id="integer"),+ pytest.param("invalid-snapshot", id="string"),+]+++def wikipedia_engine(monkeypatch):+ monkeypatch.delenv("LDR_POLICY_EGRESS_SCOPE", raising=False)+ clear_active_context()+ engine = create_search_engine(+ "wikipedia",+ settings_snapshot={+ "policy.egress_scope": "strict",+ "search.tool": "wikipedia",+ "search.engine.web.wikipedia.display_name": "Wikipedia",+ },+ programmatic_mode=True,+ use_full_search=False,+ )+ assert engine is not None+ assert engine._engine_name == "wikipedia"+ try:+ yield engine+ finally:+ engine.close()+ clear_active_context()+++def _set_strict_source(engine, strict_source, monkeypatch):+ if strict_source == "operator":+ engine.settings_snapshot["policy.egress_scope"] = {"value": "adaptive"}+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", " STRICT ")+ else:+ engine.settings_snapshot["policy.egress_scope"] = {"value": " strict "}+++def _update_primary(engine, primary, wrapped, refresh):+ snapshot = (+ deepcopy(engine.settings_snapshot)+ if refresh+ else engine.settings_snapshot+ )+ if primary is MISSING:+ snapshot.pop("search.tool")+ elif wrapped:+ snapshot["search.tool"]["value"] = primary+ else:+ snapshot["search.tool"] = primary+ engine.settings_snapshot = snapshot++[email protected]("primary", INVALID_PRIMARIES)[email protected]("wrapped", [False, True], ids=["raw", "wrapped"])+ "refresh", [False, True], ids=["in-place", "refreshed"]+)[email protected]("strict_source", ["saved", "operator"])+def test_invalid_strict_primary_stops_search_and_full_content(+ wikipedia_engine, monkeypatch, primary, wrapped, refresh, strict_source+):+ engine = wikipedia_engine+ _set_strict_source(engine, strict_source, monkeypatch)+ if wrapped:+ engine.settings_snapshot["search.tool"] = {"value": "wikipedia"}+ engine._verify_egress_scope() # Warm a legitimate runtime memo.+ _update_primary(engine, primary, wrapped, refresh)++ with patch.object(engine, "_get_previews", return_value=[]) as provider:+ # An invalid policy must not become a successful memoized decision.+ for _ in range(2):+ with pytest.raises(PolicyDeniedError) as exc_info:+ engine.run("synthetic review query")+ assert exc_info.value.decision.reason == "invalid_policy_config"+ provider.assert_not_called()++ with pytest.raises(PolicyDeniedError) as factory_error:+ create_search_engine(+ "wikipedia",+ settings_snapshot=engine.settings_snapshot,+ programmatic_mode=True,+ use_full_search=False,+ )+ assert factory_error.value.decision.reason == "invalid_policy_config"++ engine.include_full_content = True+ assert engine._build_full_search_egress_context() is None+ assert not engine.include_full_content++[email protected]("primary", [" wikipedia ", " arxiv "])[email protected]("wrapped", [False, True], ids=["raw", "wrapped"])+ "refresh", [False, True], ids=["in-place", "refreshed"]+)[email protected]("strict_source", ["saved", "operator"])+def test_valid_strict_primary_remains_authoritative(+ wikipedia_engine, monkeypatch, primary, wrapped, refresh, strict_source+):+ engine = wikipedia_engine+ _set_strict_source(engine, strict_source, monkeypatch)+ if wrapped:+ engine.settings_snapshot["search.tool"] = {"value": "wikipedia"}+ engine._verify_egress_scope()+ _update_primary(engine, primary, wrapped, refresh)++ with patch.object(engine, "_get_previews", return_value=[]) as provider:+ if primary.strip() == "wikipedia":+ assert engine.run("synthetic review query") == []+ provider.assert_called_once()+ else:+ with pytest.raises(PolicyDeniedError) as exc_info:+ engine.run("synthetic review query")+ assert exc_info.value.decision.reason == "strict_not_primary"+ provider.assert_not_called()++ context = engine._build_full_search_egress_context()+ assert context.scope == EgressScope.STRICT+ assert context.primary_engine == primary.strip()++[email protected]("scope", ["adaptive", "public_only", "private_only"])[email protected]("primary", INVALID_PRIMARIES)+def test_non_strict_engine_fallback_preserves_scope(+ wikipedia_engine, scope, primary+):+ engine = wikipedia_engine+ engine.settings_snapshot["policy.egress_scope"] = scope+ _update_primary(engine, primary, wrapped=False, refresh=False)++ with patch.object(engine, "_get_previews", return_value=[]) as provider:+ if scope == "private_only":+ with pytest.raises(PolicyDeniedError) as exc_info:+ engine.run("synthetic review query")+ assert (+ exc_info.value.decision.reason == "scope_mismatch_private_only"+ )+ provider.assert_not_called()+ else:+ assert engine.run("synthetic review query") == []+ provider.assert_called_once()++ context = engine._build_full_search_egress_context()+ assert context.primary_engine == "wikipedia"+ expected = "public_only" if scope == "adaptive" else scope+ assert context.scope.value == expected++[email protected]("snapshot", INVALID_SNAPSHOTS)[email protected]("warm_memo", [False, True], ids=["cold", "warm"])+def test_operator_strict_rejects_missing_or_malformed_snapshot(+ wikipedia_engine, monkeypatch, snapshot, warm_memo+):+ engine = wikipedia_engine+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", " STRICT ")+ if warm_memo:+ engine._verify_egress_scope()+ engine.settings_snapshot = snapshot++ with patch.object(engine, "_get_previews", return_value=[]) as provider:+ for _ in range(2):+ with pytest.raises(PolicyDeniedError) as exc_info:+ engine.run("synthetic review query")+ assert exc_info.value.decision.reason == "invalid_policy_config"+ provider.assert_not_called()++ engine.include_full_content = True+ assert engine._build_full_search_egress_context() is None+ assert not engine.include_full_content++[email protected]("snapshot", [None, {}], ids=["missing", "empty"])+def test_missing_snapshot_preserves_programmatic_behavior_without_strict(+ wikipedia_engine, snapshot+):+ engine = wikipedia_engine+ engine.settings_snapshot = snapshot++ with patch.object(engine, "_get_previews", return_value=[]) as provider:+ assert engine.run("synthetic review query") == []+ provider.assert_called_once()++ engine.include_full_content = True+ assert engine._build_full_search_egress_context() is None+ assert engine.include_full_contentdiff --git a/tests/web/warning_checks/test_orchestrator.py b/tests/web/warning_checks/test_orchestrator.pyindex f0c41c2ee2..312e30a7e1 100644--- a/tests/web/warning_checks/test_orchestrator.py+++ b/tests/web/warning_checks/test_orchestrator.py@@ -621,6 +621,24 @@ class TestCalculateWarningsUnprotectedBannerUsesEffectiveScope:assert "egress_unprotected" in {w["type"] for w in warnings}+def test_adaptive_warnings_resolve_padded_private_primary():+ from local_deep_research.web.warning_checks import calculate_warnings++ manager = _make_settings_manager(+ {"search.tool": " library ", "llm.provider": "openai"}+ )+ manager.get_settings_snapshot.return_value = {+ "policy.egress_scope": "adaptive",+ "search.tool": " library ",+ }+ with _patch_orchestrator(manager):+ warnings = calculate_warnings(username="alice")++ types = {warning["type"] for warning in warnings}+ assert "public_egress_enabled" not in types+ assert "cloud_llm_enabled" not in types++class TestSearxngPrivateUrlWarning:"""Orchestrator wiring for the SearXNG private-URL banner."""diff --git a/tests/web_search_engines/test_search_engine_base_query_logging.py b/tests/web_search_engines/test_search_engine_base_query_logging.pyindex 4aa1650fd8..fed6e4d466 100644--- a/tests/web_search_engines/test_search_engine_base_query_logging.py+++ b/tests/web_search_engines/test_search_engine_base_query_logging.py@@ -225,6 +225,7 @@ def test_guardian_success_path_omits_the_query_from_search_metadata():}engine = GuardianSearchEngine.__new__(GuardianSearchEngine)+ BaseSearchEngine.__init__(engine, programmatic_mode=True)engine.llm = Noneengine.max_filtered_results = Noneengine.from_date = "2026-01-01"