~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): scrub RateLimitError leak + route CLI through secure wrapper (#4996)
LearningCircuit92a8f2c3c797
diff --git a/changelog.d/4996.security.md b/changelog.d/4996.security.mdnew file mode 100644index 0000000000..0c2aeaaf6a--- /dev/null+++ b/changelog.d/4996.security.md@@ -0,0 +1 @@+`RateLimitError` exceptions raised by the PubMed and arXiv search engines and the rate-limited LLM wrapper now carry the scrubbed exception message instead of the raw `str(e)`, and are raised `from None` so the implicit `__context__` chain (which still holds the raw message) cannot re-leak through full-traceback renderers such as the thread excepthook or diagnose-mode logging. This closes a leak where credentials echoed back in an upstream 429 error body (e.g. a Bearer token) could re-leak through tenacity or global exception handlers that log the raised exception outside the secure-logging directories. The rate-limiting monitoring CLI's top-level exception handler now prints the scrubbed reason to stderr (the package disables loguru at import, so a logger call alone is invisible in standalone runs) and routes the same scrubbed reason through the `security.secure_logging` wrapper instead of `print(str(e))`.diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.pyindex 6a43bad162..9c73f3a862 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py@@ -185,7 +185,13 @@ class ArXivSearchEngine(BaseSearchEngine):or "service unavailable" in error_msg.lower()or "503" in error_msg):- raise RateLimitError(f"arXiv rate limit hit: {error_msg}")+ # `from None` suppresses the implicit __context__ chain:+ # the original exception still carries the raw message, so+ # a full traceback render (chain=True) would re-leak the+ # secret that safe_msg just scrubbed.+ raise RateLimitError(+ f"arXiv rate limit hit: {safe_msg}"+ ) from Nonereturn []diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.pyindex f5c435a2c4..f531e76ebd 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py@@ -808,7 +808,13 @@ The default assumption should be that medical and scientific queries want RECENTor "503" in error_msgor "403" in error_msg):- raise RateLimitError(f"PubMed rate limit hit: {error_msg}")+ # `from None` suppresses the implicit __context__ chain:+ # the original exception still carries the raw message, so+ # a full traceback render (chain=True) would re-leak the+ # secret that safe_msg just scrubbed.+ raise RateLimitError(+ f"PubMed rate limit hit: {safe_msg}"+ ) from Nonereturn []diff --git a/src/local_deep_research/web_search_engines/rate_limiting/cli.py b/src/local_deep_research/web_search_engines/rate_limiting/cli.pyindex 109c4c0d0c..fb604cd72e 100644--- a/src/local_deep_research/web_search_engines/rate_limiting/cli.py+++ b/src/local_deep_research/web_search_engines/rate_limiting/cli.py@@ -6,6 +6,8 @@ import argparseimport sysfrom datetime import datetime+from ...security import scrub_error+from ...security.secure_logging import loggerfrom .tracker import get_tracker@@ -201,7 +203,17 @@ Examples:try:args.func(args)except Exception as e:- print(f"Error: {e}")+ # Surface a scrubbed reason so operators see *what* failed without+ # leaking secrets that may be embedded in str(e) (e.g. a Bearer+ # token echoed back in an upstream 429). The package disables+ # loguru for "local_deep_research" at import time and only the+ # web app's config_logger() re-enables it, so in a standalone CLI+ # run the logger call alone would be invisible — print the+ # scrubbed reason to stderr too. The wrapper gates the traceback+ # behind LDR_APP_DEBUG + LDR_LOGURU_DIAGNOSE.+ safe_reason = scrub_error(e)+ print(f"Error: {safe_reason}", file=sys.stderr)+ logger.exception(f"Rate-limiting CLI command failed: {safe_reason}")sys.exit(1)diff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.pyindex 35595d4f1c..ecb3d24f3c 100644--- a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py@@ -5,6 +5,7 @@ Rate-limited wrapper for LLM calls.from typing import Optionalfrom urllib.parse import urlparse+from ....security import scrub_errorfrom ....security.secure_logging import loggerfrom tenacity import (retry,@@ -191,7 +192,16 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):# Check if it's a rate limit error and wrap itif is_llm_rate_limit_error(e):logger.warning("LLM rate limit error detected")- raise RateLimitError(f"LLM rate limit: {str(e)}")+ # Scrub before wrapping: LLM providers can echo the+ # Authorization header back in a 429 body. The scrub+ # keeps non-credential text (e.g. "retry after 20+ # seconds") intact for extract_retry_after(). `from+ # None` suppresses the __context__ chain, which still+ # carries the raw message.+ safe_msg = scrub_error(e)+ raise RateLimitError(+ f"LLM rate limit: {safe_msg}"+ ) from Noneraise# Pass through any other attributes to the base LLMdiff --git a/tests/rate_limiting/test_cli.py b/tests/rate_limiting/test_cli.pynew file mode 100644index 0000000000..eb60ab682d--- /dev/null+++ b/tests/rate_limiting/test_cli.py@@ -0,0 +1,103 @@+"""Tests for the rate-limiting monitoring CLI.++Covers the top-level exception handler: it must surface a *scrubbed*+reason on stderr (standalone CLI runs have loguru disabled for the+``local_deep_research`` namespace, so a logger call alone is invisible)+and route the same scrubbed reason through the ``security.secure_logging``+wrapper — not ``print(str(e))``, which leaked raw ``str(e)`` to stdout,+bypassing the secure-logging gating the rest of ``web_search_engines/``+enforces.+"""++import sys+from unittest.mock import Mock++import pytest++from local_deep_research.web_search_engines.rate_limiting import cli+++def test_top_level_exception_uses_secure_wrapper(monkeypatch):+ """Unhandled exceptions must hit ``logger.exception`` and exit 1."""++ def boom(_args):+ raise RuntimeError("simulated CLI failure")++ monkeypatch.setattr(cli, "cmd_status", boom)+ monkeypatch.setattr(sys, "argv", ["cli", "status"])++ logger_spy = Mock()+ monkeypatch.setattr(cli, "logger", logger_spy)++ with pytest.raises(SystemExit) as exc_info:+ cli.main()++ assert exc_info.value.code == 1+ logger_spy.exception.assert_called_once()+ # The scrubbed reason must be interpolated; bare "command failed"+ # leaves operators with zero detail (regression guarded below).+ args, _ = logger_spy.exception.call_args+ assert "simulated CLI failure" in args[0]+++def test_top_level_exception_prints_scrubbed_reason_to_stderr(+ monkeypatch, capsys+):+ """The scrubbed reason must be visible without any logging setup.++ ``local_deep_research/__init__`` calls ``logger.disable()`` for the+ package namespace at import time, and only the web app's+ ``config_logger()`` re-enables it — the CLI never does. So in a+ standalone run the logger call alone produces no visible output; the+ handler must also print the scrubbed reason to stderr, or operators+ get a silent exit 1.+ """+ leaked = "Bearer sk-cli-leaked-1234567890"++ def boom(_args):+ raise RuntimeError(f"upstream 429: {leaked}")++ monkeypatch.setattr(cli, "cmd_status", boom)+ monkeypatch.setattr(sys, "argv", ["cli", "status"])++ with pytest.raises(SystemExit) as exc_info:+ cli.main()++ assert exc_info.value.code == 1+ err = capsys.readouterr().err+ assert leaked not in err+ assert "upstream 429:" in err+ assert "[REDACTED" in err+++def test_top_level_exception_scrubs_secret_in_message(+ monkeypatch, loguru_caplog_full+):+ """Secrets embedded in ``str(e)`` must not reach log sinks.++ The CLI's top-level handler interpolates ``scrub_error(e)`` — if that+ scrubbing ever regresses to ``str(e)`` directly, the secret would+ land in the log output. (The ``{exception}`` block the fixture+ renders stays empty here: diagnose mode is off by default, so the+ wrapper never attaches the exception object — the assertions guard+ the message line.)+ """+ leaked = "Bearer sk-cli-leaked-1234567890"++ def boom(_args):+ raise RuntimeError(f"upstream 429: {leaked}")++ monkeypatch.setattr(cli, "cmd_status", boom)+ monkeypatch.setattr(sys, "argv", ["cli", "status"])++ with loguru_caplog_full.at_level("ERROR"):+ with pytest.raises(SystemExit):+ cli.main()++ log_text = loguru_caplog_full.text+ assert leaked not in log_text+ # The scrubber collapses ``sk-...`` to ``[REDACTED]``; the surrounding+ # ``upstream 429:`` text is non-secret and should still appear so+ # operators see *what* failed (not just that something failed).+ assert "upstream 429:" in log_text+ assert "[REDACTED" in log_textdiff --git a/tests/rate_limiting/test_llm_wrapper_extended.py b/tests/rate_limiting/test_llm_wrapper_extended.pyindex a52bd74cdf..cdaf131091 100644--- a/tests/rate_limiting/test_llm_wrapper_extended.py+++ b/tests/rate_limiting/test_llm_wrapper_extended.py@@ -216,6 +216,40 @@ class TestDoInvoke:with pytest.raises(RateLimitError, match="LLM rate limit"):wrapper._do_invoke("test prompt")+ def test_rate_limit_error_message_is_scrubbed(self):+ """Wrapped RateLimitError must not carry raw exception secrets.++ LLM providers can echo the Authorization header back in a 429+ body. The wrapped error must carry the scrubbed message, keep+ non-credential text (used by ``extract_retry_after``), and a full+ traceback render must not re-leak the secret through the implicit+ ``__context__`` chain (guards the ``from None`` on the raise).+ """+ import traceback++ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )+ from local_deep_research.web_search_engines.rate_limiting.exceptions import (+ RateLimitError,+ )++ leaked = "Bearer sk-llmleaked1234567890"+ base_llm = Mock()+ base_llm.invoke.side_effect = Exception(+ f"429 rate limit exceeded: {leaked}, retry after 20 seconds"+ )+ wrapper = create_rate_limited_llm_wrapper(base_llm)++ with pytest.raises(RateLimitError) as exc_info:+ wrapper._do_invoke("test prompt")++ msg = str(exc_info.value)+ assert "sk-llmleaked1234567890" not in msg+ assert "retry after 20 seconds" in msg+ rendered = "".join(traceback.format_exception(exc_info.value))+ assert "sk-llmleaked1234567890" not in rendered+def test_non_rate_limit_error_passed_through(self):"""Non-rate-limit errors pass through unchanged."""from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (diff --git a/tests/search_engines/test_search_engine_arxiv.py b/tests/search_engines/test_search_engine_arxiv.pyindex 6bc0d84c10..48a678b1f2 100644--- a/tests/search_engines/test_search_engine_arxiv.py+++ b/tests/search_engines/test_search_engine_arxiv.py@@ -184,6 +184,43 @@ class TestArXivErrorHandling:results = arxiv_engine._get_previews("test query")assert results == []+ def test_rate_limit_error_message_is_scrubbed(+ self, arxiv_engine, monkeypatch+ ):+ """Raised RateLimitError must not propagate raw exception secrets.++ An upstream API can echo credentials back in an error body (e.g. a+ Bearer token in a 429 response). The substring check on ``error_msg``+ identifies the rate-limit shape, but the raised ``RateLimitError``+ must carry the scrubbed ``safe_msg`` — otherwise tenacity / global+ handlers logging the raised exception re-leak the secret.+ """+ import traceback+ from urllib.error import URLError++ from local_deep_research.web_search_engines.rate_limiting import (+ RateLimitError,+ )++ leaked = "Bearer sk-arxivleaked0987654321"+ mock_client = Mock()+ mock_client.results.side_effect = URLError(+ f"429 Too Many Requests: {leaked}"+ )+ monkeypatch.setattr("arxiv.Client", Mock(return_value=mock_client))+ monkeypatch.setattr("arxiv.Search", Mock(return_value=Mock()))++ with pytest.raises(RateLimitError) as exc_info:+ arxiv_engine._get_previews("test query")++ msg = str(exc_info.value)+ assert "sk-arxivleaked0987654321" not in msg+ # A full traceback render must not re-leak the secret through the+ # implicit __context__ chain (guards the `from None` on the raise:+ # handlers like the thread excepthook format with chain=True).+ rendered = "".join(traceback.format_exception(exc_info.value))+ assert "sk-arxivleaked0987654321" not in rendered+class TestArXivSortingOptions:"""Tests for ArXiv sorting functionality."""diff --git a/tests/web_search_engines/engines/test_search_engine_pubmed.py b/tests/web_search_engines/engines/test_search_engine_pubmed.pyindex ddfbeb44c0..58d521b0a1 100644--- a/tests/web_search_engines/engines/test_search_engine_pubmed.py+++ b/tests/web_search_engines/engines/test_search_engine_pubmed.py@@ -12,6 +12,8 @@ Tests cover:from unittest.mock import Mock, patch+import pytest+class TestPubMedSearchEngineInit:"""Tests for PubMedSearchEngine initialization."""@@ -826,6 +828,39 @@ class TestGetArticleSummaries:except RateLimitError:pass # Expected+ def test_rate_limit_error_message_is_scrubbed(self):+ """Raised RateLimitError must not propagate raw exception secrets.++ An upstream API can echo credentials back in an error body (e.g. a+ Bearer token in a 429 response). The raised ``RateLimitError`` must+ carry the scrubbed ``safe_msg``, and a full traceback render must+ not re-leak the secret through the implicit ``__context__`` chain+ (guards the ``from None`` on the raise).+ """+ import traceback++ from local_deep_research.web_search_engines.engines.search_engine_pubmed import (+ PubMedSearchEngine,+ )+ from local_deep_research.web_search_engines.rate_limiting import (+ RateLimitError,+ )++ engine = PubMedSearchEngine()+ leaked = "Bearer sk-pubmedleaked1234567890"++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_pubmed.safe_get"+ ) as mock_get:+ mock_get.side_effect = Exception(f"429 Too Many Requests: {leaked}")++ with pytest.raises(RateLimitError) as exc_info:+ engine._get_article_summaries(["12345"])++ assert "sk-pubmedleaked1234567890" not in str(exc_info.value)+ rendered = "".join(traceback.format_exception(exc_info.value))+ assert "sk-pubmedleaked1234567890" not in rendered+class TestGetArticleAbstracts:"""Tests for _get_article_abstracts method."""