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.

refactor(security): add shared scrub_error() dual-scrub helper (#4183 follow-up) (#5019)

LearningCircuitb610378c4315
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 026d87d8ed..f1f5882527 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -5,7 +5,7 @@ from langchain_core.messages import AIMessage
from loguru import logger
from ..llm import get_llm_from_registry, is_llm_registered
-from ..security.log_sanitizer import redact_secrets, sanitize_error_message
+from ..security.log_sanitizer import scrub_error
from ..utilities.search_utilities import remove_think_tags
# Import providers module to trigger auto-discovery. get_llm() has no
@@ -312,7 +312,7 @@ def get_llm(
def _log_llm_error(error: Exception) -> None:
"""Log an LLM call failure with credential redaction."""
- safe_msg = redact_secrets(sanitize_error_message(str(error)))
+ safe_msg = scrub_error(error)
logger.warning(f"LLM Request - Failed with error: {safe_msg}")
diff --git a/src/local_deep_research/embeddings/providers/implementations/ollama.py b/src/local_deep_research/embeddings/providers/implementations/ollama.py
index 48c8b3a749..84447e793c 100644
--- a/src/local_deep_research/embeddings/providers/implementations/ollama.py
+++ b/src/local_deep_research/embeddings/providers/implementations/ollama.py
@@ -14,7 +14,7 @@ from ....utilities.llm_utils import (
)
from ..base import BaseEmbeddingProvider, Exposure
from ....security import redact_url_for_log, safe_get, safe_post
-from ....security.log_sanitizer import redact_secrets, sanitize_error_message
+from ....security.log_sanitizer import scrub_error
class OllamaEmbeddingsProvider(BaseEmbeddingProvider):
@@ -136,7 +136,7 @@ class OllamaEmbeddingsProvider(BaseEmbeddingProvider):
return False
except Exception as e:
- safe_msg = redact_secrets(sanitize_error_message(str(e)))
+ safe_msg = scrub_error(e)
logger.exception(
f"Error checking Ollama availability ({type(e).__name__}): {safe_msg}"
)
diff --git a/src/local_deep_research/llm/providers/auto_discovery.py b/src/local_deep_research/llm/providers/auto_discovery.py
index 03af0f49af..56dd859a75 100644
--- a/src/local_deep_research/llm/providers/auto_discovery.py
+++ b/src/local_deep_research/llm/providers/auto_discovery.py
@@ -9,7 +9,7 @@ from ...security.secure_logging import logger
from .base import BaseLLMProvider, normalize_provider
from .openai_base import OpenAICompatibleProvider
from ..llm_registry import register_llm
-from ...security.log_sanitizer import redact_secrets, sanitize_error_message
+from ...security.log_sanitizer import scrub_error
class ProviderInfo:
@@ -156,7 +156,7 @@ class ProviderDiscovery:
)
except Exception as e:
- safe_msg = redact_secrets(sanitize_error_message(str(e)))
+ safe_msg = scrub_error(e)
logger.exception(
f"Error loading provider from {module_name} ({type(e).__name__}): {safe_msg}"
)
diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.py
index 1abbcd7b15..f83b75b62d 100644
--- a/src/local_deep_research/security/__init__.py
+++ b/src/local_deep_research/security/__init__.py
@@ -39,6 +39,7 @@ from .log_sanitizer import (
sanitize_error_for_client,
sanitize_error_message,
sanitize_for_log,
+ scrub_error,
strip_control_chars,
)
from .filename_sanitizer import sanitize_filename, UnsafeFilenameError
@@ -106,6 +107,7 @@ __all__ = [
"sanitize_error_for_client",
"sanitize_error_message",
"sanitize_for_log",
+ "scrub_error",
"strip_control_chars",
"sanitize_filename",
"UnsafeFilenameError",
diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.py
index 1b68ff3310..a1356e6834 100644
--- a/src/local_deep_research/security/log_sanitizer.py
+++ b/src/local_deep_research/security/log_sanitizer.py
@@ -18,7 +18,7 @@ concerns:
import dataclasses
import re
-from typing import Any, Optional
+from typing import Any, Optional, Union
# Strip C0/C1 control characters and dangerous Unicode format characters,
@@ -294,6 +294,51 @@ def sanitize_error_message(message: str) -> str:
return message
+def scrub_error(error: Union[BaseException, str], *secrets: Any) -> str:
+ """Return a log/DB-safe rendering of *error* (the "dual-scrub").
+
+ Composes the two scrub passes every catch site needs:
+ :func:`sanitize_error_message` (catches credential *shapes* — Bearer
+ tokens, URL-embedded credentials, ``sk-``/``pk-`` keys) followed by
+ :func:`redact_secrets` with the caller's known literal secret values.
+
+ Use this at every catch site that logs or persists an exception so
+ the two passes can never drift apart per-site.
+ ``BaseSearchEngine._scrub_error`` delegates here, resolving its
+ engine's ``_secret_attrs`` into the *secrets* arguments.
+
+ Defensive by design: this runs inside ``except`` blocks, so it must
+ never raise. ``str(error)`` is guarded (a custom exception whose
+ ``__str__`` raises won't crash the handler) and each secret is coerced
+ to ``str`` (a misconfigured non-string secret, e.g. an int from
+ settings, won't trip ``redact_secrets``' ``len()`` check).
+
+ Args:
+ error: An exception or a pre-built message string.
+ *secrets: Known literal secret values to redact. ``None`` and
+ falsy values are silently skipped.
+
+ Returns:
+ The scrubbed message, safe for production log sinks.
+ """
+ try:
+ message = str(error)
+ except Exception:
+ message = f"<unprintable {type(error).__name__}>"
+ # Coerce truthy non-str secrets to str; keep None/falsy as-is
+ # (redact_secrets filters those out). Guarded per secret: a
+ # pathological value whose __bool__/__str__ raises cannot be
+ # literal-matched anyway, so it is skipped rather than allowed to
+ # crash the except handler this runs in.
+ safe_secrets = []
+ for v in secrets:
+ try:
+ safe_secrets.append(v and str(v))
+ except Exception:
+ continue
+ return redact_secrets(sanitize_error_message(message), *safe_secrets)
+
+
def sanitize_error_for_client(message: str, max_length: int = 200) -> str:
"""Make an exception-derived string safe to return to an HTTP client.
diff --git a/src/local_deep_research/security/secure_logging.py b/src/local_deep_research/security/secure_logging.py
index 355420e009..935462728d 100644
--- a/src/local_deep_research/security/secure_logging.py
+++ b/src/local_deep_research/security/secure_logging.py
@@ -24,15 +24,15 @@ Usage — a drop-in replacement for the loguru import::
try:
...
except Exception as e:
- safe_msg = redact_secrets(sanitize_error_message(str(e)))
+ safe_msg = scrub_error(e) # from ..security.log_sanitizer
logger.exception(f"Engine request failed: {safe_msg}")
Caveats:
* **Messages are production-visible at ERROR.** The wrapper only strips
the traceback; the message string itself reaches every sink. Call sites
- must still pass scrubbed text (``sanitize_error_message`` /
- ``redact_secrets``), never raw ``str(e)``.
+ must still pass scrubbed text (``scrub_error`` — or in engine
+ subclasses ``self._scrub_error``), never raw ``str(e)``.
* **Known bypass routes.** ``logger.opt(exception=True).error(...)`` and
``@logger.catch`` delegate to plain loguru and are NOT gated. No call
site under ``llm/providers/``, ``embeddings/providers/`` or
diff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.py
index 8cf13ee408..aaf7f44ef9 100644
--- a/src/local_deep_research/web_search_engines/engines/full_search.py
+++ b/src/local_deep_research/web_search_engines/engines/full_search.py
@@ -8,7 +8,7 @@ from ...research_library.downloaders.extraction import (
batch_fetch_and_extract,
)
from ...security.egress.policy import PolicyDeniedError
-from ...security.log_sanitizer import redact_secrets, sanitize_error_message
+from ...security.log_sanitizer import scrub_error
from ...security.secure_logging import logger
from ...security.ssrf_validator import redact_url_for_log, validate_url
from ...utilities.js_rendering import (
@@ -86,7 +86,7 @@ class FullSearchResults:
# proceed despite the user's policy refusing the LLM. Fail closed.
raise
except Exception as e:
- safe_msg = redact_secrets(sanitize_error_message(str(e)))
+ safe_msg = scrub_error(e)
logger.exception(
f"URL filtering error ({type(e).__name__}): {safe_msg}"
)
@@ -226,7 +226,7 @@ class FullSearchResults:
),
)
except Exception as e:
- safe_msg = redact_secrets(sanitize_error_message(str(e)))
+ safe_msg = scrub_error(e)
logger.exception(
f"Error fetching full content ({type(e).__name__}): {safe_msg}"
)
diff --git a/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py b/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py
index 8a4eed52bc..31b90ea47e 100644
--- a/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py
+++ b/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py
@@ -8,7 +8,7 @@ from langchain_core.documents import Document
from ...database.models.library import DocumentChunk
from ...database.session_context import get_user_db_session
-from ...security.log_sanitizer import redact_secrets, sanitize_error_message
+from ...security.log_sanitizer import scrub_error
from ...security.secure_logging import logger
from ...utilities.url_utils import normalize_url
@@ -143,7 +143,7 @@ class LocalEmbeddingManager:
# DNS hiccup, provider validation, policy denial) must
# propagate so we don't silently fetch from huggingface.co
# when the user has explicitly opted into local embeddings.
- safe_msg = redact_secrets(sanitize_error_message(str(exc)))
+ safe_msg = scrub_error(exc)
logger.exception(
f"Embedding provider import failed ({type(exc).__name__}) — falling back to local SBERT: {safe_msg}"
)
@@ -260,9 +260,7 @@ class LocalEmbeddingManager:
)
except Exception as e:
- safe_msg = redact_secrets(
- sanitize_error_message(str(e)), self.db_password
- )
+ safe_msg = scrub_error(e, self.db_password)
logger.exception(
f"Error storing chunks to database for collection '{collection_name}' ({type(e).__name__}): {safe_msg}"
)
@@ -315,9 +313,7 @@ class LocalEmbeddingManager:
return count
except Exception as e:
- safe_msg = redact_secrets(
- sanitize_error_message(str(e)), self.db_password
- )
+ safe_msg = scrub_error(e, self.db_password)
logger.exception(
f"Error deleting chunks from database for collection '{collection_name}' ({type(e).__name__}): {safe_msg}"
)
diff --git a/src/local_deep_research/web_search_engines/relevance_filter.py b/src/local_deep_research/web_search_engines/relevance_filter.py
index 1f62bd0956..758ca3d7e3 100644
--- a/src/local_deep_research/web_search_engines/relevance_filter.py
+++ b/src/local_deep_research/web_search_engines/relevance_filter.py
@@ -39,7 +39,7 @@ from typing import Any, Dict, List, Optional
from langchain_ollama import ChatOllama
from ..config.constants import DEFAULT_MAX_FILTERED_RESULTS
-from ..security.log_sanitizer import redact_secrets, sanitize_error_message
+from ..security.log_sanitizer import scrub_error
from ..security.secure_logging import logger
# Real wrapper chains (RateLimitedLLMWrapper -> ProcessingLLMWrapper -> base)
@@ -240,7 +240,7 @@ def filter_previews_for_relevance(
prompt_template,
)
except Exception as e:
- safe_msg = redact_secrets(sanitize_error_message(str(e)))
+ safe_msg = scrub_error(e)
logger.exception(
f"[{engine_name}] batch {i} failed — skipping its results ({type(e).__name__}): {safe_msg}"
)
@@ -275,9 +275,7 @@ def filter_previews_for_relevance(
try:
results_per_batch[i] = fut.result()
except Exception as e:
- safe_msg = redact_secrets(
- sanitize_error_message(str(e))
- )
+ safe_msg = scrub_error(e)
logger.exception(
f"[{engine_name}] batch {i} failed — skipping ({type(e).__name__}): {safe_msg}"
)
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 998444297b..03dd2d89e2 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
@@ -18,7 +18,7 @@ from ..advanced_search_system.filters.base_filter import BaseFilter
from ..utilities.type_utils import unwrap_setting
from ..config.constants import DEFAULT_MAX_FILTERED_RESULTS
from ..config.thread_settings import get_setting_from_snapshot
-from ..security.log_sanitizer import redact_secrets, sanitize_error_message
+from ..security.log_sanitizer import sanitize_error_message, scrub_error
from ..security.egress.classification import Exposure, Sensitivity
from ..utilities.thread_context import clear_search_context, set_search_context
@@ -1241,33 +1241,17 @@ class BaseSearchEngine(ABC):
def _scrub_error(self, error: Union[BaseException, str]) -> str:
"""Return a log/DB-safe rendering of *error*.
- Applies the "dual-scrub": the regex-based
- :func:`sanitize_error_message` pass (catches credential *shapes* —
- Bearer tokens, URL-embedded credentials, ``sk-``/``pk-`` keys)
- followed by :func:`redact_secrets` with this engine's known literal
- secret values (resolved from ``_secret_attrs``).
+ Delegates the "dual-scrub" to :func:`~..security.log_sanitizer.scrub_error`,
+ resolving this engine's known literal secret values from
+ ``_secret_attrs``. *error* may be an exception or a pre-built
+ message string.
Use this at every catch site that logs or persists an exception so
- the two scrub passes can never drift apart per-engine. *error* may be
- an exception or a pre-built message string.
-
- Defensive by design: this runs inside ``except`` blocks, so it must
- never raise. ``str(error)`` is guarded (a custom exception whose
- ``__str__`` raises won't crash the handler) and each secret is coerced
- to ``str`` (a misconfigured non-string secret, e.g. an int from
- settings, won't trip ``redact_secrets``' ``len()`` check).
+ the two scrub passes can never drift apart per-engine.
"""
- try:
- message = str(error)
- except Exception:
- message = f"<unprintable {type(error).__name__}>"
- # Coerce truthy non-str secrets to str; keep None/falsy as-is
- # (redact_secrets filters those out).
- secrets = [
- (v and str(v))
- for v in (getattr(self, name, None) for name in self._secret_attrs)
- ]
- return redact_secrets(sanitize_error_message(message), *secrets)
+ return scrub_error(
+ error, *(getattr(self, name, None) for name in self._secret_attrs)
+ )
def _mask_api_key(self, api_key: str, visible_chars: int = 4) -> str:
"""
diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.py
index 2ed661b51c..690acd2233 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
@@ -2,7 +2,7 @@ import inspect
from typing import Any, Dict, Optional
from ..security.egress.policy import PolicyDeniedError
-from ..security.log_sanitizer import redact_secrets, sanitize_error_message
+from ..security.log_sanitizer import scrub_error
from ..security.module_whitelist import get_safe_module_class
from ..security.secure_logging import logger
from .retriever_registry import retriever_registry
@@ -260,7 +260,7 @@ def create_search_engine(
requires_api_key = engine_config.get("requires_api_key", False)
# Bound here (not just inside ``if requires_api_key``) so the except
- # handler below can pass the in-scope key to redact_secrets() — without
+ # handler below can pass the in-scope key to scrub_error() — without
# the hoist, the no-key path would hit a NameError when scrubbing.
api_key = None
@@ -469,9 +469,7 @@ def create_search_engine(
# None — which would fail OPEN from an enforcement standpoint.
raise
except Exception as e:
- safe_msg = redact_secrets(
- sanitize_error_message(str(e)), api_key and str(api_key)
- )
+ safe_msg = scrub_error(e, api_key)
logger.exception(
f"Failed to create search engine '{engine_name}' ({type(e).__name__}): {safe_msg}"
)
@@ -490,7 +488,7 @@ def _create_full_search_wrapper(
"""Create a full search wrapper for the base engine if supported"""
try:
# Bound up here (re-populated below) so the except handler can
- # always pull credential values out of it for redact_secrets() —
+ # always pull credential values out of it for scrub_error() —
# without the hoist, an exception before the dict is rebuilt would
# hit a NameError when trying to scrub the keys.
wrapper_params: Dict[str, Any] = {}
@@ -610,17 +608,12 @@ def _create_full_search_wrapper(
except Exception as e:
# Extract any credential values the wrapper was going to receive
- # so a constructor exception echoing them gets literal-redacted.
- wrapper_secrets = [
- v
- for v in (
- wrapper_params.get("api_key"),
- wrapper_params.get("serpapi_api_key"),
- )
- if isinstance(v, str) and v
- ]
- safe_msg = redact_secrets(
- sanitize_error_message(str(e)), *wrapper_secrets
+ # so a constructor exception echoing them gets literal-redacted
+ # (scrub_error skips None/falsy values and str-coerces the rest).
+ safe_msg = scrub_error(
+ e,
+ wrapper_params.get("api_key"),
+ wrapper_params.get("serpapi_api_key"),
)
logger.exception(
f"Failed to create full search wrapper for {engine_name} ({type(e).__name__}): {safe_msg}"
diff --git a/tests/security/test_log_sanitizer.py b/tests/security/test_log_sanitizer.py
index ba33fb291e..9950d6f870 100644
--- a/tests/security/test_log_sanitizer.py
+++ b/tests/security/test_log_sanitizer.py
@@ -6,6 +6,7 @@ from local_deep_research.security.log_sanitizer import (
redact_secrets,
sanitize_error_for_client,
sanitize_for_log,
+ scrub_error,
strip_control_chars,
)
@@ -393,3 +394,91 @@ class TestSanitizeErrorForClient:
)
assert exported is sanitize_error_for_client
+
+
+class TestScrubError:
+ """Unit tests for scrub_error (the shared dual-scrub helper)."""
+
+ def test_scrubs_credential_shapes_from_exception(self):
+ err = ValueError("401 for Bearer sk-abc1234567890abcdef")
+ result = scrub_error(err)
+ assert "sk-abc1234567890abcdef" not in result
+
+ def test_redacts_literal_secrets(self):
+ # A bare key with no recognizable shape only falls to the
+ # literal pass — the reason the dual-scrub exists.
+ err = RuntimeError("auth failed for key plainkey12345678")
+ result = scrub_error(err, "plainkey12345678")
+ assert "plainkey12345678" not in result
+ assert "***REDACTED***" in result
+
+ def test_accepts_prebuilt_message_string(self):
+ result = scrub_error("token tok-xyz9876543 rejected", "tok-xyz9876543")
+ assert "tok-xyz9876543" not in result
+
+ def test_non_string_secret_coerced(self):
+ # A misconfigured numeric secret must not crash the except
+ # handler that calls this (redact_secrets calls len()).
+ err = RuntimeError("key 123456789012 invalid")
+ result = scrub_error(err, 123456789012)
+ assert "123456789012" not in result
+
+ def test_none_and_falsy_secrets_skipped(self):
+ msg = "plain message"
+ assert scrub_error(RuntimeError(msg), None, "", 0) == msg
+
+ def test_multiple_secrets_all_redacted(self):
+ # Kills the "forward only the first secret" mutant: every
+ # truthy secret must survive the coercion. (Longest-first
+ # ordering itself is pinned by
+ # test_overlapping_secrets_redacted_longest_first.)
+ err = RuntimeError("user token1234567 key sk-abc12345 done")
+ result = scrub_error(err, "token1234567", "abc12345", "sk-abc12345")
+ assert "token1234567" not in result
+ assert "abc12345" not in result
+
+ def test_pathological_secret_does_not_crash(self):
+ # The never-raise contract covers secrets too: a value whose
+ # __bool__/__str__ raises is skipped, not propagated out of the
+ # except handler; the other secrets are still redacted.
+ class BadBool:
+ def __bool__(self):
+ raise ValueError("nobool")
+
+ err = RuntimeError("key goodsecret123456 invalid")
+ result = scrub_error(err, BadBool(), "goodsecret123456")
+ assert "goodsecret123456" not in result
+
+ def test_unprintable_exception_guarded(self):
+ class Unprintable(Exception):
+ def __str__(self):
+ raise RuntimeError("boom")
+
+ result = scrub_error(Unprintable())
+ assert result == "<unprintable Unprintable>"
+
+ def test_matches_engine_scrub_error(self):
+ # BaseSearchEngine._scrub_error delegates here; the two must
+ # produce identical output for the same inputs.
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class _Engine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, relevant_items):
+ return relevant_items
+
+ # __new__ skips BaseSearchEngine.__init__ — only _scrub_error's
+ # _secret_attrs lookup matters here.
+ engine = _Engine.__new__(_Engine)
+ engine.api_key = "literalsecret123"
+ err = RuntimeError("denied for literalsecret123")
+ assert engine._scrub_error(err) == scrub_error(err, "literalsecret123")
+
+ def test_exported_from_security_package(self):
+ from local_deep_research.security import scrub_error as exported
+
+ assert exported is scrub_error