~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): add runtime egress scope verification in BaseSearchEngine (#4472)
LearningCircuit4bf5d49cf732
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py b/src/local_deep_research/web_search_engines/engines/search_engine_collection.pyindex 4d0b9ef1d8..e5b2e439af 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py@@ -60,6 +60,14 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):self.collection_id = collection_idself.collection_name = collection_nameself.collection_key = f"collection_{collection_id}"+ # The policy registry name for this engine is known at construction+ # (the factory only stamps registry engines), so set it here —+ # direct instantiations (e.g. the library search route) get the+ # runtime egress backstop without caller cooperation. NB: between+ # super().__init__ (which stamps "library") and this line the+ # instance briefly carries the parent's name — nothing may call+ # _verify_egress_scope() in that window.+ self._engine_name = self.collection_key# Load collection-specific embedding settingsself._load_collection_embedding_settings()@@ -135,6 +143,11 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):logger.error("Cannot search collection without username")return []+ # search() does not go through BaseSearchEngine.run(), so apply the+ # runtime egress backstop here as well. Raises PolicyDeniedError on+ # denial — deliberately BEFORE the broad try/except below.+ self._verify_egress_scope()+try:# Get RAG index info for this collectionwith get_user_db_session(self.username) as db_session:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.pyindex 69b553fc45..fb0824979e 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py@@ -56,6 +56,12 @@ class LibraryRAGSearchEngine(BaseSearchEngine):self.username = (settings_snapshot.get("_username") if settings_snapshot else None)+ # Self-stamp the policy registry name so direct instantiations get+ # the runtime egress backstop without caller cooperation (the+ # factory stamps registry engines, but routes/services may build+ # this engine directly). CollectionSearchEngine overrides this+ # with its collection key after calling super().__init__.+ self._engine_name = "library"if not self.username:logger.warning(@@ -115,6 +121,13 @@ class LibraryRAGSearchEngine(BaseSearchEngine):logger.error("Cannot search library without username")return []+ # search() can be called directly (bypassing run()), so apply the+ # runtime egress backstop here too. Memoized per snapshot, so the+ # run() -> _get_previews() -> search() path re-checks for free.+ # Raises PolicyDeniedError on denial — deliberately BEFORE the+ # broad try/except below.+ self._verify_egress_scope()+try:# Initialize serviceslibrary_service = LibraryService(username=self.username)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 b22225b541..3f767b3359 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@@ -298,6 +298,16 @@ class BaseSearchEngine(ABC):) # Store settings snapshotself.engine_type = self.__class__.__name__+ self._engine_name: str = "" # set by the factory after construction+ # The snapshot dict the runtime egress backstop last verified+ # against (identity comparison; holding the reference keeps the+ # memo valid — a verification re-runs when the caller assigns a+ # NEW snapshot) plus the policy-relevant VALUES it carried at+ # verification time, so an in-place mutation of the scope or+ # primary key on the same dict is also caught.+ self._egress_verified_snapshot: Optional[Dict[str, Any]] = None+ self._egress_verified_policy_key: Optional[tuple] = None+ self._egress_skip_warned = Falseself._configure_programmatic_mode(programmatic_mode)self._last_wait_time = (0.0 # Default to 0 for successful searches without rate limiting@@ -375,6 +385,123 @@ class BaseSearchEngine(ABC):search_result_count=self._last_results_count if success else 0,)+ def _verify_egress_scope(self) -> None:+ """Runtime backstop: verify this engine is allowed under the egress+ 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+ ``PolicyDeniedError`` when the policy denies the engine; any other+ internal error in the policy evaluation is logged and ignored so a+ broken backstop never takes down searches the factory PEP already+ approved.++ This is a defense-in-depth check behind the factory PEP, the+ strategy-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).++ The verification is memoized per snapshot IDENTITY plus the+ policy-relevant VALUES (scope, primary): the full policy inputs+ are stable for a given snapshot object, so re-evaluating on every+ ``run()`` would only repeat the same decision — and under+ ADAPTIVE scope with a URL-configurable primary the evaluation can+ include a DNS lookup (bounded at 2s), which must not become a+ per-search stall. Assigning a refreshed snapshot OR mutating the+ scope/primary keys in place invalidates the memo and re-verifies.+ Denials are never memoized (they raise).+ """+ if not self.settings_snapshot:+ return+ if not self._engine_name:+ # A snapshot WITHOUT a stamped engine name means a direct+ # instantiation the factory never saw and no subclass+ # self-stamps — the backstop cannot evaluate it. Surface the+ # gap in the audit log (once per instance) instead of+ # skipping silently.+ if not self._egress_skip_warned:+ self._egress_skip_warned = True+ logger.bind(policy_audit=True).warning(+ "egress backstop skipped: engine has a settings "+ "snapshot but no _engine_name stamped",+ engine_type=self.__class__.__name__,+ )+ return+ if (+ self.settings_snapshot is self._egress_verified_snapshot+ and self._egress_policy_key() == self._egress_verified_policy_key+ ):+ return+ from ..security.egress.policy import PolicyDeniedError++ try:+ self._check_egress_policy()+ except PolicyDeniedError:+ logger.bind(policy_audit=True).warning(+ "runtime egress backstop denied engine",+ engine=self._engine_name,+ )+ raise+ except Exception:+ logger.bind(policy_audit=True).debug(+ "egress runtime verify errored; "+ "factory PEP still enforces at instantiation",+ engine=self._engine_name,+ )+ else:+ self._egress_verified_snapshot = self.settings_snapshot+ self._egress_verified_policy_key = self._egress_policy_key()++ def _egress_policy_key(self) -> tuple:+ """The policy-relevant snapshot values the backstop memo guards on.++ Cheap dict reads only — no context construction, no DNS. Not an+ exhaustive input set (URL settings or DB-side collection flags can+ also influence the decision), but it covers the keys an in-place+ mutation would realistically target; the factory PEP remains the+ primary enforcement for everything else.++ MAINTENANCE: if a new snapshot key ever becomes policy-relevant in+ ``context_from_snapshot``/``evaluate_engine``, add it here too —+ otherwise an in-place mutation of that key returns a stale memo.++ """+ scope = self.settings_snapshot.get("policy.egress_scope")+ if isinstance(scope, dict) and "value" in scope:+ scope = scope.get("value")+ primary = self.settings_snapshot.get("search.tool")+ if isinstance(primary, dict) and "value" in primary:+ primary = primary.get("value")+ return (scope, primary)++ def _check_egress_policy(self) -> None:+ """Inner helper so the raise is not inside the except handler+ (ruff TRY301). Raises PolicyDeniedError on scope mismatch."""+ from ..security.egress.policy import (+ PolicyDeniedError,+ context_from_snapshot,+ evaluate_engine,+ )++ primary = self.settings_snapshot.get("search.tool", self._engine_name)+ if isinstance(primary, dict) and "value" in primary:+ primary = primary["value"]+ ctx = context_from_snapshot(+ self.settings_snapshot,+ primary or self._engine_name,+ username=self.settings_snapshot.get("_username"),+ )+ decision = evaluate_engine(+ self._engine_name,+ ctx,+ settings_snapshot=self.settings_snapshot,+ )+ if not decision.allowed:+ raise PolicyDeniedError(decision, target=self._engine_name)+def run(self, query: str, research_context: Dict[str, Any] | None = None) -> List[Dict[str, Any]]:@@ -394,6 +521,10 @@ class BaseSearchEngine(ABC):"""logger.info(f"---Execute a search using {self.__class__.__name__}---")+ # Runtime egress scope backstop: verify this engine is allowed+ # before making any HTTP requests.+ self._verify_egress_scope()+# Track search call for metrics (if available and not in programmatic mode)should_record_metrics = Falsecontext_was_set = Falsediff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.pyindex e0837579b5..d2404952f6 100644--- a/src/local_deep_research/web_search_engines/search_engine_factory.py+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py@@ -385,6 +385,11 @@ def create_search_engine(# Create the engine instance with filtered parametersengine = engine_class(**filtered_params)+ # Stamp the registry name so BaseSearchEngine._verify_egress_scope()+ # can check egress scope at run time.+ if isinstance(engine, BaseSearchEngine):+ engine._engine_name = engine_name+# Most engine subclasses do not name ``programmatic_mode`` in their# signature (or accept it via **kwargs without forwarding to# ``super().__init__``), so the constructor often falls back to thediff --git a/tests/web_search_engines/test_search_engine_base.py b/tests/web_search_engines/test_search_engine_base.pyindex 69363791b8..b7f23f1f75 100644--- a/tests/web_search_engines/test_search_engine_base.py+++ b/tests/web_search_engines/test_search_engine_base.py@@ -12,6 +12,8 @@ Tests cover:from unittest.mock import Mock+import pytest+from local_deep_research.config.constants import DEFAULT_MAX_FILTERED_RESULTS@@ -895,3 +897,452 @@ class TestInitFullSearchForwardsSettingsSnapshot:# The base class normalizes missing snapshot to {} not None — accept eithersnap = kwargs.get("settings_snapshot")assert snap is None or snap == {}+++# =============================================================================+# Runtime egress scope verification tests+# =============================================================================+++def _scope_snapshot(scope, tool="arxiv"):+ """Build a minimal settings snapshot for egress tests."""+ return {+ "policy.egress_scope": {"value": scope},+ "search.tool": {"value": tool},+ }+++def _make_egress_engine(engine_name="", snapshot=None, **kw):+ """Create a concrete BaseSearchEngine with egress fields wired up."""+ from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )++ class _E(BaseSearchEngine):+ def _get_previews(self, query):+ return []++ def _get_full_content(self, relevant_items):+ return relevant_items++ _E.__name__ = engine_name or "TestEngine"+ eng = _E(programmatic_mode=True, settings_snapshot=snapshot, **kw)+ if engine_name:+ eng._engine_name = engine_name+ return eng+++class TestVerifyEgressScope:+ """Tests for _verify_egress_scope and _check_egress_policy."""++ @staticmethod+ def _fake_engine_class(is_public=None, is_local=None):+ """Build a fake engine class with given flags for patching."""+ return type(+ "FakeEngine", (), {"is_public": is_public, "is_local": is_local}+ )++ def test_no_op_without_snapshot(self):+ """No settings_snapshot → silent pass-through."""+ eng = _make_egress_engine(engine_name="arxiv", snapshot=None)+ eng._verify_egress_scope() # should not raise++ def test_no_op_without_engine_name(self):+ """No _engine_name → silent pass-through."""+ eng = _make_egress_engine(+ snapshot=_scope_snapshot("private_only", "arxiv")+ )+ assert eng._engine_name == ""+ eng._verify_egress_scope() # should not raise++ def test_no_op_with_empty_snapshot(self):+ """Empty dict snapshot → silent pass-through."""+ eng = _make_egress_engine(engine_name="arxiv", snapshot={})+ eng._verify_egress_scope() # should not raise++ def test_denied_raises_on_direct_call(self):+ """_check_egress_policy raises PolicyDeniedError when a public+ engine is used under PRIVATE_ONLY scope."""+ from unittest.mock import patch++ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ fake_cls = self._fake_engine_class(is_public=True, is_local=False)+ snap = _scope_snapshot("private_only", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ with pytest.raises(PolicyDeniedError) as exc_info:+ eng._check_egress_policy()+ assert exc_info.value.target == "arxiv"++ def test_allowed_scope_does_not_raise(self):+ """Public engine under BOTH scope → no error."""+ from unittest.mock import patch++ fake_cls = self._fake_engine_class(is_public=True, is_local=False)+ snap = _scope_snapshot("both", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ eng._check_egress_policy() # should not raise++ def test_public_engine_allowed_under_public_only(self):+ """Public engine under PUBLIC_ONLY → allowed."""+ from unittest.mock import patch++ fake_cls = self._fake_engine_class(is_public=True, is_local=False)+ snap = _scope_snapshot("public_only", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ eng._check_egress_policy() # should not raise++ def test_local_engine_allowed_under_private_only(self):+ """Local engine under PRIVATE_ONLY → allowed."""+ from unittest.mock import patch++ fake_cls = self._fake_engine_class(is_public=False, is_local=True)+ snap = _scope_snapshot("private_only", "localengine")+ eng = _make_egress_engine(engine_name="localengine", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ eng._check_egress_policy() # should not raise++ def test_local_engine_denied_under_public_only(self):+ """Local engine under PUBLIC_ONLY → denied."""+ from unittest.mock import patch++ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ fake_cls = self._fake_engine_class(is_public=False, is_local=True)+ snap = _scope_snapshot("public_only", "localengine")+ eng = _make_egress_engine(engine_name="localengine", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ with pytest.raises(PolicyDeniedError):+ eng._check_egress_policy()++ def test_verify_propagates_policy_denied(self):+ """_verify_egress_scope re-raises PolicyDeniedError — the backstop+ actually denies rather than just logging."""+ from unittest.mock import patch++ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ fake_cls = self._fake_engine_class(is_public=True, is_local=False)+ snap = _scope_snapshot("private_only", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ with pytest.raises(PolicyDeniedError):+ eng._verify_egress_scope()++ def test_verify_swallows_internal_errors(self):+ """Unexpected internal errors in the policy evaluation are logged,+ not propagated — a broken backstop must not break searches the+ factory PEP already approved."""+ from unittest.mock import patch++ snap = _scope_snapshot("both", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch.object(+ eng, "_check_egress_policy", side_effect=RuntimeError("boom")+ ):+ eng._verify_egress_scope() # should not raise++ def test_snapshot_dict_value_extracted(self):+ """When search.tool is a dict with 'value', the value is extracted."""+ from unittest.mock import patch++ fake_cls = self._fake_engine_class(is_public=True, is_local=False)+ snap = {+ "policy.egress_scope": {"value": "both"},+ "search.tool": {"value": "arxiv"},+ }+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ eng._check_egress_policy() # arxiv under BOTH → allowed++ def test_run_raises_on_denied_engine(self):+ """run() propagates PolicyDeniedError from the runtime backstop —+ a denied engine must not execute its search."""+ from unittest.mock import patch++ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ fake_cls = self._fake_engine_class(is_public=True, is_local=False)+ snap = _scope_snapshot("private_only", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ with pytest.raises(PolicyDeniedError):+ eng.run("test query")++ def test_run_allows_permitted_engine(self):+ """run() proceeds normally when engine is allowed."""+ from unittest.mock import patch++ fake_cls = self._fake_engine_class(is_public=True, is_local=False)+ snap = _scope_snapshot("public_only", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ results = eng.run("test query")+ assert isinstance(results, list)++ def test_verification_memoized_per_snapshot_identity(self):+ """A successful verification is memoized for the SAME snapshot+ object: the policy is not re-evaluated on every run (under+ ADAPTIVE with a URL-configurable primary that evaluation can+ include a DNS lookup). Assigning a refreshed snapshot+ invalidates the memo."""+ from unittest.mock import patch++ snap = _scope_snapshot("both", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch.object(+ eng, "_check_egress_policy", wraps=eng._check_egress_policy+ ) as spy:+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=self._fake_engine_class(+ is_public=True, is_local=False+ ),+ ):+ eng._verify_egress_scope()+ eng._verify_egress_scope()+ eng._verify_egress_scope()+ assert spy.call_count == 1++ # A refreshed (new) snapshot object re-verifies.+ eng.settings_snapshot = _scope_snapshot("both", "arxiv")+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=self._fake_engine_class(+ is_public=True, is_local=False+ ),+ ):+ eng._verify_egress_scope()+ assert spy.call_count == 2++ def test_in_place_scope_mutation_invalidates_memo(self):+ """Mutating the scope key IN PLACE on the same snapshot dict must+ re-verify (the memo guards on the policy-relevant values, not just+ object identity) — and deny when the new scope forbids the engine."""+ from unittest.mock import patch++ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ fake_cls = self._fake_engine_class(is_public=True, is_local=False)+ snap = _scope_snapshot("both", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ eng._verify_egress_scope() # allowed and memoized+ # In-place mutation of the SAME dict object.+ eng.settings_snapshot["policy.egress_scope"]["value"] = (+ "private_only"+ )+ with pytest.raises(PolicyDeniedError):+ eng._verify_egress_scope()++ def test_denial_not_memoized(self):+ """Denials raise every time — only successful verifications are+ memoized."""+ from unittest.mock import patch++ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ fake_cls = self._fake_engine_class(is_public=True, is_local=False)+ snap = _scope_snapshot("private_only", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ with pytest.raises(PolicyDeniedError):+ eng._verify_egress_scope()+ with pytest.raises(PolicyDeniedError):+ eng._verify_egress_scope()++ def test_cached_engine_scope_change_denied(self):+ """A cached engine is re-checked against its CURRENT snapshot on+ every run. NB: the backstop reads ``self.settings_snapshot``, so a+ scope change is only caught when the caller refreshes the snapshot+ on the cached instance (as simulated here)."""+ from unittest.mock import patch++ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ fake_cls = self._fake_engine_class(is_public=True, is_local=False)+ # Engine was created under BOTH scope → allowed+ snap = _scope_snapshot("both", "arxiv")+ eng = _make_egress_engine(engine_name="arxiv", snapshot=snap)+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ eng._verify_egress_scope() # fine++ # Now scope changes to PRIVATE_ONLY on the cached instance+ eng.settings_snapshot = _scope_snapshot("private_only", "arxiv")+ with patch(+ "local_deep_research.security.egress.policy._get_engine_class",+ return_value=fake_cls,+ ):+ with pytest.raises(PolicyDeniedError):+ eng._verify_egress_scope()+++class TestCollectionEngineEgress:+ """CollectionSearchEngine.search() bypasses run(), so it applies the+ runtime backstop itself; the engine name is stamped at construction."""++ @staticmethod+ def _make_collection_engine(snapshot):+ from local_deep_research.web_search_engines.engines.search_engine_collection import (+ CollectionSearchEngine,+ )++ return CollectionSearchEngine(+ collection_id="abc-123",+ collection_name="Test Collection",+ settings_snapshot=snapshot,+ )++ def test_engine_name_stamped_in_init(self):+ eng = self._make_collection_engine(snapshot={"_username": "testuser"})+ assert eng._engine_name == "collection_abc-123"++ def test_search_denied_under_public_only(self):+ """A (default-private) collection under PUBLIC_ONLY scope is denied+ by search() before any FAISS/DB work happens. The collection lookup+ fails closed to private in tests (no user DB)."""+ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ snap = {+ "_username": "testuser",+ "policy.egress_scope": {"value": "public_only"},+ "search.tool": {"value": "wikipedia"},+ }+ eng = self._make_collection_engine(snapshot=snap)+ with pytest.raises(PolicyDeniedError):+ eng.search("test query")++ def test_search_allowed_under_private_only(self):+ """A collection under PRIVATE_ONLY passes the backstop: search()+ proceeds PAST the policy check. In tests there is no user DB, so+ the next layer raises a DB error — what matters here is that it is+ NOT PolicyDeniedError. (search() deliberately propagates non-policy+ errors instead of masking them as 'no results'.)"""+ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ snap = {+ "_username": "testuser",+ "policy.egress_scope": {"value": "private_only"},+ "search.tool": {"value": "wikipedia"},+ }+ eng = self._make_collection_engine(snapshot=snap)+ try:+ results = eng.search("test query")+ except PolicyDeniedError:+ pytest.fail(+ "PRIVATE_ONLY must allow a collection engine; the egress "+ "backstop wrongly denied it"+ )+ except Exception:+ # DB-layer failure (no test user DB) — fine: the backstop+ # allowed the search to proceed past the policy check.+ return+ assert isinstance(results, list)+++class TestLibraryEngineEgress:+ """LibraryRAGSearchEngine self-stamps 'library' and applies the+ backstop in search(), which is callable directly (bypassing run())."""++ @staticmethod+ def _make_library_engine(snapshot):+ from local_deep_research.web_search_engines.engines.search_engine_library import (+ LibraryRAGSearchEngine,+ )++ return LibraryRAGSearchEngine(settings_snapshot=snapshot)++ def test_engine_name_stamped_in_init(self):+ eng = self._make_library_engine({"_username": "tester"})+ assert eng._engine_name == "library"++ def test_search_denied_under_public_only(self):+ """The library is always private-nature, so PUBLIC_ONLY denies+ search() before any DB/FAISS work happens."""+ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )++ snap = {+ "_username": "tester",+ "policy.egress_scope": {"value": "public_only"},+ "search.tool": {"value": "wikipedia"},+ }+ eng = self._make_library_engine(snap)+ with pytest.raises(PolicyDeniedError):+ eng.search("test query")+++class TestEngineNameSetByFactory:+ """Test that _engine_name is properly tracked."""++ def test_default_engine_name_empty(self):+ eng = _make_egress_engine()+ assert eng._engine_name == ""++ def test_engine_name_set_explicitly(self):+ eng = _make_egress_engine(engine_name="searxng")+ assert eng._engine_name == "searxng"++ def test_engine_name_mutable(self):+ eng = _make_egress_engine()+ assert eng._engine_name == ""+ eng._engine_name = "collection_abc-123"+ assert eng._engine_name == "collection_abc-123"