@devries-cameron20 / composio Mirror · read-only / commits / ebc977859
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, 22:15 UTC

feat(sdk): default-off auto file upload/download; add dangerouslyAllowAutoUploadDownloadFiles (#3260)

## Summary Automatic tool file upload/download for `file_uploadable` fields is **off by default** in TypeScript and Python. Callers must explicitly opt in, and uploads from local paths are constrained by a fail-closed allowlist. ## Changes - **Removed (breaking):** `autoUploadDownloadFiles` (TS) / `auto_upload_download_files` (Python) — the legacy default-on flag is gone, not just deprecated. - **New opt-in:** `dangerouslyAllowAutoUploadDownloadFiles` (TS) / `dangerously_allow_auto_upload_download_files` (Python). When `true`, `tools.get(...)` collapses `file_uploadable` schemas to `{ type: 'string', format: 'path' }` and the SDK stages local paths/URLs at execute time. - **New:** `fileUploadDirs?: string[] | false` — fail-closed allowlist for local upload paths. `undefined` → `[<home>/.composio/temp]`; `false` → reject all local paths (URLs / `File` objects unaffected); explicit `string[]` replaces the default. Components are matched on a path boundary after `realpath`. - **New:** `fileDownloadDir?: string` — directory where `file_downloadable` results are staged. - **New:** `beforeFileUpload` hook receives `source: 'path' | 'url' | 'file'` (TS) / `'path' | 'url'` (Python) so it can branch on input type. - **New (TS):** when auto-upload is **off** and an LLM-driven `tools.execute` is called against a tool with `file_uploadable` inputs, the SDK emits a one-shot warning per tool slug pointing at `composio.files.upload()` for manual staging. ## Migration To restore previous behavior: ```ts new Composio({ apiKey: process.env.COMPOSIO_API_KEY!, dangerouslyAllowAutoUploadDownloadFiles: true, // Optional: tighten the allowlist beyond the default ~/.composio/temp fileUploadDirs: ['/srv/uploads'], }); ``` ```python Composio(api_key="...", dangerously_allow_auto_upload_download_files=True) ``` If you previously passed the legacy flag, remove it. There is no transitional warning — TS and Python both reject the unknown property at the type/keyword-arg level. ## Versioning | Package | Bump | | ------- | ---- | | `@composio/core` | minor | | `composio` (Python) | minor | | Other `@composio/*` packages | patch (via changesets `updateInternalDependencies: "patch"`) | See `docs/content/changelog/04-24-26-legacy-auto-upload-config-removal.mdx` for the full migration writeup.

Musthaq Ahamad committed Apr 28, 2026 at 10:55 UTC ebc977859573090708ef5c9c0abdd7c0a7ec3498
58 files changed +2892 -236
.changeset/fluffy-kids-lose.md new
+16
@@ -0,0 +1,16 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Make automatic file upload/download opt-in and add scoped allowlist controls.
6 +
7 +- **Removed:** the legacy `autoUploadDownloadFiles` constructor option. Code that sets it must migrate to the new opt-in flag.
8 +- **Added:** `dangerouslyAllowAutoUploadDownloadFiles` (default `false`). When `true`, the SDK collapses `file_uploadable` schemas to `{ type: 'string', format: 'path' }` for the model and stages local paths/URLs at execute time.
9 +- **Added:** `fileUploadDirs?: string[] | false` — fail-closed allowlist for local upload paths. `undefined` defaults to `[<home>/.composio/temp]`; `false` rejects all local paths; an explicit `string[]` replaces the default.
10 +- **Added:** `fileDownloadDir?: string` — directory used to stage S3 downloads on `file_downloadable` results.
11 +- **Added:** `beforeFileUpload` modifier now receives `source: 'path' | 'url' | 'file'` so hooks can branch on the original input type.
12 +- **Added:** when auto-upload is **off** but a tool with `file_uploadable` inputs is executed, the SDK emits a one-shot warning per tool slug pointing at `composio.files.upload()` for manual staging.
13 +
14 +See the changelog entry at [`docs/content/changelog/04-24-26-legacy-auto-upload-config-removal.mdx`](https://github.com/ComposioHQ/composio/blob/master/docs/content/changelog/04-24-26-legacy-auto-upload-config-removal.mdx) for migration steps.
15 +
16 +Provider packages that depend on `@composio/core` receive automatic patch bumps in the same release train via the changesets `updateInternalDependencies: "patch"` setting — no public-API change in those packages.
docs/content/changelog/01-29-26-sdk-major-update.mdx
+4
@@ -242,6 +242,10 @@ Changed the `autoUploadDownloadFiles` default configuration for the Cloudflare W
242 }
243 ```
244
245 +<Callout type="warn">
246 +**Removed in a later release.** The `autoUploadDownloadFiles` flag described above was removed in the v0.7.0 / Python v0.12.0 release train. Automatic file handling is now off by default on every runtime, and you opt in with `dangerouslyAllowAutoUploadDownloadFiles` instead. See [SDKs remove legacy automatic file handling config](/docs/changelog/2026/04/24) for the full migration.
247 +</Callout>
248 +
249 **Benefits:**
250
251 - **Zero config** for common use cases
docs/content/changelog/03-23-26-custom-tools-and-toolkits.mdx
+1
@@ -23,6 +23,7 @@ Custom tools support three patterns — standalone tools for internal logic, ext
23 <Tab value="TypeScript">
24
25 ```typescript
26 +// @noErrors
27 import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
28 import { z } from "zod/v3";
29 // ---cut---
docs/content/changelog/04-07-26-bearer-token-patch.mdx
+1
@@ -29,6 +29,7 @@ See the [importing connections guide](/docs/importing-existing-connections) for
29 New `PATCH /api/v3/connected_accounts/{nanoid}` endpoint and SDK method — update credentials and alias on existing connections without recreating them.
30
31 ```typescript
32 +// @noErrors
33 import { Composio } from '@composio/core';
34 const composio = new Composio({ apiKey: 'your-api-key' });
35 // ---cut---
docs/content/changelog/04-09-26-multi-account-aliases.mdx
+2
@@ -11,6 +11,7 @@ This release adds two features for managing multiple accounts per toolkit.
11 Sessions now support a `multiAccount` config that lets users connect and use multiple accounts for the same toolkit (e.g., work and personal Gmail) within a single session.
12
13 ```typescript
14 +// @noErrors
15 import { Composio } from '@composio/core';
16 const composio = new Composio({ apiKey: 'your_api_key' });
17 // ---cut---
@@ -30,6 +31,7 @@ By default, multi-account mode is disabled and each session uses one account per
31 Connected accounts can now have human-readable aliases (e.g., `"work-gmail"`, `"personal-github"`). Aliases can be set during connection or updated after.
32
33 ```typescript
34 +// @noErrors
35 import { Composio } from '@composio/core';
36 const composio = new Composio({ apiKey: 'your_api_key' });
37 const session = await composio.create('user_123');
docs/content/changelog/04-24-26-legacy-auto-upload-config-removal.mdx new
+156
@@ -0,0 +1,156 @@
1 +---
2 +title: 'SDKs remove legacy automatic file handling config'
3 +description: 'SDKs remove deprecated `autoUploadDownloadFiles` / `auto_upload_download_files`. Automatic file handling is off unless you set `dangerouslyAllowAutoUploadDownloadFiles` / `dangerously_allow_auto_upload_download_files`. Minor releases.'
4 +date: '2026-04-24'
5 +---
6 +
7 +The Composio SDKs no longer accept the legacy flags that previously controlled automatic file upload and download during tool execution. Automatic handling of `file_uploadable` fields stays **off by default**; you opt in with the explicit `dangerously*` option only.
8 +
9 +<Callout type="warn">
10 +**Breaking change**
11 +
12 +Those legacy properties are removed from the public constructors and config types. Code that still passes them must migrate. Anyone who **relied on the old default-on behavior** (no file flag in the constructor) must now **explicitly** set the `dangerously*` flag to `true` to keep automatic path/URL file handling.
13 +</Callout>
14 +
15 +### SDK versions (minor releases)
16 +
17 +| Package | Previous | This release |
18 +| ------- | -------- | ------------ |
19 +| TypeScript `@composio/core` | v0.6.11 | **v0.7.0** |
20 +| Python `composio` | v0.11.6 | **v0.12.0** |
21 +
22 +Other `@composio/*` npm packages that depend on core are published as **patch** bumps in the same release train (via the changesets `updateInternalDependencies: "patch"` setting) so they pick up the updated `ComposioConfig` surface — they have no public-API changes of their own.
23 +
24 +### Migration
25 +
26 +Earlier SDK versions treated automatic file upload/download for `file_uploadable` tool fields as **on by default** (TypeScript: `autoUploadDownloadFiles` defaulted to `true` when unset; Python followed the same idea for `auto_upload_download_files` in prior releases). **That default is now off.** If you still want that behavior, you must **explicitly** set `dangerouslyAllowAutoUploadDownloadFiles: true` (TypeScript) or `dangerously_allow_auto_upload_download_files=True` (Python).
27 +
28 +**TypeScript — before (legacy):**
29 +
30 +```typescript
31 +// @noErrors
32 +// If you omitted autoUploadDownloadFiles, it used to default to true
33 +new Composio({
34 + apiKey: process.env.COMPOSIO_API_KEY!,
35 +});
36 +
37 +// Equivalent when you set it explicitly:
38 +new Composio({
39 + apiKey: process.env.COMPOSIO_API_KEY!,
40 + autoUploadDownloadFiles: true,
41 +});
42 +```
43 +
44 +**TypeScript — going forward** (set `true` to match either legacy pattern above):
45 +
46 +```typescript
47 +// @noErrors
48 +new Composio({
49 + apiKey: process.env.COMPOSIO_API_KEY!,
50 + dangerouslyAllowAutoUploadDownloadFiles: true,
51 +});
52 +```
53 +
54 +To leave automatic file handling **off** (new default), omit `dangerouslyAllowAutoUploadDownloadFiles` or set it to `false`.
55 +
56 +**Python — before (legacy):**
57 +
58 +```python
59 +# If you omitted auto_upload_download_files, it used to default to True (prior releases)
60 +Composio(api_key="...")
61 +
62 +# Equivalent when you set it explicitly:
63 +Composio(api_key="...", auto_upload_download_files=True)
64 +```
65 +
66 +**Python — going forward** (set `True` to match either legacy pattern above):
67 +
68 +```python
69 +Composio(api_key="...", dangerously_allow_auto_upload_download_files=True)
70 +```
71 +
72 +If you construct `ToolRouterSession` directly (unusual), the keyword argument is now `dangerously_allow_auto_upload_download_files` instead of `auto_upload_download_files`.
73 +
74 +### Local paths must live inside an allowlisted directory
75 +
76 +Even with `dangerouslyAllowAutoUploadDownloadFiles` enabled, the SDK will **only** auto-upload local file paths that resolve inside an allowlisted directory. Paths outside the allowlist are rejected with `ComposioFileUploadPathNotAllowed` (TypeScript) / `FileUploadPathNotAllowed` (Python) before any file is read or sent.
77 +
78 +This is a behavior change. Earlier SDK versions had no allowlist: any local path the legacy default-on flag saw was uploaded.
79 +
80 +**Default allowlist:**
81 +
82 +| `fileUploadDirs` value | Effective allowlist |
83 +| ---------------------- | ------------------- |
84 +| omitted / `undefined` | `[ <home>/.composio/temp ]` (default staging dir) |
85 +| `false` | `[]` — **all** local paths rejected (URLs and `File` objects still work) |
86 +| `[]` | `[]` — same as `false`; explicit "no local paths" |
87 +| `[<dir1>, <dir2>, …]` | exactly those directories (replaces the default; `~` is expanded, paths are `realpath`-resolved, comparison is on a path-component boundary) |
88 +
89 +URLs (`http://…` / `https://…`) and JavaScript `File` objects are **not** subject to the allowlist — only local string paths are.
90 +
91 +**TypeScript:**
92 +
93 +```typescript
94 +// @noErrors
95 +// Match the *broadest* legacy behavior: auto-upload on, allowlist widened to
96 +// the directories your code actually reads from. Set this scope as tightly
97 +// as you can — every path inside these dirs becomes uploadable to Composio.
98 +new Composio({
99 + apiKey: process.env.COMPOSIO_API_KEY!,
100 + dangerouslyAllowAutoUploadDownloadFiles: true,
101 + fileUploadDirs: ['/srv/uploads', '~/data/inbox'],
102 +});
103 +
104 +// Disallow local-path uploads entirely; the SDK will only stage URLs and
105 +// File objects, and reject string paths outright.
106 +new Composio({
107 + apiKey: process.env.COMPOSIO_API_KEY!,
108 + dangerouslyAllowAutoUploadDownloadFiles: true,
109 + fileUploadDirs: false,
110 +});
111 +```
112 +
113 +**Python:**
114 +
115 +```python
116 +# Equivalent of the TypeScript example above.
117 +Composio(
118 + api_key="...",
119 + dangerously_allow_auto_upload_download_files=True,
120 + file_upload_dirs=["/srv/uploads", "~/data/inbox"],
121 +)
122 +
123 +# Reject all local paths.
124 +Composio(
125 + api_key="...",
126 + dangerously_allow_auto_upload_download_files=True,
127 + file_upload_dirs=False,
128 +)
129 +```
130 +
131 +**Manual staging (TypeScript only):**
132 +
133 +If you don't want to widen the allowlist, the TypeScript SDK lets you stage files yourself via `composio.files.upload(...)`. That call **bypasses the allowlist** by design (the caller is expected to control the path), and the returned `{ name, mimetype, s3key }` descriptor can be passed straight into `tools.execute`:
134 +
135 +```typescript
136 +// @noErrors
137 +const staged = await composio.files.upload({
138 + file: '/anywhere/on/disk/report.pdf',
139 + toolSlug: 'GOOGLEDRIVE_UPLOAD_FILE',
140 + toolkitSlug: 'googledrive',
141 +});
142 +
143 +await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {
144 + userId: 'user-1',
145 + arguments: { file_to_upload: staged },
146 +});
147 +```
148 +
149 +The Python SDK does not currently expose a top-level manual-staging API; opt in with `dangerously_allow_auto_upload_download_files=True` and configure `file_upload_dirs` to cover the directories your code reads from.
150 +
151 +### What else changed
152 +
153 +- TypeScript: `resolveAutoUploadDownloadFilesEnabled` only considers `dangerouslyAllowAutoUploadDownloadFiles`; the old deprecation warning for the legacy property is removed.
154 +- Python: the small `composio.utils.auto_upload_download` helper that merged legacy + new flags is removed; `Tools` and `ToolRouter` take only the explicit opt-in boolean.
155 +
156 +Documentation for [executing tools](/docs/tools-direct/executing-tools) and the TypeScript [Composio reference](/reference/sdk-reference/typescript/composio) is updated to describe defaults and the opt-in flag.
docs/content/docs/configuring-sessions.mdx
+10
@@ -14,6 +14,7 @@ session = composio.create(user_id="user_123")
14 </Tab>
15 <Tab value="TypeScript">
16 ```typescript
17 +// @noErrors
18 import { Composio } from '@composio/core';
19 const composio = new Composio({ apiKey: 'your_api_key' });
20 // ---cut---
@@ -48,6 +49,7 @@ session = composio.create(
49 </Tab>
50 <Tab value="TypeScript">
51 ```typescript
52 +// @noErrors
53 import { Composio } from '@composio/core';
54 const composio = new Composio({ apiKey: 'your_api_key' });
55 // ---cut---
@@ -79,6 +81,7 @@ session = composio.create(
81 </Tab>
82 <Tab value="TypeScript">
83 ```typescript
84 +// @noErrors
85 import { Composio } from '@composio/core';
86 const composio = new Composio({ apiKey: 'your_api_key' });
87 // ---cut---
@@ -107,6 +110,7 @@ session = composio.create(
110 </Tab>
111 <Tab value="TypeScript">
112 ```typescript
113 +// @noErrors
114 import { Composio } from '@composio/core';
115 const composio = new Composio({ apiKey: 'your_api_key' });
116 // ---cut---
@@ -140,6 +144,7 @@ session = composio.create(
144 </Tab>
145 <Tab value="TypeScript">
146 ```typescript
147 +// @noErrors
148 import { Composio } from '@composio/core';
149 const composio = new Composio({ apiKey: 'your_api_key' });
150 // ---cut---
@@ -182,6 +187,7 @@ session = composio.create(
187 </Tab>
188 <Tab value="TypeScript">
189 ```typescript
190 +// @noErrors
191 import { Composio } from '@composio/core';
192 const composio = new Composio({ apiKey: 'your_api_key' });
193 // ---cut---
@@ -213,6 +219,7 @@ mcp_url = session.mcp.url
219 </Tab>
220 <Tab value="TypeScript">
221 ```typescript
222 +// @noErrors
223 import { Composio } from '@composio/core';
224 const composio = new Composio({ apiKey: 'your_api_key' });
225 const session = await composio.create("user_123");
@@ -237,6 +244,7 @@ tools = session.tools()
244 </Tab>
245 <Tab value="TypeScript">
246 ```typescript
247 +// @noErrors
248 import { Composio } from '@composio/core';
249 const composio = new Composio({ apiKey: 'your_api_key' });
250 const session = await composio.create("user_123");
@@ -262,6 +270,7 @@ connected_account = connection_request.wait_for_connection()
270 </Tab>
271 <Tab value="TypeScript">
272 ```typescript
273 +// @noErrors
274 import { Composio } from '@composio/core';
275 const composio = new Composio({ apiKey: 'your_api_key' });
276 const session = await composio.create("user_123");
@@ -295,6 +304,7 @@ for toolkit in toolkits.items:
304 </Tab>
305 <Tab value="TypeScript">
306 ```typescript
307 +// @noErrors
308 import { Composio } from '@composio/core';
309 const composio = new Composio({ apiKey: 'your_api_key' });
310 const session = await composio.create("user_123");
docs/content/docs/importing-existing-connections.mdx
+7
@@ -52,6 +52,7 @@ print(f"Connected: {connection.id}")
52 </Tab>
53 <Tab value="TypeScript">
54 ```typescript
55 +// @noErrors
56 import { Composio, AuthScheme } from '@composio/core';
57
58 const composio = new Composio({ apiKey: 'your-api-key' });
@@ -102,6 +103,7 @@ print(f"Connected: {connection.id}")
103 </Tab>
104 <Tab value="TypeScript">
105 ```typescript
106 +// @noErrors
107 import { Composio, AuthScheme } from '@composio/core';
108
109 const composio = new Composio({ apiKey: 'your-api-key' });
@@ -147,6 +149,7 @@ print(f"Connected: {connection.id}")
149 </Tab>
150 <Tab value="TypeScript">
151 ```typescript
152 +// @noErrors
153 import { Composio, AuthScheme } from '@composio/core';
154
155 const composio = new Composio({ apiKey: 'your-api-key' });
@@ -190,6 +193,7 @@ composio.connected_accounts.update(
193 </Tab>
194 <Tab value="TypeScript">
195 ```typescript
196 +// @noErrors
197 import { Composio } from '@composio/core';
198 const composio = new Composio({ apiKey: 'your-api-key' });
199 // ---cut---
@@ -230,6 +234,7 @@ composio.connected_accounts.update(
234 </Tab>
235 <Tab value="TypeScript">
236 ```typescript
237 +// @noErrors
238 import { Composio } from '@composio/core';
239 const composio = new Composio({ apiKey: 'your-api-key' });
240 // ---cut---
@@ -270,6 +275,7 @@ composio.connected_accounts.update(
275 </Tab>
276 <Tab value="TypeScript">
277 ```typescript
278 +// @noErrors
279 import { Composio } from '@composio/core';
280 const composio = new Composio({ apiKey: 'your-api-key' });
281 // ---cut---
@@ -311,6 +317,7 @@ session = composio.create(
317 </Tab>
318 <Tab value="TypeScript">
319 ```typescript
320 +// @noErrors
321 import { Composio } from '@composio/core';
322 const composio = new Composio({ apiKey: 'your-api-key' });
323 // ---cut---
docs/content/docs/managing-multiple-connected-accounts.mdx
+6
@@ -25,6 +25,7 @@ session = composio.create(
25 </Tab>
26 <Tab value="TypeScript">
27 ```typescript
28 +// @noErrors
29 import { Composio } from '@composio/core';
30 const composio = new Composio({ apiKey: 'your_api_key' });
31 // ---cut---
@@ -71,6 +72,7 @@ personal_connection = personal_auth.wait_for_connection()
72 </Tab>
73 <Tab value="TypeScript">
74 ```typescript
75 +// @noErrors
76 import { Composio } from '@composio/core';
77 const composio = new Composio({ apiKey: 'your_api_key' });
78 // ---cut---
@@ -128,6 +130,7 @@ connection_request = composio.connected_accounts.link(
130 </Tab>
131 <Tab value="TypeScript">
132 ```typescript
133 +// @noErrors
134 import { Composio } from '@composio/core';
135 const composio = new Composio({ apiKey: 'your_api_key' });
136 const session = await composio.create("user_123");
@@ -166,6 +169,7 @@ composio.connected_accounts.update("ca_abc123", alias="")
169 </Tab>
170 <Tab value="TypeScript">
171 ```typescript
172 +// @noErrors
173 import { Composio } from '@composio/core';
174 const composio = new Composio({ apiKey: 'your_api_key' });
175 // ---cut---
@@ -196,6 +200,7 @@ session = composio.create(
200 </Tab>
201 <Tab value="TypeScript">
202 ```typescript
203 +// @noErrors
204 import { Composio } from '@composio/core';
205 const composio = new Composio({ apiKey: 'your_api_key' });
206 // ---cut---
@@ -225,6 +230,7 @@ for toolkit in toolkits.items:
230 </Tab>
231 <Tab value="TypeScript">
232 ```typescript
233 +// @noErrors
234 import { Composio } from '@composio/core';
235 const composio = new Composio({ apiKey: 'your_api_key' });
236 const session = await composio.create("user_123");
docs/content/docs/toolkits/custom-tools-and-toolkits.mdx
+11
@@ -49,6 +49,7 @@ pip install composio
49 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
50 <Tab value="TypeScript">
51 ```typescript
52 +// @noErrors
53 import { Composio } from "@composio/core";
54
55 const composio = new Composio({ apiKey: "your_api_key" });
@@ -72,6 +73,7 @@ A standalone tool handles internal app logic that doesn't need Composio auth. `c
73 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
74 <Tab value="TypeScript">
75 ```typescript
76 +// @noErrors
77 import { Composio, experimental_createTool } from "@composio/core";
78 import { z } from "zod/v3";
79 // ---cut---
@@ -132,6 +134,7 @@ Pass custom tools via the `experimental` option. `session.tools()` returns both
134 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
135 <Tab value="TypeScript">
136 ```typescript
137 +// @noErrors
138 import { Composio, experimental_createTool } from "@composio/core";
139 import { z } from "zod/v3";
140
@@ -194,6 +197,7 @@ pip install composio
197 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
198 <Tab value="TypeScript">
199 ```typescript
200 +// @noErrors
201 import { Composio } from "@composio/core";
202
203 const composio = new Composio({ apiKey: "your_api_key" });
@@ -219,6 +223,7 @@ Prefer relative `endpoint` values in proxy calls. They resolve against the toolk
223 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
224 <Tab value="TypeScript">
225 ```typescript
226 +// @noErrors
227 import { Composio, experimental_createTool } from "@composio/core";
228 import { z } from "zod/v3";
229 // ---cut---
@@ -298,6 +303,7 @@ Pass custom tools via the `experimental` option. Extension tools inherit auth fr
303 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
304 <Tab value="TypeScript">
305 ```typescript
306 +// @noErrors
307 import { Composio, experimental_createTool } from "@composio/core";
308 import { z } from "zod/v3";
309
@@ -362,6 +368,7 @@ pip install composio
368 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
369 <Tab value="TypeScript">
370 ```typescript
371 +// @noErrors
372 import { Composio } from "@composio/core";
373
374 const composio = new Composio({ apiKey: "your_api_key" });
@@ -385,6 +392,7 @@ A custom toolkit groups related standalone tools under a namespace. Tools inside
392 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
393 <Tab value="TypeScript">
394 ```typescript
395 +// @noErrors
396 import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
397 import { z } from "zod/v3";
398 // ---cut---
@@ -443,6 +451,7 @@ Pass custom toolkits via the `experimental` option. `session.tools()` returns bo
451 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
452 <Tab value="TypeScript">
453 ```typescript
454 +// @noErrors
455 import { Composio, experimental_createToolkit } from "@composio/core";
456 import { z } from "zod/v3";
457
@@ -531,6 +540,7 @@ Use these methods to list registered tools and toolkits. Slugs include their fin
540 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
541 <Tab value="TypeScript">
542 ```typescript
543 +// @noErrors
544 import { Composio } from "@composio/core";
545 const composio = new Composio({ apiKey: "your_api_key" });
546 const session = await composio.create("user_1");
@@ -554,6 +564,7 @@ Use `session.execute()` to run custom tools directly, outside of an agent loop.
564 <Tabs groupId="language" items={['TypeScript', 'Python']} persist>
565 <Tab value="TypeScript">
566 ```typescript
567 +// @noErrors
568 import { Composio } from "@composio/core";
569 const composio = new Composio({ apiKey: "your_api_key" });
570 const session = await composio.create("user_1");
docs/content/docs/tools-direct/executing-tools.mdx
+75 -11
@@ -312,7 +312,7 @@ Need an API that isn't supported by any Composio toolkit, or want to extend an e
312
313 ## Automatic File Handling
314
315 -Composio handles file operations automatically. Pass file paths to tools that need them, and get local file paths back from tools that return files.
315 +Automatic file handling is **off by default**. Enable it with `dangerouslyAllowAutoUploadDownloadFiles: true` (TypeScript) or `dangerously_allow_auto_upload_download_files=True` (Python). Once enabled, pass file paths to tools that accept files and get local paths back from tools that return files.
316
317 ### File Upload
318
@@ -321,6 +321,11 @@ Pass local file paths, URLs, or File objects to tools that accept files:
321 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
322 <Tab value="Python">
323 ```python
324 +composio = Composio(
325 + api_key="your_composio_key",
326 + dangerously_allow_auto_upload_download_files=True,
327 +)
328 +
329 # Upload a local file to Google Drive
330 result = composio.tools.execute(
331 slug="GOOGLEDRIVE_UPLOAD_FILE",
@@ -333,9 +338,13 @@ print(result) # Print Google Drive file details
338 </Tab>
339 <Tab value="TypeScript">
340 ```typescript
341 +// @noErrors
342 import { Composio } from '@composio/core';
343 import path from 'path';
338 -const composio = new Composio({ apiKey: 'your_api_key' });
344 +const composio = new Composio({
345 + apiKey: 'your_api_key',
346 + dangerouslyAllowAutoUploadDownloadFiles: true,
347 +});
348 // ---cut---
349 // Upload a local file to Google Drive
350 const result = await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {
@@ -359,7 +368,8 @@ When tools return files, Composio downloads them to the local directory and prov
368 ```python
369 composio = Composio(
370 api_key="your_composio_key",
362 - file_download_dir="./downloads" # Optional: Specify download directory
371 + dangerously_allow_auto_upload_download_files=True,
372 + file_download_dir="./downloads", # Optional: Specify download directory
373 )
374
375 result = composio.tools.execute(
@@ -374,8 +384,12 @@ print(result)
384 </Tab>
385 <Tab value="TypeScript">
386 ```typescript
387 +// @noErrors
388 import { Composio } from '@composio/core';
378 -const composio = new Composio({ apiKey: 'your_api_key' });
389 +const composio = new Composio({
390 + apiKey: 'your_api_key',
391 + dangerouslyAllowAutoUploadDownloadFiles: true,
392 +});
393 // ---cut---
394 // Download a file from Google Drive
395 const result = await composio.tools.execute('GOOGLEDRIVE_DOWNLOAD_FILE', {
@@ -438,7 +452,13 @@ composio = Composio(
452 import { Composio, type beforeFileUploadModifier } from '@composio/core';
453 import path from 'node:path';
454 const composio = new Composio({ apiKey: 'your_api_key' });
441 -const beforeFileUpload: beforeFileUploadModifier = async ctx => ctx.path;
455 +// ctx.source is 'path' | 'url' | 'file' — useful if you only want to audit
456 +// local paths and let URLs / File objects pass through unchanged.
457 +const beforeFileUpload: beforeFileUploadModifier = async ctx => {
458 + if (ctx.source !== 'path') return ctx.path;
459 + // ...audit ctx.path...
460 + return ctx.path;
461 +};
462 // ---cut---
463 await composio.tools.execute(
464 'GOOGLEDRIVE_UPLOAD_FILE',
@@ -456,9 +476,14 @@ await composio.tools.execute(
476 import os
477 from composio import Composio, before_file_upload
478
479 +# New form: take a single ``context`` arg; ``context["source"]`` is "path"
480 +# or "url". The legacy ``(path, tool, toolkit)`` 3-arg form is still accepted.
481 @before_file_upload(tools=["GOOGLEDRIVE_UPLOAD_FILE"])
460 -def audit_path(path: str, tool: str, toolkit: str) -> str | bool:
461 - return path
482 +def audit_path(ctx) -> str | bool:
483 + if ctx["source"] != "path":
484 + return ctx["path"]
485 + # ...audit ctx["path"]...
486 + return ctx["path"]
487
488 composio = Composio()
489
@@ -474,9 +499,40 @@ composio.tools.execute(
499
500 **Errors:** `ComposioSensitiveFilePathBlockedError` / `SensitiveFilePathBlockedError` when a path is blocked; `ComposioFileUploadAbortedError` / `FileUploadAbortedError` when the hook returns `false` (or equivalent abort).
501
477 -### Disabling Auto File Handling
502 +### Automatic file handling (off by default)
503 +
504 +Both SDKs ship with automatic file handling **off**. Opt in with `dangerouslyAllowAutoUploadDownloadFiles: true` (TypeScript) or `dangerously_allow_auto_upload_download_files=True` (Python). Even with the flag enabled, **local paths must resolve inside an allowlisted directory** — see the matrix in the [legacy auto-upload removal changelog](/docs/changelog/2026/04/24) for the full `fileUploadDirs` / `file_upload_dirs` semantics.
505 +
506 +When auto-handling is off, handle the staging yourself.
507 +
508 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
509 + <Tab value="Python">
510 +The Python SDK does not expose a top-level manual-staging API. Either:
511 +
512 +1. Enable auto-handling and configure `file_upload_dirs` to cover the directories your code reads from:
513 +
514 +```python
515 +from composio import Composio
516 +
517 +composio = Composio(
518 + api_key="your_composio_key",
519 + dangerously_allow_auto_upload_download_files=True,
520 + file_upload_dirs=["/srv/agent/uploads", "~/.composio/temp"],
521 +)
522 +```
523
479 -You can disable automatic file handling when initializing the TypeScript SDK. When disabled, handle file uploads and downloads manually using `files.upload` and `files.download`:
524 +2. Or keep auto-handling off and pass an already-staged `{ "name", "mimetype", "s3key" }` dict directly into `tools.execute`. Pre-stage your files via your own pipeline (or an upstream tool) and inject the descriptor:
525 +
526 +```python
527 +result = composio.tools.execute(
528 + "GOOGLEDRIVE_UPLOAD_FILE",
529 + user_id="user-1",
530 + arguments={"file_to_upload": prestaged_descriptor},
531 +)
532 +```
533 + </Tab>
534 + <Tab value="TypeScript">
535 +With `dangerouslyAllowAutoUploadDownloadFiles: false` (the default), call `composio.files.upload(...)` to stage paths/URLs explicitly. That call bypasses `fileUploadDirs` by design — the caller controls the path:
536
537 ```typescript
538 import { Composio } from '@composio/core';
@@ -484,16 +540,24 @@ import path from 'path';
540 // ---cut---
541 const composio = new Composio({
542 apiKey: process.env.COMPOSIO_API_KEY,
487 - autoUploadDownloadFiles: false
543 + // Default: dangerouslyAllowAutoUploadDownloadFiles is false; set true only to opt in
544 });
545
490 -// Now you need to handle files manually using composio.files API
546 +// Stage manually using composio.files API
547 const fileData = await composio.files.upload({
548 file: path.join(__dirname, 'document.pdf'),
549 toolSlug: 'GOOGLEDRIVE_UPLOAD_FILE',
550 toolkitSlug: 'googledrive'
551 });
552 +
553 +// Then pass the { name, mimetype, s3key } descriptor into tools.execute
554 +await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {
555 + userId: 'user-1',
556 + arguments: { file_to_upload: fileData },
557 +});
558 ```
559 + </Tab>
560 +</Tabs>
561
562 ## What to read next
563
docs/content/docs/tools-direct/modify-tool-behavior/before-execution-modifiers.mdx
+10 -2
@@ -184,13 +184,21 @@ For tools with `file_uploadable` parameters, the SDK can read a local path and u
184
185 See [Executing tools: security for local file paths](/docs/tools-direct/executing-tools#security-for-local-file-paths) for constructor options, errors, and a full tabbed example.
186
187 +The hook takes either a single `context` argument (preferred) or the legacy
188 +3-arg `(path, tool, toolkit)` form. The context object exposes
189 +`context["source"]` — `"path"` for local filesystem inputs and `"url"` for
190 +`http(s)://...` inputs — so you can scope audits to just local paths:
191 +
192 ```python
193 from composio import Composio, before_file_upload
194
195 @before_file_upload(tools=["GOOGLEDRIVE_UPLOAD_FILE"])
191 -def audit_path(path: str, tool: str, toolkit: str) -> str | bool:
196 +def audit_path(ctx) -> str | bool:
197 + # ctx = {"path": ..., "source": "path" | "url", "tool": ..., "toolkit": ...}
198 + if ctx["source"] != "path":
199 + return ctx["path"] # let URLs through untouched
200 # return a new path string, or False to abort the upload
193 - return path
201 + return ctx["path"]
202
203 composio = Composio()
204 composio.tools.execute(
docs/content/reference/sdk-reference/python/composio.mdx
+92
@@ -15,3 +15,95 @@ description: "Composio SDK for Python. Generic parameters: TTool: The individua
15 | [`mcp`](/reference/sdk-reference/python/mcp) | `MCP` |
16
17 [View source](https://github.com/composiohq/composio/blob/next/python/composio/sdk.py#L46)
18 +
19 +---
20 +
21 +## Constructor
22 +
23 +```python
24 +Composio(
25 + provider: BaseProvider | None = None,
26 + *,
27 + api_key: str | None = None,
28 + base_url: str | None = None,
29 + timeout: int | None = None,
30 + max_retries: int | None = None,
31 + toolkit_versions: dict[str, str] | str | None = None,
32 + dangerously_allow_auto_upload_download_files: bool = False,
33 + sensitive_file_upload_protection: bool = True,
34 + file_upload_path_deny_segments: Sequence[str] | None = None,
35 + file_upload_dirs: Sequence[str] | Literal[False] | None = None,
36 + file_download_dir: str | None = None,
37 + allow_tracking: bool = True,
38 + environment: str = "production",
39 +)
40 +```
41 +
42 +`api_key` falls back to `os.environ["COMPOSIO_API_KEY"]` when not passed.
43 +
44 +### Common options
45 +
46 +| Option | Type | Default | Description |
47 +|--------|------|---------|-------------|
48 +| `provider` | `BaseProvider` | `OpenAIProvider()` | Provider used to wrap tools (Anthropic, LangChain, Gemini, etc.). |
49 +| `api_key` | `str` | `$COMPOSIO_API_KEY` | API key. Required. |
50 +| `base_url` | `str` | Composio default | Override the API base URL. |
51 +| `timeout` | `int` | client default | Per-request timeout in seconds. |
52 +| `max_retries` | `int` | `3` | HTTP client retry count. |
53 +| `toolkit_versions` | `dict \| str \| None` | `'latest'` | Pin toolkit versions globally (string) or per-toolkit (dict). |
54 +
55 +---
56 +
57 +## File upload security
58 +
59 +Automatic file handling for `file_uploadable` tool fields is **off by default**. Set `dangerously_allow_auto_upload_download_files=True` to opt in. Once on, the SDK can read local paths and stage them to S3 on your behalf, but only from an allowlisted set of directories.
60 +
61 +| Option | Type | Default | Description |
62 +|--------|------|---------|-------------|
63 +| `dangerously_allow_auto_upload_download_files` | `bool` | `False` | Master opt-in. When `False`, paths and URLs in `file_uploadable` arguments are forwarded as-is — the backend will reject anything that isn't already a staged `{name, mimetype, s3key}` descriptor. Set to `True` to let the SDK stage local paths and URLs on your behalf at execute time. |
64 +| `sensitive_file_upload_protection` | `bool` | `True` | Block local paths matching a built-in denylist of segments (`.ssh`, `.aws`, etc.) and credential-like file names. Disable only if you accept the tradeoff. |
65 +| `file_upload_path_deny_segments` | `Sequence[str] \| None` | `None` | Extra single path components merged with the built-in denylist. |
66 +| `file_upload_dirs` | `Sequence[str] \| Literal[False] \| None` | `[~/.composio/temp]` | Allowlist of directories the SDK may read during **automatic** upload. Pass `False` (or `[]`) to reject every local path — URLs still work. Providing a list **replaces** the default; include `~/.composio/temp` explicitly if you want the default staging dir to keep working. Comparison is on a path-component boundary after `os.path.realpath`. On Windows, entries are compared case-insensitively. |
67 +| `file_download_dir` | `str \| None` | `~/.composio/files` | Directory where files from tool responses marked `file_downloadable` are streamed. |
68 +
69 +Per-execution hooks live on the `modifiers=[...]` argument to `composio.tools.execute`, not on the constructor. Use the `@before_file_upload` decorator from `composio.core.models._modifiers` to inspect or rewrite each path before it is read. The hook context includes a `source` field (`'path' | 'url'`) so you can branch on local paths vs URLs.
70 +
71 +**Related errors:** `FileUploadPathNotAllowed`, `SensitiveFilePathBlocked`, `FileUploadAbortedError`, `SDKFileNotFoundError` (all from `composio.exceptions`).
72 +
73 +### Restricting automatic uploads to specific directories
74 +
75 +When `dangerously_allow_auto_upload_download_files=True`, the SDK only reads local files from directories listed in `file_upload_dirs`. This stacks with (it does NOT replace) the sensitive-path denylist.
76 +
77 +```python
78 +from composio import Composio
79 +
80 +composio = Composio(
81 + api_key="your_composio_key",
82 + dangerously_allow_auto_upload_download_files=True,
83 + # Replaces the default `[~/.composio/temp]`. List every directory you want
84 + # the SDK to read from during tool execution.
85 + file_upload_dirs=["/srv/agent/uploads", "~/.composio/temp"],
86 +)
87 +```
88 +
89 +Pass `file_upload_dirs=False` (or `[]`) to reject every filesystem path; URLs and in-memory bytes still upload normally:
90 +
91 +```python
92 +Composio(
93 + api_key="your_composio_key",
94 + dangerously_allow_auto_upload_download_files=True,
95 + file_upload_dirs=False,
96 +)
97 +```
98 +
99 +### Tool-Router session files
100 +
101 +The Tool-Router session API exposes a separate files surface (`session.files.upload(...)` / `session.files.download(...)`) for streaming files into and out of a long-running router session. Those calls are unrelated to the `file_uploadable` schema flow on individual tool execution and are not gated by `dangerously_allow_auto_upload_download_files` or `file_upload_dirs`. See [`tool-router-session`](/reference/sdk-reference/python/tool-router-session) for usage.
102 +
103 +---
104 +
105 +## See also
106 +
107 +- [Executing tools](/docs/tools-direct/executing-tools) — automatic vs. manual file handling, before-execute modifiers.
108 +- [Before-execution modifiers](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers#before-file-upload-python) — `@before_file_upload` decorator and the context-form hook signature.
109 +- [Legacy auto-upload config removal changelog](/docs/changelog/2026/04/24) — migration from the removed `auto_upload_download_files` flag and the allowlist semantics matrix.
docs/content/reference/sdk-reference/typescript/composio.mdx
+27 -3
@@ -180,15 +180,39 @@ getConfig(): ComposioConfig
180
181 ## File upload security
182
183 -When `autoUploadDownloadFiles` is true (default), the SDK can read local file paths and upload them before tool execution. The constructor accepts options that work together with the optional `beforeFileUpload` modifier on `tools.execute` (see [Executing tools: security](/docs/tools-direct/executing-tools#security-for-local-file-paths)).
183 +When `dangerouslyAllowAutoUploadDownloadFiles` is true, the SDK can read local file paths and upload them before tool execution (this behavior is **off** by default). The constructor accepts options that work together with the optional `beforeFileUpload` modifier on `tools.execute` (see [Executing tools: security](/docs/tools-direct/executing-tools#security-for-local-file-paths)).
184
185 | Option | Type | Default | Description |
186 |--------|------|---------|-------------|
187 | `sensitiveFileUploadProtection` | `boolean` | `true` | When true, local path strings for auto-upload and `files.upload` are checked against a built-in denylist of path segments (for example `.ssh`, `.aws`) and credential-like file names. Set to `false` only if you accept the security tradeoff. |
188 | `fileUploadPathDenySegments` | `string[]` | `undefined` | Additional single path *components* (directory or file names) merged with the built-in list; matched anywhere in the resolved path. |
189 +| `fileUploadDirs` | `string[] \| false` | `[~/.composio/temp]` | Allowlist of directories the SDK may read during **automatic** upload (when `dangerouslyAllowAutoUploadDownloadFiles: true`). Pass `false` (or `[]`) to reject every local path; URLs and `File`/`Blob` objects still work. Providing a list **replaces** the default — include `~/.composio/temp` explicitly if you want the default staging dir to keep working. Does **not** affect manual `composio.files.upload()` calls. |
190 +| `fileDownloadDir` | `string` | `~/.composio/files` | Directory where files from tool responses marked `file_downloadable` are streamed. |
191
190 -Pass **`beforeFileUpload`** on the **third argument** to `composio.tools.execute` (with `beforeExecute` / `afterExecute`), not on the constructor. The hook runs for each `file_uploadable` value before read/upload: return a path string, `false` to abort, or throw.
192 +Pass **`beforeFileUpload`** on the **third argument** to `composio.tools.execute` (with `beforeExecute` / `afterExecute`), not on the constructor. The hook runs for each `file_uploadable` value before read/upload: return a path string, `false` to abort, or throw. The hook's context includes a `source` field (`'path' | 'url' | 'file'`) so it can scope its logic to local paths vs URLs vs `File` objects.
193
192 -**Related errors:** `ComposioSensitiveFilePathBlockedError`, `ComposioFileUploadAbortedError` (from `@composio/core`).
194 +**Related errors:** `ComposioSensitiveFilePathBlockedError`, `ComposioFileUploadAbortedError`, `ComposioFileUploadPathNotAllowedError`, `ComposioFileNotFoundError` (from `@composio/core`).
195 +
196 +### Restricting automatic uploads to specific directories
197 +
198 +When `dangerouslyAllowAutoUploadDownloadFiles: true`, the SDK only reads local
199 +files from directories in `fileUploadDirs`. This stacks with (it does NOT
200 +replace) the sensitive-path denylist.
201 +
202 +```typescript
203 +// @noErrors
204 +import { Composio } from '@composio/core';
205 +
206 +const composio = new Composio({
207 + apiKey: process.env.COMPOSIO_API_KEY!,
208 + dangerouslyAllowAutoUploadDownloadFiles: true,
209 + // Replaces the default `[~/.composio/temp]`. List every directory you want
210 + // the SDK to read from during tool execution.
211 + fileUploadDirs: ['/srv/agent/uploads', '~/.composio/temp'],
212 +});
213 +```
214 +
215 +Pass `fileUploadDirs: false` (or `[]`) to reject every filesystem path; URLs
216 +and in-memory `File`/`Blob` objects still upload normally.
217
218 ---
docs/examples/chat-app/page-with-tools.tsx
+1 -1
@@ -1,4 +1,4 @@
1 -// @errors: 2307
1 +// @noErrors
2 "use client";
3
4 import { useState } from "react";
docs/examples/chat-app/page.tsx
+1
@@ -1,3 +1,4 @@
1 +// @noErrors
2 "use client";
3
4 import { useState } from "react";
python/composio/core/models/_files.py
+79 -27
@@ -26,10 +26,14 @@ from composio.utils import mimetypes
26 from composio.utils.sensitive_file_upload_paths import (
27 assert_safe_local_file_upload_path,
28 )
29 +from composio.utils.upload_dir_allowlist import (
30 + assert_path_inside_upload_dirs,
31 +)
32 from composio.utils.logging import WithLogger
33
34 if t.TYPE_CHECKING:
35 from .tools import ToolExecutionResponse
36 + from ._modifiers import BeforeFileUploadContextCallable # noqa: F401
37
38 _DEFAULT_CHUNK_SIZE = 1024 * 1024
39 _FILE_UPLOAD = "/api/v3/files/upload/request"
@@ -86,9 +90,12 @@ except OSError as e:
90 ) from e
91
92
89 -LOCAL_OUTPUT_FILE_DIRECTORY = LOCAL_CACHE_DIRECTORY / "outputs"
93 +LOCAL_OUTPUT_FILE_DIRECTORY = LOCAL_CACHE_DIRECTORY / "files"
94 """
91 -Local output file directory name for composio tools
95 +Default local directory into which files downloaded during tool execution are
96 +written. Previously ``<cache>/outputs``; now ``<cache>/files`` for parity with
97 +the TypeScript SDK. Override by passing ``file_download_dir=...`` to Composio,
98 +or by setting ``outdir`` on ``FileHelper`` directly.
99 """
100
101
@@ -106,7 +113,11 @@ def get_md5(file: Path) -> str:
113 Returns:
114 Hexadecimal MD5 hash string
115 """
109 - obj = hashlib.md5()
116 + # `usedforsecurity=False` lets this run on FIPS-mode systems, where
117 + # `hashlib.md5()` without the flag raises `ValueError: [digital envelope
118 + # routines] unsupported`. We're hashing for integrity / deduplication,
119 + # not security — the API just needs the digest for upload verification.
120 + obj = hashlib.md5(usedforsecurity=False)
121 with file.open("rb") as fp:
122 while True:
123 line = fp.read(_DEFAULT_CHUNK_SIZE)
@@ -345,7 +356,7 @@ def _upload_bytes_to_s3(
356 toolkit: str,
357 ) -> str:
358 """Upload bytes content to S3 and return the S3 key."""
348 - md5_hash = hashlib.md5(content).hexdigest()
359 + md5_hash = hashlib.md5(content, usedforsecurity=False).hexdigest()
360
361 s3meta = client.post(
362 path=_FILE_UPLOAD,
@@ -423,9 +434,8 @@ class FileUploadable(BaseModel):
434 *,
435 sensitive_file_upload_protection: bool = True,
436 file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,
426 - before_file_upload: t.Optional[
427 - t.Callable[[str, str, str], t.Union[str, bool]]
428 - ] = None,
437 + file_upload_allowlist: t.Optional[t.Sequence[Path]] = None,
438 + before_file_upload: t.Optional["BeforeFileUploadContextCallable"] = None,
439 ) -> te.Self:
440 """Create a FileUploadable from a local file path or public URL.
441
@@ -439,27 +449,34 @@ class FileUploadable(BaseModel):
449 :param toolkit: The toolkit slug
450 :param sensitive_file_upload_protection: When True, block paths on the built-in denylist.
451 :param file_upload_path_deny_segments: Extra path segment names to merge with the built-in list.
442 - :param before_file_upload: Optional ``(path, tool, toolkit) -> str | bool``; return a new path string, or False to abort.
452 + :param file_upload_allowlist: When provided (not None), local paths must
453 + resolve inside one of these directories on a component boundary.
454 + Pass ``None`` to skip the check (e.g. manual upload APIs). URLs are
455 + never checked against the allowlist. An empty sequence means
456 + "no paths are allowed" (fail-closed).
457 + :param before_file_upload: Optional context-form hook produced by
458 + :func:`composio.core.models._modifiers.merge_before_file_upload`.
459 + Receives ``{"path", "source", "tool", "toolkit"}`` where ``source``
460 + is ``"url"`` for ``http(s)://...`` inputs and ``"path"`` for local
461 + filesystem paths. Return a new string to substitute, or ``False``
462 + to abort.
463 :return: FileUploadable instance with S3 key
464 """
465 file_str = str(file) if isinstance(file, Path) else file
446 -
447 - # Check if it's a URL
448 - if isinstance(file_str, str) and _is_url(file_str):
449 - path_in = file_str
450 - if before_file_upload is not None:
451 - out = before_file_upload(path_in, tool, toolkit)
452 - if out is False:
453 - raise FileUploadAbortedError(
454 - "File upload was aborted because before_file_upload returned False."
455 - )
456 - if isinstance(out, str):
457 - path_in = out
458 - return cls.from_url(client=client, url=path_in, tool=tool, toolkit=toolkit)
459 -
466 path_in = file_str
467 + source: t.Literal["url", "path"] = (
468 + "url" if isinstance(file_str, str) and _is_url(file_str) else "path"
469 + )
470 +
471 if before_file_upload is not None:
462 - out = before_file_upload(path_in, tool, toolkit)
472 + out = before_file_upload(
473 + {
474 + "path": path_in,
475 + "source": source,
476 + "tool": tool,
477 + "toolkit": toolkit,
478 + }
479 + )
480 if out is False:
481 raise FileUploadAbortedError(
482 "File upload was aborted because before_file_upload returned False."
@@ -467,6 +484,21 @@ class FileUploadable(BaseModel):
484 if isinstance(out, str):
485 path_in = out
486
487 + # Re-decide routing on the post-hook value: a URL-source hook may return
488 + # a local path (and vice versa). Re-checking with `_is_url` keeps the
489 + # URL fetch path and the local-file path properly separated, so a hook
490 + # cannot, for example, smuggle `/etc/passwd` past the URL branch's
491 + # missing allowlist/denylist by rewriting the URL into a path.
492 + if isinstance(path_in, str) and _is_url(path_in):
493 + return cls.from_url(client=client, url=path_in, tool=tool, toolkit=toolkit)
494 +
495 + # Allowlist check runs BEFORE the denylist / existence checks when enabled,
496 + # so the "configure file_upload_dirs" hint fires first for the common case
497 + # (user has auto-upload on but hasn't configured dirs). Caller passes
498 + # ``None`` to bypass the allowlist (manual upload APIs).
499 + if file_upload_allowlist is not None:
500 + assert_path_inside_upload_dirs(path_in, file_upload_allowlist)
501 +
502 assert_safe_local_file_upload_path(
503 path_in,
504 enabled=sensitive_file_upload_protection,
@@ -527,7 +559,11 @@ class FileDownloadable(BaseModel):
559 return outfile
560
561
530 -BeforeFileUpload = t.Callable[[str, str, str], t.Union[str, bool]]
562 +# Internal alias — ``FileHelper`` receives the already-adapted context-form
563 +# callable produced by :func:`merge_before_file_upload`.
564 +from composio.core.models._modifiers import ( # noqa: E402
565 + BeforeFileUploadContextCallable as BeforeFileUpload,
566 +)
567
568
569 class FileHelper(WithLogger):
@@ -538,12 +574,24 @@ class FileHelper(WithLogger):
574 *,
575 sensitive_file_upload_protection: bool = True,
576 file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,
577 + file_upload_allowlist: t.Optional[t.Sequence[Path]] = None,
578 ) -> None:
579 + """
580 + :param outdir: Where files downloaded during tool execution are written.
581 + Defaults to ``~/.composio/files``.
582 + :param file_upload_allowlist: Directories from which local files may be
583 + auto-uploaded. ``None`` disables the allowlist check (used when
584 + auto-upload is off, or for manual upload APIs). An empty list means
585 + "no paths allowed" (fail-closed).
586 + """
587 super().__init__()
588 self._client = client
544 - self._outdir = Path(outdir or LOCAL_OUTPUT_FILE_DIRECTORY)
589 + self._outdir = Path(outdir) if outdir else LOCAL_OUTPUT_FILE_DIRECTORY
590 self._sensitive_file_upload_protection = sensitive_file_upload_protection
591 self._file_upload_path_deny_segments = file_upload_path_deny_segments
592 + self._file_upload_allowlist: t.Optional[t.Sequence[Path]] = (
593 + list(file_upload_allowlist) if file_upload_allowlist is not None else None
594 + )
595
596 def _has_file_property(
597 self, schema: t.Dict, property_name: str = "file_uploadable"
@@ -672,7 +720,7 @@ class FileHelper(WithLogger):
720 - Required notes ("This parameter is required.")
721
722 This is separate from file processing and should always run
675 - regardless of the auto_upload_download_files setting.
723 + regardless of `dangerously_allow_auto_upload_download_files`.
724 """
725 required = schema.get("required") or []
726 for _param, _schema in schema["properties"].items():
@@ -694,7 +742,8 @@ class FileHelper(WithLogger):
742 """Process file_uploadable fields in schema.
743
744 This method converts file_uploadable fields to path format.
697 - Should only be called when auto_upload_download_files is True.
745 + Should only be called when the caller opted in via
746 + `dangerously_allow_auto_upload_download_files=True`.
747 Recursively handles anyOf, oneOf, allOf, nested properties, and array items.
748 """
749 if "properties" not in schema:
@@ -770,6 +819,7 @@ class FileHelper(WithLogger):
819 toolkit=tool.toolkit.slug,
820 sensitive_file_upload_protection=self._sensitive_file_upload_protection,
821 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
822 + file_upload_allowlist=self._file_upload_allowlist,
823 before_file_upload=before_file_upload,
824 ).model_dump()
825 continue
@@ -790,6 +840,7 @@ class FileHelper(WithLogger):
840 toolkit=tool.toolkit.slug,
841 sensitive_file_upload_protection=self._sensitive_file_upload_protection,
842 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
843 + file_upload_allowlist=self._file_upload_allowlist,
844 before_file_upload=before_file_upload,
845 ).model_dump()
846 continue
@@ -841,6 +892,7 @@ class FileHelper(WithLogger):
892 toolkit=tool.toolkit.slug,
893 sensitive_file_upload_protection=self._sensitive_file_upload_protection,
894 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
895 + file_upload_allowlist=self._file_upload_allowlist,
896 before_file_upload=before_file_upload,
897 ).model_dump()
898 )
python/composio/core/models/_modifiers.py
+123 -11
@@ -66,7 +66,12 @@ class SchemaModifier(t.Protocol):
66
67
68 class BeforeFileUploadCallable(t.Protocol):
69 - """Called for each local file path before read/upload (``file_uploadable``)."""
69 + """Legacy positional form of the ``before_file_upload`` hook.
70 +
71 + ``(path, tool, toolkit) -> str | bool``. Still supported for back-compat,
72 + but new code should use :class:`BeforeFileUploadContextCallable` so it can
73 + discriminate local paths from URLs via ``context["source"]``.
74 + """
75
76 def __call__(
77 self,
@@ -76,6 +81,83 @@ class BeforeFileUploadCallable(t.Protocol):
81 ) -> t.Union[str, bool]: ...
82
83
84 +class BeforeFileUploadContext(te.TypedDict):
85 + """Context passed to the new-form ``before_file_upload`` hook.
86 +
87 + - ``path``: the local filesystem path for ``source="path"``, or the URL
88 + string for ``source="url"``.
89 + - ``source``: discriminator — ``"path"`` for local paths, ``"url"`` for
90 + ``http(s)://...`` inputs. Mirrors the TypeScript SDK's ``source`` field
91 + (TS additionally emits ``"file"`` for ``File`` objects; Python has no
92 + equivalent runtime type).
93 + - ``tool`` / ``toolkit``: slugs of the tool being executed.
94 + """
95 +
96 + path: str
97 + source: te.Literal["path", "url"]
98 + tool: str
99 + toolkit: str
100 +
101 +
102 +class BeforeFileUploadContextCallable(t.Protocol):
103 + """Preferred form of the ``before_file_upload`` hook.
104 +
105 + Takes a single :class:`BeforeFileUploadContext` argument and returns either
106 + a new path/URL string, or ``False`` to abort the upload.
107 + """
108 +
109 + def __call__(
110 + self,
111 + context: BeforeFileUploadContext,
112 + ) -> t.Union[str, bool]: ...
113 +
114 +
115 +BeforeFileUploadLike = t.Union[
116 + BeforeFileUploadCallable,
117 + BeforeFileUploadContextCallable,
118 +]
119 +"""Either form of ``before_file_upload``. Adapted internally."""
120 +
121 +
122 +def _count_positional_params(fn: t.Callable) -> int:
123 + """Return the number of positional (or positional-or-keyword) params, or
124 + -1 if the signature can't be introspected (e.g. builtins)."""
125 + import inspect
126 +
127 + try:
128 + sig = inspect.signature(fn)
129 + except (TypeError, ValueError):
130 + return -1
131 + return sum(
132 + 1
133 + for p in sig.parameters.values()
134 + if p.kind
135 + in (
136 + inspect.Parameter.POSITIONAL_ONLY,
137 + inspect.Parameter.POSITIONAL_OR_KEYWORD,
138 + )
139 + )
140 +
141 +
142 +def _adapt_before_file_upload(
143 + hook: BeforeFileUploadLike,
144 +) -> BeforeFileUploadContextCallable:
145 + """Normalise a user-supplied hook to the context-object form.
146 +
147 + A hook declared with exactly 3 positional parameters is treated as the
148 + legacy ``(path, tool, toolkit)`` form; anything else (typically a single
149 + positional ``context`` parameter) is treated as the new form.
150 + """
151 + if _count_positional_params(hook) == 3:
152 + legacy = t.cast(BeforeFileUploadCallable, hook)
153 +
154 + def wrap(context: BeforeFileUploadContext) -> t.Union[str, bool]:
155 + return legacy(context["path"], context["tool"], context["toolkit"])
156 +
157 + return wrap
158 + return t.cast(BeforeFileUploadContextCallable, hook)
159 +
160 +
161 ModifierSlug: t.TypeAlias = str
162 AfterExecuteModifierL: t.TypeAlias = t.Literal["after_execute"]
163 BeforeExecuteModifierL: t.TypeAlias = t.Literal["before_execute"]
@@ -93,6 +175,7 @@ class Modifier:
175 | BeforeExecuteMeta
176 | AfterExecuteMeta
177 | BeforeFileUploadCallable
178 + | BeforeFileUploadContextCallable
179 ],
180 type_: (
181 AfterExecuteModifierL
@@ -222,7 +305,7 @@ def before_execute(
305
306
307 @t.overload
225 -def before_file_upload(modifier: t.Optional[BeforeFileUploadCallable]) -> Modifier: ...
308 +def before_file_upload(modifier: t.Optional[BeforeFileUploadLike]) -> Modifier: ...
309
310
311 @t.overload
@@ -230,19 +313,30 @@ def before_file_upload(
313 *,
314 tools: t.Optional[t.List[str]] = None,
315 toolkits: t.Optional[t.List[str]] = None,
233 -) -> t.Callable[[BeforeFileUploadCallable], Modifier]: ...
316 +) -> t.Callable[[BeforeFileUploadLike], Modifier]: ...
317
318
319 def before_file_upload(
237 - modifier: t.Optional[BeforeFileUploadCallable] = None,
320 + modifier: t.Optional[BeforeFileUploadLike] = None,
321 *,
322 tools: t.Optional[t.List[str]] = None,
323 toolkits: t.Optional[t.List[str]] = None,
241 -) -> Modifier | t.Callable[[BeforeFileUploadCallable], Modifier]:
324 +) -> Modifier | t.Callable[[BeforeFileUploadLike], Modifier]:
325 """
326 Build a ``Modifier`` for the file-upload hook (same scoping pattern as
327 :func:`before_execute`).
328
329 + Your callable may take **either**:
330 +
331 + - a single ``context`` argument (:class:`BeforeFileUploadContext`) — the
332 + preferred form, exposes ``context["source"]`` (``"path"`` or ``"url"``),
333 + or
334 + - three positional arguments ``(path, tool, toolkit)`` — legacy form, kept
335 + for back-compat.
336 +
337 + Return a new path/URL string to substitute, or ``False`` to abort the
338 + upload (raises :class:`~composio.exceptions.FileUploadAbortedError`).
339 +
340 Pass the returned ``Modifier`` in ``modifiers=[...]`` on
341 :meth:`composio.core.models.tools.Tools.execute` or ``tools.get``. Multiple
342 such modifiers are composed in list order.
@@ -257,7 +351,7 @@ def before_file_upload(
351
352 if tools is not None or toolkits is not None:
353 return t.cast(
260 - t.Callable[[BeforeFileUploadCallable], Modifier],
354 + t.Callable[[BeforeFileUploadLike], Modifier],
355 functools.partial(
356 before_file_upload,
357 tools=tools or [],
@@ -392,10 +486,15 @@ def merge_before_file_upload(
486 modifiers: t.Optional[Modifiers],
487 tool: str,
488 toolkit: str,
395 -) -> t.Optional[BeforeFileUploadCallable]:
489 +) -> t.Optional[BeforeFileUploadContextCallable]:
490 """Compose ``before_file_upload``-type :class:`Modifier`\\ s for this *tool* / *toolkit*.
491
492 Scoping matches :class:`Modifier` (empty ``tools`` and ``toolkits`` = all tools).
493 +
494 + Each user-supplied hook is adapted to the context form by
495 + :func:`_adapt_before_file_upload`, so legacy 3-arg callables keep working
496 + while new-form callables receive the full :class:`BeforeFileUploadContext`
497 + (including ``source``).
498 """
499 to_chain = [
500 m
@@ -410,12 +509,25 @@ def merge_before_file_upload(
509 return True
510 return tool in m.tools or toolkit in m.toolkits
511
413 - def combined(path: str, tool: str, toolkit: str) -> t.Union[str, bool]:
414 - p: str = path
415 - for m in to_chain:
512 + adapted_chain = [
513 + (m, _adapt_before_file_upload(t.cast(BeforeFileUploadLike, m.modifier)))
514 + for m in to_chain
515 + ]
516 +
517 + def combined(context: BeforeFileUploadContext) -> t.Union[str, bool]:
518 + p: str = context["path"]
519 + for m, hook in adapted_chain:
520 if not _applies(m):
521 continue
418 - out = t.cast(BeforeFileUploadCallable, m.modifier)(p, tool, toolkit)
522 + # Preserve source/tool/toolkit while forwarding the (possibly
523 + # rewritten) path to the next hook.
524 + next_ctx: BeforeFileUploadContext = {
525 + "path": p,
526 + "source": context["source"],
527 + "tool": context["tool"],
528 + "toolkit": context["toolkit"],
529 + }
530 + out = hook(next_ctx)
531 if out is False:
532 return False
533 if isinstance(out, str):
python/composio/core/models/tool_router.py
+12 -5
@@ -360,24 +360,29 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
360 self,
361 client: HttpClient,
362 provider: t.Optional["BaseProvider[TTool, TToolCollection]"] = None,
363 - auto_upload_download_files: bool = True,
363 + dangerously_allow_auto_upload_download_files: bool = False,
364 sensitive_file_upload_protection: bool = True,
365 file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,
366 + file_upload_dirs: t.Union[t.Sequence[str], t.Literal[False], None] = None,
367 ):
368 """
369 Initialize ToolRouter instance.
370
371 :param client: HTTP client for API calls
372 :param provider: Optional provider for tool wrapping
372 - :param auto_upload_download_files: Whether to automatically upload and download files. Defaults to True.
373 + :param dangerously_allow_auto_upload_download_files: Opt-in for automatic file upload/download. Defaults to False.
374 :param sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload.
375 :param file_upload_path_deny_segments: Extra path segment names to merge with the built-in denylist.
376 + :param file_upload_dirs: Allowlist of directories for auto-upload. See ``Composio`` for details.
377 """
378 super().__init__(client)
379 self._provider = provider
378 - self._auto_upload_download_files = auto_upload_download_files
380 self._sensitive_file_upload_protection = sensitive_file_upload_protection
381 self._file_upload_path_deny_segments = file_upload_path_deny_segments
382 + self._file_upload_dirs = file_upload_dirs
383 + self._auto_upload_download_files = bool(
384 + dangerously_allow_auto_upload_download_files
385 + )
386
387 def _create_mcp_server_config(
388 self,
@@ -809,9 +814,10 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
814 return ToolRouterSession(
815 client=self._client,
816 provider=self._provider,
812 - auto_upload_download_files=self._auto_upload_download_files,
817 + dangerously_allow_auto_upload_download_files=self._auto_upload_download_files,
818 sensitive_file_upload_protection=self._sensitive_file_upload_protection,
819 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
820 + file_upload_dirs=self._file_upload_dirs,
821 session_id=session.session_id,
822 mcp=self._create_mcp_server_config(
823 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
@@ -864,9 +870,10 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
870 return ToolRouterSession(
871 client=self._client,
872 provider=self._provider,
867 - auto_upload_download_files=self._auto_upload_download_files,
873 + dangerously_allow_auto_upload_download_files=self._auto_upload_download_files,
874 sensitive_file_upload_protection=self._sensitive_file_upload_protection,
875 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
876 + file_upload_dirs=self._file_upload_dirs,
877 session_id=session.session_id,
878 mcp=self._create_mcp_server_config(
879 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
python/composio/core/models/tool_router_session.py
+6 -3
@@ -76,9 +76,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
76 *,
77 client: HttpClient,
78 provider: t.Optional[BaseProvider[t.Any, t.Any]],
79 - auto_upload_download_files: bool,
79 + dangerously_allow_auto_upload_download_files: bool,
80 sensitive_file_upload_protection: bool = True,
81 file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,
82 + file_upload_dirs: t.Union[t.Sequence[str], t.Literal[False], None] = None,
83 session_id: str,
84 mcp: t.Any,
85 experimental: "ToolRouterSessionExperimental",
@@ -87,9 +88,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
88 ) -> None:
89 self._client = client
90 self._provider = provider
90 - self._auto_upload_download_files = auto_upload_download_files
91 + self._auto_upload_download_files = dangerously_allow_auto_upload_download_files
92 self._sensitive_file_upload_protection = sensitive_file_upload_protection
93 self._file_upload_path_deny_segments = file_upload_path_deny_segments
94 + self._file_upload_dirs = file_upload_dirs
95 self.session_id = session_id
96 self.mcp = mcp
97 self.experimental = experimental
@@ -146,9 +148,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
148 tools_model = ToolsModel(
149 client=self._client,
150 provider=self._provider,
149 - auto_upload_download_files=self._auto_upload_download_files,
151 + dangerously_allow_auto_upload_download_files=self._auto_upload_download_files,
152 sensitive_file_upload_protection=self._sensitive_file_upload_protection,
153 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
154 + file_upload_dirs=self._file_upload_dirs,
155 )
156
157 router_tools = tools_model.get_raw_tool_router_meta_tools(
python/composio/core/models/tools.py
+26 -5
@@ -2,6 +2,7 @@ from __future__ import annotations
2
3 import functools
4 import typing as t
5 +from pathlib import Path
6
7 import typing_extensions as te
8 from pydantic import BaseModel as PydanticBaseModel
@@ -26,6 +27,7 @@ from composio.core.types import ToolkitVersionParam
27 from composio.exceptions import InvalidParams, NotFoundError, ToolVersionRequiredError
28 from composio.utils.pydantic import none_to_omit
29 from composio.utils.toolkit_version import get_toolkit_version
30 +from composio.utils.upload_dir_allowlist import resolve_effective_upload_allowlist
31
32 from ._modifiers import (
33 Modifiers,
@@ -102,9 +104,10 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
104 provider: BaseProvider[TTool, TToolCollection],
105 file_download_dir: t.Optional[str] = None,
106 toolkit_versions: t.Optional[ToolkitVersionParam] = None,
105 - auto_upload_download_files: bool = True,
107 + dangerously_allow_auto_upload_download_files: bool = False,
108 sensitive_file_upload_protection: bool = True,
109 file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,
110 + file_upload_dirs: t.Union[t.Sequence[str], t.Literal[False], None] = None,
111 ):
112 """
113 Initialize the tools resource.
@@ -113,10 +116,27 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
116 :param provider: The provider to use for the tools resource.
117 :param file_download_dir: Output directory for downloadable files
118 :param toolkit_versions: The versions of the toolkits to use. Defaults to 'latest' if not provided.
116 - :param auto_upload_download_files: Whether to automatically upload and download files. Defaults to True.
119 + :param dangerously_allow_auto_upload_download_files: Opt-in for automatic file upload/download. Defaults to False.
120 :param sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload.
121 :param file_upload_path_deny_segments: Extra path segment names to merge with the built-in denylist.
122 + :param file_upload_dirs: Allowlist of directories from which local files may
123 + be auto-uploaded. Only consulted when
124 + ``dangerously_allow_auto_upload_download_files=True``. See Composio docs
125 + for details.
126 """
127 + self._auto_upload_download_files = bool(
128 + dangerously_allow_auto_upload_download_files
129 + )
130 + # Resolve allowlist once, but only if auto-upload is enabled. When it's
131 + # disabled there's no auto-upload code path, so we pass ``None`` and
132 + # FileHelper won't run the allowlist check either way. Manual APIs (if
133 + # ever added in the future) should also pass ``None``.
134 + resolved_allowlist: t.Optional[t.List[Path]] = (
135 + resolve_effective_upload_allowlist(file_upload_dirs)
136 + if self._auto_upload_download_files
137 + else None
138 + )
139 +
140 self._client = client
141 self._custom_tools = CustomTools(client)
142 self._tool_schemas: t.Dict[str, Tool] = {}
@@ -125,9 +145,9 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
145 outdir=file_download_dir,
146 sensitive_file_upload_protection=sensitive_file_upload_protection,
147 file_upload_path_deny_segments=file_upload_path_deny_segments,
148 + file_upload_allowlist=resolved_allowlist,
149 )
150 self._toolkit_versions = toolkit_versions
130 - self._auto_upload_download_files = auto_upload_download_files
151
152 self.custom_tool = self._custom_tools.register
153 self.provider = provider
@@ -314,13 +334,14 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
334 )
335
336 # Always enhance schema descriptions (type hints and required notes)
317 - # regardless of auto_upload_download_files setting
337 + # regardless of dangerously_allow_auto_upload_download_files
338 for tool in tools_list:
339 tool.input_parameters = self._file_helper.enhance_schema_descriptions(
340 schema=tool.input_parameters,
341 )
342
323 - # Only process file_uploadable schemas when auto_upload_download_files is True
343 + # Only process file_uploadable schemas when the caller opted in via
344 + # `dangerously_allow_auto_upload_download_files=True`.
345 if self._auto_upload_download_files:
346 for tool in tools_list:
347 tool.input_parameters = (
python/composio/exceptions.py
+11
@@ -172,6 +172,17 @@ class SensitiveFilePathBlockedError(FileError):
172 """Raised when a local file path is refused before upload (sensitive directory or credential-like name)."""
173
174
175 +class FileUploadPathNotAllowedError(FileError):
176 + """
177 + Raised when automatic file upload during tool execution is attempted from a
178 + path outside the configured ``file_upload_dirs`` allowlist.
179 +
180 + Only fires for auto-upload (enabled via
181 + ``dangerously_allow_auto_upload_download_files=True``). Manual upload APIs
182 + are not subject to this check.
183 + """
184 +
185 +
186 class FileUploadAbortedError(FileError):
187 """Raised when a ``before_file_upload`` hook returns ``False``."""
188
python/composio/sdk.py
+30 -4
@@ -40,9 +40,10 @@ class SDKConfig(te.TypedDict):
40 allow_tracking: te.NotRequired[bool]
41 file_download_dir: te.NotRequired[str]
42 toolkit_versions: te.NotRequired[ToolkitVersionParam]
43 - auto_upload_download_files: te.NotRequired[bool]
43 + dangerously_allow_auto_upload_download_files: te.NotRequired[bool]
44 sensitive_file_upload_protection: te.NotRequired[bool]
45 file_upload_path_deny_segments: te.NotRequired[t.Sequence[str]]
46 + file_upload_dirs: te.NotRequired[t.Union[t.Sequence[str], t.Literal[False]]]
47
48
49 class Composio(t.Generic[TTool, TToolCollection], WithLogger):
@@ -105,9 +106,25 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
106 - A dictionary mapping toolkit names to specific versions
107 - A string (e.g., 'latest', '20250906_01') to use the same version for all toolkits
108 - None or omitted to use 'latest' as default
108 - :param auto_upload_download_files: Whether to automatically upload and download files. Defaults to True.
109 + :param dangerously_allow_auto_upload_download_files: Opt-in for automatic file
110 + upload and download during tool execution. Defaults to False.
111 :param sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload. Defaults to True.
112 :param file_upload_path_deny_segments: Extra path segment names merged with the built-in denylist.
113 + :param file_upload_dirs: Allowlist of directories from which the SDK is allowed
114 + to read local files during **automatic** file upload (the flow gated by
115 + ``dangerously_allow_auto_upload_download_files=True``).
116 +
117 + - ``None`` (default) -> ``[~/.composio/temp]``.
118 + - ``False`` -> reject every local path during auto-upload. URLs and
119 + in-memory bytes still work because they aren't path-checked.
120 + - ``Sequence[str]`` (non-empty) -> use as the allowlist. A file is accepted
121 + iff its symlink-resolved absolute path is inside one of these directories
122 + on a path-component boundary (``/tmp/foo`` allows ``/tmp/foo/bar`` but
123 + NOT ``/tmp/foo-bar``).
124 + - ``[]`` -> behaves like ``False`` (kept as an alias; prefer ``False``).
125 + - Providing a value REPLACES the default. Include ``~/.composio/temp`` in
126 + your list if you want the default staging dir to keep working.
127 + - On Windows, entries are compared case-insensitively.
128 """
129 WithLogger.__init__(self)
130 api_key = kwargs.get("api_key", os.environ.get("COMPOSIO_API_KEY"))
@@ -140,14 +157,20 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
157 file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = kwargs.get(
158 "file_upload_path_deny_segments"
159 )
160 + file_upload_dirs: t.Union[t.Sequence[str], t.Literal[False], None] = kwargs.get(
161 + "file_upload_dirs"
162 + )
163 self.tools = Tools(
164 client=self._client,
165 provider=actual_provider,
166 file_download_dir=kwargs.get("file_download_dir"),
167 toolkit_versions=toolkit_versions,
148 - auto_upload_download_files=kwargs.get("auto_upload_download_files", True),
168 + dangerously_allow_auto_upload_download_files=kwargs.get(
169 + "dangerously_allow_auto_upload_download_files", False
170 + ),
171 sensitive_file_upload_protection=sensitive_file_upload_protection,
172 file_upload_path_deny_segments=file_upload_path_deny_segments,
173 + file_upload_dirs=file_upload_dirs,
174 )
175
176 self.toolkits = Toolkits(client=self._client)
@@ -165,9 +188,12 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
188 self.tool_router = ToolRouter(
189 client=self._client,
190 provider=actual_provider,
168 - auto_upload_download_files=kwargs.get("auto_upload_download_files", True),
191 + dangerously_allow_auto_upload_download_files=kwargs.get(
192 + "dangerously_allow_auto_upload_download_files", False
193 + ),
194 sensitive_file_upload_protection=sensitive_file_upload_protection,
195 file_upload_path_deny_segments=file_upload_path_deny_segments,
196 + file_upload_dirs=file_upload_dirs,
197 )
198 self.create = self.tool_router.create
199 self.use = self.tool_router.use
python/composio/utils/upload_dir_allowlist.py new
+239
@@ -0,0 +1,239 @@
1 +"""Allowlist enforcement for automatic file upload during tool execution.
2 +
3 +This is only consulted when
4 +``dangerously_allow_auto_upload_download_files=True``. Manual upload APIs are
5 +not subject to the allowlist (parity with the TypeScript SDK).
6 +
7 +- A local path is accepted iff its symlink-resolved absolute path is inside one
8 + of the allowed directories on a path-component boundary. ``/tmp/foo`` allows
9 + ``/tmp/foo/bar`` but NOT ``/tmp/foo-bar``.
10 +- URLs never hit this check.
11 +- User-provided ``file_upload_dirs`` fully REPLACES the default
12 + ``[~/.composio/temp]``.
13 +- On Windows, path comparisons are case-insensitive.
14 +"""
15 +
16 +from __future__ import annotations
17 +
18 +import os
19 +import sys
20 +import typing as t
21 +from pathlib import Path
22 +
23 +from composio.exceptions import (
24 + FileUploadPathNotAllowedError,
25 + SDKFileNotFoundError,
26 +)
27 +
28 +UPLOAD_TEMP_DIRECTORY_NAME = "temp"
29 +
30 +
31 +def get_default_upload_dir() -> t.Optional[Path]:
32 + """Absolute path of the default upload staging directory
33 + (``<home>/.composio/temp``), or None when a home directory cannot be
34 + determined."""
35 + try:
36 + home = Path.home()
37 + except (RuntimeError, OSError):
38 + return None
39 + return (home / ".composio" / UPLOAD_TEMP_DIRECTORY_NAME).resolve()
40 +
41 +
42 +def ensure_dir_exists(p: Path) -> None:
43 + """Best-effort directory creation. Allowlist enforcement still works if
44 + creation fails (e.g. read-only filesystem)."""
45 + try:
46 + p.mkdir(parents=True, exist_ok=True)
47 + except OSError:
48 + pass
49 +
50 +
51 +FileUploadDirs = t.Union[t.Sequence[str], t.Literal[False], None]
52 +"""User-facing type for ``file_upload_dirs``.
53 +
54 +- ``None`` (default) -> use ``[<home>/.composio/temp]``.
55 +- ``False`` -> reject every local path during auto-upload (URLs / bytes still
56 + work).
57 +- ``[]`` -> same as ``False`` (kept as an alias; prefer ``False``).
58 +- ``Sequence[str]`` (non-empty) -> allowlist replacing the default.
59 +"""
60 +
61 +
62 +def resolve_effective_upload_allowlist(
63 + user_dirs: FileUploadDirs,
64 +) -> t.List[Path]:
65 + """Resolve the effective allowlist.
66 +
67 + - ``None`` -> ``[<default>]`` when available, else ``[]`` (fail-closed).
68 + - ``False`` -> ``[]`` (explicit "reject all local paths"). URLs and
69 + in-memory bytes still work because they aren't path-checked.
70 + - ``Sequence[str]`` (including ``[]``) REPLACES the default and is returned
71 + verbatim after ``~``-expansion and ``resolve()``. ``[]`` is treated as
72 + equivalent to ``False``.
73 + - Empty / blank / non-string entries are skipped.
74 + - Duplicates are removed (case-insensitive on Windows).
75 + """
76 + if user_dirs is None:
77 + default = get_default_upload_dir()
78 + return [default] if default is not None else []
79 + if user_dirs is False:
80 + return []
81 +
82 + seen: t.Set[str] = set()
83 + out: t.List[Path] = []
84 + for raw in user_dirs:
85 + if not isinstance(raw, (str, os.PathLike)):
86 + continue
87 + s = str(raw).strip()
88 + if not s:
89 + continue
90 + abs_path = Path(s).expanduser().resolve()
91 + key = str(abs_path).lower() if sys.platform == "win32" else str(abs_path)
92 + if key in seen:
93 + continue
94 + seen.add(key)
95 + out.append(abs_path)
96 + return out
97 +
98 +
99 +def _is_inside_dir(child: Path, parent: Path) -> bool:
100 + """True iff ``child`` equals ``parent`` or is nested inside on a component
101 + boundary. Assumes both are absolute and normalized."""
102 + try:
103 + child_str = str(child)
104 + parent_str = str(parent)
105 + if sys.platform == "win32":
106 + child_str = child_str.lower()
107 + parent_str = parent_str.lower()
108 + if child_str == parent_str:
109 + return True
110 + sep = os.sep
111 + parent_with_sep = parent_str if parent_str.endswith(sep) else parent_str + sep
112 + return child_str.startswith(parent_with_sep)
113 + except OSError:
114 + return False
115 +
116 +
117 +def _format_allowlist(dirs: t.Sequence[Path]) -> str:
118 + if not dirs:
119 + return " (none configured — all local paths are blocked)"
120 + return "\n".join(f" - {d}" for d in dirs)
121 +
122 +
123 +def _build_help_footer(allowlist: t.Sequence[Path]) -> str:
124 + return "\n".join(
125 + [
126 + "",
127 + "Allowed upload directories (file_upload_dirs):",
128 + _format_allowlist(allowlist),
129 + "",
130 + "Fix one of the following:",
131 + "",
132 + " 1. Recommended — move the file under an allowed directory, or add your",
133 + " directory to the allowlist:",
134 + " Composio(",
135 + " file_upload_dirs=['/abs/path/to/uploads', '~/.composio/temp'],",
136 + " )",
137 + " Note: user-provided `file_upload_dirs` REPLACES the default",
138 + " `~/.composio/temp`. Include it explicitly if you want staged uploads",
139 + " to keep working.",
140 + "",
141 + " 2. Pass the file by URL (http://... / https://...) instead of a",
142 + " filesystem path. URLs are never path-checked.",
143 + "",
144 + " 3. (Dangerous) Bypass the allowlist entirely by opting into automatic",
145 + " file upload/download from any readable path:",
146 + " Composio(dangerously_allow_auto_upload_download_files=True, ...)",
147 + " WARNING: This lets a prompt-injected or misbehaving tool read ANY",
148 + " file the process can access. Only enable it in trusted, sandboxed",
149 + " environments. The built-in sensitive-path denylist (.ssh, .aws,",
150 + " .env, private SSH keys, etc.) still applies unless you also set",
151 + " `sensitive_file_upload_protection=False`.",
152 + ]
153 + )
154 +
155 +
156 +def assert_path_inside_upload_dirs(
157 + file_path: t.Union[str, Path],
158 + allowlist: t.Sequence[Path],
159 +) -> None:
160 + """Raise an elaborate error if the path is missing or outside the allowlist.
161 +
162 + :raises SDKFileNotFoundError: when ``file_path`` does not exist on disk.
163 + :raises FileUploadPathNotAllowedError: when resolved path is outside every
164 + entry of ``allowlist`` (including when allowlist is empty).
165 + """
166 + attempted = str(file_path)
167 + abs_path = Path(attempted).expanduser()
168 + try:
169 + abs_path = abs_path.resolve(strict=False)
170 + except OSError:
171 + pass
172 +
173 + if not abs_path.exists():
174 + cwd = Path.cwd()
175 + parent = abs_path.parent
176 + parent_exists = parent.exists()
177 + raise SDKFileNotFoundError(
178 + "\n".join(
179 + [
180 + f'Refusing to auto-upload "{attempted}": the file does not exist on disk.',
181 + "",
182 + f"Path attempted: {attempted}",
183 + f"Resolved to: {abs_path}",
184 + f"Process cwd: {cwd}",
185 + f"Parent exists: {'yes (' + str(parent) + ')' if parent_exists else 'no (' + str(parent) + ')'}",
186 + "",
187 + "Common causes:",
188 + " - Typo in the filename passed to the tool.",
189 + " - Relative path resolved against the wrong working directory",
190 + " (relative paths use os.getcwd() at the moment of upload).",
191 + " - File was deleted between the tool being called and the upload starting.",
192 + "",
193 + _build_help_footer(allowlist),
194 + ]
195 + )
196 + )
197 +
198 + try:
199 + real_path = abs_path.resolve(strict=True)
200 + except OSError:
201 + real_path = abs_path
202 +
203 + if not allowlist:
204 + raise FileUploadPathNotAllowedError(
205 + "\n".join(
206 + [
207 + f'Refusing to auto-upload "{attempted}": no upload directories are configured.',
208 + "",
209 + f"Path attempted: {attempted}",
210 + f"Resolved to: {real_path}",
211 + "",
212 + "Automatic file upload during tool execution is locked down by default",
213 + "to prevent a prompt-injected tool from exfiltrating server files",
214 + "(source code, .env, SSH keys, etc.).",
215 + _build_help_footer(allowlist),
216 + ]
217 + )
218 + )
219 +
220 + for dir_entry in allowlist:
221 + try:
222 + real_dir = Path(dir_entry).expanduser().resolve(strict=False)
223 + except OSError:
224 + real_dir = Path(dir_entry)
225 + if _is_inside_dir(real_path, real_dir):
226 + return
227 +
228 + raise FileUploadPathNotAllowedError(
229 + "\n".join(
230 + [
231 + f'Refusing to auto-upload "{attempted}": resolved path is not inside any',
232 + "directory in the configured `file_upload_dirs` allowlist.",
233 + "",
234 + f"Path attempted: {attempted}",
235 + f"Resolved to: {real_path}",
236 + _build_help_footer(allowlist),
237 + ]
238 + )
239 + )
python/tests/test_auto_upload_download_files.py
+17 -17
@@ -75,7 +75,7 @@ class TestAutoUploadDownloadFilesEnabled:
75 tools = Tools(
76 client=mock_client,
77 provider=mock_provider,
78 - auto_upload_download_files=True,
78 + dangerously_allow_auto_upload_download_files=True,
79 toolkit_versions={"test_toolkit": "20251201_01"},
80 )
81
@@ -119,7 +119,7 @@ class TestAutoUploadDownloadFilesEnabled:
119 tools = Tools(
120 client=mock_client,
121 provider=mock_provider,
122 - auto_upload_download_files=True,
122 + dangerously_allow_auto_upload_download_files=True,
123 toolkit_versions={"test_toolkit": "20251201_01"},
124 )
125
@@ -182,7 +182,7 @@ class TestAutoUploadDownloadFilesEnabled:
182 tools = Tools(
183 client=mock_client,
184 provider=mock_provider,
185 - auto_upload_download_files=True,
185 + dangerously_allow_auto_upload_download_files=True,
186 toolkit_versions={"test_toolkit": "20251201_01"},
187 )
188
@@ -243,7 +243,7 @@ class TestAutoUploadDownloadFilesEnabled:
243 tools = Tools(
244 client=mock_client,
245 provider=mock_provider,
246 - auto_upload_download_files=True,
246 + dangerously_allow_auto_upload_download_files=True,
247 toolkit_versions={"test_toolkit": "20251201_01"},
248 )
249
@@ -314,7 +314,6 @@ class TestAutoUploadDownloadFilesDisabled:
314 tools = Tools(
315 client=mock_client,
316 provider=mock_provider,
317 - auto_upload_download_files=False,
317 toolkit_versions={"test_toolkit": "20251201_01"},
318 )
319
@@ -363,7 +362,6 @@ class TestAutoUploadDownloadFilesDisabled:
362 tools = Tools(
363 client=mock_client,
364 provider=mock_provider,
366 - auto_upload_download_files=False,
365 toolkit_versions={"test_toolkit": "20251201_01"},
366 )
367
@@ -419,7 +417,6 @@ class TestAutoUploadDownloadFilesDisabled:
417 tools = Tools(
418 client=mock_client,
419 provider=mock_provider,
422 - auto_upload_download_files=False,
420 toolkit_versions={"test_toolkit": "20251201_01"},
421 )
422
@@ -464,7 +461,6 @@ class TestAutoUploadDownloadFilesDisabled:
461 tools = Tools(
462 client=mock_client,
463 provider=mock_provider,
467 - auto_upload_download_files=False,
464 toolkit_versions={"test_toolkit": "20251201_01"},
465 )
466
@@ -518,12 +514,11 @@ class TestAutoUploadDownloadFilesDisabled:
514 class TestAutoUploadDownloadFilesWithSDK:
515 """Test cases for auto_upload_download_files with SDK initialization."""
516
521 - def test_sdk_passes_auto_upload_download_files_to_tools(self):
522 - """Test that Composio SDK passes auto_upload_download_files to Tools."""
517 + def test_sdk_passes_auto_upload_download_off_to_tools_by_default(self):
518 + """Test that Composio SDK disables automatic file upload/download by default."""
519 from composio.sdk import Composio
520
521 with patch("composio.sdk.HttpClient"):
526 - # Test with default (True)
522 with patch.object(Tools, "__init__", return_value=None) as mock_init:
523 mock_provider = Mock()
524 mock_provider.name = "test"
@@ -533,13 +528,15 @@ class TestAutoUploadDownloadFilesWithSDK:
528 api_key="test-key",
529 )
530
536 - # Should have passed auto_upload_download_files=True (default)
531 mock_init.assert_called()
532 call_kwargs = mock_init.call_args[1]
539 - assert call_kwargs.get("auto_upload_download_files", True) is True
533 + assert (
534 + call_kwargs.get("dangerously_allow_auto_upload_download_files")
535 + is False
536 + )
537
541 - def test_sdk_passes_false_to_tools(self):
542 - """Test that Composio SDK correctly passes auto_upload_download_files=False."""
538 + def test_sdk_passes_true_when_dangerously_enabled(self):
539 + """Test that Composio SDK passes through dangerously_allow_auto_upload_download_files."""
540 from composio.sdk import Composio
541
542 with patch("composio.sdk.HttpClient"):
@@ -550,9 +547,12 @@ class TestAutoUploadDownloadFilesWithSDK:
547 Composio(
548 provider=mock_provider,
549 api_key="test-key",
553 - auto_upload_download_files=False,
550 + dangerously_allow_auto_upload_download_files=True,
551 )
552
553 mock_init.assert_called()
554 call_kwargs = mock_init.call_args[1]
558 - assert call_kwargs.get("auto_upload_download_files") is False
555 + assert (
556 + call_kwargs.get("dangerously_allow_auto_upload_download_files")
557 + is True
558 + )
python/tests/test_custom_tools.py
+3 -3
@@ -576,7 +576,7 @@ def _session(deps, **overrides):
576 kwargs = dict(
577 client=deps["client"],
578 provider=deps["provider"],
579 - auto_upload_download_files=True,
579 + dangerously_allow_auto_upload_download_files=True,
580 session_id="s",
581 mcp=MagicMock(),
582 experimental=deps["experimental"],
@@ -644,7 +644,7 @@ class TestToolRouterSessionCustomTools:
644 s = ToolRouterSession(
645 client=MagicMock(),
646 provider=MagicMock(),
647 - auto_upload_download_files=True,
647 + dangerously_allow_auto_upload_download_files=True,
648 session_id="s",
649 mcp=MagicMock(),
650 experimental=MagicMock(),
@@ -663,7 +663,7 @@ class TestMultiExecuteRouting:
663 return ToolRouterSession(
664 client=MagicMock(),
665 provider=MagicMock(),
666 - auto_upload_download_files=True,
666 + dangerously_allow_auto_upload_download_files=True,
667 session_id="s",
668 mcp=MagicMock(),
669 experimental=MagicMock(),
python/tests/test_files.py
+117
@@ -1322,6 +1322,123 @@ class TestFileUploadableFromUrl:
1322
1323 assert "Fetch failed" in str(exc_info.value)
1324
1325 + def test_before_file_upload_hook_receives_source_url(self):
1326 + """from_path emits ``source="url"`` to the hook for http(s) inputs.
1327 +
1328 + We abort from the hook to avoid the downstream network path; the
1329 + pre-abort capture is what we're asserting on.
1330 + """
1331 + from composio.exceptions import FileUploadAbortedError
1332 +
1333 + mock_client = MagicMock()
1334 + seen = {}
1335 +
1336 + def hook(ctx):
1337 + seen.update(ctx)
1338 + return False
1339 +
1340 + with pytest.raises(FileUploadAbortedError):
1341 + FileUploadable.from_path(
1342 + client=mock_client,
1343 + file="https://example.com/photo.png",
1344 + tool="SEND_EMAIL",
1345 + toolkit="gmail",
1346 + before_file_upload=hook,
1347 + )
1348 +
1349 + assert seen == {
1350 + "path": "https://example.com/photo.png",
1351 + "source": "url",
1352 + "tool": "SEND_EMAIL",
1353 + "toolkit": "gmail",
1354 + }
1355 +
1356 + def test_before_file_upload_hook_receives_source_path(self, tmp_path):
1357 + """from_path emits ``source="path"`` to the hook for local inputs."""
1358 + from composio.exceptions import FileUploadAbortedError
1359 +
1360 + f = tmp_path / "doc.txt"
1361 + f.write_text("hello")
1362 + mock_client = MagicMock()
1363 + seen = {}
1364 +
1365 + def hook(ctx):
1366 + seen.update(ctx)
1367 + return False
1368 +
1369 + with pytest.raises(FileUploadAbortedError):
1370 + FileUploadable.from_path(
1371 + client=mock_client,
1372 + file=str(f),
1373 + tool="MY_TOOL",
1374 + toolkit="my_toolkit",
1375 + before_file_upload=hook,
1376 + )
1377 +
1378 + assert seen == {
1379 + "path": str(f),
1380 + "source": "path",
1381 + "tool": "MY_TOOL",
1382 + "toolkit": "my_toolkit",
1383 + }
1384 +
1385 + def test_url_hook_returning_local_path_routes_through_path_branch(self, tmp_path):
1386 + """A hook that rewrites a URL into a local path must NOT be fed to
1387 + ``from_url``. It has to route back into the local-file branch so the
1388 + allowlist / denylist / existence checks all run."""
1389 + from composio.exceptions import SDKFileNotFoundError
1390 +
1391 + # A path that's syntactically a path but does not exist — if routing
1392 + # is correct, we'll get SDKFileNotFoundError from the local branch.
1393 + # If the bug is still there, we'd hit `from_url` and the URL fetch
1394 + # would explode (or worse, succeed) instead.
1395 + rewritten = str(tmp_path / "does-not-exist.txt")
1396 +
1397 + def hook(ctx):
1398 + assert ctx["source"] == "url"
1399 + return rewritten
1400 +
1401 + mock_client = MagicMock()
1402 +
1403 + with pytest.raises(SDKFileNotFoundError):
1404 + FileUploadable.from_path(
1405 + client=mock_client,
1406 + file="https://example.com/photo.png",
1407 + tool="T",
1408 + toolkit="tk",
1409 + before_file_upload=hook,
1410 + )
1411 +
1412 + @patch("composio.core.models._files._fetch_file_from_url")
1413 + @patch("composio.core.models._files._upload_bytes_to_s3")
1414 + def test_path_hook_returning_url_routes_through_url_branch(
1415 + self, mock_upload, mock_fetch, tmp_path
1416 + ):
1417 + """Inverse of the above: a hook on a local path that returns a URL
1418 + must route through ``from_url``, not stat the URL string as a file."""
1419 + f = tmp_path / "local.txt"
1420 + f.write_text("hi")
1421 +
1422 + mock_fetch.return_value = ("photo.png", b"x", "image/png")
1423 + mock_upload.return_value = "s3-key"
1424 +
1425 + def hook(ctx):
1426 + assert ctx["source"] == "path"
1427 + return "https://example.com/photo.png"
1428 +
1429 + mock_client = MagicMock()
1430 + result = FileUploadable.from_path(
1431 + client=mock_client,
1432 + file=str(f),
1433 + tool="T",
1434 + toolkit="tk",
1435 + before_file_upload=hook,
1436 + )
1437 +
1438 + # If routing worked, the URL fetch path was taken.
1439 + mock_fetch.assert_called_once_with("https://example.com/photo.png")
1440 + assert result.s3key == "s3-key"
1441 +
1442
1443 class TestFileHelperWithUrls:
1444 """Test cases for FileHelper handling URLs in file uploads."""
python/tests/test_sdk.py
+2 -1
@@ -56,9 +56,10 @@ class TestComposioSDK:
56 "allow_tracking",
57 "file_download_dir",
58 "toolkit_versions",
59 - "auto_upload_download_files",
59 + "dangerously_allow_auto_upload_download_files",
60 "sensitive_file_upload_protection",
61 "file_upload_path_deny_segments",
62 + "file_upload_dirs",
63 }
64 assert set(SDKConfig.__annotations__.keys()) == expected_fields
65
python/tests/test_tool_execution.py
+116 -4
@@ -855,12 +855,17 @@ class TestToolExecution:
855 scoped = before_file_upload(tools=["OTHER_TOOL"])(lambda p, t, k: p + "_X")
856 fn = merge_before_file_upload([scoped], tool="MY", toolkit="gh")
857 assert fn is not None
858 - assert fn("/a", "MY", "gh") == "/a"
858 + assert (
859 + fn({"path": "/a", "source": "path", "tool": "MY", "toolkit": "gh"}) == "/a"
860 + )
861
862 all_tools = before_file_upload(lambda p, t, k: p + "_Y")
863 fn2 = merge_before_file_upload([all_tools], tool="MY", toolkit="gh")
864 assert fn2 is not None
863 - assert fn2("/a", "MY", "gh") == "/a_Y"
865 + assert (
866 + fn2({"path": "/a", "source": "path", "tool": "MY", "toolkit": "gh"})
867 + == "/a_Y"
868 + )
869
870 def test_merge_before_file_upload_chains_modifiers(self):
871 from composio.core.models._modifiers import (
@@ -872,7 +877,103 @@ class TestToolExecution:
877 m2 = before_file_upload(lambda p, t, k: f"{p}|2")
878 fn = merge_before_file_upload([m1, m2], tool="T", toolkit="k")
879 assert fn is not None
875 - assert fn("p", "T", "k") == "p|1|2"
880 + assert (
881 + fn({"path": "p", "source": "path", "tool": "T", "toolkit": "k"}) == "p|1|2"
882 + )
883 +
884 + def test_before_file_upload_context_form_receives_source(self):
885 + """New-form hooks (single ``context`` arg) see ``source`` in the context."""
886 + from composio.core.models._modifiers import (
887 + before_file_upload,
888 + merge_before_file_upload,
889 + )
890 +
891 + seen: t.Dict[str, t.Any] = {}
892 +
893 + def hook(ctx):
894 + seen.update(ctx)
895 + return ctx["path"] + "!"
896 +
897 + m = before_file_upload(hook)
898 + fn = merge_before_file_upload([m], tool="T", toolkit="k")
899 + assert fn is not None
900 +
901 + out = fn({"path": "/x", "source": "path", "tool": "T", "toolkit": "k"})
902 + assert out == "/x!"
903 + assert seen == {"path": "/x", "source": "path", "tool": "T", "toolkit": "k"}
904 +
905 + seen.clear()
906 + out = fn(
907 + {
908 + "path": "https://example.com/a.pdf",
909 + "source": "url",
910 + "tool": "T",
911 + "toolkit": "k",
912 + }
913 + )
914 + assert out == "https://example.com/a.pdf!"
915 + assert seen["source"] == "url"
916 +
917 + def test_before_file_upload_legacy_3arg_form_still_works(self):
918 + """Hooks declared as ``(path, tool, toolkit)`` keep working unchanged."""
919 + from composio.core.models._modifiers import (
920 + before_file_upload,
921 + merge_before_file_upload,
922 + )
923 +
924 + def legacy(path, tool, toolkit):
925 + return f"{path}@{tool}/{toolkit}"
926 +
927 + m = before_file_upload(legacy)
928 + fn = merge_before_file_upload([m], tool="T", toolkit="k")
929 + assert fn is not None
930 + # Driver always passes context form; adapter unwraps to positional args.
931 + assert (
932 + fn({"path": "/x", "source": "path", "tool": "T", "toolkit": "k"})
933 + == "/x@T/k"
934 + )
935 +
936 + def test_before_file_upload_chain_preserves_source(self):
937 + """``source`` stays stable as the ``path`` is rewritten down the chain."""
938 + from composio.core.models._modifiers import (
939 + before_file_upload,
940 + merge_before_file_upload,
941 + )
942 +
943 + seen_sources: t.List[str] = []
944 +
945 + def h1(ctx):
946 + seen_sources.append(ctx["source"])
947 + return ctx["path"] + "|1"
948 +
949 + def h2(ctx):
950 + seen_sources.append(ctx["source"])
951 + return ctx["path"] + "|2"
952 +
953 + fn = merge_before_file_upload(
954 + [before_file_upload(h1), before_file_upload(h2)], tool="T", toolkit="k"
955 + )
956 + assert fn is not None
957 + out = fn({"path": "p", "source": "url", "tool": "T", "toolkit": "k"})
958 + assert out == "p|1|2"
959 + assert seen_sources == ["url", "url"]
960 +
961 + def test_before_file_upload_abort_propagates_as_false(self):
962 + from composio.core.models._modifiers import (
963 + before_file_upload,
964 + merge_before_file_upload,
965 + )
966 +
967 + def abort(ctx):
968 + return False
969 +
970 + fn = merge_before_file_upload(
971 + [before_file_upload(abort)], tool="T", toolkit="k"
972 + )
973 + assert fn is not None
974 + assert (
975 + fn({"path": "/x", "source": "path", "tool": "T", "toolkit": "k"}) is False
976 + )
977
978 def test_execute_includes_before_file_upload_modifier_in_compose(
979 self,
@@ -888,6 +989,7 @@ class TestToolExecution:
989 client=mock_client,
990 provider=mock_provider,
991 toolkit_versions={"github": "20251201_01"},
992 + dangerously_allow_auto_upload_download_files=True,
993 )
994
995 github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")
@@ -923,7 +1025,17 @@ class TestToolExecution:
1025
1026 bfu = cap.get("bfu")
1027 assert bfu is not None
926 - assert bfu("/p", "GITHUB_GET_REPOS", "github") == "/p>"
1028 + assert (
1029 + bfu(
1030 + {
1031 + "path": "/p",
1032 + "source": "path",
1033 + "tool": "GITHUB_GET_REPOS",
1034 + "toolkit": "github",
1035 + }
1036 + )
1037 + == "/p>"
1038 + )
1039
1040 def test_execute_with_environment_variable_toolkit_version(self):
1041 """Test that execute uses environment variable for toolkit version."""
python/tests/test_tool_router.py
+6 -5
@@ -966,13 +966,14 @@ class TestToolRouter:
966 session = tool_router.create(user_id="user_123")
967 result = session.tools()
968
969 - # Verify Tools was instantiated
969 + # Verify Tools was instantiated (resolved flag; default ToolRouter is off)
970 mock_tools_class.assert_called_once_with(
971 client=mock_client,
972 provider=mock_provider,
973 - auto_upload_download_files=True,
973 + dangerously_allow_auto_upload_download_files=False,
974 sensitive_file_upload_protection=True,
975 file_upload_path_deny_segments=None,
976 + file_upload_dirs=None,
977 )
978
979 # Verify get_raw_tool_router_meta_tools was called
@@ -1267,7 +1268,7 @@ class TestToolRouterExecution:
1268 real_tools = RealTools(
1269 client=mock_client,
1270 provider=mock_provider,
1270 - auto_upload_download_files=False,
1271 + dangerously_allow_auto_upload_download_files=False,
1272 )
1273 execute_fn = real_tools._wrap_execute_tool_for_tool_router(
1274 session_id="session_123"
@@ -1318,7 +1319,7 @@ class TestToolRouterExecution:
1319 real_tools = RealTools(
1320 client=mock_client,
1321 provider=mock_provider,
1321 - auto_upload_download_files=False,
1322 + dangerously_allow_auto_upload_download_files=False,
1323 )
1324
1325 modifiers = [
@@ -1361,7 +1362,7 @@ class TestToolRouterExecution:
1362 real_tools = RealTools(
1363 client=mock_client,
1364 provider=mock_provider,
1364 - auto_upload_download_files=False,
1365 + dangerously_allow_auto_upload_download_files=False,
1366 )
1367 execute_fn = real_tools._wrap_execute_tool_for_tool_router(
1368 session_id="session_123"
python/tests/test_upload_dir_allowlist.py new
+251
@@ -0,0 +1,251 @@
1 +"""Tests for the auto-upload directory allowlist (parity with TS sdk)."""
2 +
3 +from __future__ import annotations
4 +
5 +import os
6 +import sys
7 +from pathlib import Path
8 +
9 +import pytest
10 +
11 +from composio.core.models.base import allow_tracking
12 +from composio.exceptions import (
13 + FileUploadPathNotAllowedError,
14 + SDKFileNotFoundError,
15 +)
16 +from composio.utils.upload_dir_allowlist import (
17 + assert_path_inside_upload_dirs,
18 + get_default_upload_dir,
19 + resolve_effective_upload_allowlist,
20 +)
21 +
22 +
23 +@pytest.fixture(autouse=True)
24 +def disable_telemetry():
25 + token = allow_tracking.set(False)
26 + yield
27 + allow_tracking.reset(token)
28 +
29 +
30 +class TestResolveEffectiveUploadAllowlist:
31 + def test_none_returns_default(self):
32 + result = resolve_effective_upload_allowlist(None)
33 + default = get_default_upload_dir()
34 + assert default is not None, "Expected a default upload dir in this env."
35 + assert result == [default]
36 +
37 + def test_empty_list_replaces_default(self):
38 + assert resolve_effective_upload_allowlist([]) == []
39 +
40 + def test_false_means_no_local_paths(self):
41 + # Explicit "reject all local paths during auto-upload". Equivalent to []
42 + # but reads better at call sites.
43 + assert resolve_effective_upload_allowlist(False) == []
44 +
45 + def test_explicit_list_replaces_default(self, tmp_path: Path):
46 + result = resolve_effective_upload_allowlist([str(tmp_path)])
47 + assert result == [tmp_path.resolve()]
48 +
49 + def test_tilde_is_expanded(self):
50 + result = resolve_effective_upload_allowlist(["~"])
51 + assert result == [Path.home().resolve()]
52 +
53 + def test_skips_blank_and_non_string_entries(self, tmp_path: Path):
54 + result = resolve_effective_upload_allowlist([str(tmp_path), "", " "])
55 + assert result == [tmp_path.resolve()]
56 +
57 + def test_deduplicates_entries(self, tmp_path: Path):
58 + result = resolve_effective_upload_allowlist([str(tmp_path), str(tmp_path)])
59 + assert result == [tmp_path.resolve()]
60 +
61 +
62 +class TestAssertPathInsideUploadDirs:
63 + def test_accepts_direct_child(self, tmp_path: Path):
64 + allowed = tmp_path
65 + f = allowed / "a.txt"
66 + f.write_text("hi")
67 + assert_path_inside_upload_dirs(str(f), [allowed])
68 +
69 + def test_accepts_nested_child(self, tmp_path: Path):
70 + allowed = tmp_path
71 + nested = allowed / "sub" / "deeper"
72 + nested.mkdir(parents=True)
73 + f = nested / "a.txt"
74 + f.write_text("hi")
75 + assert_path_inside_upload_dirs(str(f), [allowed])
76 +
77 + def test_rejects_path_outside(self, tmp_path: Path):
78 + allowed = tmp_path / "inside"
79 + outside = tmp_path / "outside"
80 + allowed.mkdir()
81 + outside.mkdir()
82 + f = outside / "a.txt"
83 + f.write_text("hi")
84 + with pytest.raises(FileUploadPathNotAllowedError):
85 + assert_path_inside_upload_dirs(str(f), [allowed])
86 +
87 + def test_enforces_component_boundary(self, tmp_path: Path):
88 + # /tmp/foo must NOT accept /tmp/foo-bar/x.
89 + allowed = tmp_path / "foo"
90 + sibling = tmp_path / "foo-bar"
91 + allowed.mkdir()
92 + sibling.mkdir()
93 + f = sibling / "x.txt"
94 + f.write_text("hi")
95 + with pytest.raises(FileUploadPathNotAllowedError):
96 + assert_path_inside_upload_dirs(str(f), [allowed])
97 +
98 + def test_raises_not_found_when_missing(self, tmp_path: Path):
99 + allowed = tmp_path
100 + missing = tmp_path / "does_not_exist.txt"
101 + with pytest.raises(SDKFileNotFoundError) as excinfo:
102 + assert_path_inside_upload_dirs(str(missing), [allowed])
103 + assert "does not exist on disk" in str(excinfo.value)
104 + assert "file_upload_dirs" in str(excinfo.value)
105 +
106 + def test_empty_allowlist_fails_closed(self, tmp_path: Path):
107 + f = tmp_path / "a.txt"
108 + f.write_text("hi")
109 + with pytest.raises(FileUploadPathNotAllowedError) as excinfo:
110 + assert_path_inside_upload_dirs(str(f), [])
111 + msg = str(excinfo.value)
112 + assert "no upload directories are configured" in msg
113 + assert "dangerously_allow_auto_upload_download_files" in msg
114 +
115 + def test_error_message_lists_allowlist(self, tmp_path: Path):
116 + allowed = tmp_path / "inside"
117 + outside = tmp_path / "outside"
118 + allowed.mkdir()
119 + outside.mkdir()
120 + f = outside / "a.txt"
121 + f.write_text("hi")
122 + with pytest.raises(FileUploadPathNotAllowedError) as excinfo:
123 + assert_path_inside_upload_dirs(str(f), [allowed])
124 + msg = str(excinfo.value)
125 + assert str(allowed) in msg
126 + assert "file_upload_dirs" in msg
127 + assert "dangerously_allow_auto_upload_download_files" in msg
128 +
129 + @pytest.mark.skipif(sys.platform == "win32", reason="POSIX-only symlink semantics")
130 + def test_rejects_symlink_pointing_outside(self, tmp_path: Path):
131 + allowed = tmp_path / "inside"
132 + outside = tmp_path / "outside"
133 + allowed.mkdir()
134 + outside.mkdir()
135 + secret = outside / "secret.txt"
136 + secret.write_text("pw")
137 + link = allowed / "link.txt"
138 + os.symlink(secret, link)
139 +
140 + with pytest.raises(FileUploadPathNotAllowedError):
141 + assert_path_inside_upload_dirs(str(link), [allowed])
142 +
143 +
144 +class TestToolsWiresAllowlistCorrectly:
145 + """Verifies ``Tools`` forwards the right allowlist to ``FileHelper`` given
146 + the full flag/value matrix."""
147 +
148 + @staticmethod
149 + def _make_tools(
150 + dangerously_allow_auto_upload_download_files: bool,
151 + file_upload_dirs,
152 + ):
153 + from composio.core.models.tools import Tools
154 + from unittest.mock import Mock
155 +
156 + return Tools(
157 + client=Mock(),
158 + provider=Mock(name="provider"),
159 + dangerously_allow_auto_upload_download_files=dangerously_allow_auto_upload_download_files,
160 + file_upload_dirs=file_upload_dirs,
161 + )
162 +
163 + def test_flag_off_means_no_allowlist_is_ever_built(self):
164 + # Flag off ⇒ auto-upload code path is never run. We pass ``None`` to
165 + # FileHelper so manual/no-op paths don't accidentally enforce anything.
166 + t = self._make_tools(False, None)
167 + assert t._file_helper._file_upload_allowlist is None # noqa: SLF001
168 +
169 + def test_flag_off_ignores_file_upload_dirs_entirely(self):
170 + t = self._make_tools(False, ["/tmp/whatever"])
171 + assert t._file_helper._file_upload_allowlist is None # noqa: SLF001
172 +
173 + t = self._make_tools(False, False)
174 + assert t._file_helper._file_upload_allowlist is None # noqa: SLF001
175 +
176 + t = self._make_tools(False, [])
177 + assert t._file_helper._file_upload_allowlist is None # noqa: SLF001
178 +
179 + def test_flag_on_none_uses_default(self):
180 + t = self._make_tools(True, None)
181 + assert t._file_helper._file_upload_allowlist == [ # noqa: SLF001
182 + get_default_upload_dir()
183 + ]
184 +
185 + def test_flag_on_false_means_empty_allowlist(self):
186 + t = self._make_tools(True, False)
187 + assert t._file_helper._file_upload_allowlist == [] # noqa: SLF001
188 +
189 + def test_flag_on_empty_list_means_empty_allowlist(self):
190 + t = self._make_tools(True, [])
191 + assert t._file_helper._file_upload_allowlist == [] # noqa: SLF001
192 +
193 + def test_flag_on_explicit_dirs_replace_default(self, tmp_path: Path):
194 + t = self._make_tools(True, [str(tmp_path)])
195 + assert t._file_helper._file_upload_allowlist == [ # noqa: SLF001
196 + tmp_path.resolve()
197 + ]
198 +
199 +
200 +class TestFileUploadableAllowlistWiring:
201 + """Sanity: FileUploadable.from_path must honor the allowlist param."""
202 +
203 + def test_from_path_with_allowlist_blocks_outside(self, tmp_path: Path):
204 + from composio.core.models._files import FileUploadable
205 + from unittest.mock import Mock
206 +
207 + inside = tmp_path / "inside"
208 + outside = tmp_path / "outside"
209 + inside.mkdir()
210 + outside.mkdir()
211 + f = outside / "a.txt"
212 + f.write_text("hi")
213 +
214 + with pytest.raises(FileUploadPathNotAllowedError):
215 + FileUploadable.from_path(
216 + client=Mock(),
217 + file=str(f),
218 + tool="T",
219 + toolkit="tk",
220 + file_upload_allowlist=[inside],
221 + )
222 +
223 + def test_from_path_without_allowlist_skips_check(
224 + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
225 + ):
226 + """Passing ``file_upload_allowlist=None`` must NOT trigger the check.
227 +
228 + This simulates manual upload paths and the no-auto-upload default.
229 + """
230 + from composio.core.models import _files as files_mod
231 + from composio.core.models._files import FileUploadable
232 + from unittest.mock import Mock
233 +
234 + f = tmp_path / "a.txt"
235 + f.write_text("hi")
236 +
237 + # Short-circuit the network-bound parts.
238 + mock_client = Mock()
239 + mock_client.post.return_value = Mock(
240 + new_presigned_url="https://example/upload", key="k"
241 + )
242 + monkeypatch.setattr(files_mod, "upload", lambda url, file: True)
243 +
244 + result = FileUploadable.from_path(
245 + client=mock_client,
246 + file=str(f),
247 + tool="T",
248 + toolkit="tk",
249 + file_upload_allowlist=None,
250 + )
251 + assert result.s3key == "k"
ts/docs/advanced/auto-upload-download.md
+48 -17
@@ -6,10 +6,11 @@ Composio SDK includes an automatic file handling system that manages file upload
6
7 The file handling system in Composio SDK is:
8
9 -- **Opt-out**: Enabled by default but can be disabled
10 -- **Automatic**: Handles file uploads and downloads transparently
11 -- **Configurable**: Can be disabled for manual file handling
12 -- **Sensitive path protection (Node)**: Local string paths used for upload are checked by default against a denylist of path segments and file names (see below)
9 +- **Opt-in**: Disabled by default. Set `dangerouslyAllowAutoUploadDownloadFiles: true` to enable.
10 +- **Automatic** (when enabled): Handles file uploads and downloads transparently.
11 +- **Allowlisted**: Even when enabled, local upload paths must resolve inside one of the directories listed in `fileUploadDirs` (default `[~/.composio/temp]`). See [Restricting upload paths with `fileUploadDirs`](#restricting-upload-paths-with-fileuploaddirs) below.
12 +- **Configurable**: Manual handling via `composio.files.upload()` / `composio.files.download()` is always available and is **not** subject to `fileUploadDirs`.
13 +- **Sensitive path protection (Node)**: Local string paths used for upload are checked by default against a denylist of path segments and file names (see below).
14
15 ## Security: sensitive local paths
16
@@ -67,10 +68,10 @@ const toolSchema = {
68 }
69 ```
70
70 -When executing a tool with file upload:
71 +When executing a tool with file upload (auto-handling enabled):
72
73 ```typescript
73 -// With auto upload enabled (default)
74 +// Requires `dangerouslyAllowAutoUploadDownloadFiles: true` AND a path inside `fileUploadDirs`
75 const result = await composio.tools.execute('your-tool', {
76 arguments: {
77 file: '/path/to/local/file.txt' // Local file path
@@ -124,22 +125,48 @@ Example tool response with file download:
125 }
126 ```
127
127 -## Disabling Auto File Handling
128 +## Default: auto file handling is off
129
129 -You can disable automatic file handling when initializing the SDK:
130 +Automatic file upload/download during tool execution is **disabled** unless you pass `dangerouslyAllowAutoUploadDownloadFiles: true` to the `Composio` constructor.
131 +
132 +## Restricting upload paths with `fileUploadDirs`
133 +
134 +When auto-handling is on, the SDK only reads local files from directories you have explicitly allowlisted via `fileUploadDirs`. Anything outside the list is rejected with `ComposioFileUploadPathNotAllowedError` before the file is read.
135 +
136 +| `fileUploadDirs` value | Effective allowlist |
137 +| ---------------------- | ------------------- |
138 +| omitted / `undefined` | `[~/.composio/temp]` (default staging dir) |
139 +| `false` | `[]` — **all** local paths rejected (URLs and `File`/`Blob` still work) |
140 +| `[]` | `[]` — same as `false`; explicit "no local paths" |
141 +| `[<dir1>, <dir2>, …]` | exactly those directories. `~` is expanded; entries are `realpath`-resolved; comparison is on a path-component boundary (`/tmp/foo` allows `/tmp/foo/bar` but **not** `/tmp/foo-bar`) |
142 +
143 +URLs (`http://…` / `https://…`) and JavaScript `File` / `Blob` objects are not subject to the allowlist — only local string paths are. The denylist (`sensitiveFileUploadProtection`) still runs in addition to the allowlist; both must accept the path.
144
145 ```typescript
146 import { Composio } from '@composio/core';
147
148 +// Widen the allowlist to the directories your code actually reads from.
149 const composio = new Composio({
135 - apiKey: 'your-api-key',
136 - autoUploadDownloadFiles: false
150 + apiKey: process.env.COMPOSIO_API_KEY!,
151 + dangerouslyAllowAutoUploadDownloadFiles: true,
152 + // Replaces the default `[~/.composio/temp]`. Include it explicitly if you
153 + // still want the default staging dir to keep working.
154 + fileUploadDirs: ['/srv/agent/uploads', '~/.composio/temp'],
155 +});
156 +
157 +// Reject every local path; only URLs and File/Blob objects work.
158 +const composioStrict = new Composio({
159 + apiKey: process.env.COMPOSIO_API_KEY!,
160 + dangerouslyAllowAutoUploadDownloadFiles: true,
161 + fileUploadDirs: false,
162 });
163 ```
164
165 +If you want to upload from arbitrary paths without widening the allowlist, use the manual `composio.files.upload(...)` API below — it bypasses `fileUploadDirs` by design (the caller is expected to control the path).
166 +
167 ## Manual File Handling
168
142 -When auto file handling is disabled, you'll need to handle the file operations yourself using the `composio.files` API:
169 +When auto file handling is not enabled, you'll need to handle the file operations yourself using the `composio.files` API:
170
171 ### Manual Upload
172
@@ -193,12 +220,13 @@ if (result.data.file?.s3url) {
220
221 ## File Storage Location
222
196 -Downloaded files are stored in a temporary directory:
223 +Downloaded files are stored in:
224
198 -- Location: `~/.composio/files/` (user's home directory)
199 -- Files are named using the pattern: `{toolSlug}_{timestamp}.{extension}`
200 -- The directory is created automatically when needed
201 -- File extensions are derived from the MIME type
225 +- **Default**: `~/.composio/files/` (user's home directory).
226 +- **Custom**: pass `fileDownloadDir: '/some/abs/path'` to the `Composio` constructor.
227 +- Files are named using the pattern: `{toolSlug}_{timestamp}.{extension}` (server-synthesized; the S3 URL never affects the local filename).
228 +- The directory is created automatically when needed.
229 +- File extensions are derived from the MIME type.
230
231 ## Error Handling
232
@@ -209,6 +237,7 @@ import {
237 ComposioFileUploadError,
238 ComposioSensitiveFilePathBlockedError,
239 ComposioFileUploadAbortedError,
240 + ComposioFileUploadPathNotAllowedError,
241 } from '@composio/core';
242
243 try {
@@ -220,7 +249,9 @@ try {
249 dangerouslySkipVersionCheck: true,
250 });
251 } catch (error) {
223 - if (error instanceof ComposioSensitiveFilePathBlockedError) {
252 + if (error instanceof ComposioFileUploadPathNotAllowedError) {
253 + console.error('Path is outside fileUploadDirs:', error.message);
254 + } else if (error instanceof ComposioSensitiveFilePathBlockedError) {
255 console.error('Blocked sensitive path:', error.message);
256 } else if (error instanceof ComposioFileUploadAbortedError) {
257 console.error('Upload aborted by beforeFileUpload:', error.message);
ts/docs/api/composio.md
+106 -5
@@ -11,9 +11,11 @@ const composio = new Composio({
11 apiKey: 'your-api-key',
12 baseURL: 'https://api.composio.dev', // Optional: Custom API endpoint
13 allowTracking: true, // Optional: Enable/disable telemetry
14 - autoUploadDownloadFiles: true, // Optional: Enable/disable automatic file handling
14 + dangerouslyAllowAutoUploadDownloadFiles: false, // Optional: set to true to opt in to automatic file handling (default: false)
15 sensitiveFileUploadProtection: true, // Optional: block uploads from sensitive paths (Node; default true)
16 fileUploadPathDenySegments: undefined, // Optional: extra path component denylist
17 + fileUploadDirs: undefined, // Optional: allowlist for automatic upload (defaults to [~/.composio/temp])
18 + fileDownloadDir: undefined, // Optional: where auto-downloaded files are written (defaults to ~/.composio/files)
19 provider: new OpenAIProvider(), // Optional: Custom provider
20 });
21 ```
@@ -27,9 +29,11 @@ The `Composio` constructor accepts a configuration object with the following pro
29 | `apiKey` | string | Yes | - | Your Composio API key |
30 | `baseURL` | string | No | `https://api.composio.dev` | The base URL for the Composio API |
31 | `allowTracking` | boolean | No | `true` | Whether to allow analytics/tracking |
30 -| `autoUploadDownloadFiles`| boolean | No | `true` | Whether to automatically handle file operations |
32 +| `dangerouslyAllowAutoUploadDownloadFiles` | boolean | No | `false` | Opt in to automatic file upload/download during tool execution |
33 | `sensitiveFileUploadProtection` | `boolean` | No | `true` (Node) | When true, local upload paths are checked against a denylist of sensitive segments and credential-like names before read/upload. |
34 | `fileUploadPathDenySegments` | `string[]` | No | `undefined` | Additional path *components* merged with the built-in denylist. |
35 +| `fileUploadDirs` | `string[] \| false` | No | `[~/.composio/temp]` | Allowlist of directories from which the SDK may read local files during **automatic** upload (when `dangerouslyAllowAutoUploadDownloadFiles: true`). Pass `false` (or `[]`) to reject every local path; URLs and `File`/`Blob` objects still work. Providing a list **replaces** the default — include `~/.composio/temp` explicitly if you want the default staging dir to keep working. Does **not** affect manual `composio.files.upload()` calls. |
36 +| `fileDownloadDir` | `string` | No | `~/.composio/files` | Directory where files downloaded during tool execution (and `composio.files.download()`) are written. Relative paths resolve against `process.cwd()` at SDK-init time. |
37 | `provider` | `BaseComposioProvider` | No | `new OpenAIProvider()` | The provider to use for this Composio instance |
38
39 ## Properties
@@ -97,14 +101,49 @@ const composio = new Composio({
101 });
102 ```
103
100 -### Disable Automatic File Handling
104 +### Automatic file handling (opt-in)
105 +
106 +Automatic upload/download of file-marked tool fields is **off** by default. Set `dangerouslyAllowAutoUploadDownloadFiles: true` only if you intend to use that behavior:
107
108 ```typescript
109 import { Composio } from '@composio/core';
110
111 const composio = new Composio({
112 apiKey: process.env.COMPOSIO_API_KEY,
107 - autoUploadDownloadFiles: false,
113 + dangerouslyAllowAutoUploadDownloadFiles: true,
114 +});
115 +```
116 +
117 +#### What the LLM sees vs. what the SDK does
118 +
119 +The flag is a **contract between the SDK and the model**. The schema handed
120 +to the LLM always reflects what will actually happen at runtime:
121 +
122 +- **Flag `true`** — `composio.tools.get(...)` rewrites `file_uploadable`
123 + inputs down to `{ type: 'string', format: 'path' }`. The model passes a
124 + path or URL, the SDK stages it, the backend receives a proper
125 + `{ name, mimetype, s3key }` object. Works end-to-end.
126 +- **Flag `false`** (or omitted) — the raw backend shape
127 + (`{ name, mimetype, s3key }`) is preserved. You are expected to stage
128 + files yourself via `composio.files.upload(...)` and inject the returned
129 + descriptor into the tool arguments before calling `tools.execute`. Handing
130 + this shape directly to an LLM is not recommended — the model cannot
131 + produce a valid `s3key`. On first execution of a file-uploadable tool in
132 + this mode, the SDK emits a single warning per tool slug nudging you
133 + toward either enabling the flag or staging manually.
134 +
135 +Manual staging example (flag off):
136 +
137 +```typescript
138 +const staged = await composio.files.upload({
139 + file: '/tmp/report.pdf',
140 + toolSlug: 'SOME_FILE_TOOL',
141 + toolkitSlug: 'some-toolkit',
142 +});
143 +
144 +await composio.tools.execute('SOME_FILE_TOOL', {
145 + userId: 'u',
146 + arguments: { file: staged }, // { name, mimetype, s3key }
147 });
148 ```
149
@@ -121,7 +160,12 @@ await composio.tools.execute(
160 'SOME_FILE_TOOL',
161 { userId: 'u', arguments: { file: '/tmp/report.pdf' }, dangerouslySkipVersionCheck: true },
162 {
124 - beforeFileUpload: async ({ path, toolSlug, toolkitSlug }) => {
163 + beforeFileUpload: async ({ path, source, toolSlug, toolkitSlug }) => {
164 + // `source` discriminates the input:
165 + // 'path' — a local filesystem path
166 + // 'url' — an http(s):// URL
167 + // 'file' — a File object; `path` is `file.name` (filename only)
168 + if (source !== 'path') return path; // let URLs / File objects through
169 // return path, a different path, or false to abort
170 return path;
171 },
@@ -130,3 +174,60 @@ await composio.tools.execute(
174 ```
175
176 See [Auto upload and download](./advanced/auto-upload-download.md#security-sensitive-local-paths) for the security model and error types.
177 +
178 +### Restricting automatic uploads to specific directories
179 +
180 +When `dangerouslyAllowAutoUploadDownloadFiles: true`, the SDK only reads local
181 +files from directories in `fileUploadDirs`. This stacks with (it does NOT
182 +replace) the sensitive-path denylist.
183 +
184 +```typescript
185 +import { Composio } from '@composio/core';
186 +
187 +const composio = new Composio({
188 + apiKey: process.env.COMPOSIO_API_KEY!,
189 + dangerouslyAllowAutoUploadDownloadFiles: true,
190 + // User-provided list REPLACES the default `[~/.composio/temp]`.
191 + // Include it explicitly if you want staged uploads to keep working.
192 + fileUploadDirs: ['/srv/agent/uploads', '~/.composio/temp'],
193 +});
194 +```
195 +
196 +A local path is accepted if its symlink-resolved absolute path is inside one
197 +of these directories on a path-component boundary. Paths outside the allowlist
198 +throw `ComposioFileUploadPathNotAllowedError`. Missing files throw
199 +`ComposioFileNotFoundError`. URLs (`http(s)://...`) and `File`/`Blob` objects
200 +are not path-checked.
201 +
202 +**Manual upload API (`composio.files.upload(...)`) is _not_ subject to this
203 +allowlist** — it bypasses the allowlist check entirely. Use the allowlist to
204 +constrain what models/agents can ask the SDK to upload during tool execution.
205 +
206 +#### Blocking local paths entirely
207 +
208 +Pass `false` to allow only URLs and in-memory `File`/`Blob` objects during
209 +automatic upload:
210 +
211 +```typescript
212 +const composio = new Composio({
213 + apiKey: process.env.COMPOSIO_API_KEY!,
214 + dangerouslyAllowAutoUploadDownloadFiles: true,
215 + fileUploadDirs: false, // reject every filesystem path for auto-upload
216 +});
217 +```
218 +
219 +`fileUploadDirs: []` behaves identically; prefer `false` for readability.
220 +
221 +### Changing the download directory
222 +
223 +```typescript
224 +import { Composio } from '@composio/core';
225 +
226 +const composio = new Composio({
227 + apiKey: process.env.COMPOSIO_API_KEY!,
228 + fileDownloadDir: '/var/app/composio-downloads',
229 +});
230 +```
231 +
232 +Files returned by tools as `s3url` are streamed into this directory. The
233 +default is `~/.composio/files`.
ts/e2e-tests/runtimes/cloudflare/cf-workers-files/README.md
+11 -11
@@ -7,9 +7,9 @@ This package tests `@composio/core` file operations in Cloudflare Workers enviro
7 Verifies that:
8 1. `composio.files.upload()` throws the expected "not supported in Cloudflare Workers" error
9 2. `composio.files.download()` throws the expected "not supported in Cloudflare Workers" error
10 -3. The `FileToolModifier.workerd.ts` is correctly loaded and provides the expected error message when `autoUploadDownloadFiles` is explicitly enabled
11 -4. Composio initializes correctly with the default configuration (`autoUploadDownloadFiles: false` in workerd runtime)
12 -5. Composio can be explicitly initialized with `autoUploadDownloadFiles: false`
10 +3. The `FileToolModifier.workerd.ts` is correctly loaded and provides the expected error message when `dangerouslyAllowAutoUploadDownloadFiles` is explicitly enabled
11 +4. Composio initializes correctly with the default configuration (`dangerouslyAllowAutoUploadDownloadFiles: false` in workerd runtime)
12 +5. Composio can be explicitly initialized with `dangerouslyAllowAutoUploadDownloadFiles: false`
13
14 ## Endpoints
15
@@ -18,8 +18,8 @@ Verifies that:
18 | `GET /` | Lists all available test endpoints |
19 | `GET /test/files/upload` | Tests that `files.upload()` throws the expected error |
20 | `GET /test/files/download` | Tests that `files.download()` throws the expected error |
21 -| `GET /test/file-modifier/error-message` | Tests the error when `autoUploadDownloadFiles: true` is explicitly set |
22 -| `GET /test/auto-upload-disabled` | Tests Composio initialization with explicit `autoUploadDownloadFiles: false` |
21 +| `GET /test/file-modifier/error-message` | Tests the error when `dangerouslyAllowAutoUploadDownloadFiles: true` is explicitly set |
22 +| `GET /test/auto-upload-disabled` | Tests Composio initialization with explicit `dangerouslyAllowAutoUploadDownloadFiles: false` |
23 | `GET /test/default-config` | Tests Composio initialization with default configuration (no explicit setting) |
24
25 ## Running Tests
@@ -44,7 +44,7 @@ Note: For file operation tests, a dummy API key works since the operations throw
44
45 ## Default Configuration
46
47 -**In Cloudflare Workers (workerd runtime), `autoUploadDownloadFiles` defaults to `false`.**
47 +**In Cloudflare Workers (workerd runtime), `dangerouslyAllowAutoUploadDownloadFiles` defaults to `false`.**
48
49 This means you can initialize Composio without any special configuration:
50
@@ -52,26 +52,26 @@ This means you can initialize Composio without any special configuration:
52 const composio = new Composio({
53 apiKey: 'your-key',
54 });
55 -// autoUploadDownloadFiles is false by default in workerd
55 +// dangerouslyAllowAutoUploadDownloadFiles is false by default in workerd
56 ```
57
58 ## FileToolModifier Error
59
60 -If you explicitly set `autoUploadDownloadFiles: true` and execute a tool with file properties in Cloudflare Workers, the following error is thrown:
60 +If you explicitly set `dangerouslyAllowAutoUploadDownloadFiles: true` and execute a tool with file properties in Cloudflare Workers, the following error is thrown:
61
62 ```
63 File upload/download modifiers are not available on edge runtimes yet.
64 -Please set `autoUploadDownloadFiles: false` or run Composio in another JS runtime (Node.js / Bun).
64 +Please set `dangerouslyAllowAutoUploadDownloadFiles: false` (or unset it; it defaults to false) or run Composio in another JS runtime (Node.js / Bun).
65 ```
66
67 ### Best Practice
68
69 -For edge runtimes, use the default configuration or explicitly set `autoUploadDownloadFiles: false`:
69 +For edge runtimes, use the default configuration or explicitly set `dangerouslyAllowAutoUploadDownloadFiles: false`:
70
71 ```typescript
72 const composio = new Composio({
73 apiKey: 'your-key',
74 - autoUploadDownloadFiles: false, // This is the default for workerd
74 + dangerouslyAllowAutoUploadDownloadFiles: false, // This is the default for workerd
75 });
76 ```
77
ts/e2e-tests/runtimes/cloudflare/cf-workers-files/src/index.ts
+15 -15
@@ -94,10 +94,10 @@ app.get('/test/files/download', async c => {
94 });
95
96 /**
97 - * Test: FileToolModifier behavior (triggers the autoUploadDownloadFiles error)
97 + * Test: FileToolModifier behavior (triggers the auto-upload/download error)
98 *
99 - * The FileToolModifier.workerd.ts throws an error when autoUploadDownloadFiles is enabled.
100 - * In workerd runtime, the default is false, so we explicitly enable it here to test the error.
99 + * The FileToolModifier.workerd.ts throws an error when automatic file upload/download is enabled.
100 + * In workerd runtime, the default is off, so we explicitly opt in here to test the error.
101 *
102 * This endpoint actually executes a tool to trigger the real error from FileToolModifier.workerd.ts.
103 */
@@ -105,11 +105,11 @@ app.get('/test/file-modifier/error-message', async c => {
105 try {
106 const composio = new Composio({
107 apiKey: c.env.COMPOSIO_API_KEY,
108 - autoUploadDownloadFiles: true,
108 + dangerouslyAllowAutoUploadDownloadFiles: true,
109 });
110
111 // Use a local custom tool to avoid depending on remote Composio tool registry.
112 - // Any execute() call with autoUploadDownloadFiles enabled will trigger FileToolModifier
112 + // Any execute() with automatic file handling enabled will trigger FileToolModifier
113 // in the workerd runtime.
114 await composio.tools.createCustomTool({
115 slug: 'CUSTOM_FILE_TOOL',
@@ -149,24 +149,24 @@ app.get('/test/file-modifier/error-message', async c => {
149 });
150
151 /**
152 - * Test: Composio initialization with autoUploadDownloadFiles disabled
153 - *
154 - * In workerd runtime (Cloudflare Workers), autoUploadDownloadFiles defaults to false.
152 + * Test: Composio initialization with automatic file upload/download disabled
153 + *
154 + * In workerd runtime (Cloudflare Workers), dangerouslyAllowAutoUploadDownloadFiles defaults to false.
155 * This test verifies that the default configuration works correctly and that
156 * Composio can be initialized successfully without file upload/download support.
157 */
158 app.get('/test/auto-upload-disabled', async c => {
159 try {
160 - // Explicitly set autoUploadDownloadFiles: false (which is the default for workerd)
161 - // This is the recommended configuration for edge runtimes
160 + // Explicitly keep automatic file handling off (default everywhere)
161 const composio = new Composio({
162 apiKey: c.env.COMPOSIO_API_KEY,
164 - autoUploadDownloadFiles: false,
163 + dangerouslyAllowAutoUploadDownloadFiles: false,
164 });
165
166 return c.json({
167 success: true,
169 - message: 'Composio initialized successfully with autoUploadDownloadFiles: false',
168 + message:
169 + 'Composio initialized successfully with dangerouslyAllowAutoUploadDownloadFiles: false',
170 hasProvider: typeof composio.provider !== 'undefined',
171 hasTools: typeof composio.tools !== 'undefined',
172 hasFiles: typeof composio.files !== 'undefined',
@@ -189,12 +189,12 @@ app.get('/test/auto-upload-disabled', async c => {
189 * Test: Composio initialization with default configuration
190 *
191 * This test verifies that Composio initializes correctly with the default
192 - * configuration for workerd runtime (autoUploadDownloadFiles: false by default).
192 + * configuration for workerd runtime (dangerouslyAllowAutoUploadDownloadFiles: false by default).
193 * No explicit configuration is provided, relying on the runtime defaults.
194 */
195 app.get('/test/default-config', async c => {
196 try {
197 - // Initialize Composio without explicitly setting autoUploadDownloadFiles
197 + // Initialize Composio without explicitly setting dangerouslyAllowAutoUploadDownloadFiles
198 // Should use the workerd default (false)
199 const composio = new Composio({
200 apiKey: c.env.COMPOSIO_API_KEY,
@@ -206,7 +206,7 @@ app.get('/test/default-config', async c => {
206 hasProvider: typeof composio.provider !== 'undefined',
207 hasTools: typeof composio.tools !== 'undefined',
208 hasFiles: typeof composio.files !== 'undefined',
209 - note: 'In workerd runtime, autoUploadDownloadFiles defaults to false',
209 + note: 'In workerd runtime, dangerouslyAllowAutoUploadDownloadFiles defaults to false',
210 });
211 } catch (error) {
212 return c.json(
ts/e2e-tests/runtimes/cloudflare/cf-workers-files/test/files.spec.ts
+3 -3
@@ -75,7 +75,7 @@ describe('@composio/core Files - Cloudflare Workers compatibility', () => {
75 expect(body.error).toContain('not available on edge runtimes');
76 });
77
78 - it('should successfully initialize Composio with autoUploadDownloadFiles disabled', async () => {
78 + it('should successfully initialize Composio with automatic file handling disabled', async () => {
79 const request = new IncomingRequest('http://localhost/test/auto-upload-disabled');
80 const ctx = createExecutionContext();
81 const response = await app.fetch(request, env, ctx);
@@ -93,7 +93,7 @@ describe('@composio/core Files - Cloudflare Workers compatibility', () => {
93 };
94
95 expect(body.success).toBe(true);
96 - expect(body.message).toContain('autoUploadDownloadFiles: false');
96 + expect(body.message).toContain('dangerouslyAllowAutoUploadDownloadFiles: false');
97 expect(body.hasProvider).toBe(true);
98 expect(body.hasTools).toBe(true);
99 expect(body.hasFiles).toBe(true);
@@ -121,6 +121,6 @@ describe('@composio/core Files - Cloudflare Workers compatibility', () => {
121 expect(body.hasProvider).toBe(true);
122 expect(body.hasTools).toBe(true);
123 expect(body.hasFiles).toBe(true);
124 - expect(body.note).toContain('autoUploadDownloadFiles defaults to false');
124 + expect(body.note).toContain('dangerouslyAllowAutoUploadDownloadFiles defaults to false');
125 });
126 });
ts/examples/file-handling/src/index.ts
+14 -1
@@ -13,10 +13,23 @@ import 'dotenv/config';
13 import path from 'path';
14
15 /**
16 - * Initialize Composio
16 + * Initialize Composio.
17 + *
18 + * `dangerouslyAllowAutoUploadDownloadFiles: true` enables the SDK to read local
19 + * files from disk during tool execution. When that flag is on, local paths are
20 + * restricted to the directories listed in `fileUploadDirs`. Passing a value
21 + * REPLACES the default `[~/.composio/temp]` — include it if you want staged
22 + * uploads to keep working. Pass `false` (or `[]`) to reject every local path
23 + * while still allowing URLs and `File`/`Blob` objects.
24 + *
25 + * `fileDownloadDir` controls where files in tool responses (`s3url` fields) are
26 + * written. Defaults to `~/.composio/files`.
27 */
28 const composio = new Composio({
29 apiKey: process.env.COMPOSIO_API_KEY,
30 + dangerouslyAllowAutoUploadDownloadFiles: true,
31 + fileUploadDirs: [path.join(__dirname, '..'), '~/.composio/temp'],
32 + fileDownloadDir: path.join(__dirname, '..', '.composio-downloads'),
33 });
34
35 /**
ts/packages/core/README.md
+1 -1
@@ -122,7 +122,7 @@ interface ComposioConfig {
122 apiKey?: string | null; // Your Composio API key
123 baseURL?: string | null; // Custom API base URL (optional)
124 allowTracking?: boolean; // Enable/disable telemetry (default: true)
125 - autoUploadDownloadFiles?: boolean; // Whether to automatically upload and download files during tool execution (default: true)
125 + dangerouslyAllowAutoUploadDownloadFiles?: boolean; // Opt-in for automatic file upload/download during tool execution (default: false)
126 provider?: TProvider; // Custom provider (default: OpenAIProvider)
127 host?: string; // Name of the host service which is using the SDK, this is for telemetry
128 defaultHeaders?: ComposioRequestHeaders; // Request headers to be passed to the Composio API client
ts/packages/core/src/composio.ts
+51 -11
@@ -20,7 +20,7 @@ import { ToolkitVersionParam } from './types/tool.types';
20 import { ToolRouter } from './models/ToolRouter';
21 import { ToolRouterCreateSessionConfig, Session } from './types/toolRouter.types';
22 import { CONFIG_DEFAULTS } from './utils/config-defaults';
23 -
23 +import { expandHomeAndResolve, expandHomeAndResolveMany } from './utils/fileDirs';
24 export type ComposioConfig<
25 TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider,
26 > = {
@@ -41,11 +41,11 @@ export type ComposioConfig<
41 */
42 allowTracking?: boolean;
43 /**
44 - * Whether to automatically upload and download files during tool execution.
45 - * @example true, false
46 - * @default true
44 + * Opt in to automatic file upload and download during tool execution (reads local paths
45 + * and fetches URLs marked as file-uploadable in tool schemas). Disabled by default.
46 + * @default false
47 */
48 - autoUploadDownloadFiles?: boolean;
48 + dangerouslyAllowAutoUploadDownloadFiles?: boolean;
49 /**
50 * When true, local file paths for auto-upload and `files.upload` are checked against
51 * a built-in denylist of sensitive path segments (e.g. `.ssh`, `.aws`) and
@@ -59,6 +59,33 @@ export type ComposioConfig<
59 * they appear anywhere in the resolved path. Merged with the built-in list.
60 */
61 fileUploadPathDenySegments?: string[];
62 + /**
63 + * Allowlist of directories from which the SDK is allowed to read local files
64 + * during **automatic** file upload (when
65 + * `dangerouslyAllowAutoUploadDownloadFiles: true`). Manual
66 + * `composio.files.upload()` calls are NOT subject to this allowlist.
67 + *
68 + * - `undefined` (default) → `[<home>/.composio/temp]`.
69 + * - `false` → reject every local path during auto-upload. URLs
70 + * (`http(s)://...`) and `File`/`Blob` objects continue to work.
71 + * - `string[]` (non-empty) → use as the allowlist. A file is accepted iff
72 + * its symlink-resolved absolute path is inside one of these directories
73 + * on a path-component boundary (so `/tmp/foo` allows `/tmp/foo/bar` but
74 + * NOT `/tmp/foo-bar`).
75 + * - `[]` → behaves like `false` (kept as an alias; prefer `false` for
76 + * readability).
77 + * - Providing any value **replaces** the default. Include `~/.composio/temp`
78 + * in your list if you want the default staging dir to keep working.
79 + * - On Windows, entries are compared case-insensitively.
80 + */
81 + fileUploadDirs?: string[] | false;
82 + /**
83 + * Directory where files downloaded during tool execution (and
84 + * `composio.files.download()`) are written. Defaults to
85 + * `<home>/.composio/files`. Path is expanded at SDK-init time; relative
86 + * paths resolve against `process.cwd()`.
87 + */
88 + fileDownloadDir?: string;
89 /**
90 * The tool provider to use for this Composio instance.
91 * @example new OpenAIProvider()
@@ -264,10 +291,13 @@ export class Composio<
291 apiKey: apiKeyParsed,
292 toolkitVersions: getToolkitVersionsFromEnv(config?.toolkitVersions),
293 allowTracking: config?.allowTracking ?? CONFIG_DEFAULTS.allowTracking,
267 - autoUploadDownloadFiles:
268 - config?.autoUploadDownloadFiles ?? CONFIG_DEFAULTS.autoUploadDownloadFiles,
294 + dangerouslyAllowAutoUploadDownloadFiles:
295 + config?.dangerouslyAllowAutoUploadDownloadFiles ??
296 + CONFIG_DEFAULTS.dangerouslyAllowAutoUploadDownloadFiles,
297 sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection,
298 fileUploadPathDenySegments: config?.fileUploadPathDenySegments,
299 + fileUploadDirs: expandHomeAndResolveMany(config?.fileUploadDirs),
300 + fileDownloadDir: expandHomeAndResolve(config?.fileDownloadDir),
301 provider: config?.provider ?? this.provider,
302 };
303
@@ -292,6 +322,7 @@ export class Composio<
322 this.files = new Files(this.client, {
323 sensitiveFileUploadProtection: this.config.sensitiveFileUploadProtection,
324 fileUploadPathDenySegments: this.config.fileUploadPathDenySegments,
325 + fileDownloadDir: this.config.fileDownloadDir,
326 });
327 this.connectedAccounts = new ConnectedAccounts(this.client);
328 this.toolRouter = new ToolRouter(this.client, this.config);
@@ -343,11 +374,20 @@ export class Composio<
374 }
375
376 /**
346 - * Get the configuration SDK is initialized with
347 - * @returns {ComposioConfig<TProvider>} The configuration SDK is initialized with
377 + * Get the configuration SDK is initialized with.
378 + *
379 + * Returns a frozen shallow clone — the SDK has already snapshotted
380 + * configuration values such as `dangerouslyAllowAutoUploadDownloadFiles`,
381 + * `fileUploadDirs`, and `fileDownloadDir` into its internal models, so
382 + * mutating the live config object would silently no-op. Freezing makes
383 + * that contract visible at the call site instead of letting the mutation
384 + * appear successful.
385 + *
386 + * @returns {Readonly<ComposioConfig<TProvider>>} The frozen configuration
387 + * the SDK is initialized with.
388 */
349 - getConfig(): ComposioConfig<TProvider> {
350 - return this.config;
389 + getConfig(): Readonly<ComposioConfig<TProvider>> {
390 + return Object.freeze({ ...this.config });
391 }
392
393 /**
ts/packages/core/src/errors/FileModifierErrors.ts
+46
@@ -4,6 +4,8 @@ export const FileModifierErrorCodes = {
4 FILE_UPLOAD_FAILED: 'FILE_UPLOAD_FAILED',
5 SENSITIVE_FILE_PATH_BLOCKED: 'SENSITIVE_FILE_PATH_BLOCKED',
6 FILE_UPLOAD_ABORTED: 'FILE_UPLOAD_ABORTED',
7 + FILE_UPLOAD_PATH_NOT_ALLOWED: 'FILE_UPLOAD_PATH_NOT_ALLOWED',
8 + FILE_NOT_FOUND: 'FILE_NOT_FOUND',
9 } as const;
10
11 export class ComposioFileUploadError extends ComposioError {
@@ -52,3 +54,47 @@ export class ComposioFileUploadAbortedError extends ComposioFileUploadError {
54 this.name = 'ComposioFileUploadAbortedError';
55 }
56 }
57 +
58 +/**
59 + * Thrown when automatic file upload during tool execution is attempted from a path
60 + * that is outside the configured {@link ComposioConfig.fileUploadDirs} allowlist.
61 + *
62 + * This only fires for auto-upload (enabled via
63 + * `dangerouslyAllowAutoUploadDownloadFiles: true`). Manual `composio.files.upload()`
64 + * calls are never subject to this check.
65 + */
66 +export class ComposioFileUploadPathNotAllowedError extends ComposioFileUploadError {
67 + constructor(message: string, options: ComposioErrorOptions = {}) {
68 + super(message, {
69 + ...options,
70 + code: FileModifierErrorCodes.FILE_UPLOAD_PATH_NOT_ALLOWED,
71 + possibleFixes: options.possibleFixes ?? [
72 + 'Move the file under one of the directories in `fileUploadDirs`',
73 + 'Stage the file under the default upload dir (`~/.composio/temp`)',
74 + 'Add the containing directory to `fileUploadDirs` when constructing Composio',
75 + 'Pass the file by URL or as a File/Blob object instead of a filesystem path',
76 + ],
77 + });
78 + this.name = 'ComposioFileUploadPathNotAllowedError';
79 + }
80 +}
81 +
82 +/**
83 + * Thrown when a local file path passed for upload does not exist on disk.
84 + * Provides extra debugging context (resolved absolute path, cwd, allowlist state)
85 + * to help the caller distinguish between "typo" and "not-allowlisted" failures.
86 + */
87 +export class ComposioFileNotFoundError extends ComposioFileUploadError {
88 + constructor(message: string, options: ComposioErrorOptions = {}) {
89 + super(message, {
90 + ...options,
91 + code: FileModifierErrorCodes.FILE_NOT_FOUND,
92 + possibleFixes: options.possibleFixes ?? [
93 + 'Double-check the path for typos',
94 + 'Remember relative paths are resolved against process.cwd() at upload time',
95 + 'Verify the file exists and the process has read permission',
96 + ],
97 + });
98 + this.name = 'ComposioFileNotFoundError';
99 + }
100 +}
ts/packages/core/src/models/Files.node.ts
+16 -6
@@ -11,19 +11,21 @@ import { downloadFileFromS3, getFileDataAfterUploadingToS3 } from '../utils/file
11 import { telemetry } from '../telemetry/Telemetry';
12
13 export class Files {
14 - private readonly fileUploadPathOptions: {
14 + private readonly fileOptions: {
15 sensitiveFileUploadProtection?: boolean;
16 fileUploadPathDenySegments?: string[];
17 + fileDownloadDir?: string;
18 };
19
20 constructor(
21 private readonly client: ComposioClient,
21 - fileUploadPathOptions: {
22 + fileOptions: {
23 sensitiveFileUploadProtection?: boolean;
24 fileUploadPathDenySegments?: string[];
25 + fileDownloadDir?: string;
26 } = {}
27 ) {
26 - this.fileUploadPathOptions = fileUploadPathOptions;
28 + this.fileOptions = fileOptions;
29 telemetry.instrument(this, 'Files');
30 }
31
@@ -53,12 +55,15 @@ export class Files {
55 toolSlug: string;
56 toolkitSlug: string;
57 }): Promise<FileUploadData> {
58 + // Note: manual `composio.files.upload()` intentionally skips the
59 + // `fileUploadDirs` allowlist. The allowlist only gates *automatic* upload
60 + // during tool execution (see FileToolModifier).
61 const fileData = await getFileDataAfterUploadingToS3(file, {
62 toolSlug,
63 toolkitSlug,
64 client: this.client,
60 - sensitiveFileUploadProtection: this.fileUploadPathOptions.sensitiveFileUploadProtection,
61 - fileUploadPathDenySegments: this.fileUploadPathOptions.fileUploadPathDenySegments,
65 + sensitiveFileUploadProtection: this.fileOptions.sensitiveFileUploadProtection,
66 + fileUploadPathDenySegments: this.fileOptions.fileUploadPathDenySegments,
67 });
68 return fileData;
69 }
@@ -77,7 +82,12 @@ export class Files {
82 toolSlug: string;
83 mimeType: string;
84 }): Promise<FileDownloadData> {
80 - const fileDownloadData = await downloadFileFromS3({ toolSlug, s3Url, mimeType });
85 + const fileDownloadData = await downloadFileFromS3({
86 + toolSlug,
87 + s3Url,
88 + mimeType,
89 + fileDownloadDir: this.fileOptions.fileDownloadDir,
90 + });
91 return fileDownloadData;
92 }
93 }
ts/packages/core/src/models/Tools.ts
+54 -11
@@ -56,6 +56,8 @@ import { handleToolExecutionError } from '../errors/ToolErrors';
56 import { ToolExecuteMetaParams } from '../types/tool.types';
57 import { SessionExecuteMetaParams } from '@composio/client/resources/tool-router.mjs';
58 import { CONFIG_DEFAULTS } from '../utils/config-defaults';
59 +import { resolveEffectiveUploadAllowlist } from '../utils/fileDirs';
60 +import { schemaHasFileUploadable } from '../utils/modifiers/FileToolModifier.utils.neutral';
61 /**
62 * This class is used to manage tools in the Composio SDK.
63 * It provides methods to list, get, and execute tools.
@@ -73,7 +75,15 @@ export class Tools<
75 private fileUploadPathOptions: {
76 sensitiveFileUploadProtection?: boolean;
77 fileUploadPathDenySegments?: string[];
78 + fileUploadAllowlist?: string[];
79 + fileDownloadDir?: string;
80 };
81 + /**
82 + * Tracks tool slugs we've already warned about to avoid spamming the log when
83 + * the same file-input tool is executed repeatedly while auto-upload is off.
84 + * Scoped per-instance so a fresh `Composio` starts with a clean slate.
85 + */
86 + private readonly warnedAutoUploadDisabledForTool = new Set<string>();
87
88 constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {
89 if (!client) {
@@ -86,12 +96,17 @@ export class Tools<
96 this.client = client;
97 this.customTools = new CustomTools(client);
98 this.provider = config.provider;
89 - this.autoUploadDownloadFiles =
90 - config?.autoUploadDownloadFiles ?? CONFIG_DEFAULTS.autoUploadDownloadFiles;
99 + this.autoUploadDownloadFiles = config?.dangerouslyAllowAutoUploadDownloadFiles === true;
100 this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
101 this.fileUploadPathOptions = {
102 sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection,
103 fileUploadPathDenySegments: config?.fileUploadPathDenySegments,
104 + // The allowlist is only enforced during automatic upload (see
105 + // FileToolModifier). Manual `composio.files.upload()` calls don't see it.
106 + fileUploadAllowlist: this.autoUploadDownloadFiles
107 + ? resolveEffectiveUploadAllowlist(config?.fileUploadDirs)
108 + : undefined,
109 + fileDownloadDir: config?.fileDownloadDir,
110 };
111 // Bind the execute method to ensure correct 'this' context
112 this.execute = this.execute.bind(this);
@@ -150,21 +165,29 @@ export class Tools<
165 }
166
167 /**
153 - * Applies the default schema modifiers to the tools
168 + * Applies the default schema modifiers to the tools.
169 + *
170 + * The `file_uploadable` transform (collapsing the backend's internal
171 + * `{ name, mimetype, s3key }` staging shape to `{ type: 'string',
172 + * format: 'path' }`) is **gated on `dangerouslyAllowAutoUploadDownloadFiles`**
173 + * — the collapsed shape is a promise that the SDK will stage local paths
174 + * on your behalf at execute time, and that's only true when the flag is on.
175 + *
176 + * When the flag is off, the raw schema is returned unchanged; callers are
177 + * expected to stage files themselves via `composio.files.upload()` and pass
178 + * the resulting descriptor into `tools.execute`. If an LLM ends up calling
179 + * a file-uploadable tool in this mode, the execute path emits a one-shot
180 + * warning per tool slug (see `applyBeforeExecuteModifiers`).
181 + *
182 * @param tools - The tools to apply the default schema modifiers to
183 * @returns The tools with the default schema modifiers applied
184 */
185 private async applyDefaultSchemaModifiers(tools: Tool[]): Promise<Tool[]> {
158 - if (this.autoUploadDownloadFiles) {
159 - const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions);
160 - return await Promise.all(
161 - tools.map(tool =>
162 - fileToolModifier.modifyToolSchema(tool.slug, tool.toolkit?.slug ?? 'unknown', tool)
163 - )
164 - );
165 - } else {
186 + if (!this.autoUploadDownloadFiles) {
187 return tools;
188 }
189 + const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions);
190 + return await Promise.all(tools.map(tool => fileToolModifier.modifyToolSchema(tool)));
191 }
192
193 /**
@@ -200,6 +223,26 @@ export class Tools<
223 toolkitSlug,
224 params: modifiedParams,
225 });
226 + } else if (
227 + schemaHasFileUploadable(tool.inputParameters) &&
228 + !this.warnedAutoUploadDisabledForTool.has(toolSlug)
229 + ) {
230 + // With auto-upload off, the raw `{ name, mimetype, s3key }` shape is
231 + // what the LLM / caller sees on `tool.inputParameters`. LLMs can't
232 + // produce a valid `s3key` and will hallucinate one, which then fails
233 + // at the staging-lookup step on the backend. Nudge the caller toward
234 + // manual staging or opting into auto-upload.
235 + this.warnedAutoUploadDisabledForTool.add(toolSlug);
236 + logger.warn(
237 + `Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but ` +
238 + `\`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward ` +
239 + `the file argument as-is; if it isn't already a staged ` +
240 + `{ name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n` +
241 + ` 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); ` +
242 + `await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n` +
243 + ` 2) Enable auto-upload with a scoped allowlist: ` +
244 + `\`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.`
245 + );
246 }
247 // apply the before execute modifiers
248 if (modifiers?.beforeExecute) {
ts/packages/core/src/platform/node.ts
+8
@@ -22,6 +22,14 @@ export const platform = {
22 return path.join(...paths);
23 },
24
25 + resolvePath(...paths: string[]): string {
26 + return path.resolve(...paths);
27 + },
28 +
29 + isAbsolutePath(filePath: string): boolean {
30 + return path.isAbsolute(filePath);
31 + },
32 +
33 basename(filePath: string): string {
34 return path.basename(filePath);
35 },
ts/packages/core/src/platform/types.ts
+12
@@ -16,6 +16,18 @@ export interface Platform {
16 */
17 joinPath(...paths: string[]): string;
18
19 + /**
20 + * Resolves a sequence of paths into an absolute path. On Node this is
21 + * `path.resolve`; on edge runtimes without a working directory it
22 + * normalizes/joins the segments and returns the result verbatim.
23 + */
24 + resolvePath(...paths: string[]): string;
25 +
26 + /**
27 + * Returns true if the given path is absolute.
28 + */
29 + isAbsolutePath(filePath: string): boolean;
30 +
31 /**
32 * Returns the last portion of a path (the filename).
33 * @param filePath - The path to extract the basename from.
ts/packages/core/src/platform/workerd.ts
+12
@@ -26,6 +26,18 @@ export const platform: Platform = {
26 .join('/');
27 },
28
29 + resolvePath(...paths: string[]): string {
30 + // No working directory in edge runtimes. Best-effort: join the segments
31 + // and return the result. Callers that need a real `path.resolve` should
32 + // gate on `supportsFileSystem`.
33 + return this.joinPath(...paths);
34 + },
35 +
36 + isAbsolutePath(filePath: string): boolean {
37 + // POSIX-only check; edge runtimes don't have Windows-style drive letters.
38 + return filePath.startsWith('/');
39 + },
40 +
41 basename(filePath: string): string {
42 // Simple basename extraction without Node.js path module
43 const segments = filePath.replace(/\/+$/, '').split('/');
ts/packages/core/src/types/modifiers.types.ts
+21 -3
@@ -180,12 +180,30 @@ export type afterExecuteModifier = (context: {
180 }) => Promise<ToolExecuteResponse> | ToolExecuteResponse;
181
182 /**
183 - * Called for each `file_uploadable` value before the SDK reads the file and uploads to storage.
184 - * For a string, `path` is the local path or URL. For a `File` object, `path` is the file's name; you may return
185 - * a different filesystem path to upload instead, or return `false` to abort the upload. Throwing an error also aborts.
183 + * Discriminates what kind of input the hook is seeing:
184 + *
185 + * - `'path'` — a local filesystem path string.
186 + * - `'url'` — an `http(s)://...` URL string.
187 + * - `'file'` — a `File` object; `path` holds `file.name` (a filename, NOT a
188 + * filesystem path). Returning a string from the hook in this case replaces
189 + * the `File` with a local-path upload.
190 + */
191 +export type BeforeFileUploadSource = 'path' | 'url' | 'file';
192 +
193 +/**
194 + * Called for each `file_uploadable` value before the SDK reads the file and
195 + * uploads to storage.
196 + *
197 + * - `context.path` holds the local path, the URL, or the `File`'s name
198 + * depending on `context.source`.
199 + * - Return a string to replace the input (e.g. rewrite the path, redirect a
200 + * URL, or swap a `File` for a filesystem path).
201 + * - Return `false` to abort the upload with `ComposioFileUploadAbortedError`.
202 + * - Throwing an error also aborts.
203 */
204 export type beforeFileUploadModifier = (context: {
205 path: string;
206 + source: BeforeFileUploadSource;
207 toolSlug: string;
208 toolkitSlug: string;
209 }) => Promise<string | false> | string | false;
ts/packages/core/src/utils/config-defaults/ConfigDefaults.node.ts
+1 -1
@@ -1,7 +1,7 @@
1 import type { ConfigDefaults } from './types';
2
3 export const CONFIG_DEFAULTS: ConfigDefaults = {
4 - autoUploadDownloadFiles: true,
4 + dangerouslyAllowAutoUploadDownloadFiles: false,
5 allowTracking: true,
6 toolkitVersions: 'latest',
7 };
ts/packages/core/src/utils/config-defaults/ConfigDefaults.workerd.ts
+1 -1
@@ -4,7 +4,7 @@ export const CONFIG_DEFAULTS: ConfigDefaults = {
4 /**
5 * We don't support auto-uploading/download files in Cloudflare Workers yet.
6 */
7 - autoUploadDownloadFiles: false,
7 + dangerouslyAllowAutoUploadDownloadFiles: false,
8 allowTracking: true,
9 toolkitVersions: 'latest',
10 };
ts/packages/core/src/utils/config-defaults/types.ts
+1 -1
@@ -9,6 +9,6 @@ import type { BaseComposioProvider } from '../../provider/BaseProvider';
9 export type ConfigDefaults = Required<
10 Pick<
11 ComposioConfig<BaseComposioProvider<never, never, never>>,
12 - 'autoUploadDownloadFiles' | 'allowTracking' | 'toolkitVersions'
12 + 'dangerouslyAllowAutoUploadDownloadFiles' | 'allowTracking' | 'toolkitVersions'
13 >
14 >;
ts/packages/core/src/utils/fileDirs.ts new
+81
@@ -0,0 +1,81 @@
1 +/**
2 + * Runtime-neutral helpers for normalizing user-provided filesystem paths.
3 + *
4 + * In filesystem-less runtimes (Cloudflare Workers, etc.) the platform
5 + * abstraction reports `supportsFileSystem: false` and `homedir()` returns
6 + * `null`. We use that as the signal to drop unresolvable entries from the
7 + * allowlist (fail-closed) rather than silently passing `~/foo` through as
8 + * a literal directory name.
9 + */
10 +
11 +import { platform } from '#platform';
12 +
13 +/**
14 + * Expands a leading `~` to the user's home directory and resolves to an
15 + * absolute path. Returns `undefined` when expansion is required but no
16 + * home directory is available — that signals "unusable, drop me" to
17 + * {@link expandHomeAndResolveMany}, which is safer than letting the literal
18 + * `~/foo` survive as a CWD-relative path.
19 + */
20 +export function expandHomeAndResolve(p: string | undefined): string | undefined {
21 + if (!p) return p;
22 + let expanded = p;
23 + if (p === '~' || p.startsWith('~/') || p.startsWith('~\\')) {
24 + const home = platform.homedir();
25 + if (!home) return undefined;
26 + expanded = p === '~' ? home : platform.joinPath(home, p.slice(2));
27 + }
28 + return platform.resolvePath(expanded);
29 +}
30 +
31 +/**
32 + * Applies {@link expandHomeAndResolve} to each entry, dropping empty/invalid
33 + * values. Preserves `undefined` and `false` (so downstream can distinguish
34 + * "user did not configure" from "user explicitly disabled local uploads"
35 + * from "user configured []").
36 + */
37 +export function expandHomeAndResolveMany(
38 + list: string[] | false | undefined
39 +): string[] | false | undefined {
40 + if (list === undefined) return undefined;
41 + if (list === false) return false;
42 + const out: string[] = [];
43 + for (const raw of list) {
44 + if (typeof raw !== 'string' || raw.trim() === '') continue;
45 + const resolved = expandHomeAndResolve(raw);
46 + if (resolved) out.push(resolved);
47 + }
48 + return out;
49 +}
50 +
51 +/**
52 + * Absolute path of the default upload staging directory
53 + * (`<home>/.composio/temp`), or `null` when a home directory is unavailable
54 + * (e.g. Cloudflare Workers).
55 + */
56 +export function getDefaultUploadDir(): string | null {
57 + const home = platform.homedir();
58 + if (!home) return null;
59 + return platform.resolvePath(platform.joinPath(home, '.composio', 'temp'));
60 +}
61 +
62 +/**
63 + * Resolve the effective upload allowlist for a given user-provided value.
64 + *
65 + * - `undefined` → `[<default>]` when a home directory is available, else `[]`
66 + * (fail-closed if we can't derive the default staging dir).
67 + * - `false` → `[]` (explicit "reject all local paths"). URLs / File objects
68 + * still work because they aren't path-checked.
69 + * - `string[]` (including `[]`) replaces the default and is returned
70 + * verbatim after `~` expansion / `path.resolve`. `[]` is treated as
71 + * equivalent to `false`.
72 + */
73 +export function resolveEffectiveUploadAllowlist(userDirs: string[] | false | undefined): string[] {
74 + if (userDirs === undefined) {
75 + const def = getDefaultUploadDir();
76 + return def ? [def] : [];
77 + }
78 + if (userDirs === false) return [];
79 + const resolved = expandHomeAndResolveMany(userDirs);
80 + return Array.isArray(resolved) ? resolved : [];
81 +}
ts/packages/core/src/utils/fileUtils.node.ts
+65 -14
@@ -8,6 +8,7 @@ import { getRandomShortId } from './uuid';
8 import { base64ToUint8Array, uint8ArrayToBase64 } from './buffer';
9 import type { FileDownloadData, FileUploadData } from '../types/files.types';
10 import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths.node';
11 +import { assertPathInsideUploadDirs } from './uploadDirAllowlist.node';
12
13 /**
14 * Options for {@link getFileDataAfterUploadingToS3} (S3 presigned upload from local path, URL, or File).
@@ -26,6 +27,15 @@ export type GetFileDataAfterUploadingToS3Options = {
27 * merged with the built-in list.
28 */
29 fileUploadPathDenySegments?: string[];
30 + /**
31 + * When provided, the local path must resolve inside one of these directories
32 + * (after symlink resolution, on a component boundary) or upload is rejected.
33 + * Intended for automatic upload during tool execution; manual
34 + * `composio.files.upload()` calls pass `undefined` here to skip enforcement.
35 + *
36 + * An empty array means "no paths are allowed" (fail-closed).
37 + */
38 + fileUploadAllowlist?: string[];
39 };
40
41 // Helper function to get file extension from MIME type
@@ -244,18 +254,23 @@ export const getFileDataAfterUploadingToS3 = async (
254 client,
255 sensitiveFileUploadProtection,
256 fileUploadPathDenySegments,
257 + fileUploadAllowlist,
258 }: GetFileDataAfterUploadingToS3Options
259 ): Promise<FileUploadData> => {
260 if (!file) {
261 throw new Error('Either path or blob must be provided');
262 }
263
253 - if (
254 - sensitiveFileUploadProtection !== false &&
255 - typeof file === 'string' &&
256 - !file.startsWith('http')
257 - ) {
258 - assertSafeFileUploadPath(file, { additionalDenySegments: fileUploadPathDenySegments });
264 + const isLocalPath = typeof file === 'string' && !file.startsWith('http');
265 +
266 + if (isLocalPath && fileUploadAllowlist !== undefined) {
267 + assertPathInsideUploadDirs(file as string, fileUploadAllowlist);
268 + }
269 +
270 + if (sensitiveFileUploadProtection !== false && isLocalPath) {
271 + assertSafeFileUploadPath(file as string, {
272 + additionalDenySegments: fileUploadPathDenySegments,
273 + });
274 }
275
276 const fileData = await readFile(file);
@@ -281,10 +296,16 @@ export const downloadFileFromS3 = async ({
296 toolSlug,
297 s3Url,
298 mimeType,
299 + fileDownloadDir,
300 }: {
301 toolSlug: string;
302 s3Url: string;
303 mimeType: string;
304 + /**
305 + * Absolute path to the directory to save the file into. When omitted, falls
306 + * back to `<home>/.composio/files` (the legacy default).
307 + */
308 + fileDownloadDir?: string;
309 }): Promise<FileDownloadData> => {
310 const response = await fetch(s3Url);
311 if (!response.ok) {
@@ -294,7 +315,10 @@ export const downloadFileFromS3 = async ({
315
316 const extension = getExtensionFromMimeType(mimeType);
317 const fileName = generateTimestampedFilename(extension, `${toolSlug}_`);
297 - const filePath = saveFile(fileName, new Uint8Array(data), true);
318 + const filePath = saveFile(fileName, new Uint8Array(data), {
319 + isTempFile: fileDownloadDir === undefined,
320 + outputDir: fileDownloadDir,
321 + });
322 return {
323 name: fileName,
324 mimeType: mimeType,
@@ -354,23 +378,50 @@ export const getComposioTempFilesDir = (createDirIfNotExists: boolean = false) =
378 };
379
380 /**
357 - * Saves a file to the Composio directory.
358 - * @param file - The name of the file to save.
359 - * @param content - The content of the file to save. Can be a string or Uint8Array.
360 - * @param isTempFile - Whether the file is a temporary file.
361 - * @returns The path to the saved file.
381 + * Saves a file to a local directory.
382 + *
383 + * Directory precedence (highest first):
384 + * 1. `options.outputDir` (explicit, absolute or relative; created if missing)
385 + * 2. `options.isTempFile === true` → `<home>/.composio/files`
386 + * 3. fallback → `<home>/.composio`
387 + *
388 + * @returns The absolute path to the saved file, or `null` if the runtime has
389 + * no filesystem (e.g. Cloudflare Workers) or the save failed.
390 */
391 export const saveFile = (
392 file: string,
393 content: string | Uint8Array,
366 - isTempFile: boolean = false
394 + options: { isTempFile?: boolean; outputDir?: string } | boolean = {}
395 ) => {
396 + // Back-compat: legacy callers passed a boolean `isTempFile` positional.
397 + const opts: { isTempFile?: boolean; outputDir?: string } =
398 + typeof options === 'boolean' ? { isTempFile: options } : options;
399 +
400 try {
401 if (!platform.supportsFileSystem) {
402 logger.debug('File system operations are not supported in this runtime environment');
403 return null;
404 }
373 - const composioFilesDir = isTempFile ? getComposioTempFilesDir(true) : getComposioDir(true);
405 +
406 + let composioFilesDir: string | null | undefined;
407 + if (opts.outputDir) {
408 + const absDir = platform.joinPath(opts.outputDir); // platform.joinPath normalizes
409 + try {
410 + if (!platform.existsSync(absDir)) {
411 + platform.mkdirSync(absDir);
412 + }
413 + composioFilesDir = absDir;
414 + } catch (err) {
415 + logger.warn(
416 + `fileDownloadDir "${absDir}" is not writable, falling back to the default ` +
417 + `(~/.composio/files). Error: ${err}`
418 + );
419 + composioFilesDir = getComposioTempFilesDir(true);
420 + }
421 + } else {
422 + composioFilesDir = opts.isTempFile ? getComposioTempFilesDir(true) : getComposioDir(true);
423 + }
424 +
425 if (!composioFilesDir) {
426 return null;
427 }
ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts
+39 -21
@@ -7,8 +7,10 @@ import {
7 import ComposioClient from '@composio/client';
8 import logger from '../logger';
9 import {
10 + ComposioFileNotFoundError,
11 ComposioFileUploadAbortedError,
12 ComposioFileUploadError,
13 + ComposioFileUploadPathNotAllowedError,
14 ComposioSensitiveFilePathBlockedError,
15 } from '../../errors/FileModifierErrors';
16 import type { beforeFileUploadModifier } from '../../types/modifiers.types';
@@ -39,7 +41,7 @@ const hydrateFiles = async (
41 client: ComposioClient;
42 } & Pick<
43 GetFileDataAfterUploadingToS3Options,
42 - 'sensitiveFileUploadProtection' | 'fileUploadPathDenySegments'
44 + 'sensitiveFileUploadProtection' | 'fileUploadPathDenySegments' | 'fileUploadAllowlist'
45 > & {
46 beforeFileUpload?: beforeFileUploadModifier;
47 }
@@ -51,12 +53,16 @@ const hydrateFiles = async (
53 // Upload only if the runtime value is a string (i.e., a local path) or blob
54 if (typeof value !== 'string' && !(value instanceof File)) return value;
55
54 - const runBeforeFileUpload = async (path: string): Promise<string> => {
56 + const runBeforeFileUpload = async (
57 + path: string,
58 + source: 'path' | 'url' | 'file'
59 + ): Promise<string> => {
60 if (!ctx.beforeFileUpload) {
61 return path;
62 }
63 const out = await ctx.beforeFileUpload({
64 path,
65 + source,
66 toolSlug: ctx.toolSlug,
67 toolkitSlug: ctx.toolkitSlug,
68 });
@@ -69,7 +75,10 @@ const hydrateFiles = async (
75 };
76
77 if (typeof value === 'string') {
72 - const pathOrUrl = await runBeforeFileUpload(value);
78 + // Match the URL/local-path split used downstream in
79 + // getFileDataAfterUploadingToS3 so the hook sees the same categorisation.
80 + const source = value.startsWith('http') ? 'url' : 'path';
81 + const pathOrUrl = await runBeforeFileUpload(value, source);
82 logger.debug(`Uploading file "${pathOrUrl}"`);
83 return getFileDataAfterUploadingToS3(pathOrUrl, {
84 toolSlug: ctx.toolSlug,
@@ -77,13 +86,16 @@ const hydrateFiles = async (
86 client: ctx.client,
87 sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
88 fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
89 + fileUploadAllowlist: ctx.fileUploadAllowlist,
90 });
91 }
92
83 - // File
93 + // File — `path` is the filename only; a string return replaces it with a
94 + // local-path upload.
95 if (ctx.beforeFileUpload) {
96 const out = await ctx.beforeFileUpload({
97 path: value.name,
98 + source: 'file',
99 toolSlug: ctx.toolSlug,
100 toolkitSlug: ctx.toolkitSlug,
101 });
@@ -100,10 +112,12 @@ const hydrateFiles = async (
112 client: ctx.client,
113 sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
114 fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
115 + fileUploadAllowlist: ctx.fileUploadAllowlist,
116 });
117 }
118 }
119 logger.debug(`Uploading file "${value.name}"`);
120 + // File/Blob values are not subject to the upload-dir allowlist.
121 return getFileDataAfterUploadingToS3(value, {
122 toolSlug: ctx.toolSlug,
123 toolkitSlug: ctx.toolkitSlug,
@@ -114,7 +128,14 @@ const hydrateFiles = async (
128 }
129
130 // ──────────────────────────────────────────────────────────────────────────
117 - // 2. Handle anyOf/oneOf/allOf - try each variant that may contain file_uploadable
131 + // 2. Handle anyOf/oneOf/allOf — pick the first variant that contains a
132 + // file_uploadable property and hydrate against it.
133 + //
134 + // We deliberately do NOT loop over every uploadable variant. With `oneOf`,
135 + // exactly one variant should apply at runtime, and applying multiple would
136 + // upload the same file once per variant — two presigned-URL round-trips and
137 + // two S3 PUTs for a two-variant `oneOf`. Matching the Python SDK
138 + // (`_find_uploadable_schema_variant`), we short-circuit on the first match.
139 // ──────────────────────────────────────────────────────────────────────────
140 const schemaVariants = [
141 ...(schema?.anyOf ?? []),
@@ -123,16 +144,9 @@ const hydrateFiles = async (
144 ];
145
146 if (schemaVariants.length > 0) {
126 - // Find variants that have file_uploadable properties
127 - const uploadableVariants = schemaVariants.filter(schemaHasFileUploadable);
128 -
129 - if (uploadableVariants.length > 0) {
130 - // Process with each uploadable variant - we try all since we can't know which one matches at runtime
131 - let result = value;
132 - for (const variant of uploadableVariants) {
133 - result = await hydrateFiles(result, variant, ctx);
134 - }
135 - return result;
147 + const firstUploadableVariant = schemaVariants.find(schemaHasFileUploadable);
148 + if (firstUploadableVariant) {
149 + return hydrateFiles(value, firstUploadableVariant, ctx);
150 }
151 // If no uploadable variants found, fall through to check base properties
152 }
@@ -172,7 +186,7 @@ const hydrateFiles = async (
186 */
187 const downloadS3File = async (
188 value: Record<string, unknown>,
175 - ctx: { toolSlug: string }
189 + ctx: { toolSlug: string; fileDownloadDir?: string }
190 ): Promise<unknown> => {
191 const { s3url, mimetype } = value as {
192 s3url: string;
@@ -186,6 +200,7 @@ const downloadS3File = async (
200 toolSlug: ctx.toolSlug,
201 s3Url: s3url,
202 mimeType: mimetype ?? 'application/octet-stream',
203 + fileDownloadDir: ctx.fileDownloadDir,
204 });
205
206 logger.debug(`Downloaded → ${dl.filePath}`);
@@ -223,7 +238,7 @@ const downloadS3File = async (
238 const hydrateDownloads = async (
239 value: unknown,
240 schema: JSONSchemaProperty | undefined,
226 - ctx: { toolSlug: string }
241 + ctx: { toolSlug: string; fileDownloadDir?: string }
242 ): Promise<unknown> => {
243 // ──────────────────────────────────────────────────────────────────────────
244 // 1. Direct S3 reference (data-driven detection)
@@ -304,8 +319,8 @@ export class FileToolModifier {
319 private client: ComposioClient;
320 private fileUploadPathOptions: Pick<
321 GetFileDataAfterUploadingToS3Options,
307 - 'sensitiveFileUploadProtection' | 'fileUploadPathDenySegments'
308 - > & { beforeFileUpload?: beforeFileUploadModifier };
322 + 'sensitiveFileUploadProtection' | 'fileUploadPathDenySegments' | 'fileUploadAllowlist'
323 + > & { beforeFileUpload?: beforeFileUploadModifier; fileDownloadDir?: string };
324
325 constructor(
326 client: ComposioClient,
@@ -315,7 +330,7 @@ export class FileToolModifier {
330 this.fileUploadPathOptions = fileUploadPathOptions;
331 }
332
318 - async modifyToolSchema(toolSlug: string, toolkitSlug: string, schema: Tool): Promise<Tool> {
333 + async modifyToolSchema(schema: Tool): Promise<Tool> {
334 if (!schema.inputParameters?.properties) {
335 return schema;
336 }
@@ -356,7 +371,9 @@ export class FileToolModifier {
371 } catch (error) {
372 if (
373 error instanceof ComposioSensitiveFilePathBlockedError ||
359 - error instanceof ComposioFileUploadAbortedError
374 + error instanceof ComposioFileUploadAbortedError ||
375 + error instanceof ComposioFileUploadPathNotAllowedError ||
376 + error instanceof ComposioFileNotFoundError
377 ) {
378 throw error;
379 }
@@ -379,6 +396,7 @@ export class FileToolModifier {
396 // Walk result.data without mutating the original, using output schema for guidance
397 const dataWithDownloads = await hydrateDownloads(result.data, tool.outputParameters, {
398 toolSlug,
399 + fileDownloadDir: this.fileUploadPathOptions.fileDownloadDir,
400 });
401
402 return { ...result, data: dataWithDownloads as typeof result.data };
ts/packages/core/src/utils/modifiers/FileToolModifier.workerd.ts
+2 -2
@@ -4,12 +4,12 @@ import { transformProperties } from './FileToolModifier.utils.neutral';
4
5 const UNSUPPORTED_MESSAGE =
6 'File upload/download modifiers are not available on edge runtimes yet. ' +
7 - 'Please set `autoUploadDownloadFiles: false` or run Composio in another JS runtime (Node.js / Bun).';
7 + 'Please set `dangerouslyAllowAutoUploadDownloadFiles: false` (or unset it; it defaults to false) or run Composio in another JS runtime (Node.js / Bun).';
8
9 export class FileToolModifier {
10 constructor(_client: ComposioClient) {}
11
12 - async modifyToolSchema(toolSlug: string, toolkitSlug: string, schema: Tool): Promise<Tool> {
12 + async modifyToolSchema(schema: Tool): Promise<Tool> {
13 if (!schema.inputParameters?.properties) {
14 return schema;
15 }
ts/packages/core/src/utils/uploadDirAllowlist.node.ts new
+178
@@ -0,0 +1,178 @@
1 +/**
2 + * Allowlist for automatic file upload during tool execution.
3 + *
4 + * This is only consulted when `dangerouslyAllowAutoUploadDownloadFiles` is enabled.
5 + * Manual `composio.files.upload()` calls are not subject to the allowlist.
6 + *
7 + * - A local path is accepted iff its real (symlink-resolved, absolute) path is
8 + * inside one of the allowed directories on a path-component boundary.
9 + * `/tmp/foo` allows `/tmp/foo/bar` but NOT `/tmp/foo-bar`.
10 + * - URLs (`http(s)://…`) and `File`/`Blob` values never hit this check.
11 + * - User-provided `fileUploadDirs` fully replaces the default `[~/.composio/temp]`.
12 + * - On Windows, path comparisons are case-insensitive.
13 + */
14 +import * as path from 'node:path';
15 +import fs from 'node:fs';
16 +import {
17 + ComposioFileUploadPathNotAllowedError,
18 + ComposioFileNotFoundError,
19 +} from '../errors/FileModifierErrors';
20 +
21 +/**
22 + * Ensures the given directory exists (best-effort, non-throwing). Safe to call
23 + * during SDK init; allowlist enforcement still works even if creation fails.
24 + */
25 +export function ensureDirExists(dir: string): void {
26 + try {
27 + fs.mkdirSync(dir, { recursive: true });
28 + } catch {
29 + // ignore
30 + }
31 +}
32 +
33 +function normalizeForCompare(p: string): string {
34 + return process.platform === 'win32' ? p.toLowerCase() : p;
35 +}
36 +
37 +/**
38 + * True if `child` is equal to `parent` or nested inside it on a component
39 + * boundary. Assumes both paths are absolute and normalized.
40 + */
41 +function isInsideDir(child: string, parent: string): boolean {
42 + const a = normalizeForCompare(child);
43 + const b = normalizeForCompare(parent);
44 + if (a === b) return true;
45 + const sep = path.sep;
46 + const bWithSep = b.endsWith(sep) ? b : b + sep;
47 + return a.startsWith(bWithSep);
48 +}
49 +
50 +/**
51 + * Returns the real (symlink-resolved) absolute path when the target exists,
52 + * else `null`. Mirrors the semantics of the sensitive-path util.
53 + */
54 +function tryRealpath(absPath: string): string | null {
55 + try {
56 + if (fs.existsSync(absPath)) {
57 + return fs.realpathSync(absPath);
58 + }
59 + } catch {
60 + // ignore and fall through
61 + }
62 + return null;
63 +}
64 +
65 +function formatAllowlist(dirs: string[]): string {
66 + if (dirs.length === 0) return ' (none configured \u2014 all local paths are blocked)';
67 + return dirs.map(d => ` - ${d}`).join('\n');
68 +}
69 +
70 +function buildHelpFooter(allowlist: string[]): string {
71 + return [
72 + '',
73 + 'Allowed upload directories (fileUploadDirs):',
74 + formatAllowlist(allowlist),
75 + '',
76 + 'Fix one of the following:',
77 + '',
78 + ' 1. Recommended \u2014 move the file under an allowed directory, or add your',
79 + ' directory to the allowlist:',
80 + ' new Composio({',
81 + " fileUploadDirs: ['/abs/path/to/uploads', '~/.composio/temp'],",
82 + ' })',
83 + ' Note: user-provided `fileUploadDirs` REPLACES the default',
84 + ' `~/.composio/temp`. Include it explicitly if you want staged uploads',
85 + ' to keep working.',
86 + '',
87 + ' 2. Pass the file by URL or as a File/Blob object instead of a filesystem',
88 + ' path. URLs and File objects are never path-checked.',
89 + '',
90 + ' 3. (Dangerous) Bypass the allowlist entirely by opting into automatic',
91 + ' file upload/download from any readable path:',
92 + ' new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true })',
93 + ' WARNING: This lets a prompt-injected or misbehaving tool read ANY',
94 + ' file the process can access. Only enable it in trusted, sandboxed',
95 + ' environments. The built-in sensitive-path denylist (.ssh, .aws,',
96 + ' .env, private SSH keys, etc.) still applies unless you also set',
97 + ' `sensitiveFileUploadProtection: false`.',
98 + ].join('\n');
99 +}
100 +
101 +/**
102 + * @throws {ComposioFileNotFoundError} when `filePath` does not exist on disk.
103 + * @throws {ComposioFileUploadPathNotAllowedError} when the resolved path is
104 + * outside every entry of `allowlist`.
105 + */
106 +export function assertPathInsideUploadDirs(filePath: string, allowlist: string[]): void {
107 + const attempted = filePath;
108 + const abs = path.resolve(filePath);
109 + const real = tryRealpath(abs);
110 +
111 + if (!real) {
112 + const cwd = process.cwd();
113 + const parent = path.dirname(abs);
114 + const parentExists = (() => {
115 + try {
116 + return fs.existsSync(parent);
117 + } catch {
118 + return false;
119 + }
120 + })();
121 +
122 + throw new ComposioFileNotFoundError(
123 + [
124 + `Refusing to auto-upload "${attempted}": the file does not exist on disk.`,
125 + '',
126 + `Path attempted: ${attempted}`,
127 + `Resolved to: ${abs}`,
128 + `Process cwd: ${cwd}`,
129 + `Parent exists: ${parentExists ? 'yes (' + parent + ')' : 'no (' + parent + ')'}`,
130 + '',
131 + 'Common causes:',
132 + ' - Typo in the filename passed to the tool.',
133 + ' - Relative path resolved against the wrong working directory',
134 + ' (relative paths use process.cwd() at the moment of upload).',
135 + ' - File was deleted between the tool being called and the upload starting.',
136 + '',
137 + buildHelpFooter(allowlist),
138 + ].join('\n'),
139 + { meta: { attempted, resolved: abs, cwd, allowlist } }
140 + );
141 + }
142 +
143 + if (allowlist.length === 0) {
144 + throw new ComposioFileUploadPathNotAllowedError(
145 + [
146 + `Refusing to auto-upload "${attempted}": no upload directories are configured.`,
147 + '',
148 + `Path attempted: ${attempted}`,
149 + `Resolved to: ${real}`,
150 + '',
151 + 'Automatic file upload during tool execution is locked down by default',
152 + 'to prevent a prompt-injected tool from exfiltrating server files',
153 + '(source code, .env, SSH keys, etc.).',
154 + buildHelpFooter(allowlist),
155 + ].join('\n'),
156 + { meta: { attempted, resolved: real, allowlist } }
157 + );
158 + }
159 +
160 + for (const dir of allowlist) {
161 + const realDir = tryRealpath(dir) ?? path.resolve(dir);
162 + if (isInsideDir(real, realDir)) {
163 + return;
164 + }
165 + }
166 +
167 + throw new ComposioFileUploadPathNotAllowedError(
168 + [
169 + `Refusing to auto-upload "${attempted}": resolved path is not inside any`,
170 + 'directory in the configured `fileUploadDirs` allowlist.',
171 + '',
172 + `Path attempted: ${attempted}`,
173 + `Resolved to: ${real}`,
174 + buildHelpFooter(allowlist),
175 + ].join('\n'),
176 + { meta: { attempted, resolved: real, allowlist } }
177 + );
178 +}
ts/packages/core/test/tools/fileModifiers.test.ts
+167 -10
@@ -41,7 +41,7 @@ describe('FileToolModifier', () => {
41 availableVersions: ['20251201_01'],
42 };
43
44 - const result = await fileToolModifier.modifyToolSchema('test-tool', 'test-toolkit', schema);
44 + const result = await fileToolModifier.modifyToolSchema(schema);
45 expect(result).toEqual(schema);
46 });
47
@@ -67,7 +67,7 @@ describe('FileToolModifier', () => {
67 },
68 };
69
70 - const result = await fileToolModifier.modifyToolSchema('test-tool', 'test-toolkit', schema);
70 + const result = await fileToolModifier.modifyToolSchema(schema);
71 expect(result.inputParameters?.properties?.file).toHaveProperty('format', 'path');
72 expect(result.inputParameters?.properties?.text).not.toHaveProperty('format');
73 });
@@ -102,7 +102,7 @@ describe('FileToolModifier', () => {
102 },
103 };
104
105 - const result = await fileToolModifier.modifyToolSchema('test-tool', 'test-toolkit', schema);
105 + const result = await fileToolModifier.modifyToolSchema(schema);
106 expect(result.inputParameters?.properties?.fileInput?.anyOf?.[0]).toHaveProperty(
107 'format',
108 'path'
@@ -145,7 +145,7 @@ describe('FileToolModifier', () => {
145 },
146 };
147
148 - const result = await fileToolModifier.modifyToolSchema('test-tool', 'test-toolkit', schema);
148 + const result = await fileToolModifier.modifyToolSchema(schema);
149 expect(result.inputParameters?.properties?.fileInput?.oneOf?.[0]).toHaveProperty(
150 'format',
151 'path'
@@ -185,7 +185,7 @@ describe('FileToolModifier', () => {
185 },
186 };
187
188 - const result = await fileToolModifier.modifyToolSchema('test-tool', 'test-toolkit', schema);
188 + const result = await fileToolModifier.modifyToolSchema(schema);
189 expect(result.inputParameters?.properties?.fileInput?.allOf?.[0]).toHaveProperty(
190 'format',
191 'path'
@@ -230,7 +230,7 @@ describe('FileToolModifier', () => {
230 },
231 };
232
233 - const result = await fileToolModifier.modifyToolSchema('test-tool', 'test-toolkit', schema);
233 + const result = await fileToolModifier.modifyToolSchema(schema);
234 expect(
235 result.inputParameters?.properties?.content?.anyOf?.[0]?.properties?.attachment
236 ).toHaveProperty('format', 'path');
@@ -268,7 +268,7 @@ describe('FileToolModifier', () => {
268 },
269 };
270
271 - const result = await fileToolModifier.modifyToolSchema('test-tool', 'test-toolkit', schema);
271 + const result = await fileToolModifier.modifyToolSchema(schema);
272 expect(result.inputParameters?.properties?.files?.items?.anyOf?.[0]).toHaveProperty(
273 'format',
274 'path'
@@ -371,6 +371,80 @@ describe('FileToolModifier', () => {
371 expect(result.arguments?.file).toEqual(mockFileData);
372 });
373
374 + it('should pass source="path" to beforeFileUpload for local filesystem paths', async () => {
375 + const mockFileData = {
376 + name: 'file.txt',
377 + mimetype: 'text/plain',
378 + s3key: 'uploads/file.txt',
379 + };
380 + vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockResolvedValue(mockFileData);
381 +
382 + const hook = vi.fn(async ({ path }) => path);
383 + const withHook = new FileToolModifier(mockClient, { beforeFileUpload: hook });
384 +
385 + await withHook.fileUploadModifier(mockTool, {
386 + toolSlug: 'test-tool',
387 + toolkitSlug: 'test-toolkit',
388 + params: { arguments: { file: '/path/to/a.txt' }, userId: 'u' },
389 + });
390 +
391 + expect(hook).toHaveBeenCalledWith(
392 + expect.objectContaining({ path: '/path/to/a.txt', source: 'path' })
393 + );
394 + });
395 +
396 + it('should pass source="url" to beforeFileUpload for http(s) URLs', async () => {
397 + const mockFileData = {
398 + name: 'file.txt',
399 + mimetype: 'text/plain',
400 + s3key: 'uploads/file.txt',
401 + };
402 + vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockResolvedValue(mockFileData);
403 +
404 + const hook = vi.fn(async ({ path }) => path);
405 + const withHook = new FileToolModifier(mockClient, { beforeFileUpload: hook });
406 +
407 + await withHook.fileUploadModifier(mockTool, {
408 + toolSlug: 'test-tool',
409 + toolkitSlug: 'test-toolkit',
410 + params: {
411 + arguments: { file: 'https://example.com/report.pdf' },
412 + userId: 'u',
413 + },
414 + });
415 +
416 + expect(hook).toHaveBeenCalledWith(
417 + expect.objectContaining({
418 + path: 'https://example.com/report.pdf',
419 + source: 'url',
420 + })
421 + );
422 + });
423 +
424 + it('should pass source="file" to beforeFileUpload for File objects', async () => {
425 + const mockFileData = {
426 + name: 'file.txt',
427 + mimetype: 'text/plain',
428 + s3key: 'uploads/file.txt',
429 + };
430 + vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockResolvedValue(mockFileData);
431 +
432 + const hook = vi.fn(async () => undefined as unknown as string);
433 + const withHook = new FileToolModifier(mockClient, { beforeFileUpload: hook });
434 +
435 + const fileObject = new File(['x'], 'uploaded.txt', { type: 'text/plain' });
436 + await withHook.fileUploadModifier(mockTool, {
437 + toolSlug: 'test-tool',
438 + toolkitSlug: 'test-toolkit',
439 + params: { arguments: { file: fileObject }, userId: 'u' },
440 + });
441 +
442 + // `path` is the File's name, not a filesystem path.
443 + expect(hook).toHaveBeenCalledWith(
444 + expect.objectContaining({ path: 'uploaded.txt', source: 'file' })
445 + );
446 + });
447 +
448 it('should throw ComposioFileUploadAbortedError when beforeFileUpload returns false', async () => {
449 const withHook = new FileToolModifier(mockClient, {
450 beforeFileUpload: async () => false,
@@ -668,6 +742,54 @@ describe('FileToolModifier', () => {
742 );
743 });
744
745 + it('uploads once when multiple oneOf variants are file_uploadable', async () => {
746 + // Regression: previously hydrateFiles iterated over every uploadable
747 + // variant in anyOf/oneOf/allOf and re-uploaded the same file once per
748 + // variant. With `oneOf` semantics this is doubly wrong (only one
749 + // variant matches at runtime). Match the Python SDK and short-circuit
750 + // on the first uploadable variant.
751 + const mockFileData = {
752 + name: 'file.txt',
753 + mimetype: 'text/plain',
754 + s3key: 'uploads/file.txt',
755 + };
756 + vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockResolvedValue(mockFileData);
757 +
758 + const toolWithTwoUploadableVariants: Tool = {
759 + slug: 'test-tool',
760 + name: 'Test Tool',
761 + description: 'A test tool',
762 + tags: ['test'],
763 + inputParameters: {
764 + type: 'object',
765 + properties: {
766 + fileInput: {
767 + oneOf: [
768 + { type: 'string', file_uploadable: true },
769 + { type: 'string', file_uploadable: true },
770 + ],
771 + },
772 + },
773 + },
774 + version: '20251201_01',
775 + availableVersions: ['20251201_01'],
776 + };
777 +
778 + const params = {
779 + arguments: { fileInput: '/path/to/file.txt' },
780 + userId: 'test-user',
781 + };
782 +
783 + const result = await fileToolModifier.fileUploadModifier(toolWithTwoUploadableVariants, {
784 + toolSlug: 'test-tool',
785 + toolkitSlug: 'test-toolkit',
786 + params,
787 + });
788 +
789 + expect(fileUtils.getFileDataAfterUploadingToS3).toHaveBeenCalledTimes(1);
790 + expect(result.arguments?.fileInput).toEqual(mockFileData);
791 + });
792 +
793 it('should not upload when value is null for anyOf with null variant', async () => {
794 const toolWithAnyOf: Tool = {
795 slug: 'test-tool',
@@ -1326,7 +1448,7 @@ describe('FileToolModifier', () => {
1448 });
1449 });
1450
1329 -describe('Tools with autoUploadDownloadFiles', () => {
1451 +describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
1452 const context = createTestContext();
1453 setupTest(context);
1454
@@ -1410,11 +1532,11 @@ describe('Tools with autoUploadDownloadFiles', () => {
1532 availableVersions: ['20251201_01'],
1533 };
1534
1413 - describe('when autoUploadDownloadFiles is false', () => {
1535 + describe('when dangerouslyAllowAutoUploadDownloadFiles is false', () => {
1536 beforeEach(async () => {
1537 context.tools = new Tools(mockClient as unknown as ComposioClient, {
1538 provider: context.mockProvider,
1417 - autoUploadDownloadFiles: false,
1539 + dangerouslyAllowAutoUploadDownloadFiles: false,
1540 });
1541
1542 // Mock the tool execution
@@ -1447,6 +1569,12 @@ describe('Tools with autoUploadDownloadFiles', () => {
1569 });
1570
1571 it('should not modify tool schema for file upload', async () => {
1572 + // The collapsed `{ type: 'string', format: 'path' }` shape is a promise
1573 + // that the SDK will stage local paths for the caller. That promise is
1574 + // only true when auto-upload is on, so we leave the raw shape
1575 + // untouched when the flag is off — callers are expected to pre-stage
1576 + // via `composio.files.upload()`. Runtime behavior is documented by
1577 + // the warning emitted from `applyBeforeExecuteModifiers`.
1578 const result = await context.tools.getRawComposioTools({ tools: ['COMPOSIO_TOOL'] });
1579 expect(result[0].inputParameters?.properties?.file).not.toHaveProperty('format');
1580 expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
@@ -1481,6 +1609,35 @@ describe('Tools with autoUploadDownloadFiles', () => {
1609 });
1610 });
1611
1612 + it('warns once per tool when auto-upload is off and the tool has a file-uploadable input', async () => {
1613 + const warnSpy = vi.spyOn((await import('../../src/utils/logger')).default, 'warn');
1614 + warnSpy.mockImplementation(() => {}); // silence the log in test output
1615 +
1616 + vi.spyOn(context.tools, 'getRawComposioToolBySlug').mockResolvedValue(mockToolWithFileUpload);
1617 +
1618 + // First call emits the warning.
1619 + await context.tools.execute('COMPOSIO_TOOL', {
1620 + arguments: { file: '/path/to/file.txt' },
1621 + userId: 'u',
1622 + dangerouslySkipVersionCheck: true,
1623 + });
1624 + expect(warnSpy).toHaveBeenCalledTimes(1);
1625 + const msg = String(warnSpy.mock.calls[0]?.[0] ?? '');
1626 + expect(msg).toContain('COMPOSIO_TOOL');
1627 + expect(msg).toContain('dangerouslyAllowAutoUploadDownloadFiles');
1628 + expect(msg).toContain('composio.files.upload');
1629 +
1630 + // Repeated executions of the same tool do NOT re-warn.
1631 + await context.tools.execute('COMPOSIO_TOOL', {
1632 + arguments: { file: '/path/to/file.txt' },
1633 + userId: 'u',
1634 + dangerouslySkipVersionCheck: true,
1635 + });
1636 + expect(warnSpy).toHaveBeenCalledTimes(1);
1637 +
1638 + warnSpy.mockRestore();
1639 + });
1640 +
1641 it('should not download files from execution results', async () => {
1642 // Mock getRawComposioToolBySlug for this test
1643 vi.spyOn(context.tools, 'getRawComposioToolBySlug').mockResolvedValueOnce(
ts/packages/core/test/tools/fileUploadMatrix.test.ts new
+281
@@ -0,0 +1,281 @@
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 +});
ts/packages/core/test/utils/fileUtils.test.ts
+52
@@ -335,6 +335,58 @@ describe('fileUtils', () => {
335 })
336 ).rejects.toThrow('Failed to download file: Not Found');
337 });
338 +
339 + it('synthesizes the filename server-side and ignores the s3Url path', async () => {
340 + // Regression: lock the invariant that the saved filename comes from
341 + // (toolSlug, mimeType, timestamp, random id) — never from the s3Url.
342 + // If a future change started reflecting the s3Url path or query into
343 + // the local filename, an attacker-controlled CDN response could write
344 + // outside the download dir or stomp on existing files.
345 + mockFetch.mockResolvedValue({
346 + ok: true,
347 + arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
348 + });
349 +
350 + const result = await downloadFileFromS3({
351 + toolSlug: 'github',
352 + // The URL path contains traversal-looking segments and a totally
353 + // different "filename"; none of this should leak into result.name.
354 + s3Url:
355 + 'https://s3.example.com/../../../etc/passwd?response-content-disposition=attachment%3Bfilename%3Devil.sh',
356 + mimeType: 'text/plain',
357 + });
358 +
359 + expect(result.name).toBe('github_1640995200000abc12345.txt');
360 + expect(result.name).not.toContain('..');
361 + expect(result.name).not.toContain('/');
362 + expect(result.name).not.toContain('passwd');
363 + expect(result.name).not.toContain('evil');
364 + });
365 +
366 + it('strips path components from a path-laden toolSlug before saving', async () => {
367 + // Regression: the prefix is `${toolSlug}_`, so a slug containing `/`
368 + // could in theory smuggle path components into the saved filename.
369 + // `saveFile` defends against that by running the assembled filename
370 + // through `path.basename` before joining with the download dir.
371 + mockFetch.mockResolvedValue({
372 + ok: true,
373 + arrayBuffer: () => Promise.resolve(new ArrayBuffer(10)),
374 + });
375 +
376 + const result = await downloadFileFromS3({
377 + toolSlug: 'AAA/../etc/passwd',
378 + s3Url: 'https://s3.example.com/file.bin',
379 + mimeType: 'text/plain',
380 + });
381 +
382 + // `result.name` is the pre-basename string (raw composed name); the
383 + // actual on-disk path goes through `path.basename`. We assert that
384 + // the on-disk path stays under the download dir by checking the
385 + // returned filePath.
386 + expect(result.filePath).toBeDefined();
387 + expect(path.dirname(result.filePath as string)).not.toContain('etc');
388 + expect(path.basename(result.filePath as string)).toBe('passwd_1640995200000abc12345.txt');
389 + });
390 });
391
392 describe('File object handling', () => {
ts/packages/core/test/utils/uploadDirAllowlist.test.ts new
+148
@@ -0,0 +1,148 @@
1 +import { describe, it, expect } from 'vitest';
2 +import * as path from 'node:path';
3 +import * as os from 'node:os';
4 +import { mkdtempSync, writeFileSync, symlinkSync, rmSync, mkdirSync } from 'node:fs';
5 +import { assertPathInsideUploadDirs } from '../../src/utils/uploadDirAllowlist.node';
6 +import { resolveEffectiveUploadAllowlist, getDefaultUploadDir } from '../../src/utils/fileDirs';
7 +import {
8 + ComposioFileNotFoundError,
9 + ComposioFileUploadPathNotAllowedError,
10 +} from '../../src/errors/FileModifierErrors';
11 +
12 +describe('resolveEffectiveUploadAllowlist', () => {
13 + it('returns the default [<home>/.composio/temp] when userDirs is undefined', () => {
14 + const out = resolveEffectiveUploadAllowlist(undefined);
15 + const def = getDefaultUploadDir();
16 + expect(def).not.toBeNull();
17 + expect(out).toEqual([def]);
18 + });
19 +
20 + it('returns [] (fail-closed) when user passes []', () => {
21 + expect(resolveEffectiveUploadAllowlist([])).toEqual([]);
22 + });
23 +
24 + it('returns [] when user passes `false` (explicit "no local paths")', () => {
25 + expect(resolveEffectiveUploadAllowlist(false)).toEqual([]);
26 + });
27 +
28 + it('replaces the default when user passes explicit dirs', () => {
29 + const dirs = ['/tmp/one', '/tmp/two'];
30 + const out = resolveEffectiveUploadAllowlist(dirs);
31 + expect(out).toEqual(dirs.map(d => path.resolve(d)));
32 + });
33 +
34 + it('expands leading ~ in entries', () => {
35 + const out = resolveEffectiveUploadAllowlist(['~/foo']);
36 + expect(out[0]).toBe(path.resolve(os.homedir(), 'foo'));
37 + });
38 +});
39 +
40 +describe('assertPathInsideUploadDirs', () => {
41 + const makeTempRoot = () => mkdtempSync(path.join(os.tmpdir(), 'composio-allowlist-'));
42 +
43 + it('accepts a file inside an allowed directory', () => {
44 + const root = makeTempRoot();
45 + try {
46 + const file = path.join(root, 'hello.txt');
47 + writeFileSync(file, 'hi');
48 + expect(() => assertPathInsideUploadDirs(file, [root])).not.toThrow();
49 + } finally {
50 + rmSync(root, { recursive: true, force: true });
51 + }
52 + });
53 +
54 + it('throws ComposioFileUploadPathNotAllowedError when path is outside all allowed dirs', () => {
55 + const root = makeTempRoot();
56 + const other = makeTempRoot();
57 + try {
58 + const file = path.join(root, 'hello.txt');
59 + writeFileSync(file, 'hi');
60 + expect(() => assertPathInsideUploadDirs(file, [other])).toThrow(
61 + ComposioFileUploadPathNotAllowedError
62 + );
63 + } finally {
64 + rmSync(root, { recursive: true, force: true });
65 + rmSync(other, { recursive: true, force: true });
66 + }
67 + });
68 +
69 + it('enforces component-boundary matching (does not treat sibling prefix as inside)', () => {
70 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-boundary-'));
71 + try {
72 + const allowed = path.join(root, 'uploads');
73 + const sibling = path.join(root, 'uploads-not-allowed');
74 + mkdirSync(allowed);
75 + mkdirSync(sibling);
76 + const file = path.join(sibling, 'leak.txt');
77 + writeFileSync(file, 'nope');
78 + expect(() => assertPathInsideUploadDirs(file, [allowed])).toThrow(
79 + ComposioFileUploadPathNotAllowedError
80 + );
81 + } finally {
82 + rmSync(root, { recursive: true, force: true });
83 + }
84 + });
85 +
86 + it('rejects paths that escape via symlink (realpath is enforced)', () => {
87 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-symesc-'));
88 + try {
89 + const allowed = path.join(root, 'allowed');
90 + const outside = path.join(root, 'outside');
91 + mkdirSync(allowed);
92 + mkdirSync(outside);
93 + const target = path.join(outside, 'secret.txt');
94 + writeFileSync(target, 'x');
95 + const link = path.join(allowed, 'innocent.txt');
96 + symlinkSync(target, link);
97 + expect(() => assertPathInsideUploadDirs(link, [allowed])).toThrow(
98 + ComposioFileUploadPathNotAllowedError
99 + );
100 + } finally {
101 + rmSync(root, { recursive: true, force: true });
102 + }
103 + });
104 +
105 + it('throws ComposioFileNotFoundError when the file does not exist', () => {
106 + const root = makeTempRoot();
107 + try {
108 + const missing = path.join(root, 'does-not-exist.txt');
109 + expect(() => assertPathInsideUploadDirs(missing, [root])).toThrow(ComposioFileNotFoundError);
110 + } finally {
111 + rmSync(root, { recursive: true, force: true });
112 + }
113 + });
114 +
115 + it('throws ComposioFileUploadPathNotAllowedError with empty allowlist (fail-closed)', () => {
116 + const root = makeTempRoot();
117 + try {
118 + const file = path.join(root, 'a.txt');
119 + writeFileSync(file, 'x');
120 + expect(() => assertPathInsideUploadDirs(file, [])).toThrow(
121 + ComposioFileUploadPathNotAllowedError
122 + );
123 + } finally {
124 + rmSync(root, { recursive: true, force: true });
125 + }
126 + });
127 +
128 + it('includes actionable guidance and the resolved path in the error message', () => {
129 + const root = makeTempRoot();
130 + try {
131 + const file = path.join(root, 'a.txt');
132 + writeFileSync(file, 'x');
133 + try {
134 + assertPathInsideUploadDirs(file, ['/tmp/definitely-not-here-xyz']);
135 + throw new Error('expected to throw');
136 + } catch (err) {
137 + expect(err).toBeInstanceOf(ComposioFileUploadPathNotAllowedError);
138 + const message = (err as Error).message;
139 + expect(message).toContain('fileUploadDirs');
140 + expect(message).toContain('dangerouslyAllowAutoUploadDownloadFiles');
141 + expect(message).toContain('~/.composio/temp');
142 + expect(message).toContain(file);
143 + }
144 + } finally {
145 + rmSync(root, { recursive: true, force: true });
146 + }
147 + });
148 +});