~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): strip URL query strings in scrub_error() (#6422)
Devansh KMcaf15bdf2617
diff --git a/changelog.d/6403.security.md b/changelog.d/6403.security.mdnew file mode 100644index 0000000000..ab1cd9e4ec--- /dev/null+++ b/changelog.d/6403.security.md@@ -0,0 +1 @@+`scrub_error` now strips URL query strings, so a failed request's `for url:` suffix can no longer carry the raw query text into logs.diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.pyindex 182fd42d35..26f2953b6d 100644--- a/src/local_deep_research/security/log_sanitizer.py+++ b/src/local_deep_research/security/log_sanitizer.py@@ -283,6 +283,48 @@ _CREDENTIAL_PATTERNS: list[tuple[re.Pattern[str], str]] = [),]+# Query string of any URL appearing in a message bound for logs/DB, e.g. the+# "for url: https://host/path?..." suffix `requests.Response.raise_for_status`+# appends to HTTPError. Only credential-*shaped* query params are redacted by+# _CREDENTIAL_PATTERNS above; an arbitrary parameter (a search engine's `term=`,+# an `id=`, a filter) carries no credential shape yet may still be user-supplied+# text (e.g. the user's raw search query) that should not reach a log sink.+# Scoped to scrub_error() only (see below) — NOT part of sanitize_error_message,+# since that function also backs sanitize_error_for_client(), where preserving+# a failed request's own query string is useful for the caller debugging it.+#+# Scheme: RFC 3986 §3.1 is one ALPHA followed by zero or more+# ALPHA/DIGIT/+/-/. — the *lower* bound must stay 0 so a valid+# single-character scheme (``x://...``) still matches, but the+# *continuation* is capped at 31 chars (matches the sibling URL-credential+# pattern above). An unbounded ``*`` here is a measured quadratic ReDoS:+# on a message containing a long ALPHA/DIGIT/+/-/. run with no following+# "://" (e.g. a stringified response body reaching str(error)), the engine+# retries the "://" match at every run offset, backtracking the whole+# remaining run each time — O(n^2). Verified locally: unbounded, a 40k-char+# run takes ~1.5s (quadratic: ~4x per input doubling); bounded, the same+# input is back to microseconds. See test_scrub_error_is_linear_time_on_a_+# long_scheme_like_run.+#+# Query stop-set: whitespace plus the common wrappers a URL appears inside+# in prose/logs (a markdown link's ``)``, a bracketed/braced reference, or+# a quote) so the redaction doesn't consume past the URL's actual end and+# corrupt the surrounding message (e.g. eating a markdown link's closing+# paren, or swallowing a second, unspaced adjacent URL's own leading+# scheme once the first URL's wrapper is reached). Requires >=1 char+# (``+``, not ``*``): a bare trailing "?" with nothing after it is not a+# query at all, so a sentence-final "...page? yes" must not be rewritten+# into "...page?<redacted> yes", which would imply a query existed.+_URL_QUERY_STRING_RE = re.compile(+ r"([A-Za-z][A-Za-z0-9+.\-]{0,31}://[^\s?#]+)\?[^\s)\]\}\"']+"+)+++def _redact_url_query_strings(message: str) -> str:+ """Replace the query component of any URL in *message* with a fixed+ marker, preserving the scheme/host/path so the endpoint stays legible."""+ return _URL_QUERY_STRING_RE.sub(r"\1?<redacted>", message)+def sanitize_error_message(message: str) -> str:"""Remove or mask API keys, tokens, and secrets from *message* using@@ -310,15 +352,24 @@ def sanitize_error_message(message: str) -> str:def scrub_error(error: Union[BaseException, str], *secrets: Any) -> str:- """Return a log/DB-safe rendering of *error* (the "dual-scrub").+ """Return a log/DB-safe rendering of *error* (the "triple-scrub").- Composes the two scrub passes every catch site needs:+ Composes the 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.+ tokens, URL-embedded credentials, ``sk-``/``pk-`` keys), then+ :func:`redact_secrets` with the caller's known literal secret values,+ then a blanket strip of any URL's query string (``?...`` →+ ``?<redacted>``) so a non-credential-shaped parameter — e.g. a search+ engine's ``term=`` — cannot carry the caller's raw query text into+ logs via a library-formatted message such as+ ``requests``' ``"... for url: https://host/path?term=<query>"``. This+ last pass is specific to ``scrub_error``, not :func:`sanitize_error_message`+ (which also backs the client-facing :func:`sanitize_error_for_client`,+ where preserving a failed request's own query string is useful for the+ caller debugging it).Use this at every catch site that logs or persists an exception so- the two passes can never drift apart per-site.+ the passes can never drift apart per-site.``BaseSearchEngine._scrub_error`` delegates here, resolving itsengine's ``_secret_attrs`` into the *secrets* arguments.@@ -351,7 +402,9 @@ def scrub_error(error: Union[BaseException, str], *secrets: Any) -> str:safe_secrets.append(v and str(v))except Exception:continue- return redact_secrets(sanitize_error_message(message), *safe_secrets)+ return _redact_url_query_strings(+ redact_secrets(sanitize_error_message(message), *safe_secrets)+ )def sanitize_error_for_client(message: str, max_length: int = 200) -> str: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 ce4795d9b9..5c1874f37b 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@@ -224,7 +224,7 @@ class BaseSearchEngine(ABC):# Instance-attribute names holding credential values to redact from error# messages/logs via _scrub_error(). Subclasses override when they store# secrets under different names (e.g. Elasticsearch: _api_key/_password).- # Centralizing the list keeps every dual-scrub call site uniform and+ # Centralizing the list keeps every _scrub_error() call site uniform and# prevents the per-site drift that previously dropped a secret._secret_attrs: tuple[str, ...] = ("api_key",)@@ -798,7 +798,7 @@ class BaseSearchEngine(ABC):success = False# Sanitize before it flows to SearchTracker.record_search# (and the database) and to the log. Use logger.warning with- # the dual-scrubbed text instead of logger.exception: the+ # the scrubbed text instead of logger.exception: the# cause chain frequently carries the request URL or auth# header from upstream HTTP clients (see #4131).error_message = safe_msg = self._scrub_error(e)@@ -1305,13 +1305,13 @@ class BaseSearchEngine(ABC):def _scrub_error(self, error: Union[BaseException, str]) -> str:"""Return a log/DB-safe rendering of *error*.- Delegates the "dual-scrub" to :func:`~..security.log_sanitizer.scrub_error`,+ Delegates the "triple-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-builtmessage string.Use this at every catch site that logs or persists an exception so- the two scrub passes can never drift apart per-engine.+ the scrub passes can never drift apart per-engine."""return scrub_error(error, *(getattr(self, name, None) for name in self._secret_attrs)diff --git a/tests/security/test_log_sanitizer.py b/tests/security/test_log_sanitizer.pyindex b066dbe18e..3c5c07d083 100644--- a/tests/security/test_log_sanitizer.py+++ b/tests/security/test_log_sanitizer.py@@ -1,5 +1,7 @@"""Tests for log string sanitization."""+import time+import pytestfrom local_deep_research.security.log_sanitizer import (@@ -529,3 +531,148 @@ class TestScrubError:from local_deep_research.security import scrub_error as exportedassert exported is scrub_error+++class TestScrubErrorUrlQueryRedaction:+ """scrub_error() must strip a URL's query string even when it carries no+ credential-shaped parameter (#6403) — e.g. a search engine's own query+ text, reachable via a library-formatted message such as+ ``requests.Response.raise_for_status``'s ``"... for url: <url>"``.++ Scoped to scrub_error() only: sanitize_error_for_client() (the+ client-facing path) must keep preserving non-credential query params,+ per TestSanitizeErrorForClient.test_does_not_over_redact_innocuous_text.+ """++ def test_strips_query_string_from_requests_style_http_error(self):+ # Reproduces the PubMed 429 case from #6403: raise_for_status()+ # embeds the fully-encoded request URL, including the raw query+ # text, in the exception message.+ probe = "does+my+employer+know+i+have+multiple+sclerosis"+ msg = (+ "429 Client Error: Too Many Requests for url: "+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"+ f"?db=pubmed&term={probe}&retmode=json&retmax=100&usehistory=y"+ )+ result = scrub_error(Exception(msg))+ assert probe not in result+ assert "term=" not in result+ # Endpoint identity (scheme/host/path) survives — only the query+ # component is replaced, so the handler's own diagnostic value+ # (status, reason, which endpoint) is preserved.+ assert (+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"+ "?<redacted>" in result+ )+ assert "429 Client Error: Too Many Requests" in result++ def test_still_redacts_credential_shaped_query_params(self):+ # The existing credential-query-param pass and the new blanket+ # strip are not mutually exclusive — a credential-shaped param+ # must still end up redacted.+ err = Exception(+ "err https://api.x.com/search?access_token=SECRET_AT_123 fail"+ )+ result = scrub_error(err)+ assert "SECRET_AT_123" not in result++ def test_message_without_a_url_is_untouched(self):+ assert scrub_error(Exception("plain failure, no url")) == (+ "plain failure, no url"+ )++ def test_url_without_query_string_is_untouched(self):+ msg = "GET https://example.com/health failed"+ assert scrub_error(Exception(msg)) == msg++ def test_does_not_affect_sanitize_error_for_client(self):+ # The blanket URL-query strip is scrub_error-only; the client-facing+ # path must keep preserving non-credential query params (locked by+ # TestSanitizeErrorForClient.test_does_not_over_redact_innocuous_text).+ msg = "fetched https://example.com/path?id=42 ok"+ assert "id=42" in sanitize_error_for_client(msg)++ def test_one_character_scheme_is_covered(self):+ # RFC 3986 §3.1: a scheme is one ALPHA followed by zero or more+ # ALPHA/DIGIT/+/-/. — a lower-bound-1 continuation quantifier would+ # silently skip a valid single-character scheme (review of #6422).+ result = scrub_error(Exception("x://host/path?term=secret"))+ assert "secret" not in result+ assert "x://host/path?<redacted>" in result++ def test_markdown_link_closing_paren_survives(self):+ # The query must not consume past the URL's own end when it's+ # wrapped in prose punctuation — a markdown link's closing ``)``+ # must not be eaten by the redaction (review of #6422).+ result = scrub_error(Exception("see [link](https://h/p?q=1) end"))+ assert result == "see [link](https://h/p?<redacted>) end"++ def test_quoted_url_closing_quote_survives(self):+ result = scrub_error(Exception('url "https://h/p?q=1" end'))+ assert result == 'url "https://h/p?<redacted>" end'++ def test_unspaced_adjacent_urls_fail_closed(self):+ # Two URLs with no whitespace between them (e.g. a comma-joined+ # list) are not split apart — the first URL's query pattern has no+ # way to know where it ends short of whitespace/wrapper chars, so+ # the second URL is swallowed into the first's redaction. This is+ # accepted (review of #6422): over-redaction, never a leak — no+ # raw query value from either URL survives.+ result = scrub_error(+ Exception("https://x.com/p?k=1,https://y.org/q?z=2")+ )+ assert result == "https://x.com/p?<redacted>"+ assert "k=1" not in result+ assert "z=2" not in result++ def test_apostrophe_in_query_is_a_known_accepted_edge(self):+ # Stopping the query at a closing quote (needed so a *quoted URL*'s+ # own trailing quote survives, see+ # test_quoted_url_closing_quote_survives) means a literal, unencoded+ # apostrophe *inside* query text also stops the redaction early.+ # Accepted per review of #6422, on the same footing as the+ # already-accepted raw-unencoded-space edge: a URL built by a real+ # HTTP client always percent-encodes "'" to "%27", so this shape+ # does not occur in a prepared request URL.+ result = scrub_error(+ Exception("fetch https://h/p?term=what's+up failed")+ )+ assert "https://h/p?<redacted>" in result+ assert "up failed" in result++ def test_bare_question_mark_with_no_query_is_untouched(self):+ # The query group requires >=1 char (``+``, not ``*``): a bare+ # trailing "?" is not a query, so it must not be rewritten into+ # "?<redacted>", which would imply a query existed where none did+ # (review of #6422).+ msg = "try https://h/p? yes"+ assert scrub_error(Exception(msg)) == msg++ @pytest.mark.timeout(5)+ def test_scrub_error_is_linear_time_on_a_long_scheme_like_run(self):+ # @pytest.mark.timeout is a hard backstop, not just the assertion+ # below: it fails the test outright if scrub_error itself hangs,+ # so a regression worse than quadratic can't block CI indefinitely+ # waiting for a call that would otherwise never return in time.+ #+ # Regression for a measured quadratic ReDoS (review of #6422): an+ # unbounded scheme-continuation quantifier (``[A-Za-z0-9+.-]*``)+ # made matching O(n^2) on a long ALPHA/DIGIT/+/-/. run with no+ # following "://" — at every start offset the engine consumes the+ # run, fails to find "://", and backtracks the whole remaining run.+ # Measured on the unbounded regex: 50k chars ~1.4s, 100k ~5.8s,+ # 200k ~23.5s, 400k ~92.9s (clean quadratic, ~4x per doubling) —+ # a ~1MB run would hang a worker for ~15 minutes, on a path that+ # by definition handles attacker-influenceable exception text.+ # Bounding the continuation restores linear time (locally: 200k+ # chars in ~50ms). Generous 2s budget absorbs noisy CI runners+ # while still catching a regression by orders of magnitude.+ run = "a" * 200_000 # no "://" anywhere in this string+ t0 = time.perf_counter()+ scrub_error(Exception(run))+ elapsed = time.perf_counter() - t0+ assert elapsed < 2.0, (+ f"scrub_error took {elapsed:.2f}s on a 200k-char scheme-like "+ f"run (budget: 2.0s) — the scheme-continuation quantifier may "+ f"have regressed to unbounded, reintroducing quadratic ReDoS."+ )