@devries-cameron20 / composio Mirror · read-only / commits / 27ed0c9bd
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, 23:30 UTC

security(core): sensitive path blocklist + beforeFileUpload hook (patch) (#3262)

## Summary Security-hardening for automatic file upload in `@composio/core` (patch release per changeset). ### Changes - **Default denylist** for local paths before auto-upload / `files.upload`: blocks common credential directories (e.g. `.ssh`, `.aws`) and credential-like filenames (e.g. `.env`, default SSH private keys). Resolves symlinks when the path exists. - **Config:** `sensitiveFileUploadProtection`, `fileUploadPathDenySegments` on `Composio`. - **`beforeFileUpload`** hook (e.g. with `composio.tools.get` / `tools.execute`): rewrite path, return `false` to abort, or throw. - **Errors:** `ComposioSensitiveFilePathBlockedError`, `ComposioFileUploadAbortedError`; file modifier errors exported from `@composio/core` errors entry. - **Changeset:** patch bump for `@composio/core`. ### Notes - URLs and `File` blobs are not subject to the path denylist (unchanged). - Opt out of path checks only if required: `sensitiveFileUploadProtection: false`. ### Tests - `pnpm test` in `ts/packages/core` (799 tests) passed locally before commit. Made with [Cursor](https://cursor.com)

Musthaq Ahamad committed Apr 23, 2026 at 18:42 UTC 27ed0c9bd6f979bd122c6548ee5e5a8233f66d4e
63 files changed +1533 -118
.changeset/security-file-upload-hardening.md new
+7
@@ -0,0 +1,7 @@
1 +---
2 +"@composio/core": patch
3 +---
4 +
5 +**Security:** Harden automatic file uploads by default-blocking local paths under common credential locations (e.g. `.ssh`, `.aws`) and credential-like filenames (e.g. `.env`, default SSH private key names). URLs and `File` objects are unchanged. Opt out with `sensitiveFileUploadProtection: false` only if needed; extend the denylist with `fileUploadPathDenySegments`.
6 +
7 +Adds an optional `beforeFileUpload` hook (e.g. on `composio.tools.get`) to rewrite paths, return `false` to abort, or throw. New errors: `ComposioSensitiveFilePathBlockedError`, `ComposioFileUploadAbortedError`.
docs/content/changelog/04-23-26-file-upload-security.mdx new
+143
@@ -0,0 +1,143 @@
1 +---
2 +title: 'SDK file upload hardening: sensitive path blocking and upload hooks'
3 +description: 'TypeScript and Python SDKs now block automatic uploads from common credential locations by default, support extra denylist segments, and offer a before-upload hook. New error types when a path is blocked or a hook aborts the upload.'
4 +date: '2026-04-23'
5 +---
6 +
7 +The Composio SDKs add defense-in-depth for **automatic file uploads** (when a tool input is marked `file_uploadable` and the SDK reads a local path and sends the file to Composio storage). The goal is to reduce the risk of agent or app code accidentally exfiltrating secrets, SSH keys, or project env files that sit under well-known paths on disk.
8 +
9 +**URLs and `File` objects are not subject to the path-based denylist** in the same way as string paths; the checks apply to resolved local filesystem paths used for auto-upload and the programmatic upload helpers that accept paths.
10 +
11 +### SDK versions
12 +
13 +| SDK | Version (includes this behavior) |
14 +| ---------- | --------------------------------- |
15 +| TypeScript | `@composio/core` v0.6.11 or later |
16 +| Python | `composio` v0.11.6 or later |
17 +
18 +### What changed
19 +
20 +- **Default sensitive path protection** — Before reading and uploading, the SDK checks the resolved local path against a built-in list of path segments (for example `.ssh`, `.aws`, `.claude`, `.kube`) and file-name patterns (for example `.env`, default SSH private key names, `credentials`). If the path matches, the upload is refused unless you change configuration.
21 +- **Extra denylist segments** — You can add path component names to merge with the built-in list (for example a proprietary secrets directory name).
22 +- **`beforeFileUpload` / `before_file_upload` hook** — Optional hook for each file upload: return a different path, return `false` to abort, or throw. TypeScript: pass `beforeFileUpload` on the third argument to `tools.execute`. Python: use [`@before_file_upload`](/reference/sdk-reference/python/index#before_file_upload) in the `modifiers` list (same as other Python modifiers), not a separate keyword. Use this to enforce app-specific policies, audit logging, or copy-on-write to a safe temp file before upload. See [Before file upload (Python)](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers#before-file-upload-python).
23 +- **New errors** — `ComposioSensitiveFilePathBlockedError` / `SensitiveFilePathBlockedError` when a path is blocked, and `ComposioFileUploadAbortedError` / `FileUploadAbortedError` when the hook returns `false` or a hook throws in an aborting way.
24 +- **Python: modifier order** — `substitute_file_uploads` runs before `before_execute` modifiers, matching TypeScript behavior (including Tool Router `execute_meta`).
25 +
26 +### Examples
27 +
28 +#### Configure the client (defaults + extra denylist segments)
29 +
30 +Keep the built-in blocklist enabled and add path **component** names (anywhere in the resolved path) that your app treats as secret:
31 +
32 +<Tabs groupId="language" items={['TypeScript', 'Python']} persist>
33 +<Tab value="TypeScript">
34 +```typescript
35 +// @noErrors
36 +import { Composio } from '@composio/core';
37 +
38 +const composio = new Composio({
39 + apiKey: process.env.COMPOSIO_API_KEY!,
40 + sensitiveFileUploadProtection: true,
41 + fileUploadPathDenySegments: ['company-secrets', 'private-keys'],
42 +});
43 +```
44 +</Tab>
45 +<Tab value="Python">
46 +```python
47 +from composio import Composio
48 +
49 +composio = Composio(
50 + api_key="your_composio_key",
51 + sensitive_file_upload_protection=True,
52 + file_upload_path_deny_segments=("company-secrets", "private-keys"),
53 +)
54 +```
55 +</Tab>
56 +</Tabs>
57 +
58 +#### Run a hook before each automatic file read
59 +
60 +Return a new path, return `false` / `False` to abort, or throw. TypeScript passes `beforeFileUpload` in the **third** argument to `tools.execute`. In Python, use [`@before_file_upload`](/reference/sdk-reference/python/index#before_file_upload) in `modifiers`:
61 +
62 +<Tabs groupId="language" items={['TypeScript', 'Python']} persist>
63 +<Tab value="TypeScript">
64 +```typescript
65 +// @noErrors
66 +import { Composio, type beforeFileUploadModifier } from '@composio/core';
67 +import path from 'node:path';
68 +
69 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY! });
70 +
71 +const beforeFileUpload: beforeFileUploadModifier = async ctx => {
72 + // e.g. log, rewrite path, or return false to block
73 + return ctx.path;
74 +};
75 +
76 +await composio.tools.execute(
77 + 'GOOGLEDRIVE_UPLOAD_FILE',
78 + {
79 + userId: 'user-123',
80 + arguments: { file_to_upload: path.join(__dirname, 'document.pdf') },
81 + dangerouslySkipVersionCheck: true,
82 + },
83 + { beforeFileUpload },
84 +);
85 +```
86 +</Tab>
87 +<Tab value="Python">
88 +```python
89 +import os
90 +
91 +from composio import Composio, before_file_upload
92 +
93 +
94 +@before_file_upload(tools=["GOOGLEDRIVE_UPLOAD_FILE"])
95 +def before_upload(path: str, tool: str, toolkit: str) -> "str | bool":
96 + return path
97 +
98 +
99 +composio = Composio()
100 +
101 +composio.tools.execute(
102 + "GOOGLEDRIVE_UPLOAD_FILE",
103 + {"file_to_upload": os.path.join(os.getcwd(), "document.pdf")},
104 + user_id="user-123",
105 + modifiers=[before_upload],
106 +)
107 +```
108 +</Tab>
109 +</Tabs>
110 +
111 +### Opting out
112 +
113 +Set **`sensitiveFileUploadProtection: false`** (TypeScript) or **`sensitive_file_upload_protection=False`** (Python) only if you have a clear reason and accept the security tradeoff. Prefer copying files to a non-sensitive path or using the hook to gate uploads.
114 +
115 +<Tabs groupId="language" items={['TypeScript', 'Python']} persist>
116 +<Tab value="TypeScript">
117 +```typescript
118 +// @noErrors
119 +import { Composio } from '@composio/core';
120 +
121 +const composio = new Composio({
122 + apiKey: process.env.COMPOSIO_API_KEY!,
123 + sensitiveFileUploadProtection: false,
124 +});
125 +```
126 +</Tab>
127 +<Tab value="Python">
128 +```python
129 +from composio import Composio
130 +
131 +composio = Composio(
132 + api_key="your_composio_key",
133 + sensitive_file_upload_protection=False,
134 +)
135 +```
136 +</Tab>
137 +</Tabs>
138 +
139 +### Where to read more
140 +
141 +- [Executing tools: automatic file handling and security options](/docs/tools-direct/executing-tools#security-for-local-file-paths) — configuration and code patterns.
142 +- [TypeScript `Composio` client](/reference/sdk-reference/typescript/composio#file-upload-security) — related constructor options in the reference.
143 +- TypeScript SDK (repository): `ts/docs/advanced/auto-upload-download.md` — extended guide with error types and edge cases.
docs/content/docs/glossary.mdx
+1 -1
@@ -60,7 +60,7 @@ A set of tools included in every session, including `COMPOSIO_SEARCH_TOOLS`, `CO
60 </GlossaryTerm>
61
62 <GlossaryTerm name="Modifiers">
63 -Middleware that transforms tool behavior: [schema modifiers](/docs/tools-direct/modify-tool-behavior/schema-modifiers) change a tool's schema before the agent sees it, [before-execution modifiers](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers) modify arguments before a tool runs, [after-execution modifiers](/docs/tools-direct/modify-tool-behavior/after-execution-modifiers) transform the result.
63 +Middleware that transforms tool behavior: [schema modifiers](/docs/tools-direct/modify-tool-behavior/schema-modifiers) change a tool's schema before the agent sees it, [before-execution modifiers](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers) modify arguments before a tool runs, [after-execution modifiers](/docs/tools-direct/modify-tool-behavior/after-execution-modifiers) transform the result. In Python, [`@before_file_upload`](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers#before-file-upload-python) intercepts local paths for `file_uploadable` parameters before read/upload.
64 </GlossaryTerm>
65
66 <GlossaryTerm name="Native Tools">
docs/content/docs/tools-direct/executing-tools.mdx
+83
@@ -385,6 +385,89 @@ console.log(result);
385 </Tab>
386 </Tabs>
387
388 +## Security for local file paths
389 +
390 +Automatic upload reads local paths (or uses them in `files.upload`) and sends file content to Composio storage. To reduce the chance of **accidentally uploading secrets** (SSH keys, cloud credentials, `.env` files, or assistant project folders), the SDK checks resolved paths against a **default denylist** of path segments and file-name patterns. **HTTP/HTTPS URLs and `File` objects are not matched like local path strings**; only local string paths go through this check.
391 +
392 +<Callout type="warn">
393 +Disabling protection or wiring a hook that always approves paths can allow **exfiltration of sensitive files** if an LLM or malicious input points at credential locations. Prefer keeping protection on, adding [`fileUploadPathDenySegments`](/reference/sdk-reference/typescript/composio#file-upload-security) (TypeScript) / `file_upload_path_deny_segments` (Python) for your own secret directories, and using a [`beforeFileUpload`](/reference/sdk-reference/typescript/composio#file-upload-security) / `before_file_upload` hook for auditing or strict allowlists. On Python, you can use the `@before_file_upload` decorator with `modifiers=[...]` the same way as `@before_execute` — see [Before file upload (Python)](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers#before-file-upload-python) on the before-execution modifiers page.
394 +</Callout>
395 +
396 +**Constructor options (defaults protect sensitive locations):**
397 +
398 +<Tabs groupId="language" items={['TypeScript', 'Python']} persist>
399 + <Tab value="TypeScript">
400 +```typescript
401 +// @errors: 2353
402 +import { Composio } from '@composio/core';
403 +
404 +const composio = new Composio({
405 + apiKey: process.env.COMPOSIO_API_KEY!,
406 + // default true — block paths under built-in segments (e.g. .ssh, .aws) and risky basenames
407 + sensitiveFileUploadProtection: true,
408 + // optional: extra path *components* anywhere in the resolved path, merged with the built-in list
409 + fileUploadPathDenySegments: ['internal-only-secrets'],
410 +});
411 +```
412 + </Tab>
413 + <Tab value="Python">
414 +```python
415 +from composio import Composio
416 +
417 +composio = Composio(
418 + api_key="your_composio_key",
419 + sensitive_file_upload_protection=True,
420 + file_upload_path_deny_segments=("internal-only-secrets",),
421 +)
422 +```
423 + </Tab>
424 +</Tabs>
425 +
426 +**Per-execution upload hook** (run after the path is chosen but before read/upload; return a new path, `false` to abort, or throw). TypeScript passes `beforeFileUpload` on the **third** argument to `tools.execute`. In Python, add **`@before_file_upload`** functions to the `modifiers` list for `get` / `execute` (see [Before file upload (Python)](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers#before-file-upload-python)).
427 +
428 +<Tabs groupId="language" items={['TypeScript', 'Python']} persist>
429 + <Tab value="TypeScript">
430 +```typescript
431 +// @noErrors
432 +import { Composio, type beforeFileUploadModifier } from '@composio/core';
433 +import path from 'node:path';
434 +const composio = new Composio({ apiKey: 'your_api_key' });
435 +const beforeFileUpload: beforeFileUploadModifier = async ctx => ctx.path;
436 +// ---cut---
437 +await composio.tools.execute(
438 + 'GOOGLEDRIVE_UPLOAD_FILE',
439 + {
440 + userId: 'user-4235***',
441 + arguments: { file_to_upload: path.join(__dirname, 'document.pdf') },
442 + dangerouslySkipVersionCheck: true,
443 + },
444 + { beforeFileUpload }
445 +);
446 +```
447 + </Tab>
448 + <Tab value="Python">
449 +```python
450 +import os
451 +from composio import Composio, before_file_upload
452 +
453 +@before_file_upload(tools=["GOOGLEDRIVE_UPLOAD_FILE"])
454 +def audit_path(path: str, tool: str, toolkit: str) -> str | bool:
455 + return path
456 +
457 +composio = Composio()
458 +
459 +composio.tools.execute(
460 + "GOOGLEDRIVE_UPLOAD_FILE",
461 + {"file_to_upload": os.path.join(os.getcwd(), "document.pdf")},
462 + user_id="user-1235***",
463 + modifiers=[audit_path],
464 +)
465 +```
466 + </Tab>
467 +</Tabs>
468 +
469 +**Errors:** `ComposioSensitiveFilePathBlockedError` / `SensitiveFilePathBlockedError` when a path is blocked; `ComposioFileUploadAbortedError` / `FileUploadAbortedError` when the hook returns `false` (or equivalent abort).
470 +
471 ### Disabling Auto File Handling
472
473 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`:
docs/content/docs/tools-direct/modify-tool-behavior/before-execution-modifiers.mdx
+26
@@ -178,6 +178,32 @@ const agenticTools = await composio.tools.get(
178 </Tab>
179 </Tabs>
180
181 +## Before file upload (Python)
182 +
183 +For tools with `file_uploadable` parameters, the SDK can read a local path and upload the file before calling the Composio API. To audit, rewrite, or block those paths, use the [`@before_file_upload`](/reference/sdk-reference/python/index#before_file_upload) decorator and pass the decorated callables in `modifiers` to `tools.get`, `tools.execute`, or a tool router session’s `tools(modifiers=...)`.
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 +```python
188 +from composio import Composio, before_file_upload
189 +
190 +@before_file_upload(tools=["GOOGLEDRIVE_UPLOAD_FILE"])
191 +def audit_path(path: str, tool: str, toolkit: str) -> str | bool:
192 + # return a new path string, or False to abort the upload
193 + return path
194 +
195 +composio = Composio()
196 +composio.tools.execute(
197 + "GOOGLEDRIVE_UPLOAD_FILE",
198 + {"file_to_upload": "/path/to/document.pdf"},
199 + user_id="user_123",
200 + modifiers=[audit_path],
201 +)
202 +```
203 +
204 +- **Composition:** `before_file_upload`-type modifiers in the `modifiers` list are applied in **list order** (after filtering by each modifier’s `tools` / `toolkits` scope). Chaining works like a pipeline: each hook receives the path produced by the previous one.
205 +- **Relative to `before_execute`:** automatic file substitution runs **before** `before_execute` modifiers, matching TypeScript behavior (including tool router `execute_meta`).
206 +
207 ## What to read next
208
209 <Cards>
docs/content/reference/sdk-reference/python/index.mdx
+12
@@ -73,6 +73,18 @@ def my_modifier(...):
73 ...
74 ```
75
76 +### before_file_upload
77 +
78 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L236)
79 +
80 +```python
81 +@before_file_upload(modifier: BeforeFileUploadCallable | None = ..., tools: List[str | None] = ..., toolkits: List[str | None] = ...)
82 +def my_modifier(path: str, tool: str, toolkit: str) -> str | bool:
83 + ...
84 +```
85 +
86 +Builds a [Modifier](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py) for the file-upload hook. See [Before file upload (Python)](/docs/tools-direct/modify-tool-behavior/before-execution-modifiers#before-file-upload-python) for usage and examples.
87 +
88 ### schema_modifier
89
90 [View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L222)
docs/content/reference/sdk-reference/typescript/composio.mdx
+15
@@ -177,3 +177,18 @@ getConfig(): ComposioConfig
177 `ComposioConfig` — The configuration SDK is initialized with
178
179 ---
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)).
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 +
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.
191 +
192 +**Related errors:** `ComposioSensitiveFilePathBlockedError`, `ComposioFileUploadAbortedError` (from `@composio/core`).
193 +
194 +---
python/composio/__init__.py
+2
@@ -8,6 +8,7 @@ from .core.models.tool_router_session_files import RemoteFile
8 from .core.models.tools import (
9 after_execute,
10 before_execute,
11 + before_file_upload,
12 schema_modifier,
13 )
14 from .core.models.webhook_events import (
@@ -43,6 +44,7 @@ __all__ = (
44 "WebhookEventType",
45 "after_execute",
46 "before_execute",
47 + "before_file_upload",
48 "is_connection_expired_event",
49 "schema_modifier",
50 "__version__",
python/composio/core/models/_files.py
+78 -5
@@ -18,10 +18,14 @@ from composio.client.types import Tool
18 from composio.exceptions import (
19 ErrorDownloadingFile,
20 ErrorUploadingFile,
21 + FileUploadAbortedError,
22 ResponseTooLargeError,
23 SDKFileNotFoundError,
24 )
25 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.logging import WithLogger
30
31 if t.TYPE_CHECKING:
@@ -416,6 +420,12 @@ class FileUploadable(BaseModel):
420 file: t.Union[str, Path],
421 tool: str,
422 toolkit: str,
423 + *,
424 + sensitive_file_upload_protection: bool = True,
425 + 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,
429 ) -> te.Self:
430 """Create a FileUploadable from a local file path or public URL.
431
@@ -427,14 +437,44 @@ class FileUploadable(BaseModel):
437 :param file: Local file path or public URL
438 :param tool: The tool slug
439 :param toolkit: The toolkit slug
440 + :param sensitive_file_upload_protection: When True, block paths on the built-in denylist.
441 + :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.
443 :return: FileUploadable instance with S3 key
444 """
445 + file_str = str(file) if isinstance(file, Path) else file
446 +
447 # Check if it's a URL
433 - if isinstance(file, str) and _is_url(file):
434 - return cls.from_url(client=client, url=file, tool=tool, toolkit=toolkit)
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 +
460 + path_in = file_str
461 + if before_file_upload is not None:
462 + out = before_file_upload(path_in, tool, toolkit)
463 + if out is False:
464 + raise FileUploadAbortedError(
465 + "File upload was aborted because before_file_upload returned False."
466 + )
467 + if isinstance(out, str):
468 + path_in = out
469 +
470 + assert_safe_local_file_upload_path(
471 + path_in,
472 + enabled=sensitive_file_upload_protection,
473 + additional_deny_segments=file_upload_path_deny_segments,
474 + )
475
476 # Handle as local file path
437 - file = Path(file)
477 + file = Path(path_in)
478 if not file.exists():
479 raise SDKFileNotFoundError(
480 f"File not found: {file}. Please provide a valid file path."
@@ -487,11 +527,23 @@ class FileDownloadable(BaseModel):
527 return outfile
528
529
530 +BeforeFileUpload = t.Callable[[str, str, str], t.Union[str, bool]]
531 +
532 +
533 class FileHelper(WithLogger):
491 - def __init__(self, client: HttpClient, outdir: t.Optional[str] = None):
534 + def __init__(
535 + self,
536 + client: HttpClient,
537 + outdir: t.Optional[str] = None,
538 + *,
539 + sensitive_file_upload_protection: bool = True,
540 + file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,
541 + ) -> None:
542 super().__init__()
543 self._client = client
544 self._outdir = Path(outdir or LOCAL_OUTPUT_FILE_DIRECTORY)
545 + self._sensitive_file_upload_protection = sensitive_file_upload_protection
546 + self._file_upload_path_deny_segments = file_upload_path_deny_segments
547
548 def _has_file_property(
549 self, schema: t.Dict, property_name: str = "file_uploadable"
@@ -691,6 +743,8 @@ class FileHelper(WithLogger):
743 tool: Tool,
744 schema: t.Dict,
745 request: t.Dict,
746 + *,
747 + before_file_upload: t.Optional[BeforeFileUpload] = None,
748 ) -> t.Dict:
749 if "properties" not in schema:
750 return request
@@ -714,6 +768,9 @@ class FileHelper(WithLogger):
768 file=request[_param],
769 tool=tool.slug,
770 toolkit=tool.toolkit.slug,
771 + sensitive_file_upload_protection=self._sensitive_file_upload_protection,
772 + file_upload_path_deny_segments=self._file_upload_path_deny_segments,
773 + before_file_upload=before_file_upload,
774 ).model_dump()
775 continue
776
@@ -731,6 +788,9 @@ class FileHelper(WithLogger):
788 file=request[_param],
789 tool=tool.slug,
790 toolkit=tool.toolkit.slug,
791 + sensitive_file_upload_protection=self._sensitive_file_upload_protection,
792 + file_upload_path_deny_segments=self._file_upload_path_deny_segments,
793 + before_file_upload=before_file_upload,
794 ).model_dump()
795 continue
796
@@ -743,6 +803,7 @@ class FileHelper(WithLogger):
803 schema=uploadable_variant,
804 request=request[_param],
805 tool=tool,
806 + before_file_upload=before_file_upload,
807 )
808 continue
809
@@ -755,6 +816,7 @@ class FileHelper(WithLogger):
816 schema=param_schema,
817 request=request[_param],
818 tool=tool,
819 + before_file_upload=before_file_upload,
820 )
821 continue
822
@@ -777,6 +839,9 @@ class FileHelper(WithLogger):
839 file=item,
840 tool=tool.slug,
841 toolkit=tool.toolkit.slug,
842 + sensitive_file_upload_protection=self._sensitive_file_upload_protection,
843 + file_upload_path_deny_segments=self._file_upload_path_deny_segments,
844 + before_file_upload=before_file_upload,
845 ).model_dump()
846 )
847 elif isinstance(item, dict):
@@ -785,6 +850,7 @@ class FileHelper(WithLogger):
850 schema=items_schema,
851 request=item,
852 tool=tool,
853 + before_file_upload=before_file_upload,
854 )
855 )
856 else:
@@ -795,11 +861,18 @@ class FileHelper(WithLogger):
861
862 return request
863
798 - def substitute_file_uploads(self, tool: Tool, request: t.Dict) -> t.Dict:
864 + def substitute_file_uploads(
865 + self,
866 + tool: Tool,
867 + request: t.Dict,
868 + *,
869 + before_file_upload: t.Optional[BeforeFileUpload] = None,
870 + ) -> t.Dict:
871 return self._substitute_file_uploads_recursively(
872 tool=tool,
873 schema=tool.input_parameters,
874 request=request,
875 + before_file_upload=before_file_upload,
876 )
877
878 def _is_file_downloadable(self, schema: t.Dict) -> bool:
python/composio/core/models/_modifiers.py
+98
@@ -65,10 +65,22 @@ class SchemaModifier(t.Protocol):
65 ) -> "Tool": ...
66
67
68 +class BeforeFileUploadCallable(t.Protocol):
69 + """Called for each local file path before read/upload (``file_uploadable``)."""
70 +
71 + def __call__(
72 + self,
73 + path: str,
74 + tool: str,
75 + toolkit: str,
76 + ) -> t.Union[str, bool]: ...
77 +
78 +
79 ModifierSlug: t.TypeAlias = str
80 AfterExecuteModifierL: t.TypeAlias = t.Literal["after_execute"]
81 BeforeExecuteModifierL: t.TypeAlias = t.Literal["before_execute"]
82 SchemaModifierL: t.TypeAlias = t.Literal["schema"]
83 +BeforeFileUploadModifierL: t.TypeAlias = t.Literal["before_file_upload"]
84
85
86 class Modifier:
@@ -80,6 +92,7 @@ class Modifier:
92 | SchemaModifier
93 | BeforeExecuteMeta
94 | AfterExecuteMeta
95 + | BeforeFileUploadCallable
96 ],
97 type_: (
98 AfterExecuteModifierL
@@ -87,6 +100,7 @@ class Modifier:
100 | SchemaModifierL
101 | AfterExecuteMetaModifierL
102 | BeforeExecuteMetaModifierL
103 + | BeforeFileUploadModifierL
104 ),
105 tools: t.List[str],
106 toolkits: t.List[str],
@@ -207,6 +221,53 @@ def before_execute(
221 raise ValueError("Either tools or toolkits must be provided")
222
223
224 +@t.overload
225 +def before_file_upload(modifier: t.Optional[BeforeFileUploadCallable]) -> Modifier: ...
226 +
227 +
228 +@t.overload
229 +def before_file_upload(
230 + *,
231 + tools: t.Optional[t.List[str]] = None,
232 + toolkits: t.Optional[t.List[str]] = None,
233 +) -> t.Callable[[BeforeFileUploadCallable], Modifier]: ...
234 +
235 +
236 +def before_file_upload(
237 + modifier: t.Optional[BeforeFileUploadCallable] = None,
238 + *,
239 + tools: t.Optional[t.List[str]] = None,
240 + toolkits: t.Optional[t.List[str]] = None,
241 +) -> Modifier | t.Callable[[BeforeFileUploadCallable], Modifier]:
242 + """
243 + Build a ``Modifier`` for the file-upload hook (same scoping pattern as
244 + :func:`before_execute`).
245 +
246 + Pass the returned ``Modifier`` in ``modifiers=[...]`` on
247 + :meth:`composio.core.models.tools.Tools.execute` or ``tools.get``. Multiple
248 + such modifiers are composed in list order.
249 + """
250 + if modifier is not None:
251 + return Modifier(
252 + modifier=modifier,
253 + type_="before_file_upload",
254 + tools=tools or [],
255 + toolkits=toolkits or [],
256 + )
257 +
258 + if tools is not None or toolkits is not None:
259 + return t.cast(
260 + t.Callable[[BeforeFileUploadCallable], Modifier],
261 + functools.partial(
262 + before_file_upload,
263 + tools=tools or [],
264 + toolkits=toolkits or [],
265 + ),
266 + )
267 +
268 + raise ValueError("Either tools or toolkits must be provided")
269 +
270 +
271 @t.overload
272 def schema_modifier(modifier: t.Optional[SchemaModifier]) -> Modifier: ...
273
@@ -327,6 +388,43 @@ def after_execute_meta(
388 Modifiers = t.List[Modifier]
389
390
391 +def merge_before_file_upload(
392 + modifiers: t.Optional[Modifiers],
393 + tool: str,
394 + toolkit: str,
395 +) -> t.Optional[BeforeFileUploadCallable]:
396 + """Compose ``before_file_upload``-type :class:`Modifier`\\ s for this *tool* / *toolkit*.
397 +
398 + Scoping matches :class:`Modifier` (empty ``tools`` and ``toolkits`` = all tools).
399 + """
400 + to_chain = [
401 + m
402 + for m in (modifiers or [])
403 + if m.type == "before_file_upload" and m.modifier is not None
404 + ]
405 + if not to_chain:
406 + return None
407 +
408 + def _applies(m: Modifier) -> bool:
409 + if len(m.tools) == 0 and len(m.toolkits) == 0:
410 + return True
411 + return tool in m.tools or toolkit in m.toolkits
412 +
413 + def combined(path: str, tool: str, toolkit: str) -> t.Union[str, bool]:
414 + p: str = path
415 + for m in to_chain:
416 + if not _applies(m):
417 + continue
418 + out = t.cast(BeforeFileUploadCallable, m.modifier)(p, tool, toolkit)
419 + if out is False:
420 + return False
421 + if isinstance(out, str):
422 + p = out
423 + return p
424 +
425 + return combined
426 +
427 +
428 @t.overload
429 def apply_modifier_by_type(
430 modifiers: Modifiers,
python/composio/core/models/tool_router.py
+10
@@ -361,6 +361,8 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
361 client: HttpClient,
362 provider: t.Optional["BaseProvider[TTool, TToolCollection]"] = None,
363 auto_upload_download_files: bool = True,
364 + sensitive_file_upload_protection: bool = True,
365 + file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,
366 ):
367 """
368 Initialize ToolRouter instance.
@@ -368,10 +370,14 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
370 :param client: HTTP client for API calls
371 :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 sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload.
374 + :param file_upload_path_deny_segments: Extra path segment names to merge with the built-in denylist.
375 """
376 super().__init__(client)
377 self._provider = provider
378 self._auto_upload_download_files = auto_upload_download_files
379 + self._sensitive_file_upload_protection = sensitive_file_upload_protection
380 + self._file_upload_path_deny_segments = file_upload_path_deny_segments
381
382 def _create_mcp_server_config(
383 self,
@@ -804,6 +810,8 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
810 client=self._client,
811 provider=self._provider,
812 auto_upload_download_files=self._auto_upload_download_files,
813 + sensitive_file_upload_protection=self._sensitive_file_upload_protection,
814 + file_upload_path_deny_segments=self._file_upload_path_deny_segments,
815 session_id=session.session_id,
816 mcp=self._create_mcp_server_config(
817 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
@@ -857,6 +865,8 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
865 client=self._client,
866 provider=self._provider,
867 auto_upload_download_files=self._auto_upload_download_files,
868 + sensitive_file_upload_protection=self._sensitive_file_upload_protection,
869 + file_upload_path_deny_segments=self._file_upload_path_deny_segments,
870 session_id=session.session_id,
871 mcp=self._create_mcp_server_config(
872 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
python/composio/core/models/tool_router_session.py
+30 -15
@@ -77,6 +77,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
77 client: HttpClient,
78 provider: t.Optional[BaseProvider[t.Any, t.Any]],
79 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 session_id: str,
83 mcp: t.Any,
84 experimental: "ToolRouterSessionExperimental",
@@ -86,6 +88,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
88 self._client = client
89 self._provider = provider
90 self._auto_upload_download_files = auto_upload_download_files
91 + self._sensitive_file_upload_protection = sensitive_file_upload_protection
92 + self._file_upload_path_deny_segments = file_upload_path_deny_segments
93 self.session_id = session_id
94 self.mcp = mcp
95 self.experimental = experimental
@@ -108,6 +112,17 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
112 return False
113 return len(self._custom_tools_map.by_final_slug) > 0
114
115 + def _tool_router_backend_execute(
116 + self,
117 + tools_model: t.Any,
118 + modifiers: t.Optional["Modifiers"] = None,
119 + ) -> t.Callable[..., t.Any]:
120 + """Backend execute_meta wrapper with this session's file-upload settings."""
121 + return tools_model._wrap_execute_tool_for_tool_router(
122 + session_id=self.session_id,
123 + modifiers=modifiers,
124 + )
125 +
126 def tools(self, modifiers: t.Optional["Modifiers"] = None) -> TToolCollection:
127 """
128 Get provider-wrapped tools for execution with your AI framework.
@@ -132,6 +147,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
147 client=self._client,
148 provider=self._provider,
149 auto_upload_download_files=self._auto_upload_download_files,
150 + sensitive_file_upload_protection=self._sensitive_file_upload_protection,
151 + file_upload_path_deny_segments=self._file_upload_path_deny_segments,
152 )
153
154 router_tools = tools_model.get_raw_tool_router_meta_tools(
@@ -159,9 +176,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
176 if self._has_custom_tools():
177 execute_fn = self._create_routing_execute_fn(tools_model, modifiers)
178 else:
162 - execute_fn = tools_model._wrap_execute_tool_for_tool_router(
163 - session_id=self.session_id,
164 - modifiers=modifiers,
179 + execute_fn = self._tool_router_backend_execute(
180 + tools_model, modifiers=modifiers
181 )
182
183 return t.cast(
@@ -182,9 +198,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
198 Applies before_execute/after_execute modifiers around the overall
199 COMPOSIO_MULTI_EXECUTE_TOOL call, consistent with the standard path.
200 """
185 - backend_execute = tools_model._wrap_execute_tool_for_tool_router(
186 - session_id=self.session_id,
187 - modifiers=modifiers,
201 + backend_execute = self._tool_router_backend_execute(
202 + tools_model, modifiers=modifiers
203 )
204
205 def routing_execute(slug: str, arguments: t.Dict) -> t.Dict:
@@ -251,9 +266,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
266 tool_items = input_args.get("tools")
267 if not isinstance(tool_items, list) or len(tool_items) == 0:
268 # Fallback: send to backend as-is (no modifiers — caller handles them)
254 - return tools_model._wrap_execute_tool_for_tool_router(
255 - session_id=self.session_id,
256 - )(COMPOSIO_MULTI_EXECUTE_TOOL, input_args)
269 + return self._tool_router_backend_execute(tools_model)(
270 + COMPOSIO_MULTI_EXECUTE_TOOL,
271 + input_args,
272 + )
273
274 parsed = [self._parse_tool_item(item) for item in tool_items]
275
@@ -269,9 +285,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
285
286 # All remote — just forward entire payload (no modifiers — caller handles them)
287 if not local_items:
272 - return tools_model._wrap_execute_tool_for_tool_router(
273 - session_id=self.session_id,
274 - )(COMPOSIO_MULTI_EXECUTE_TOOL, input_args)
288 + return self._tool_router_backend_execute(tools_model)(
289 + COMPOSIO_MULTI_EXECUTE_TOOL,
290 + input_args,
291 + )
292
293 ctx = self._session_context
294 assert ctx is not None
@@ -298,9 +315,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
315 if remote_indices:
316 remote_tool_items = [tool_items[i] for i in remote_indices]
317 remote_input = {**input_args, "tools": remote_tool_items}
301 - execute_fn = tools_model._wrap_execute_tool_for_tool_router(
302 - session_id=self.session_id,
303 - )
318 + execute_fn = self._tool_router_backend_execute(tools_model)
319 remote_future = pool.submit(
320 execute_fn,
321 COMPOSIO_MULTI_EXECUTE_TOOL,
python/composio/core/models/tools.py
+62 -9
@@ -33,6 +33,8 @@ from ._modifiers import (
33 after_execute,
34 apply_modifier_by_type,
35 before_execute,
36 + before_file_upload,
37 + merge_before_file_upload,
38 schema_modifier,
39 )
40
@@ -101,6 +103,8 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
103 file_download_dir: t.Optional[str] = None,
104 toolkit_versions: t.Optional[ToolkitVersionParam] = None,
105 auto_upload_download_files: bool = True,
106 + sensitive_file_upload_protection: bool = True,
107 + file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,
108 ):
109 """
110 Initialize the tools resource.
@@ -110,11 +114,18 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
114 :param file_download_dir: Output directory for downloadable files
115 :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.
117 + :param sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload.
118 + :param file_upload_path_deny_segments: Extra path segment names to merge with the built-in denylist.
119 """
120 self._client = client
121 self._custom_tools = CustomTools(client)
122 self._tool_schemas: t.Dict[str, Tool] = {}
117 - self._file_helper = FileHelper(client=self._client, outdir=file_download_dir)
123 + self._file_helper = FileHelper(
124 + client=self._client,
125 + outdir=file_download_dir,
126 + sensitive_file_upload_protection=sensitive_file_upload_protection,
127 + file_upload_path_deny_segments=file_upload_path_deny_segments,
128 + )
129 self._toolkit_versions = toolkit_versions
130 self._auto_upload_download_files = auto_upload_download_files
131
@@ -369,7 +380,11 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
380 :return: Provider-specific tool collection (TToolCollection).
381 """
382 if slug is not None:
372 - return self._get(user_id=user_id, tools=[slug], modifiers=modifiers)
383 + return self._get(
384 + user_id=user_id,
385 + tools=[slug],
386 + modifiers=modifiers,
387 + )
388 return self._get(
389 user_id=user_id,
390 tools=tools,
@@ -428,6 +443,36 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
443 :param arguments: The tool arguments
444 :return: Tool execution response
445 """
446 + tool = self._tool_schemas.get(slug)
447 + if tool is None:
448 + custom_tool = self._custom_tools.get(slug=slug)
449 + if custom_tool is not None:
450 + tool = custom_tool.info
451 + self._tool_schemas[slug] = tool
452 +
453 + if tool is None:
454 + tool = t.cast(
455 + Tool,
456 + self._client.tools.retrieve(
457 + tool_slug=slug,
458 + toolkit_versions=none_to_omit(self._toolkit_versions),
459 + ),
460 + )
461 + self._tool_schemas[slug] = tool
462 +
463 + if self._auto_upload_download_files:
464 + meta_tk = tool.toolkit.slug if tool.toolkit else "unknown"
465 + bfu = merge_before_file_upload(
466 + modifiers,
467 + tool=slug,
468 + toolkit=meta_tk,
469 + )
470 + arguments = self._file_helper.substitute_file_uploads(
471 + tool=tool,
472 + request=arguments,
473 + before_file_upload=bfu,
474 + )
475 +
476 # Apply before_execute modifiers
477 # Meta tools are always from the 'composio' toolkit
478 processed_arguments = arguments
@@ -589,7 +634,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
634 :param text: The text to pass to the tool.
635 :param version: The version of the tool to execute (overrides the SDK-level toolkit versions for this execution).
636 :param dangerously_skip_version_check: Skip the version check for 'latest' version. This might cause unexpected behavior when new versions are released.
592 - :param modifiers: The modifiers to apply to the tool.
637 + :param modifiers: The modifiers to apply to the tool (include ``@before_file_upload`` for file path hooks).
638 :return: The response from the tool.
639 """
640
@@ -610,6 +655,19 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
655 )
656 self._tool_schemas[slug] = tool
657
658 + if self._auto_upload_download_files:
659 + tk = tool.toolkit.slug if tool.toolkit else "unknown"
660 + bfu = merge_before_file_upload(
661 + modifiers,
662 + tool=slug,
663 + toolkit=tk,
664 + )
665 + arguments = self._file_helper.substitute_file_uploads(
666 + tool=tool,
667 + request=arguments,
668 + before_file_upload=bfu,
669 + )
670 +
671 if modifiers is not None:
672 type_before_exec: t.Literal["before_execute"] = "before_execute"
673 request_params: ToolExecuteParams = {
@@ -654,12 +712,6 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
712 dangerously_skip_version_check = processed_params.get(
713 "dangerously_skip_version_check", dangerously_skip_version_check
714 )
657 -
658 - if self._auto_upload_download_files:
659 - arguments = self._file_helper.substitute_file_uploads(
660 - tool=tool,
661 - request=arguments,
662 - )
715 response = (
716 self._execute_custom_tool(
717 slug=slug,
@@ -727,5 +779,6 @@ __all__ = [
779 "Modifiers",
780 "after_execute",
781 "before_execute",
782 + "before_file_upload",
783 "schema_modifier",
784 ]
python/composio/exceptions.py
+8
@@ -168,6 +168,14 @@ class ErrorUploadingFile(FileError):
168 pass
169
170
171 +class SensitiveFilePathBlockedError(FileError):
172 + """Raised when a local file path is refused before upload (sensitive directory or credential-like name)."""
173 +
174 +
175 +class FileUploadAbortedError(FileError):
176 + """Raised when a ``before_file_upload`` hook returns ``False``."""
177 +
178 +
179 class ErrorDownloadingFile(FileError):
180 pass
181
python/composio/sdk.py
+14
@@ -41,6 +41,8 @@ class SDKConfig(te.TypedDict):
41 file_download_dir: te.NotRequired[str]
42 toolkit_versions: te.NotRequired[ToolkitVersionParam]
43 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
47
48 class Composio(t.Generic[TTool, TToolCollection], WithLogger):
@@ -104,6 +106,8 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
106 - A string (e.g., 'latest', '20250906_01') to use the same version for all toolkits
107 - 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 sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload. Defaults to True.
110 + :param file_upload_path_deny_segments: Extra path segment names merged with the built-in denylist.
111 """
112 WithLogger.__init__(self)
113 api_key = kwargs.get("api_key", os.environ.get("COMPOSIO_API_KEY"))
@@ -130,12 +134,20 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
134 max_retries=kwargs.get("max_retries", DEFAULT_MAX_RETRIES),
135 )
136 self.provider = actual_provider
137 + sensitive_file_upload_protection: bool = kwargs.get(
138 + "sensitive_file_upload_protection", True
139 + )
140 + file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = kwargs.get(
141 + "file_upload_path_deny_segments"
142 + )
143 self.tools = Tools(
144 client=self._client,
145 provider=actual_provider,
146 file_download_dir=kwargs.get("file_download_dir"),
147 toolkit_versions=toolkit_versions,
148 auto_upload_download_files=kwargs.get("auto_upload_download_files", True),
149 + sensitive_file_upload_protection=sensitive_file_upload_protection,
150 + file_upload_path_deny_segments=file_upload_path_deny_segments,
151 )
152
153 self.toolkits = Toolkits(client=self._client)
@@ -154,6 +166,8 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
166 client=self._client,
167 provider=actual_provider,
168 auto_upload_download_files=kwargs.get("auto_upload_download_files", True),
169 + sensitive_file_upload_protection=sensitive_file_upload_protection,
170 + file_upload_path_deny_segments=file_upload_path_deny_segments,
171 )
172 self.create = self.tool_router.create
173 self.use = self.tool_router.use
python/composio/utils/sensitive_file_upload_paths.py new
+93
@@ -0,0 +1,93 @@
1 +"""Block accidental upload of local files from well-known secret/credential locations."""
2 +
3 +from __future__ import annotations
4 +
5 +import re
6 +import typing as t
7 +from pathlib import Path
8 +
9 +# Path components that indicate a sensitive directory anywhere in a resolved local path.
10 +BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS: t.Tuple[str, ...] = (
11 + ".ssh",
12 + ".aws",
13 + ".azure",
14 + ".gnupg",
15 + ".kube",
16 + ".docker",
17 + ".claude", # may contain API keys and project context read by assistants
18 + ".password-store",
19 + "keychains",
20 +)
21 +
22 +_SECRET_LIKE_BASENAME = re.compile(r"^(\.env(\.|$)|\.netrc$|\.pgpass$)", re.IGNORECASE)
23 +_DEFAULT_PRIVATE_KEY_BASENAME = re.compile(
24 + r"^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$", re.IGNORECASE
25 +)
26 +
27 +
28 +def _normalize_path_segments(file_path: t.Union[str, Path]) -> t.List[str]:
29 + p = Path(file_path).expanduser()
30 + try:
31 + resolved = p.resolve()
32 + except OSError:
33 + resolved = p
34 + parts = [part for part in resolved.as_posix().split("/") if part]
35 + if parts and parts[0].endswith(":"):
36 + # Windows path: "C:/Users/..." -> drop drive letter segment
37 + parts = parts[1:]
38 + return parts
39 +
40 +
41 +def _get_block_reason(
42 + file_path: t.Union[str, Path],
43 + additional_deny_segments: t.Optional[t.Sequence[str]] = None,
44 +) -> t.Optional[str]:
45 + extra = [s.strip() for s in (additional_deny_segments or []) if s and s.strip()]
46 + deny: t.Set[str] = {s.lower() for s in BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS}
47 + deny.update(s.lower() for s in extra)
48 +
49 + segments = _normalize_path_segments(file_path)
50 + # Case-insensitive segment match: lower each path component once per check.
51 + for seg, key in zip(segments, (s.lower() for s in segments), strict=True):
52 + if key in deny:
53 + return f'path segment "{seg}" is in the sensitive file upload denylist'
54 +
55 + if not segments:
56 + return None
57 + basename = segments[-1]
58 + if _SECRET_LIKE_BASENAME.search(basename) or _DEFAULT_PRIVATE_KEY_BASENAME.match(
59 + basename
60 + ):
61 + return (
62 + f'file name "{basename}" looks like a credential, env, or private key file'
63 + )
64 + if basename.lower() == "credentials":
65 + return 'file name "credentials" is often used for cloud/API credential stores'
66 + return None
67 +
68 +
69 +def is_blocked_sensitive_file_upload_path(
70 + file_path: t.Union[str, Path],
71 + additional_deny_segments: t.Optional[t.Sequence[str]] = None,
72 +) -> bool:
73 + return _get_block_reason(file_path, additional_deny_segments) is not None
74 +
75 +
76 +def assert_safe_local_file_upload_path(
77 + file_path: t.Union[str, Path],
78 + *,
79 + enabled: bool = True,
80 + additional_deny_segments: t.Optional[t.Sequence[str]] = None,
81 +) -> None:
82 + """Raise SensitiveFilePathBlockedError if *file_path* matches the denylist."""
83 + if not enabled:
84 + return
85 + reason = _get_block_reason(file_path, additional_deny_segments)
86 + if reason:
87 + from composio.exceptions import SensitiveFilePathBlockedError
88 +
89 + raise SensitiveFilePathBlockedError(
90 + f"Refusing to upload: {reason}. "
91 + "Set sensitive_file_upload_protection=False on Composio if you must "
92 + "(not recommended), or use a copy outside sensitive locations."
93 + )
python/examples/modifiers.py
+14 -1
@@ -1,6 +1,12 @@
1 import os
2
3 -from composio import Composio, after_execute, before_execute, schema_modifier
3 +from composio import (
4 + Composio,
5 + after_execute,
6 + before_execute,
7 + before_file_upload,
8 + schema_modifier,
9 +)
10 from composio.types import Tool, ToolExecuteParams, ToolExecutionResponse
11
12 composio = Composio()
@@ -17,6 +23,12 @@ def before_execute_modifier(
23 return params
24
25
26 +@before_file_upload(tools=["HACKERNEWS_GET_USER"])
27 +def rewrite_upload_path(path: str, tool: str, toolkit: str) -> str:
28 + """Optional: same pattern as before_execute; use for per-tool file path policy."""
29 + return path
30 +
31 +
32 @after_execute(tools=["HACKERNEWS_GET_USER"])
33 def after_execute_modifier(
34 tool: str,
@@ -38,6 +50,7 @@ response = composio.tools.execute(
50 arguments={"username": "pg"},
51 modifiers=[
52 before_execute_modifier,
53 + rewrite_upload_path,
54 after_execute_modifier,
55 ],
56 )
python/providers/anthropic/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-anthropic"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get an array of tools with your Anthropic LLMs."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/anthropic/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_anthropic",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Anthropic LLMs.",
python/providers/autogen/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-autogen"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get an array of tools with your autogen agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/autogen/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_autogen",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Autogen agent.",
python/providers/claude_agent_sdk/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-claude-agent-sdk"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get an array of tools with Claude Code Agents SDK."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/claude_agent_sdk/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
8
9 setup(
10 name="composio_claude_agent_sdk",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools for Claude Agent SDK",
python/providers/crewai/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-crewai"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get an array of tools with your CrewAI agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/crewai/setup.py
+1 -1
@@ -6,7 +6,7 @@ from setuptools import setup
6
7 setup(
8 name="composio_crewai",
9 - version="0.11.5",
9 + version="0.11.6",
10 author="Composio",
11 author_email="tech@composio.dev",
12 description="Use Composio to get an array of tools with your CrewAI agent.",
python/providers/gemini/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-gemini"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get an array of tools with your Gemini agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/gemini/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_gemini",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Gemini agent.",
python/providers/google/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-google"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/google/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_google",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
python/providers/google_adk/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-google-adk"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/google_adk/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_google_adk",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
python/providers/langchain/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-langchain"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get an array of tools with your Langchain agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/langchain/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_langchain",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Langchain agent.",
python/providers/langgraph/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-langgraph"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get array of tools with LangGraph Agent Workflows."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/langgraph/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_langgraph",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools with LangGraph Agent Workflows",
python/providers/llamaindex/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-llamaindex"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get array of tools with LlamaIndex Agent Workflows."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/llamaindex/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_llamaindex",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools with LlamaIndex Agent Workflows",
python/providers/openai/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-openai"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get an array of tools with your OpenAI Function Call."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/openai/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_openai",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your OpenAI Function Call.",
python/providers/openai_agents/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-openai-agents"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "Use Composio to get array of strongly typed tools for OpenAI Agents"
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/openai_agents/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
8
9 setup(
10 name="composio_openai_agents",
11 - version="0.11.5",
11 + version="0.11.6",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of strongly typed tools for OpenAI Agents",
python/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio"
3 -version = "0.11.5"
3 +version = "0.11.6"
4 description = "SDK for integrating Composio with your applications."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/scripts/generate-docs.py
+1
@@ -36,6 +36,7 @@ GITHUB_BASE = "https://github.com/composiohq/composio/blob/next/python"
36 DECORATORS_TO_DOCUMENT = [
37 ("before_execute", "composio.core.models._modifiers"),
38 ("after_execute", "composio.core.models._modifiers"),
39 + ("before_file_upload", "composio.core.models._modifiers"),
40 ("schema_modifier", "composio.core.models._modifiers"),
41 ]
42
python/tests/test_auto_upload_download_files.py
+65
@@ -173,6 +173,71 @@ class TestAutoUploadDownloadFilesEnabled:
173
174 mock_upload.assert_called_once()
175
176 + def test_execute_runs_substitute_before_before_execute(
177 + self, mock_client, mock_provider
178 + ):
179 + """File substitution runs before before_execute modifiers (same order as TypeScript)."""
180 + from composio.core.models._modifiers import Modifier
181 +
182 + tools = Tools(
183 + client=mock_client,
184 + provider=mock_provider,
185 + auto_upload_download_files=True,
186 + toolkit_versions={"test_toolkit": "20251201_01"},
187 + )
188 +
189 + mock_tool = create_mock_tool(
190 + slug="TEST_TOOL",
191 + toolkit_slug="test_toolkit",
192 + input_parameters={
193 + "type": "object",
194 + "properties": {
195 + "file": {"type": "string", "file_uploadable": True},
196 + },
197 + },
198 + output_parameters={"type": "object", "properties": {}},
199 + )
200 + tools._tool_schemas["TEST_TOOL"] = mock_tool
201 +
202 + seen_in_modifier: list = []
203 +
204 + def before_modifier(tool: str, toolkit: str, params): # type: ignore[no-untyped-def]
205 + seen_in_modifier.append(dict(params["arguments"]))
206 + return params
207 +
208 + modifiers = [
209 + Modifier(
210 + modifier=before_modifier, type_="before_execute", tools=[], toolkits=[]
211 + ),
212 + ]
213 +
214 + with patch.object(
215 + tools._file_helper,
216 + "substitute_file_uploads",
217 + return_value={"file": "after_substitute"},
218 + ) as mock_sub:
219 + mock_execute_response = Mock()
220 + mock_execute_response.model_dump.return_value = {
221 + "data": {},
222 + "error": None,
223 + "successful": True,
224 + }
225 + mock_client.tools.execute.return_value = mock_execute_response
226 +
227 + with patch.object(
228 + tools, "get_raw_composio_tool_by_slug", return_value=mock_tool
229 + ):
230 + tools.execute(
231 + slug="TEST_TOOL",
232 + arguments={"file": "/tmp/x"},
233 + modifiers=modifiers,
234 + dangerously_skip_version_check=True,
235 + )
236 +
237 + mock_sub.assert_called_once()
238 + assert len(seen_in_modifier) == 1
239 + assert seen_in_modifier[0] == {"file": "after_substitute"}
240 +
241 def test_execute_calls_substitute_file_downloads(self, mock_client, mock_provider):
242 """Test that execute calls substitute_file_downloads when enabled."""
243 tools = Tools(
python/tests/test_sdk.py
+2
@@ -57,6 +57,8 @@ class TestComposioSDK:
57 "file_download_dir",
58 "toolkit_versions",
59 "auto_upload_download_files",
60 + "sensitive_file_upload_protection",
61 + "file_upload_path_deny_segments",
62 }
63 assert set(SDKConfig.__annotations__.keys()) == expected_fields
64
python/tests/test_sensitive_file_upload_paths.py new
+79
@@ -0,0 +1,79 @@
1 +"""Tests for composio.utils.sensitive_file_upload_paths."""
2 +
3 +from __future__ import annotations
4 +
5 +import tempfile
6 +from pathlib import Path
7 +
8 +import pytest
9 +
10 +from composio.exceptions import SensitiveFilePathBlockedError
11 +from composio.utils.sensitive_file_upload_paths import (
12 + assert_safe_local_file_upload_path,
13 + is_blocked_sensitive_file_upload_path,
14 +)
15 +
16 +
17 +def test_allows_normal_project_files() -> None:
18 + p = Path("/tmp") / "composio-test" / "document.pdf"
19 + assert is_blocked_sensitive_file_upload_path(p) is False
20 + assert_safe_local_file_upload_path(p)
21 +
22 +
23 +def test_blocks_common_credential_directory_segments() -> None:
24 + home = Path.home()
25 + assert is_blocked_sensitive_file_upload_path(home / ".aws" / "credentials") is True
26 + assert is_blocked_sensitive_file_upload_path(home / ".ssh" / "id_ed25519") is True
27 + assert (
28 + is_blocked_sensitive_file_upload_path(home / ".claude" / "settings.json")
29 + is True
30 + )
31 +
32 +
33 +def test_blocks_env_style_basenames() -> None:
34 + assert is_blocked_sensitive_file_upload_path(Path("/app/repo/.env")) is True
35 + assert is_blocked_sensitive_file_upload_path(Path("/app/repo/.env.local")) is True
36 +
37 +
38 +def test_blocks_default_private_key_basenames() -> None:
39 + assert is_blocked_sensitive_file_upload_path(Path("/tmp/id_ed25519")) is True
40 +
41 +
42 +def test_allows_public_key_by_basename() -> None:
43 + assert is_blocked_sensitive_file_upload_path(Path("/tmp/id_ed25519.pub")) is False
44 +
45 +
46 +def test_honors_additional_deny_segments() -> None:
47 + assert (
48 + is_blocked_sensitive_file_upload_path(
49 + Path("/data/secrets/x.txt"), additional_deny_segments=["secrets"]
50 + )
51 + is True
52 + )
53 + assert (
54 + is_blocked_sensitive_file_upload_path(
55 + Path("/data/ok/x.txt"), additional_deny_segments=["secrets"]
56 + )
57 + is False
58 + )
59 +
60 +
61 +def test_blocks_after_symlink_resolves_to_sensitive_dir() -> None:
62 + with tempfile.TemporaryDirectory() as root:
63 + root_p = Path(root)
64 + aws_dir = root_p / "nested" / ".aws"
65 + aws_dir.mkdir(parents=True)
66 + target = aws_dir / "creds"
67 + target.write_text("x", encoding="utf-8")
68 + link = root_p / "innocent-name"
69 + try:
70 + link.symlink_to(target)
71 + except OSError:
72 + pytest.skip("symlinks not supported")
73 + assert is_blocked_sensitive_file_upload_path(link) is True
74 +
75 +
76 +def test_assert_safe_raises() -> None:
77 + p = Path.home() / ".ssh" / "id_rsa"
78 + with pytest.raises(SensitiveFilePathBlockedError):
79 + assert_safe_local_file_upload_path(p)
python/tests/test_tool_execution.py
+80
@@ -1,5 +1,6 @@
1 """Test tool execution with toolkit versions and argument serialization."""
2
3 +import typing as t
4 from unittest.mock import Mock, patch
5
6 import pytest
@@ -845,6 +846,85 @@ class TestToolExecution:
846 assert result["successful"] is True
847 assert result["data"]["modified"] is True
848
849 + def test_merge_before_file_upload_scopes_by_tool(self):
850 + from composio.core.models._modifiers import (
851 + before_file_upload,
852 + merge_before_file_upload,
853 + )
854 +
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"
859 +
860 + all_tools = before_file_upload(lambda p, t, k: p + "_Y")
861 + fn2 = merge_before_file_upload([all_tools], tool="MY", toolkit="gh")
862 + assert fn2 is not None
863 + assert fn2("/a", "MY", "gh") == "/a_Y"
864 +
865 + def test_merge_before_file_upload_chains_modifiers(self):
866 + from composio.core.models._modifiers import (
867 + before_file_upload,
868 + merge_before_file_upload,
869 + )
870 +
871 + m1 = before_file_upload(lambda p, t, k: f"{p}|1")
872 + m2 = before_file_upload(lambda p, t, k: f"{p}|2")
873 + fn = merge_before_file_upload([m1, m2], tool="T", toolkit="k")
874 + assert fn is not None
875 + assert fn("p", "T", "k") == "p|1|2"
876 +
877 + def test_execute_includes_before_file_upload_modifier_in_compose(
878 + self,
879 + ):
880 + """``before_file_upload`` in ``modifiers`` is composed into substitute_file_uploads."""
881 + from composio.core.models._modifiers import before_file_upload
882 +
883 + mock_client = Mock()
884 + mock_provider = Mock()
885 + mock_provider.name = "test_provider"
886 +
887 + tools = Tools(
888 + client=mock_client,
889 + provider=mock_provider,
890 + toolkit_versions={"github": "20251201_01"},
891 + )
892 +
893 + github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")
894 +
895 + with patch.object(
896 + tools, "get_raw_composio_tool_by_slug", return_value=github_tool
897 + ):
898 + mock_client.tools.retrieve.return_value = github_tool
899 +
900 + mock_execute_response = Mock()
901 + mock_execute_response.model_dump.return_value = {
902 + "data": {"result": "success"},
903 + "error": None,
904 + "successful": True,
905 + }
906 + mock_client.tools.execute.return_value = mock_execute_response
907 +
908 + cap: t.Dict = {}
909 +
910 + def capture_sub(**kwargs):
911 + cap["bfu"] = kwargs.get("before_file_upload")
912 + return kwargs["request"]
913 +
914 + with patch.object(
915 + tools._file_helper, "substitute_file_uploads", side_effect=capture_sub
916 + ):
917 + mod = before_file_upload(lambda p, t, k: f"{p}>")
918 + tools.execute(
919 + slug="GITHUB_GET_REPOS",
920 + arguments={"owner": "a", "repo": "b"},
921 + modifiers=[mod],
922 + )
923 +
924 + bfu = cap.get("bfu")
925 + assert bfu is not None
926 + assert bfu("/p", "GITHUB_GET_REPOS", "github") == "/p>"
927 +
928 def test_execute_with_environment_variable_toolkit_version(self):
929 """Test that execute uses environment variable for toolkit version."""
930 import os
python/tests/test_tool_router.py
+20 -4
@@ -968,7 +968,11 @@ class TestToolRouter:
968
969 # Verify Tools was instantiated
970 mock_tools_class.assert_called_once_with(
971 - client=mock_client, provider=mock_provider, auto_upload_download_files=True
971 + client=mock_client,
972 + provider=mock_provider,
973 + auto_upload_download_files=True,
974 + sensitive_file_upload_protection=True,
975 + file_upload_path_deny_segments=None,
976 )
977
978 # Verify get_raw_tool_router_meta_tools was called
@@ -1260,7 +1264,11 @@ class TestToolRouterExecution:
1264 # Create a real Tools instance to test the execute function
1265 from composio.core.models.tools import Tools as RealTools
1266
1263 - real_tools = RealTools(client=mock_client, provider=mock_provider)
1267 + real_tools = RealTools(
1268 + client=mock_client,
1269 + provider=mock_provider,
1270 + auto_upload_download_files=False,
1271 + )
1272 execute_fn = real_tools._wrap_execute_tool_for_tool_router(
1273 session_id="session_123"
1274 )
@@ -1307,7 +1315,11 @@ class TestToolRouterExecution:
1315 from composio.core.models._modifiers import Modifier
1316 from composio.core.models.tools import Tools as RealTools
1317
1310 - real_tools = RealTools(client=mock_client, provider=mock_provider)
1318 + real_tools = RealTools(
1319 + client=mock_client,
1320 + provider=mock_provider,
1321 + auto_upload_download_files=False,
1322 + )
1323
1324 modifiers = [
1325 Modifier(
@@ -1346,7 +1358,11 @@ class TestToolRouterExecution:
1358 # Create a real execute function
1359 from composio.core.models.tools import Tools as RealTools
1360
1349 - real_tools = RealTools(client=mock_client, provider=mock_provider)
1361 + real_tools = RealTools(
1362 + client=mock_client,
1363 + provider=mock_provider,
1364 + auto_upload_download_files=False,
1365 + )
1366 execute_fn = real_tools._wrap_execute_tool_for_tool_router(
1367 session_id="session_123"
1368 )
ts/docs/advanced/auto-upload-download.md
+46 -6
@@ -9,6 +9,37 @@ The file handling system in Composio SDK is:
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)
13 +
14 +## Security: sensitive local paths
15 +
16 +Auto-upload reads local files and sends them to Composio storage. That is powerful for agents, but it also means a model or caller could pass a path that points at **secrets on disk** (API keys, SSH private keys, cloud CLI config). To reduce accidental exfiltration:
17 +
18 +- **`sensitiveFileUploadProtection`** (default `true`) — Before reading a file, the SDK resolves the path and checks it against a built-in list of path *components* (for example `.ssh`, `.aws`, `.claude`, `.kube`) and patterns for credential-like basenames (for example `.env`, default SSH private key names, a file named `credentials`). If the path matches, upload fails with `ComposioSensitiveFilePathBlockedError` unless you disable protection.
19 +- **`fileUploadPathDenySegments`** — Optional extra path component names (single directory or file name) merged with the built-in list, anywhere in the resolved path.
20 +- **`beforeFileUpload`** — Not a constructor option. Pass it as part of the **third argument** to `composio.tools.execute` (with `beforeExecute` / `afterExecute`). The hook receives `{ path, toolSlug, toolkitSlug }` for each `file_uploadable` value. Return a string path to upload instead, `false` to abort (`ComposioFileUploadAbortedError`), or throw.
21 +
22 +**Not path-checked the same way:** HTTP/HTTPS URLs and `File` objects do not go through the local path denylist logic in the same manner as string paths that refer to the local filesystem.
23 +
24 +**Disabling protection:** `sensitiveFileUploadProtection: false` turns off the denylist checks. Only use this if you understand the risk and have another control (for example a strict allowlist in `beforeFileUpload`).
25 +
26 +```typescript
27 +import { Composio } from '@composio/core';
28 +
29 +const composio = new Composio({
30 + apiKey: process.env.COMPOSIO_API_KEY!,
31 + sensitiveFileUploadProtection: true,
32 + fileUploadPathDenySegments: ['my-team-secrets'],
33 +});
34 +
35 +await composio.tools.execute(
36 + 'YOUR_TOOL',
37 + { userId: 'u', arguments: { file: '/safe/path/doc.pdf' }, dangerouslySkipVersionCheck: true },
38 + {
39 + beforeFileUpload: async ({ path }) => path,
40 + }
41 +);
42 +```
43
44 ## How It Works
45
@@ -174,19 +205,28 @@ Downloaded files are stored in a temporary directory:
205 The SDK includes specific error types for file operations:
206
207 ```typescript
177 -import { ComposioFileUploadError } from '@composio/core';
208 +import {
209 + ComposioFileUploadError,
210 + ComposioSensitiveFilePathBlockedError,
211 + ComposioFileUploadAbortedError,
212 +} from '@composio/core';
213
214 try {
215 await composio.tools.execute('your-tool', {
216 + userId: 'u',
217 arguments: {
182 - file: '/path/to/file.txt'
183 - }
218 + file: '/path/to/file.txt',
219 + },
220 + dangerouslySkipVersionCheck: true,
221 });
222 } catch (error) {
186 - if (error instanceof ComposioFileUploadError) {
223 + if (error instanceof ComposioSensitiveFilePathBlockedError) {
224 + console.error('Blocked sensitive path:', error.message);
225 + } else if (error instanceof ComposioFileUploadAbortedError) {
226 + console.error('Upload aborted by beforeFileUpload:', error.message);
227 + } else if (error instanceof ComposioFileUploadError) {
228 console.error('File upload failed:', error.message);
188 - // Handle file upload error
189 - // Possible fixes will be included in error.possibleFixes
229 + // Possible fixes may be included in error.possibleFixes
230 }
231 throw error;
232 }
ts/docs/api/composio.md
+27
@@ -12,6 +12,8 @@ const composio = new Composio({
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
15 + sensitiveFileUploadProtection: true, // Optional: block uploads from sensitive paths (Node; default true)
16 + fileUploadPathDenySegments: undefined, // Optional: extra path component denylist
17 provider: new OpenAIProvider(), // Optional: Custom provider
18 });
19 ```
@@ -26,6 +28,8 @@ The `Composio` constructor accepts a configuration object with the following pro
28 | `baseURL` | string | No | `https://api.composio.dev` | The base URL for the Composio API |
29 | `allowTracking` | boolean | No | `true` | Whether to allow analytics/tracking |
30 | `autoUploadDownloadFiles`| boolean | No | `true` | Whether to automatically handle file operations |
31 +| `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. |
32 +| `fileUploadPathDenySegments` | `string[]` | No | `undefined` | Additional path *components* merged with the built-in denylist. |
33 | `provider` | `BaseComposioProvider` | No | `new OpenAIProvider()` | The provider to use for this Composio instance |
34
35 ## Properties
@@ -103,3 +107,26 @@ const composio = new Composio({
107 autoUploadDownloadFiles: false,
108 });
109 ```
110 +
111 +### Per-execution `beforeFileUpload` modifier
112 +
113 +Use the **third argument** to `composio.tools.execute` to intercept each file read before upload (in addition to global `sensitiveFileUploadProtection` on the client):
114 +
115 +```typescript
116 +import { Composio } from '@composio/core';
117 +
118 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY! });
119 +
120 +await composio.tools.execute(
121 + 'SOME_FILE_TOOL',
122 + { userId: 'u', arguments: { file: '/tmp/report.pdf' }, dangerouslySkipVersionCheck: true },
123 + {
124 + beforeFileUpload: async ({ path, toolSlug, toolkitSlug }) => {
125 + // return path, a different path, or false to abort
126 + return path;
127 + },
128 + }
129 +);
130 +```
131 +
132 +See [Auto upload and download](./advanced/auto-upload-download.md#security-sensitive-local-paths) for the security model and error types.
ts/packages/core/src/composio.ts
+19 -1
@@ -46,6 +46,19 @@ export type ComposioConfig<
46 * @default true
47 */
48 autoUploadDownloadFiles?: 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
52 + * credential-like file names (e.g. `.env`, default SSH private key names). URLs and
53 + * {@link File} objects are not path-checked.
54 + * @default true
55 + */
56 + sensitiveFileUploadProtection?: boolean;
57 + /**
58 + * Extra path components (a single directory or file name) to treat as sensitive when
59 + * they appear anywhere in the resolved path. Merged with the built-in list.
60 + */
61 + fileUploadPathDenySegments?: string[];
62 /**
63 * The tool provider to use for this Composio instance.
64 * @example new OpenAIProvider()
@@ -253,6 +266,8 @@ export class Composio<
266 allowTracking: config?.allowTracking ?? CONFIG_DEFAULTS.allowTracking,
267 autoUploadDownloadFiles:
268 config?.autoUploadDownloadFiles ?? CONFIG_DEFAULTS.autoUploadDownloadFiles,
269 + sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection,
270 + fileUploadPathDenySegments: config?.fileUploadPathDenySegments,
271 provider: config?.provider ?? this.provider,
272 };
273
@@ -274,7 +289,10 @@ export class Composio<
289 this.toolkits = new Toolkits(this.client);
290 this.triggers = new Triggers(this.client, this.config);
291 this.authConfigs = new AuthConfigs(this.client);
277 - this.files = new Files(this.client);
292 + this.files = new Files(this.client, {
293 + sensitiveFileUploadProtection: this.config.sensitiveFileUploadProtection,
294 + fileUploadPathDenySegments: this.config.fileUploadPathDenySegments,
295 + });
296 this.connectedAccounts = new ConnectedAccounts(this.client);
297 this.toolRouter = new ToolRouter(this.client, this.config);
298
ts/packages/core/src/errors/FileModifierErrors.ts
+40 -5
@@ -2,18 +2,53 @@ import { ComposioError, ComposioErrorOptions } from './ComposioError';
2
3 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 } as const;
8
9 export class ComposioFileUploadError extends ComposioError {
8 - constructor(
9 - message: string = 'Failed to upload file',
10 - options: Omit<ComposioErrorOptions, 'code'> = {}
11 - ) {
10 + constructor(message: string = 'Failed to upload file', options: ComposioErrorOptions = {}) {
11 super(message, {
12 ...options,
14 - code: FileModifierErrorCodes.FILE_UPLOAD_FAILED,
13 + code: options.code ?? FileModifierErrorCodes.FILE_UPLOAD_FAILED,
14 possibleFixes: options.possibleFixes || ['Check if the file exists in the location provided'],
15 });
16 this.name = 'ComposioFileUploadError';
17 }
18 }
19 +
20 +/**
21 + * Thrown when a local file path is refused before upload (sensitive directory or
22 + * credential-like file name). Subclass of {@link ComposioFileUploadError} so existing
23 + * `instanceof ComposioFileUploadError` handlers still apply.
24 + */
25 +export class ComposioSensitiveFilePathBlockedError extends ComposioFileUploadError {
26 + constructor(message: string, options: ComposioErrorOptions = {}) {
27 + super(message, {
28 + ...options,
29 + code: FileModifierErrorCodes.SENSITIVE_FILE_PATH_BLOCKED,
30 + possibleFixes: options.possibleFixes ?? [
31 + 'Use a file outside ~/.ssh, ~/.aws, and other credential locations',
32 + 'Set sensitiveFileUploadProtection: false only if you understand the risk',
33 + 'Add path segments to block with fileUploadPathDenySegments',
34 + ],
35 + });
36 + this.name = 'ComposioSensitiveFilePathBlockedError';
37 + }
38 +}
39 +
40 +/**
41 + * Thrown when a `beforeFileUpload` hook returns `false`.
42 + */
43 +export class ComposioFileUploadAbortedError extends ComposioFileUploadError {
44 + constructor(message: string, options: ComposioErrorOptions = {}) {
45 + super(message, {
46 + ...options,
47 + code: FileModifierErrorCodes.FILE_UPLOAD_ABORTED,
48 + possibleFixes: options.possibleFixes ?? [
49 + 'Change beforeFileUpload to return a file path to upload, or allow the upload to proceed',
50 + ],
51 + });
52 + this.name = 'ComposioFileUploadAbortedError';
53 + }
54 +}
ts/packages/core/src/errors/index.ts
+3
@@ -36,3 +36,6 @@ export * from './TriggerErrors';
36
37 // Remote File Errors
38 export * from './RemoteFileErrors';
39 +
40 +// File modifier / auto upload
41 +export * from './FileModifierErrors';
ts/packages/core/src/models/Files.node.ts
+15 -1
@@ -11,7 +11,19 @@ import { downloadFileFromS3, getFileDataAfterUploadingToS3 } from '../utils/file
11 import { telemetry } from '../telemetry/Telemetry';
12
13 export class Files {
14 - constructor(private readonly client: ComposioClient) {
14 + private readonly fileUploadPathOptions: {
15 + sensitiveFileUploadProtection?: boolean;
16 + fileUploadPathDenySegments?: string[];
17 + };
18 +
19 + constructor(
20 + private readonly client: ComposioClient,
21 + fileUploadPathOptions: {
22 + sensitiveFileUploadProtection?: boolean;
23 + fileUploadPathDenySegments?: string[];
24 + } = {}
25 + ) {
26 + this.fileUploadPathOptions = fileUploadPathOptions;
27 telemetry.instrument(this, 'Files');
28 }
29
@@ -45,6 +57,8 @@ export class Files {
57 toolSlug,
58 toolkitSlug,
59 client: this.client,
60 + sensitiveFileUploadProtection: this.fileUploadPathOptions.sensitiveFileUploadProtection,
61 + fileUploadPathDenySegments: this.fileUploadPathOptions.fileUploadPathDenySegments,
62 });
63 return fileData;
64 }
ts/packages/core/src/models/Tools.ts
+19 -9
@@ -33,7 +33,6 @@ import { CustomTools } from './CustomTools';
33 import { CustomToolInputParameter, CustomToolOptions } from '../types/customTool.types';
34 import {
35 afterExecuteModifier,
36 - beforeExecuteModifier,
36 ExecuteToolModifiers,
37 SessionExecuteMetaModifiers,
38 ProviderOptions,
@@ -71,6 +70,10 @@ export class Tools<
70 private provider: TProvider;
71 private autoUploadDownloadFiles: boolean;
72 private toolkitVersions: ToolkitVersionParam;
73 + private fileUploadPathOptions: {
74 + sensitiveFileUploadProtection?: boolean;
75 + fileUploadPathDenySegments?: string[];
76 + };
77
78 constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {
79 if (!client) {
@@ -86,6 +89,10 @@ export class Tools<
89 this.autoUploadDownloadFiles =
90 config?.autoUploadDownloadFiles ?? CONFIG_DEFAULTS.autoUploadDownloadFiles;
91 this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
92 + this.fileUploadPathOptions = {
93 + sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection,
94 + fileUploadPathDenySegments: config?.fileUploadPathDenySegments,
95 + };
96 // Bind the execute method to ensure correct 'this' context
97 this.execute = this.execute.bind(this);
98 // Set the execute method for the provider.
@@ -149,7 +156,7 @@ export class Tools<
156 */
157 private async applyDefaultSchemaModifiers(tools: Tool[]): Promise<Tool[]> {
158 if (this.autoUploadDownloadFiles) {
152 - const fileToolModifier = new FileToolModifier(this.client);
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)
@@ -179,12 +186,15 @@ export class Tools<
186 toolkitSlug: string;
187 params: ToolExecuteParams;
188 },
182 - modifier?: beforeExecuteModifier
189 + modifiers?: ExecuteToolModifiers
190 ): Promise<ToolExecuteParams> {
191 let modifiedParams = params;
192 // if auto upload download files is enabled, upload the files to the Composio API
193 if (this.autoUploadDownloadFiles) {
187 - const fileToolModifier = new FileToolModifier(this.client);
194 + const fileToolModifier = new FileToolModifier(this.client, {
195 + ...this.fileUploadPathOptions,
196 + beforeFileUpload: modifiers?.beforeFileUpload,
197 + });
198 modifiedParams = await fileToolModifier.fileUploadModifier(tool, {
199 toolSlug,
200 toolkitSlug,
@@ -192,9 +202,9 @@ export class Tools<
202 });
203 }
204 // apply the before execute modifiers
195 - if (modifier) {
196 - if (typeof modifier === 'function') {
197 - modifiedParams = await modifier({
205 + if (modifiers?.beforeExecute) {
206 + if (typeof modifiers.beforeExecute === 'function') {
207 + modifiedParams = await modifiers.beforeExecute({
208 toolSlug,
209 toolkitSlug,
210 params: modifiedParams,
@@ -230,7 +240,7 @@ export class Tools<
240 let modifiedResult = result;
241 // if auto upload download files is enabled, download the files from the Composio API
242 if (this.autoUploadDownloadFiles) {
233 - const fileToolModifier = new FileToolModifier(this.client);
243 + const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions);
244 modifiedResult = await fileToolModifier.fileDownloadModifier(tool, {
245 toolSlug,
246 toolkitSlug,
@@ -921,7 +931,7 @@ export class Tools<
931 toolkitSlug,
932 params: executeParams.data,
933 },
924 - modifiers?.beforeExecute
934 + modifiers
935 );
936
937 // Execute the tool (custom or composio)
ts/packages/core/src/types/modifiers.types.ts
+15 -2
@@ -179,6 +179,19 @@ export type afterExecuteModifier = (context: {
179 result: ToolExecuteResponse;
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.
186 + */
187 +export type beforeFileUploadModifier = (context: {
188 + path: string;
189 + toolSlug: string;
190 + toolkitSlug: string;
191 +}) => Promise<string | false> | string | false;
192 +
193 +type BeforeFileUploadHook = { beforeFileUpload?: beforeFileUploadModifier };
194 +
195 /**
196 * Modifier for altering the tool schema before it's exposed to consumers.
197 *
@@ -349,7 +362,7 @@ export type ToolOptions = {
362 * This allows customizing input/output parameters, descriptions, and other metadata.
363 */
364 modifySchema?: TransformToolSchemaModifier;
352 -};
365 +} & BeforeFileUploadHook;
366
367 /**
368 * Options for configuring tool execution behavior.
@@ -390,7 +403,7 @@ export type ExecuteToolModifiers = {
403 * This allows transforming the response or implementing custom error handling.
404 */
405 afterExecute?: afterExecuteModifier;
393 -};
406 +} & BeforeFileUploadHook;
407
408 /**
409 * Type alias for meta tool execution arguments.
ts/packages/core/src/utils/fileUtils.node.ts
+31 -5
@@ -7,6 +7,26 @@ import logger from './logger';
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 +
12 +/**
13 + * Options for {@link getFileDataAfterUploadingToS3} (S3 presigned upload from local path, URL, or File).
14 + */
15 +export type GetFileDataAfterUploadingToS3Options = {
16 + toolSlug: string;
17 + toolkitSlug: string;
18 + client: ComposioClient;
19 + /**
20 + * When false, skips the sensitive-path blocklist. URLs and {@link File} objects are never checked.
21 + * @default true
22 + */
23 + sensitiveFileUploadProtection?: boolean;
24 + /**
25 + * Extra path segments (one directory/file component) to block anywhere in the resolved path;
26 + * merged with the built-in list.
27 + */
28 + fileUploadPathDenySegments?: string[];
29 +};
30
31 // Helper function to get file extension from MIME type
32 const getExtensionFromMimeType = (mimeType: string): string => {
@@ -222,16 +242,22 @@ export const getFileDataAfterUploadingToS3 = async (
242 toolSlug,
243 toolkitSlug,
244 client,
225 - }: {
226 - toolSlug: string;
227 - toolkitSlug: string;
228 - client: ComposioClient;
229 - }
245 + sensitiveFileUploadProtection,
246 + fileUploadPathDenySegments,
247 + }: GetFileDataAfterUploadingToS3Options
248 ): Promise<FileUploadData> => {
249 if (!file) {
250 throw new Error('Either path or blob must be provided');
251 }
252
253 + if (
254 + sensitiveFileUploadProtection !== false &&
255 + typeof file === 'string' &&
256 + !file.startsWith('http')
257 + ) {
258 + assertSafeFileUploadPath(file, { additionalDenySegments: fileUploadPathDenySegments });
259 + }
260 +
261 const fileData = await readFile(file);
262 logger.debug(`Uploading file to S3...`);
263 const s3key = await uploadFileToS3(
ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts
+89 -6
@@ -6,8 +6,17 @@ import {
6 } from '../../types/tool.types';
7 import ComposioClient from '@composio/client';
8 import logger from '../logger';
9 -import { ComposioFileUploadError } from '../../errors/FileModifierErrors';
10 -import { downloadFileFromS3, getFileDataAfterUploadingToS3 } from '../fileUtils.node';
9 +import {
10 + ComposioFileUploadAbortedError,
11 + ComposioFileUploadError,
12 + ComposioSensitiveFilePathBlockedError,
13 +} from '../../errors/FileModifierErrors';
14 +import type { beforeFileUploadModifier } from '../../types/modifiers.types';
15 +import {
16 + downloadFileFromS3,
17 + getFileDataAfterUploadingToS3,
18 + type GetFileDataAfterUploadingToS3Options,
19 +} from '../fileUtils.node';
20 import {
21 isPlainObject,
22 transformProperties,
@@ -28,7 +37,12 @@ const hydrateFiles = async (
37 toolSlug: string;
38 toolkitSlug: string;
39 client: ComposioClient;
31 - }
40 + } & Pick<
41 + GetFileDataAfterUploadingToS3Options,
42 + 'sensitiveFileUploadProtection' | 'fileUploadPathDenySegments'
43 + > & {
44 + beforeFileUpload?: beforeFileUploadModifier;
45 + }
46 ): Promise<unknown> => {
47 // ──────────────────────────────────────────────────────────────────────────
48 // 1. Direct file upload
@@ -37,11 +51,65 @@ const hydrateFiles = async (
51 // Upload only if the runtime value is a string (i.e., a local path) or blob
52 if (typeof value !== 'string' && !(value instanceof File)) return value;
53
40 - logger.debug(`Uploading file "${value}"`);
54 + const runBeforeFileUpload = async (path: string): Promise<string> => {
55 + if (!ctx.beforeFileUpload) {
56 + return path;
57 + }
58 + const out = await ctx.beforeFileUpload({
59 + path,
60 + toolSlug: ctx.toolSlug,
61 + toolkitSlug: ctx.toolkitSlug,
62 + });
63 + if (out === false) {
64 + throw new ComposioFileUploadAbortedError(
65 + 'File upload was aborted because beforeFileUpload returned false.'
66 + );
67 + }
68 + return out;
69 + };
70 +
71 + if (typeof value === 'string') {
72 + const pathOrUrl = await runBeforeFileUpload(value);
73 + logger.debug(`Uploading file "${pathOrUrl}"`);
74 + return getFileDataAfterUploadingToS3(pathOrUrl, {
75 + toolSlug: ctx.toolSlug,
76 + toolkitSlug: ctx.toolkitSlug,
77 + client: ctx.client,
78 + sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
79 + fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
80 + });
81 + }
82 +
83 + // File
84 + if (ctx.beforeFileUpload) {
85 + const out = await ctx.beforeFileUpload({
86 + path: value.name,
87 + toolSlug: ctx.toolSlug,
88 + toolkitSlug: ctx.toolkitSlug,
89 + });
90 + if (out === false) {
91 + throw new ComposioFileUploadAbortedError(
92 + 'File upload was aborted because beforeFileUpload returned false.'
93 + );
94 + }
95 + if (typeof out === 'string' && out !== value.name) {
96 + logger.debug(`Uploading file from path "${out}" (replaced File: ${value.name})`);
97 + return getFileDataAfterUploadingToS3(out, {
98 + toolSlug: ctx.toolSlug,
99 + toolkitSlug: ctx.toolkitSlug,
100 + client: ctx.client,
101 + sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
102 + fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
103 + });
104 + }
105 + }
106 + logger.debug(`Uploading file "${value.name}"`);
107 return getFileDataAfterUploadingToS3(value, {
108 toolSlug: ctx.toolSlug,
109 toolkitSlug: ctx.toolkitSlug,
110 client: ctx.client,
111 + sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
112 + fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
113 });
114 }
115
@@ -234,9 +302,17 @@ const hydrateDownloads = async (
302
303 export class FileToolModifier {
304 private client: ComposioClient;
237 -
238 - constructor(client: ComposioClient) {
305 + private fileUploadPathOptions: Pick<
306 + GetFileDataAfterUploadingToS3Options,
307 + 'sensitiveFileUploadProtection' | 'fileUploadPathDenySegments'
308 + > & { beforeFileUpload?: beforeFileUploadModifier };
309 +
310 + constructor(
311 + client: ComposioClient,
312 + fileUploadPathOptions: FileToolModifier['fileUploadPathOptions'] = {}
313 + ) {
314 this.client = client;
315 + this.fileUploadPathOptions = fileUploadPathOptions;
316 }
317
318 async modifyToolSchema(toolSlug: string, toolkitSlug: string, schema: Tool): Promise<Tool> {
@@ -274,9 +350,16 @@ export class FileToolModifier {
350 toolSlug,
351 toolkitSlug,
352 client: this.client,
353 + ...this.fileUploadPathOptions,
354 });
355 return { ...params, arguments: newArgs as ToolExecuteParams['arguments'] };
356 } catch (error) {
357 + if (
358 + error instanceof ComposioSensitiveFilePathBlockedError ||
359 + error instanceof ComposioFileUploadAbortedError
360 + ) {
361 + throw error;
362 + }
363 throw new ComposioFileUploadError('Failed to upload file', {
364 cause: error,
365 });
ts/packages/core/src/utils/sensitiveFileUploadPaths.node.ts new
+105
@@ -0,0 +1,105 @@
1 +/**
2 + * Blocks accidental upload of local files from well-known secret/credential locations
3 + * during auto file upload (and {@link getFileDataAfterUploadingToS3}).
4 + */
5 +import * as path from 'node:path';
6 +import fs from 'node:fs';
7 +import { ComposioSensitiveFilePathBlockedError } from '../errors/FileModifierErrors';
8 +
9 +/**
10 + * Path segments (a single path component) that indicate a sensitive directory when
11 + * they appear anywhere in a resolved local path. Compared case-insensitively on Windows.
12 + */
13 +export const BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS: readonly string[] = [
14 + '.ssh',
15 + '.aws',
16 + '.azure',
17 + '.gnupg',
18 + '.kube',
19 + '.docker',
20 + '.claude', // may contain API keys and project context read by assistants
21 + '.password-store',
22 + 'keychains', // e.g. ~/Library/Keychains
23 +];
24 +
25 +const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;
26 +/** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */
27 +const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;
28 +
29 +/**
30 + * Returns normalized path segments, resolving symlinks when the path exists.
31 + */
32 +function normalizePathSegments(filePath: string): string[] {
33 + const absolute = path.resolve(filePath);
34 + let resolved = absolute;
35 + try {
36 + if (fs.existsSync(absolute)) {
37 + resolved = fs.realpathSync(absolute);
38 + }
39 + } catch {
40 + // If realpath fails (e.g. race), use resolved path
41 + }
42 + return resolved.split(/[/\\]+/).filter(Boolean);
43 +}
44 +
45 +/**
46 + * True if the path is under a built-in or extra deny segment, or the basename
47 + * looks like an env / netrc / default SSH private key name.
48 + */
49 +export function isBlockedSensitiveFileUploadPath(
50 + filePath: string,
51 + additionalDenySegments?: string[]
52 +): boolean {
53 + return getSensitiveFileUploadPathBlockReason(filePath, additionalDenySegments) != null;
54 +}
55 +
56 +function getSensitiveFileUploadPathBlockReason(
57 + filePath: string,
58 + additionalDenySegments?: string[]
59 +): string | null {
60 + const segments = normalizePathSegments(filePath);
61 + const isWin = process.platform === 'win32';
62 + const deny = new Set(
63 + [
64 + ...BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,
65 + ...(additionalDenySegments ?? []).map(s => s.trim()).filter(Boolean),
66 + ].map(s => (isWin ? s.toLowerCase() : s))
67 + );
68 +
69 + // Windows: compare segments case-insensitively; map once instead of toLowerCase per iteration.
70 + const segmentsForMatch = isWin ? segments.map(s => s.toLowerCase()) : segments;
71 + for (let i = 0; i < segments.length; i++) {
72 + if (deny.has(segmentsForMatch[i]!)) {
73 + return `path segment "${segments[i]}" is in the sensitive file upload denylist`;
74 + }
75 + }
76 +
77 + const basename = segments.length > 0 ? segments[segments.length - 1] : '';
78 + if (basename) {
79 + if (SECRET_LIKE_BASENAME.test(basename) || DEFAULT_PRIVATE_KEY_BASENAME.test(basename)) {
80 + return `file name "${basename}" looks like a credential, env, or private key file`;
81 + }
82 + if (basename.toLowerCase() === 'credentials') {
83 + return 'file name "credentials" is often used for cloud/API credential stores';
84 + }
85 + }
86 + return null;
87 +}
88 +
89 +/**
90 + * @throws {ComposioSensitiveFilePathBlockedError} if the path is not allowed
91 + */
92 +export function assertSafeFileUploadPath(
93 + filePath: string,
94 + options?: { additionalDenySegments?: string[] }
95 +): void {
96 + const reason = getSensitiveFileUploadPathBlockReason(filePath, options?.additionalDenySegments);
97 + if (reason) {
98 + throw new ComposioSensitiveFilePathBlockedError(
99 + `Refusing to upload: ${reason}. ` +
100 + `To upload from this path anyway, set sensitiveFileUploadProtection: false on Composio ` +
101 + `(not recommended) or use a copy outside sensitive locations.`,
102 + { meta: { filePath, reason } }
103 + );
104 + }
105 +}
ts/packages/core/test/tools/fileModifiers.test.ts
+57 -1
@@ -2,7 +2,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import { FileToolModifier } from '#file_tool_modifier';
3 import ComposioClient from '@composio/client';
4 import { Tool } from '../../src/types/tool.types';
5 -import { ComposioFileUploadError } from '../../src/errors/FileModifierErrors';
5 +import {
6 + ComposioFileUploadAbortedError,
7 + ComposioFileUploadError,
8 +} from '../../src/errors/FileModifierErrors';
9 import * as fileUtils from '../../src/utils/fileUtils.node';
10 import { Tools } from '../../src/models/Tools';
11 import { createTestContext, setupTest, mockToolExecution } from '../utils/toolExecuteUtils';
@@ -330,6 +333,59 @@ describe('FileToolModifier', () => {
333 expect(result.arguments?.text).toBe('some text');
334 });
335
336 + it('should call beforeFileUpload and use returned path for string files', async () => {
337 + const mockFileData = {
338 + name: 'file.txt',
339 + mimetype: 'text/plain',
340 + s3key: 'uploads/file.txt',
341 + };
342 + vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockResolvedValue(mockFileData);
343 +
344 + const withHook = new FileToolModifier(mockClient, {
345 + beforeFileUpload: async ({ path, toolSlug, toolkitSlug }) => {
346 + expect(toolSlug).toBe('test-tool');
347 + expect(toolkitSlug).toBe('test-toolkit');
348 + return path.replace('original', 'rewritten');
349 + },
350 + });
351 +
352 + const params = {
353 + arguments: { file: '/path/to/original.txt' },
354 + userId: 'test-user',
355 + };
356 +
357 + const result = await withHook.fileUploadModifier(mockTool, {
358 + toolSlug: 'test-tool',
359 + toolkitSlug: 'test-toolkit',
360 + params,
361 + });
362 +
363 + expect(fileUtils.getFileDataAfterUploadingToS3).toHaveBeenCalledWith(
364 + '/path/to/rewritten.txt',
365 + {
366 + toolSlug: 'test-tool',
367 + toolkitSlug: 'test-toolkit',
368 + client: mockClient,
369 + }
370 + );
371 + expect(result.arguments?.file).toEqual(mockFileData);
372 + });
373 +
374 + it('should throw ComposioFileUploadAbortedError when beforeFileUpload returns false', async () => {
375 + const withHook = new FileToolModifier(mockClient, {
376 + beforeFileUpload: async () => false,
377 + });
378 +
379 + await expect(
380 + withHook.fileUploadModifier(mockTool, {
381 + toolSlug: 'test-tool',
382 + toolkitSlug: 'test-toolkit',
383 + params: { arguments: { file: '/any/path' }, userId: 'u' },
384 + })
385 + ).rejects.toThrow(ComposioFileUploadAbortedError);
386 + expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
387 + });
388 +
389 it('should throw ComposioFileUploadError on upload failure', async () => {
390 vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockRejectedValue(
391 new Error('Upload failed')
ts/packages/core/test/utils/fileUtils.test.ts
+21 -9
@@ -1,6 +1,8 @@
1 import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 +import * as path from 'node:path';
3 import { getFileDataAfterUploadingToS3, downloadFileFromS3 } from '../../src/utils/fileUtils.node';
4 import ComposioClient from '@composio/client';
5 +import { ComposioSensitiveFilePathBlockedError } from '../../src/errors/FileModifierErrors';
6
7 // Mock the uuid module
8 vi.mock('../../src/utils/uuid', () => ({
@@ -30,15 +32,15 @@ vi.mock('os', () => ({
32 homedir: vi.fn(() => '/home/test'),
33 }));
34
33 -// Mock path module
34 -vi.mock('path', () => ({
35 - default: {
36 - join: vi.fn((...args) => args.join('/')),
37 - basename: vi.fn(path => path.split('/').pop()),
38 - },
39 - join: vi.fn((...args) => args.join('/')),
40 - basename: vi.fn(path => path.split('/').pop()),
41 -}));
35 +// Mock path module (keep resolve/join for sensitive path checks; basename stays mocked for fileUtils)
36 +vi.mock('path', async importOriginal => {
37 + const actual = await importOriginal<typeof import('node:path')>();
38 + return {
39 + ...actual,
40 + default: actual,
41 + basename: vi.fn((p: string) => p.split('/').pop() ?? p),
42 + };
43 +});
44
45 // Mock global fetch
46 const mockFetch = vi.fn();
@@ -367,6 +369,16 @@ describe('fileUtils', () => {
369 // Note: Local file handling tests are covered in the existing fileModifiers.test.ts
370
371 describe('Error handling', () => {
372 + it('refuses sensitive local paths before read or S3 (built-in denylist)', async () => {
373 + await expect(
374 + getFileDataAfterUploadingToS3(path.join('/home/test', '.aws', 'creds'), {
375 + toolSlug: 'test-tool',
376 + toolkitSlug: 'test-toolkit',
377 + client: mockClient,
378 + })
379 + ).rejects.toThrow(ComposioSensitiveFilePathBlockedError);
380 + });
381 +
382 it('should handle fetch errors for URLs', async () => {
383 mockFetch.mockResolvedValue({
384 ok: false,
ts/packages/core/test/utils/sensitiveFileUploadPaths.test.ts new
+65
@@ -0,0 +1,65 @@
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 {
6 + assertSafeFileUploadPath,
7 + isBlockedSensitiveFileUploadPath,
8 +} from '../../src/utils/sensitiveFileUploadPaths.node';
9 +
10 +describe('sensitiveFileUploadPaths', () => {
11 + it('allows normal project files', () => {
12 + const p = path.join('/tmp', 'composio-test', 'document.pdf');
13 + expect(isBlockedSensitiveFileUploadPath(p)).toBe(false);
14 + expect(() => assertSafeFileUploadPath(p)).not.toThrow();
15 + });
16 +
17 + it('blocks common credential directory segments', () => {
18 + expect(isBlockedSensitiveFileUploadPath(path.join(os.homedir(), '.aws', 'credentials'))).toBe(
19 + true
20 + );
21 + expect(isBlockedSensitiveFileUploadPath(path.join(os.homedir(), '.ssh', 'id_ed25519'))).toBe(
22 + true
23 + );
24 + expect(
25 + isBlockedSensitiveFileUploadPath(path.join(os.homedir(), '.claude', 'settings.json'))
26 + ).toBe(true);
27 + });
28 +
29 + it('blocks .env-style basenames', () => {
30 + expect(isBlockedSensitiveFileUploadPath(path.join('/app', 'repo', '.env'))).toBe(true);
31 + expect(isBlockedSensitiveFileUploadPath(path.join('/app', 'repo', '.env.local'))).toBe(true);
32 + });
33 +
34 + it('blocks default private key basenames (defense in depth)', () => {
35 + expect(isBlockedSensitiveFileUploadPath(path.join('/tmp', 'id_ed25519'))).toBe(true);
36 + });
37 +
38 + it('does not block public key files by basename', () => {
39 + expect(isBlockedSensitiveFileUploadPath(path.join('/tmp', 'id_ed25519.pub'))).toBe(false);
40 + });
41 +
42 + it('honors additional deny segments from config', () => {
43 + expect(
44 + isBlockedSensitiveFileUploadPath(path.join('/data', 'secrets', 'x.txt'), ['secrets'])
45 + ).toBe(true);
46 + expect(isBlockedSensitiveFileUploadPath(path.join('/data', 'ok', 'x.txt'), ['secrets'])).toBe(
47 + false
48 + );
49 + });
50 +
51 + it('blocks after realpath resolves a symlink into a sensitive directory', () => {
52 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-symlink-'));
53 + try {
54 + const awsDir = path.join(root, 'nested', '.aws');
55 + mkdirSync(awsDir, { recursive: true });
56 + const target = path.join(awsDir, 'creds');
57 + writeFileSync(target, 'x');
58 + const link = path.join(root, 'innocent-name');
59 + symlinkSync(target, link);
60 + expect(isBlockedSensitiveFileUploadPath(link)).toBe(true);
61 + } finally {
62 + rmSync(root, { recursive: true, force: true });
63 + }
64 + });
65 +});
uv.lock
+13 -13
@@ -591,7 +591,7 @@ wheels = [
591
592 [[package]]
593 name = "composio"
594 -version = "0.11.2"
594 +version = "0.11.6"
595 source = { virtual = "python" }
596 dependencies = [
597 { name = "composio-client" },
@@ -621,7 +621,7 @@ dev = [
621
622 [package.metadata]
623 requires-dist = [
624 - { name = "composio-client", specifier = "==1.28.0" },
624 + { name = "composio-client", specifier = "==1.33.0" },
625 { name = "json-schema-to-pydantic", specifier = ">=0.4.8" },
626 { name = "openai" },
627 { name = "pydantic", specifier = ">=2.6.4" },
@@ -648,7 +648,7 @@ dev = [
648
649 [[package]]
650 name = "composio-anthropic"
651 -version = "0.11.2"
651 +version = "0.11.6"
652 source = { virtual = "python/providers/anthropic" }
653 dependencies = [
654 { name = "anthropic" },
@@ -663,7 +663,7 @@ requires-dist = [
663
664 [[package]]
665 name = "composio-client"
666 -version = "1.28.0"
666 +version = "1.33.0"
667 source = { registry = "https://pypi.org/simple" }
668 dependencies = [
669 { name = "anyio" },
@@ -673,14 +673,14 @@ dependencies = [
673 { name = "sniffio" },
674 { name = "typing-extensions" },
675 ]
676 -sdist = { url = "https://files.pythonhosted.org/packages/99/45/5f063d364bef7879252c3dab517a42a9f3fdf1ad8943895f5b718c27fd31/composio_client-1.28.0.tar.gz", hash = "sha256:787869c1fba543f07aa26d1f64e5f37e4909465b37af24ec4b5a01fd73115045", size = 209918 }
676 +sdist = { url = "https://files.pythonhosted.org/packages/4b/11/88d09721f03431deb8b055fe39cedb79697e5a72d4342fa033d277b1eb70/composio_client-1.33.0.tar.gz", hash = "sha256:3b92400383ca2454a361e3ad8d55e2b447b47ed3c4cd4910f61466e5933554c1", size = 225669 }
677 wheels = [
678 - { url = "https://files.pythonhosted.org/packages/4e/8c/901f59aaf8674f8bda6da1fbae087eb5209f11a9b26f6118c2be49702d0c/composio_client-1.28.0-py3-none-any.whl", hash = "sha256:8f037d8e66b3bfb3aa701b4d26c8a242d22638031b938a363874ebc41e4710ee", size = 239827 },
678 + { url = "https://files.pythonhosted.org/packages/93/bc/83efc07964e39109c4471f8873dda98cd16137c8e4e2d4456a8a5d8f9c42/composio_client-1.33.0-py3-none-any.whl", hash = "sha256:8c01f096772272398760f5c553b3444b5706e346b294856f613b092f1d3afd6b", size = 252699 },
679 ]
680
681 [[package]]
682 name = "composio-crewai"
683 -version = "0.11.2"
683 +version = "0.11.6"
684 source = { virtual = "python/providers/crewai" }
685 dependencies = [
686 { name = "composio" },
@@ -695,7 +695,7 @@ requires-dist = [
695
696 [[package]]
697 name = "composio-gemini"
698 -version = "0.11.2"
698 +version = "0.11.6"
699 source = { virtual = "python/providers/gemini" }
700 dependencies = [
701 { name = "composio" },
@@ -710,7 +710,7 @@ requires-dist = [
710
711 [[package]]
712 name = "composio-google"
713 -version = "0.11.2"
713 +version = "0.11.6"
714 source = { virtual = "python/providers/google" }
715 dependencies = [
716 { name = "composio" },
@@ -725,7 +725,7 @@ requires-dist = [
725
726 [[package]]
727 name = "composio-google-adk"
728 -version = "0.11.2"
728 +version = "0.11.6"
729 source = { virtual = "python/providers/google_adk" }
730 dependencies = [
731 { name = "composio" },
@@ -740,7 +740,7 @@ requires-dist = [
740
741 [[package]]
742 name = "composio-langchain"
743 -version = "0.11.2"
743 +version = "0.11.6"
744 source = { virtual = "python/providers/langchain" }
745 dependencies = [
746 { name = "composio" },
@@ -755,7 +755,7 @@ requires-dist = [
755
756 [[package]]
757 name = "composio-openai"
758 -version = "0.11.2"
758 +version = "0.11.6"
759 source = { virtual = "python/providers/openai" }
760 dependencies = [
761 { name = "composio" },
@@ -770,7 +770,7 @@ requires-dist = [
770
771 [[package]]
772 name = "composio-openai-agents"
773 -version = "0.11.2"
773 +version = "0.11.6"
774 source = { virtual = "python/providers/openai_agents" }
775 dependencies = [
776 { name = "composio" },