Skip to content

~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.

fix(engines): stop over-rejecting real API keys with placeholder substrings (#4988)

LearningCircuitf7fae54e1b96
diff --git a/changelog.d/4988.bugfix.md b/changelog.d/4988.bugfix.md
new file mode 100644
index 0000000000..2167593e68
--- /dev/null
+++ b/changelog.d/4988.bugfix.md
@@ -0,0 +1,3 @@
+Real API keys that happened to contain placeholder substrings (e.g. `sk-real-secret_API_KEY`) were silently rejected by `_is_api_key_placeholder`, causing engines to disappear from auto-search with no useful error. The check now uses exact case-insensitive matching against a known set of placeholders, plus bracket-template detection (`<...>`, `${...}`) — so substring-overreach rejections no longer happen. Env-var-name pastes like `BRAVE_API_KEY` (literal env var name instead of its value) now pass through the placeholder filter and fail at API-call time with a clear auth error.
+
+Also added the hyphenated placeholder variants (`your-api-key-here`, `your-openai-key-here`, etc.) that the project's own `.env.template` ships, so copying the template verbatim is correctly rejected.
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.py
index a9e7b84a74..ce4795d9b9 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
@@ -35,17 +35,42 @@ if TYPE_CHECKING:
# Three call sites previously had inconsistent subsets of this list, which
# let invalid placeholders silently through the production path in
# search_engines_config.py. Centralizing here so all three stay in sync.
+#
+# All entries are lowercased — comparison is case-insensitive (see
+# ``_is_api_key_placeholder``). Substring patterns like ``endswith("_API_KEY")``
+# are intentionally NOT used: they silently rejected legitimate keys that
+# happened to contain those substrings (e.g. ``sk-real-secret_API_KEY``).
+# Users who paste an env-var name like ``BRAVE_API_KEY`` instead of its value
+# will get a clear API-call-time auth failure instead.
API_KEY_PLACEHOLDERS = frozenset(
{
"",
- "None",
+ "none",
"null",
- "PLACEHOLDER",
- "YOUR_API_KEY_HERE",
- "YOUR_API_KEY",
- "API_KEY",
+ "placeholder",
+ # Underscore forms
+ "your_api_key_here",
"your_api_key",
- "your-api-key",
+ "api_key",
+ "insert_api_key_here",
+ "insert_api_key",
+ # Hyphenated forms shipped in ``src/local_deep_research/defaults/.env.template``
+ # or ``docs/env_configuration.md`` as the literal value users are told to
+ # copy-paste. Each must be rejected verbatim. Drift is enforced by
+ # ``TestEnvTemplatePlaceholdersCovered`` and ``TestEnvDocsPlaceholdersCovered``.
+ "your-api-key-here",
+ "your-anthropic-key-here",
+ "your-openai-key-here",
+ "your-openrouter-key-here",
+ "your-google-api-key-here",
+ "your-brave-key-here",
+ "your-serpapi-key-here",
+ "your-tavily-key-here",
+ # Defensive extras — plausible variations users might type but not in
+ # any template/docs. Listed explicitly so they don't silently accumulate.
+ "your-api-key", # without -here suffix
+ "your-key-here", # without api- prefix
+ "your-azure-key", # Azure provider variant
}
)
@@ -61,21 +86,15 @@ def _is_api_key_placeholder(api_key: Optional[str]) -> bool:
"""Return True if ``api_key`` looks like a placeholder, not a real key.
Catches:
- - Exact-match placeholders (see ``API_KEY_PLACEHOLDERS``)
- - Environment-variable-style names ending in ``_API_KEY``
- (e.g. ``BRAVE_API_KEY``)
- - Templates starting with ``YOUR_``
- - Angle-bracket templates: ``<key>`` or ``${KEY}``
+ - Exact-match placeholders, case-insensitively (see ``API_KEY_PLACEHOLDERS``)
+ - Angle-bracket templates: ``<...>`` (e.g. ``<your_api_key>``)
+ - Shell-variable templates: ``${...}`` (e.g. ``${BRAVE_API_KEY}``)
"""
if not api_key:
return True
- api_key = api_key.strip()
+ api_key = api_key.strip().lower()
if api_key in API_KEY_PLACEHOLDERS:
return True
- if api_key.endswith("_API_KEY"):
- return True
- if api_key.startswith("YOUR_"):
- return True
if api_key.startswith("<") and api_key.endswith(">"):
return True
if api_key.startswith("${") and api_key.endswith("}"):
diff --git a/tests/search_engines/test_base_helpers.py b/tests/search_engines/test_base_helpers.py
index 14bb79d1a8..ded5c03e03 100644
--- a/tests/search_engines/test_base_helpers.py
+++ b/tests/search_engines/test_base_helpers.py
@@ -10,12 +10,15 @@ Tests cover:
"""
import copy
+import re
+from pathlib import Path
from unittest.mock import Mock, patch
import pytest
from local_deep_research.web_search_engines.search_engine_base import (
BaseSearchEngine,
+ _is_api_key_placeholder,
)
from local_deep_research.web_search_engines.rate_limiting import (
RateLimitError,
@@ -65,13 +68,28 @@ class TestIsValidApiKey:
"""'null' string returns False."""
assert BaseSearchEngine._is_valid_api_key("null") is False
- def test_placeholder_ends_with_api_key(self):
- """Keys ending with _API_KEY are rejected."""
- assert BaseSearchEngine._is_valid_api_key("BRAVE_API_KEY") is False
+ def test_real_key_containing_api_key_substring_not_rejected(self):
+ """Real keys that happen to end in '_API_KEY' must NOT be rejected.
- def test_placeholder_starts_with_your(self):
- """Keys starting with YOUR_ are rejected."""
- assert BaseSearchEngine._is_valid_api_key("YOUR_SECRET_KEY") is False
+ Regression guard: ``endswith("_API_KEY")`` substring matching
+ previously rejected legitimate keys like ``sk-real-secret_API_KEY``.
+ Users who accidentally paste an env-var name (``BRAVE_API_KEY``)
+ will now get an API-call-time auth failure rather than silent
+ pre-filtering — that's the correct failure mode.
+ """
+ assert (
+ BaseSearchEngine._is_valid_api_key("sk-real-secret_API_KEY") is True
+ )
+ assert BaseSearchEngine._is_valid_api_key("BRAVE_API_KEY") is True
+
+ def test_real_key_starting_with_your_not_rejected(self):
+ """Real keys that happen to start with 'YOUR' must NOT be rejected.
+
+ Regression guard: ``startswith("YOUR_")`` substring matching
+ previously rejected legitimate keys like ``YOUR8xk29fReal``.
+ """
+ assert BaseSearchEngine._is_valid_api_key("YOUR_SECRET_KEY") is True
+ assert BaseSearchEngine._is_valid_api_key("YOUR8xk29fReal") is True
def test_whitespace_only_returns_false(self):
"""Whitespace-only string returns False."""
@@ -89,6 +107,315 @@ class TestIsValidApiKey:
"""Environment variable placeholders are rejected."""
assert BaseSearchEngine._is_valid_api_key("${API_KEY}") is False
+ def test_placeholder_match_is_case_insensitive(self):
+ """Placeholder detection is case-insensitive — catches lowercase
+ variants like ``your_api_key_here`` and ``placeholder`` that real
+ users actually type into config files."""
+ assert BaseSearchEngine._is_valid_api_key("your_api_key_here") is False
+ assert BaseSearchEngine._is_valid_api_key("placeholder") is False
+ assert BaseSearchEngine._is_valid_api_key("PlaceHolder") is False
+ assert BaseSearchEngine._is_valid_api_key("NULL") is False
+
+ def test_insert_api_key_here_placeholder(self):
+ """``insert_api_key_here`` (a common docs example placeholder) is rejected."""
+ assert (
+ BaseSearchEngine._is_valid_api_key("insert_api_key_here") is False
+ )
+ assert (
+ BaseSearchEngine._is_valid_api_key("INSERT_API_KEY_HERE") is False
+ )
+
+
+class TestIsApiKeyPlaceholder:
+ """Direct tests for the module-level ``_is_api_key_placeholder`` helper.
+
+ This helper is the single source of truth used by:
+ - ``BaseSearchEngine._is_valid_api_key`` (instance/static method)
+ - ``search_engines_config._resolve_api_key`` (production filter path)
+ Locks in the contract so both callers stay in sync.
+ """
+
+ def test_none_is_placeholder(self):
+ assert _is_api_key_placeholder(None) is True
+
+ def test_empty_string_is_placeholder(self):
+ assert _is_api_key_placeholder("") is True
+
+ @pytest.mark.parametrize(
+ "placeholder",
+ [
+ "None",
+ "null",
+ "PLACEHOLDER",
+ "placeholder",
+ "PlaceHolder",
+ "NULL",
+ "YOUR_API_KEY_HERE",
+ "your_api_key_here",
+ "YOUR_API_KEY",
+ "your_api_key",
+ "your-api-key",
+ "API_KEY",
+ "api_key",
+ "INSERT_API_KEY_HERE",
+ "insert_api_key_here",
+ "insert_api_key",
+ # Hyphenated forms shipped in .env.template / docs
+ "your-api-key-here",
+ "your-key-here",
+ "your-openai-key-here",
+ "your-google-api-key-here",
+ "your-anthropic-key-here",
+ "your-brave-key-here",
+ "your-azure-key",
+ ],
+ )
+ def test_known_placeholders_rejected_case_insensitively(self, placeholder):
+ assert _is_api_key_placeholder(placeholder) is True
+
+ @pytest.mark.parametrize(
+ "real_key",
+ [
+ "sk-abc123def456",
+ "sk-real-secret_API_KEY", # regression: substring was rejected by old endswith check
+ "BRAVE_API_KEY", # env-var-name paste: not pre-filtered
+ "YOUR_SECRET_KEY", # regression: substring was rejected
+ "YOUR8xk29fReal", # regression: substring was rejected
+ "BSA" + "x" * 30, # plausible Brave-shaped key
+ "tvly-" + "a" * 40, # plausible Tavily-shaped key
+ ],
+ )
+ def test_real_keys_not_rejected(self, real_key):
+ """Regression guard: substring patterns previously rejected real keys."""
+ assert _is_api_key_placeholder(real_key) is False
+
+ @pytest.mark.parametrize(
+ "template",
+ [
+ "<API_KEY>",
+ "<your_api_key>",
+ "<insert_key_here>",
+ "${API_KEY}",
+ "${BRAVE_API_KEY}",
+ ],
+ )
+ def test_template_brackets_rejected(self, template):
+ """Bracket-style templates are still rejected — only the bare
+ ``endswith('_API_KEY')`` / ``startswith('YOUR_')`` substring checks
+ were removed, not the bracket-template checks."""
+ assert _is_api_key_placeholder(template) is True
+
+ def test_strips_whitespace_before_checking(self):
+ assert _is_api_key_placeholder(" YOUR_API_KEY_HERE ") is True
+ assert _is_api_key_placeholder(" sk-real-key ") is False
+
+
+class TestEnvTemplatePlaceholdersCovered:
+ """Guard against drift between ``.env.template`` and placeholder detection.
+
+ Every API-key value shipped in
+ ``src/local_deep_research/defaults/.env.template`` must be recognized
+ by ``_is_api_key_placeholder`` — otherwise users who copy-paste the
+ template value verbatim silently fail engine registration on the
+ production path. Converts what was previously a comment-based
+ contract on ``API_KEY_PLACEHOLDERS`` into an enforced one.
+ """
+
+ ENV_TEMPLATE_PATH = (
+ Path(__file__).parent.parent.parent
+ / "src"
+ / "local_deep_research"
+ / "defaults"
+ / ".env.template"
+ )
+
+ def test_all_env_template_api_key_values_are_detected_as_placeholders(self):
+ content = self.ENV_TEMPLATE_PATH.read_text()
+
+ # Match commented env var assignments like:
+ # # LDR_LLM_OPENAI_API_KEY=your-openai-key-here
+ # Variable name must end in _API_KEY so we don't pick up engine IDs,
+ # URLs, numeric defaults, etc. Use ``[ \t]`` rather than ``\s`` so the
+ # pattern can't bleed across newlines when a row ships an empty value.
+ pattern = re.compile(
+ r"^#[ \t]*(LDR_\w*_API_KEY)[ \t]*=[ \t]*(.+?)[ \t]*$",
+ re.MULTILINE,
+ )
+
+ misses = []
+ for match in pattern.finditer(content):
+ env_var = match.group(1)
+ raw_value = match.group(2).strip().strip('"').strip("'")
+ if not raw_value:
+ continue
+ if not _is_api_key_placeholder(raw_value):
+ misses.append((env_var, raw_value))
+
+ assert not misses, (
+ f"API key placeholder(s) shipped in .env.template but not "
+ f"detected by _is_api_key_placeholder: {misses}. "
+ f"Add each missing value to API_KEY_PLACEHOLDERS in "
+ f"search_engine_base.py (or extend the bracket-template "
+ f"checks if the value uses <...> or ${{...}} form)."
+ )
+
+
+class TestEnvDocsPlaceholdersCovered:
+ """Guard against drift between ``docs/env_configuration.md`` and
+ placeholder detection.
+
+ Companion to ``TestEnvTemplatePlaceholdersCovered``. Every API-key value
+ shipped in the env docs as a copy-pasteable example (``export ...``,
+ ``set ...``, ``-e ...``) must be recognized by ``_is_api_key_placeholder``
+ so users following the docs verbatim don't silently fail engine
+ registration.
+ """
+
+ ENV_DOCS_PATH = (
+ Path(__file__).parent.parent.parent / "docs" / "env_configuration.md"
+ )
+
+ def test_all_env_docs_api_key_values_are_detected_as_placeholders(self):
+ content = self.ENV_DOCS_PATH.read_text()
+
+ # Match any ``LDR_*_API_KEY=value`` assignment regardless of prefix
+ # (``export``, ``set``, ``-e``, ``-``). Value can be bare, single- or
+ # double-quoted, or bracketed. The bare alternative excludes quotes
+ # so empty-quoted examples like ``API_KEY=""`` in prose (which are
+ # documentation about empty values, not placeholders) don't match.
+ pattern = re.compile(
+ r"(LDR_\w*_API_KEY)\s*=\s*"
+ r'("[^"]+"|\'[^\']+\'|[^\s\\"\']+)'
+ )
+
+ misses = []
+ seen = set()
+ for match in pattern.finditer(content):
+ env_var = match.group(1)
+ raw_value = match.group(2).strip().strip('"').strip("'")
+ if not raw_value:
+ continue
+ # Deduplicate — docs repeat the same example across shell styles.
+ key = (env_var, raw_value)
+ if key in seen:
+ continue
+ seen.add(key)
+ if not _is_api_key_placeholder(raw_value):
+ misses.append((env_var, raw_value))
+
+ assert not misses, (
+ f"API key placeholder(s) shipped in docs/env_configuration.md "
+ f"but not detected by _is_api_key_placeholder: {misses}. "
+ f"Add each missing value to API_KEY_PLACEHOLDERS in "
+ f"search_engine_base.py (or extend the bracket-template "
+ f"checks if the value uses <...> or ${{...}} form)."
+ )
+
+
+class TestApiKeyPlaceholdersReverseContract:
+ """Reverse-direction contract: every entry in ``API_KEY_PLACEHOLDERS``
+ must be justified — either it appears in ``.env.template`` or
+ ``docs/env_configuration.md`` (so it catches real user paste errors),
+ or it's a generic placeholder (``null``, ``placeholder``, etc.), or
+ it's explicitly listed below as a defensive extra.
+
+ Prevents speculative entries from accumulating silently. When adding a
+ new entry to ``API_KEY_PLACEHOLDERS``, also add it to a doc or to the
+ ``DEFENSIVE_EXTRAS`` allowlist below with a brief justification.
+ """
+
+ # Generic placeholders that don't need a doc source — they catch
+ # common paste errors regardless of which file a user is editing.
+ GENERIC_PLACEHOLDERS = frozenset(
+ {
+ "",
+ "none",
+ "null",
+ "placeholder",
+ "your_api_key_here",
+ "your_api_key",
+ "api_key",
+ "insert_api_key_here",
+ "insert_api_key",
+ }
+ )
+
+ # Hyphenated forms that are plausible user pastes but don't appear in
+ # any current doc. Mirror the source comment in ``search_engine_base.py``.
+ DEFENSIVE_EXTRAS = frozenset(
+ {
+ "your-api-key", # without -here suffix
+ "your-key-here", # without api- prefix
+ "your-azure-key", # Azure provider variant
+ }
+ )
+
+ @pytest.fixture(autouse=True)
+ def _extract_documented_placeholders(self):
+ """One-time extraction of placeholders from both doc sources."""
+ repo_root = Path(__file__).parent.parent.parent
+ template_path = (
+ repo_root
+ / "src"
+ / "local_deep_research"
+ / "defaults"
+ / ".env.template"
+ )
+ docs_path = repo_root / "docs" / "env_configuration.md"
+
+ template_pattern = re.compile(
+ r"^#[ \t]*(LDR_\w*_API_KEY)[ \t]*=[ \t]*(.+?)[ \t]*$",
+ re.MULTILINE,
+ )
+ docs_pattern = re.compile(
+ r"(LDR_\w*_API_KEY)\s*=\s*"
+ r'("[^"]+"|\'[^\']+\'|[^\s\\"\']+)'
+ )
+
+ documented = set()
+ for content, pat in (
+ (template_path.read_text(), template_pattern),
+ (docs_path.read_text(), docs_pattern),
+ ):
+ for match in pat.finditer(content):
+ raw_value = match.group(2).strip().strip('"').strip("'").lower()
+ if raw_value:
+ documented.add(raw_value)
+ self._documented = documented
+
+ def test_every_api_key_placeholder_is_justified(self):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ API_KEY_PLACEHOLDERS,
+ )
+
+ justified = (
+ self._documented | self.GENERIC_PLACEHOLDERS | self.DEFENSIVE_EXTRAS
+ )
+ unjustified = API_KEY_PLACEHOLDERS - justified
+ assert not unjustified, (
+ f"Entries in API_KEY_PLACEHOLDERS without a justification: "
+ f"{sorted(unjustified)}. Each entry must either appear in "
+ f".env.template / docs/env_configuration.md, be a generic "
+ f"placeholder in GENERIC_PLACEHOLDERS, or be explicitly listed "
+ f"in DEFENSIVE_EXTRAS with a comment."
+ )
+
+ def test_defensive_extras_match_source_comment(self):
+ """Lockstep guard: if someone adds a defensive extra to the source
+ comment but forgets DEFENSIVE_EXTRAS here (or vice versa), this
+ test fires. The two lists must stay in sync."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ API_KEY_PLACEHOLDERS,
+ )
+
+ # Every DEFENSIVE_EXTRAS entry must be in API_KEY_PLACEHOLDERS.
+ orphaned_in_test = self.DEFENSIVE_EXTRAS - API_KEY_PLACEHOLDERS
+ assert not orphaned_in_test, (
+ f"DEFENSIVE_EXTRAS lists entries that aren't in "
+ f"API_KEY_PLACEHOLDERS: {sorted(orphaned_in_test)}. "
+ f"Either add them to the source set or remove them here."
+ )
+
class TestCleanResultUrl:
"""Tests for _clean_result_url static method."""
diff --git a/tests/web_search_engines/test_search_engines_config.py b/tests/web_search_engines/test_search_engines_config.py
index 5b002a3f5e..c8153428bd 100644
--- a/tests/web_search_engines/test_search_engines_config.py
+++ b/tests/web_search_engines/test_search_engines_config.py
@@ -11,16 +11,21 @@ Tests the configuration loading and processing for search engines:
from unittest.mock import MagicMock, patch
+from local_deep_research.web_search_engines.search_engines_config import (
+ _extract_per_engine_config,
+ _get_setting,
+ _resolve_api_key,
+ default_search_engine,
+ get_available_engines,
+ search_config,
+)
+
class TestGetSetting:
"""Tests for _get_setting function."""
def test_returns_value_from_snapshot(self):
"""Should return value from settings snapshot when available."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _get_setting,
- )
-
with patch(
"local_deep_research.web_search_engines.search_engines_config.get_setting_from_snapshot",
return_value="snapshot_value",
@@ -34,10 +39,6 @@ class TestGetSetting:
def test_returns_value_from_db_session(self):
"""Should return value from db session when snapshot not available."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _get_setting,
- )
-
mock_session = MagicMock()
mock_settings_manager = MagicMock()
mock_settings_manager.get_setting.return_value = "db_value"
@@ -55,19 +56,11 @@ class TestGetSetting:
def test_returns_default_when_no_source_available(self):
"""Should return default value when no settings source available."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _get_setting,
- )
-
result = _get_setting("test.key", "default_value")
assert result == "default_value"
def test_prefers_snapshot_over_db_session(self):
"""Should prefer settings snapshot over database session."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _get_setting,
- )
-
mock_session = MagicMock()
mock_settings_manager = MagicMock()
mock_settings_manager.get_setting.return_value = "db_value"
@@ -92,10 +85,6 @@ class TestGetSetting:
def test_handles_snapshot_exception(self):
"""Should fall back to db_session when snapshot raises exception."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _get_setting,
- )
-
mock_session = MagicMock()
mock_settings_manager = MagicMock()
mock_settings_manager.get_setting.return_value = "db_value"
@@ -120,10 +109,6 @@ class TestGetSetting:
def test_handles_db_session_exception(self):
"""Should return default when db_session raises exception."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _get_setting,
- )
-
mock_session = MagicMock()
with patch(
@@ -139,10 +124,6 @@ class TestGetSetting:
def test_passes_username_to_settings_manager(self):
"""Should pass username to settings manager."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _get_setting,
- )
-
mock_session = MagicMock()
mock_settings_manager = MagicMock()
mock_settings_manager.get_setting.return_value = "value"
@@ -165,20 +146,12 @@ class TestExtractPerEngineConfig:
def test_extracts_simple_flat_config(self):
"""Should return flat config as-is for non-dotted keys."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _extract_per_engine_config,
- )
-
raw_config = {"key1": "value1", "key2": "value2"}
result = _extract_per_engine_config(raw_config)
assert result == {"key1": "value1", "key2": "value2"}
def test_extracts_single_level_nested_config(self):
"""Should convert single dotted keys to nested dict."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _extract_per_engine_config,
- )
-
raw_config = {
"engine1.param1": "value1",
"engine1.param2": "value2",
@@ -190,10 +163,6 @@ class TestExtractPerEngineConfig:
def test_extracts_multiple_engines(self):
"""Should extract configs for multiple engines."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _extract_per_engine_config,
- )
-
raw_config = {
"duckduckgo.api_key": "key1",
"google.api_key": "key2",
@@ -206,10 +175,6 @@ class TestExtractPerEngineConfig:
def test_extracts_deeply_nested_config(self):
"""Should recursively extract deeply nested configs."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _extract_per_engine_config,
- )
-
raw_config = {
"engine.nested.param1": "value1",
"engine.nested.param2": "value2",
@@ -220,19 +185,11 @@ class TestExtractPerEngineConfig:
def test_handles_empty_config(self):
"""Should return empty dict for empty input."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _extract_per_engine_config,
- )
-
result = _extract_per_engine_config({})
assert result == {}
def test_mixes_flat_and_nested(self):
"""Should handle mix of flat and nested keys."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _extract_per_engine_config,
- )
-
raw_config = {
"simple_key": "simple_value",
"engine.param": "nested_value",
@@ -258,10 +215,6 @@ class TestSearchConfig:
mock_get_setting.return_value = {}
mock_registry.list_registered.return_value = []
- from local_deep_research.web_search_engines.search_engines_config import (
- search_config,
- )
-
result = search_config()
assert isinstance(result, dict)
@@ -278,10 +231,6 @@ class TestSearchConfig:
mock_get_setting.return_value = {}
mock_registry.list_registered.return_value = []
- from local_deep_research.web_search_engines.search_engines_config import (
- search_config,
- )
-
result = search_config()
assert "auto" not in result
assert "meta" not in result
@@ -301,10 +250,6 @@ class TestSearchConfig:
mock_get_setting.return_value = {}
mock_registry.list_registered.return_value = ["custom_retriever"]
- from local_deep_research.web_search_engines.search_engines_config import (
- search_config,
- )
-
result = search_config()
assert "custom_retriever" in result
assert result["custom_retriever"]["is_retriever"] is True
@@ -331,10 +276,6 @@ class TestSearchConfig:
mock_get_setting.side_effect = get_setting_side_effect
- from local_deep_research.web_search_engines.search_engines_config import (
- search_config,
- )
-
result = search_config()
assert "library" in result
assert result["library"]["class_name"] == "LibraryRAGSearchEngine"
@@ -356,10 +297,6 @@ class TestSearchConfig:
mock_get_setting.side_effect = get_setting_side_effect
- from local_deep_research.web_search_engines.search_engines_config import (
- search_config,
- )
-
result = search_config()
assert "library" not in result
@@ -413,10 +350,6 @@ class TestDefaultSearchEngine:
"""Should return configured default search engine."""
mock_get_setting.return_value = "google"
- from local_deep_research.web_search_engines.search_engines_config import (
- default_search_engine,
- )
-
result = default_search_engine()
assert result == "google"
@@ -427,10 +360,6 @@ class TestDefaultSearchEngine:
"""Should return 'wikipedia' as default when not configured."""
mock_get_setting.return_value = "wikipedia"
- from local_deep_research.web_search_engines.search_engines_config import (
- default_search_engine,
- )
-
result = default_search_engine()
assert result == "wikipedia"
@@ -441,10 +370,6 @@ class TestDefaultSearchEngine:
"""Should query the correct setting key."""
mock_get_setting.return_value = "duckduckgo"
- from local_deep_research.web_search_engines.search_engines_config import (
- default_search_engine,
- )
-
default_search_engine()
mock_get_setting.assert_called_once()
call_args = mock_get_setting.call_args
@@ -459,10 +384,6 @@ class TestDefaultSearchEngine:
mock_get_setting.return_value = "searxng"
mock_session = MagicMock()
- from local_deep_research.web_search_engines.search_engines_config import (
- default_search_engine,
- )
-
default_search_engine(db_session=mock_session)
call_kwargs = mock_get_setting.call_args[1]
assert call_kwargs["db_session"] is mock_session
@@ -475,10 +396,6 @@ class TestDefaultSearchEngine:
mock_get_setting.return_value = "brave"
snapshot = {"search.engine.DEFAULT_SEARCH_ENGINE": "brave"}
- from local_deep_research.web_search_engines.search_engines_config import (
- default_search_engine,
- )
-
default_search_engine(settings_snapshot=snapshot)
call_kwargs = mock_get_setting.call_args[1]
assert call_kwargs["settings_snapshot"] is snapshot
@@ -642,3 +559,164 @@ class TestListEligibleEngineConfigsAvailability:
assert "searxng" in res
assert "arxiv" not in res
+
+
+MODULE = "local_deep_research.web_search_engines.search_engines_config"
+
+
+class TestModuleResolveApiKey:
+ """Tests for the module-level ``_resolve_api_key()`` in search_engines_config.
+
+ This is the production filter path called by ``get_available_engines()``:
+ it decides whether an engine shows up in auto-search. Previously had
+ zero direct test coverage — these tests would have caught the silent
+ substring-overreach regression shipped by #3065 and inherited by #4715.
+ """
+
+ def _resolve(self, engine_name, engine_config, settings_snapshot):
+ return _resolve_api_key(engine_name, engine_config, settings_snapshot)
+
+ def test_returns_key_from_snapshot_dict_value(self):
+ snapshot = {
+ "search.engine.web.brave.api_key": {"value": "real-key-123"}
+ }
+ assert self._resolve("brave", {}, snapshot) == "real-key-123"
+
+ def test_returns_key_from_snapshot_plain_string(self):
+ snapshot = {"search.engine.web.brave.api_key": "real-key-456"}
+ assert self._resolve("brave", {}, snapshot) == "real-key-456"
+
+ def test_falls_back_to_engine_config_api_key(self):
+ snapshot = {}
+ config = {"api_key": "config-key-789"}
+ assert self._resolve("brave", config, snapshot) == "config-key-789"
+
+ def test_snapshot_takes_priority_over_config(self):
+ snapshot = {
+ "search.engine.web.brave.api_key": {"value": "snapshot-key"}
+ }
+ config = {"api_key": "config-key"}
+ assert self._resolve("brave", config, snapshot) == "snapshot-key"
+
+ def test_returns_none_when_no_key(self):
+ assert self._resolve("brave", {}, {}) is None
+
+ def test_returns_none_when_snapshot_value_is_empty(self):
+ snapshot = {"search.engine.web.brave.api_key": ""}
+ assert self._resolve("brave", {}, snapshot) is None
+
+ def test_returns_none_when_snapshot_value_is_none(self):
+ snapshot = {"search.engine.web.brave.api_key": None}
+ assert self._resolve("brave", {}, snapshot) is None
+
+ def test_real_key_with_api_key_substring_passes(self):
+ """Regression: substring-overreach previously rejected real keys
+ ending in ``_API_KEY`` — they must pass the filter. The string
+ below is chosen so the OLD ``endswith("_API_KEY")`` check would
+ have rejected it; the new exact-match check passes it through."""
+ snapshot = {
+ "search.engine.web.brave.api_key": "sk-real-secret_API_KEY",
+ }
+ assert self._resolve("brave", {}, snapshot) == "sk-real-secret_API_KEY"
+
+ def test_real_key_starting_with_your_passes(self):
+ snapshot = {"search.engine.web.brave.api_key": "YOUR8xk29fReal"}
+ assert self._resolve("brave", {}, snapshot) == "YOUR8xk29fReal"
+
+ def test_env_var_name_paste_passes_filter(self):
+ """If a user pastes an env-var NAME (``BRAVE_API_KEY``) instead of
+ its value, the filter no longer silently drops the engine — it
+ passes through and the engine fails at API-call time with a clear
+ auth error. That's the preferred failure mode."""
+ snapshot = {"search.engine.web.brave.api_key": "BRAVE_API_KEY"}
+ assert self._resolve("brave", {}, snapshot) == "BRAVE_API_KEY"
+
+
+class TestGetAvailableEngines:
+ """Tests for ``get_available_engines()`` — the shared filter used by
+ the langgraph-agent tool builder. Locks in the contract: snapshot
+ required, exclude_engines respected, use_api_key_services honoured,
+ requires_api_key engines gated on a resolvable key.
+ """
+
+ def _get(self, **kwargs):
+ return get_available_engines(**kwargs)
+
+ def test_returns_empty_dict_without_snapshot(self):
+ assert self._get() == {}
+ assert self._get(settings_snapshot=None) == {}
+ assert self._get(settings_snapshot={}) == {}
+
+ @patch(f"{MODULE}.get_setting_from_snapshot")
+ @patch(f"{MODULE}.search_config")
+ def test_excludes_engines_not_enabled_for_auto_search(
+ self, mock_sc, mock_gss
+ ):
+ """Engines with ``use_in_auto_search = False`` are filtered out."""
+ mock_sc.return_value = {
+ "searxng": {"requires_api_key": False},
+ "brave": {"requires_api_key": False},
+ }
+
+ def gss_side_effect(key, default, **kwargs):
+ return key == "search.engine.web.searxng.use_in_auto_search"
+
+ mock_gss.side_effect = gss_side_effect
+
+ result = self._get(settings_snapshot={"_some": "data"})
+ assert "searxng" in result
+ assert "brave" not in result
+
+ @patch(f"{MODULE}._resolve_api_key", return_value=None)
+ @patch(f"{MODULE}.get_setting_from_snapshot", return_value=True)
+ @patch(f"{MODULE}.search_config")
+ def test_excludes_engine_with_missing_api_key(
+ self, mock_sc, mock_gss, mock_resolve
+ ):
+ mock_sc.return_value = {"brave": {"requires_api_key": True}}
+
+ result = self._get(settings_snapshot={"_some": "data"})
+ assert "brave" not in result
+
+ @patch(f"{MODULE}._resolve_api_key", return_value="real-key")
+ @patch(f"{MODULE}.get_setting_from_snapshot", return_value=True)
+ @patch(f"{MODULE}.search_config")
+ def test_includes_engine_with_valid_api_key(
+ self, mock_sc, mock_gss, mock_resolve
+ ):
+ mock_sc.return_value = {"brave": {"requires_api_key": True}}
+
+ result = self._get(settings_snapshot={"_some": "data"})
+ assert "brave" in result
+
+ @patch(f"{MODULE}.get_setting_from_snapshot", return_value=True)
+ @patch(f"{MODULE}.search_config")
+ def test_excludes_api_key_engines_when_use_api_key_services_false(
+ self, mock_sc, mock_gss
+ ):
+ mock_sc.return_value = {
+ "searxng": {"requires_api_key": False},
+ "brave": {"requires_api_key": True},
+ }
+
+ result = self._get(
+ settings_snapshot={"_some": "data"},
+ use_api_key_services=False,
+ )
+ assert "searxng" in result
+ assert "brave" not in result
+
+ @patch(f"{MODULE}.get_setting_from_snapshot", return_value=True)
+ @patch(f"{MODULE}.search_config")
+ def test_respects_exclude_engines_parameter(self, mock_sc, mock_gss):
+ mock_sc.return_value = {
+ "searxng": {"requires_api_key": False},
+ "wikipedia": {"requires_api_key": False},
+ }
+
+ result = self._get(
+ settings_snapshot={"_some": "data"},
+ exclude_engines={"wikipedia"},
+ )
+ assert "searxng" in result
+ assert "wikipedia" not in result