~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(fetch): return a recoverable tool message on a per-URL egress denial (#4761)
LearningCircuitc81a56ab2cdc
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 bc79f6c731..bfae8f5965 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,7 +35,10 @@ from loguru import loggerfrom 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 local_deep_research.security import (+ redact_url_for_log,+ sanitize_error_for_client,+)from .prompts import SUMMARY_FOCUS_PROMPT, SUMMARY_FOCUS_QUERY_PROMPT@@ -108,11 +111,27 @@ def _enforce_url_policy(url: str, egress_context: Any) -> None:raise PolicyDeniedError(decision, target=url)+def _denial_reason(exc: Any) -> str:+ """Best-effort egress-denial reason code for an agent-facing message."""+ return getattr(getattr(exc, "decision", None), "reason", "policy_denied")+++# Shared instruction appended to every per-URL egress denial returned to the+# agent. Tells it WHY the fetch was refused and what to do instead, so it+# adapts (stays in-scope) rather than retrying the same out-of-scope URL.+_EGRESS_DENIAL_HINT = (+ "In this run only local collection/library documents can be fetched; "+ "skip external URLs."+)++def _make_full_fetch_tool(collector: Any,settings_snapshot: dict | None = None,egress_context: Any = None,):+ mode_label = "full"+@tooldef fetch_content(url: str) -> str:"""Download and read the full text content from a URL. Use when search snippets aren't detailed enough."""@@ -121,14 +140,13 @@ def _make_full_fetch_tool(PolicyDeniedError,)- # Policy gate: raise PolicyDeniedError so it propagates to the- # agent layer (matching the factory PEP contract). Caught- # separately from transient fetch errors so the agent can tell- # them apart.- _enforce_url_policy(url, egress_context)-enable_js = _read_js_rendering_setting(settings_snapshot)try:+ # Per-URL egress gate (pre-fetch) + ContentFetcher's own+ # per-redirect gate both raise PolicyDeniedError on an out-of-scope+ # URL. Run the gate INSIDE the try so the denial is returned as a+ # recoverable tool message (see the except below).+ _enforce_url_policy(url, egress_context)with ContentFetcher(timeout=CONTENT_FETCH_TIMEOUT,enable_js_rendering=enable_js,@@ -151,13 +169,30 @@ def _make_full_fetch_tool(f"Failed to fetch {url}: "f"{result.get('error', 'unknown error')}")- except PolicyDeniedError:- raise+ except PolicyDeniedError as exc:+ # An out-of-scope URL is a RECOVERABLE, per-call decision (the agent+ # picked one bad URL among many). Return it as a tool message — like+ # the transient-error path below — so the lead agent and pooled+ # subagents handle it identically and the agent can adapt, instead+ # of re-raising (which aborts a subagent and depends on each agent's+ # tool-error layer). The URL was already NOT fetched; the policy+ # already enforced — only the REPORTING changes, not security.+ return _scrub_tool_error(+ f"Cannot fetch {url}: blocked by egress policy "+ f"({_denial_reason(exc)}). {_EGRESS_DENIAL_HINT}"+ )except Exception as exc:- logger.exception("fetch_content tool error")- # 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.+ # Message carries the mode + a REDACTED scheme://host only (no+ # userinfo/path/query) so an operator can locate the failure without+ # the log line leaking credentials, query tokens, or page content.+ # The traceback follows the sink's diagnose setting (off by default;+ # see utilities/log_utils). The agent/user-facing return is scrubbed+ # separately below.+ logger.exception(+ "fetch_content tool error (mode={}, url={})",+ mode_label,+ redact_url_for_log(url),+ )return _scrub_tool_error(f"Error fetching {url}: {exc}")return fetch_content@@ -191,10 +226,12 @@ def _make_summary_fetch_tool(PolicyDeniedError,)- _enforce_url_policy(url, egress_context)-enable_js = _read_js_rendering_setting(settings_snapshot)try:+ # Run the per-URL egress gate INSIDE the try so an out-of-scope URL+ # is returned as a recoverable tool message (see the except below),+ # not re-raised.+ _enforce_url_policy(url, egress_context)with ContentFetcher(timeout=CONTENT_FETCH_TIMEOUT,enable_js_rendering=enable_js,@@ -245,7 +282,14 @@ def _make_summary_fetch_tool(summary_msg, "content", str(summary_msg)).strip()except Exception as exc:- logger.exception("fetch_content summary LLM error")+ # Redacted scheme://host + mode only — no page content,+ # focus, or credentials in the message. Traceback follows+ # the sink's diagnose setting (off by default).+ logger.exception(+ "fetch_content summary LLM error (mode={}, url={})",+ mode_label,+ redact_url_for_log(url),+ )return _scrub_tool_error(f"Error summarizing {url}: {exc}")# Diagnostic log: per-fetch input/output for evaluating the@@ -282,13 +326,27 @@ def _make_summary_fetch_tool(collector, url, title, summary)return f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{summary}"- except PolicyDeniedError:- raise+ except PolicyDeniedError as exc:+ # Recoverable per-URL denial — return a tool message so both the+ # lead agent and pooled subagents handle it identically and the+ # agent stays in-scope. The URL was already NOT fetched; only the+ # reporting changes, not security. (See the full-fetch variant.)+ return _scrub_tool_error(+ f"Cannot fetch {url}: blocked by egress policy "+ f"({_denial_reason(exc)}). {_EGRESS_DENIAL_HINT}"+ )except Exception as exc:- logger.exception("fetch_content tool error")- # 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.+ # Message carries the mode + a REDACTED scheme://host only (no+ # userinfo/path/query) so an operator can locate the failure without+ # the log line leaking credentials, query tokens, or page content.+ # The traceback follows the sink's diagnose setting (off by default;+ # see utilities/log_utils). The agent/user-facing return is scrubbed+ # separately below.+ logger.exception(+ "fetch_content tool error (mode={}, url={})",+ mode_label,+ redact_url_for_log(url),+ )return _scrub_tool_error(f"Error fetching {url}: {exc}")return fetch_contentdiff --git a/tests/advanced_search_system/tools/test_fetch_modes.py b/tests/advanced_search_system/tools/test_fetch_modes.pyindex 6e52422430..ebdfd8f77e 100644--- a/tests/advanced_search_system/tools/test_fetch_modes.py+++ b/tests/advanced_search_system/tools/test_fetch_modes.py@@ -280,3 +280,95 @@ def test_summary_mode_forwards_js_setting():lambda: tool.invoke({"url": "http://example.com/", "focus": "x"}))assert kwargs.get("enable_js_rendering") is False+++# ---------------------------------------------------------------------------+# Egress policy: an out-of-scope URL is a RECOVERABLE tool message, not a+# raised exception. Re-raising used to abort a pooled subagent (and depended+# on each agent's tool-error layer); returning a message lets the lead agent+# and subagents handle it identically and stay in-scope. The URL is never+# fetched either way — only the reporting changes.+# ---------------------------------------------------------------------------+++def test_full_mode_egress_denial_returns_message_not_raises():+ from local_deep_research.security.egress.policy import Decision++ collector = SearchResultsCollector([])+ tool = build_fetch_tool("full", collector, egress_context=object())++ with patch(+ "local_deep_research.security.egress.policy.evaluate_url",+ return_value=Decision(False, "scope_mismatch_private_only"),+ ):+ out = tool.invoke({"url": "https://public.example.com/x"})++ assert isinstance(out, str)+ assert "Cannot fetch" in out+ assert "scope_mismatch_private_only" in out # the reason is surfaced+ assert "skip external URLs" in out # the adapt-and-stay-local hint+ # The denied URL must never be registered as a citation.+ assert collector.results == []+++def test_summary_mode_egress_denial_returns_message_not_raises():+ from local_deep_research.security.egress.policy import Decision++ collector = SearchResultsCollector([])+ model = _model_returning("should-never-be-called")+ tool = build_fetch_tool(+ "summary_focus", collector, model=model, egress_context=object()+ )++ with patch(+ "local_deep_research.security.egress.policy.evaluate_url",+ return_value=Decision(False, "scope_mismatch_private_only"),+ ):+ out = tool.invoke({"url": "https://public.example.com/x", "focus": "y"})++ assert isinstance(out, str)+ assert "Cannot fetch" in out+ assert "scope_mismatch_private_only" in out+ # The gate fires BEFORE any fetch/summarise work.+ model.invoke.assert_not_called()+ assert collector.results == []+++def test_fetch_error_log_redacts_url_and_adds_mode():+ """The server-log line for a fetch error carries the MODE and a REDACTED+ scheme://host (no userinfo / path / query) — enough to locate the failure+ without leaking credentials, query tokens, page paths, or content. Asserted+ on the args passed to logger.exception (robust to loguru sink config)."""+ collector = SearchResultsCollector([])+ tool = build_fetch_tool("full", collector)++ fetcher = MagicMock()+ fetcher.fetch.side_effect = Exception("boom")+ cm = MagicMock()+ cm.__enter__.return_value = fetcher+ cm.__exit__.return_value = False++ url = (+ "https://user:[email protected]:8080/secretpath?token=ABCXYZ"+ )+ with patch(+ "local_deep_research.advanced_search_system.tools.fetch.logger"+ ) as mock_logger:+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher",+ return_value=cm,+ ):+ tool.invoke({"url": url})++ mock_logger.exception.assert_called_once()+ args = mock_logger.exception.call_args.args+ # args = (template, mode_label, redacted_url)+ assert "mode={}" in args[0] and "url={}" in args[0]+ assert "full" in args # the mode+ assert (+ "https://proxy.example.com:8080" in args+ ) # redacted scheme://host:port+ flat = " ".join(map(str, args))+ assert "SECRET123" not in flat # userinfo dropped+ assert "ABCXYZ" not in flat # query token dropped+ assert "secretpath" not in flat # path dropped