Skip to content

Commit 01cc02e

Browse files
authored
fix(tools): bound HTTP fetch inputs and content types (#121)
1 parent 78f0ace commit 01cc02e

2 files changed

Lines changed: 91 additions & 1 deletion

File tree

‎agentkit/tools/builtin/http_fetch.py‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import asyncio
66
import ipaddress
77
import logging
8+
import math
89
import socket
910
from urllib.parse import urljoin, urlparse
1011

@@ -16,6 +17,8 @@
1617

1718
DEFAULT_TIMEOUT_S = 10.0
1819
DEFAULT_MAX_CHARS = 100_000
20+
MAX_TIMEOUT_S = 30.0
21+
MAX_CHARS = DEFAULT_MAX_CHARS
1922
MAX_REDIRECTS = 3
2023

2124
#: Hard ceiling on bytes read from a response body. ``max_chars`` bounds what is *returned*;
@@ -180,8 +183,12 @@ async def http_fetch(
180183
Redirects are validated individually against SSRF restrictions, and the connected peer
181184
address is re-checked against the validated addresses.
182185
"""
186+
if not math.isfinite(timeout_s):
187+
raise ValueError("timeout_s must be finite")
188+
timeout_s = max(0.1, min(timeout_s, MAX_TIMEOUT_S))
189+
max_chars = max(1, min(max_chars, MAX_CHARS))
183190
current_url = url
184-
read_budget = min(MAX_RESPONSE_BYTES, max(max_chars, 1))
191+
read_budget = min(MAX_RESPONSE_BYTES, max_chars)
185192

186193
async with httpx.AsyncClient(timeout=httpx.Timeout(timeout_s)) as client:
187194
for _ in range(MAX_REDIRECTS + 1):
@@ -200,6 +207,17 @@ async def http_fetch(
200207

201208
response.raise_for_status()
202209

210+
content_type = (
211+
response.headers.get("content-type", "").split(";", 1)[0].strip().lower()
212+
)
213+
if content_type and not (
214+
content_type.startswith("text/")
215+
or content_type
216+
in {"application/json", "application/xml", "application/javascript"}
217+
or content_type.endswith(("+json", "+xml"))
218+
):
219+
raise ValueError(f"Unsupported content type: {content_type}")
220+
203221
chunks: list[bytes] = []
204222
total = 0
205223
async for chunk in response.aiter_bytes():

‎tests/unit/test_tool_http_fetch.py‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,78 @@ async def test_http_fetch_size_limit() -> None:
160160
assert len(content) == 500
161161

162162

163+
@pytest.mark.asyncio
164+
@pytest.mark.parametrize(("requested", "expected"), [(-20, 1), (10**9, 100_000)])
165+
async def test_http_fetch_clamps_max_chars(requested: int, expected: int) -> None:
166+
response = httpx.Response(
167+
200, text="x" * 100_001, request=httpx.Request("GET", "https://example.com")
168+
)
169+
with (
170+
patch("agentkit.tools.builtin.http_fetch.resolve_host_ips", return_value=[PUBLIC_IP]),
171+
_patch_stream(response),
172+
):
173+
assert len(await http_fetch("https://example.com", max_chars=requested)) == expected
174+
175+
176+
@pytest.mark.asyncio
177+
@pytest.mark.parametrize(("requested", "expected"), [(-1.0, 0.1), (10**9, 30.0)])
178+
async def test_http_fetch_clamps_timeout(requested: float, expected: float) -> None:
179+
response = httpx.Response(200, text="ok", request=httpx.Request("GET", "https://example.com"))
180+
original_client = httpx.AsyncClient
181+
with (
182+
patch("agentkit.tools.builtin.http_fetch.resolve_host_ips", return_value=[PUBLIC_IP]),
183+
_patch_stream(response),
184+
patch(
185+
"agentkit.tools.builtin.http_fetch.httpx.AsyncClient", wraps=original_client
186+
) as client,
187+
):
188+
assert await http_fetch("https://example.com", timeout_s=requested) == "ok"
189+
assert client.call_args.kwargs["timeout"].connect == expected
190+
191+
192+
@pytest.mark.asyncio
193+
@pytest.mark.parametrize("timeout", [float("nan"), float("inf"), float("-inf")])
194+
async def test_http_fetch_rejects_nonfinite_timeout(timeout: float) -> None:
195+
with pytest.raises(ValueError, match="finite"):
196+
await http_fetch("https://example.com", timeout_s=timeout)
197+
198+
199+
@pytest.mark.asyncio
200+
@pytest.mark.parametrize("content_type", ["application/octet-stream", "image/png"])
201+
async def test_http_fetch_rejects_binary_before_reading(content_type: str) -> None:
202+
response = httpx.Response(
203+
200,
204+
headers={"Content-Type": content_type},
205+
content=b"\x00\xff",
206+
request=httpx.Request("GET", "https://example.com"),
207+
)
208+
with (
209+
patch("agentkit.tools.builtin.http_fetch.resolve_host_ips", return_value=[PUBLIC_IP]),
210+
_patch_stream(response),
211+
patch.object(response, "aiter_bytes", side_effect=AssertionError("body read")),
212+
pytest.raises(ValueError, match="Unsupported content type"),
213+
):
214+
await http_fetch("https://example.com")
215+
216+
217+
@pytest.mark.asyncio
218+
@pytest.mark.parametrize(
219+
"content_type", ["application/json; charset=utf-8", "application/problem+json", "text/html"]
220+
)
221+
async def test_http_fetch_accepts_textual_media_types(content_type: str) -> None:
222+
response = httpx.Response(
223+
200,
224+
headers={"Content-Type": content_type},
225+
content=b"hello",
226+
request=httpx.Request("GET", "https://example.com"),
227+
)
228+
with (
229+
patch("agentkit.tools.builtin.http_fetch.resolve_host_ips", return_value=[PUBLIC_IP]),
230+
_patch_stream(response),
231+
):
232+
assert await http_fetch("https://example.com") == "hello"
233+
234+
163235
@pytest.mark.asyncio
164236
async def test_http_fetch_rejects_rebind_to_unvalidated_peer() -> None:
165237
"""A connection that lands off the validated addresses must be refused.

0 commit comments

Comments
 (0)