~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
refactor(security): dedupe _scrub_tool_error into sanitize_error_for_agent (#5034)
LearningCircuitd92a6a086d12
diff --git a/changelog.d/+security-agent-error-sanitizer-preset.misc.md b/changelog.d/+security-agent-error-sanitizer-preset.misc.mdnew file mode 100644index 0000000000..a9a92be699--- /dev/null+++ b/changelog.d/+security-agent-error-sanitizer-preset.misc.md@@ -0,0 +1 @@+Tool/agent error strings now flow through a single `security.sanitize_error_for_agent` helper instead of two identical `_scrub_tool_error` wrappers in `advanced_search_system/strategies/langgraph_agent_strategy.py` and `advanced_search_system/tools/fetch/__init__.py`. The new helper delegates to `sanitize_error_for_client` (credential redaction then control-char strip and length cap) with the 500-char cap that the agent path needs to preserve the categorizable signal for the `ErrorReporter` pattern map. No behavior change at any call site.diff --git a/docs/developing/credential-scrubbing.md b/docs/developing/credential-scrubbing.mdindex 925d69644a..5582476878 100644--- a/docs/developing/credential-scrubbing.md+++ b/docs/developing/credential-scrubbing.md@@ -14,6 +14,13 @@ for that, which this repo already runs in pre-commit/CI).`sk-`/`pk-`, Google `AIza`/`ya29.`, GitHub `ghp_`/`github_pat_`, AWS`AKIA`/`ASIA`, Slack `xox*-`, JWTs). `sanitize_error_for_client()` composesit with control-char stripping + length capping.+ `sanitize_error_for_agent()` is the agent/tool-facing sibling — it delegates+ to `sanitize_error_for_client()` with a 500-char cap instead of 200, so a+ classification signal such as a rate-limit phrase sitting deep in a provider+ message survives — and carries the same caveat: both remove credential+ *shapes* only, so use them on text already known to be safe apart from an+ embedded secret, never as a filter that makes an arbitrary exception safe+ to show.2. **`redact_secrets(text, *known_literals)`** — the **backstop**. When youhold the actual secret value (e.g. the configured API key), pass it here soit is scrubbed regardless of shape. This is the real guarantee fordiff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.pyindex dd64ed6a95..1be2d71bd5 100644--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py@@ -28,7 +28,7 @@ from ...citation_handler import CitationHandlerfrom ...security.egress import EngineClassification, classify_enginefrom ...security import (redact_url_for_log,- sanitize_error_for_client,+ sanitize_error_for_agent,scrub_error,)from ...utilities.llm_utils import invoke_llm_sync@@ -110,18 +110,6 @@ SUBAGENT_TIMEOUT_OVERALL_MULTIPLIER = 2 # safety cap multiplier: the overall# CONTENT_FETCH_TIMEOUT and CONTENT_MAX_LENGTH live alongside the fetch# tool builders in advanced_search_system/tools/fetch/.-# Cap for credential-scrubbed tool/agent error strings. Larger than the-# 200-char HTTP-client default of ``sanitize_error_for_client`` because these-# strings feed the agent's reasoning AND the ErrorReporter pattern map, where-# over-aggressive truncation drops the categorizable error signal. Credential-# scrubbing still runs first on the full untruncated string (#4633).-_TOOL_ERROR_MAX_LEN = 500---def _scrub_tool_error(message: str) -> str:- """Scrub credentials from an LLM/agent-facing tool error string."""- return sanitize_error_for_client(message, max_length=_TOOL_ERROR_MAX_LEN)-# ---------------------------------------------------------------------------# Thread-safe search result collector@@ -1208,7 +1196,7 @@ def _make_web_search_tool(# Scrub credentials: a search-engine exception can embed the# request URL, which may carry an API key. Full detail is logged# server-side above.- return _scrub_tool_error(f"Search error: {exc}")+ return sanitize_error_for_agent(f"Search error: {exc}")finally:safe_close(engine, "web search engine")try:@@ -1266,7 +1254,9 @@ def _make_specialized_search_tool(return _format_results(indexed, start)except Exception as exc:logger.exception(f"search_{engine_name} tool error")- return _scrub_tool_error(f"Search error ({engine_name}): {exc}")+ return sanitize_error_for_agent(+ f"Search error ({engine_name}): {exc}"+ )finally:safe_close(engine, f"{engine_name} search engine")try:@@ -1679,7 +1669,9 @@ def _make_research_subtopic_tool(return f"Research on '{topic}' reached iteration limit. Partial findings above."except Exception as exc:logger.exception(f"Subagent failed for: {topic[:80]}")- return _scrub_tool_error(f"Research on '{topic}' failed: {exc}")+ return sanitize_error_for_agent(+ f"Research on '{topic}' failed: {exc}"+ )# Capture the lead thread's search context (it carries the user's DB# password) so each pool worker can open the per-user ENCRYPTED database@@ -1824,7 +1816,7 @@ def _make_research_subtopic_tool(ordered_results[task_id] = future.result()except Exception as exc:logger.exception(f"Subagent failed for: {topic[:80]}")- ordered_results[task_id] = _scrub_tool_error(+ ordered_results[task_id] = sanitize_error_for_agent(f"Research on '{topic}' failed: {exc}")@@ -2689,7 +2681,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):except Exception as exc:logger.exception("Failed to create LangGraph agent")return self._error_result(- _scrub_tool_error(+ sanitize_error_for_agent(f"Failed to create agent (model may not "f"support tool calling): {exc}")@@ -2874,7 +2866,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):return get_llm_response_text(response)except Exception as exc:logger.exception("Fallback synthesis failed")- return _scrub_tool_error(+ return sanitize_error_for_agent(f"Research collected {len(results)} sources but "f"synthesis failed: {exc}")@@ -3139,7 +3131,9 @@ class LangGraphAgentStrategy(BaseSearchStrategy):# "Agent error: <Type>:" prefix stays at the front (no secrets, ahead# of any truncation) so the ErrorReportGenerator pattern map still# matches on the exception type.- return _scrub_tool_error(f"Agent error: {type(exc).__name__}: {exc}")+ return sanitize_error_for_agent(+ f"Agent error: {type(exc).__name__}: {exc}"+ )def _error_result(self, error: str) -> Dict[str, Any]:logger.error(f"LangGraph agent strategy error: {error}")diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.pyindex cb1e306521..d05d45cff2 100644--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py@@ -583,12 +583,14 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):# research_service.py:startswith("Error:") routes such strings# through ErrorReportGenerator for friendly rendering.logger.exception("Error in research process")- # max_length=500 aligns with _TOOL_ERROR_MAX_LEN- # (langgraph_agent_strategy.py) and _ERROR_BOUNDARY_MAX_LEN- # (web/api.py): the 200-char default would truncate- # categorizable tokens (e.g. "Connection refused" past char- # 200) here, before the boundary's more generous cap could- # preserve them for ErrorReportGenerator classification.+ # max_length=500, not the helper's 200-char default: a+ # categorizable token (e.g. "Connection refused") can sit past+ # char 200 of a long provider message, and cutting it here+ # would drop the signal before ErrorReportGenerator ever sees+ # it. The api_v1 HTTP boundary re-scrubs at the same 500, so+ # this string is never re-truncated downstream either. Written+ # as a literal: log_sanitizer's value is a private name, and+ # api_v1's lives in the web layer this module must not import.safe_msg = sanitize_error_for_client(str(e), max_length=500)synthesized_content = f"Error: {safe_msg}"formatted_findings = f"Error: {safe_msg}"diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.pyindex 6d1c7ce7a3..4540fa2bc8 100644--- a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py+++ b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py@@ -37,7 +37,7 @@ from local_deep_research.utilities.js_rendering import ()from local_deep_research.security import (redact_url_for_log,- sanitize_error_for_client,+ sanitize_error_for_agent,)from local_deep_research.utilities.llm_utils import invoke_llm_sync@@ -55,16 +55,6 @@ from .prompts import SUMMARY_FOCUS_PROMPT, SUMMARY_FOCUS_QUERY_PROMPTCONTENT_FETCH_TIMEOUT = 30CONTENT_MAX_LENGTH = 10_000-# Cap for credential-scrubbed fetch-tool error strings. Larger than the-# 200-char HTTP-client default because these errors feed the agent's-# reasoning; credential scrubbing still runs first on the full string (#4633).-_TOOL_ERROR_MAX_LEN = 500---def _scrub_tool_error(message: str) -> str:- """Scrub credentials from an LLM/agent-facing fetch-tool error string."""- return sanitize_error_for_client(message, max_length=_TOOL_ERROR_MAX_LEN)-FETCH_MODES = ("disabled",@@ -316,7 +306,7 @@ def _fetch_raw_content(if pre is not None:kind, payload = preif kind == _KIND_ERROR:- return None, url, _scrub_tool_error(payload)+ return None, url, sanitize_error_for_agent(payload)if kind == _KIND_RESULT:# A local library document was resolved directly from the user DB.# Skip both the egress gate (local read) and ContentFetcher (no HTTP).@@ -385,7 +375,7 @@ def _make_full_fetch_tool(# result['error'] comes from ContentFetcher, which returns a# raw str(exception) — scrub it (and the url) before this# reaches the agent/LLM and user-visible output (#4633).- return _scrub_tool_error(+ return sanitize_error_for_agent(f"Failed to fetch {url}: {result.get('error', 'unknown error')}")except PolicyDeniedError as exc:@@ -397,7 +387,7 @@ def _make_full_fetch_tool(# tool-error layer). The URL was already NOT fetched; the policy# already enforced — only the REPORTING changes, not security.target_url = getattr(exc, "target", "") or url- return _scrub_tool_error(+ return sanitize_error_for_agent(f"Cannot fetch {target_url}: blocked by egress policy "f"({_denial_reason(exc)}). {_EGRESS_DENIAL_HINT}")@@ -414,7 +404,9 @@ def _make_full_fetch_tool(mode_label,redact_url_for_log(target_url),)- return _scrub_tool_error(f"Error fetching {target_url}: {exc}")+ return sanitize_error_for_agent(+ f"Error fetching {target_url}: {exc}"+ )return fetch_content@@ -463,7 +455,7 @@ def _make_summary_fetch_tool(# result['error'] comes from ContentFetcher, which returns a# raw str(exception) — scrub it (and the url) before this# reaches the agent/LLM / user output (#4633).- return _scrub_tool_error(+ return sanitize_error_for_agent(f"Failed to fetch {url}: "f"{result.get('error', 'unknown error')}")@@ -511,7 +503,9 @@ def _make_summary_fetch_tool(mode_label,redact_url_for_log(url),)- return _scrub_tool_error(f"Error summarizing {url}: {exc}")+ return sanitize_error_for_agent(+ f"Error summarizing {url}: {exc}"+ )# Diagnostic log: per-fetch input/output for evaluating the# summariser. Single multi-line block so it's atomic per call@@ -551,7 +545,7 @@ def _make_summary_fetch_tool(# agent stays in-scope. The URL was already NOT fetched; only the# reporting changes, not security. (See the full-fetch variant.)target_url = getattr(exc, "target", "") or url- return _scrub_tool_error(+ return sanitize_error_for_agent(f"Cannot fetch {target_url}: blocked by egress policy "f"({_denial_reason(exc)}). {_EGRESS_DENIAL_HINT}")@@ -568,7 +562,9 @@ def _make_summary_fetch_tool(mode_label,redact_url_for_log(target_url),)- return _scrub_tool_error(f"Error fetching {target_url}: {exc}")+ return sanitize_error_for_agent(+ f"Error fetching {target_url}: {exc}"+ )return fetch_contentdiff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.pyindex 10c87a9ab1..ec6c77252b 100644--- a/src/local_deep_research/security/__init__.py+++ b/src/local_deep_research/security/__init__.py@@ -38,6 +38,7 @@ from .password_validator import PasswordValidatorfrom .log_sanitizer import (redact_secrets,sanitize_error_details,+ sanitize_error_for_agent,sanitize_error_for_client,sanitize_error_message,sanitize_for_log,@@ -105,6 +106,7 @@ __all__ = ["PasswordValidator","redact_secrets","sanitize_error_details",+ "sanitize_error_for_agent","sanitize_error_for_client","sanitize_error_message","sanitize_for_log",diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.pyindex 9452048950..a77d6eeed7 100644--- a/src/local_deep_research/security/log_sanitizer.py+++ b/src/local_deep_research/security/log_sanitizer.py@@ -290,8 +290,10 @@ _CREDENTIAL_PATTERNS: list[tuple[re.Pattern[str], str]] = [# 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.+# since that function also backs sanitize_error_for_client() — and, through it,+# sanitize_error_for_agent(), which is that helper at a 500-char cap — 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@@ -388,9 +390,10 @@ def scrub_error(error: Union[BaseException, str], *secrets: Any) -> str:logs via a library-formatted message such as``requests``' ``"... for url: https://host/path?term=<query>"``. Thislast 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).+ (which also backs the client-facing :func:`sanitize_error_for_client` and,+ through it, the agent-facing :func:`sanitize_error_for_agent` — 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 sothe passes can never drift apart per-site.@@ -476,6 +479,49 @@ def sanitize_error_for_client(message: str, max_length: int = 200) -> str:)+# Larger cap than ``sanitize_error_for_client``'s HTTP-client default: these+# strings feed the agent's reasoning AND the ErrorReporter pattern map, where+# over-aggressive truncation drops the categorizable error signal. Credential+# scrubbing still runs first on the full untruncated string (#4633).+_AGENT_ERROR_MAX_LEN = 500+++def sanitize_error_for_agent(message: str) -> str:+ """Scrub an exception-derived string that is bound for an LLM / agent.++ A preset over :func:`sanitize_error_for_client`: it removes credential+ *shapes* and control characters and caps the result at 500 characters.+ It delegates rather than re-composing those passes, so the agent path+ cannot drift away from the client path — the cap is the only+ difference between the two.++ Why 500 and not the client helper's 200-char default: a tool error+ feeds the model's reasoning loop and the ``ErrorReporter`` pattern map,+ and the classification signal often sits deep in a provider message (a+ rate-limit phrase such as ``"429 Too Many Requests"`` behind a long+ upstream prefix). A 200-char cap removes that signal before anything+ downstream can act on it.++ Scope, because it is easy to over-trust: this removes credential+ *shapes*. It does NOT remove server filesystem paths, SQL text,+ provider endpoints or dependency internals. Use it on a message the+ caller already knows to be safe apart from a possible embedded secret+ — not as a filter that makes an arbitrary exception safe to show.+ Where an exception can carry those other kinds of detail, do not pass+ its text through here at all: select one of a fixed set of messages+ from the exception's type, or forward only author-written constants,+ and keep the detail server-side in the logs.++ "Agent" is not a routing boundary. Agent-facing text does reach HTTP+ responses: a strategy's ``formatted_findings`` travels through+ ``api/research_functions.py`` to ``web/routers/api_v1.py``, whose+ boundary re-applies the same credential-shape pass. Choosing between+ this helper and :func:`sanitize_error_for_client` picks a cap; it does+ not decide where the string ends up.+ """+ return sanitize_error_for_client(message, max_length=_AGENT_ERROR_MAX_LEN)++def sanitize_error_details(value: Any) -> Any:"""Recursively redact credential *shapes* from the string leaves of astructured ``details`` value (``dict`` / ``list`` / ``tuple`` / dataclass).diff --git a/src/local_deep_research/web/routers/api_v1.py b/src/local_deep_research/web/routers/api_v1.pyindex 073a54a02b..3c957ead22 100644--- a/src/local_deep_research/web/routers/api_v1.py+++ b/src/local_deep_research/web/routers/api_v1.py@@ -34,8 +34,8 @@ from ..dependencies.threadpool import run_db_syncrouter = APIRouter(prefix="/api/v1", tags=["API v1"])-# Match the largest strategy-layer cap (_TOOL_ERROR_MAX_LEN = 500 in-# langgraph_agent_strategy.py) at the HTTP boundary so a message already+# Match the largest strategy-layer cap (_AGENT_ERROR_MAX_LEN = 500 in+# security/log_sanitizer.py) at the HTTP boundary so a message already# scrubbed at the strategy layer is never re-truncated here, and# categorizable exception tokens (e.g. "Connection refused" sitting deep in a# long error) survive to the API client. The 200-char default of@@ -47,7 +47,7 @@ def _scrub_error_fields(results: Dict[str, Any]) -> None:"""In-place defense-in-depth scrub for exception-derived fields about toleave the API (CWE-209, CodeQL #8019).- Strategy-layer ``_scrub_tool_error``/``sanitize_error_for_client`` already+ Strategy-layer ``sanitize_error_for_agent``/``sanitize_error_for_client`` alreadywraps exception text at the source; this is the final HTTP boundary. Onlyfires on fields that start with the literal ``"Error:"`` marker solegitimate research prose is never touched, and truncation is from the taildiff --git a/tests/security/test_log_sanitizer.py b/tests/security/test_log_sanitizer.pyindex 6fe684d32a..286647277c 100644--- a/tests/security/test_log_sanitizer.py+++ b/tests/security/test_log_sanitizer.py@@ -6,6 +6,7 @@ import pytestfrom local_deep_research.security.log_sanitizer import (redact_secrets,+ sanitize_error_for_agent,sanitize_error_for_client,sanitize_for_log,scrub_error,@@ -759,3 +760,80 @@ class TestScrubErrorUrlQueryRedaction:f"run (budget: 2.0s) — the scheme-continuation quantifier may "f"have regressed to unbounded, reintroducing quadratic ReDoS.")+++class TestSanitizeErrorForAgent:+ """The agent-facing composition used for tool errors returned into a+ LangGraph / agent reasoning loop. Same redaction as+ :class:`TestSanitizeErrorForClient`, but with a 500-char cap so the+ agent and the ErrorReporter pattern map keep the categorizable signal.+ """++ def test_redacts_api_key_in_url(self):+ msg = (+ "HTTPError for https://api.example.com/doc?api_key=secret1234567890"+ )+ result = sanitize_error_for_agent(msg)+ assert "secret1234567890" not in result++ def test_truncates_to_500_chars(self):+ # The HTTP-client default is 200; the agent cap is 500. A 600-char+ # message must be capped to 500, not 200.+ result = sanitize_error_for_agent("e" * 600)+ assert len(result) <= 500+ assert len(result) > 200 # would fail under the client cap++ def test_credential_scrubbed_before_truncation(self):+ # A key sitting past the 500-char boundary must still be redacted,+ # not merely cut off (scrub-before-truncate invariant).+ key = "sk-abcdefghijklmnopqrstuvwxyz0123456789"+ msg = "x" * 490 + " " + key+ result = sanitize_error_for_agent(msg)+ assert key not in result+ assert result == "x" * 490 + " [REDAC..."++ def test_preserves_long_categorizable_signal(self):+ # The whole reason for the larger cap: an ErrorReporter pattern like+ # "RateLimitError: 429 Too Many Requests (forwarded from upstream)"+ # must survive intact so the pattern map can categorize it. Under+ # the 200-char client cap the error type would be lost entirely.+ msg = (+ "upstream detail: "+ + "x" * 240+ + (+ " RateLimitError: 429 Too Many Requests — the upstream provider "+ "is throttling this account. Retry-After suggests backoff."+ )+ )+ result = sanitize_error_for_agent(msg)+ assert "RateLimitError" in result+ assert "429" in result+ assert len(result) == len(msg) # well under cap, unchanged++ def test_strips_control_characters(self):+ # Falsifiability: the composition is redaction THEN+ # sanitize_for_log, and only the latter strips control chars — a+ # mutant that drops it (returning sanitize_error_message alone, or+ # delegating to a client helper that only redacts) leaves these+ # bytes in place. _UNSAFE_CHAR_RE covers C0 (\x00-\x1f) and C1+ # (\x7f-\x9f) as separate ranges, so probe one of each alongside+ # a secret to pin both halves of the composition at once.+ key = "sk-abcdefghijklmnopqrstuvwxyz0123456789"+ msg = f"boom \x1b[31m ESC and \x9b CSI carrying {key} inline"+ result = sanitize_error_for_agent(msg)+ assert "\x1b" not in result # C0+ assert "\x9b" not in result # C1+ assert key not in result+ assert "[REDACTED_KEY]" in result++ def test_importable_from_security_package(self):+ import local_deep_research.security as security_pkg+ from local_deep_research.security import (+ sanitize_error_for_agent as exported,+ )++ assert exported is sanitize_error_for_agent+ # ``from ... import`` resolves the attribute directly and never+ # consults ``__all__``, so assert the export list separately: a+ # name dropped from ``__all__`` would otherwise pass unnoticed.+ assert "sanitize_error_for_agent" in security_pkg.__all__diff --git a/tests/strategies/test_strategy_analyze_topic.py b/tests/strategies/test_strategy_analyze_topic.pyindex b8e3a046ff..22f8b2d2cc 100644--- a/tests/strategies/test_strategy_analyze_topic.py+++ b/tests/strategies/test_strategy_analyze_topic.py@@ -453,8 +453,10 @@ class TestErrorHandling:settings_snapshot=strategy_settings_snapshot,)# The categorizable token sits past char 200 of the scrubbed- # message: it must survive the strategy-layer cap (500, aligned- # with _ERROR_BOUNDARY_MAX_LEN / _TOOL_ERROR_MAX_LEN). With+ # message (index 295 of 325): it must survive the strategy-layer+ # cap, the literal 500 in source_based_strategy.py — the same+ # value as api_v1.py's _ERROR_BOUNDARY_MAX_LEN and+ # log_sanitizer.py's _AGENT_ERROR_MAX_LEN. With# sanitize_error_for_client's 200-char default it would be# truncated away before the API boundary ever sees it.padding = "x" * 230