1
+/**
2
+ * Behavior matrix for the file upload / download gating introduced with
3
+ * `fileUploadDirs` and `fileDownloadDir`. Exercises the interaction between:
4
+ *
5
+ * - `dangerouslyAllowAutoUploadDownloadFiles` (off | on)
6
+ * - Caller (automatic via `tools.execute` | manual via `composio.files.*`)
7
+ * - Direction (upload | download)
8
+ * - `fileUploadDirs` shape (`undefined`, `false`, `[]`, `string[]`)
9
+ *
10
+ * Runtime filesystem operations and HTTP are mocked; we only assert what the
11
+ * SDK tries to do and what errors it raises.
12
+ */
13
+
14
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
15
+import * as os from 'node:os';
16
+import * as path from 'node:path';
17
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
18
+import ComposioClient from '@composio/client';
19
+
20
+import { Tools } from '../../src/models/Tools';
21
+import { Files } from '../../src/models/Files.node';
22
+import * as fileUtilsModule from '../../src/utils/fileUtils.node';
23
+import { mockClient } from '../utils/mocks/client.mock';
24
+import { MockProvider } from '../utils/mocks/provider.mock';
25
+import {
26
+ ComposioFileUploadPathNotAllowedError,
27
+ ComposioFileNotFoundError,
28
+} from '../../src/errors/FileModifierErrors';
29
+import { getDefaultUploadDir } from '../../src/utils/fileDirs';
30
+
31
+// Mock network-bound helpers so we can assert inputs without hitting the API.
32
+vi.mock('../../src/utils/fileUtils.node', async importOriginal => {
33
+ const actual = await importOriginal<typeof import('../../src/utils/fileUtils.node')>();
34
+ return {
35
+ ...actual,
36
+ downloadFileFromS3: vi.fn(),
37
+ // Keep the real `getFileDataAfterUploadingToS3` so path checks run, but
38
+ // stub the S3 upload happening inside it.
39
+ uploadFileToS3: vi.fn(),
40
+ };
41
+});
42
+
43
+const mkTemp = () => mkdtempSync(path.join(os.tmpdir(), 'composio-matrix-'));
44
+
45
+const makeTools = (opts: {
46
+ dangerouslyAllowAutoUploadDownloadFiles?: boolean;
47
+ fileUploadDirs?: string[] | false;
48
+ fileDownloadDir?: string;
49
+}) => {
50
+ return new Tools(mockClient as unknown as ComposioClient, {
51
+ provider: new MockProvider(),
52
+ ...opts,
53
+ });
54
+};
55
+
56
+describe('File handling matrix — Tools constructor resolves allowlist correctly', () => {
57
+ afterEach(() => vi.clearAllMocks());
58
+
59
+ describe('dangerouslyAllowAutoUploadDownloadFiles = false (default)', () => {
60
+ it('leaves fileUploadAllowlist undefined (auto-upload code path is never run)', () => {
61
+ const t = makeTools({});
62
+ // `fileUploadAllowlist` lives on the private options the class forwards
63
+ // to FileToolModifier. When the flag is off we leave it undefined so the
64
+ // modifier isn't even constructed.
65
+ expect(
66
+ (t as unknown as { fileUploadPathOptions: { fileUploadAllowlist?: string[] } })
67
+ .fileUploadPathOptions.fileUploadAllowlist
68
+ ).toBeUndefined();
69
+ });
70
+
71
+ it('ignores fileUploadDirs entirely (including `false`)', () => {
72
+ const t = makeTools({ fileUploadDirs: false });
73
+ expect(
74
+ (t as unknown as { fileUploadPathOptions: { fileUploadAllowlist?: string[] } })
75
+ .fileUploadPathOptions.fileUploadAllowlist
76
+ ).toBeUndefined();
77
+ });
78
+ });
79
+
80
+ describe('dangerouslyAllowAutoUploadDownloadFiles = true', () => {
81
+ it('defaults fileUploadAllowlist to [~/.composio/temp] when fileUploadDirs is unset', () => {
82
+ const t = makeTools({ dangerouslyAllowAutoUploadDownloadFiles: true });
83
+ const opts = (t as unknown as { fileUploadPathOptions: { fileUploadAllowlist?: string[] } })
84
+ .fileUploadPathOptions;
85
+ expect(opts.fileUploadAllowlist).toEqual([getDefaultUploadDir()]);
86
+ });
87
+
88
+ it('resolves to [] when fileUploadDirs is `false` (explicit "no local paths")', () => {
89
+ const t = makeTools({
90
+ dangerouslyAllowAutoUploadDownloadFiles: true,
91
+ fileUploadDirs: false,
92
+ });
93
+ const opts = (t as unknown as { fileUploadPathOptions: { fileUploadAllowlist?: string[] } })
94
+ .fileUploadPathOptions;
95
+ expect(opts.fileUploadAllowlist).toEqual([]);
96
+ });
97
+
98
+ it('resolves to [] when fileUploadDirs is `[]` (alias for `false`)', () => {
99
+ const t = makeTools({
100
+ dangerouslyAllowAutoUploadDownloadFiles: true,
101
+ fileUploadDirs: [],
102
+ });
103
+ const opts = (t as unknown as { fileUploadPathOptions: { fileUploadAllowlist?: string[] } })
104
+ .fileUploadPathOptions;
105
+ expect(opts.fileUploadAllowlist).toEqual([]);
106
+ });
107
+
108
+ it('uses user-provided dirs verbatim when fileUploadDirs is a non-empty array', () => {
109
+ const dir = mkTemp();
110
+ try {
111
+ const t = makeTools({
112
+ dangerouslyAllowAutoUploadDownloadFiles: true,
113
+ fileUploadDirs: [dir],
114
+ });
115
+ const opts = (t as unknown as { fileUploadPathOptions: { fileUploadAllowlist?: string[] } })
116
+ .fileUploadPathOptions;
117
+ expect(opts.fileUploadAllowlist).toEqual([path.resolve(dir)]);
118
+ } finally {
119
+ rmSync(dir, { recursive: true, force: true });
120
+ }
121
+ });
122
+ });
123
+});
124
+
125
+describe('File handling matrix — manual Files API bypasses the allowlist', () => {
126
+ const mkClient = () =>
127
+ ({
128
+ baseURL: 'https://api.composio.dev',
129
+ apiKey: 'test',
130
+ }) as unknown as ComposioClient;
131
+
132
+ beforeEach(() => vi.clearAllMocks());
133
+
134
+ it('composio.files.upload() accepts a local path that is NOT in any allowlist', async () => {
135
+ const tmp = mkTemp();
136
+ try {
137
+ const file = path.join(tmp, 'a.txt');
138
+ writeFileSync(file, 'x');
139
+
140
+ // Stub the actual S3 call so the manual upload can complete.
141
+ const stubbed = vi.spyOn(fileUtilsModule, 'getFileDataAfterUploadingToS3');
142
+ stubbed.mockResolvedValueOnce({ name: 'a.txt', mimetype: 'text/plain', s3key: 'k' });
143
+
144
+ const files = new Files(mkClient());
145
+ const result = await files.upload({
146
+ file,
147
+ toolSlug: 'T',
148
+ toolkitSlug: 'tk',
149
+ });
150
+
151
+ expect(result.s3key).toBe('k');
152
+
153
+ // The call must NOT include a `fileUploadAllowlist` — that's what keeps
154
+ // manual upload unconstrained.
155
+ const callArg = stubbed.mock.calls[0]?.[1] as { fileUploadAllowlist?: unknown };
156
+ expect(callArg.fileUploadAllowlist).toBeUndefined();
157
+ } finally {
158
+ rmSync(tmp, { recursive: true, force: true });
159
+ }
160
+ });
161
+
162
+ it('composio.files.download() works regardless of `dangerouslyAllowAutoUploadDownloadFiles`', async () => {
163
+ const downloadMock = vi.spyOn(fileUtilsModule, 'downloadFileFromS3');
164
+ downloadMock.mockResolvedValueOnce({
165
+ name: 'x.txt',
166
+ mimeType: 'text/plain',
167
+ s3Url: 'https://s3.example/x',
168
+ filePath: '/tmp/fake/x.txt',
169
+ });
170
+
171
+ const files = new Files(mkClient(), { fileDownloadDir: '/var/app/dl' });
172
+ const res = await files.download({
173
+ toolSlug: 'T',
174
+ s3Url: 'https://s3.example/x',
175
+ mimeType: 'text/plain',
176
+ });
177
+
178
+ expect(res.filePath).toBe('/tmp/fake/x.txt');
179
+ // The manual download path forwards the configured `fileDownloadDir`.
180
+ expect(downloadMock.mock.calls[0]?.[0]).toMatchObject({
181
+ fileDownloadDir: '/var/app/dl',
182
+ });
183
+ });
184
+});
185
+
186
+describe('File handling matrix — auto upload honors the resolved allowlist', () => {
187
+ let getFileDataSpy: ReturnType<typeof vi.spyOn>;
188
+
189
+ beforeEach(() => {
190
+ vi.clearAllMocks();
191
+ // Keep the real implementation so allowlist enforcement runs, but stub the
192
+ // S3 upload that happens inside it.
193
+ getFileDataSpy = vi.spyOn(fileUtilsModule, 'uploadFileToS3' as never);
194
+ (getFileDataSpy as unknown as { mockResolvedValue: (v: string) => void }).mockResolvedValue(
195
+ 's3-key'
196
+ );
197
+ });
198
+
199
+ const callUpload = async (file: string, fileUploadAllowlist: string[] | undefined) => {
200
+ return fileUtilsModule.getFileDataAfterUploadingToS3(file, {
201
+ toolSlug: 'T',
202
+ toolkitSlug: 'tk',
203
+ client: mockClient as unknown as ComposioClient,
204
+ fileUploadAllowlist,
205
+ });
206
+ };
207
+
208
+ it('rejects local paths outside the allowlist with ComposioFileUploadPathNotAllowedError', async () => {
209
+ const allowed = mkTemp();
210
+ const outside = mkTemp();
211
+ try {
212
+ const file = path.join(outside, 'leak.txt');
213
+ writeFileSync(file, 'x');
214
+ await expect(callUpload(file, [allowed])).rejects.toBeInstanceOf(
215
+ ComposioFileUploadPathNotAllowedError
216
+ );
217
+ } finally {
218
+ rmSync(allowed, { recursive: true, force: true });
219
+ rmSync(outside, { recursive: true, force: true });
220
+ }
221
+ });
222
+
223
+ it('rejects ALL local paths when allowlist is [] (the `false` / fail-closed case)', async () => {
224
+ const tmp = mkTemp();
225
+ try {
226
+ const file = path.join(tmp, 'a.txt');
227
+ writeFileSync(file, 'x');
228
+ await expect(callUpload(file, [])).rejects.toBeInstanceOf(
229
+ ComposioFileUploadPathNotAllowedError
230
+ );
231
+ } finally {
232
+ rmSync(tmp, { recursive: true, force: true });
233
+ }
234
+ });
235
+
236
+ it('allows URLs even when allowlist is [] (URLs are never path-checked)', async () => {
237
+ // Stub global fetch so `readFile` (URL branch) doesn't hit the network.
238
+ const fetchSpy = vi
239
+ .spyOn(globalThis, 'fetch')
240
+ .mockRejectedValueOnce(new Error('stubbed-network'));
241
+
242
+ // Passes the allowlist gate (because the URL isn't a local path), then
243
+ // fails at the network layer. Any non-allowlist error proves the gate
244
+ // didn't reject the URL.
245
+ const http = 'https://example.com/file.pdf';
246
+ await expect(callUpload(http, [])).rejects.toThrowError('stubbed-network');
247
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
248
+ });
249
+
250
+ it('raises ComposioFileNotFoundError when the file is missing under auto-upload', async () => {
251
+ const allowed = mkTemp();
252
+ try {
253
+ const missing = path.join(allowed, 'nope.txt');
254
+ await expect(callUpload(missing, [allowed])).rejects.toBeInstanceOf(
255
+ ComposioFileNotFoundError
256
+ );
257
+ } finally {
258
+ rmSync(allowed, { recursive: true, force: true });
259
+ }
260
+ });
261
+
262
+ it('does NOT throw an allowlist error when the file is inside an allowed dir', async () => {
263
+ // We can't easily stub the S3 upload from outside the module, so we just
264
+ // assert the error (if any) is not the allowlist rejection. The happy
265
+ // path for `assertPathInsideUploadDirs` itself is covered directly in
266
+ // `test/utils/uploadDirAllowlist.test.ts`.
267
+ const allowed = mkTemp();
268
+ try {
269
+ const file = path.join(allowed, 'ok.txt');
270
+ writeFileSync(file, 'x');
271
+ try {
272
+ await callUpload(file, [allowed]);
273
+ } catch (err) {
274
+ expect(err).not.toBeInstanceOf(ComposioFileUploadPathNotAllowedError);
275
+ expect(err).not.toBeInstanceOf(ComposioFileNotFoundError);
276
+ }
277
+ } finally {
278
+ rmSync(allowed, { recursive: true, force: true });
279
+ }
280
+ });
281
+});