From 8a9fc779715ee501b02a3cc89e4834b7913448df Mon Sep 17 00:00:00 2001 From: He Yunhui Date: Tue, 1 Dec 2026 14:29:08 +0800 Subject: [PATCH] fix(tools): block non-global and malformed addresses in assert_public_url --- .../tools/builtin_tools/test_http_request.py | 23 +++++++++++++++++-- veadk/tools/builtin_tools/web_fetch.py | 13 ++++++++--- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/tests/tools/builtin_tools/test_http_request.py b/tests/tools/builtin_tools/test_http_request.py index c943dacdb..b6eff6a2e 100644 --- a/tests/tools/builtin_tools/test_http_request.py +++ b/tests/tools/builtin_tools/test_http_request.py @@ -165,15 +165,34 @@ def test_rejects_bad_url(url): assert "error" in result -def test_blocks_private_address(monkeypatch): +@pytest.mark.parametrize( + "addr", + [ + "127.0.0.1", + "100.96.0.96", + "100.100.100.200", + "fe80::1%eth0", + "not-an-ip", + ], +) +def test_blocks_private_and_non_global_addresses(monkeypatch, addr): monkeypatch.setattr( "veadk.tools.builtin_tools.web_fetch.socket.getaddrinfo", - lambda *args, **kwargs: _addrinfo("127.0.0.1"), + lambda *args, **kwargs: _addrinfo(addr), ) result = http_request("http://internal.example.com") assert "error" in result +def test_blocks_empty_dns_resolution(monkeypatch): + monkeypatch.setattr( + "veadk.tools.builtin_tools.web_fetch.socket.getaddrinfo", + lambda *args, **kwargs: [], + ) + result = http_request("http://empty.example.com") + assert "error" in result + + @pytest.mark.parametrize( "headers", [ diff --git a/veadk/tools/builtin_tools/web_fetch.py b/veadk/tools/builtin_tools/web_fetch.py index c6623c3ae..189996ad0 100644 --- a/veadk/tools/builtin_tools/web_fetch.py +++ b/veadk/tools/builtin_tools/web_fetch.py @@ -75,14 +75,21 @@ def _assert_public_host(host: str) -> None: infos = socket.getaddrinfo(host, None) except socket.gaierror as e: raise _WebFetchError(f"DNS resolution failed for {host!r}: {e}") + if not infos: + raise _WebFetchError(f"DNS resolution returned no addresses for {host!r}") for info in infos: addr = info[4][0] + if isinstance(addr, str) and "%" in addr: + addr = addr.split("%", 1)[0] try: ip = ipaddress.ip_address(addr) - except ValueError: - continue + except ValueError as e: + raise _WebFetchError( + f"Invalid resolved address for host {host!r}: {addr!r}" + ) from e if ( - ip.is_private + not ip.is_global + or ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved