fix(web_fetch): validate URLs before calling hosted readers (#8447)

* fix(web_fetch): validate URLs before calling hosted readers

* fix(web_fetch): apply the URL check to all hosted readers

* fix(web_fetch): preserve bracketed query parameters
This commit is contained in:
Nan Gao 2026-11-21 11:41:57 +08:00 committed by GitHub
parent b41bd8b2ec
commit 40ef4f6ac1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 346 additions and 31 deletions

View File

@ -1021,6 +1021,17 @@ empty or omitted `include_domains`. These filters compose with `max_results`
and the model's optional `time_range`. The model-visible arguments remain `query`
and `time_range`; the filters do not apply to `web_fetch` or other search providers.
#### Hosted reader URLs
GroundRoute, InfoQuest, Jina, Sofya, SpecStream, Tavily, Unbrowse and the
official Exa API accept absolute HTTP(S) URLs for `web_fetch`. The tool checks
the URL locally before contacting the reader.
Malformed URLs, embedded user credentials, local hostnames such as `localhost`,
known metadata hosts and non-public IP literals return a tool error.
The reader receives an accepted URL exactly as supplied, including encoded paths
and repeated query parameters such as `tag[]=api&tag[]=guides`. The reader
resolves the hostname in its own network.
#### Jina fetch retries
Jina's `web_fetch` keeps one attempt by default. Configure retries on its existing
@ -1416,7 +1427,7 @@ DEER_FLOW_RUN_LIVE_TESTS=1 uv run pytest tests/test_deepseek_search_live.py -q
**Built-in Tools**:
- `web_search` - Search the web (DuckDuckGo, Tavily, Brave, Serper, Serply, Exa, InfoQuest, Tencent Cloud WSA, DeepSeek, Firecrawl, fastCRW, GroundRoute, Sofya, SpecStream, You.com)
- `web_fetch` - Fetch web pages (Jina AI, Crawl4AI, Exa, InfoQuest, Firecrawl, fastCRW, GroundRoute, Browserless, Sofya, SpecStream, Unbrowse)
- `web_fetch` - Fetch web pages (Jina AI, Crawl4AI, Exa, InfoQuest, Firecrawl, fastCRW, GroundRoute, Browserless, Sofya, SpecStream, Tavily, Unbrowse)
- `web_capture` - Capture rendered webpage screenshots as artifacts (Browserless)
- `image_search` - Search for reference images (DuckDuckGo, InfoQuest, Serper, Brave)
- `ls` - List directory contents

View File

@ -7,7 +7,7 @@ from exa_py import Exa
from langchain.tools import tool
from deerflow.community.provider_credentials import resolve_api_key
from deerflow.community.url_safety import safe_public_result_url, validate_delegated_backend_url
from deerflow.community.url_safety import safe_public_result_url, validate_delegated_backend_url, validate_hosted_fetch_url
from deerflow.config import get_app_config
logger = logging.getLogger(__name__)
@ -82,6 +82,13 @@ def _get_exa_client(tool_name: str = "web_search") -> Exa:
return _build_exa_client(extra, _resolve_base_url(extra))
def _uses_hosted_exa(base_url: str | None) -> bool:
if base_url is None:
return True
endpoint = urlparse(base_url)
return endpoint.scheme == "https" and (endpoint.hostname or "").removesuffix(".") == "api.exa.ai" and endpoint.port in (None, 443)
def _build_exa_client(extra: dict, base_url: str | None) -> Exa:
api_key = resolve_api_key(extra.get("api_key")) or resolve_api_key(os.getenv("EXA_API_KEY"))
# The SDK re-reads EXA_API_KEY unstripped when api_key is None and sends "" as
@ -152,6 +159,10 @@ def web_fetch_tool(url: str) -> str:
config = get_app_config().get_tool_config("web_fetch")
extra = config.model_extra if config is not None else {}
base_url = _resolve_base_url(extra)
if _uses_hosted_exa(base_url):
target_error = validate_hosted_fetch_url(url)
if target_error:
return target_error
if base_url:
# A custom backend fetches the URL in its own network, like other delegated fetch services.
backend_error = validate_delegated_backend_url(

View File

@ -25,7 +25,7 @@ import httpx
from langchain.tools import tool
from deerflow.community.provider_credentials import resolve_api_key
from deerflow.community.url_safety import safe_public_result_url
from deerflow.community.url_safety import safe_public_result_url, validate_hosted_fetch_url
from deerflow.config import get_app_config
logger = logging.getLogger(__name__)
@ -183,6 +183,9 @@ async def web_fetch_tool(url: str) -> str:
Args:
url: The URL to fetch the contents of.
"""
target_error = validate_hosted_fetch_url(url)
if target_error:
return target_error
api_key, _ = await asyncio.to_thread(_resolve_tool_settings, "web_fetch")
if not api_key:
return _missing_key_error("web_fetch", url=url)

View File

@ -3,6 +3,7 @@ import logging
from langchain.tools import tool
from deerflow.community.url_safety import validate_hosted_fetch_url
from deerflow.config import get_app_config
from deerflow.utils.readability import ReadabilityExtractor
@ -112,6 +113,10 @@ async def web_fetch_tool(url: str) -> str:
Args:
url: The URL to fetch the contents of.
"""
url_error = validate_hosted_fetch_url(url)
if url_error:
return url_error
client = await asyncio.to_thread(_get_infoquest_client)
result = await client.fetch(url)
if result.startswith("Error: "):

View File

@ -3,6 +3,7 @@ import asyncio
from langchain.tools import tool
from deerflow.community.jina_ai.jina_client import JinaClient
from deerflow.community.url_safety import validate_hosted_fetch_url
from deerflow.config import get_app_config
from deerflow.utils.readability import ReadabilityExtractor
@ -52,6 +53,10 @@ async def web_fetch_tool(url: str) -> str:
Args:
url: The URL to fetch the contents of.
"""
url_error = validate_hosted_fetch_url(url)
if url_error:
return url_error
jina_client = JinaClient()
timeout = 10
proxy = None

View File

@ -15,7 +15,7 @@ from langchain.tools import tool
from deerflow.community.provider_credentials import resolve_api_key
from deerflow.community.search_time_range import SearchTimeRange
from deerflow.community.url_safety import safe_public_result_url
from deerflow.community.url_safety import safe_public_result_url, validate_hosted_fetch_url
from deerflow.config import get_app_config
logger = logging.getLogger(__name__)
@ -203,6 +203,10 @@ def web_fetch_tool(url: str) -> str:
Args:
url: The URL to fetch the contents of.
"""
url_error = validate_hosted_fetch_url(url)
if url_error:
return url_error
api_key = _get_api_key("web_fetch")
if not api_key:
return f"Error: {_missing_key_message('web_fetch')}"

View File

@ -17,7 +17,7 @@ from langchain.tools import tool
from deerflow.community.provider_credentials import resolve_api_key
from deerflow.community.search_max_results import coerce_max_results
from deerflow.community.url_safety import safe_public_result_url
from deerflow.community.url_safety import safe_public_result_url, validate_hosted_fetch_url
from deerflow.config import get_app_config
logger = logging.getLogger(__name__)
@ -163,6 +163,9 @@ def web_fetch_tool(url: str) -> str:
Args:
url: The URL to fetch the contents of.
"""
target_error = validate_hosted_fetch_url(url)
if target_error:
return target_error
api_key = _get_api_key("web_fetch")
if not api_key:
return f"Error: {_missing_key_message('web_fetch')}"

View File

@ -8,7 +8,7 @@ from tavily import AsyncTavilyClient
from deerflow.community.provider_credentials import resolve_api_key
from deerflow.community.search_time_range import SearchTimeRange
from deerflow.community.url_safety import safe_public_result_url
from deerflow.community.url_safety import safe_public_result_url, validate_hosted_fetch_url
from deerflow.config import get_app_config
from deerflow.config.tool_config import ToolConfig
from deerflow.utils.file_io import await_drained
@ -129,6 +129,9 @@ async def web_fetch_tool(url: str) -> str:
Args:
url: The URL to fetch the contents of.
"""
target_error = validate_hosted_fetch_url(url)
if target_error:
return target_error
# Config resolution stats and hashes the config files; keep it off the event loop.
client = await _open_tavily_client("web_fetch")
try:

View File

@ -18,6 +18,7 @@ import httpx
from langchain.tools import tool
from deerflow.community.provider_credentials import resolve_api_key
from deerflow.community.url_safety import validate_hosted_fetch_url
from deerflow.config import get_app_config
logger = logging.getLogger(__name__)
@ -163,6 +164,10 @@ def web_fetch_tool(url: str) -> str:
Args:
url: The URL to fetch the contents of.
"""
url_error = validate_hosted_fetch_url(url)
if url_error:
return url_error
api_key = _get_api_key("web_fetch")
if not api_key:
return f"Error: {_missing_key_message('web_fetch')}"

View File

@ -7,8 +7,11 @@ import socket
from collections.abc import Callable
from urllib.parse import ParseResult, urlparse
from pydantic import AnyHttpUrl, TypeAdapter, ValidationError
_BLOCKED_HOSTNAMES = {"localhost", "metadata.google.internal"}
_IDNA_DOT_TRANSLATION = str.maketrans("\u3002\uff0e\uff61", "...")
_HTTP_URL = TypeAdapter(AnyHttpUrl)
def safe_public_result_url(value: object) -> str:
@ -27,18 +30,43 @@ def safe_public_result_url(value: object) -> str:
return ""
if parsed.scheme not in {"http", "https"} or not parsed.netloc or not host:
return ""
return url if _is_public_url_host(host) else ""
def validate_hosted_fetch_url(url: str) -> str | None:
"""Check a hosted reader's input locally. The provider resolves the host."""
if isinstance(url, str) and ("[" in url or "]" in url):
# Strict parsing needs brackets in query parameters like tag[] escaped.
# Only this check uses the escaped form. Readers receive the original URL.
before_fragment, hash_mark, fragment = url.partition("#")
base, question_mark, query = before_fragment.partition("?")
escaped_query = query.replace("[", "%5B").replace("]", "%5D")
url = f"{base}{question_mark}{escaped_query}{hash_mark}{fragment}"
try:
parsed = _HTTP_URL.validate_python(url, strict=True)
except ValidationError:
return "Error: Expected an absolute HTTP(S) URL"
if parsed.username is not None or parsed.password is not None:
return "Error: Hosted readers require a URL without embedded credentials"
# The HTTP parser canonicalizes international names and brackets IPv6 hosts.
if not parsed.host or not _is_public_url_host(parsed.host.strip("[]")):
return "Error: Hosted readers require a public URL"
return None
def _is_public_url_host(host: str) -> bool:
# IDNA clients treat these Unicode label separators as ASCII dots. Screen
# the normalized host so an IP literal cannot masquerade as a DNS name.
host = host.translate(_IDNA_DOT_TRANSLATION).lower().rstrip(".")
if not host or host in _BLOCKED_HOSTNAMES or host.endswith(".localhost"):
return ""
return False
try:
address = ipaddress.ip_address(host)
except ValueError:
address = _decode_result_ipv4(host)
if address is None:
return url
return True
if isinstance(address, ipaddress.IPv6Address):
embedded = address.ipv4_mapped or address.sixtofour
if embedded is None and address in ipaddress.ip_network("64:ff9b::/96"):
@ -46,8 +74,8 @@ def safe_public_result_url(value: object) -> str:
if embedded is None and 1 < int(address) < 1 << 32:
embedded = ipaddress.IPv4Address(int(address) & 0xFFFFFFFF)
if embedded is not None and is_blocked_address(embedded):
return ""
return "" if is_blocked_address(address) else url
return False
return not is_blocked_address(address)
def _decode_result_ipv4(host: str) -> ipaddress.IPv4Address | None:

View File

@ -49,6 +49,7 @@ pytestmark = pytest.mark.asyncio
# A private literal target needs no DNS lookup; the backends point at the
# discard port and never receive a request because ``send`` is stubbed.
_URL = "http://127.0.0.1:9/page"
_HOSTED_URL = "https://reader.example/page"
_EXTRAS = {
"allow_private_addresses": True,
"network_isolation_confirmed": True,
@ -127,17 +128,17 @@ def _with_runtime(tool: Any, **kwargs: Any) -> Callable[[Path], Any]:
# (module, entry point, config reads per call). Browser navigation also screens
# the URL through ``validate_browser_url`` in a worker, which reads its policy.
_CASES = [
pytest.param(jina_tools, _call(jina_tools.web_fetch_tool, url=_URL), 1, id="jina_ai-web_fetch"),
pytest.param(jina_tools, _call(jina_tools.web_fetch_tool, url=_HOSTED_URL), 1, id="jina_ai-web_fetch"),
pytest.param(crawl4ai_tools, _call(crawl4ai_tools.web_fetch_tool, url=_URL), 1, id="crawl4ai-web_fetch"),
pytest.param(browserless_tools, _call(browserless_tools.web_fetch_tool, url=_URL), 1, id="browserless-web_fetch"),
pytest.param(browserless_tools, _with_runtime(browserless_tools.web_capture_tool, url=_URL), 1, id="browserless-web_capture"),
pytest.param(tavily_tools, _call(tavily_tools.web_search_tool, query="q"), 1, id="tavily-web_search"),
pytest.param(tavily_tools, _call(tavily_tools.web_fetch_tool, url=_URL), 1, id="tavily-web_fetch"),
pytest.param(tavily_tools, _call(tavily_tools.web_fetch_tool, url=_HOSTED_URL), 1, id="tavily-web_fetch"),
pytest.param(searxng_tools, _call(searxng_tools.web_search_tool, query="q"), 1, id="searxng-web_search"),
pytest.param(firecrawl_tools, _call(firecrawl_tools.web_search_tool, query="q"), 1, id="firecrawl-web_search"),
pytest.param(firecrawl_tools, _call(firecrawl_tools.web_fetch_tool, url=_URL), 1, id="firecrawl-web_fetch"),
pytest.param(infoquest_tools, _call(infoquest_tools.web_search_tool, query="q"), 1, id="infoquest-web_search"),
pytest.param(infoquest_tools, _call(infoquest_tools.web_fetch_tool, url=_URL), 1, id="infoquest-web_fetch"),
pytest.param(infoquest_tools, _call(infoquest_tools.web_fetch_tool, url=_HOSTED_URL), 1, id="infoquest-web_fetch"),
pytest.param(infoquest_tools, _call(infoquest_tools.image_search_tool, query="q"), 1, id="infoquest-image_search"),
pytest.param(jsonify_tools, _call(jsonify_tools.dataset_rows_tool, dataset="d"), 1, id="jsonify-dataset_rows"),
pytest.param(ragflow_tools, lambda _tmp_path: ragflow_tools.knowledge_search_tool.coroutine("q", runtime=None), 1, id="ragflow-knowledge_search"),

View File

@ -1,6 +1,7 @@
"""Unit tests for the Exa community tools."""
import json
import logging
from unittest.mock import MagicMock, patch
import pytest
@ -181,6 +182,37 @@ class TestWebSearchTool:
class TestWebFetchTool:
@pytest.mark.parametrize("base_url", [None, "https://api.exa.ai", "https://API.EXA.AI:443/", "https://api.exa.ai/v1"])
def test_hosted_fetch_refuses_private_target_before_delegation(self, mock_app_config, caplog, monkeypatch, base_url):
from deerflow.community.exa.tools import web_fetch_tool
mock_app_config.return_value.get_tool_config.return_value.model_extra["base_url"] = base_url
monkeypatch.delenv("EXA_BASE_URL", raising=False)
caplog.set_level(logging.DEBUG, logger="deerflow.community.exa")
marker = "private-fetch-marker"
with patch("exa_py.api.requests.post") as post, patch("socket.getaddrinfo") as lookup:
output = web_fetch_tool.invoke({"url": f"https://127.0.0.1/{marker}"})
post.assert_not_called()
lookup.assert_not_called()
assert output.startswith("Error:")
assert marker not in output and marker not in caplog.text
def test_hosted_fetch_delegates_public_target_unchanged_without_dns(self, mock_app_config, monkeypatch):
from deerflow.community.exa.tools import web_fetch_tool
target = "https://docs.example/articles%2Freport?lang=en&a=1&a=2"
monkeypatch.delenv("EXA_BASE_URL", raising=False)
with patch("exa_py.api.requests.post") as post, patch("socket.getaddrinfo") as lookup:
post.return_value.status_code = 200
post.return_value.json.return_value = {"results": [], "requestId": "example"}
output = web_fetch_tool.invoke({"url": target})
assert output == "Error: No results found"
post.assert_called_once()
assert json.loads(post.call_args.kwargs["data"])["urls"] == [target]
lookup.assert_not_called()
def test_basic_fetch(self, mock_app_config, mock_exa_client):
"""Test basic web fetch returns formatted content."""
mock_result = MagicMock()
@ -362,14 +394,14 @@ class TestBaseUrl:
assert raw not in result
mock_exa_cls.assert_not_called()
def _fetch(self, extra):
def _fetch(self, extra, *, target="https://example.com"):
patcher = _patch_tool_config(extra)
try:
with patch("deerflow.community.exa.tools.Exa") as mock_exa_cls:
mock_exa_cls.return_value.get_contents.return_value = MagicMock(results=[MagicMock(title="Page", text="Body")])
from deerflow.community.exa.tools import web_fetch_tool
result = web_fetch_tool.invoke({"url": "https://example.com"})
result = web_fetch_tool.invoke({"url": target})
return result, mock_exa_cls
finally:
patcher.stop()
@ -381,9 +413,11 @@ class TestBaseUrl:
mock_exa_cls.assert_not_called()
def test_fetch_allows_private_backend_with_isolation_confirmed(self):
result, mock_exa_cls = self._fetch({"api_key": "k", "base_url": "http://127.0.0.1:8080", "network_isolation_confirmed": "true"})
target = "https://192.0.2.7/manual"
result, mock_exa_cls = self._fetch({"api_key": "k", "base_url": "http://127.0.0.1:8080", "network_isolation_confirmed": "true"}, target=target)
assert result == "# Page\n\nBody"
mock_exa_cls.assert_called_once_with(api_key="k", base_url="http://127.0.0.1:8080")
mock_exa_cls.return_value.get_contents.assert_called_once_with([target], text={"max_characters": 4096})
def test_fetch_allows_public_backend(self):
result, mock_exa_cls = self._fetch({"api_key": "k", "base_url": "https://93.184.216.34"})

View File

@ -31,7 +31,7 @@ def _invoker(monkeypatch, tool_name):
monkeypatch.setattr(tools, "get_app_config", lambda: config)
real_client = httpx.AsyncClient
async def invoke(payload, *, status_code=200):
async def invoke(payload, *, status_code=200, url=_FETCH_URL, expected_requests=1):
requests = []
def respond(request):
@ -47,8 +47,10 @@ def _invoker(monkeypatch, tool_name):
if tool_name == "web_search":
result = await tools.web_search_tool.ainvoke({"query": _SEARCH_QUERY})
else:
result = await tools.web_fetch_tool.ainvoke({"url": _FETCH_URL})
assert len(requests) == 1
result = await tools.web_fetch_tool.ainvoke({"url": url})
for request in requests:
assert json.loads(request.content)["query"] == url
assert len(requests) == expected_requests
return result
return invoke
@ -143,10 +145,19 @@ async def test_fetch_skips_malformed_entries_and_returns_the_first_usable_result
async def test_valid_fetch_keeps_existing_response(invoke_fetch, caplog):
assert await invoke_fetch({"results": [{"title": "Page", "content": "Body text"}]}) == "# Page\n\nBody text"
target = "https://docs.example/pages%2Fsummary?ref=one&ref=two"
assert await invoke_fetch({"results": [{"title": "Page", "content": "Body text"}]}, url=target) == "# Page\n\nBody text"
assert _error_logs(caplog) == []
async def test_fetch_rejects_private_url_before_any_request(invoke_fetch, caplog):
caplog.set_level(logging.DEBUG, logger=_LOGGER_NAME)
marker = "private-fetch-marker"
result = await invoke_fetch({"results": []}, url=f"https://127.0.0.1/{marker}", expected_requests=0)
assert result.startswith("Error:")
assert marker not in result and marker not in caplog.text
@pytest.mark.parametrize(
("payload", "expected"),
[

View File

@ -49,6 +49,24 @@ def responses(monkeypatch):
assert all(client.is_closed for client in clients)
@pytest.mark.anyio
async def test_fetch_tool_screens_target_before_post(responses, monkeypatch, caplog):
queued, requests = responses
queued.append(httpx.Response(200, json={"content": _HTML}))
monkeypatch.setattr("socket.getaddrinfo", lambda *args, **kwargs: pytest.fail("Hosted fetch must leave DNS to the provider"))
caplog.set_level(logging.DEBUG, logger="deerflow.community.infoquest")
result = await tools.web_fetch_tool.ainvoke({"url": "https://infoquest-test-marker.localhost/article"})
assert requests == []
assert result.startswith("Error:")
assert "infoquest-test-marker" not in result
assert "infoquest-test-marker" not in caplog.text
url = "https://reader.example.com/articles/a%2Fb?tag[]=a%20b&view=full&tag[]=c%26d"
assert "Example article content." in await tools.web_fetch_tool.ainvoke({"url": url})
assert [json.loads(request.content)["url"] for request in requests] == [url]
@pytest.mark.anyio
@pytest.mark.parametrize("field", ["reader_result", "content"])
@pytest.mark.parametrize("value", [None, False, 0, [], {}, ["provider-payload"], {"text": "provider-payload"}])

View File

@ -2,6 +2,8 @@
import json
import logging
from functools import partial
from types import SimpleNamespace
from unittest.mock import MagicMock
import httpx
@ -296,6 +298,32 @@ async def test_crawl_no_auth_header_without_api_key(jina_client, monkeypatch):
assert "Authorization" not in captured_headers
@pytest.mark.anyio
async def test_web_fetch_screens_target_before_post(monkeypatch, caplog):
requests = []
def respond(request):
requests.append(json.loads(request.content)["url"])
return httpx.Response(200, text="<html><body><p>Public article.</p></body></html>")
client = partial(httpx.AsyncClient, transport=httpx.MockTransport(respond))
monkeypatch.setattr(jina_client_module, "httpx", SimpleNamespace(AsyncClient=client))
monkeypatch.setattr("deerflow.community.jina_ai.tools.get_app_config", lambda: SimpleNamespace(get_tool_config=lambda _: None))
monkeypatch.setattr("socket.getaddrinfo", lambda *args, **kwargs: pytest.fail("Hosted fetch must leave DNS to the provider"))
monkeypatch.setenv("JINA_API_KEY", "synthetic-test-key")
caplog.set_level(logging.DEBUG, logger="deerflow.community.jina_ai")
result = await web_fetch_tool.ainvoke({"url": "https://jina-test-marker.localhost/article"})
assert requests == []
assert result.startswith("Error:")
assert "jina-test-marker" not in result
assert "jina-test-marker" not in caplog.text
url = "https://reader.example.com/articles/a%2Fb?view=full&tag=a%20b"
assert "Public article." in await web_fetch_tool.ainvoke({"url": url})
assert requests == [url]
@pytest.mark.anyio
async def test_web_fetch_tool_returns_error_on_crawl_failure(monkeypatch):
"""Test that web_fetch_tool short-circuits and returns the error string when crawl fails."""

View File

@ -2,6 +2,8 @@
import json
import logging
from functools import partial
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import httpx
@ -500,6 +502,31 @@ class TestWebSearchTool:
class TestWebFetchTool:
def test_screens_url_before_provider_call(self, mock_config_with_key, monkeypatch, caplog):
from deerflow.community.sofya import tools
requests = []
def respond(request):
requests.append(json.loads(request.content))
return httpx.Response(200, json={"results": [{"content": "Article."}]})
client = partial(httpx.Client, transport=httpx.MockTransport(respond))
monkeypatch.setattr(tools, "httpx", SimpleNamespace(Client=client, HTTPStatusError=httpx.HTTPStatusError))
monkeypatch.setattr("socket.getaddrinfo", lambda *args, **kwargs: pytest.fail("Hosted fetch must leave DNS to the provider"))
caplog.set_level(logging.DEBUG, logger=tools.__name__)
result = tools.web_fetch_tool.invoke({"url": "https://sofya-test-marker.localhost/article"})
assert requests == []
assert result.startswith("Error:")
assert "sofya-test-marker" not in result
assert "sofya-test-marker" not in caplog.text
public_url = "https://reader.example.com:443/articles/a%2Fb?tag=a%20b"
assert "Article." in tools.web_fetch_tool.invoke({"url": public_url})
[payload] = requests
assert payload["urls"] == [public_url]
def test_returns_title_and_content(self, mock_config_with_key):
results = [{"title": "Example Page", "url": "https://example.com", "content": "# Markdown body", "success": True}]

View File

@ -2,6 +2,7 @@
import json
import logging
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import httpx
@ -260,22 +261,39 @@ class TestWebSearchTool:
class TestWebFetchTool:
def _fetch(self, data):
with patch(f"{_MODULE}.httpx.Client") as mock_client_cls:
mock_request = mock_client_cls.return_value.__enter__.return_value.request
mock_request.return_value = _make_response(data)
def _fetch(self, data, *, url="https://example.com/post"):
from deerflow.community.specstream.tools import web_fetch_tool
from deerflow.community.specstream.tools import web_fetch_tool
requests = []
return web_fetch_tool.invoke({"url": "https://example.com/post"}), mock_request
def respond(request):
requests.append(request)
return httpx.Response(200, json={"data": data})
transport = httpx.MockTransport(respond)
provider_httpx = SimpleNamespace(Client=lambda **kwargs: httpx.Client(transport=transport, **kwargs), HTTPStatusError=httpx.HTTPStatusError)
with patch(f"{_MODULE}.httpx", provider_httpx):
return web_fetch_tool.invoke({"url": url}), requests
def test_returns_title_and_content(self, mock_config_with_key):
result, mock_request = self._fetch({"results": [{"url": "https://example.com/post", "status": "ok", "title": "Example", "text": "Hello world"}]})
target = "https://docs.example/pages%2Fsummary?ref=one&ref=two"
result, requests = self._fetch({"results": [{"url": target, "status": "ok", "title": "Example", "text": "Hello world"}]}, url=target)
assert result == "# Example\n\nHello world"
assert mock_request.call_args.args == ("POST", "https://api.specstream.ai/v1/extract")
assert mock_request.call_args.kwargs["headers"]["Authorization"] == "Bearer test-specstream-key"
assert mock_request.call_args.kwargs["json"] == {"urls": ["https://example.com/post"], "format": "markdown"}
[request] = requests
assert request.method == "POST"
assert str(request.url) == "https://api.specstream.ai/v1/extract"
assert request.headers["Authorization"] == "Bearer test-specstream-key"
assert json.loads(request.content) == {"urls": [target], "format": "markdown"}
def test_fetch_rejects_private_url_before_any_request(self, mock_config_with_key, caplog):
caplog.set_level(logging.DEBUG, logger=_MODULE)
marker = "private-fetch-marker"
result, requests = self._fetch({"results": []}, url=f"https://127.0.0.1/{marker}")
assert requests == []
assert result.startswith("Error:")
assert marker not in result and marker not in caplog.text
def test_truncates_long_content(self, mock_config_with_key):
result, _ = self._fetch({"results": [{"status": "ok", "title": "T", "text": "x" * 10000}]})

View File

@ -268,3 +268,30 @@ async def test_fetch_valid_payload_keeps_existing_normalization(monkeypatch, cap
assert result == "# Report title\n\nImportant findings."
assert len(requests) == 1
assert _error_logs(caplog) == []
@pytest.mark.anyio
async def test_fetch_refuses_private_target_before_delegation(monkeypatch, caplog):
from deerflow.community.tavily.tools import web_fetch_tool
marker = "private-fetch-marker"
caplog.set_level(logging.DEBUG, logger=_LOGGER_NAME)
output, requests = await _invoke(monkeypatch, web_fetch_tool, {"url": f"https://127.0.0.1/{marker}"}, {"results": []})
assert requests == []
assert output.startswith("Error:")
assert marker not in output and marker not in caplog.text
@pytest.mark.anyio
async def test_fetch_delegates_public_target_unchanged_without_dns(monkeypatch):
from deerflow.community.tavily.tools import web_fetch_tool
lookup = MagicMock(side_effect=AssertionError("unexpected DNS lookup"))
monkeypatch.setattr("socket.getaddrinfo", lookup)
target = "https://docs.example/articles%2Freport?lang=en&a=1&a=2"
output, requests = await _invoke(monkeypatch, web_fetch_tool, {"url": target}, {"results": [{"title": "Report", "raw_content": "Body"}]})
assert output == "# Report\n\nBody"
assert [json.loads(req.content)["urls"] for req in requests] == [[target]]
lookup.assert_not_called()

View File

@ -2,6 +2,8 @@
import json
import logging
from functools import partial
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import httpx
@ -140,6 +142,31 @@ class TestMissingKeyMessage:
class TestWebFetchTool:
def test_screens_url_before_provider_call(self, mock_config_with_key, monkeypatch, caplog):
from deerflow.community.unbrowse import tools
requests = []
def respond(request):
requests.append(json.loads(request.content))
return httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {"structuredContent": {"markdown": "Article."}}})
client = partial(httpx.Client, transport=httpx.MockTransport(respond))
monkeypatch.setattr(tools, "httpx", SimpleNamespace(Client=client, HTTPStatusError=httpx.HTTPStatusError))
monkeypatch.setattr("socket.getaddrinfo", lambda *args, **kwargs: pytest.fail("Hosted fetch must leave DNS to the provider"))
caplog.set_level(logging.DEBUG, logger=tools.__name__)
result = tools.web_fetch_tool.invoke({"url": "https://unbrowse-test-marker.localhost/article"})
assert requests == []
assert result.startswith("Error:")
assert "unbrowse-test-marker" not in result
assert "unbrowse-test-marker" not in caplog.text
public_url = "https://reader.example.com:443/articles/a%2Fb?tag=a%20b"
assert "Article." in tools.web_fetch_tool.invoke({"url": public_url})
[payload] = requests
assert payload["params"]["arguments"]["url"] == public_url
def test_returns_title_and_markdown(self, mock_config_with_key):
with patch("deerflow.community.unbrowse.tools.httpx.Client") as mock_client_cls:
mock_post = mock_client_cls.return_value.__enter__.return_value.post

View File

@ -4,7 +4,53 @@ import ipaddress
import pytest
from deerflow.community.url_safety import is_blocked_address, validate_delegated_backend_url, validate_public_http_url
from deerflow.community.url_safety import is_blocked_address, validate_delegated_backend_url, validate_hosted_fetch_url, validate_public_http_url
@pytest.mark.parametrize(
"url",
[
"relative/path",
"ftp://example.com/report",
"https:///report",
"https://example.com:invalid/report",
"https://example.com:65536/report",
"https://example.com:invalid/catalog?tag[]=api",
"https://example.com/catalog[old]?tag[]=api",
"https://example.com/catalog?tag[]=bad%zz",
"https://example.com/catalog#details?tag[]=api",
"https://example.com/report\n",
"https://example.com/one\x7ftwo",
"https://reader@example.com/report",
"https://reader:password@example.com/report",
"http://localhost/",
"http://app.localhost./",
"http://metadata.google.internal/",
"http://192.168.1.1/",
"http://[::1]/",
],
)
def test_hosted_fetch_rejects_unsupported_targets(url):
error = validate_hosted_fetch_url(url)
assert error is not None
assert url not in error
@pytest.mark.parametrize(
"url",
[
"https://docs.example/report%2F2026?sig=Ab%2B0%3D",
"https://docs.example/catalog?filter[tag][]=api&filter[tag][]=guides#details",
"http://bücher.example:8080/katalog",
"https://8.8.8.8/",
"https://[2606:4700:4700::1111]/?tag[]=api",
],
)
def test_hosted_fetch_accepts_public_targets_without_dns(monkeypatch, url):
monkeypatch.setattr("socket.getaddrinfo", lambda *args: pytest.fail("hosted reader target was resolved locally"))
assert validate_hosted_fetch_url(url) is None
@pytest.mark.parametrize(