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(core): secure Tool Router session URL uploads (#3900)

Shrey Singla2f63fe540775
diff --git a/.changeset/secure-session-url-uploads.md b/.changeset/secure-session-url-uploads.md
new file mode 100644
index 000000000..891eaca44
--- /dev/null
+++ b/.changeset/secure-session-url-uploads.md
@@ -0,0 +1,5 @@
+---
+'@composio/core': patch
+---
+
+Guard Tool Router session URL uploads against SSRF, revalidate redirect targets, and enforce a streamed 100 MiB response limit across TypeScript URL upload paths.
diff --git a/ts/packages/core/package.json b/ts/packages/core/package.json
index 111ca0ee6..352e1483b 100644
--- a/ts/packages/core/package.json
+++ b/ts/packages/core/package.json
@@ -33,6 +33,12 @@
"edge-light": "./dist/utils/config-defaults/ConfigDefaults.workerd.mjs",
"node": "./dist/utils/config-defaults/ConfigDefaults.node.mjs",
"default": "./dist/utils/config-defaults/ConfigDefaults.node.mjs"
+ },
+ "#ssrf_guard": {
+ "workerd": "./dist/utils/ssrfGuard.workerd.mjs",
+ "edge-light": "./dist/utils/ssrfGuard.workerd.mjs",
+ "node": "./dist/utils/ssrfGuard.node.mjs",
+ "default": "./dist/utils/ssrfGuard.node.mjs"
}
},
"exports": {
diff --git a/ts/packages/core/src/errors/SsrfErrors.ts b/ts/packages/core/src/errors/SsrfErrors.ts
index 42ba64521..70e395182 100644
--- a/ts/packages/core/src/errors/SsrfErrors.ts
+++ b/ts/packages/core/src/errors/SsrfErrors.ts
@@ -14,9 +14,10 @@ export interface ComposioBlockedInternalUrlErrorOptions extends Omit<ComposioErr
/**
* Thrown when a URL file input resolves to a private, loopback, link-local, or
* otherwise internal address, or points at a non-http(s) scheme. Guards against
- * turning `composio.files.upload(url)` (and automatic upload during tool
- * execution) into a server-side request forgery (SSRF) probe of internal
- * infrastructure such as cloud metadata endpoints (`169.254.169.254`).
+ * turning URL-based file uploads (including Tool Router session files and
+ * automatic upload during tool execution) into a server-side request forgery
+ * (SSRF) probe of internal infrastructure such as cloud metadata endpoints
+ * (`169.254.169.254`).
*/
export class ComposioBlockedInternalUrlError extends ComposioError {
constructor(
diff --git a/ts/packages/core/src/models/ToolRouterSessionFileMount.ts b/ts/packages/core/src/models/ToolRouterSessionFileMount.ts
index a28c036a8..4284e36a1 100644
--- a/ts/packages/core/src/models/ToolRouterSessionFileMount.ts
+++ b/ts/packages/core/src/models/ToolRouterSessionFileMount.ts
@@ -18,7 +18,9 @@ import {
import { RemoteFile } from './RemoteFile';
import { ValidationError } from '../errors';
import { platform } from '#platform';
+import { ssrfSafeFetch } from '#ssrf_guard';
import { getExtensionFromMimeType } from '../utils/mime';
+import { readResponseBodyWithLimit } from '../utils/readResponseBody';
import { getRandomShortId } from '../utils/uuid';
/**
@@ -110,11 +112,11 @@ export class ToolRouterSessionFilesMount {
): Promise<{ fileToUpload: File; remotePath: string; mimetype: string }> {
if (typeof input === 'string') {
if (input.startsWith('http://') || input.startsWith('https://')) {
- const response = await fetch(input);
+ const response = await ssrfSafeFetch(input);
if (!response.ok) {
throw new Error(`Failed to fetch file from URL: ${response.statusText}`);
}
- const arrayBuffer = await response.arrayBuffer();
+ const content = await readResponseBodyWithLimit(response);
const rawContentType = response.headers.get('content-type') || 'application/octet-stream';
const mimeType = rawContentType.split(';')[0].trim();
const url = new URL(input);
@@ -125,7 +127,7 @@ export class ToolRouterSessionFilesMount {
const extension = getExtensionFromMimeType(mimeType);
filename = `${getRandomShortId()}.${extension}`;
}
- const file = new File([arrayBuffer], filename, { type: mimeType });
+ const file = new File([content as BlobPart], filename, { type: mimeType });
return {
fileToUpload: file,
remotePath: options.remotePath ?? filename,
@@ -178,6 +180,8 @@ export class ToolRouterSessionFilesMount {
*
* Accepts a file path (local or URL), a native File object, or a raw buffer.
* The file is stored in the virtual filesystem associated with the tool router session.
+ * URL inputs require a Node.js or Bun runtime so the destination can be DNS-validated;
+ * edge runtimes must fetch the file themselves and pass a File or ArrayBuffer.
*
* @param input - File path (string), native File, or raw buffer (ArrayBuffer | Uint8Array).
* @param options - Optional configuration. When passing a buffer, remotePath is required.
diff --git a/ts/packages/core/src/utils/fileUtils.node.ts b/ts/packages/core/src/utils/fileUtils.node.ts
index 6c30e7753..50a00dbf3 100644
--- a/ts/packages/core/src/utils/fileUtils.node.ts
+++ b/ts/packages/core/src/utils/fileUtils.node.ts
@@ -10,6 +10,7 @@ import type { FileDownloadData, FileUploadData } from '../types/files.types';
import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths';
import { assertPathInsideUploadDirs } from './uploadDirAllowlist.node';
import { ssrfSafeFetch } from './ssrfGuard.node';
+import { readResponseBodyWithLimit } from './readResponseBody';
/**
* Options for {@link getFileDataAfterUploadingToS3} (S3 presigned upload from local path, URL, or File).
@@ -177,8 +178,7 @@ const readFileContentFromURL = async (
if (!response.ok) {
throw new Error(`Failed to fetch file: ${response.statusText}`);
}
- const arrayBuffer = await response.arrayBuffer();
- const content = new Uint8Array(arrayBuffer);
+ const content = await readResponseBodyWithLimit(response);
const mimeType = response.headers.get('content-type') || 'application/octet-stream';
// Extract clean filename from URL, removing query parameters
diff --git a/ts/packages/core/src/utils/readResponseBody.ts b/ts/packages/core/src/utils/readResponseBody.ts
new file mode 100644
index 000000000..697d6ad12
--- /dev/null
+++ b/ts/packages/core/src/utils/readResponseBody.ts
@@ -0,0 +1,63 @@
+/** Maximum size accepted for files fetched from user-supplied URLs (100 MiB). */
+export const MAX_URL_UPLOAD_SIZE_BYTES = 100 * 1024 * 1024;
+
+const sizeLimitError = (actualSize: number, maxBytes: number): Error =>
+ new Error(`File size (${actualSize} bytes) exceeds maximum allowed size (${maxBytes} bytes)`);
+
+/**
+ * Read a fetch response without allowing an untrusted server to exhaust memory.
+ *
+ * `Content-Length` is checked as an early rejection, but the streamed byte
+ * count is authoritative because the header can be absent or dishonest.
+ */
+export const readResponseBodyWithLimit = async (
+ response: Response,
+ maxBytes: number = MAX_URL_UPLOAD_SIZE_BYTES
+): Promise<Uint8Array> => {
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
+ throw new RangeError('maxBytes must be a non-negative safe integer');
+ }
+
+ const contentLength = response.headers.get('content-length')?.trim();
+ if (contentLength && /^\d+$/.test(contentLength)) {
+ const declaredSize = Number(contentLength);
+ if (!Number.isSafeInteger(declaredSize) || declaredSize > maxBytes) {
+ const error = sizeLimitError(declaredSize, maxBytes);
+ await response.body?.cancel(error).catch(() => undefined);
+ throw error;
+ }
+ }
+
+ if (!response.body) {
+ return new Uint8Array();
+ }
+
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let totalBytes = 0;
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (!value || value.byteLength === 0) continue;
+
+ totalBytes += value.byteLength;
+ if (totalBytes > maxBytes) {
+ await reader.cancel(sizeLimitError(totalBytes, maxBytes));
+ throw sizeLimitError(totalBytes, maxBytes);
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ const body = new Uint8Array(totalBytes);
+ let offset = 0;
+ for (const chunk of chunks) {
+ body.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return body;
+};
diff --git a/ts/packages/core/src/utils/ssrfGuard.node.ts b/ts/packages/core/src/utils/ssrfGuard.node.ts
index 728a65e82..23ed3ef89 100644
--- a/ts/packages/core/src/utils/ssrfGuard.node.ts
+++ b/ts/packages/core/src/utils/ssrfGuard.node.ts
@@ -5,12 +5,12 @@ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
/**
* SSRF guard for user-supplied URL file inputs.
*
- * `composio.files.upload(url)` and automatic file upload during tool execution
- * fetch arbitrary user-provided URLs. Without a guard, a caller (or a tool
- * argument produced by an LLM) can point the SDK at internal infrastructure —
- * loopback, RFC1918 ranges, link-local cloud-metadata endpoints
- * (`169.254.169.254`), or a public URL that 3xx-redirects into internal space —
- * turning the SDK into a server-side request forgery probe.
+ * `composio.files.upload(url)`, Tool Router session file uploads, and automatic
+ * file upload during tool execution fetch arbitrary user-provided URLs. Without
+ * a guard, a caller (or a tool argument produced by an LLM) can point the SDK at
+ * internal infrastructure — loopback, RFC1918 ranges, link-local cloud-metadata
+ * endpoints (`169.254.169.254`), or a public URL that 3xx-redirects into internal
+ * space — turning the SDK into a server-side request forgery probe.
*
* This module validates the *resolved* address (not just the hostname string,
* which defeats decimal/octal/hex IP obfuscation) before every fetch, and
diff --git a/ts/packages/core/src/utils/ssrfGuard.workerd.ts b/ts/packages/core/src/utils/ssrfGuard.workerd.ts
new file mode 100644
index 000000000..ab78fc2ac
--- /dev/null
+++ b/ts/packages/core/src/utils/ssrfGuard.workerd.ts
@@ -0,0 +1,19 @@
+import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
+
+/**
+ * Edge runtimes do not expose the DNS resolution APIs needed to prove that a
+ * hostname is publicly routable before connecting. Fail closed instead of
+ * falling back to an unguarded fetch.
+ */
+export const ssrfSafeFetch = async (rawUrl: string): Promise<Response> => {
+ throw new ComposioBlockedInternalUrlError(
+ 'URL file uploads are not supported in edge runtimes because the destination cannot be safely validated',
+ {
+ url: rawUrl,
+ possibleFixes: [
+ 'Fetch the public URL yourself and pass a File or ArrayBuffer instead',
+ 'Run the URL upload in a Node.js or Bun runtime',
+ ],
+ }
+ );
+};
diff --git a/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts b/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts
index 609fff65d..7d555f004 100644
--- a/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts
+++ b/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts
@@ -1,8 +1,17 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ToolRouterSessionFilesMount } from '../../src/models/ToolRouterSessionFileMount';
-import { ValidationError } from '../../src/errors';
+import { ComposioBlockedInternalUrlError, ValidationError } from '../../src/errors';
import { DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID } from '../../src/utils/constants';
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn(),
+}));
+
+// eslint-disable-next-line no-restricted-imports
+import { lookup } from 'node:dns/promises';
+
+const mockLookup = vi.mocked(lookup);
+
const sessionId = 'trs_session_123';
const createMockClient = () => ({
@@ -24,6 +33,7 @@ describe('ToolRouterSessionFilesMount', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mockLookup.mockReset();
mockClient = createMockClient();
filesMount = new ToolRouterSessionFilesMount(mockClient as any, sessionId);
});
@@ -209,12 +219,97 @@ describe('ToolRouterSessionFilesMount', () => {
};
beforeEach(() => {
- globalThis.fetch = vi.fn().mockImplementation((url: string, init?: RequestInit) => {
- if (init?.method === 'PUT') {
- return Promise.resolve({ ok: true });
- }
- return Promise.reject(new Error('Unexpected fetch'));
- }) as unknown as typeof fetch;
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockImplementation((_url: string, init?: RequestInit) => {
+ if (init?.method === 'PUT') {
+ return Promise.resolve({ ok: true });
+ }
+ return Promise.reject(new Error('Unexpected fetch'));
+ })
+ );
+ });
+
+ afterEach(() => vi.unstubAllGlobals());
+
+ it.each([
+ ['loopback', 'http://127.0.0.1/private', '127.0.0.1'],
+ ['cloud metadata', 'http://169.254.169.254/latest/meta-data/', '169.254.169.254'],
+ ])('should block %s URL uploads before fetching', async (_label, url, address) => {
+ mockLookup.mockResolvedValueOnce([{ address, family: 4 }] as never);
+
+ await expect(filesMount.upload(url)).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);
+
+ expect(fetch).not.toHaveBeenCalled();
+ expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
+ expect(mockClient.toolRouter.session.files.createDownloadURL).not.toHaveBeenCalled();
+ });
+
+ it('should block a public URL that redirects to cloud metadata', async () => {
+ mockLookup
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }] as never)
+ .mockResolvedValueOnce([{ address: '169.254.169.254', family: 4 }] as never);
+ vi.mocked(fetch).mockResolvedValueOnce(
+ new Response(null, {
+ status: 302,
+ headers: { location: 'http://169.254.169.254/latest/meta-data/' },
+ })
+ );
+
+ await expect(filesMount.upload('https://public.example/redirect')).rejects.toBeInstanceOf(
+ ComposioBlockedInternalUrlError
+ );
+
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
+ });
+
+ it('should fetch and upload a public URL through the SSRF-safe path', async () => {
+ mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
+ vi.mocked(fetch)
+ .mockResolvedValueOnce(
+ new Response('hello', {
+ status: 200,
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
+ })
+ )
+ .mockResolvedValueOnce(new Response(null, { status: 200 }));
+ mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
+ ...createUploadURLResponse,
+ mount_relative_path: 'hello.txt',
+ });
+ mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
+ ...createDownloadURLResponse,
+ mount_relative_path: 'hello.txt',
+ });
+
+ const result = await filesMount.upload('https://files.example/hello.txt');
+
+ expect(fetch).toHaveBeenNthCalledWith(
+ 1,
+ 'https://files.example/hello.txt',
+ expect.objectContaining({ redirect: 'manual' })
+ );
+ expect(result.mountRelativePath).toBe('hello.txt');
+ });
+
+ it('should reject a URL response whose declared size exceeds 100 MiB', async () => {
+ mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
+ vi.mocked(fetch).mockResolvedValueOnce(
+ new Response('small body', {
+ status: 200,
+ headers: {
+ 'content-type': 'text/plain',
+ 'content-length': String(100 * 1024 * 1024 + 1),
+ },
+ })
+ );
+
+ await expect(filesMount.upload('https://files.example/oversized.txt')).rejects.toThrow(
+ 'exceeds maximum allowed size'
+ );
+
+ expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
});
it('should upload local file and return RemoteFile', async () => {
diff --git a/ts/packages/core/test/utils/fileUtils.test.ts b/ts/packages/core/test/utils/fileUtils.test.ts
index 50d56c970..e33db5d47 100644
--- a/ts/packages/core/test/utils/fileUtils.test.ts
+++ b/ts/packages/core/test/utils/fileUtils.test.ts
@@ -53,6 +53,12 @@ vi.mock('node:dns/promises', () => ({
const mockFetch = vi.fn();
global.fetch = mockFetch;
+const fetchedFileResponse = (contentType: string = 'application/pdf') =>
+ new Response(new Uint8Array(10), {
+ status: 200,
+ headers: { 'content-type': contentType },
+ });
+
describe('fileUtils', () => {
let mockClient: ComposioClient;
@@ -76,11 +82,7 @@ describe('fileUtils', () => {
describe('URL filename generation with query parameters', () => {
beforeEach(() => {
// Mock successful fetch response
- mockFetch.mockResolvedValue({
- ok: true,
- arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
- headers: new Map([['content-type', 'application/pdf']]),
- });
+ mockFetch.mockResolvedValue(fetchedFileResponse());
// Mock successful S3 upload
(mockClient.files.createPresignedURL as any).mockResolvedValue({
@@ -95,11 +97,7 @@ describe('fileUtils', () => {
return Promise.resolve({ ok: true });
}
// For the initial file fetch
- return Promise.resolve({
- ok: true,
- arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
- headers: new Map([['content-type', 'application/pdf']]),
- });
+ return Promise.resolve(fetchedFileResponse());
});
});
@@ -155,6 +153,29 @@ describe('fileUtils', () => {
expect(result.name).toBe('file_ts1640995200000abc12345.pdf');
});
+
+ it('should reject an oversized URL response before requesting an upload URL', async () => {
+ mockFetch.mockReset();
+ mockFetch.mockResolvedValueOnce(
+ new Response('small body', {
+ status: 200,
+ headers: {
+ 'content-type': 'application/pdf',
+ 'content-length': String(100 * 1024 * 1024 + 1),
+ },
+ })
+ );
+
+ await expect(
+ getFileDataAfterUploadingToS3('https://example.com/oversized.pdf', {
+ toolSlug: 'test-tool',
+ toolkitSlug: 'test-toolkit',
+ client: mockClient,
+ })
+ ).rejects.toThrow('exceeds maximum allowed size');
+
+ expect(mockClient.files.createPresignedURL).not.toHaveBeenCalled();
+ });
});
describe('MIME type extension handling', () => {
@@ -175,11 +196,7 @@ describe('fileUtils', () => {
vi.clearAllMocks();
// Mock successful fetch response
- mockFetch.mockResolvedValueOnce({
- ok: true,
- arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
- headers: new Map([['content-type', mimeType]]),
- });
+ mockFetch.mockResolvedValueOnce(fetchedFileResponse(mimeType));
// Mock successful S3 upload
(mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
@@ -205,11 +222,7 @@ describe('fileUtils', () => {
// Reset mocks
vi.clearAllMocks();
- mockFetch.mockResolvedValueOnce({
- ok: true,
- arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
- headers: new Map([['content-type', 'text/plain; charset=utf-8']]),
- });
+ mockFetch.mockResolvedValueOnce(fetchedFileResponse('text/plain; charset=utf-8'));
// Mock successful S3 upload
(mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
@@ -244,11 +257,7 @@ describe('fileUtils', () => {
// Reset mocks for each iteration
vi.clearAllMocks();
- mockFetch.mockResolvedValueOnce({
- ok: true,
- arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
- headers: new Map([['content-type', mimeType]]),
- });
+ mockFetch.mockResolvedValueOnce(fetchedFileResponse(mimeType));
// Mock successful S3 upload
(mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
@@ -274,11 +283,7 @@ describe('fileUtils', () => {
// Reset mocks
vi.clearAllMocks();
- mockFetch.mockResolvedValueOnce({
- ok: true,
- arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
- headers: new Map([['content-type', 'application/custom-format']]),
- });
+ mockFetch.mockResolvedValueOnce(fetchedFileResponse('application/custom-format'));
// Mock successful S3 upload
(mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
@@ -472,11 +477,7 @@ describe('fileUtils', () => {
});
it('should handle S3 upload errors', async () => {
- mockFetch.mockResolvedValueOnce({
- ok: true,
- arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
- headers: new Map([['content-type', 'application/pdf']]),
- });
+ mockFetch.mockResolvedValueOnce(fetchedFileResponse());
(mockClient.files.createPresignedURL as any).mockResolvedValue({
key: 'test-key',
diff --git a/ts/packages/core/test/utils/readResponseBody.test.ts b/ts/packages/core/test/utils/readResponseBody.test.ts
new file mode 100644
index 000000000..dc03d2ec7
--- /dev/null
+++ b/ts/packages/core/test/utils/readResponseBody.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it, vi } from 'vitest';
+import { readResponseBodyWithLimit } from '../../src/utils/readResponseBody';
+
+describe('readResponseBodyWithLimit', () => {
+ it('rejects an oversized Content-Length before reading the body', async () => {
+ const cancel = vi.fn();
+ const response = new Response(new ReadableStream({ cancel }), {
+ headers: { 'content-length': '5' },
+ });
+
+ await expect(readResponseBodyWithLimit(response, 4)).rejects.toThrow(
+ 'exceeds maximum allowed size'
+ );
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(response.bodyUsed).toBe(true);
+ });
+
+ it('rejects and cancels a stream that exceeds the limit without a size header', async () => {
+ const cancel = vi.fn();
+ const response = new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new Uint8Array([1, 2, 3]));
+ controller.enqueue(new Uint8Array([4, 5]));
+ },
+ cancel,
+ })
+ );
+
+ await expect(readResponseBodyWithLimit(response, 4)).rejects.toThrow(
+ 'exceeds maximum allowed size'
+ );
+ expect(cancel).toHaveBeenCalledOnce();
+ });
+
+ it('accepts a body exactly at the limit', async () => {
+ const response = new Response(new Uint8Array([1, 2, 3, 4]), {
+ headers: { 'content-length': '4' },
+ });
+
+ await expect(readResponseBodyWithLimit(response, 4)).resolves.toEqual(
+ new Uint8Array([1, 2, 3, 4])
+ );
+ });
+
+ it('rejects invalid limits', async () => {
+ await expect(readResponseBodyWithLimit(new Response(), -1)).rejects.toThrow(RangeError);
+ });
+});
diff --git a/ts/packages/core/test/utils/ssrfGuard.workerd.test.ts b/ts/packages/core/test/utils/ssrfGuard.workerd.test.ts
new file mode 100644
index 000000000..ce0d760db
--- /dev/null
+++ b/ts/packages/core/test/utils/ssrfGuard.workerd.test.ts
@@ -0,0 +1,17 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ComposioBlockedInternalUrlError } from '../../src/errors/SsrfErrors';
+import { ssrfSafeFetch } from '../../src/utils/ssrfGuard.workerd';
+
+describe('ssrfSafeFetch (workerd)', () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it('fails closed without attempting a fetch', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(ssrfSafeFetch('https://example.com/file.pdf')).rejects.toBeInstanceOf(
+ ComposioBlockedInternalUrlError
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/ts/packages/core/tsconfig.json b/ts/packages/core/tsconfig.json
index 00a5e9d3b..49140ba74 100644
--- a/ts/packages/core/tsconfig.json
+++ b/ts/packages/core/tsconfig.json
@@ -22,7 +22,8 @@
"#config_defaults": [
"./src/utils/config-defaults/ConfigDefaults.node.ts",
"./src/utils/config-defaults/ConfigDefaults.workerd.ts"
- ]
+ ],
+ "#ssrf_guard": ["./src/utils/ssrfGuard.node.ts", "./src/utils/ssrfGuard.workerd.ts"]
}
},
"include": ["src/**/*.ts"]
diff --git a/ts/packages/core/tsdown.config.ts b/ts/packages/core/tsdown.config.ts
index 279fdf901..4950c87b3 100644
--- a/ts/packages/core/tsdown.config.ts
+++ b/ts/packages/core/tsdown.config.ts
@@ -33,6 +33,10 @@ export default defineConfig({
'src/utils/config-defaults/ConfigDefaults.node.ts',
'src/utils/config-defaults/ConfigDefaults.workerd.ts',
+ // #ssrf_guard
+ 'src/utils/ssrfGuard.node.ts',
+ 'src/utils/ssrfGuard.workerd.ts',
+
// public utility subpaths
'src/utils/json-schema.ts',
],
@@ -48,6 +52,7 @@ export default defineConfig({
'#files',
'#file_tool_modifier',
'#config_defaults',
+ '#ssrf_guard',
],
},
});
diff --git a/ts/packages/core/vitest.config.ts b/ts/packages/core/vitest.config.ts
index 79f7e9d62..1bda45bdd 100644
--- a/ts/packages/core/vitest.config.ts
+++ b/ts/packages/core/vitest.config.ts
@@ -17,6 +17,7 @@ export default defineConfig({
__dirname,
'src/utils/config-defaults/ConfigDefaults.node.ts'
),
+ '#ssrf_guard': path.resolve(__dirname, 'src/utils/ssrfGuard.node.ts'),
},
},
test: {
diff --git a/ts/packages/slim/package.json b/ts/packages/slim/package.json
index 4ba54663d..954132386 100644
--- a/ts/packages/slim/package.json
+++ b/ts/packages/slim/package.json
@@ -33,6 +33,12 @@
"edge-light": "./dist/utils/config-defaults/ConfigDefaults.workerd.mjs",
"node": "./dist/utils/config-defaults/ConfigDefaults.node.mjs",
"default": "./dist/utils/config-defaults/ConfigDefaults.node.mjs"
+ },
+ "#ssrf_guard": {
+ "workerd": "./dist/utils/ssrfGuard.workerd.mjs",
+ "edge-light": "./dist/utils/ssrfGuard.workerd.mjs",
+ "node": "./dist/utils/ssrfGuard.node.mjs",
+ "default": "./dist/utils/ssrfGuard.node.mjs"
}
},
"exports": {