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(cli): guard URL file uploads against SSRF (#4319)

Alberto Schiabel95f9d3295f3f
diff --git a/.changeset/safe-url-file-uploads.md b/.changeset/safe-url-file-uploads.md
new file mode 100644
index 000000000..5b81f8c7b
--- /dev/null
+++ b/.changeset/safe-url-file-uploads.md
@@ -0,0 +1,5 @@
+---
+'@composio/core': patch
+---
+
+Expose the runtime-conditional SSRF-safe fetch helper for protected URL upload consumers.
diff --git a/ts/packages/cli/src/services/tool-file-uploads.ts b/ts/packages/cli/src/services/tool-file-uploads.ts
index 95613a8ee..b13b7e135 100644
--- a/ts/packages/cli/src/services/tool-file-uploads.ts
+++ b/ts/packages/cli/src/services/tool-file-uploads.ts
@@ -6,6 +6,7 @@
import type { FileSystem, Path } from '@effect/platform';
import type { Composio as RawComposioClient } from '@composio/client';
import { assertSafeFileUploadPath } from '@composio/core';
+import { ssrfSafeFetch } from '@composio/core/utils/ssrf-guard';
import { Cause, Data, Effect, Exit, Predicate } from 'effect';
import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
@@ -143,8 +144,9 @@ export const findFileUploadablePaths = (
};
const readFileFromUrl = async (path: Path.Path, url: string) => {
- const response = await fetch(url);
+ const response = await ssrfSafeFetch(url);
if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
throw new ToolFileUploadError({
message: `Failed to fetch file: ${response.statusText}`,
reason: 'source-fetch',
@@ -249,7 +251,7 @@ const uploadFile = async (params: {
toolkit_slug: params.toolkitSlug,
});
- const uploadResponse = await fetch(presigned.new_presigned_url, {
+ const uploadResponse = await ssrfSafeFetch(presigned.new_presigned_url, {
method: 'PUT',
body: fileData.bytes,
headers: {
@@ -259,12 +261,14 @@ const uploadFile = async (params: {
});
if (!uploadResponse.ok) {
+ await uploadResponse.body?.cancel().catch(() => undefined);
throw new ToolFileUploadError({
message: `Failed to upload file to S3: ${uploadResponse.statusText}`,
reason: 'upload',
status: uploadResponse.status,
});
}
+ await uploadResponse.body?.cancel().catch(() => undefined);
return {
name: fileData.fileName,
diff --git a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
index a4667847f..4e4c655e8 100644
--- a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
@@ -22,6 +22,10 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';
import type { ToolkitDetailed } from 'src/models/toolkits';
import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),
+}));
+
// Disable CI redaction so tests see raw values. `src/ui/redact` reads `CI` once
// at import time, so the variable has to be gone before the imports above run —
// `vi.hoisted` executes ahead of them. The explicit CI-redaction test overrides
diff --git a/ts/packages/cli/test/src/services/tool-file-uploads.test.ts b/ts/packages/cli/test/src/services/tool-file-uploads.test.ts
index c8eebe1a2..21666f261 100644
--- a/ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+++ b/ts/packages/cli/test/src/services/tool-file-uploads.test.ts
@@ -6,7 +6,10 @@ import { FileSystem, Path } from '@effect/platform';
import { BunFileSystem, BunPath } from '@effect/platform-bun';
import { Effect, Layer } from 'effect';
import { Composio as RawComposioClient } from '@composio/client';
-import { ComposioSensitiveFilePathBlockedError } from '@composio/core';
+import {
+ ComposioBlockedInternalUrlError,
+ ComposioSensitiveFilePathBlockedError,
+} from '@composio/core';
import { schemaHasFileUploadable, uploadToolInputFiles } from 'src/services/tool-file-uploads';
// Schema with a single `file_uploadable` attachment field — mirrors tools like
@@ -130,7 +133,7 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
writeFileSync(file, 'hello');
const createPresignedURL = vi.fn(async () => ({
- new_presigned_url: 'https://s3.example.com/put',
+ new_presigned_url: 'https://1.1.1.1/put',
key: 's3key-123',
}));
const client = makeClient(createPresignedURL);
@@ -164,3 +167,70 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
);
});
});
+
+describe('uploadToolInputFiles — URL SSRF boundary', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it.effect('rejects an unsafe source before requesting an upload destination', () =>
+ Effect.gen(function* () {
+ const fsApi = yield* FileSystem.FileSystem;
+ const pathApi = yield* Path.Path;
+ const createPresignedURL = vi.fn();
+ const client = makeClient(createPresignedURL);
+ const sourceUrl = 'http://169.254.169.254/latest/meta-data/credentials';
+
+ yield* Effect.promise(() =>
+ expect(
+ uploadToolInputFiles({
+ fs: fsApi,
+ path: pathApi,
+ toolSlug: 'GMAIL_SEND_EMAIL',
+ arguments_: { attachment: sourceUrl },
+ inputSchema,
+ client,
+ })
+ ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError)
+ );
+
+ expect(createPresignedURL).not.toHaveBeenCalled();
+ }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
+ );
+
+ it.effect('rejects an unsafe presigned destination before sending file bytes', () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
+ const file = path.join(root, 'document.pdf');
+ writeFileSync(file, 'hello');
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
+ const createPresignedURL = vi.fn(async () => ({
+ new_presigned_url: 'http://127.0.0.1:8080/upload',
+ key: 's3key-123',
+ }));
+
+ return Effect.gen(function* () {
+ const fsApi = yield* FileSystem.FileSystem;
+ const pathApi = yield* Path.Path;
+
+ yield* Effect.promise(() =>
+ expect(
+ uploadToolInputFiles({
+ fs: fsApi,
+ path: pathApi,
+ toolSlug: 'GMAIL_SEND_EMAIL',
+ arguments_: { attachment: file },
+ inputSchema,
+ client: makeClient(createPresignedURL),
+ })
+ ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError)
+ );
+
+ expect(createPresignedURL).toHaveBeenCalledOnce();
+ expect(fetchSpy).not.toHaveBeenCalled();
+ }).pipe(
+ Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
+ Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
+ );
+ });
+});
diff --git a/ts/packages/cli/vitest.config.ts b/ts/packages/cli/vitest.config.ts
index 1fb225d41..c26528400 100644
--- a/ts/packages/cli/vitest.config.ts
+++ b/ts/packages/cli/vitest.config.ts
@@ -14,6 +14,7 @@ export default defineConfig({
'~': path.resolve(__dirname, './'),
src: path.resolve(__dirname, './src'),
test: path.resolve(__dirname, './test'),
+ '@composio/core/utils/ssrf-guard': path.join(coreDir, 'src/utils/ssrfGuard.node.ts'),
'@composio/core/experimental': path.join(coreDir, 'src/experimental/index.ts'),
'@composio/core': path.join(coreDir, 'src/index.ts'),
'@composio/ts-builders': path.join(tsBuildersDir, 'src/index.ts'),
@@ -30,6 +31,7 @@ export default defineConfig({
'#platform': path.join(coreDir, 'src/platform/node.ts'),
'#files': path.join(coreDir, 'src/models/Files.node.ts'),
'#file_tool_modifier': path.join(coreDir, 'src/utils/modifiers/FileToolModifier.node.ts'),
+ '#ssrf_guard': path.join(coreDir, 'src/utils/ssrfGuard.node.ts'),
},
},
test: {
diff --git a/ts/packages/core/package.json b/ts/packages/core/package.json
index 8eb35d275..a6dff4e30 100644
--- a/ts/packages/core/package.json
+++ b/ts/packages/core/package.json
@@ -75,6 +75,24 @@
"types": "./dist/utils/json-schema.d.mts",
"default": "./dist/utils/json-schema.mjs"
},
+ "./utils/ssrf-guard": {
+ "workerd": {
+ "types": "./dist/utils/ssrfGuard.workerd.d.mts",
+ "default": "./dist/utils/ssrfGuard.workerd.mjs"
+ },
+ "edge-light": {
+ "types": "./dist/utils/ssrfGuard.workerd.d.mts",
+ "default": "./dist/utils/ssrfGuard.workerd.mjs"
+ },
+ "node": {
+ "types": "./dist/utils/ssrfGuard.node.d.mts",
+ "default": "./dist/utils/ssrfGuard.node.mjs"
+ },
+ "default": {
+ "types": "./dist/utils/ssrfGuard.node.d.mts",
+ "default": "./dist/utils/ssrfGuard.node.mjs"
+ }
+ },
"./generated": {
"types": "./generated/index.d.ts",
"default": "./generated/index.js"
diff --git a/ts/packages/core/src/utils/pinnedDispatcher.node.ts b/ts/packages/core/src/utils/pinnedDispatcher.node.ts
index 632fef014..e573210ad 100644
--- a/ts/packages/core/src/utils/pinnedDispatcher.node.ts
+++ b/ts/packages/core/src/utils/pinnedDispatcher.node.ts
@@ -1,4 +1,7 @@
import { isIP } from 'node:net';
+import { request as httpRequest } from 'node:http';
+import { request as httpsRequest } from 'node:https';
+import { Readable } from 'node:stream';
import type { Agent } from 'undici';
/**
@@ -36,6 +39,37 @@ const GLOBAL_DISPATCHER_SYMBOLS = [
let undici: Promise<typeof import('undici')> | undefined;
const loadUndici = (): Promise<typeof import('undici')> => (undici ??= import('undici'));
+const lookupPinnedAddresses = (
+ addresses: ReadonlyArray<string>,
+ options: { all?: boolean },
+ callback: (
+ error: NodeJS.ErrnoException | null,
+ address: string | Array<{ address: string; family: number }>,
+ family?: number
+ ) => void
+) => {
+ if (options.all) {
+ callback(
+ null,
+ addresses.map(address => ({ address, family: isIP(address) }))
+ );
+ return;
+ }
+
+ const [address] = addresses;
+ callback(null, address, isIP(address));
+};
+
+const knownBodyLength = (body: BodyInit | null | undefined): number | undefined => {
+ if (body === null || body === undefined) return undefined;
+ if (typeof body === 'string') return new TextEncoder().encode(body).byteLength;
+ if (body instanceof URLSearchParams) return new TextEncoder().encode(body.toString()).byteLength;
+ if (body instanceof ArrayBuffer) return body.byteLength;
+ if (ArrayBuffer.isView(body)) return body.byteLength;
+ if (body instanceof Blob) return body.size;
+ return undefined;
+};
+
/**
* A `fetch` dispatcher that connects to `addresses` instead of resolving the
* hostname again.
@@ -71,24 +105,86 @@ export const createPinnedDispatcher = async (addresses: ReadonlyArray<string>):
// off, or a `family`/`localAddress` was requested. Answering in the
// wrong shape is rejected as an invalid address, which would fail
// every pinned fetch in such a process.
- if (options.all) {
- // All of them, in resolver order: handing over a single address of a
- // dual-stack host would strand callers whose network cannot reach
- // that family, where the runtime would otherwise have fallen back.
- callback(
- null,
- addresses.map(address => ({ address, family: isIP(address) }))
- );
- return;
- }
-
- const [address] = addresses;
- callback(null, address, isIP(address));
+ lookupPinnedAddresses(addresses, options, callback);
},
},
});
};
+/**
+ * Fetch through the Node-compatible HTTP client while pinning DNS resolution.
+ *
+ * Bun implements the Node HTTP client and its `lookup` hook, but its native
+ * `fetch` ignores undici's `dispatcher` option. This transport preserves the
+ * original hostname for Host and TLS SNI while making the socket use an
+ * address that the SSRF guard already validated.
+ */
+export const pinnedHttpFetch = async (
+ rawUrl: string,
+ init: RequestInit,
+ addresses: ReadonlyArray<string>
+): Promise<Response> => {
+ const normalized = new Request(rawUrl, init);
+ const url = new URL(rawUrl);
+ const request = url.protocol === 'https:' ? httpsRequest : httpRequest;
+ const headers = new Headers(normalized.headers);
+ const bodyLength = knownBodyLength(init.body);
+ if (bodyLength !== undefined && !headers.has('content-length')) {
+ headers.set('content-length', String(bodyLength));
+ }
+
+ return new Promise<Response>((resolve, reject) => {
+ const outgoing = request(
+ url,
+ {
+ method: normalized.method,
+ headers: Object.fromEntries(headers.entries()),
+ signal: normalized.signal,
+ lookup: (_hostname, options, callback) =>
+ lookupPinnedAddresses(addresses, options, callback),
+ },
+ incoming => {
+ const headers = new Headers();
+ for (let index = 0; index < incoming.rawHeaders.length; index += 2) {
+ headers.append(incoming.rawHeaders[index], incoming.rawHeaders[index + 1]);
+ }
+
+ const status = incoming.statusCode ?? 500;
+ const body = [101, 103, 204, 205, 304].includes(status)
+ ? null
+ : (Readable.toWeb(incoming) as ReadableStream<Uint8Array>);
+ resolve(
+ new Response(body, {
+ status,
+ statusText: incoming.statusMessage,
+ headers,
+ })
+ );
+ }
+ );
+
+ outgoing.once('error', reject);
+
+ void (async () => {
+ try {
+ if (normalized.body) {
+ const reader = normalized.body.getReader();
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (!outgoing.write(value)) {
+ await new Promise<void>(resolveDrain => outgoing.once('drain', resolveDrain));
+ }
+ }
+ }
+ outgoing.end();
+ } catch (error) {
+ outgoing.destroy(error instanceof Error ? error : new Error(String(error)));
+ }
+ })();
+ });
+};
+
/**
* Whether the process-wide dispatcher `fetch` falls back to (when a request
* carries no `dispatcher` of its own) is something other than a stock `Agent`.
diff --git a/ts/packages/core/src/utils/ssrfGuard.node.ts b/ts/packages/core/src/utils/ssrfGuard.node.ts
index 1a941deff..28659925a 100644
--- a/ts/packages/core/src/utils/ssrfGuard.node.ts
+++ b/ts/packages/core/src/utils/ssrfGuard.node.ts
@@ -1,7 +1,11 @@
import { lookup } from 'node:dns/promises'; // we're in a Node.js-specific module
import { isIP } from 'node:net';
import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
-import { createPinnedDispatcher, hasCustomGlobalDispatcher } from './pinnedDispatcher.node';
+import {
+ createPinnedDispatcher,
+ hasCustomGlobalDispatcher,
+ pinnedHttpFetch,
+} from './pinnedDispatcher.node';
/**
* SSRF guard for user-supplied URL file inputs.
@@ -26,7 +30,8 @@ import { createPinnedDispatcher, hasCustomGlobalDispatcher } from './pinnedDispa
* Residual: a hop whose effective dispatcher is a configured route — a
* caller-supplied `init.dispatcher`, a non-stock global dispatcher (a
* `ProxyAgent` or `EnvHttpProxyAgent` installed via `setGlobalDispatcher`), or
- * the runtime's env-proxy mode (`NODE_USE_ENV_PROXY`) — keeps only the
+ * the runtime's env-proxy mode (automatic on Bun, opt-in via
+ * `NODE_USE_ENV_PROXY` on Node) — keeps only the
* pre-flight validation. Pinning would dial the validated address instead of
* the proxy, and the proxy resolves the hostname itself where the SDK cannot
* see or pin that resolution. The Python guard carries the same residual for
@@ -37,17 +42,18 @@ const MAX_REDIRECTS = 5;
/**
* Whether the runtime would route `url` through an env proxy the SDK cannot
- * see into. Only meaningful when `NODE_USE_ENV_PROXY` opts the built-in
- * `fetch` into env proxies (Node >= 24); without that flag the runtime's
- * `fetch` ignores `HTTP_PROXY`/`HTTPS_PROXY` entirely, so mirroring Python's
- * bare env-var check would drop pinning for users whose fetch never proxied.
+ * see into. Bun honors proxy environment variables automatically. Node's
+ * built-in `fetch` requires the `NODE_USE_ENV_PROXY` opt-in (Node >= 24), so
+ * a bare env-var check on Node would drop pinning for users whose fetch never
+ * proxied.
*
* `NO_PROXY=*` is the one bypass honored precisely (nothing is proxied, so
* pinning is safe again); per-host `NO_PROXY` entries are treated
* conservatively as proxied rather than parsed.
*/
-const envProxyApplies = (url: URL): boolean => {
- const useEnvProxy = ['1', 'true'].includes((process.env.NODE_USE_ENV_PROXY ?? '').toLowerCase());
+const envProxyApplies = (url: URL, isBun: boolean): boolean => {
+ const useEnvProxy =
+ isBun || ['1', 'true'].includes((process.env.NODE_USE_ENV_PROXY ?? '').toLowerCase());
if (!useEnvProxy) return false;
if ((process.env.NO_PROXY ?? process.env.no_proxy ?? '') === '*') return false;
const schemeVar = url.protocol === 'https:' ? 'HTTPS_PROXY' : 'HTTP_PROXY';
@@ -230,6 +236,7 @@ export const ssrfSafeFetch = async (
for (let hop = 0; hop <= maxRedirects; hop++) {
const addresses = await assertSafeFetchTarget(currentUrl);
+ const isBun = typeof process.versions.bun === 'string';
// Pinning replaces the connect target; through a configured route that
// would dial the validated origin instead of the route's next hop (the
@@ -237,20 +244,25 @@ export const ssrfSafeFetch = async (
const callerDispatcher = (init as RequestInit & { dispatcher?: unknown }).dispatcher;
const respectConfiguredRoute =
callerDispatcher !== undefined ||
- envProxyApplies(new URL(currentUrl)) ||
+ envProxyApplies(new URL(currentUrl), isBun) ||
hasCustomGlobalDispatcher();
- const dispatcher = respectConfiguredRoute ? undefined : await createPinnedDispatcher(addresses);
+ const dispatcher =
+ respectConfiguredRoute || isBun ? undefined : await createPinnedDispatcher(addresses);
let response: Response;
try {
- // `dispatcher` is a Node-only extension to `RequestInit`.
- response = await fetch(
- currentUrl,
- (dispatcher === undefined
- ? { ...init, redirect: 'manual' }
- : { ...init, redirect: 'manual', dispatcher }) as RequestInit
- );
+ if (isBun && !respectConfiguredRoute) {
+ response = await pinnedHttpFetch(currentUrl, { ...init, 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
+ );
+ }
} catch (error) {
if (dispatcher !== undefined) {
await dispatcher.close().catch(() => undefined);
diff --git a/ts/packages/core/src/utils/ssrfGuard.workerd.ts b/ts/packages/core/src/utils/ssrfGuard.workerd.ts
index 81a897baa..eb0519427 100644
--- a/ts/packages/core/src/utils/ssrfGuard.workerd.ts
+++ b/ts/packages/core/src/utils/ssrfGuard.workerd.ts
@@ -5,7 +5,11 @@ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
* hostname is publicly routable before connecting. Fail closed instead of
* falling back to an unguarded fetch.
*/
-export const ssrfSafeFetch = async (rawUrl: string): Promise<Response> => {
+export const ssrfSafeFetch = async (
+ rawUrl: string,
+ _init: RequestInit = {},
+ _maxRedirects?: number
+): Promise<Response> => {
throw new ComposioBlockedInternalUrlError(
'URL file uploads are not supported in edge runtimes because the destination cannot be safely validated',
{
diff --git a/ts/packages/core/test/utils/pinnedDispatcher.node.test.ts b/ts/packages/core/test/utils/pinnedDispatcher.node.test.ts
index 7629b1c45..61e6cf424 100644
--- a/ts/packages/core/test/utils/pinnedDispatcher.node.test.ts
+++ b/ts/packages/core/test/utils/pinnedDispatcher.node.test.ts
@@ -5,6 +5,7 @@ import { Agent, ProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'und
import {
createPinnedDispatcher,
hasCustomGlobalDispatcher,
+ pinnedHttpFetch,
} from '../../src/utils/pinnedDispatcher.node';
/**
@@ -97,6 +98,68 @@ describe('createPinnedDispatcher', () => {
});
});
+describe('pinnedHttpFetch', () => {
+ let server: Server | undefined;
+
+ afterEach(async () => {
+ if (server) {
+ await new Promise<void>(resolve => server!.close(() => resolve()));
+ server = undefined;
+ }
+ });
+
+ it('connects to a validated address while preserving the original host', async () => {
+ let receivedHost = '';
+ let receivedBody = '';
+ let receivedContentLength = '';
+ server = createServer((request, response) => {
+ receivedHost = request.headers.host ?? '';
+ receivedContentLength = request.headers['content-length'] ?? '';
+ request.setEncoding('utf8');
+ request.on('data', chunk => {
+ receivedBody += chunk;
+ });
+ request.on('end', () => {
+ response.writeHead(200, { 'content-type': 'text/plain' });
+ response.end('pinned payload');
+ });
+ });
+ await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));
+ const port = (server.address() as AddressInfo).port;
+
+ const response = await pinnedHttpFetch(
+ `http://pinned.invalid:${port}/payload`,
+ { method: 'PUT', body: 'upload body' },
+ ['127.0.0.1']
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.text()).toBe('pinned payload');
+ expect(receivedHost).toBe(`pinned.invalid:${port}`);
+ expect(receivedBody).toBe('upload body');
+ expect(receivedContentLength).toBe('11');
+ });
+
+ it('does not add Content-Length to a request without a body', async () => {
+ let receivedContentLength: string | undefined;
+ server = createServer((request, response) => {
+ receivedContentLength = request.headers['content-length'];
+ response.end('ok');
+ });
+ await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));
+ const port = (server.address() as AddressInfo).port;
+
+ const response = await pinnedHttpFetch(
+ `http://pinned.invalid:${port}/payload`,
+ { method: 'GET' },
+ ['127.0.0.1']
+ );
+
+ expect(await response.text()).toBe('ok');
+ expect(receivedContentLength).toBeUndefined();
+ });
+});
+
describe('hasCustomGlobalDispatcher', () => {
it('reports the stock dispatcher as not custom', () => {
expect(hasCustomGlobalDispatcher()).toBe(false);
diff --git a/ts/packages/core/test/utils/ssrfGuard.test.ts b/ts/packages/core/test/utils/ssrfGuard.test.ts
index 65ecd1f43..f73c35f24 100644
--- a/ts/packages/core/test/utils/ssrfGuard.test.ts
+++ b/ts/packages/core/test/utils/ssrfGuard.test.ts
@@ -9,15 +9,18 @@ vi.mock('node:dns/promises', () => ({
vi.mock('../../src/utils/pinnedDispatcher.node', () => ({
createPinnedDispatcher: vi.fn(() => Promise.resolve({ close: () => Promise.resolve() })),
hasCustomGlobalDispatcher: vi.fn(() => false),
+ pinnedHttpFetch: vi.fn(),
}));
import {
createPinnedDispatcher,
hasCustomGlobalDispatcher,
+ pinnedHttpFetch,
} from '../../src/utils/pinnedDispatcher.node';
const mockCreatePinnedDispatcher = vi.mocked(createPinnedDispatcher);
const mockHasCustomGlobalDispatcher = vi.mocked(hasCustomGlobalDispatcher);
+const mockPinnedHttpFetch = vi.mocked(pinnedHttpFetch);
// eslint-disable-next-line no-restricted-imports
import { lookup } from 'node:dns/promises';
@@ -133,6 +136,7 @@ describe('ssrfSafeFetch', () => {
mockFetch.mockReset();
mockCreatePinnedDispatcher.mockClear();
mockHasCustomGlobalDispatcher.mockReturnValue(false);
+ mockPinnedHttpFetch.mockReset();
// Deterministic even on machines that carry the runtime env-proxy opt-in.
vi.stubEnv('NODE_USE_ENV_PROXY', '');
vi.stubGlobal('fetch', mockFetch);
@@ -222,6 +226,34 @@ describe('ssrfSafeFetch', () => {
expect(mockCreatePinnedDispatcher).toHaveBeenCalledWith(['93.184.216.34']);
});
+ it('keeps Bun fetch on an explicitly configured environment proxy', async () => {
+ resolvesTo('93.184.216.34');
+ mockFetch.mockResolvedValue(new Response('data', { status: 200 }));
+ vi.stubEnv('HTTPS_PROXY', 'http://proxy.example:3128');
+ vi.stubEnv('NO_PROXY', '');
+ const bunDescriptor = Object.getOwnPropertyDescriptor(process.versions, 'bun');
+ Object.defineProperty(process.versions, 'bun', {
+ configurable: true,
+ value: '1.4.0',
+ });
+
+ try {
+ await ssrfSafeFetch('https://example.com/file.pdf');
+ } finally {
+ if (bunDescriptor) {
+ Object.defineProperty(process.versions, 'bun', bunDescriptor);
+ } else {
+ delete (process.versions as NodeJS.ProcessVersions & { bun?: string }).bun;
+ }
+ }
+
+ expect(mockPinnedHttpFetch).not.toHaveBeenCalled();
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://example.com/file.pdf',
+ expect.objectContaining({ redirect: 'manual' })
+ );
+ });
+
it('validates and fetches a public URL', async () => {
resolvesTo('93.184.216.34');
const ok = new Response('data', { status: 200 });