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(security): scrub credentials from search/fetch/agent tool errors (follow-up to #4625) (#4633)

LearningCircuit1629ddffb2e2
diff --git a/changelog.d/+scrub-search-fetch-tool-errors.security.md b/changelog.d/+scrub-search-fetch-tool-errors.security.md
new file mode 100644
index 0000000000..a4e8ae5d8c
--- /dev/null
+++ b/changelog.d/+scrub-search-fetch-tool-errors.security.md
@@ -0,0 +1 @@
+Search, fetch, and agent tool error messages are now scrubbed of credentials before they reach the LLM and the user-visible research output — a search-engine or LLM exception can embed a request URL carrying an API key, so these are now routed through the same `sanitize_error_for_client` helper used for download errors.
diff --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.py
index 69ef4b87fd..7bcbdf5114 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
@@ -27,6 +27,7 @@ from ...utilities.search_utilities import (
from ..tools.fetch import FETCH_MODES, build_fetch_tool
from .base_strategy import BaseSearchStrategy
from ...constants import DEFAULT_SEARCH_TOOL
+from ...security import sanitize_error_for_client
# ---------------------------------------------------------------------------
# Constants
@@ -42,6 +43,18 @@ MAX_SUBAGENT_WORKERS = 4
# 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
@@ -221,7 +234,10 @@ def _make_web_search_tool(
return _format_results(results, start)
except Exception as exc:
logger.exception("web_search tool error")
- return f"Search error: {exc}"
+ # 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}")
finally:
safe_close(engine, "web search engine")
@@ -266,7 +282,7 @@ def _make_specialized_search_tool(
return _format_results(results, start)
except Exception as exc:
logger.exception(f"search_{engine_name} tool error")
- return f"Search error ({engine_name}): {exc}"
+ return _scrub_tool_error(f"Search error ({engine_name}): {exc}")
finally:
safe_close(engine, f"{engine_name} search engine")
@@ -376,7 +392,7 @@ 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 f"Research on '{topic}' failed: {exc}"
+ return _scrub_tool_error(f"Research on '{topic}' failed: {exc}")
def _run_subagent_with_egress(topic: str) -> str:
# threading.local is NOT inherited by ThreadPoolExecutor workers,
@@ -414,7 +430,8 @@ def _make_research_subtopic_tool(
f"Research on '{topic}' timed out."
)
except Exception as exc:
- ordered_results[topic] = (
+ logger.exception(f"Subagent failed for: {topic[:80]}")
+ ordered_results[topic] = _scrub_tool_error(
f"Research on '{topic}' failed: {exc}"
)
except TimeoutError:
@@ -867,7 +884,10 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
except Exception as exc:
logger.exception("Failed to create LangGraph agent")
return self._error_result(
- f"Failed to create agent (model may not support tool calling): {exc}"
+ _scrub_tool_error(
+ f"Failed to create agent (model may not "
+ f"support tool calling): {exc}"
+ )
)
# Stream agent execution
@@ -1114,7 +1134,10 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
)
except Exception as exc:
logger.exception("Fallback synthesis failed")
- return f"Research collected {len(results)} sources but synthesis failed: {exc}"
+ return _scrub_tool_error(
+ f"Research collected {len(results)} sources but "
+ f"synthesis failed: {exc}"
+ )
def _finalize(
self,
@@ -1215,7 +1238,11 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
on. The bare `str(exc)` produced by the catch-all loses the type,
which makes deep LangChain / LangGraph failures hard to recognise.
"""
- return f"Agent error: {type(exc).__name__}: {exc}"
+ # Scrub credentials before this error is rendered to the user. The
+ # "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}")
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/tools/fetch/__init__.py b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
index 483c19b634..bc79f6c731 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
@@ -35,6 +35,7 @@ from loguru import logger
from local_deep_research.utilities.js_rendering import (
read_js_rendering_setting as _read_js_rendering_setting,
)
+from local_deep_research.security import sanitize_error_for_client
from .prompts import SUMMARY_FOCUS_PROMPT, SUMMARY_FOCUS_QUERY_PROMPT
@@ -45,6 +46,17 @@ from .prompts import SUMMARY_FOCUS_PROMPT, SUMMARY_FOCUS_QUERY_PROMPT
CONTENT_FETCH_TIMEOUT = 30
CONTENT_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",
"full",
@@ -132,12 +144,21 @@ def _make_full_fetch_tool(
return (
f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{content}"
)
- return f"Failed to fetch {url}: {result.get('error', 'unknown error')}"
+ # 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(
+ f"Failed to fetch {url}: "
+ f"{result.get('error', 'unknown error')}"
+ )
except PolicyDeniedError:
raise
except Exception as exc:
logger.exception("fetch_content tool error")
- return f"Error fetching {url}: {exc}"
+ # Scrub credentials before this reaches the agent/LLM and the
+ # user-visible research output: the exception (or url) can embed
+ # a credentialed URL. Full detail stays in the server log above.
+ return _scrub_tool_error(f"Error fetching {url}: {exc}")
return fetch_content
@@ -181,7 +202,13 @@ def _make_summary_fetch_tool(
) as fetcher:
result = fetcher.fetch(url, max_length=CONTENT_MAX_LENGTH)
if result.get("status") != "success":
- return f"Failed to fetch {url}: {result.get('error', 'unknown error')}"
+ # 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(
+ f"Failed to fetch {url}: "
+ f"{result.get('error', 'unknown error')}"
+ )
title = result.get("title") or ""
content = result.get("content") or ""
@@ -219,7 +246,7 @@ def _make_summary_fetch_tool(
).strip()
except Exception as exc:
logger.exception("fetch_content summary LLM error")
- return f"Error summarizing {url}: {exc}"
+ return _scrub_tool_error(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
@@ -259,7 +286,10 @@ def _make_summary_fetch_tool(
raise
except Exception as exc:
logger.exception("fetch_content tool error")
- return f"Error fetching {url}: {exc}"
+ # Scrub credentials before this reaches the agent/LLM and the
+ # user-visible research output: the exception (or url) can embed
+ # a credentialed URL. Full detail stays in the server log above.
+ return _scrub_tool_error(f"Error fetching {url}: {exc}")
return fetch_content
diff --git a/tests/advanced_search_system/tools/test_fetch_modes.py b/tests/advanced_search_system/tools/test_fetch_modes.py
index 1f7ad27ffe..6e52422430 100644
--- a/tests/advanced_search_system/tools/test_fetch_modes.py
+++ b/tests/advanced_search_system/tools/test_fetch_modes.py
@@ -210,6 +210,56 @@ def test_full_mode_defaults_to_js_off_without_snapshot():
assert kwargs.get("enable_js_rendering") is False
+def test_fetch_error_scrubs_credentialed_url_from_exception():
+ """A fetch exception that embeds a credentialed URL must be scrubbed
+ before the tool return reaches the agent/LLM and the user-visible
+ research output (credential-leak follow-up to #4625). Full detail stays
+ in the server log."""
+ collector = SearchResultsCollector([])
+ tool = build_fetch_tool("full", collector)
+
+ fetcher = MagicMock()
+ fetcher.fetch.side_effect = Exception(
+ "ConnectionError for https://user:[email protected]:8080"
+ )
+ cm = MagicMock()
+ cm.__enter__.return_value = fetcher
+ cm.__exit__.return_value = False
+
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm
+ ):
+ out = tool.invoke({"url": "http://example.com/"})
+
+ assert "SUPERSECRET123" not in out # credential scrubbed
+ assert "Error fetching" in out # still a useful error for the agent
+
+
+def test_failed_fetch_scrubs_credentials_from_result_error():
+ """A non-success fetch result carries ContentFetcher's raw error string,
+ which can embed a credentialed URL. It must be scrubbed before the
+ 'Failed to fetch' tool return reaches the agent/LLM (#4633)."""
+ collector = SearchResultsCollector([])
+ tool = build_fetch_tool("full", collector)
+
+ fetcher = MagicMock()
+ fetcher.fetch.return_value = {
+ "status": "error",
+ "error": "blocked: https://user:[email protected]",
+ }
+ cm = MagicMock()
+ cm.__enter__.return_value = fetcher
+ cm.__exit__.return_value = False
+
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm
+ ):
+ out = tool.invoke({"url": "http://example.com/"})
+
+ assert "SUPERSECRET999" not in out # credential scrubbed
+ assert "Failed to fetch" in out # still a useful error for the agent
+
+
def test_summary_mode_forwards_js_setting():
"""Summary-mode tool also forwards the JS toggle from the snapshot."""
collector = SearchResultsCollector([])
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index d0fbd74108..d0811230f3 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -244,6 +244,39 @@ class TestLangGraphAgentStrategy:
assert hasattr(strategy, "analyze_topic")
assert hasattr(strategy, "collector")
+ def test_format_agent_error_scrubs_credentials(self):
+ """_format_agent_error is rendered to the user, so it must scrub
+ credentials from the exception text — while keeping the
+ 'Agent error: <Type>:' prefix the ErrorReportGenerator pattern map
+ matches on (credential-leak follow-up to #4625)."""
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ LangGraphAgentStrategy,
+ )
+
+ exc = RuntimeError(
+ "LLM call failed: https://api.example.com/v1?api_key=SECRETKEY123"
+ )
+ out = LangGraphAgentStrategy._format_agent_error(exc)
+
+ assert "SECRETKEY123" not in out # credential scrubbed
+ assert out.startswith("Agent error: RuntimeError:") # type prefix kept
+
+ def test_format_agent_error_keeps_categorizable_token_past_200_chars(self):
+ """The larger (500) cap for tool/agent errors keeps the categorizable
+ signal that can sit deep in a long exception message — the 200-char
+ HTTP-client default would truncate it and degrade ErrorReporter
+ categorization to 'unknown' (#4633)."""
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ LangGraphAgentStrategy,
+ )
+
+ exc = RuntimeError(("x" * 230) + " Connection refused")
+ out = LangGraphAgentStrategy._format_agent_error(exc)
+
+ # The token sits past char 200; it survives the 500 cap (a 200 cap
+ # would drop it).
+ assert "Connection refused" in out
+
def test_default_params(self):
strategy = self._make_strategy()
assert strategy.max_iterations == 50