Skip to content

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)

Alberto Schiabelba85f4d18306
diff --git a/.changeset/ssrf-redirect-semantics.md b/.changeset/ssrf-redirect-semantics.md
new file mode 100644
index 000000000..c872cfecf
--- /dev/null
+++ b/.changeset/ssrf-redirect-semantics.md
@@ -0,0 +1,5 @@
+---
+'@composio/core': patch
+---
+
+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.
diff --git a/.changeset/ssrf-transition-ranges.md b/.changeset/ssrf-transition-ranges.md
new file mode 100644
index 000000000..89f6c7e47
--- /dev/null
+++ b/.changeset/ssrf-transition-ranges.md
@@ -0,0 +1,5 @@
+---
+'@composio/core': patch
+---
+
+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.
diff --git a/.github/workflows/py.test.yml b/.github/workflows/py.test.yml
index b1c4437c0..4ffb40084 100644
--- a/.github/workflows/py.test.yml
+++ b/.github/workflows/py.test.yml
@@ -246,6 +246,11 @@ jobs:
- name: Check API key
id: api-key
+ env:
+ # A pull request from a fork cannot read repository secrets, so the
+ # key is missing for a reason no contributor can fix. Skip the way
+ # Dependabot does rather than failing their PR.
+ IS_FORK_PR: ${{ github.event.pull_request.head.repo.fork || false }}
run: |
if [ -z "$COMPOSIO_API_KEY" ]; then
echo "available=false" >> "$GITHUB_OUTPUT"
@@ -253,6 +258,10 @@ jobs:
echo "::notice::Skipping secret-backed Python integration tests for Dependabot; missing COMPOSIO_API_KEY."
exit 0
fi
+ if [ "$IS_FORK_PR" = "true" ]; then
+ echo "::notice::Skipping secret-backed Python integration tests for a pull request from a fork; repository secrets are not available to it."
+ exit 0
+ fi
echo "::error::COMPOSIO_API_KEY is not set"
exit 1
diff --git a/python/composio/utils/url_safety.py b/python/composio/utils/url_safety.py
index af0ff979a..89608d21e 100644
--- a/python/composio/utils/url_safety.py
+++ b/python/composio/utils/url_safety.py
@@ -47,7 +47,31 @@ _CONNECT_ERRORS = (
urllib3.exceptions.NameResolutionError,
)
+# Ranges that must not be reachable from a user-supplied URL but that
+# ``ipaddress.is_global`` does not reject on its own, because it only asks
+# whether an address is private. The TypeScript guard blocks the same ones from
+# its explicit CIDR list.
+_ALSO_BLOCKED_NETWORKS = (
+ ipaddress.ip_network("224.0.0.0/4"), # IPv4 multicast
+ ipaddress.ip_network("192.88.99.0/24"), # 6to4 relay anycast (RFC 7526)
+ ipaddress.ip_network("ff00::/8"), # IPv6 multicast
+ ipaddress.ip_network("fec0::/10"), # IPv6 site-local (deprecated)
+)
+
_REDIRECT_STATUS_CODES = frozenset({301, 302, 303, 307, 308})
+# Headers that describe a request body, so they have to go when the body does.
+# The Fetch standard's "request-body-header name" set, plus the two `requests`
+# purges for the same reason (it recomputes both from the body it sends).
+_BODY_HEADERS = frozenset(
+ {
+ "content-encoding",
+ "content-language",
+ "content-length",
+ "content-location",
+ "content-type",
+ "transfer-encoding",
+ }
+)
_MAX_REDIRECTS = 5
@@ -68,6 +92,9 @@ def is_blocked_ip(value: str) -> bool:
if embedded_ipv4 is not None:
return is_blocked_ip(str(embedded_ipv4))
+ if any(address in network for network in _ALSO_BLOCKED_NETWORKS):
+ return True
+
return not address.is_global
@@ -143,6 +170,28 @@ def parse_content_length(value: t.Optional[str]) -> t.Optional[int]:
return size if size >= 0 else None
+def _redirect_rewrite(status_code: int, method: str) -> t.Optional[str]:
+ """The method the hop after a redirect uses, or ``None`` to replay as-is.
+
+ A returned method also means the request body goes: these are the Fetch
+ standard's redirect rules, which the TypeScript guard applies too and which
+ following redirects by hand means applying by hand. ``303`` points at a
+ result URL that has no use for the original body, so every method loses it
+ and everything but ``HEAD`` becomes a ``GET``; ``301``/``302`` do the same
+ to a ``POST`` only; ``307``/``308`` replay both.
+
+ ``requests`` would have applied its own rules in ``resolve_redirects``, and
+ they are not quite these: it downgrades ``302`` for every non-``HEAD``
+ method, matching what browsers did before ``307`` existed. The two SDKs
+ agreeing is worth more than matching that legacy, so the Fetch rules win.
+ """
+ if status_code == 303:
+ return "HEAD" if method == "HEAD" else "GET"
+ if status_code in {301, 302} and method == "POST":
+ return "GET"
+ return None
+
+
def safe_request(
method: str,
url: str,
@@ -162,10 +211,17 @@ def safe_request(
region redirect). Call sites that require a direct URL should use
:func:`safe_get`, which rejects nothing but simply does not follow them.
+ Following a redirect by hand also means rewriting the method and body by
+ hand; see :func:`_redirect_rewrite` for the rules and why they are the
+ Fetch standard's rather than the ones ``requests`` would apply.
+
:param max_redirects: Hops to follow before giving up.
:raises BlockedInternalUrlError: If any hop fails validation, or the
redirect chain is longer than ``max_redirects``.
"""
+ # `requests` normalizes the method on the prepared request, and the
+ # redirect rules below compare against it, so normalize once up front.
+ method = method.upper()
body = kwargs.get("data")
current_url = url
@@ -179,6 +235,26 @@ def safe_request(
response.close()
current_url = urljoin(current_url, location)
+ # The next hop is whatever `Location` says, query string included, so
+ # `params` must not be appended to it a second time — that is how
+ # `requests` builds a redirected request, and it keeps a query-string
+ # credential from being handed to a target that never asked for one.
+ kwargs.pop("params", None)
+
+ rewritten_method = _redirect_rewrite(response.status_code, method)
+ if rewritten_method is not None:
+ method = rewritten_method
+ body = None
+ for key in ("data", "json", "files"):
+ kwargs.pop(key, None)
+ if headers := kwargs.get("headers"):
+ kwargs["headers"] = {
+ name: value
+ for name, value in headers.items()
+ if name.lower() not in _BODY_HEADERS
+ }
+ continue
+
# `requests` rewinds the body itself when it follows a redirect; doing
# it manually means doing that too, or a retried upload sends nothing.
seek = getattr(body, "seek", None)
diff --git a/python/tests/test_url_safety.py b/python/tests/test_url_safety.py
index 0abbc93ac..73e5eb9d5 100644
--- a/python/tests/test_url_safety.py
+++ b/python/tests/test_url_safety.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import io
import socket
+import typing as t
from unittest.mock import MagicMock, call, patch
import pytest
@@ -31,6 +32,19 @@ from composio.utils.url_safety import (
"::169.254.169.254",
"64:ff9b::7f00:1",
"64:ff9b::a9fe:a9fe",
+ # Ranges the TypeScript guard's CIDR list blocks, so this one does too.
+ "224.0.0.1",
+ "233.252.0.1",
+ "192.88.99.1",
+ "ff02::1",
+ "fec0::1",
+ # Blocked here already; asserted so the two lists stay comparable.
+ "2001::7f00:1",
+ "2002:7f00:1::",
+ "2002:c0a8:1::",
+ "64:ff9b:1::7f00:1",
+ "100::1",
+ "2001:db8::1",
],
)
def test_blocks_non_public_addresses(address: str) -> None:
@@ -45,6 +59,11 @@ def test_blocks_non_public_addresses(address: str) -> None:
"2606:4700:4700::1111",
"::8.8.8.8",
"64:ff9b::8.8.8.8",
+ # Neighbours of the blocked ranges above, so neither list overreaches.
+ "2001:4860:4860::8888",
+ "2a00:1450:4001:80f::200e",
+ "223.255.255.255",
+ "192.88.100.1",
],
)
def test_allows_public_addresses(address: str) -> None:
@@ -177,6 +196,102 @@ def test_safe_request_follows_validated_redirect(mock_assert, mock_request) -> N
assert body.read() == b"payload"
+# What the hop after a redirect is expected to carry: either the original body
+# and the headers describing it, or neither.
+_REPLAYED: t.Dict[str, t.Any] = {
+ "data": b"payload",
+ "headers": {"Content-Type": "application/octet-stream", "X-Test": "kept"},
+}
+_BODILESS: t.Dict[str, t.Any] = {"headers": {"X-Test": "kept"}}
+
+
+ ("status_code", "method", "expected_method", "expected_kwargs"),
+ [
+ (301, "POST", "GET", _BODILESS),
+ (301, "PUT", "PUT", _REPLAYED),
+ (302, "POST", "GET", _BODILESS),
+ (302, "PUT", "PUT", _REPLAYED),
+ (303, "POST", "GET", _BODILESS),
+ (303, "PUT", "GET", _BODILESS),
+ (303, "HEAD", "HEAD", _BODILESS),
+ (307, "POST", "POST", _REPLAYED),
+ (308, "PUT", "PUT", _REPLAYED),
+ ],
+)
+@patch("composio.utils.url_safety.requests.Session.request")
+@patch("composio.utils.url_safety.assert_safe_fetch_target")
+def test_safe_request_applies_fetch_redirect_semantics(
+ mock_assert,
+ mock_request,
+ status_code: int,
+ method: str,
+ expected_method: str,
+ expected_kwargs: t.Dict[str, t.Any],
+) -> None:
+ """The same rules `ssrfSafeFetch` gets from `fetch` in the TypeScript SDK.
+
+ A 303 sends every method to a bodiless result request, 301/302 do that to a
+ POST only, and 307/308 replay the original method and body.
+ """
+ mock_request.side_effect = [
+ _response(status_code, "https://example.com/result"),
+ _response(200),
+ ]
+
+ safe_request(method, "https://example.com/create", **_REPLAYED)
+
+ assert mock_request.call_args_list[1] == call(
+ expected_method,
+ "https://example.com/result",
+ allow_redirects=False,
+ **expected_kwargs,
+ )
+ assert mock_assert.call_args_list[1] == call("https://example.com/result")
+
+
+@patch("composio.utils.url_safety.requests.Session.request")
+@patch("composio.utils.url_safety.assert_safe_fetch_target")
+def test_safe_request_keeps_the_downgrade_across_later_hops(
+ mock_assert, mock_request
+) -> None:
+ """A hop after the 303 must not resurrect the method or the body."""
+ mock_request.side_effect = [
+ _response(303, "https://example.com/result"),
+ _response(307, "https://example.com/final"),
+ _response(200),
+ ]
+
+ safe_request("POST", "https://example.com/create", **_REPLAYED)
+
+ assert mock_request.call_args_list[2] == call(
+ "GET",
+ "https://example.com/final",
+ allow_redirects=False,
+ **_BODILESS,
+ )
+
+
+@patch("composio.utils.url_safety.requests.Session.request")
+@patch("composio.utils.url_safety.assert_safe_fetch_target")
+def test_safe_request_does_not_reapply_params_to_the_redirect_target(
+ mock_assert, mock_request
+) -> None:
+ """`Location` carries its own query; re-appending would leak the original."""
+ mock_request.side_effect = [
+ _response(307, "https://other.example.com/elsewhere"),
+ _response(200),
+ ]
+
+ safe_request("GET", "https://example.com/download", params={"token": "secret"})
+
+ assert mock_request.call_args_list[1] == call(
+ "GET",
+ "https://other.example.com/elsewhere",
+ allow_redirects=False,
+ )
+
+
@patch("composio.utils.url_safety.requests.Session.request")
@patch("composio.utils.url_safety.assert_safe_fetch_target")
def test_safe_request_relative_redirect_is_resolved(mock_assert, mock_request) -> None:
diff --git a/ts/packages/core/src/utils/ssrfGuard.node.ts b/ts/packages/core/src/utils/ssrfGuard.node.ts
index 28659925a..24c53073e 100644
--- a/ts/packages/core/src/utils/ssrfGuard.node.ts
+++ b/ts/packages/core/src/utils/ssrfGuard.node.ts
@@ -40,6 +40,56 @@ import {
const MAX_REDIRECTS = 5;
+/**
+ * The Fetch standard's "redirect status" set. A 3xx outside it is not a
+ * redirect to follow even when it carries a `location` — `304 Not Modified`
+ * and `305 Use Proxy` most of all, and following those would replay the
+ * request against a target the caller never asked for. The Python guard
+ * follows the same set (`_REDIRECT_STATUS_CODES`).
+ */
+const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);
+
+/**
+ * Headers that describe a request body, so they have to go when the body does:
+ * the Fetch standard's "request-body-header name" set, plus the two the Python
+ * guard also drops because `requests` recomputes them from the body it sends.
+ */
+const BODY_HEADERS = [
+ 'content-encoding',
+ 'content-language',
+ 'content-length',
+ 'content-location',
+ 'content-type',
+ 'transfer-encoding',
+];
+
+/**
+ * The method the hop after a redirect uses, or `null` to replay as-is. A
+ * returned method also means the request body goes.
+ *
+ * These are the Fetch standard's redirect rules, which following redirects by
+ * hand (`redirect: 'manual'`) means `fetch` never applies for us: `303` points
+ * at a result URL that has no use for the original body, so every method loses
+ * it and everything but `HEAD` becomes a `GET`; `301`/`302` do the same to a
+ * `POST` only; `307`/`308` replay both. Without this, a `303` answering an
+ * upload would PUT the payload again at a URL that expects a GET. The Python
+ * guard applies the same rules in `safe_request`.
+ */
+const redirectRewrite = (status: number, method: string): string | null => {
+ if (status === 303) return method === 'HEAD' ? 'HEAD' : 'GET';
+ if ((status === 301 || status === 302) && method === 'POST') return 'GET';
+ return null;
+};
+
+const applyRedirectSemantics = (init: RequestInit, status: number): RequestInit => {
+ const method = redirectRewrite(status, (init.method ?? 'GET').toUpperCase());
+ if (method === null) return init;
+
+ const headers = new Headers(init.headers);
+ for (const name of BODY_HEADERS) headers.delete(name);
+ return { ...init, method, body: undefined, headers };
+};
+
/**
* Whether the runtime would route `url` through an env proxy the SDK cannot
* see into. Bun honors proxy environment variables automatically. Node's
@@ -77,6 +127,7 @@ const IPV4_BLOCKED_CIDRS: ReadonlyArray<readonly [string, number]> = [
['172.16.0.0', 12], // private
['192.0.0.0', 24], // IETF protocol assignments
['192.0.2.0', 24], // TEST-NET-1
+ ['192.88.99.0', 24], // 6to4 relay anycast (deprecated, RFC 7526)
['192.168.0.0', 16], // private
['198.18.0.0', 15], // benchmarking
['198.51.100.0', 24], // TEST-NET-2
@@ -146,8 +197,20 @@ const isBlockedIpv6 = (ip: string): boolean => {
return isBlockedIpv4Long((((h[6] << 16) >>> 0) | h[7]) >>> 0);
}
+ // Transition and tunnel ranges. Each one either carries an arbitrary IPv4
+ // address in its low bits or is reserved, so a public-looking literal here
+ // can still name internal space: `2002:7f00:1::` is 6to4 for `127.0.0.1`.
+ // Blocking the whole range rather than decoding it matches the Python guard,
+ // where `ipaddress.is_global` already rejects all of them.
+ if (h[0] === 0x2001 && (h[1] & 0xfe00) === 0) return true; // IETF protocol assignments 2001::/23 (incl. Teredo)
+ if (h[0] === 0x2001 && h[1] === 0x0db8) return true; // documentation 2001:db8::/32
+ if (h[0] === 0x2002) return true; // 6to4 2002::/16
+ if (h[0] === 0x0064 && h[1] === 0xff9b && h[2] === 0x0001) return true; // local-use NAT64 64:ff9b:1::/48
+ if (h[0] === 0x0100 && h[1] === 0 && h[2] === 0 && h[3] === 0) return true; // discard-only 100::/64
+
if ((h[0] & 0xfe00) === 0xfc00) return true; // unique local fc00::/7
if ((h[0] & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
+ if ((h[0] & 0xffc0) === 0xfec0) return true; // site-local fec0::/10 (deprecated)
if ((h[0] & 0xff00) === 0xff00) return true; // multicast ff00::/8
return false;
@@ -221,7 +284,8 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<string[]> =
* connects to the address it validated, and re-validates and re-pins every
* redirect hop (redirects are followed manually up to {@link MAX_REDIRECTS}).
* Intermediate redirect bodies are cancelled; non-redirect responses are
- * returned unchanged.
+ * returned unchanged. Each hop carries the method and body the Fetch standard
+ * says it should — see {@link applyRedirectSemantics}.
*
* A hop whose effective dispatcher is a configured route (caller-supplied
* `init.dispatcher`, non-stock global dispatcher, env-proxy mode) is *not*
@@ -233,6 +297,9 @@ export const ssrfSafeFetch = async (
maxRedirects: number = MAX_REDIRECTS
): Promise<Response> => {
let currentUrl = rawUrl;
+ // Rebound per hop: a redirect can drop the method and body (see
+ // `applyRedirectSemantics`), and the following hops must send what is left.
+ let currentInit = init;
for (let hop = 0; hop <= maxRedirects; hop++) {
const addresses = await assertSafeFetchTarget(currentUrl);
@@ -241,7 +308,7 @@ export const ssrfSafeFetch = async (
// Pinning replaces the connect target; through a configured route that
// would dial the validated origin instead of the route's next hop (the
// proxy), so those hops keep the pre-flight check only.
- const callerDispatcher = (init as RequestInit & { dispatcher?: unknown }).dispatcher;
+ const callerDispatcher = (currentInit as RequestInit & { dispatcher?: unknown }).dispatcher;
const respectConfiguredRoute =
callerDispatcher !== undefined ||
envProxyApplies(new URL(currentUrl), isBun) ||
@@ -253,14 +320,18 @@ export const ssrfSafeFetch = async (
let response: Response;
try {
if (isBun && !respectConfiguredRoute) {
- response = await pinnedHttpFetch(currentUrl, { ...init, redirect: 'manual' }, addresses);
+ response = await pinnedHttpFetch(
+ currentUrl,
+ { ...currentInit, redirect: 'manual' },
+ addresses
+ );
} else {
// `dispatcher` is a Node-only extension to `RequestInit`.
response = await fetch(
currentUrl,
(dispatcher === undefined
- ? { ...init, redirect: 'manual' }
- : { ...init, redirect: 'manual', dispatcher }) as RequestInit
+ ? { ...currentInit, redirect: 'manual' }
+ : { ...currentInit, redirect: 'manual', dispatcher }) as RequestInit
);
}
} catch (error) {
@@ -277,7 +348,7 @@ export const ssrfSafeFetch = async (
}
const isRedirect =
- response.status >= 300 && response.status < 400 && response.headers.has('location');
+ REDIRECT_STATUS_CODES.has(response.status) && response.headers.has('location');
if (!isRedirect) {
return response;
}
@@ -287,6 +358,7 @@ export const ssrfSafeFetch = async (
await response.body?.cancel().catch(() => undefined);
currentUrl = new URL(response.headers.get('location')!, currentUrl).toString();
+ currentInit = applyRedirectSemantics(currentInit, response.status);
}
throw new ComposioBlockedInternalUrlError(
diff --git a/ts/packages/core/test/utils/ssrfGuard.test.ts b/ts/packages/core/test/utils/ssrfGuard.test.ts
index f73c35f24..f4e4ec642 100644
--- a/ts/packages/core/test/utils/ssrfGuard.test.ts
+++ b/ts/packages/core/test/utils/ssrfGuard.test.ts
@@ -43,13 +43,24 @@ describe('isBlockedIp', () => {
'169.254.169.254', // cloud metadata
'100.64.0.1', // CGNAT
'0.0.0.0',
+ '224.0.0.1', // multicast
+ '233.252.0.1', // MCAST-TEST-NET
+ '192.88.99.1', // 6to4 relay anycast (deprecated)
]) {
expect(isBlockedIp(ip), ip).toBe(true);
}
});
it('allows public IPv4 addresses', () => {
- for (const ip of ['8.8.8.8', '1.1.1.1', '93.184.216.34', '172.15.0.1', '172.32.0.1']) {
+ for (const ip of [
+ '8.8.8.8',
+ '1.1.1.1',
+ '93.184.216.34',
+ '172.15.0.1',
+ '172.32.0.1',
+ '223.255.255.255',
+ '192.88.100.1',
+ ]) {
expect(isBlockedIp(ip), ip).toBe(false);
}
});
@@ -75,8 +86,35 @@ describe('isBlockedIp', () => {
}
});
+ it('blocks the transition ranges that carry an arbitrary IPv4 address', () => {
+ // A public-looking literal that still names internal space. The Python
+ // guard rejects all of these through `ipaddress.is_global`.
+ for (const ip of [
+ '2002:7f00:1::', // 6to4 for 127.0.0.1
+ '2002:c0a8:1::', // 6to4 for 192.168.0.1
+ '2002:8080:8080::', // 6to4 for a public address — the range goes as a whole
+ '2001::7f00:1', // Teredo 2001::/32
+ '2001:2::1', // benchmarking
+ '2001:10::1', // ORCHID
+ '2001:db8::1', // documentation
+ '64:ff9b:1::7f00:1', // local-use NAT64 for 127.0.0.1
+ '100::1', // discard-only
+ 'fec0::1', // site-local (deprecated)
+ ]) {
+ expect(isBlockedIp(ip), ip).toBe(true);
+ }
+ });
+
it('allows public IPv6 and public IPv4-mapped/compat addresses', () => {
- for (const ip of ['2606:4700:4700::1111', '::ffff:8.8.8.8', '::8.8.8.8', '::808:808']) {
+ for (const ip of [
+ '2606:4700:4700::1111',
+ '::ffff:8.8.8.8',
+ '::8.8.8.8',
+ '::808:808',
+ // Neighbours of the ranges above, so the list does not overreach.
+ '2001:4860:4860::8888',
+ '2a00:1450:4001:80f::200e',
+ ]) {
expect(isBlockedIp(ip), ip).toBe(false);
}
});
@@ -338,4 +376,81 @@ describe('ssrfSafeFetch', () => {
// maxRedirects = 2 => hops 0, 1, 2 are fetched before the budget throws.
expect(cancel).toHaveBeenCalledTimes(3);
});
+
+ // `redirect: 'manual'` means `fetch` never applies its own redirect rules, so
+ // the guard applies them: a 303 sends every method to a bodiless result
+ // request, 301/302 do that to a POST only, and 307/308 replay both. The
+ // Python guard follows the same table in `safe_request`.
+ it.each([
+ { status: 301, method: 'POST', expected: 'GET', replays: false },
+ { status: 301, method: 'PUT', expected: 'PUT', replays: true },
+ { status: 302, method: 'POST', expected: 'GET', replays: false },
+ { status: 302, method: 'PUT', expected: 'PUT', replays: true },
+ { status: 303, method: 'POST', expected: 'GET', replays: false },
+ { status: 303, method: 'PUT', expected: 'GET', replays: false },
+ { status: 303, method: 'HEAD', expected: 'HEAD', replays: false },
+ { status: 307, method: 'POST', expected: 'POST', replays: true },
+ { status: 308, method: 'PUT', expected: 'PUT', replays: true },
+ ])(
+ 'sends $method as $expected after a $status',
+ async ({ status, method, expected, replays }) => {
+ resolvesTo('93.184.216.34');
+ mockFetch
+ .mockResolvedValueOnce(
+ new Response(null, { status, headers: { location: 'https://example.com/result' } })
+ )
+ .mockResolvedValueOnce(new Response('data', { status: 200 }));
+
+ await ssrfSafeFetch('https://example.com/create', {
+ method,
+ body: 'payload',
+ headers: { 'Content-Type': 'application/octet-stream', 'X-Test': 'kept' },
+ });
+
+ const [url, init] = mockFetch.mock.calls[1];
+ expect(url).toBe('https://example.com/result');
+ expect(init.method).toBe(expected);
+ expect(init.body).toBe(replays ? 'payload' : undefined);
+ expect(new Headers(init.headers).get('content-type')).toBe(
+ replays ? 'application/octet-stream' : null
+ );
+ // Only the headers that describe the body go with it.
+ expect(new Headers(init.headers).get('x-test')).toBe('kept');
+ }
+ );
+
+ it('keeps the downgrade across later hops', async () => {
+ resolvesTo('93.184.216.34');
+ mockFetch
+ .mockResolvedValueOnce(
+ new Response(null, { status: 303, headers: { location: 'https://example.com/result' } })
+ )
+ .mockResolvedValueOnce(
+ new Response(null, { status: 307, headers: { location: 'https://example.com/final' } })
+ )
+ .mockResolvedValueOnce(new Response('data', { status: 200 }));
+
+ await ssrfSafeFetch('https://example.com/create', { method: 'POST', body: 'payload' });
+
+ // A 307 replays whatever the request is *now*, not what it started as.
+ expect(mockFetch.mock.calls[2][1].method).toBe('GET');
+ expect(mockFetch.mock.calls[2][1].body).toBeUndefined();
+ });
+
+ it.each([300, 304, 305, 306])(
+ 'returns a %i without following its location',
+ async (status: number) => {
+ resolvesTo('93.184.216.34');
+ // Only 301/302/303/307/308 are redirects to follow; a `location` on any
+ // other 3xx does not make it one.
+ mockFetch.mockResolvedValue(
+ new Response(null, { status, headers: { location: 'https://example.com/elsewhere' } })
+ );
+
+ const res = await ssrfSafeFetch('https://example.com/file.pdf');
+
+ expect(res.status).toBe(status);
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ }
+ );
});