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 487 lines 18.8 KB
Raw
1 import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 import { RemoteFile } from '../../src/models/RemoteFile';
3 import {
4 ComposioBlockedInternalUrlError,
5 RemoteFileDownloadError,
6 ValidationError,
7 } from '../../src/errors';
8
9 // `downloadUrl` comes from an API response, so downloads run through the SSRF
10 // guard, which resolves the host before connecting. Resolve as public by
11 // default; the guard's own tests cover the blocking behavior.
12 vi.mock('node:dns/promises', () => ({
13 lookup: vi.fn(),
14 }));
15
16 // eslint-disable-next-line no-restricted-imports
17 import { lookup } from 'node:dns/promises';
18
19 const mockLookup = vi.mocked(lookup);
20
21 describe('RemoteFile', () => {
22 const validCamelCaseData = {
23 expiresAt: '2025-12-31T23:59:59.000Z',
24 mountRelativePath: 'output/report.pdf',
25 sandboxMountPrefix: '/mnt/files',
26 downloadUrl: 'https://s3.example.com/presigned-url',
27 };
28
29 const validSnakeCaseData = {
30 expires_at: '2025-12-31T23:59:59.000Z',
31 mount_relative_path: 'output/report.pdf',
32 sandbox_mount_prefix: '/mnt/files',
33 download_url: 'https://s3.example.com/presigned-url',
34 };
35
36 let originalFetch: typeof globalThis.fetch;
37
38 beforeEach(() => {
39 originalFetch = globalThis.fetch;
40 mockLookup.mockReset();
41 mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
42 });
43
44 afterEach(() => {
45 globalThis.fetch = originalFetch;
46 });
47
48 describe('constructor', () => {
49 it('should create instance with valid camelCase data', () => {
50 const file = new RemoteFile(validCamelCaseData);
51 expect(file.expiresAt).toBe(validCamelCaseData.expiresAt);
52 expect(file.mountRelativePath).toBe(validCamelCaseData.mountRelativePath);
53 expect(file.sandboxMountPrefix).toBe(validCamelCaseData.sandboxMountPrefix);
54 expect(file.downloadUrl).toBe(validCamelCaseData.downloadUrl);
55 });
56 });
57
58 describe('parse', () => {
59 it('should parse snake_case API response and return RemoteFile', () => {
60 const file = RemoteFile.parse(validSnakeCaseData);
61 expect(file).toBeInstanceOf(RemoteFile);
62 expect(file.expiresAt).toBe(validSnakeCaseData.expires_at);
63 expect(file.mountRelativePath).toBe(validSnakeCaseData.mount_relative_path);
64 expect(file.downloadUrl).toBe(validSnakeCaseData.download_url);
65 });
66
67 it('should throw ValidationError for invalid data', () => {
68 expect(() => RemoteFile.parse({})).toThrow(ValidationError);
69 expect(() => RemoteFile.parse({ expires_at: 'x' })).toThrow(ValidationError);
70 expect(() => RemoteFile.parse(null)).toThrow(ValidationError);
71 });
72 });
73
74 describe('filename', () => {
75 it('should return basename of mount path', () => {
76 const file = new RemoteFile(validCamelCaseData);
77 expect(file.filename).toBe('report.pdf');
78 });
79
80 it('should handle nested path', () => {
81 const file = new RemoteFile({
82 ...validCamelCaseData,
83 mountRelativePath: 'output/subdir/data.json',
84 });
85 expect(file.filename).toBe('data.json');
86 });
87 });
88
89 describe('buffer', () => {
90 it('should fetch and return file content as Uint8Array', async () => {
91 const content = new Uint8Array([1, 2, 3]);
92 globalThis.fetch = vi.fn().mockResolvedValue({
93 ok: true,
94 arrayBuffer: () => Promise.resolve(content.buffer),
95 });
96
97 const file = new RemoteFile(validCamelCaseData);
98 const result = await file.buffer();
99
100 // `redirect: 'manual'` is the guard following redirects itself so it can
101 // re-validate each hop, rather than letting fetch follow them unchecked;
102 // the `dispatcher` alongside it pins the connection to the address the
103 // guard validated.
104 expect(globalThis.fetch).toHaveBeenCalledWith(
105 validCamelCaseData.downloadUrl,
106 expect.objectContaining({ redirect: 'manual' })
107 );
108 expect(result).toBeInstanceOf(Uint8Array);
109 expect(result).toEqual(content);
110 });
111
112 it('should throw RemoteFileDownloadError when fetch fails', async () => {
113 globalThis.fetch = vi.fn().mockResolvedValue({
114 ok: false,
115 status: 404,
116 statusText: 'Not Found',
117 });
118
119 const file = new RemoteFile(validCamelCaseData);
120
121 await expect(file.buffer()).rejects.toThrow(RemoteFileDownloadError);
122 await expect(file.buffer()).rejects.toMatchObject({
123 name: 'RemoteFileDownloadError',
124 message: expect.stringContaining('404'),
125 });
126 });
127
128 it('should map a mid-stream transport failure and retain its cause', async () => {
129 const cause = new TypeError('peer reset mid-stream');
130 let pulls = 0;
131 globalThis.fetch = vi.fn().mockResolvedValue(
132 new Response(
133 new ReadableStream({
134 pull(controller) {
135 if (pulls++ === 0) {
136 controller.enqueue(new Uint8Array([1, 2, 3]));
137 } else {
138 controller.error(cause);
139 }
140 },
141 })
142 )
143 );
144
145 const file = new RemoteFile(validCamelCaseData);
146 await expect(file.buffer()).rejects.toMatchObject({
147 name: 'RemoteFileDownloadError',
148 cause,
149 });
150 });
151
152 it('should map a transport failure before response headers arrive', async () => {
153 const cause = new TypeError('connection refused');
154 globalThis.fetch = vi.fn().mockRejectedValue(cause);
155
156 const file = new RemoteFile(validCamelCaseData);
157 await expect(file.buffer()).rejects.toMatchObject({
158 name: 'RemoteFileDownloadError',
159 cause,
160 });
161 });
162
163 it('should reject a declared body larger than the shared download limit', async () => {
164 globalThis.fetch = vi.fn().mockResolvedValue(
165 new Response('ignored', {
166 headers: { 'content-length': String(101 * 1024 * 1024) },
167 })
168 );
169
170 const file = new RemoteFile(validCamelCaseData);
171 await expect(file.buffer()).rejects.toMatchObject({
172 name: 'RemoteFileDownloadError',
173 cause: expect.objectContaining({
174 message: expect.stringContaining('exceeds maximum allowed size'),
175 }),
176 });
177 });
178 });
179
180 describe('text', () => {
181 it('should fetch and return file content as UTF-8 string', async () => {
182 const content = 'Hello, World!';
183 globalThis.fetch = vi.fn().mockResolvedValue({
184 ok: true,
185 arrayBuffer: () => Promise.resolve(new TextEncoder().encode(content).buffer),
186 });
187
188 const file = new RemoteFile(validCamelCaseData);
189 const result = await file.text();
190
191 expect(result).toBe(content);
192 });
193 });
194
195 describe('blob', () => {
196 it('should fetch and return file content as Blob', async () => {
197 const blob = new Blob(['data'], { type: 'text/plain' });
198 globalThis.fetch = vi.fn().mockResolvedValue({
199 ok: true,
200 status: 200,
201 statusText: 'OK',
202 headers: new Headers({ 'content-type': blob.type }),
203 body: blob.stream(),
204 });
205
206 const file = new RemoteFile(validCamelCaseData);
207 const result = await file.blob();
208
209 expect(result.type).toBe(blob.type);
210 expect(await result.text()).toBe(await blob.text());
211 });
212
213 it('should throw RemoteFileDownloadError when fetch fails', async () => {
214 globalThis.fetch = vi.fn().mockResolvedValue({
215 ok: false,
216 status: 403,
217 statusText: 'Forbidden',
218 });
219
220 const file = new RemoteFile(validCamelCaseData);
221
222 await expect(file.blob()).rejects.toThrow(RemoteFileDownloadError);
223 });
224 });
225
226 describe('SSRF guard', () => {
227 // `downloadUrl` is set from an API response. Under the SDK's trust boundary
228 // that is untrusted input, so a response naming an internal address must
229 // not be fetched — the bytes go straight back to the caller, typically into
230 // an LLM context.
231 it.each([
232 ['loopback', 'http://127.0.0.1/secret', '127.0.0.1'],
233 ['cloud metadata', 'http://169.254.169.254/latest/meta-data/', '169.254.169.254'],
234 ])('should block a %s downloadUrl before fetching', async (_label, downloadUrl, address) => {
235 mockLookup.mockResolvedValue([{ address, family: 4 }] as never);
236 globalThis.fetch = vi.fn();
237
238 const file = new RemoteFile({ ...validCamelCaseData, downloadUrl });
239
240 await expect(file.buffer()).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);
241 await expect(file.blob()).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);
242 await expect(file.text()).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);
243 expect(globalThis.fetch).not.toHaveBeenCalled();
244 });
245
246 it('should block a downloadUrl that redirects into private space', async () => {
247 mockLookup
248 .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }] as never)
249 .mockResolvedValueOnce([{ address: '169.254.169.254', family: 4 }] as never);
250 globalThis.fetch = vi.fn().mockResolvedValue(
251 new Response(null, {
252 status: 302,
253 headers: { location: 'http://169.254.169.254/latest/meta-data/' },
254 })
255 );
256
257 const file = new RemoteFile(validCamelCaseData);
258
259 await expect(file.buffer()).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);
260 // The first hop was fetched; the redirect target never was.
261 expect(globalThis.fetch).toHaveBeenCalledTimes(1);
262 });
263 });
264
265 describe('save', () => {
266 it('should save file to specified path when platform supports file system', async () => {
267 const content = new Uint8Array([1, 2, 3]);
268 globalThis.fetch = vi.fn().mockResolvedValue({
269 ok: true,
270 arrayBuffer: () => Promise.resolve(content.buffer),
271 });
272
273 const file = new RemoteFile(validCamelCaseData);
274 const { platform } = await import('../../src/platform/node');
275 const { join } = await import('node:path');
276 const { tmpdir } = await import('node:os');
277 const savePath = join(tmpdir(), `composio-remote-file-test-${Date.now()}.pdf`);
278
279 const result = await file.save(savePath);
280
281 expect(result).toBe(savePath);
282 expect(platform.existsSync(savePath)).toBe(true);
283 const written = platform.readFileSync(savePath) as Uint8Array;
284 expect(new Uint8Array(written)).toEqual(content);
285 });
286
287 it('should save to an explicit path without resolving a home directory', async () => {
288 const { platform } = await import('../../src/platform/node');
289 const { mkdtempSync, readFileSync, rmSync, rmdirSync } = await import('node:fs');
290 const { join } = await import('node:path');
291 const { tmpdir } = await import('node:os');
292 const directory = mkdtempSync(join(tmpdir(), 'composio-remote-file-explicit-'));
293 const savePath = join(directory, 'report.pdf');
294 const content = new Uint8Array([1, 2, 3]);
295 const homedir = vi.spyOn(platform, 'homedir').mockReturnValue(null);
296 globalThis.fetch = vi.fn().mockResolvedValue(new Response(content));
297
298 try {
299 await expect(new RemoteFile(validCamelCaseData).save(savePath)).resolves.toBe(savePath);
300 expect(new Uint8Array(readFileSync(savePath))).toEqual(content);
301 expect(homedir).not.toHaveBeenCalled();
302 } finally {
303 vi.restoreAllMocks();
304 rmSync(savePath, { force: true });
305 rmdirSync(directory);
306 }
307 });
308
309 it('should reject a default save without a home directory before downloading or writing', async () => {
310 const { platform } = await import('../../src/platform/node');
311 vi.spyOn(platform, 'homedir').mockReturnValue(null);
312 const mkdir = vi.spyOn(platform, 'mkdirSync');
313 const write = vi.spyOn(platform, 'writeFileSync');
314 const writeExclusive = vi.spyOn(platform, 'writeFileExclusiveSync');
315 const fetch = vi.fn();
316 globalThis.fetch = fetch;
317
318 try {
319 await expect(new RemoteFile(validCamelCaseData).save()).rejects.toThrow(
320 'Cannot determine save location: home directory is not available'
321 );
322 expect(fetch).not.toHaveBeenCalled();
323 expect(mkdir).not.toHaveBeenCalled();
324 expect(write).not.toHaveBeenCalled();
325 expect(writeExclusive).not.toHaveBeenCalled();
326 } finally {
327 vi.restoreAllMocks();
328 }
329 });
330
331 describe('default location', () => {
332 // `save()` without a path derives the filename from `mountRelativePath`,
333 // a server-controlled response field. These cover the SEC-316 guard the
334 // Python SDK already applies; see `src/utils/safePath.ts`.
335 const content = new Uint8Array([1, 2, 3]);
336 let homeDir: string;
337 let composioDir: string;
338
339 beforeEach(async () => {
340 const { mkdtempSync } = await import('node:fs');
341 const { join } = await import('node:path');
342 const { tmpdir } = await import('node:os');
343 const { platform } = await import('../../src/platform/node');
344
345 homeDir = mkdtempSync(join(tmpdir(), 'composio-remote-file-home-'));
346 composioDir = join(homeDir, '.composio');
347 vi.spyOn(platform, 'homedir').mockReturnValue(homeDir);
348
349 globalThis.fetch = vi.fn().mockResolvedValue({
350 ok: true,
351 arrayBuffer: () => Promise.resolve(content.buffer),
352 });
353 });
354
355 afterEach(async () => {
356 vi.restoreAllMocks();
357 const { rmSync } = await import('node:fs');
358 rmSync(homeDir, { recursive: true, force: true });
359 });
360
361 it.each([
362 ['out/report.pdf', 'report.pdf'],
363 ['C:report.txt', 'report.txt'],
364 ['\ufeffreport.txt', '\ufeffreport.txt'],
365 ['\u0085report.txt\u0085', 'report.txt'],
366 ['out/report_2026-09-29T10:30:00.csv', 'report_2026-09-29T10_30_00-d7211bb25cb815fe.csv'],
367 ['What is this?.png', 'What is this_-9c68adf2da8b6e8d.png'],
368 ['report.\u00a0', 'report-11aada8ba3168adf'],
369 ['NUL.txt', '_NUL-d0848f78ce05ded6.txt'],
370 [`${'請'.repeat(70)}.pdf`, `${'請'.repeat(35)}-a7cbc40614b84819.pdf`],
371 ])(
372 'should save %j under the default directory as %j',
373 async (mountRelativePath, expectedName) => {
374 const { platform } = await import('../../src/platform/node');
375 const { join } = await import('node:path');
376 const file = new RemoteFile({ ...validCamelCaseData, mountRelativePath });
377
378 const result = await file.save();
379
380 expect(result).toBe(join(composioDir, 'files', expectedName));
381 expect(new Uint8Array(platform.readFileSync(result) as Uint8Array)).toEqual(content);
382 }
383 );
384
385 it('should not let files whose names normalize alike overwrite each other', async () => {
386 const { platform } = await import('../../src/platform/node');
387 const bodies = [new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3])];
388 globalThis.fetch = vi
389 .fn()
390 .mockResolvedValueOnce({ ok: true, arrayBuffer: () => Promise.resolve(bodies[0].buffer) })
391 .mockResolvedValueOnce({ ok: true, arrayBuffer: () => Promise.resolve(bodies[1].buffer) })
392 .mockResolvedValueOnce({
393 ok: true,
394 arrayBuffer: () => Promise.resolve(bodies[2].buffer),
395 });
396
397 const paths = [];
398 for (const mountRelativePath of ['report?.png', 'report*.png', 'report_.png']) {
399 paths.push(await new RemoteFile({ ...validCamelCaseData, mountRelativePath }).save());
400 }
401
402 expect(new Set(paths).size).toBe(3);
403 expect(
404 paths.map(path => new Uint8Array(platform.readFileSync(path) as Uint8Array))
405 ).toEqual(bodies);
406 });
407
408 it.each([
409 ['report?.png', 'report_-05fcb95aa5b918e9.png'],
410 ['report_-05fcb95aa5b918e9.png', 'report?.png'],
411 ])('should keep both downloads when %j and %j map to one name', async (first, second) => {
412 const { platform } = await import('../../src/platform/node');
413 const bodies = [new Uint8Array([1]), new Uint8Array([2])];
414 globalThis.fetch = vi
415 .fn()
416 .mockResolvedValueOnce({ ok: true, arrayBuffer: () => Promise.resolve(bodies[0].buffer) })
417 .mockResolvedValueOnce({
418 ok: true,
419 arrayBuffer: () => Promise.resolve(bodies[1].buffer),
420 });
421
422 const paths = [];
423 for (const mountRelativePath of [first, second]) {
424 paths.push(await new RemoteFile({ ...validCamelCaseData, mountRelativePath }).save());
425 }
426
427 expect(new Set(paths).size).toBe(2);
428 expect(paths.map(path => new Uint8Array(platform.readFileSync(path)))).toEqual(bodies);
429 });
430
431 it('should preserve concurrent default saves within the filename byte limit', async () => {
432 const { platform } = await import('../../src/platform/node');
433 const bodies = [new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3])];
434 let nextBody = 0;
435 globalThis.fetch = vi.fn().mockImplementation(() => {
436 const body = bodies[nextBody++];
437 return Promise.resolve({ ok: true, arrayBuffer: () => Promise.resolve(body.buffer) });
438 });
439 const files = bodies.map(
440 () =>
441 new RemoteFile({
442 ...validCamelCaseData,
443 mountRelativePath: `${'請'.repeat(41)}.pdf`,
444 })
445 );
446
447 const paths = await Promise.all(files.map(file => file.save()));
448
449 expect(new Set(paths).size).toBe(3);
450 expect(paths.map(path => new Uint8Array(platform.readFileSync(path)))).toEqual(bodies);
451 for (const path of paths) {
452 const name = path.slice(path.lastIndexOf('/') + 1);
453 expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(128);
454 expect(name.endsWith('.pdf')).toBe(true);
455 }
456 });
457
458 // Each of these would make the save path equal its own directory (or the
459 // parent), which previously surfaced as an unhandled `EISDIR` from
460 // `writeFileSync` after the directory had already been created.
461 it.each(['', '.', 'sub/.', 'foo/..', '..', '\u00a0.\u00a0', '\u2007..\u2007'])(
462 'should reject mountRelativePath %j before downloading',
463 async mountRelativePath => {
464 const { platform } = await import('../../src/platform/node');
465 const file = new RemoteFile({ ...validCamelCaseData, mountRelativePath });
466 const fetchMock = vi.fn().mockRejectedValue(new Error('Download unavailable'));
467 globalThis.fetch = fetchMock;
468
469 await expect(file.save()).rejects.toThrow(ValidationError);
470 await expect(file.save()).rejects.toThrow(/leaves no usable basename/);
471 expect(fetchMock).not.toHaveBeenCalled();
472 expect(platform.existsSync(composioDir)).toBe(false);
473 }
474 );
475
476 it('should still honor an explicit path when the mount path is unusable', async () => {
477 const { platform } = await import('../../src/platform/node');
478 const { join } = await import('node:path');
479 const file = new RemoteFile({ ...validCamelCaseData, mountRelativePath: '..' });
480 const savePath = join(homeDir, 'explicit.pdf');
481
482 await expect(file.save(savePath)).resolves.toBe(savePath);
483 expect(platform.existsSync(savePath)).toBe(true);
484 });
485 });
486 });
487 });