@devries-cameron20 / composio-1 / commits / ba85f4d18
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(sdk): honor Fetch redirect semantics in both SSRF guards (#4387)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4271, whose commit it carries unchanged - applies the Fetch standard's redirect method/body rules in **both** SSRF guards via `_redirect_rewrite` / `redirectRewrite`: a `303` retries as a bodiless request, a `301`/`302` does the same for a `POST`, and `307`/`308` replay both - narrows `ssrfSafeFetch` to the five statuses the Fetch standard calls a redirect, so a `304` or `305` carrying a `Location` is returned to the caller instead of followed — Python already used `_REDIRECT_STATUS_CODES` - drops `params` after the first hop in `safe_request`, since `Location` carries the query for the target it names and re-appending handed a query-string credential to a target that never asked for one - purges the union of the Fetch `request-body-header` set and the two `requests` also drops, identically on both sides - blocks the IPv6 transition ranges the TypeScript CIDR list missed — 6to4 `2002::/16`, Teredo and the rest of `2001::/23`, local-use NAT64 `64:ff9b:1::/48`, `100::/64`, `2001:db8::/32`, site-local `fec0::/10` — and the IPv4/IPv6 multicast and `192.88.99.0/24` ranges Python's `is_global` missed ## Context Both guards follow redirects by hand so every hop is revalidated against the address blocklist. That also means neither inherits the method and body rewriting `fetch` and `requests` would have done, so an upload answered with a `303` was replayed — payload and all — at a result URL that expects a GET. https://github.com/ComposioHQ/composio/pull/4271 landed that rule in Python only, which left the two SDKs disagreeing on the same wire behavior. Reviewing for that divergence surfaced the redirect-status set, the `params` replay, and the address-blocklist gaps above. `2002:7f00:1::` is 6to4 for `127.0.0.1`, and it passed the TypeScript guard as a public address. Verified with `pytest python/tests/test_url_safety.py` (56 passed) and `vitest run` in `@composio/core` (54 files, 1280 passed), plus `ruff`, `tsc --noEmit`, `oxlint` and `prettier`. Fail-before confirmed: 10 of the new TypeScript cases and 5 of the new Python cases fail against the unmodified guards. Two known gaps are deliberately left out, each deserving its own change: neither guard strips `Authorization`/`Cookie` on a cross-origin redirect, and a non-seekable Python body is re-sent exhausted on a `307` where TypeScript throws a bare `TypeError` on a consumed `ReadableStream`. https://claude.ai/code/session_01SB3ZJdvoqBcRrWb2toWVrX --------- Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>

Alberto Schiabel committed Sep 8, 2026 at 20:51 UTC ba85f4d18306e990f72af0e9ee69f88571df4e89
7 files changed +405 -8
.changeset/ssrf-redirect-semantics.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Apply the Fetch standard's redirect rules in `ssrfSafeFetch`, which following redirects manually meant `fetch` never applied: a `303` now retries as a bodiless `GET` instead of replaying an upload's method and body at a result URL, a `301`/`302` does the same for a `POST`, and `307`/`308` keep replaying both. Only `301`, `302`, `303`, `307` and `308` count as redirects to follow, so a `304` or `305` carrying a `Location` is returned to the caller rather than followed.
.changeset/ssrf-transition-ranges.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Close the IPv6 transition ranges the SSRF guard's address blocklist let through: 6to4 (`2002::/16`), Teredo and the rest of `2001::/23`, local-use NAT64 (`64:ff9b:1::/48`), `100::/64`, `2001:db8::/32` and site-local `fec0::/10` each carry or reach an arbitrary IPv4 address, so `2002:7f00:1::` was a public-looking literal for `127.0.0.1`. IPv4 multicast and the `192.88.99.0/24` 6to4 relay range are blocked too.
.github/workflows/py.test.yml
+9
@@ -246,6 +246,11 @@ jobs:
246
247 - name: Check API key
248 id: api-key
249 + env:
250 + # A pull request from a fork cannot read repository secrets, so the
251 + # key is missing for a reason no contributor can fix. Skip the way
252 + # Dependabot does rather than failing their PR.
253 + IS_FORK_PR: ${{ github.event.pull_request.head.repo.fork || false }}
254 run: |
255 if [ -z "$COMPOSIO_API_KEY" ]; then
256 echo "available=false" >> "$GITHUB_OUTPUT"
@@ -253,6 +258,10 @@ jobs:
258 echo "::notice::Skipping secret-backed Python integration tests for Dependabot; missing COMPOSIO_API_KEY."
259 exit 0
260 fi
261 + if [ "$IS_FORK_PR" = "true" ]; then
262 + echo "::notice::Skipping secret-backed Python integration tests for a pull request from a fork; repository secrets are not available to it."
263 + exit 0
264 + fi
265
266 echo "::error::COMPOSIO_API_KEY is not set"
267 exit 1
python/composio/utils/url_safety.py
+76
@@ -47,7 +47,31 @@ _CONNECT_ERRORS = (
47 urllib3.exceptions.NameResolutionError,
48 )
49
50 +# Ranges that must not be reachable from a user-supplied URL but that
51 +# ``ipaddress.is_global`` does not reject on its own, because it only asks
52 +# whether an address is private. The TypeScript guard blocks the same ones from
53 +# its explicit CIDR list.
54 +_ALSO_BLOCKED_NETWORKS = (
55 + ipaddress.ip_network("224.0.0.0/4"), # IPv4 multicast
56 + ipaddress.ip_network("192.88.99.0/24"), # 6to4 relay anycast (RFC 7526)
57 + ipaddress.ip_network("ff00::/8"), # IPv6 multicast
58 + ipaddress.ip_network("fec0::/10"), # IPv6 site-local (deprecated)
59 +)
60 +
61 _REDIRECT_STATUS_CODES = frozenset({301, 302, 303, 307, 308})
62 +# Headers that describe a request body, so they have to go when the body does.
63 +# The Fetch standard's "request-body-header name" set, plus the two `requests`
64 +# purges for the same reason (it recomputes both from the body it sends).
65 +_BODY_HEADERS = frozenset(
66 + {
67 + "content-encoding",
68 + "content-language",
69 + "content-length",
70 + "content-location",
71 + "content-type",
72 + "transfer-encoding",
73 + }
74 +)
75 _MAX_REDIRECTS = 5
76
77
@@ -68,6 +92,9 @@ def is_blocked_ip(value: str) -> bool:
92 if embedded_ipv4 is not None:
93 return is_blocked_ip(str(embedded_ipv4))
94
95 + if any(address in network for network in _ALSO_BLOCKED_NETWORKS):
96 + return True
97 +
98 return not address.is_global
99
100
@@ -143,6 +170,28 @@ def parse_content_length(value: t.Optional[str]) -> t.Optional[int]:
170 return size if size >= 0 else None
171
172
173 +def _redirect_rewrite(status_code: int, method: str) -> t.Optional[str]:
174 + """The method the hop after a redirect uses, or ``None`` to replay as-is.
175 +
176 + A returned method also means the request body goes: these are the Fetch
177 + standard's redirect rules, which the TypeScript guard applies too and which
178 + following redirects by hand means applying by hand. ``303`` points at a
179 + result URL that has no use for the original body, so every method loses it
180 + and everything but ``HEAD`` becomes a ``GET``; ``301``/``302`` do the same
181 + to a ``POST`` only; ``307``/``308`` replay both.
182 +
183 + ``requests`` would have applied its own rules in ``resolve_redirects``, and
184 + they are not quite these: it downgrades ``302`` for every non-``HEAD``
185 + method, matching what browsers did before ``307`` existed. The two SDKs
186 + agreeing is worth more than matching that legacy, so the Fetch rules win.
187 + """
188 + if status_code == 303:
189 + return "HEAD" if method == "HEAD" else "GET"
190 + if status_code in {301, 302} and method == "POST":
191 + return "GET"
192 + return None
193 +
194 +
195 def safe_request(
196 method: str,
197 url: str,
@@ -162,10 +211,17 @@ def safe_request(
211 region redirect). Call sites that require a direct URL should use
212 :func:`safe_get`, which rejects nothing but simply does not follow them.
213
214 + Following a redirect by hand also means rewriting the method and body by
215 + hand; see :func:`_redirect_rewrite` for the rules and why they are the
216 + Fetch standard's rather than the ones ``requests`` would apply.
217 +
218 :param max_redirects: Hops to follow before giving up.
219 :raises BlockedInternalUrlError: If any hop fails validation, or the
220 redirect chain is longer than ``max_redirects``.
221 """
222 + # `requests` normalizes the method on the prepared request, and the
223 + # redirect rules below compare against it, so normalize once up front.
224 + method = method.upper()
225 body = kwargs.get("data")
226 current_url = url
227
@@ -179,6 +235,26 @@ def safe_request(
235 response.close()
236 current_url = urljoin(current_url, location)
237
238 + # The next hop is whatever `Location` says, query string included, so
239 + # `params` must not be appended to it a second time — that is how
240 + # `requests` builds a redirected request, and it keeps a query-string
241 + # credential from being handed to a target that never asked for one.
242 + kwargs.pop("params", None)
243 +
244 + rewritten_method = _redirect_rewrite(response.status_code, method)
245 + if rewritten_method is not None:
246 + method = rewritten_method
247 + body = None
248 + for key in ("data", "json", "files"):
249 + kwargs.pop(key, None)
250 + if headers := kwargs.get("headers"):
251 + kwargs["headers"] = {
252 + name: value
253 + for name, value in headers.items()
254 + if name.lower() not in _BODY_HEADERS
255 + }
256 + continue
257 +
258 # `requests` rewinds the body itself when it follows a redirect; doing
259 # it manually means doing that too, or a retried upload sends nothing.
260 seek = getattr(body, "seek", None)
python/tests/test_url_safety.py
+115
@@ -4,6 +4,7 @@ from __future__ import annotations
4
5 import io
6 import socket
7 +import typing as t
8 from unittest.mock import MagicMock, call, patch
9
10 import pytest
@@ -31,6 +32,19 @@ from composio.utils.url_safety import (
32 "::169.254.169.254",
33 "64:ff9b::7f00:1",
34 "64:ff9b::a9fe:a9fe",
35 + # Ranges the TypeScript guard's CIDR list blocks, so this one does too.
36 + "224.0.0.1",
37 + "233.252.0.1",
38 + "192.88.99.1",
39 + "ff02::1",
40 + "fec0::1",
41 + # Blocked here already; asserted so the two lists stay comparable.
42 + "2001::7f00:1",
43 + "2002:7f00:1::",
44 + "2002:c0a8:1::",
45 + "64:ff9b:1::7f00:1",
46 + "100::1",
47 + "2001:db8::1",
48 ],
49 )
50 def test_blocks_non_public_addresses(address: str) -> None:
@@ -45,6 +59,11 @@ def test_blocks_non_public_addresses(address: str) -> None:
59 "2606:4700:4700::1111",
60 "::8.8.8.8",
61 "64:ff9b::8.8.8.8",
62 + # Neighbours of the blocked ranges above, so neither list overreaches.
63 + "2001:4860:4860::8888",
64 + "2a00:1450:4001:80f::200e",
65 + "223.255.255.255",
66 + "192.88.100.1",
67 ],
68 )
69 def test_allows_public_addresses(address: str) -> None:
@@ -177,6 +196,102 @@ def test_safe_request_follows_validated_redirect(mock_assert, mock_request) -> N
196 assert body.read() == b"payload"
197
198
199 +# What the hop after a redirect is expected to carry: either the original body
200 +# and the headers describing it, or neither.
201 +_REPLAYED: t.Dict[str, t.Any] = {
202 + "data": b"payload",
203 + "headers": {"Content-Type": "application/octet-stream", "X-Test": "kept"},
204 +}
205 +_BODILESS: t.Dict[str, t.Any] = {"headers": {"X-Test": "kept"}}
206 +
207 +
208 +@pytest.mark.parametrize(
209 + ("status_code", "method", "expected_method", "expected_kwargs"),
210 + [
211 + (301, "POST", "GET", _BODILESS),
212 + (301, "PUT", "PUT", _REPLAYED),
213 + (302, "POST", "GET", _BODILESS),
214 + (302, "PUT", "PUT", _REPLAYED),
215 + (303, "POST", "GET", _BODILESS),
216 + (303, "PUT", "GET", _BODILESS),
217 + (303, "HEAD", "HEAD", _BODILESS),
218 + (307, "POST", "POST", _REPLAYED),
219 + (308, "PUT", "PUT", _REPLAYED),
220 + ],
221 +)
222 +@patch("composio.utils.url_safety.requests.Session.request")
223 +@patch("composio.utils.url_safety.assert_safe_fetch_target")
224 +def test_safe_request_applies_fetch_redirect_semantics(
225 + mock_assert,
226 + mock_request,
227 + status_code: int,
228 + method: str,
229 + expected_method: str,
230 + expected_kwargs: t.Dict[str, t.Any],
231 +) -> None:
232 + """The same rules `ssrfSafeFetch` gets from `fetch` in the TypeScript SDK.
233 +
234 + A 303 sends every method to a bodiless result request, 301/302 do that to a
235 + POST only, and 307/308 replay the original method and body.
236 + """
237 + mock_request.side_effect = [
238 + _response(status_code, "https://example.com/result"),
239 + _response(200),
240 + ]
241 +
242 + safe_request(method, "https://example.com/create", **_REPLAYED)
243 +
244 + assert mock_request.call_args_list[1] == call(
245 + expected_method,
246 + "https://example.com/result",
247 + allow_redirects=False,
248 + **expected_kwargs,
249 + )
250 + assert mock_assert.call_args_list[1] == call("https://example.com/result")
251 +
252 +
253 +@patch("composio.utils.url_safety.requests.Session.request")
254 +@patch("composio.utils.url_safety.assert_safe_fetch_target")
255 +def test_safe_request_keeps_the_downgrade_across_later_hops(
256 + mock_assert, mock_request
257 +) -> None:
258 + """A hop after the 303 must not resurrect the method or the body."""
259 + mock_request.side_effect = [
260 + _response(303, "https://example.com/result"),
261 + _response(307, "https://example.com/final"),
262 + _response(200),
263 + ]
264 +
265 + safe_request("POST", "https://example.com/create", **_REPLAYED)
266 +
267 + assert mock_request.call_args_list[2] == call(
268 + "GET",
269 + "https://example.com/final",
270 + allow_redirects=False,
271 + **_BODILESS,
272 + )
273 +
274 +
275 +@patch("composio.utils.url_safety.requests.Session.request")
276 +@patch("composio.utils.url_safety.assert_safe_fetch_target")
277 +def test_safe_request_does_not_reapply_params_to_the_redirect_target(
278 + mock_assert, mock_request
279 +) -> None:
280 + """`Location` carries its own query; re-appending would leak the original."""
281 + mock_request.side_effect = [
282 + _response(307, "https://other.example.com/elsewhere"),
283 + _response(200),
284 + ]
285 +
286 + safe_request("GET", "https://example.com/download", params={"token": "secret"})
287 +
288 + assert mock_request.call_args_list[1] == call(
289 + "GET",
290 + "https://other.example.com/elsewhere",
291 + allow_redirects=False,
292 + )
293 +
294 +
295 @patch("composio.utils.url_safety.requests.Session.request")
296 @patch("composio.utils.url_safety.assert_safe_fetch_target")
297 def test_safe_request_relative_redirect_is_resolved(mock_assert, mock_request) -> None:
ts/packages/core/src/utils/ssrfGuard.node.ts
+78 -6
@@ -40,6 +40,56 @@ import {
40
41 const MAX_REDIRECTS = 5;
42
43 +/**
44 + * The Fetch standard's "redirect status" set. A 3xx outside it is not a
45 + * redirect to follow even when it carries a `location` — `304 Not Modified`
46 + * and `305 Use Proxy` most of all, and following those would replay the
47 + * request against a target the caller never asked for. The Python guard
48 + * follows the same set (`_REDIRECT_STATUS_CODES`).
49 + */
50 +const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);
51 +
52 +/**
53 + * Headers that describe a request body, so they have to go when the body does:
54 + * the Fetch standard's "request-body-header name" set, plus the two the Python
55 + * guard also drops because `requests` recomputes them from the body it sends.
56 + */
57 +const BODY_HEADERS = [
58 + 'content-encoding',
59 + 'content-language',
60 + 'content-length',
61 + 'content-location',
62 + 'content-type',
63 + 'transfer-encoding',
64 +];
65 +
66 +/**
67 + * The method the hop after a redirect uses, or `null` to replay as-is. A
68 + * returned method also means the request body goes.
69 + *
70 + * These are the Fetch standard's redirect rules, which following redirects by
71 + * hand (`redirect: 'manual'`) means `fetch` never applies for us: `303` points
72 + * at a result URL that has no use for the original body, so every method loses
73 + * it and everything but `HEAD` becomes a `GET`; `301`/`302` do the same to a
74 + * `POST` only; `307`/`308` replay both. Without this, a `303` answering an
75 + * upload would PUT the payload again at a URL that expects a GET. The Python
76 + * guard applies the same rules in `safe_request`.
77 + */
78 +const redirectRewrite = (status: number, method: string): string | null => {
79 + if (status === 303) return method === 'HEAD' ? 'HEAD' : 'GET';
80 + if ((status === 301 || status === 302) && method === 'POST') return 'GET';
81 + return null;
82 +};
83 +
84 +const applyRedirectSemantics = (init: RequestInit, status: number): RequestInit => {
85 + const method = redirectRewrite(status, (init.method ?? 'GET').toUpperCase());
86 + if (method === null) return init;
87 +
88 + const headers = new Headers(init.headers);
89 + for (const name of BODY_HEADERS) headers.delete(name);
90 + return { ...init, method, body: undefined, headers };
91 +};
92 +
93 /**
94 * Whether the runtime would route `url` through an env proxy the SDK cannot
95 * see into. Bun honors proxy environment variables automatically. Node's
@@ -77,6 +127,7 @@ const IPV4_BLOCKED_CIDRS: ReadonlyArray<readonly [string, number]> = [
127 ['172.16.0.0', 12], // private
128 ['192.0.0.0', 24], // IETF protocol assignments
129 ['192.0.2.0', 24], // TEST-NET-1
130 + ['192.88.99.0', 24], // 6to4 relay anycast (deprecated, RFC 7526)
131 ['192.168.0.0', 16], // private
132 ['198.18.0.0', 15], // benchmarking
133 ['198.51.100.0', 24], // TEST-NET-2
@@ -146,8 +197,20 @@ const isBlockedIpv6 = (ip: string): boolean => {
197 return isBlockedIpv4Long((((h[6] << 16) >>> 0) | h[7]) >>> 0);
198 }
199
200 + // Transition and tunnel ranges. Each one either carries an arbitrary IPv4
201 + // address in its low bits or is reserved, so a public-looking literal here
202 + // can still name internal space: `2002:7f00:1::` is 6to4 for `127.0.0.1`.
203 + // Blocking the whole range rather than decoding it matches the Python guard,
204 + // where `ipaddress.is_global` already rejects all of them.
205 + if (h[0] === 0x2001 && (h[1] & 0xfe00) === 0) return true; // IETF protocol assignments 2001::/23 (incl. Teredo)
206 + if (h[0] === 0x2001 && h[1] === 0x0db8) return true; // documentation 2001:db8::/32
207 + if (h[0] === 0x2002) return true; // 6to4 2002::/16
208 + if (h[0] === 0x0064 && h[1] === 0xff9b && h[2] === 0x0001) return true; // local-use NAT64 64:ff9b:1::/48
209 + if (h[0] === 0x0100 && h[1] === 0 && h[2] === 0 && h[3] === 0) return true; // discard-only 100::/64
210 +
211 if ((h[0] & 0xfe00) === 0xfc00) return true; // unique local fc00::/7
212 if ((h[0] & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
213 + if ((h[0] & 0xffc0) === 0xfec0) return true; // site-local fec0::/10 (deprecated)
214 if ((h[0] & 0xff00) === 0xff00) return true; // multicast ff00::/8
215
216 return false;
@@ -221,7 +284,8 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<string[]> =
284 * connects to the address it validated, and re-validates and re-pins every
285 * redirect hop (redirects are followed manually up to {@link MAX_REDIRECTS}).
286 * Intermediate redirect bodies are cancelled; non-redirect responses are
224 - * returned unchanged.
287 + * returned unchanged. Each hop carries the method and body the Fetch standard
288 + * says it should — see {@link applyRedirectSemantics}.
289 *
290 * A hop whose effective dispatcher is a configured route (caller-supplied
291 * `init.dispatcher`, non-stock global dispatcher, env-proxy mode) is *not*
@@ -233,6 +297,9 @@ export const ssrfSafeFetch = async (
297 maxRedirects: number = MAX_REDIRECTS
298 ): Promise<Response> => {
299 let currentUrl = rawUrl;
300 + // Rebound per hop: a redirect can drop the method and body (see
301 + // `applyRedirectSemantics`), and the following hops must send what is left.
302 + let currentInit = init;
303
304 for (let hop = 0; hop <= maxRedirects; hop++) {
305 const addresses = await assertSafeFetchTarget(currentUrl);
@@ -241,7 +308,7 @@ export const ssrfSafeFetch = async (
308 // Pinning replaces the connect target; through a configured route that
309 // would dial the validated origin instead of the route's next hop (the
310 // proxy), so those hops keep the pre-flight check only.
244 - const callerDispatcher = (init as RequestInit & { dispatcher?: unknown }).dispatcher;
311 + const callerDispatcher = (currentInit as RequestInit & { dispatcher?: unknown }).dispatcher;
312 const respectConfiguredRoute =
313 callerDispatcher !== undefined ||
314 envProxyApplies(new URL(currentUrl), isBun) ||
@@ -253,14 +320,18 @@ export const ssrfSafeFetch = async (
320 let response: Response;
321 try {
322 if (isBun && !respectConfiguredRoute) {
256 - response = await pinnedHttpFetch(currentUrl, { ...init, redirect: 'manual' }, addresses);
323 + response = await pinnedHttpFetch(
324 + currentUrl,
325 + { ...currentInit, redirect: 'manual' },
326 + addresses
327 + );
328 } else {
329 // `dispatcher` is a Node-only extension to `RequestInit`.
330 response = await fetch(
331 currentUrl,
332 (dispatcher === undefined
262 - ? { ...init, redirect: 'manual' }
263 - : { ...init, redirect: 'manual', dispatcher }) as RequestInit
333 + ? { ...currentInit, redirect: 'manual' }
334 + : { ...currentInit, redirect: 'manual', dispatcher }) as RequestInit
335 );
336 }
337 } catch (error) {
@@ -277,7 +348,7 @@ export const ssrfSafeFetch = async (
348 }
349
350 const isRedirect =
280 - response.status >= 300 && response.status < 400 && response.headers.has('location');
351 + REDIRECT_STATUS_CODES.has(response.status) && response.headers.has('location');
352 if (!isRedirect) {
353 return response;
354 }
@@ -287,6 +358,7 @@ export const ssrfSafeFetch = async (
358 await response.body?.cancel().catch(() => undefined);
359
360 currentUrl = new URL(response.headers.get('location')!, currentUrl).toString();
361 + currentInit = applyRedirectSemantics(currentInit, response.status);
362 }
363
364 throw new ComposioBlockedInternalUrlError(
ts/packages/core/test/utils/ssrfGuard.test.ts
+117 -2
@@ -43,13 +43,24 @@ describe('isBlockedIp', () => {
43 '169.254.169.254', // cloud metadata
44 '100.64.0.1', // CGNAT
45 '0.0.0.0',
46 + '224.0.0.1', // multicast
47 + '233.252.0.1', // MCAST-TEST-NET
48 + '192.88.99.1', // 6to4 relay anycast (deprecated)
49 ]) {
50 expect(isBlockedIp(ip), ip).toBe(true);
51 }
52 });
53
54 it('allows public IPv4 addresses', () => {
52 - for (const ip of ['8.8.8.8', '1.1.1.1', '93.184.216.34', '172.15.0.1', '172.32.0.1']) {
55 + for (const ip of [
56 + '8.8.8.8',
57 + '1.1.1.1',
58 + '93.184.216.34',
59 + '172.15.0.1',
60 + '172.32.0.1',
61 + '223.255.255.255',
62 + '192.88.100.1',
63 + ]) {
64 expect(isBlockedIp(ip), ip).toBe(false);
65 }
66 });
@@ -75,8 +86,35 @@ describe('isBlockedIp', () => {
86 }
87 });
88
89 + it('blocks the transition ranges that carry an arbitrary IPv4 address', () => {
90 + // A public-looking literal that still names internal space. The Python
91 + // guard rejects all of these through `ipaddress.is_global`.
92 + for (const ip of [
93 + '2002:7f00:1::', // 6to4 for 127.0.0.1
94 + '2002:c0a8:1::', // 6to4 for 192.168.0.1
95 + '2002:8080:8080::', // 6to4 for a public address — the range goes as a whole
96 + '2001::7f00:1', // Teredo 2001::/32
97 + '2001:2::1', // benchmarking
98 + '2001:10::1', // ORCHID
99 + '2001:db8::1', // documentation
100 + '64:ff9b:1::7f00:1', // local-use NAT64 for 127.0.0.1
101 + '100::1', // discard-only
102 + 'fec0::1', // site-local (deprecated)
103 + ]) {
104 + expect(isBlockedIp(ip), ip).toBe(true);
105 + }
106 + });
107 +
108 it('allows public IPv6 and public IPv4-mapped/compat addresses', () => {
79 - for (const ip of ['2606:4700:4700::1111', '::ffff:8.8.8.8', '::8.8.8.8', '::808:808']) {
109 + for (const ip of [
110 + '2606:4700:4700::1111',
111 + '::ffff:8.8.8.8',
112 + '::8.8.8.8',
113 + '::808:808',
114 + // Neighbours of the ranges above, so the list does not overreach.
115 + '2001:4860:4860::8888',
116 + '2a00:1450:4001:80f::200e',
117 + ]) {
118 expect(isBlockedIp(ip), ip).toBe(false);
119 }
120 });
@@ -338,4 +376,81 @@ describe('ssrfSafeFetch', () => {
376 // maxRedirects = 2 => hops 0, 1, 2 are fetched before the budget throws.
377 expect(cancel).toHaveBeenCalledTimes(3);
378 });
379 +
380 + // `redirect: 'manual'` means `fetch` never applies its own redirect rules, so
381 + // the guard applies them: a 303 sends every method to a bodiless result
382 + // request, 301/302 do that to a POST only, and 307/308 replay both. The
383 + // Python guard follows the same table in `safe_request`.
384 + it.each([
385 + { status: 301, method: 'POST', expected: 'GET', replays: false },
386 + { status: 301, method: 'PUT', expected: 'PUT', replays: true },
387 + { status: 302, method: 'POST', expected: 'GET', replays: false },
388 + { status: 302, method: 'PUT', expected: 'PUT', replays: true },
389 + { status: 303, method: 'POST', expected: 'GET', replays: false },
390 + { status: 303, method: 'PUT', expected: 'GET', replays: false },
391 + { status: 303, method: 'HEAD', expected: 'HEAD', replays: false },
392 + { status: 307, method: 'POST', expected: 'POST', replays: true },
393 + { status: 308, method: 'PUT', expected: 'PUT', replays: true },
394 + ])(
395 + 'sends $method as $expected after a $status',
396 + async ({ status, method, expected, replays }) => {
397 + resolvesTo('93.184.216.34');
398 + mockFetch
399 + .mockResolvedValueOnce(
400 + new Response(null, { status, headers: { location: 'https://example.com/result' } })
401 + )
402 + .mockResolvedValueOnce(new Response('data', { status: 200 }));
403 +
404 + await ssrfSafeFetch('https://example.com/create', {
405 + method,
406 + body: 'payload',
407 + headers: { 'Content-Type': 'application/octet-stream', 'X-Test': 'kept' },
408 + });
409 +
410 + const [url, init] = mockFetch.mock.calls[1];
411 + expect(url).toBe('https://example.com/result');
412 + expect(init.method).toBe(expected);
413 + expect(init.body).toBe(replays ? 'payload' : undefined);
414 + expect(new Headers(init.headers).get('content-type')).toBe(
415 + replays ? 'application/octet-stream' : null
416 + );
417 + // Only the headers that describe the body go with it.
418 + expect(new Headers(init.headers).get('x-test')).toBe('kept');
419 + }
420 + );
421 +
422 + it('keeps the downgrade across later hops', async () => {
423 + resolvesTo('93.184.216.34');
424 + mockFetch
425 + .mockResolvedValueOnce(
426 + new Response(null, { status: 303, headers: { location: 'https://example.com/result' } })
427 + )
428 + .mockResolvedValueOnce(
429 + new Response(null, { status: 307, headers: { location: 'https://example.com/final' } })
430 + )
431 + .mockResolvedValueOnce(new Response('data', { status: 200 }));
432 +
433 + await ssrfSafeFetch('https://example.com/create', { method: 'POST', body: 'payload' });
434 +
435 + // A 307 replays whatever the request is *now*, not what it started as.
436 + expect(mockFetch.mock.calls[2][1].method).toBe('GET');
437 + expect(mockFetch.mock.calls[2][1].body).toBeUndefined();
438 + });
439 +
440 + it.each([300, 304, 305, 306])(
441 + 'returns a %i without following its location',
442 + async (status: number) => {
443 + resolvesTo('93.184.216.34');
444 + // Only 301/302/303/307/308 are redirects to follow; a `location` on any
445 + // other 3xx does not make it one.
446 + mockFetch.mockResolvedValue(
447 + new Response(null, { status, headers: { location: 'https://example.com/elsewhere' } })
448 + );
449 +
450 + const res = await ssrfSafeFetch('https://example.com/file.pdf');
451 +
452 + expect(res.status).toBe(status);
453 + expect(mockFetch).toHaveBeenCalledTimes(1);
454 + }
455 + );
456 });