@devries-cameron20 / composio Mirror · read-only / commits / 2f63fe540
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 18:30 UTC

fix(core): secure Tool Router session URL uploads (#3900)

## Summary - route Tool Router session URL uploads through the SDK's SSRF-safe fetch path - validate every redirect target and reject destinations that resolve to non-public network addresses - stream URL response bodies with a 100 MiB limit instead of buffering unbounded responses - fail closed for URL uploads on edge runtimes where DNS validation is unavailable - apply the bounded response reader to the existing core URL-upload path as well - add a patch changeset for `@composio/core` ## Root cause Tool Router session file uploads fetched string URL inputs directly and buffered the entire response. That bypassed the SSRF checks already used by other SDK upload paths and allowed an untrusted URL to target internal network resources or return an unbounded response body. ## Impact Node.js and Bun URL uploads now validate resolved addresses before connecting and revalidate redirect hops. Cloudflare Workers and other edge runtimes reject URL inputs with a typed error; callers can fetch trusted content themselves and pass a `File` or `ArrayBuffer` instead. ## Validation - focused SSRF and file upload tests: 59 passed - full `@composio/core` suite: 1,034 passed - TypeScript checks with both tsgo and tsc - ESLint and Prettier - package build, ATTW, and publint - changeset validation - Cloudflare Workers live E2E: 5 passed - live Node Tool Router upload/list/download/delete flow - live Node Tool Router HTTPS URL upload and cleanup <!-- codesmith:footer --> --- <a href="https://app.blacksmith.sh/ComposioHQ/codesmith/composio/pr/3900"><picture><source media="(prefers-color-scheme: dark)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v2.svg"><source media="(prefers-color-scheme: light)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-light-v2.svg"><img alt="View with Codesmith" src="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v2.svg"></picture></a> <a href="https://backend.blacksmith.sh/track/enable-autofix?expires=1787224599&installation_model_id=428187&pr_number=3900&repository=ComposioHQ%2Fcomposio&return_to=https%3A%2F%2Fgithub.com%2FComposioHQ%2Fcomposio%2Fpull%2F3900&signature=ef519ac58a7945667565c1c143983f353b8947c988079d76c04afa9ab3b111d1"><picture><source media="(prefers-color-scheme: dark)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-light.svg"><img alt="Autofix with Codesmith" src="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"></picture></a> <sup>Need help on this PR? Tag <code>/codesmith</code> with what you need. Autofix is disabled.</sup> <!-- codesmith:autofix:disabled --> <!-- /codesmith:footer -->

Shrey Singla committed Jul 22, 2026 at 14:51 UTC 2f63fe540775b9bb851798d13aa1d4bc79a8cb98
16 files changed +331 -58
.changeset/secure-session-url-uploads.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Guard Tool Router session URL uploads against SSRF, revalidate redirect targets, and enforce a streamed 100 MiB response limit across TypeScript URL upload paths.
ts/packages/core/package.json
+6
@@ -33,6 +33,12 @@
33 "edge-light": "./dist/utils/config-defaults/ConfigDefaults.workerd.mjs",
34 "node": "./dist/utils/config-defaults/ConfigDefaults.node.mjs",
35 "default": "./dist/utils/config-defaults/ConfigDefaults.node.mjs"
36 + },
37 + "#ssrf_guard": {
38 + "workerd": "./dist/utils/ssrfGuard.workerd.mjs",
39 + "edge-light": "./dist/utils/ssrfGuard.workerd.mjs",
40 + "node": "./dist/utils/ssrfGuard.node.mjs",
41 + "default": "./dist/utils/ssrfGuard.node.mjs"
42 }
43 },
44 "exports": {
ts/packages/core/src/errors/SsrfErrors.ts
+4 -3
@@ -14,9 +14,10 @@ export interface ComposioBlockedInternalUrlErrorOptions extends Omit<ComposioErr
14 /**
15 * Thrown when a URL file input resolves to a private, loopback, link-local, or
16 * otherwise internal address, or points at a non-http(s) scheme. Guards against
17 - * turning `composio.files.upload(url)` (and automatic upload during tool
18 - * execution) into a server-side request forgery (SSRF) probe of internal
19 - * infrastructure such as cloud metadata endpoints (`169.254.169.254`).
17 + * turning URL-based file uploads (including Tool Router session files and
18 + * automatic upload during tool execution) into a server-side request forgery
19 + * (SSRF) probe of internal infrastructure such as cloud metadata endpoints
20 + * (`169.254.169.254`).
21 */
22 export class ComposioBlockedInternalUrlError extends ComposioError {
23 constructor(
ts/packages/core/src/models/ToolRouterSessionFileMount.ts
+7 -3
@@ -18,7 +18,9 @@ import {
18 import { RemoteFile } from './RemoteFile';
19 import { ValidationError } from '../errors';
20 import { platform } from '#platform';
21 +import { ssrfSafeFetch } from '#ssrf_guard';
22 import { getExtensionFromMimeType } from '../utils/mime';
23 +import { readResponseBodyWithLimit } from '../utils/readResponseBody';
24 import { getRandomShortId } from '../utils/uuid';
25
26 /**
@@ -110,11 +112,11 @@ export class ToolRouterSessionFilesMount {
112 ): Promise<{ fileToUpload: File; remotePath: string; mimetype: string }> {
113 if (typeof input === 'string') {
114 if (input.startsWith('http://') || input.startsWith('https://')) {
113 - const response = await fetch(input);
115 + const response = await ssrfSafeFetch(input);
116 if (!response.ok) {
117 throw new Error(`Failed to fetch file from URL: ${response.statusText}`);
118 }
117 - const arrayBuffer = await response.arrayBuffer();
119 + const content = await readResponseBodyWithLimit(response);
120 const rawContentType = response.headers.get('content-type') || 'application/octet-stream';
121 const mimeType = rawContentType.split(';')[0].trim();
122 const url = new URL(input);
@@ -125,7 +127,7 @@ export class ToolRouterSessionFilesMount {
127 const extension = getExtensionFromMimeType(mimeType);
128 filename = `${getRandomShortId()}.${extension}`;
129 }
128 - const file = new File([arrayBuffer], filename, { type: mimeType });
130 + const file = new File([content as BlobPart], filename, { type: mimeType });
131 return {
132 fileToUpload: file,
133 remotePath: options.remotePath ?? filename,
@@ -178,6 +180,8 @@ export class ToolRouterSessionFilesMount {
180 *
181 * Accepts a file path (local or URL), a native File object, or a raw buffer.
182 * The file is stored in the virtual filesystem associated with the tool router session.
183 + * URL inputs require a Node.js or Bun runtime so the destination can be DNS-validated;
184 + * edge runtimes must fetch the file themselves and pass a File or ArrayBuffer.
185 *
186 * @param input - File path (string), native File, or raw buffer (ArrayBuffer | Uint8Array).
187 * @param options - Optional configuration. When passing a buffer, remotePath is required.
ts/packages/core/src/utils/fileUtils.node.ts
+2 -2
@@ -10,6 +10,7 @@ import type { FileDownloadData, FileUploadData } from '../types/files.types';
10 import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths';
11 import { assertPathInsideUploadDirs } from './uploadDirAllowlist.node';
12 import { ssrfSafeFetch } from './ssrfGuard.node';
13 +import { readResponseBodyWithLimit } from './readResponseBody';
14
15 /**
16 * Options for {@link getFileDataAfterUploadingToS3} (S3 presigned upload from local path, URL, or File).
@@ -177,8 +178,7 @@ const readFileContentFromURL = async (
178 if (!response.ok) {
179 throw new Error(`Failed to fetch file: ${response.statusText}`);
180 }
180 - const arrayBuffer = await response.arrayBuffer();
181 - const content = new Uint8Array(arrayBuffer);
181 + const content = await readResponseBodyWithLimit(response);
182 const mimeType = response.headers.get('content-type') || 'application/octet-stream';
183
184 // Extract clean filename from URL, removing query parameters
ts/packages/core/src/utils/readResponseBody.ts new
+63
@@ -0,0 +1,63 @@
1 +/** Maximum size accepted for files fetched from user-supplied URLs (100 MiB). */
2 +export const MAX_URL_UPLOAD_SIZE_BYTES = 100 * 1024 * 1024;
3 +
4 +const sizeLimitError = (actualSize: number, maxBytes: number): Error =>
5 + new Error(`File size (${actualSize} bytes) exceeds maximum allowed size (${maxBytes} bytes)`);
6 +
7 +/**
8 + * Read a fetch response without allowing an untrusted server to exhaust memory.
9 + *
10 + * `Content-Length` is checked as an early rejection, but the streamed byte
11 + * count is authoritative because the header can be absent or dishonest.
12 + */
13 +export const readResponseBodyWithLimit = async (
14 + response: Response,
15 + maxBytes: number = MAX_URL_UPLOAD_SIZE_BYTES
16 +): Promise<Uint8Array> => {
17 + if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
18 + throw new RangeError('maxBytes must be a non-negative safe integer');
19 + }
20 +
21 + const contentLength = response.headers.get('content-length')?.trim();
22 + if (contentLength && /^\d+$/.test(contentLength)) {
23 + const declaredSize = Number(contentLength);
24 + if (!Number.isSafeInteger(declaredSize) || declaredSize > maxBytes) {
25 + const error = sizeLimitError(declaredSize, maxBytes);
26 + await response.body?.cancel(error).catch(() => undefined);
27 + throw error;
28 + }
29 + }
30 +
31 + if (!response.body) {
32 + return new Uint8Array();
33 + }
34 +
35 + const reader = response.body.getReader();
36 + const chunks: Uint8Array[] = [];
37 + let totalBytes = 0;
38 +
39 + try {
40 + while (true) {
41 + const { done, value } = await reader.read();
42 + if (done) break;
43 + if (!value || value.byteLength === 0) continue;
44 +
45 + totalBytes += value.byteLength;
46 + if (totalBytes > maxBytes) {
47 + await reader.cancel(sizeLimitError(totalBytes, maxBytes));
48 + throw sizeLimitError(totalBytes, maxBytes);
49 + }
50 + chunks.push(value);
51 + }
52 + } finally {
53 + reader.releaseLock();
54 + }
55 +
56 + const body = new Uint8Array(totalBytes);
57 + let offset = 0;
58 + for (const chunk of chunks) {
59 + body.set(chunk, offset);
60 + offset += chunk.byteLength;
61 + }
62 + return body;
63 +};
ts/packages/core/src/utils/ssrfGuard.node.ts
+6 -6
@@ -5,12 +5,12 @@ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
5 /**
6 * SSRF guard for user-supplied URL file inputs.
7 *
8 - * `composio.files.upload(url)` and automatic file upload during tool execution
9 - * fetch arbitrary user-provided URLs. Without a guard, a caller (or a tool
10 - * argument produced by an LLM) can point the SDK at internal infrastructure —
11 - * loopback, RFC1918 ranges, link-local cloud-metadata endpoints
12 - * (`169.254.169.254`), or a public URL that 3xx-redirects into internal space —
13 - * turning the SDK into a server-side request forgery probe.
8 + * `composio.files.upload(url)`, Tool Router session file uploads, and automatic
9 + * file upload during tool execution fetch arbitrary user-provided URLs. Without
10 + * a guard, a caller (or a tool argument produced by an LLM) can point the SDK at
11 + * internal infrastructure — loopback, RFC1918 ranges, link-local cloud-metadata
12 + * endpoints (`169.254.169.254`), or a public URL that 3xx-redirects into internal
13 + * space — turning the SDK into a server-side request forgery probe.
14 *
15 * This module validates the *resolved* address (not just the hostname string,
16 * which defeats decimal/octal/hex IP obfuscation) before every fetch, and
ts/packages/core/src/utils/ssrfGuard.workerd.ts new
+19
@@ -0,0 +1,19 @@
1 +import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
2 +
3 +/**
4 + * Edge runtimes do not expose the DNS resolution APIs needed to prove that a
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> => {
9 + throw new ComposioBlockedInternalUrlError(
10 + 'URL file uploads are not supported in edge runtimes because the destination cannot be safely validated',
11 + {
12 + url: rawUrl,
13 + possibleFixes: [
14 + 'Fetch the public URL yourself and pass a File or ArrayBuffer instead',
15 + 'Run the URL upload in a Node.js or Bun runtime',
16 + ],
17 + }
18 + );
19 +};
ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts
+103 -8
@@ -1,8 +1,17 @@
1 -import { describe, it, expect, vi, beforeEach } from 'vitest';
1 +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 import { ToolRouterSessionFilesMount } from '../../src/models/ToolRouterSessionFileMount';
3 -import { ValidationError } from '../../src/errors';
3 +import { ComposioBlockedInternalUrlError, ValidationError } from '../../src/errors';
4 import { DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID } from '../../src/utils/constants';
5
6 +vi.mock('node:dns/promises', () => ({
7 + lookup: vi.fn(),
8 +}));
9 +
10 +// eslint-disable-next-line no-restricted-imports
11 +import { lookup } from 'node:dns/promises';
12 +
13 +const mockLookup = vi.mocked(lookup);
14 +
15 const sessionId = 'trs_session_123';
16
17 const createMockClient = () => ({
@@ -24,6 +33,7 @@ describe('ToolRouterSessionFilesMount', () => {
33
34 beforeEach(() => {
35 vi.clearAllMocks();
36 + mockLookup.mockReset();
37 mockClient = createMockClient();
38 filesMount = new ToolRouterSessionFilesMount(mockClient as any, sessionId);
39 });
@@ -209,12 +219,97 @@ describe('ToolRouterSessionFilesMount', () => {
219 };
220
221 beforeEach(() => {
212 - globalThis.fetch = vi.fn().mockImplementation((url: string, init?: RequestInit) => {
213 - if (init?.method === 'PUT') {
214 - return Promise.resolve({ ok: true });
215 - }
216 - return Promise.reject(new Error('Unexpected fetch'));
217 - }) as unknown as typeof fetch;
222 + vi.stubGlobal(
223 + 'fetch',
224 + vi.fn().mockImplementation((_url: string, init?: RequestInit) => {
225 + if (init?.method === 'PUT') {
226 + return Promise.resolve({ ok: true });
227 + }
228 + return Promise.reject(new Error('Unexpected fetch'));
229 + })
230 + );
231 + });
232 +
233 + afterEach(() => vi.unstubAllGlobals());
234 +
235 + it.each([
236 + ['loopback', 'http://127.0.0.1/private', '127.0.0.1'],
237 + ['cloud metadata', 'http://169.254.169.254/latest/meta-data/', '169.254.169.254'],
238 + ])('should block %s URL uploads before fetching', async (_label, url, address) => {
239 + mockLookup.mockResolvedValueOnce([{ address, family: 4 }] as never);
240 +
241 + await expect(filesMount.upload(url)).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);
242 +
243 + expect(fetch).not.toHaveBeenCalled();
244 + expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
245 + expect(mockClient.toolRouter.session.files.createDownloadURL).not.toHaveBeenCalled();
246 + });
247 +
248 + it('should block a public URL that redirects to cloud metadata', async () => {
249 + mockLookup
250 + .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }] as never)
251 + .mockResolvedValueOnce([{ address: '169.254.169.254', family: 4 }] as never);
252 + vi.mocked(fetch).mockResolvedValueOnce(
253 + new Response(null, {
254 + status: 302,
255 + headers: { location: 'http://169.254.169.254/latest/meta-data/' },
256 + })
257 + );
258 +
259 + await expect(filesMount.upload('https://public.example/redirect')).rejects.toBeInstanceOf(
260 + ComposioBlockedInternalUrlError
261 + );
262 +
263 + expect(fetch).toHaveBeenCalledTimes(1);
264 + expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
265 + });
266 +
267 + it('should fetch and upload a public URL through the SSRF-safe path', async () => {
268 + mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
269 + vi.mocked(fetch)
270 + .mockResolvedValueOnce(
271 + new Response('hello', {
272 + status: 200,
273 + headers: { 'content-type': 'text/plain; charset=utf-8' },
274 + })
275 + )
276 + .mockResolvedValueOnce(new Response(null, { status: 200 }));
277 + mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
278 + ...createUploadURLResponse,
279 + mount_relative_path: 'hello.txt',
280 + });
281 + mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
282 + ...createDownloadURLResponse,
283 + mount_relative_path: 'hello.txt',
284 + });
285 +
286 + const result = await filesMount.upload('https://files.example/hello.txt');
287 +
288 + expect(fetch).toHaveBeenNthCalledWith(
289 + 1,
290 + 'https://files.example/hello.txt',
291 + expect.objectContaining({ redirect: 'manual' })
292 + );
293 + expect(result.mountRelativePath).toBe('hello.txt');
294 + });
295 +
296 + it('should reject a URL response whose declared size exceeds 100 MiB', async () => {
297 + mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
298 + vi.mocked(fetch).mockResolvedValueOnce(
299 + new Response('small body', {
300 + status: 200,
301 + headers: {
302 + 'content-type': 'text/plain',
303 + 'content-length': String(100 * 1024 * 1024 + 1),
304 + },
305 + })
306 + );
307 +
308 + await expect(filesMount.upload('https://files.example/oversized.txt')).rejects.toThrow(
309 + 'exceeds maximum allowed size'
310 + );
311 +
312 + expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
313 });
314
315 it('should upload local file and return RemoteFile', async () => {
ts/packages/core/test/utils/fileUtils.test.ts
+36 -35
@@ -53,6 +53,12 @@ vi.mock('node:dns/promises', () => ({
53 const mockFetch = vi.fn();
54 global.fetch = mockFetch;
55
56 +const fetchedFileResponse = (contentType: string = 'application/pdf') =>
57 + new Response(new Uint8Array(10), {
58 + status: 200,
59 + headers: { 'content-type': contentType },
60 + });
61 +
62 describe('fileUtils', () => {
63 let mockClient: ComposioClient;
64
@@ -76,11 +82,7 @@ describe('fileUtils', () => {
82 describe('URL filename generation with query parameters', () => {
83 beforeEach(() => {
84 // Mock successful fetch response
79 - mockFetch.mockResolvedValue({
80 - ok: true,
81 - arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
82 - headers: new Map([['content-type', 'application/pdf']]),
83 - });
85 + mockFetch.mockResolvedValue(fetchedFileResponse());
86
87 // Mock successful S3 upload
88 (mockClient.files.createPresignedURL as any).mockResolvedValue({
@@ -95,11 +97,7 @@ describe('fileUtils', () => {
97 return Promise.resolve({ ok: true });
98 }
99 // For the initial file fetch
98 - return Promise.resolve({
99 - ok: true,
100 - arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
101 - headers: new Map([['content-type', 'application/pdf']]),
102 - });
100 + return Promise.resolve(fetchedFileResponse());
101 });
102 });
103
@@ -155,6 +153,29 @@ describe('fileUtils', () => {
153
154 expect(result.name).toBe('file_ts1640995200000abc12345.pdf');
155 });
156 +
157 + it('should reject an oversized URL response before requesting an upload URL', async () => {
158 + mockFetch.mockReset();
159 + mockFetch.mockResolvedValueOnce(
160 + new Response('small body', {
161 + status: 200,
162 + headers: {
163 + 'content-type': 'application/pdf',
164 + 'content-length': String(100 * 1024 * 1024 + 1),
165 + },
166 + })
167 + );
168 +
169 + await expect(
170 + getFileDataAfterUploadingToS3('https://example.com/oversized.pdf', {
171 + toolSlug: 'test-tool',
172 + toolkitSlug: 'test-toolkit',
173 + client: mockClient,
174 + })
175 + ).rejects.toThrow('exceeds maximum allowed size');
176 +
177 + expect(mockClient.files.createPresignedURL).not.toHaveBeenCalled();
178 + });
179 });
180
181 describe('MIME type extension handling', () => {
@@ -175,11 +196,7 @@ describe('fileUtils', () => {
196 vi.clearAllMocks();
197
198 // Mock successful fetch response
178 - mockFetch.mockResolvedValueOnce({
179 - ok: true,
180 - arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
181 - headers: new Map([['content-type', mimeType]]),
182 - });
199 + mockFetch.mockResolvedValueOnce(fetchedFileResponse(mimeType));
200
201 // Mock successful S3 upload
202 (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
@@ -205,11 +222,7 @@ describe('fileUtils', () => {
222 // Reset mocks
223 vi.clearAllMocks();
224
208 - mockFetch.mockResolvedValueOnce({
209 - ok: true,
210 - arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
211 - headers: new Map([['content-type', 'text/plain; charset=utf-8']]),
212 - });
225 + mockFetch.mockResolvedValueOnce(fetchedFileResponse('text/plain; charset=utf-8'));
226
227 // Mock successful S3 upload
228 (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
@@ -244,11 +257,7 @@ describe('fileUtils', () => {
257 // Reset mocks for each iteration
258 vi.clearAllMocks();
259
247 - mockFetch.mockResolvedValueOnce({
248 - ok: true,
249 - arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
250 - headers: new Map([['content-type', mimeType]]),
251 - });
260 + mockFetch.mockResolvedValueOnce(fetchedFileResponse(mimeType));
261
262 // Mock successful S3 upload
263 (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
@@ -274,11 +283,7 @@ describe('fileUtils', () => {
283 // Reset mocks
284 vi.clearAllMocks();
285
277 - mockFetch.mockResolvedValueOnce({
278 - ok: true,
279 - arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
280 - headers: new Map([['content-type', 'application/custom-format']]),
281 - });
286 + mockFetch.mockResolvedValueOnce(fetchedFileResponse('application/custom-format'));
287
288 // Mock successful S3 upload
289 (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
@@ -472,11 +477,7 @@ describe('fileUtils', () => {
477 });
478
479 it('should handle S3 upload errors', async () => {
475 - mockFetch.mockResolvedValueOnce({
476 - ok: true,
477 - arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
478 - headers: new Map([['content-type', 'application/pdf']]),
479 - });
480 + mockFetch.mockResolvedValueOnce(fetchedFileResponse());
481
482 (mockClient.files.createPresignedURL as any).mockResolvedValue({
483 key: 'test-key',
ts/packages/core/test/utils/readResponseBody.test.ts new
+49
@@ -0,0 +1,49 @@
1 +import { describe, expect, it, vi } from 'vitest';
2 +import { readResponseBodyWithLimit } from '../../src/utils/readResponseBody';
3 +
4 +describe('readResponseBodyWithLimit', () => {
5 + it('rejects an oversized Content-Length before reading the body', async () => {
6 + const cancel = vi.fn();
7 + const response = new Response(new ReadableStream({ cancel }), {
8 + headers: { 'content-length': '5' },
9 + });
10 +
11 + await expect(readResponseBodyWithLimit(response, 4)).rejects.toThrow(
12 + 'exceeds maximum allowed size'
13 + );
14 + expect(cancel).toHaveBeenCalledOnce();
15 + expect(response.bodyUsed).toBe(true);
16 + });
17 +
18 + it('rejects and cancels a stream that exceeds the limit without a size header', async () => {
19 + const cancel = vi.fn();
20 + const response = new Response(
21 + new ReadableStream<Uint8Array>({
22 + start(controller) {
23 + controller.enqueue(new Uint8Array([1, 2, 3]));
24 + controller.enqueue(new Uint8Array([4, 5]));
25 + },
26 + cancel,
27 + })
28 + );
29 +
30 + await expect(readResponseBodyWithLimit(response, 4)).rejects.toThrow(
31 + 'exceeds maximum allowed size'
32 + );
33 + expect(cancel).toHaveBeenCalledOnce();
34 + });
35 +
36 + it('accepts a body exactly at the limit', async () => {
37 + const response = new Response(new Uint8Array([1, 2, 3, 4]), {
38 + headers: { 'content-length': '4' },
39 + });
40 +
41 + await expect(readResponseBodyWithLimit(response, 4)).resolves.toEqual(
42 + new Uint8Array([1, 2, 3, 4])
43 + );
44 + });
45 +
46 + it('rejects invalid limits', async () => {
47 + await expect(readResponseBodyWithLimit(new Response(), -1)).rejects.toThrow(RangeError);
48 + });
49 +});
ts/packages/core/test/utils/ssrfGuard.workerd.test.ts new
+17
@@ -0,0 +1,17 @@
1 +import { afterEach, describe, expect, it, vi } from 'vitest';
2 +import { ComposioBlockedInternalUrlError } from '../../src/errors/SsrfErrors';
3 +import { ssrfSafeFetch } from '../../src/utils/ssrfGuard.workerd';
4 +
5 +describe('ssrfSafeFetch (workerd)', () => {
6 + afterEach(() => vi.unstubAllGlobals());
7 +
8 + it('fails closed without attempting a fetch', async () => {
9 + const fetchMock = vi.fn();
10 + vi.stubGlobal('fetch', fetchMock);
11 +
12 + await expect(ssrfSafeFetch('https://example.com/file.pdf')).rejects.toBeInstanceOf(
13 + ComposioBlockedInternalUrlError
14 + );
15 + expect(fetchMock).not.toHaveBeenCalled();
16 + });
17 +});
ts/packages/core/tsconfig.json
+2 -1
@@ -22,7 +22,8 @@
22 "#config_defaults": [
23 "./src/utils/config-defaults/ConfigDefaults.node.ts",
24 "./src/utils/config-defaults/ConfigDefaults.workerd.ts"
25 - ]
25 + ],
26 + "#ssrf_guard": ["./src/utils/ssrfGuard.node.ts", "./src/utils/ssrfGuard.workerd.ts"]
27 }
28 },
29 "include": ["src/**/*.ts"]
ts/packages/core/tsdown.config.ts
+5
@@ -33,6 +33,10 @@ export default defineConfig({
33 'src/utils/config-defaults/ConfigDefaults.node.ts',
34 'src/utils/config-defaults/ConfigDefaults.workerd.ts',
35
36 + // #ssrf_guard
37 + 'src/utils/ssrfGuard.node.ts',
38 + 'src/utils/ssrfGuard.workerd.ts',
39 +
40 // public utility subpaths
41 'src/utils/json-schema.ts',
42 ],
@@ -48,6 +52,7 @@ export default defineConfig({
52 '#files',
53 '#file_tool_modifier',
54 '#config_defaults',
55 + '#ssrf_guard',
56 ],
57 },
58 });
ts/packages/core/vitest.config.ts
+1
@@ -17,6 +17,7 @@ export default defineConfig({
17 __dirname,
18 'src/utils/config-defaults/ConfigDefaults.node.ts'
19 ),
20 + '#ssrf_guard': path.resolve(__dirname, 'src/utils/ssrfGuard.node.ts'),
21 },
22 },
23 test: {
ts/packages/slim/package.json
+6
@@ -33,6 +33,12 @@
33 "edge-light": "./dist/utils/config-defaults/ConfigDefaults.workerd.mjs",
34 "node": "./dist/utils/config-defaults/ConfigDefaults.node.mjs",
35 "default": "./dist/utils/config-defaults/ConfigDefaults.node.mjs"
36 + },
37 + "#ssrf_guard": {
38 + "workerd": "./dist/utils/ssrfGuard.workerd.mjs",
39 + "edge-light": "./dist/utils/ssrfGuard.workerd.mjs",
40 + "node": "./dist/utils/ssrfGuard.node.mjs",
41 + "default": "./dist/utils/ssrfGuard.node.mjs"
42 }
43 },
44 "exports": {