@devries-cameron20 / composio-1 / commits / 95f9d3295
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(cli): guard URL file uploads against SSRF (#4319)

## Summary - route attacker-controlled URL sources and API-provided presigned upload destinations through the runtime-conditional core SSRF guard - expose that guard through a Node/workerd-aware core subpath - validate and revalidate DNS on redirects, pin Node and Bun connections to validated addresses, and preserve configured proxy routes - fail closed for user-chosen URL uploads in edge runtimes - cancel ignored response bodies and cover both upload boundaries at the public CLI pipeline - avoid adding `Content-Length: 0` to bodyless Bun GET requests ## Local reproduction On `next`, the CLI pipeline used bare `fetch` for both targets. A local loopback source and an internal presigned destination reached the network path. With this branch, the real `uploadToolInputFiles` pipeline blocks a `127.0.0.1` source before presigning and a `169.254.169.254` destination before sending bytes. A direct Bun proof also confirmed the pinned transport reaches a validated address without calling native `fetch`, while retaining the original Host header. Focused tests preserve native Bun fetch when an environment proxy is configured. ## Cross-SDK parity Python already applies public-address validation, redirect checks, DNS pinning, and response limits to URL uploads. Its focused URL-safety and upload suite remains green: 62 passed. No Python behavior change was needed. ## Verification - `pnpm build:packages`: 19 packages built - root `pnpm typecheck`: 14 package checks passed - TypeScript core: 53 files, 1,246 passed and 2 expected failures - focused core SSRF and pinned-transport tests: 31 passed - Python URL-safety/upload tests: 62 passed - real Bun execution of both CLI upload boundaries: blocked before presign/send - `git diff --check` The CLI Effect test file contains source and presigned-destination regressions and typechecks. Its local runner is blocked on current `next` by the repository-wide `@effect/vitest` config failure; hosted CLI checks exercise that boundary. ## Contributor context Supersedes [#4299](https://github.com/ComposioHQ/composio/pull/4299) · [Glen](https://app.tryglen.com/ComposioHQ/composio/pull/4299) after independently reproducing the attack path. The report is valid and useful, but the proposed root export hard-coded a Node module into an edge-capable package, its happy-path test did not execute the returned Effect, and it omitted destination protection, response cleanup, and Bun address pinning.

Alberto Schiabel committed Sep 3, 2026 at 11:51 UTC 95f9d3295f3ff82e3d00907fc09b8bc38b568cc3
11 files changed +345 -35
.changeset/safe-url-file-uploads.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Expose the runtime-conditional SSRF-safe fetch helper for protected URL upload consumers.
ts/packages/cli/src/services/tool-file-uploads.ts
+6 -2
@@ -6,6 +6,7 @@
6 import type { FileSystem, Path } from '@effect/platform';
7 import type { Composio as RawComposioClient } from '@composio/client';
8 import { assertSafeFileUploadPath } from '@composio/core';
9 +import { ssrfSafeFetch } from '@composio/core/utils/ssrf-guard';
10 import { Cause, Data, Effect, Exit, Predicate } from 'effect';
11 import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
12
@@ -143,8 +144,9 @@ export const findFileUploadablePaths = (
144 };
145
146 const readFileFromUrl = async (path: Path.Path, url: string) => {
146 - const response = await fetch(url);
147 + const response = await ssrfSafeFetch(url);
148 if (!response.ok) {
149 + await response.body?.cancel().catch(() => undefined);
150 throw new ToolFileUploadError({
151 message: `Failed to fetch file: ${response.statusText}`,
152 reason: 'source-fetch',
@@ -249,7 +251,7 @@ const uploadFile = async (params: {
251 toolkit_slug: params.toolkitSlug,
252 });
253
252 - const uploadResponse = await fetch(presigned.new_presigned_url, {
254 + const uploadResponse = await ssrfSafeFetch(presigned.new_presigned_url, {
255 method: 'PUT',
256 body: fileData.bytes,
257 headers: {
@@ -259,12 +261,14 @@ const uploadFile = async (params: {
261 });
262
263 if (!uploadResponse.ok) {
264 + await uploadResponse.body?.cancel().catch(() => undefined);
265 throw new ToolFileUploadError({
266 message: `Failed to upload file to S3: ${uploadResponse.statusText}`,
267 reason: 'upload',
268 status: uploadResponse.status,
269 });
270 }
271 + await uploadResponse.body?.cancel().catch(() => undefined);
272
273 return {
274 name: fileData.fileName,
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+4
@@ -22,6 +22,10 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';
22 import type { ToolkitDetailed } from 'src/models/toolkits';
23 import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
24
25 +vi.mock('node:dns/promises', () => ({
26 + lookup: vi.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),
27 +}));
28 +
29 // Disable CI redaction so tests see raw values. `src/ui/redact` reads `CI` once
30 // at import time, so the variable has to be gone before the imports above run —
31 // `vi.hoisted` executes ahead of them. The explicit CI-redaction test overrides
ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+72 -2
@@ -6,7 +6,10 @@ import { FileSystem, Path } from '@effect/platform';
6 import { BunFileSystem, BunPath } from '@effect/platform-bun';
7 import { Effect, Layer } from 'effect';
8 import { Composio as RawComposioClient } from '@composio/client';
9 -import { ComposioSensitiveFilePathBlockedError } from '@composio/core';
9 +import {
10 + ComposioBlockedInternalUrlError,
11 + ComposioSensitiveFilePathBlockedError,
12 +} from '@composio/core';
13 import { schemaHasFileUploadable, uploadToolInputFiles } from 'src/services/tool-file-uploads';
14
15 // Schema with a single `file_uploadable` attachment field — mirrors tools like
@@ -130,7 +133,7 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
133 writeFileSync(file, 'hello');
134
135 const createPresignedURL = vi.fn(async () => ({
133 - new_presigned_url: 'https://s3.example.com/put',
136 + new_presigned_url: 'https://1.1.1.1/put',
137 key: 's3key-123',
138 }));
139 const client = makeClient(createPresignedURL);
@@ -164,3 +167,70 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
167 );
168 });
169 });
170 +
171 +describe('uploadToolInputFiles — URL SSRF boundary', () => {
172 + afterEach(() => {
173 + vi.unstubAllGlobals();
174 + vi.restoreAllMocks();
175 + });
176 +
177 + it.effect('rejects an unsafe source before requesting an upload destination', () =>
178 + Effect.gen(function* () {
179 + const fsApi = yield* FileSystem.FileSystem;
180 + const pathApi = yield* Path.Path;
181 + const createPresignedURL = vi.fn();
182 + const client = makeClient(createPresignedURL);
183 + const sourceUrl = 'http://169.254.169.254/latest/meta-data/credentials';
184 +
185 + yield* Effect.promise(() =>
186 + expect(
187 + uploadToolInputFiles({
188 + fs: fsApi,
189 + path: pathApi,
190 + toolSlug: 'GMAIL_SEND_EMAIL',
191 + arguments_: { attachment: sourceUrl },
192 + inputSchema,
193 + client,
194 + })
195 + ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError)
196 + );
197 +
198 + expect(createPresignedURL).not.toHaveBeenCalled();
199 + }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
200 + );
201 +
202 + it.effect('rejects an unsafe presigned destination before sending file bytes', () => {
203 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
204 + const file = path.join(root, 'document.pdf');
205 + writeFileSync(file, 'hello');
206 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
207 + const createPresignedURL = vi.fn(async () => ({
208 + new_presigned_url: 'http://127.0.0.1:8080/upload',
209 + key: 's3key-123',
210 + }));
211 +
212 + return Effect.gen(function* () {
213 + const fsApi = yield* FileSystem.FileSystem;
214 + const pathApi = yield* Path.Path;
215 +
216 + yield* Effect.promise(() =>
217 + expect(
218 + uploadToolInputFiles({
219 + fs: fsApi,
220 + path: pathApi,
221 + toolSlug: 'GMAIL_SEND_EMAIL',
222 + arguments_: { attachment: file },
223 + inputSchema,
224 + client: makeClient(createPresignedURL),
225 + })
226 + ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError)
227 + );
228 +
229 + expect(createPresignedURL).toHaveBeenCalledOnce();
230 + expect(fetchSpy).not.toHaveBeenCalled();
231 + }).pipe(
232 + Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
233 + Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
234 + );
235 + });
236 +});
ts/packages/cli/vitest.config.ts
+2
@@ -14,6 +14,7 @@ export default defineConfig({
14 '~': path.resolve(__dirname, './'),
15 src: path.resolve(__dirname, './src'),
16 test: path.resolve(__dirname, './test'),
17 + '@composio/core/utils/ssrf-guard': path.join(coreDir, 'src/utils/ssrfGuard.node.ts'),
18 '@composio/core/experimental': path.join(coreDir, 'src/experimental/index.ts'),
19 '@composio/core': path.join(coreDir, 'src/index.ts'),
20 '@composio/ts-builders': path.join(tsBuildersDir, 'src/index.ts'),
@@ -30,6 +31,7 @@ export default defineConfig({
31 '#platform': path.join(coreDir, 'src/platform/node.ts'),
32 '#files': path.join(coreDir, 'src/models/Files.node.ts'),
33 '#file_tool_modifier': path.join(coreDir, 'src/utils/modifiers/FileToolModifier.node.ts'),
34 + '#ssrf_guard': path.join(coreDir, 'src/utils/ssrfGuard.node.ts'),
35 },
36 },
37 test: {
ts/packages/core/package.json
+18
@@ -75,6 +75,24 @@
75 "types": "./dist/utils/json-schema.d.mts",
76 "default": "./dist/utils/json-schema.mjs"
77 },
78 + "./utils/ssrf-guard": {
79 + "workerd": {
80 + "types": "./dist/utils/ssrfGuard.workerd.d.mts",
81 + "default": "./dist/utils/ssrfGuard.workerd.mjs"
82 + },
83 + "edge-light": {
84 + "types": "./dist/utils/ssrfGuard.workerd.d.mts",
85 + "default": "./dist/utils/ssrfGuard.workerd.mjs"
86 + },
87 + "node": {
88 + "types": "./dist/utils/ssrfGuard.node.d.mts",
89 + "default": "./dist/utils/ssrfGuard.node.mjs"
90 + },
91 + "default": {
92 + "types": "./dist/utils/ssrfGuard.node.d.mts",
93 + "default": "./dist/utils/ssrfGuard.node.mjs"
94 + }
95 + },
96 "./generated": {
97 "types": "./generated/index.d.ts",
98 "default": "./generated/index.js"
ts/packages/core/src/utils/pinnedDispatcher.node.ts
+109 -13
@@ -1,4 +1,7 @@
1 import { isIP } from 'node:net';
2 +import { request as httpRequest } from 'node:http';
3 +import { request as httpsRequest } from 'node:https';
4 +import { Readable } from 'node:stream';
5 import type { Agent } from 'undici';
6
7 /**
@@ -36,6 +39,37 @@ const GLOBAL_DISPATCHER_SYMBOLS = [
39 let undici: Promise<typeof import('undici')> | undefined;
40 const loadUndici = (): Promise<typeof import('undici')> => (undici ??= import('undici'));
41
42 +const lookupPinnedAddresses = (
43 + addresses: ReadonlyArray<string>,
44 + options: { all?: boolean },
45 + callback: (
46 + error: NodeJS.ErrnoException | null,
47 + address: string | Array<{ address: string; family: number }>,
48 + family?: number
49 + ) => void
50 +) => {
51 + if (options.all) {
52 + callback(
53 + null,
54 + addresses.map(address => ({ address, family: isIP(address) }))
55 + );
56 + return;
57 + }
58 +
59 + const [address] = addresses;
60 + callback(null, address, isIP(address));
61 +};
62 +
63 +const knownBodyLength = (body: BodyInit | null | undefined): number | undefined => {
64 + if (body === null || body === undefined) return undefined;
65 + if (typeof body === 'string') return new TextEncoder().encode(body).byteLength;
66 + if (body instanceof URLSearchParams) return new TextEncoder().encode(body.toString()).byteLength;
67 + if (body instanceof ArrayBuffer) return body.byteLength;
68 + if (ArrayBuffer.isView(body)) return body.byteLength;
69 + if (body instanceof Blob) return body.size;
70 + return undefined;
71 +};
72 +
73 /**
74 * A `fetch` dispatcher that connects to `addresses` instead of resolving the
75 * hostname again.
@@ -71,24 +105,86 @@ export const createPinnedDispatcher = async (addresses: ReadonlyArray<string>):
105 // off, or a `family`/`localAddress` was requested. Answering in the
106 // wrong shape is rejected as an invalid address, which would fail
107 // every pinned fetch in such a process.
74 - if (options.all) {
75 - // All of them, in resolver order: handing over a single address of a
76 - // dual-stack host would strand callers whose network cannot reach
77 - // that family, where the runtime would otherwise have fallen back.
78 - callback(
79 - null,
80 - addresses.map(address => ({ address, family: isIP(address) }))
81 - );
82 - return;
83 - }
84 -
85 - const [address] = addresses;
86 - callback(null, address, isIP(address));
108 + lookupPinnedAddresses(addresses, options, callback);
109 },
110 },
111 });
112 };
113
114 +/**
115 + * Fetch through the Node-compatible HTTP client while pinning DNS resolution.
116 + *
117 + * Bun implements the Node HTTP client and its `lookup` hook, but its native
118 + * `fetch` ignores undici's `dispatcher` option. This transport preserves the
119 + * original hostname for Host and TLS SNI while making the socket use an
120 + * address that the SSRF guard already validated.
121 + */
122 +export const pinnedHttpFetch = async (
123 + rawUrl: string,
124 + init: RequestInit,
125 + addresses: ReadonlyArray<string>
126 +): Promise<Response> => {
127 + const normalized = new Request(rawUrl, init);
128 + const url = new URL(rawUrl);
129 + const request = url.protocol === 'https:' ? httpsRequest : httpRequest;
130 + const headers = new Headers(normalized.headers);
131 + const bodyLength = knownBodyLength(init.body);
132 + if (bodyLength !== undefined && !headers.has('content-length')) {
133 + headers.set('content-length', String(bodyLength));
134 + }
135 +
136 + return new Promise<Response>((resolve, reject) => {
137 + const outgoing = request(
138 + url,
139 + {
140 + method: normalized.method,
141 + headers: Object.fromEntries(headers.entries()),
142 + signal: normalized.signal,
143 + lookup: (_hostname, options, callback) =>
144 + lookupPinnedAddresses(addresses, options, callback),
145 + },
146 + incoming => {
147 + const headers = new Headers();
148 + for (let index = 0; index < incoming.rawHeaders.length; index += 2) {
149 + headers.append(incoming.rawHeaders[index], incoming.rawHeaders[index + 1]);
150 + }
151 +
152 + const status = incoming.statusCode ?? 500;
153 + const body = [101, 103, 204, 205, 304].includes(status)
154 + ? null
155 + : (Readable.toWeb(incoming) as ReadableStream<Uint8Array>);
156 + resolve(
157 + new Response(body, {
158 + status,
159 + statusText: incoming.statusMessage,
160 + headers,
161 + })
162 + );
163 + }
164 + );
165 +
166 + outgoing.once('error', reject);
167 +
168 + void (async () => {
169 + try {
170 + if (normalized.body) {
171 + const reader = normalized.body.getReader();
172 + while (true) {
173 + const { done, value } = await reader.read();
174 + if (done) break;
175 + if (!outgoing.write(value)) {
176 + await new Promise<void>(resolveDrain => outgoing.once('drain', resolveDrain));
177 + }
178 + }
179 + }
180 + outgoing.end();
181 + } catch (error) {
182 + outgoing.destroy(error instanceof Error ? error : new Error(String(error)));
183 + }
184 + })();
185 + });
186 +};
187 +
188 /**
189 * Whether the process-wide dispatcher `fetch` falls back to (when a request
190 * carries no `dispatcher` of its own) is something other than a stock `Agent`.
ts/packages/core/src/utils/ssrfGuard.node.ts
+29 -17
@@ -1,7 +1,11 @@
1 import { lookup } from 'node:dns/promises'; // we're in a Node.js-specific module
2 import { isIP } from 'node:net';
3 import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
4 -import { createPinnedDispatcher, hasCustomGlobalDispatcher } from './pinnedDispatcher.node';
4 +import {
5 + createPinnedDispatcher,
6 + hasCustomGlobalDispatcher,
7 + pinnedHttpFetch,
8 +} from './pinnedDispatcher.node';
9
10 /**
11 * SSRF guard for user-supplied URL file inputs.
@@ -26,7 +30,8 @@ import { createPinnedDispatcher, hasCustomGlobalDispatcher } from './pinnedDispa
30 * Residual: a hop whose effective dispatcher is a configured route — a
31 * caller-supplied `init.dispatcher`, a non-stock global dispatcher (a
32 * `ProxyAgent` or `EnvHttpProxyAgent` installed via `setGlobalDispatcher`), or
29 - * the runtime's env-proxy mode (`NODE_USE_ENV_PROXY`) — keeps only the
33 + * the runtime's env-proxy mode (automatic on Bun, opt-in via
34 + * `NODE_USE_ENV_PROXY` on Node) — keeps only the
35 * pre-flight validation. Pinning would dial the validated address instead of
36 * the proxy, and the proxy resolves the hostname itself where the SDK cannot
37 * see or pin that resolution. The Python guard carries the same residual for
@@ -37,17 +42,18 @@ const MAX_REDIRECTS = 5;
42
43 /**
44 * Whether the runtime would route `url` through an env proxy the SDK cannot
40 - * see into. Only meaningful when `NODE_USE_ENV_PROXY` opts the built-in
41 - * `fetch` into env proxies (Node >= 24); without that flag the runtime's
42 - * `fetch` ignores `HTTP_PROXY`/`HTTPS_PROXY` entirely, so mirroring Python's
43 - * bare env-var check would drop pinning for users whose fetch never proxied.
45 + * see into. Bun honors proxy environment variables automatically. Node's
46 + * built-in `fetch` requires the `NODE_USE_ENV_PROXY` opt-in (Node >= 24), so
47 + * a bare env-var check on Node would drop pinning for users whose fetch never
48 + * proxied.
49 *
50 * `NO_PROXY=*` is the one bypass honored precisely (nothing is proxied, so
51 * pinning is safe again); per-host `NO_PROXY` entries are treated
52 * conservatively as proxied rather than parsed.
53 */
49 -const envProxyApplies = (url: URL): boolean => {
50 - const useEnvProxy = ['1', 'true'].includes((process.env.NODE_USE_ENV_PROXY ?? '').toLowerCase());
54 +const envProxyApplies = (url: URL, isBun: boolean): boolean => {
55 + const useEnvProxy =
56 + isBun || ['1', 'true'].includes((process.env.NODE_USE_ENV_PROXY ?? '').toLowerCase());
57 if (!useEnvProxy) return false;
58 if ((process.env.NO_PROXY ?? process.env.no_proxy ?? '') === '*') return false;
59 const schemeVar = url.protocol === 'https:' ? 'HTTPS_PROXY' : 'HTTP_PROXY';
@@ -230,6 +236,7 @@ export const ssrfSafeFetch = async (
236
237 for (let hop = 0; hop <= maxRedirects; hop++) {
238 const addresses = await assertSafeFetchTarget(currentUrl);
239 + const isBun = typeof process.versions.bun === 'string';
240
241 // Pinning replaces the connect target; through a configured route that
242 // would dial the validated origin instead of the route's next hop (the
@@ -237,20 +244,25 @@ export const ssrfSafeFetch = async (
244 const callerDispatcher = (init as RequestInit & { dispatcher?: unknown }).dispatcher;
245 const respectConfiguredRoute =
246 callerDispatcher !== undefined ||
240 - envProxyApplies(new URL(currentUrl)) ||
247 + envProxyApplies(new URL(currentUrl), isBun) ||
248 hasCustomGlobalDispatcher();
249
243 - const dispatcher = respectConfiguredRoute ? undefined : await createPinnedDispatcher(addresses);
250 + const dispatcher =
251 + respectConfiguredRoute || isBun ? undefined : await createPinnedDispatcher(addresses);
252
253 let response: Response;
254 try {
247 - // `dispatcher` is a Node-only extension to `RequestInit`.
248 - response = await fetch(
249 - currentUrl,
250 - (dispatcher === undefined
251 - ? { ...init, redirect: 'manual' }
252 - : { ...init, redirect: 'manual', dispatcher }) as RequestInit
253 - );
255 + if (isBun && !respectConfiguredRoute) {
256 + response = await pinnedHttpFetch(currentUrl, { ...init, redirect: 'manual' }, addresses);
257 + } else {
258 + // `dispatcher` is a Node-only extension to `RequestInit`.
259 + response = await fetch(
260 + currentUrl,
261 + (dispatcher === undefined
262 + ? { ...init, redirect: 'manual' }
263 + : { ...init, redirect: 'manual', dispatcher }) as RequestInit
264 + );
265 + }
266 } catch (error) {
267 if (dispatcher !== undefined) {
268 await dispatcher.close().catch(() => undefined);
ts/packages/core/src/utils/ssrfGuard.workerd.ts
+5 -1
@@ -5,7 +5,11 @@ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
5 * hostname is publicly routable before connecting. Fail closed instead of
6 * falling back to an unguarded fetch.
7 */
8 -export const ssrfSafeFetch = async (rawUrl: string): Promise<Response> => {
8 +export const ssrfSafeFetch = async (
9 + rawUrl: string,
10 + _init: RequestInit = {},
11 + _maxRedirects?: number
12 +): Promise<Response> => {
13 throw new ComposioBlockedInternalUrlError(
14 'URL file uploads are not supported in edge runtimes because the destination cannot be safely validated',
15 {
ts/packages/core/test/utils/pinnedDispatcher.node.test.ts
+63
@@ -5,6 +5,7 @@ import { Agent, ProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'und
5 import {
6 createPinnedDispatcher,
7 hasCustomGlobalDispatcher,
8 + pinnedHttpFetch,
9 } from '../../src/utils/pinnedDispatcher.node';
10
11 /**
@@ -97,6 +98,68 @@ describe('createPinnedDispatcher', () => {
98 });
99 });
100
101 +describe('pinnedHttpFetch', () => {
102 + let server: Server | undefined;
103 +
104 + afterEach(async () => {
105 + if (server) {
106 + await new Promise<void>(resolve => server!.close(() => resolve()));
107 + server = undefined;
108 + }
109 + });
110 +
111 + it('connects to a validated address while preserving the original host', async () => {
112 + let receivedHost = '';
113 + let receivedBody = '';
114 + let receivedContentLength = '';
115 + server = createServer((request, response) => {
116 + receivedHost = request.headers.host ?? '';
117 + receivedContentLength = request.headers['content-length'] ?? '';
118 + request.setEncoding('utf8');
119 + request.on('data', chunk => {
120 + receivedBody += chunk;
121 + });
122 + request.on('end', () => {
123 + response.writeHead(200, { 'content-type': 'text/plain' });
124 + response.end('pinned payload');
125 + });
126 + });
127 + await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));
128 + const port = (server.address() as AddressInfo).port;
129 +
130 + const response = await pinnedHttpFetch(
131 + `http://pinned.invalid:${port}/payload`,
132 + { method: 'PUT', body: 'upload body' },
133 + ['127.0.0.1']
134 + );
135 +
136 + expect(response.status).toBe(200);
137 + expect(await response.text()).toBe('pinned payload');
138 + expect(receivedHost).toBe(`pinned.invalid:${port}`);
139 + expect(receivedBody).toBe('upload body');
140 + expect(receivedContentLength).toBe('11');
141 + });
142 +
143 + it('does not add Content-Length to a request without a body', async () => {
144 + let receivedContentLength: string | undefined;
145 + server = createServer((request, response) => {
146 + receivedContentLength = request.headers['content-length'];
147 + response.end('ok');
148 + });
149 + await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));
150 + const port = (server.address() as AddressInfo).port;
151 +
152 + const response = await pinnedHttpFetch(
153 + `http://pinned.invalid:${port}/payload`,
154 + { method: 'GET' },
155 + ['127.0.0.1']
156 + );
157 +
158 + expect(await response.text()).toBe('ok');
159 + expect(receivedContentLength).toBeUndefined();
160 + });
161 +});
162 +
163 describe('hasCustomGlobalDispatcher', () => {
164 it('reports the stock dispatcher as not custom', () => {
165 expect(hasCustomGlobalDispatcher()).toBe(false);
ts/packages/core/test/utils/ssrfGuard.test.ts
+32
@@ -9,15 +9,18 @@ vi.mock('node:dns/promises', () => ({
9 vi.mock('../../src/utils/pinnedDispatcher.node', () => ({
10 createPinnedDispatcher: vi.fn(() => Promise.resolve({ close: () => Promise.resolve() })),
11 hasCustomGlobalDispatcher: vi.fn(() => false),
12 + pinnedHttpFetch: vi.fn(),
13 }));
14
15 import {
16 createPinnedDispatcher,
17 hasCustomGlobalDispatcher,
18 + pinnedHttpFetch,
19 } from '../../src/utils/pinnedDispatcher.node';
20
21 const mockCreatePinnedDispatcher = vi.mocked(createPinnedDispatcher);
22 const mockHasCustomGlobalDispatcher = vi.mocked(hasCustomGlobalDispatcher);
23 +const mockPinnedHttpFetch = vi.mocked(pinnedHttpFetch);
24
25 // eslint-disable-next-line no-restricted-imports
26 import { lookup } from 'node:dns/promises';
@@ -133,6 +136,7 @@ describe('ssrfSafeFetch', () => {
136 mockFetch.mockReset();
137 mockCreatePinnedDispatcher.mockClear();
138 mockHasCustomGlobalDispatcher.mockReturnValue(false);
139 + mockPinnedHttpFetch.mockReset();
140 // Deterministic even on machines that carry the runtime env-proxy opt-in.
141 vi.stubEnv('NODE_USE_ENV_PROXY', '');
142 vi.stubGlobal('fetch', mockFetch);
@@ -222,6 +226,34 @@ describe('ssrfSafeFetch', () => {
226 expect(mockCreatePinnedDispatcher).toHaveBeenCalledWith(['93.184.216.34']);
227 });
228
229 + it('keeps Bun fetch on an explicitly configured environment proxy', async () => {
230 + resolvesTo('93.184.216.34');
231 + mockFetch.mockResolvedValue(new Response('data', { status: 200 }));
232 + vi.stubEnv('HTTPS_PROXY', 'http://proxy.example:3128');
233 + vi.stubEnv('NO_PROXY', '');
234 + const bunDescriptor = Object.getOwnPropertyDescriptor(process.versions, 'bun');
235 + Object.defineProperty(process.versions, 'bun', {
236 + configurable: true,
237 + value: '1.4.0',
238 + });
239 +
240 + try {
241 + await ssrfSafeFetch('https://example.com/file.pdf');
242 + } finally {
243 + if (bunDescriptor) {
244 + Object.defineProperty(process.versions, 'bun', bunDescriptor);
245 + } else {
246 + delete (process.versions as NodeJS.ProcessVersions & { bun?: string }).bun;
247 + }
248 + }
249 +
250 + expect(mockPinnedHttpFetch).not.toHaveBeenCalled();
251 + expect(mockFetch).toHaveBeenCalledWith(
252 + 'https://example.com/file.pdf',
253 + expect.objectContaining({ redirect: 'manual' })
254 + );
255 + });
256 +
257 it('validates and fetches a public URL', async () => {
258 resolvesTo('93.184.216.34');
259 const ok = new Response('data', { status: 200 });