~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(egress): include URL on "policy denied URL fetch" WARNING and suppress misleading MILESTONE for fetch_content denials (#5279)
Sa141a3b9f3a0
diff --git a/changelog.d/5278.bugfix.md b/changelog.d/5278.bugfix.mdnew file mode 100644index 0000000000..d3f27c7603--- /dev/null+++ b/changelog.d/5278.bugfix.md@@ -0,0 +1 @@+langgraph-agent `fetch_content` no longer mis-renders egress denials as `📄 From the page: Cannot fetch …` in the chat panel — denial and error strings from the tool are now logged as warnings only, and the MILESTONE channel is reserved for successful reads. The `policy denied URL fetch` WARNING emitted by `security/egress/policy.py` now inlines the offending URL (redacted to `scheme://host:port`) into its message body — alongside `reason`, `scope`, `count`, and `counted` — so a triager reading the persisted `research_logs_<uuid>.jsonl` can correlate each denial with the URL the agent attempted. With the chat-panel MILESTONE suppression, this WARNING is now the only persistent record of a denial — if the URL were missing here, there would be nothing else to read it from. The message body is what `database_sink` writes to `app_logs.message`, so this is the only layer at which the URL actually reaches the JSONL.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.pyindex aaadf8cdc1..1de8e27f3d 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@@ -1166,6 +1166,27 @@ class LangGraphAgentStrategy(BaseSearchStrategy):tool_name = getattr(msg, "name", "tool")display_name = self._display_tool_name(tool_name)raw = str(getattr(msg, "content", ""))++ # Suppress the misleading "📄 From the page: Cannot fetch <url>: ..."+ # pattern for ``fetch_content`` denial/error observations. The fetch+ # tool returns a "Cannot fetch …: blocked by egress policy (…)"+ # string when the egress gate refuses the URL (policy.py:_record_denial+ # already emits a WARNING with the same URL), and the chat panel+ # would re-emit that string under the "From the page:" label — which+ # reads to the user as if the page was read and its content is a+ # denial. The WARNING in the persisted log is the audit signal;+ # suppressing the MILESTONE here keeps the chat UI truthful. The+ # caller skips the _update_progress call when this returns None.+ # Gated on the tool name (not the content prefix alone) so a+ # non-fetch tool whose result happens to start with "Cannot fetch "+ # still surfaces normally — the suppression is about the+ # ``fetch_content`` denial framing, not a generic string-substring+ # match.+ if tool_name == "fetch_content" and (+ raw.startswith("Cannot fetch ") or raw.startswith("Error fetching ")+ ):+ return None+preview = raw[:_OBSERVATION_PREVIEW_MAX_CHARS].replace("\n", " ")# Keep the stable tool id in metadata; the friendly label# already lives in the message.@@ -1565,7 +1586,16 @@ class LangGraphAgentStrategy(BaseSearchStrategy):elif "tools" in chunk:msgs = chunk["tools"].get("messages", [])for msg in msgs:- obs_message, obs_metadata = self._observation_event(msg)+ obs_event = self._observation_event(msg)+ # _observation_event returns None when the tool+ # result is a denial/error string ("Cannot fetch …"+ # / "Error fetching …"); the WARNING in+ # policy.py is the audit signal and the chat+ # milestone would otherwise read as a successful+ # page read whose content is a denial.+ if obs_event is None:+ continue+ obs_message, obs_metadata = obs_eventself._update_progress(obs_message,min(diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.pyindex 404f9d2590..6a7f60c3d8 100644--- a/src/local_deep_research/security/egress/policy.py+++ b/src/local_deep_research/security/egress/policy.py@@ -950,19 +950,19 @@ def evaluate_url(url: str, ctx: EgressContext) -> Decision:return Decision(False, "denial_quota_exceeded")if not isinstance(url, str) or not url:- return _record_denial(ctx, "url_malformed")+ return _record_denial(ctx, url, "url_malformed")try:parsed = urlsplit(url)except Exception:- return _record_denial(ctx, "url_malformed")+ return _record_denial(ctx, url, "url_malformed")if parsed.scheme.lower() in _DANGEROUS_SCHEMES:- return _record_denial(ctx, "dangerous_scheme")+ return _record_denial(ctx, url, "dangerous_scheme")if parsed.scheme.lower() not in ("http", "https"):- return _record_denial(ctx, "unsupported_scheme")+ return _record_denial(ctx, url, "unsupported_scheme")if not parsed.hostname:- return _record_denial(ctx, "no_hostname")+ return _record_denial(ctx, url, "no_hostname")# HTTP client libraries (requests/urllib3) percent-DECODE the host# in the netloc before the socket connect, but urlsplit().hostname@@ -995,7 +995,7 @@ def evaluate_url(url: str, ctx: EgressContext) -> Decision:if is_ip_blocked(host, allow_localhost=True, allow_private_ips=True):- return _record_denial(ctx, "blocked_metadata_ip")+ return _record_denial(ctx, url, "blocked_metadata_ip")# is_ip_blocked only parses canonical IP notation, so an# alternate-encoded metadata literal (octal/hex/integer) slips# through above. Normalize it to the dotted-quad the resolver@@ -1011,14 +1011,14 @@ def evaluate_url(url: str, ctx: EgressContext) -> Decision:alt, allow_localhost=True, allow_private_ips=True)):- return _record_denial(ctx, "blocked_metadata_ip")+ return _record_denial(ctx, url, "blocked_metadata_ip")# Metadata endpoints reachable by hostname (GCP) — is_ip_blocked# can't see these because they aren't IP literals. Block by name so# the invariant holds under PUBLIC_ONLY/BOTH too (the SSRF validator# backstops the actual fetch, but evaluate_url's own guarantee must# not depend on it).if host.lower() in _METADATA_HOSTNAMES:- return _record_denial(ctx, "blocked_metadata_ip")+ return _record_denial(ctx, url, "blocked_metadata_ip")except Exception: # noqa: silent-exception - defensive, see below# Non-IP host or helper error: fall through to normal# classification (DNS path has its own handling).@@ -1040,32 +1040,50 @@ def evaluate_url(url: str, ctx: EgressContext) -> Decision:# bigger risk than false-positives on DOI redirects.if classification is True:return Decision(True, "allowed_private_host_under_strict")- return _record_denial(ctx, "strict_public_host")+ return _record_denial(ctx, url, "strict_public_host")if ctx.scope == EgressScope.PUBLIC_ONLY:if classification is False:return Decision(True, "allowed_public_host")- return _record_denial(ctx, "scope_mismatch_public_only")+ return _record_denial(ctx, url, "scope_mismatch_public_only")if ctx.scope == EgressScope.PRIVATE_ONLY:if classification is True:return Decision(True, "allowed_private_host")- return _record_denial(ctx, "scope_mismatch_private_only")+ return _record_denial(ctx, url, "scope_mismatch_private_only")# BOTH: any classified host is fine.if classification is None:- return _record_denial(ctx, "host_unclassified")+ return _record_denial(ctx, url, "host_unclassified")return Decision(True, "allowed_both_scope")except Exception: # pragma: no cover - defensivelogger.bind(policy_audit=True).exception("evaluate_url internal error")return Decision(False, "internal_error")-def _record_denial(ctx: EgressContext, reason: str) -> Decision:+def _record_denial(ctx: EgressContext, url: object, reason: str) -> Decision:"""Increment the denial counter inside the frozen context's mutable dictand emit a redacted audit log line. Lock guards the read-modify-writeagainst concurrent subagent threads.++ The offending URL is inlined into the WARNING message body rather than+ bound as a kwarg, matching the rest of the app's log convention (see+ ``[FILE_INTEGRITY]`` audit lines, successful-fetch ``[N] Title: ... URL: ...``+ observations). The ``database_sink`` persists ``record["message"]``+ verbatim into ``app_logs.message`` — and that is what the JSONL exporter+ emits — so this is the only layer at which a triager can read the URL.++ Note: after ``langgraph_agent_strategy._observation_event`` was taught+ to return ``None`` for ``fetch_content`` denial/error strings, the chat+ panel no longer emits a ``📄 From the page: Cannot fetch …`` MILESTONE+ for denials. The persisted WARNING is therefore the **only** record of+ the denial in the research log — if the URL is missing from this+ message body, there is nothing else to cross-reference. The URL still+ passes through ``redact_url_for_log`` so tokens, query strings, and+ paths never reach the audit log."""+ from ..ssrf_validator import redact_url_for_log+counts_toward_quota = reason not in _NON_QUOTA_DENIAL_REASONS# Increment the per-RUN counter (the run's active context, shared across# every call-site context) rather than this one context's — see _quota_ctx.@@ -1074,12 +1092,30 @@ def _record_denial(ctx: EgressContext, reason: str) -> Decision:if counts_toward_quota:qctx._fetch_denial_count["count"] += 1count = qctx._fetch_denial_count["count"]+ # ``url_malformed`` and the ``urlsplit``-except path can hand us a+ # non-string (None, bytes, int) — urllib3.parse_url raises TypeError on+ # int/bytes and returns a Url with scheme=None for None, neither of which+ # we want on the audit line. Coerce to a stable, type-tagged placeholder+ # so the WARNING still carries a useful field even when the URL itself+ # was unparseable. The denial decision is unaffected — we already+ # decided to refuse.+ if not isinstance(url, str):+ audit_url = f"<unparseable:{type(url).__name__}>"+ else:+ audit_url = redact_url_for_log(url)+ # The URL / reason / scope / count / counted must ride on the message+ # body, NOT as logger.warning kwargs. database_sink builds log_entry+ # only from record["message"] and the few fixed fields it copies+ # manually (module/function/line/level/timestamp/research_id) — it+ # never reads record["extra"], so any kwarg binding here is dropped+ # at the persistence boundary and never reaches app_logs.message+ # (or the JSONL exporter that reads it). The pinned+ # ``test_record_denial_warning_message_carries_redacted_url`` and+ # ``test_record_denial_warning_message_reaches_persisted_log`` tests+ # assert this invariant.logger.bind(policy_audit=True).warning(- "policy denied URL fetch",- reason=reason,- scope=ctx.scope.value,- denial_count=count,- counted=counts_toward_quota,+ f"policy denied URL fetch url={audit_url} reason={reason} "+ f"scope={ctx.scope.value} count={count} counted={counts_toward_quota}")return Decision(False, reason)diff --git a/tests/security/test_egress_url_edgecases_followup.py b/tests/security/test_egress_url_edgecases_followup.pyindex ef6e113d98..7bd09de49c 100644--- a/tests/security/test_egress_url_edgecases_followup.py+++ b/tests/security/test_egress_url_edgecases_followup.py@@ -310,3 +310,211 @@ def test_quota_cap_precedes_metadata_check():decision = evaluate_url("http://169.254.169.254/", ctx)assert decision.allowed is Falseassert decision.reason == "denial_quota_exceeded"+++# ---------------------------------------------------------------------------+# Pin the audit WARNING carries the URL — a triager reading the persisted+# log must be able to correlate each denial with the URL the agent attempted+# without cross-referencing the adjacent MILESTONE the tool emits to the+# chat panel. Both fields were added when the duplicate-logging/landing-page+# UX bug was fixed (denial MILESTONE is suppressed in+# ``langgraph_agent_strategy._observation_event``; the URL moves to the+# WARNING here).+# ---------------------------------------------------------------------------+++class TestDenialLogCarriesUrl:+ """``policy.py:_record_denial`` must put the offending URL on the WARNING+ message body. The whole audit signal rides on the persisted+ ``app_logs.message`` string (and therefore the JSONL exporter), so any+ structured kwarg binding is dropped at ``database_sink`` — the only way+ the URL reaches a triager is as part of the message.++ Pin the contract via signature inspection so a future refactor that+ drops the ``url`` parameter is caught immediately. The actual+ message-body assertion is in the behavioural tests below. End-to-end+ binding is covered by the existing ``evaluate_url`` denials in this+ file: those exercise every ``_record_denial`` call site, and the+ WARNING is emitted unconditionally inside the helper.+ """++ def test_record_denial_signature_carries_url(self):+ import inspect++ from local_deep_research.security.egress import policy as policy_mod++ sig = inspect.signature(policy_mod._record_denial)+ params = list(sig.parameters)+ assert "url" in params, (+ "_record_denial must accept url= so the WARNING carries it"+ )+ # ctx, url, reason — in that order, matching the body of evaluate_url.+ assert params[:3] == ["ctx", "url", "reason"]++ def test_record_denial_inlines_audit_url_in_warning_message(self):+ """Read the source of ``_record_denial`` to confirm the WARNING+ message body contains the inlined ``url=audit_url`` substring. The+ signature check above proves the argument is accepted; this proves+ the body actually interpolates it into the warning message — which+ is what ``database_sink`` persists into ``app_logs.message`` and+ what the JSONL exporter ships to the triager. Pinned on the LOCAL+ name (``audit_url``) so a refactor that swaps the redacted form for+ a leaky raw-URL binding is caught immediately.+ """+ import inspect++ from local_deep_research.security.egress import policy as policy_mod++ src = inspect.getsource(policy_mod._record_denial)+ assert "url={audit_url}" in src, (+ "_record_denial must inline url={audit_url} (the redacted form) "+ "into the logger.warning message body"+ )++ def test_record_denial_warning_message_carries_redacted_url(self):+ """Behavioral pin: the WARNING message body carries the REDACTED+ URL (``scheme://host[:port]``), not the raw URL. The earlier+ ``inspect.getsource`` pin checks the inlining site; this one+ exercises the actual call so a refactor that drops the redactor+ (or pipes the raw URL through) is caught immediately.++ Uses a mock on the module logger rather than a loguru sink: the+ package disables loguru under ``local_deep_research`` by default+ (``__init__.py``), so sink-based capture is brittle without the+ full ``loguru_caplog`` fixture plumbing.+ """+ from unittest.mock import MagicMock++ from local_deep_research.security.egress import policy as policy_mod++ bound = MagicMock()+ with patch.object(policy_mod, "logger") as mock_logger:+ mock_logger.bind.return_value = bound+ decision = policy_mod._record_denial(+ make_ctx(scope=EgressScope.STRICT),+ "https://user:[email protected]/v1/keys?token=abc#frag",+ "strict_public_host",+ )++ assert decision.allowed is False+ mock_logger.bind.assert_called_once_with(policy_audit=True)+ bound.warning.assert_called_once()+ call_args, call_kwargs = bound.warning.call_args+ assert call_kwargs == {}, (+ f"_record_denial must call logger.warning with only a positional "+ f"message (no kwargs), so the URL survives database_sink. "+ f"Got kwargs={call_kwargs!r}"+ )+ assert len(call_args) == 1, (+ f"_record_denial must call logger.warning with exactly one "+ f"positional arg (the inlined message). Got {call_args!r}"+ )+ message = call_args[0]+ # Redacted form drops userinfo, path, query, fragment.+ assert "url=https://api.example.com" in message, (+ f"WARNING message did not carry redacted url: {message!r}"+ )+ assert "secret" not in message+ assert "token=abc" not in message+ assert "reason=strict_public_host" in message+ assert "scope=strict" in message+ assert "count=1" in message+ assert "counted=True" in message++ def test_record_denial_warning_message_reaches_persisted_log(self):+ """End-to-end: drive ``_record_denial`` for real and confirm the+ URL survives the path that produces ``research_logs_*.jsonl``:+ the WARNING message is what ``database_sink`` writes to+ ``app_logs.message``, so a triager reading the JSONL sees the URL.++ Previous fixes passed the URL as a ``logger.warning(..., url=...)``+ kwarg, which is dropped by ``database_sink`` because it does not+ consult ``record['extra']`` — that was the silent gap behind #5278.+ Inlining the URL into the message body is what makes the URL+ actually reach the persisted log; this test pins that contract.+ """+ from unittest.mock import MagicMock++ from local_deep_research.security.egress import policy as policy_mod++ bound = MagicMock()+ with patch.object(policy_mod, "logger") as mock_logger:+ mock_logger.bind.return_value = bound+ policy_mod._record_denial(+ make_ctx(scope=EgressScope.STRICT),+ "https://southasiascholaractivistcollective.org/reporting-guide-hindutva/",+ "scope_mismatch_private_only",+ )++ message = bound.warning.call_args[0][0]+ assert (+ "url=https://southasiascholaractivistcollective.org" in message+ ), (+ "Inlined URL must reach the message body that database_sink "+ "persists into app_logs.message (and the JSONL exporter "+ "emits). Got: " + repr(message)+ )++ @pytest.mark.parametrize(+ "bad_url",+ [+ None,+ 12345,+ b"http://example.com",+ "",+ ],+ )+ def test_url_malformed_logs_unparseable_placeholder(self, bad_url):+ """``_record_denial`` must not blow up on non-str / empty ``url`` —+ the ``url_malformed`` path of ``evaluate_url`` (and the+ ``urlsplit``-except path) can hand us ``None``, ``bytes``, ``int``,+ or ``""``. ``urllib3.parse_url`` raises TypeError on int/bytes and+ returns a Url with scheme=None for None/"" — neither produces a+ useful audit line. ``_record_denial`` must coerce to a stable+ type-tagged placeholder so the WARNING still carries a useful+ ``url=`` fragment in the message body and the denial decision is+ unaffected.+ """+ from unittest.mock import MagicMock++ from local_deep_research.security.egress import policy as policy_mod++ bound = MagicMock()+ with patch.object(policy_mod, "logger") as mock_logger:+ mock_logger.bind.return_value = bound+ decision = policy_mod._record_denial(+ make_ctx(scope=EgressScope.PUBLIC_ONLY),+ bad_url,+ "url_malformed",+ )++ assert decision.allowed is False+ assert decision.reason == "url_malformed"+ bound.warning.assert_called_once()+ message = bound.warning.call_args[0][0]+ # Non-str inputs (None, int, bytes) get a type-tagged placeholder;+ # empty string is still a str — the redactor's empty parse path+ # resolves to "?://<no-host>".+ if isinstance(bad_url, str):+ assert "url=?://<no-host>" in message, (+ f"empty-string url did not produce a stable placeholder: "+ f"{message!r}"+ )+ else:+ expected = f"<unparseable:{type(bad_url).__name__}>"+ assert f"url={expected}" in message, (+ f"non-str url {bad_url!r} did not produce a stable "+ f"placeholder: {message!r}"+ )++ def test_evaluate_url_with_non_str_url_does_not_raise(self):+ """End-to-end: ``evaluate_url`` accepts the same non-str inputs the+ audit code is hardened against; the denial decision is unaffected+ and the WARNING is emitted without an exception.+ """+ for bad in (None, 12345, b"http://example.com", ""):+ decision = evaluate_url(+ bad, make_ctx(scope=EgressScope.PUBLIC_ONLY)+ )+ assert decision.allowed is False+ assert decision.reason == "url_malformed"diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.pyindex a8c11107f3..f220288939 100644--- a/tests/strategies/test_langgraph_agent_strategy.py+++ b/tests/strategies/test_langgraph_agent_strategy.py@@ -669,6 +669,81 @@ class TestObservationEvent:assert metadata["content"] == content+ def test_fetch_content_denial_returns_none(self):+ """``_observation_event`` returns ``None`` when the tool result is a+ ``fetch_content`` denial or error string. The caller skips the+ MILESTONE in that case (the WARNING in ``policy.py:_record_denial``+ is the audit signal). Returning a tuple here would render+ ``📄 From the page: Cannot fetch …`` in the chat panel — a framing+ that reads as if the page was read.+ """+ strategy = self._make_strategy()+ denial = (+ "Cannot fetch https://example.com/page: blocked by egress "+ "policy (scope_mismatch_private_only). In this run only …"+ )+ assert (+ strategy._observation_event(+ self._msg(name="fetch_content", content=denial)+ )+ is None+ )++ error = (+ "Error fetching https://example.com/page: ConnectionError('boom')"+ )+ assert (+ strategy._observation_event(+ self._msg(name="fetch_content", content=error)+ )+ is None+ )++ def test_successful_fetch_still_emits_milestone(self):+ """A successful ``fetch_content`` observation (the tool returns a+ ``[N] Title: …\\nURL: …`` payload) must still produce a milestone —+ the suppression above is denial-only.+ """+ strategy = self._make_strategy()+ content = (+ "[1] Title: Foo\nURL: https://example.com/page\n\nSummary text"+ )+ message, metadata = strategy._observation_event(+ self._msg(name="fetch_content", content=content)+ )++ assert message.startswith("📄 From the page: ")+ assert metadata["phase"] == "observation"+ assert metadata["tool"] == "fetch_content"+ # The URL is part of the flattened preview — covered by the existing+ # test_message_is_flattened_150_char_preview contract for general+ # observations, so just assert presence here.+ assert "https://example.com/page" in message++ @pytest.mark.parametrize(+ "tool_name",+ ["web_search", "research_subtopic", "arxiv", "synthetic_tool"],+ )+ def test_non_fetch_tool_denial_prefix_is_not_suppressed(self, tool_name):+ """Suppression is gated on ``tool_name == "fetch_content"`` — a+ non-fetch tool whose result happens to start with ``Cannot fetch``+ or ``Error fetching`` (e.g. an engine returning a denial string)+ must still surface as a MILESTONE. The earlier string-prefix-only+ match would silently drop legitimate observations from other+ tools whose content happens to begin with those words.+ """+ strategy = self._make_strategy()+ content = "Cannot fetch results: upstream returned 503 after retries"+ message, metadata = strategy._observation_event(+ self._msg(name=tool_name, content=content)+ )++ assert message is not None+ assert message.startswith("📄 From ")+ assert "Cannot fetch results" in message+ assert metadata["phase"] == "observation"+ assert metadata["tool"] == tool_name+# ---------------------------------------------------------------------------# Step heartbeat (full tool listing)