Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 550 lines 20 KB
Raw
1 import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 import ComposioClient, { Auth } from '@composio/client';
3 import { ToolRouterSessionFilesMount } from '../../src/models/ToolRouterSessionFileMount';
4 import { ComposioBlockedInternalUrlError, ValidationError } from '../../src/errors';
5 import { DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID } from '../../src/utils/constants';
6
7 vi.mock('node:dns/promises', () => ({
8 lookup: vi.fn(),
9 }));
10
11 // eslint-disable-next-line no-restricted-imports
12 import { lookup } from 'node:dns/promises';
13
14 const mockLookup = vi.mocked(lookup);
15
16 const sessionId = 'trs_session_123';
17
18 const createMockClient = () => {
19 const client = new ComposioClient({ auth: Auth.project('test-api-key') });
20 const files = Object.assign(client.toolRouter.session.files, {
21 list: vi.fn<typeof client.toolRouter.session.files.list>(),
22 createUploadURL: vi.fn<typeof client.toolRouter.session.files.createUploadURL>(),
23 createDownloadURL: vi.fn<typeof client.toolRouter.session.files.createDownloadURL>(),
24 delete: vi.fn<typeof client.toolRouter.session.files.delete>(),
25 });
26 const session = Object.assign(client.toolRouter.session, { files });
27 const toolRouter = Object.assign(client.toolRouter, { session });
28 return Object.assign(client, { toolRouter });
29 };
30
31 describe('ToolRouterSessionFilesMount', () => {
32 let mockClient: ReturnType<typeof createMockClient>;
33 let filesMount: ToolRouterSessionFilesMount;
34
35 beforeEach(() => {
36 vi.clearAllMocks();
37 mockLookup.mockReset();
38 // Uploads PUT to a response-supplied `upload_url`, which is now validated
39 // like any other fetch target; resolve test hosts as public by default so
40 // only the tests that care about the guard have to say anything about DNS.
41 mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
42 mockClient = createMockClient();
43 filesMount = new ToolRouterSessionFilesMount(mockClient, sessionId);
44 });
45
46 describe('list', () => {
47 it('should call list with default mountId and no path', async () => {
48 mockClient.toolRouter.session.files.list.mockResolvedValueOnce({ items: [] });
49
50 const result = await filesMount.list();
51
52 expect(mockClient.toolRouter.session.files.list).toHaveBeenCalledWith(
53 DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
54 {
55 session_id: sessionId,
56 mount_relative_prefix: undefined,
57 cursor: undefined,
58 limit: undefined,
59 }
60 );
61 expect(result).toEqual({ items: [], nextCursor: undefined });
62 });
63
64 it('should call list with custom path and mountId (strips leading slash for API)', async () => {
65 mockClient.toolRouter.session.files.list.mockResolvedValueOnce({ items: [] });
66
67 await filesMount.list({
68 path: '/documents',
69 mountId: 'custom-mount',
70 });
71
72 expect(mockClient.toolRouter.session.files.list).toHaveBeenCalledWith('custom-mount', {
73 session_id: sessionId,
74 mount_relative_prefix: 'documents',
75 cursor: undefined,
76 limit: undefined,
77 });
78 });
79
80 it('should return transformed response with items and nextCursor', async () => {
81 const apiResponse = {
82 items: [
83 {
84 last_modified: '2025-03-09T12:00:00.000Z',
85 mount_relative_path: 'file.txt',
86 sandbox_mount_prefix: '/mnt/files',
87 size: 42,
88 },
89 ],
90 next_cursor: 'cursor_abc123',
91 };
92 mockClient.toolRouter.session.files.list.mockResolvedValueOnce(apiResponse);
93
94 const result = await filesMount.list();
95
96 expect(result).toEqual({
97 items: [
98 {
99 lastModified: '2025-03-09T12:00:00.000Z',
100 mountRelativePath: 'file.txt',
101 sandboxMountPrefix: '/mnt/files',
102 size: 42,
103 },
104 ],
105 nextCursor: 'cursor_abc123',
106 });
107 });
108
109 it('should pass cursor and limit for pagination (path / omitted for root)', async () => {
110 mockClient.toolRouter.session.files.list.mockResolvedValueOnce({ items: [] });
111
112 await filesMount.list({
113 path: '/',
114 cursor: 'cursor_page2',
115 limit: 25,
116 });
117
118 expect(mockClient.toolRouter.session.files.list).toHaveBeenCalledWith(
119 DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
120 {
121 session_id: sessionId,
122 mount_relative_prefix: undefined,
123 cursor: 'cursor_page2',
124 limit: 25,
125 }
126 );
127 });
128 });
129
130 describe('download', () => {
131 const createDownloadURLResponse = {
132 expires_at: '2025-12-31T23:59:59.000Z',
133 mount_relative_path: 'output/report.pdf',
134 sandbox_mount_prefix: '/mnt/files',
135 download_url: 'https://s3.example.com/presigned',
136 };
137
138 it('should call createDownloadURL and return RemoteFile', async () => {
139 mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(
140 createDownloadURLResponse
141 );
142
143 const result = await filesMount.download('/output/report.pdf');
144
145 expect(mockClient.toolRouter.session.files.createDownloadURL).toHaveBeenCalledWith(
146 DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
147 {
148 session_id: sessionId,
149 mount_relative_path: '/output/report.pdf',
150 }
151 );
152 expect(result).toBeDefined();
153 expect(result.mountRelativePath).toBe('output/report.pdf');
154 expect(result.downloadUrl).toBe('https://s3.example.com/presigned');
155 });
156
157 it('should use custom mountId when provided', async () => {
158 mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(
159 createDownloadURLResponse
160 );
161
162 await filesMount.download('/output/report.pdf', { mountId: 'exports' });
163
164 expect(mockClient.toolRouter.session.files.createDownloadURL).toHaveBeenCalledWith(
165 'exports',
166 {
167 session_id: sessionId,
168 mount_relative_path: '/output/report.pdf',
169 }
170 );
171 });
172 });
173
174 describe('delete', () => {
175 const deleteResponse = {
176 mount_relative_path: '/temp/cache.json',
177 sandbox_mount_prefix: '/mnt/files',
178 };
179
180 it('should call delete and return parsed response', async () => {
181 mockClient.toolRouter.session.files.delete.mockResolvedValueOnce(deleteResponse);
182
183 const result = await filesMount.delete('/temp/cache.json');
184
185 expect(mockClient.toolRouter.session.files.delete).toHaveBeenCalledWith(
186 DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
187 {
188 session_id: sessionId,
189 mount_relative_path: '/temp/cache.json',
190 }
191 );
192 expect(result).toEqual({
193 mountRelativePath: '/temp/cache.json',
194 sandboxMountPrefix: '/mnt/files',
195 });
196 });
197
198 it('should use custom mountId when provided', async () => {
199 mockClient.toolRouter.session.files.delete.mockResolvedValueOnce(deleteResponse);
200
201 await filesMount.delete('/old-backup', { mountId: 'backups' });
202
203 expect(mockClient.toolRouter.session.files.delete).toHaveBeenCalledWith('backups', {
204 session_id: sessionId,
205 mount_relative_path: '/old-backup',
206 });
207 });
208 });
209
210 describe('upload', () => {
211 const mountRelativePath = 'composio-upload-test.txt';
212 const createUploadURLResponse = {
213 upload_url: 'https://s3.example.com/upload',
214 mount_relative_path: mountRelativePath,
215 sandbox_mount_prefix: '/mnt/files',
216 expires_at: '2025-12-31T23:59:59.000Z',
217 };
218
219 const createDownloadURLResponse = {
220 download_url: 'https://s3.example.com/presigned',
221 mount_relative_path: mountRelativePath,
222 sandbox_mount_prefix: '/mnt/files',
223 expires_at: '2025-12-31T23:59:59.000Z',
224 };
225
226 beforeEach(() => {
227 vi.stubGlobal(
228 'fetch',
229 vi.fn().mockImplementation((_url: string, init?: RequestInit) => {
230 if (init?.method === 'PUT') {
231 return Promise.resolve({ ok: true });
232 }
233 return Promise.reject(new Error('Unexpected fetch'));
234 })
235 );
236 });
237
238 afterEach(() => vi.unstubAllGlobals());
239
240 it.each([
241 ['loopback', 'http://127.0.0.1/private', '127.0.0.1'],
242 ['cloud metadata', 'http://169.254.169.254/latest/meta-data/', '169.254.169.254'],
243 ])('should block %s URL uploads before fetching', async (_label, url, address) => {
244 mockLookup.mockResolvedValueOnce([{ address, family: 4 }] as never);
245
246 await expect(filesMount.upload(url)).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);
247
248 expect(fetch).not.toHaveBeenCalled();
249 expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
250 expect(mockClient.toolRouter.session.files.createDownloadURL).not.toHaveBeenCalled();
251 });
252
253 it('should block a public URL that redirects to cloud metadata', async () => {
254 mockLookup
255 .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }] as never)
256 .mockResolvedValueOnce([{ address: '169.254.169.254', family: 4 }] as never);
257 vi.mocked(fetch).mockResolvedValueOnce(
258 new Response(null, {
259 status: 302,
260 headers: { location: 'http://169.254.169.254/latest/meta-data/' },
261 })
262 );
263
264 await expect(filesMount.upload('https://public.example/redirect')).rejects.toBeInstanceOf(
265 ComposioBlockedInternalUrlError
266 );
267
268 expect(fetch).toHaveBeenCalledTimes(1);
269 expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
270 });
271
272 it('should release a failed URL response body before throwing', async () => {
273 mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
274 const cancel = vi.fn();
275 const response = new Response(new ReadableStream({ cancel }), {
276 status: 500,
277 statusText: 'Internal Server Error',
278 });
279 vi.mocked(fetch).mockResolvedValueOnce(response);
280
281 await expect(filesMount.upload('https://files.example/failed.txt')).rejects.toThrow(
282 'Failed to fetch file from URL: Internal Server Error'
283 );
284
285 expect(cancel).toHaveBeenCalledOnce();
286 expect(response.bodyUsed).toBe(true);
287 expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
288 });
289
290 it('should fetch and upload a public URL through the SSRF-safe path', async () => {
291 mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
292 vi.mocked(fetch)
293 .mockResolvedValueOnce(
294 new Response('hello', {
295 status: 200,
296 headers: { 'content-type': 'text/plain; charset=utf-8' },
297 })
298 )
299 .mockResolvedValueOnce(new Response(null, { status: 200 }));
300 mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
301 ...createUploadURLResponse,
302 mount_relative_path: 'hello.txt',
303 });
304 mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
305 ...createDownloadURLResponse,
306 mount_relative_path: 'hello.txt',
307 });
308
309 const result = await filesMount.upload('https://files.example/hello.txt');
310
311 expect(fetch).toHaveBeenNthCalledWith(
312 1,
313 'https://files.example/hello.txt',
314 expect.objectContaining({ redirect: 'manual' })
315 );
316 expect(result.mountRelativePath).toBe('hello.txt');
317 });
318
319 it('should reject a URL response whose declared size exceeds 100 MiB', async () => {
320 mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
321 vi.mocked(fetch).mockResolvedValueOnce(
322 new Response('small body', {
323 status: 200,
324 headers: {
325 'content-type': 'text/plain',
326 'content-length': String(100 * 1024 * 1024 + 1),
327 },
328 })
329 );
330
331 await expect(filesMount.upload('https://files.example/oversized.txt')).rejects.toThrow(
332 'exceeds maximum allowed size'
333 );
334
335 expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
336 });
337
338 it('should upload local file and return RemoteFile', async () => {
339 const { platform } = await import('../../src/platform/node');
340 const { join } = await import('node:path');
341 const { tmpdir } = await import('node:os');
342 const testFilePath = join(tmpdir(), 'composio-upload-test.txt');
343 platform.writeFileSync(testFilePath, 'test content', 'utf8');
344
345 mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce(
346 createUploadURLResponse
347 );
348 mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(
349 createDownloadURLResponse
350 );
351
352 const result = await filesMount.upload(testFilePath);
353
354 expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(
355 DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
356 {
357 session_id: sessionId,
358 mount_relative_path: 'composio-upload-test.txt',
359 mimetype: 'application/octet-stream',
360 }
361 );
362 expect(mockClient.toolRouter.session.files.createDownloadURL).toHaveBeenCalledWith(
363 DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
364 {
365 session_id: sessionId,
366 mount_relative_path: mountRelativePath,
367 }
368 );
369 expect(result.mountRelativePath).toBe(mountRelativePath);
370 expect(result.downloadUrl).toBe('https://s3.example.com/presigned');
371 });
372
373 it('should block a response-supplied upload_url that resolves internally', async () => {
374 // The user-supplied URL branch above was already guarded; `upload_url`
375 // comes back from the API and was not. Both are untrusted here, and this
376 // one receives the file's bytes.
377 mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
378 ...createUploadURLResponse,
379 upload_url: 'http://metadata.example/upload',
380 });
381 mockLookup.mockResolvedValue([{ address: '169.254.169.254', family: 4 }] as never);
382
383 await expect(
384 filesMount.upload(new File(['data'], 'report.txt', { type: 'text/plain' }))
385 ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);
386
387 expect(fetch).not.toHaveBeenCalled();
388 expect(mockClient.toolRouter.session.files.createDownloadURL).not.toHaveBeenCalled();
389 });
390
391 it('should handle upload response body wrapper', async () => {
392 const { platform } = await import('../../src/platform/node');
393 const { join } = await import('node:path');
394 const { tmpdir } = await import('node:os');
395 const testFilePath = join(tmpdir(), 'composio-upload-test.txt');
396 platform.writeFileSync(testFilePath, 'test content', 'utf8');
397
398 mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
399 url: 'https://api.example.com/upload_url',
400 status: 201,
401 body: createUploadURLResponse,
402 });
403 mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(
404 createDownloadURLResponse
405 );
406
407 const result = await filesMount.upload(testFilePath);
408
409 expect(result.mountRelativePath).toBe(mountRelativePath);
410 expect(result.downloadUrl).toBe('https://s3.example.com/presigned');
411 });
412
413 it('should upload native File object', async () => {
414 const file = new File([new TextEncoder().encode('hello')], 'greeting.txt', {
415 type: 'text/plain',
416 });
417
418 mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
419 ...createUploadURLResponse,
420 mount_relative_path: 'greeting.txt',
421 });
422 mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
423 ...createDownloadURLResponse,
424 mount_relative_path: 'greeting.txt',
425 });
426
427 const result = await filesMount.upload(file);
428
429 expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(
430 DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
431 {
432 session_id: sessionId,
433 mount_relative_path: 'greeting.txt',
434 mimetype: 'text/plain',
435 }
436 );
437 expect(result.mountRelativePath).toBe('greeting.txt');
438 });
439
440 it('should upload File with custom remotePath', async () => {
441 const file = new File([new Uint8Array([1, 2, 3])], 'original.bin', {
442 type: 'application/octet-stream',
443 });
444
445 mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
446 ...createUploadURLResponse,
447 mount_relative_path: 'custom-name.bin',
448 });
449 mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
450 ...createDownloadURLResponse,
451 mount_relative_path: 'custom-name.bin',
452 });
453
454 const result = await filesMount.upload(file, { remotePath: 'custom-name.bin' });
455
456 expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(
457 DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
458 {
459 session_id: sessionId,
460 mount_relative_path: 'custom-name.bin',
461 mimetype: 'application/octet-stream',
462 }
463 );
464 expect(result.mountRelativePath).toBe('custom-name.bin');
465 });
466
467 it('should upload raw buffer with remotePath and mimetype', async () => {
468 const buffer = new TextEncoder().encode('{"key":"value"}');
469
470 mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
471 ...createUploadURLResponse,
472 mount_relative_path: 'data.json',
473 });
474 mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
475 ...createDownloadURLResponse,
476 mount_relative_path: 'data.json',
477 });
478
479 const result = await filesMount.upload(buffer, {
480 remotePath: 'data.json',
481 mimetype: 'application/json',
482 });
483
484 expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(
485 DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
486 {
487 session_id: sessionId,
488 mount_relative_path: 'data.json',
489 mimetype: 'application/json',
490 }
491 );
492 expect(result.mountRelativePath).toBe('data.json');
493 });
494
495 it('should return mountRelativePath from API response when it differs from requested path', async () => {
496 const buffer = new Uint8Array([0x89, 0x50, 0x4e, 0x47]); // PNG signature
497
498 mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
499 ...createUploadURLResponse,
500 mount_relative_path: 'upload-7949b409.jpg', // API returns different path
501 });
502 mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
503 ...createDownloadURLResponse,
504 mount_relative_path: 'upload-7949b409.jpg',
505 });
506
507 const result = await filesMount.upload(buffer, { remotePath: 'file.png' });
508
509 expect(result.mountRelativePath).toBe('upload-7949b409.jpg');
510 });
511
512 it('should throw when buffer is provided without mimetype or remotePath', async () => {
513 const buffer = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
514
515 await expect(filesMount.upload(buffer)).rejects.toThrow(
516 'When passing a buffer, either mimetype or remotePath (filename) is required'
517 );
518 });
519
520 it('should upload ArrayBuffer with mimetype when remotePath omitted', async () => {
521 const buffer = new ArrayBuffer(8);
522 new DataView(buffer).setUint32(0, 0xdeadbeef);
523
524 mockClient.toolRouter.session.files.createUploadURL.mockImplementation((_, params) =>
525 Promise.resolve({
526 ...createUploadURLResponse,
527 mount_relative_path: params.mount_relative_path,
528 })
529 );
530 mockClient.toolRouter.session.files.createDownloadURL.mockImplementation((_, params) =>
531 Promise.resolve({
532 ...createDownloadURLResponse,
533 mount_relative_path: params.mount_relative_path,
534 })
535 );
536
537 const result = await filesMount.upload(buffer, { mimetype: 'application/octet-stream' });
538
539 expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(
540 DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
541 expect.objectContaining({
542 session_id: sessionId,
543 mimetype: 'application/octet-stream',
544 mount_relative_path: expect.stringMatching(/^upload-.+\.bin$/),
545 })
546 );
547 expect(result.mountRelativePath).toMatch(/^upload-.+\.bin$/);
548 });
549 });
550 });