Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
security(core): sensitive path blocklist + beforeFileUpload hook (patch) (#3262)
Musthaq Ahamad27ed0c9bd6f9
diff --git a/.changeset/security-file-upload-hardening.md b/.changeset/security-file-upload-hardening.mdnew file mode 100644index 000000000..ace3cc5af--- /dev/null+++ b/.changeset/security-file-upload-hardening.md@@ -0,0 +1,7 @@+---+"@composio/core": patch+---++**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`.++Adds an optional `beforeFileUpload` hook (e.g. on `composio.tools.get`) to rewrite paths, return `false` to abort, or throw. New errors: `ComposioSensitiveFilePathBlockedError`, `ComposioFileUploadAbortedError`.diff --git a/docs/content/changelog/04-23-26-file-upload-security.mdx b/docs/content/changelog/04-23-26-file-upload-security.mdxnew file mode 100644index 000000000..e2b28f0ae--- /dev/null+++ b/docs/content/changelog/04-23-26-file-upload-security.mdx@@ -0,0 +1,143 @@+---+title: 'SDK file upload hardening: sensitive path blocking and upload hooks'+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.'+date: '2026-04-23'+---++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.++**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.++### SDK versions++| SDK | Version (includes this behavior) |+| ---------- | --------------------------------- |+| TypeScript | `@composio/core` v0.6.11 or later |+| Python | `composio` v0.11.6 or later |++### What changed++- **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.+- **Extra denylist segments** — You can add path component names to merge with the built-in list (for example a proprietary secrets directory name).+- **`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).+- **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.+- **Python: modifier order** — `substitute_file_uploads` runs before `before_execute` modifiers, matching TypeScript behavior (including Tool Router `execute_meta`).++### Examples++#### Configure the client (defaults + extra denylist segments)++Keep the built-in blocklist enabled and add path **component** names (anywhere in the resolved path) that your app treats as secret:++<Tabs groupId="language" items={['TypeScript', 'Python']} persist>+<Tab value="TypeScript">+```typescript+// @noErrors+import { Composio } from '@composio/core';++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY!,+ sensitiveFileUploadProtection: true,+ fileUploadPathDenySegments: ['company-secrets', 'private-keys'],+});+```+</Tab>+<Tab value="Python">+```python+from composio import Composio++composio = Composio(+ api_key="your_composio_key",+ sensitive_file_upload_protection=True,+ file_upload_path_deny_segments=("company-secrets", "private-keys"),+)+```+</Tab>+</Tabs>++#### Run a hook before each automatic file read++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`:++<Tabs groupId="language" items={['TypeScript', 'Python']} persist>+<Tab value="TypeScript">+```typescript+// @noErrors+import { Composio, type beforeFileUploadModifier } from '@composio/core';+import path from 'node:path';++const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY! });++const beforeFileUpload: beforeFileUploadModifier = async ctx => {+ // e.g. log, rewrite path, or return false to block+ return ctx.path;+};++await composio.tools.execute(+ 'GOOGLEDRIVE_UPLOAD_FILE',+ {+ userId: 'user-123',+ arguments: { file_to_upload: path.join(__dirname, 'document.pdf') },+ dangerouslySkipVersionCheck: true,+ },+ { beforeFileUpload },+);+```+</Tab>+<Tab value="Python">+```python+import os++from composio import Composio, before_file_upload+++@before_file_upload(tools=["GOOGLEDRIVE_UPLOAD_FILE"])+def before_upload(path: str, tool: str, toolkit: str) -> "str | bool":+ return path+++composio = Composio()++composio.tools.execute(+ "GOOGLEDRIVE_UPLOAD_FILE",+ {"file_to_upload": os.path.join(os.getcwd(), "document.pdf")},+ user_id="user-123",+ modifiers=[before_upload],+)+```+</Tab>+</Tabs>++### Opting out++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.++<Tabs groupId="language" items={['TypeScript', 'Python']} persist>+<Tab value="TypeScript">+```typescript+// @noErrors+import { Composio } from '@composio/core';++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY!,+ sensitiveFileUploadProtection: false,+});+```+</Tab>+<Tab value="Python">+```python+from composio import Composio++composio = Composio(+ api_key="your_composio_key",+ sensitive_file_upload_protection=False,+)+```+</Tab>+</Tabs>++### Where to read more++- [Executing tools: automatic file handling and security options](/docs/tools-direct/executing-tools#security-for-local-file-paths) — configuration and code patterns.+- [TypeScript `Composio` client](/reference/sdk-reference/typescript/composio#file-upload-security) — related constructor options in the reference.+- TypeScript SDK (repository): `ts/docs/advanced/auto-upload-download.md` — extended guide with error types and edge cases.diff --git a/docs/content/docs/glossary.mdx b/docs/content/docs/glossary.mdxindex 845af3c93..d85a98019 100644--- a/docs/content/docs/glossary.mdx+++ b/docs/content/docs/glossary.mdx@@ -60,7 +60,7 @@ A set of tools included in every session, including `COMPOSIO_SEARCH_TOOLS`, `CO</GlossaryTerm><GlossaryTerm name="Modifiers">-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.+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.</GlossaryTerm><GlossaryTerm name="Native Tools">diff --git a/docs/content/docs/tools-direct/executing-tools.mdx b/docs/content/docs/tools-direct/executing-tools.mdxindex acd3e21ad..f3f99fcfc 100644--- a/docs/content/docs/tools-direct/executing-tools.mdx+++ b/docs/content/docs/tools-direct/executing-tools.mdx@@ -385,6 +385,89 @@ console.log(result);</Tab></Tabs>+## Security for local file paths++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.++<Callout type="warn">+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.+</Callout>++**Constructor options (defaults protect sensitive locations):**++<Tabs groupId="language" items={['TypeScript', 'Python']} persist>+ <Tab value="TypeScript">+```typescript+// @errors: 2353+import { Composio } from '@composio/core';++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY!,+ // default true — block paths under built-in segments (e.g. .ssh, .aws) and risky basenames+ sensitiveFileUploadProtection: true,+ // optional: extra path *components* anywhere in the resolved path, merged with the built-in list+ fileUploadPathDenySegments: ['internal-only-secrets'],+});+```+ </Tab>+ <Tab value="Python">+```python+from composio import Composio++composio = Composio(+ api_key="your_composio_key",+ sensitive_file_upload_protection=True,+ file_upload_path_deny_segments=("internal-only-secrets",),+)+```+ </Tab>+</Tabs>++**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)).++<Tabs groupId="language" items={['TypeScript', 'Python']} persist>+ <Tab value="TypeScript">+```typescript+// @noErrors+import { Composio, type beforeFileUploadModifier } from '@composio/core';+import path from 'node:path';+const composio = new Composio({ apiKey: 'your_api_key' });+const beforeFileUpload: beforeFileUploadModifier = async ctx => ctx.path;+// ---cut---+await composio.tools.execute(+ 'GOOGLEDRIVE_UPLOAD_FILE',+ {+ userId: 'user-4235***',+ arguments: { file_to_upload: path.join(__dirname, 'document.pdf') },+ dangerouslySkipVersionCheck: true,+ },+ { beforeFileUpload }+);+```+ </Tab>+ <Tab value="Python">+```python+import os+from composio import Composio, before_file_upload++@before_file_upload(tools=["GOOGLEDRIVE_UPLOAD_FILE"])+def audit_path(path: str, tool: str, toolkit: str) -> str | bool:+ return path++composio = Composio()++composio.tools.execute(+ "GOOGLEDRIVE_UPLOAD_FILE",+ {"file_to_upload": os.path.join(os.getcwd(), "document.pdf")},+ user_id="user-1235***",+ modifiers=[audit_path],+)+```+ </Tab>+</Tabs>++**Errors:** `ComposioSensitiveFilePathBlockedError` / `SensitiveFilePathBlockedError` when a path is blocked; `ComposioFileUploadAbortedError` / `FileUploadAbortedError` when the hook returns `false` (or equivalent abort).+### Disabling Auto File HandlingYou can disable automatic file handling when initializing the TypeScript SDK. When disabled, handle file uploads and downloads manually using `files.upload` and `files.download`:diff --git a/docs/content/docs/tools-direct/modify-tool-behavior/before-execution-modifiers.mdx b/docs/content/docs/tools-direct/modify-tool-behavior/before-execution-modifiers.mdxindex ae9030b44..cc761c650 100644--- a/docs/content/docs/tools-direct/modify-tool-behavior/before-execution-modifiers.mdx+++ b/docs/content/docs/tools-direct/modify-tool-behavior/before-execution-modifiers.mdx@@ -178,6 +178,32 @@ const agenticTools = await composio.tools.get(</Tab></Tabs>+## Before file upload (Python)++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=...)`.++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.++```python+from composio import Composio, before_file_upload++@before_file_upload(tools=["GOOGLEDRIVE_UPLOAD_FILE"])+def audit_path(path: str, tool: str, toolkit: str) -> str | bool:+ # return a new path string, or False to abort the upload+ return path++composio = Composio()+composio.tools.execute(+ "GOOGLEDRIVE_UPLOAD_FILE",+ {"file_to_upload": "/path/to/document.pdf"},+ user_id="user_123",+ modifiers=[audit_path],+)+```++- **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.+- **Relative to `before_execute`:** automatic file substitution runs **before** `before_execute` modifiers, matching TypeScript behavior (including tool router `execute_meta`).+## What to read next<Cards>diff --git a/docs/content/reference/sdk-reference/python/index.mdx b/docs/content/reference/sdk-reference/python/index.mdxindex afba64b9d..d0311f5de 100644--- a/docs/content/reference/sdk-reference/python/index.mdx+++ b/docs/content/reference/sdk-reference/python/index.mdx@@ -73,6 +73,18 @@ def my_modifier(...):...```+### before_file_upload++[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L236)++```python+@before_file_upload(modifier: BeforeFileUploadCallable | None = ..., tools: List[str | None] = ..., toolkits: List[str | None] = ...)+def my_modifier(path: str, tool: str, toolkit: str) -> str | bool:+ ...+```++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.+### schema_modifier[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/_modifiers.py#L222)diff --git a/docs/content/reference/sdk-reference/typescript/composio.mdx b/docs/content/reference/sdk-reference/typescript/composio.mdxindex d667976bd..196557c70 100644--- a/docs/content/reference/sdk-reference/typescript/composio.mdx+++ b/docs/content/reference/sdk-reference/typescript/composio.mdx@@ -177,3 +177,18 @@ getConfig(): ComposioConfig`ComposioConfig` — The configuration SDK is initialized with---++## File upload security++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)).++| Option | Type | Default | Description |+|--------|------|---------|-------------|+| `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. |+| `fileUploadPathDenySegments` | `string[]` | `undefined` | Additional single path *components* (directory or file names) merged with the built-in list; matched anywhere in the resolved path. |++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.++**Related errors:** `ComposioSensitiveFilePathBlockedError`, `ComposioFileUploadAbortedError` (from `@composio/core`).++---diff --git a/python/composio/__init__.py b/python/composio/__init__.pyindex 03fac43c3..3f1b91bd3 100644--- a/python/composio/__init__.py+++ b/python/composio/__init__.py@@ -8,6 +8,7 @@ from .core.models.tool_router_session_files import RemoteFilefrom .core.models.tools import (after_execute,before_execute,+ before_file_upload,schema_modifier,)from .core.models.webhook_events import (@@ -43,6 +44,7 @@ __all__ = ("WebhookEventType","after_execute","before_execute",+ "before_file_upload","is_connection_expired_event","schema_modifier","__version__",diff --git a/python/composio/core/models/_files.py b/python/composio/core/models/_files.pyindex 52a076b2f..26ebf9914 100644--- a/python/composio/core/models/_files.py+++ b/python/composio/core/models/_files.py@@ -18,10 +18,14 @@ from composio.client.types import Toolfrom composio.exceptions import (ErrorDownloadingFile,ErrorUploadingFile,+ FileUploadAbortedError,ResponseTooLargeError,SDKFileNotFoundError,)from composio.utils import mimetypes+from composio.utils.sensitive_file_upload_paths import (+ assert_safe_local_file_upload_path,+)from composio.utils.logging import WithLoggerif t.TYPE_CHECKING:@@ -416,6 +420,12 @@ class FileUploadable(BaseModel):file: t.Union[str, Path],tool: str,toolkit: str,+ *,+ sensitive_file_upload_protection: bool = True,+ file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,+ before_file_upload: t.Optional[+ t.Callable[[str, str, str], t.Union[str, bool]]+ ] = None,) -> te.Self:"""Create a FileUploadable from a local file path or public URL.@@ -427,14 +437,44 @@ class FileUploadable(BaseModel)::param file: Local file path or public URL:param tool: The tool slug:param toolkit: The toolkit slug+ :param sensitive_file_upload_protection: When True, block paths on the built-in denylist.+ :param file_upload_path_deny_segments: Extra path segment names to merge with the built-in list.+ :param before_file_upload: Optional ``(path, tool, toolkit) -> str | bool``; return a new path string, or False to abort.:return: FileUploadable instance with S3 key"""+ file_str = str(file) if isinstance(file, Path) else file+# Check if it's a URL- if isinstance(file, str) and _is_url(file):- return cls.from_url(client=client, url=file, tool=tool, toolkit=toolkit)+ if isinstance(file_str, str) and _is_url(file_str):+ path_in = file_str+ if before_file_upload is not None:+ out = before_file_upload(path_in, tool, toolkit)+ if out is False:+ raise FileUploadAbortedError(+ "File upload was aborted because before_file_upload returned False."+ )+ if isinstance(out, str):+ path_in = out+ return cls.from_url(client=client, url=path_in, tool=tool, toolkit=toolkit)++ path_in = file_str+ if before_file_upload is not None:+ out = before_file_upload(path_in, tool, toolkit)+ if out is False:+ raise FileUploadAbortedError(+ "File upload was aborted because before_file_upload returned False."+ )+ if isinstance(out, str):+ path_in = out++ assert_safe_local_file_upload_path(+ path_in,+ enabled=sensitive_file_upload_protection,+ additional_deny_segments=file_upload_path_deny_segments,+ )# Handle as local file path- file = Path(file)+ file = Path(path_in)if not file.exists():raise SDKFileNotFoundError(f"File not found: {file}. Please provide a valid file path."@@ -487,11 +527,23 @@ class FileDownloadable(BaseModel):return outfile+BeforeFileUpload = t.Callable[[str, str, str], t.Union[str, bool]]++class FileHelper(WithLogger):- def __init__(self, client: HttpClient, outdir: t.Optional[str] = None):+ def __init__(+ self,+ client: HttpClient,+ outdir: t.Optional[str] = None,+ *,+ sensitive_file_upload_protection: bool = True,+ file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,+ ) -> None:super().__init__()self._client = clientself._outdir = Path(outdir or LOCAL_OUTPUT_FILE_DIRECTORY)+ self._sensitive_file_upload_protection = sensitive_file_upload_protection+ self._file_upload_path_deny_segments = file_upload_path_deny_segmentsdef _has_file_property(self, schema: t.Dict, property_name: str = "file_uploadable"@@ -691,6 +743,8 @@ class FileHelper(WithLogger):tool: Tool,schema: t.Dict,request: t.Dict,+ *,+ before_file_upload: t.Optional[BeforeFileUpload] = None,) -> t.Dict:if "properties" not in schema:return request@@ -714,6 +768,9 @@ class FileHelper(WithLogger):file=request[_param],tool=tool.slug,toolkit=tool.toolkit.slug,+ sensitive_file_upload_protection=self._sensitive_file_upload_protection,+ file_upload_path_deny_segments=self._file_upload_path_deny_segments,+ before_file_upload=before_file_upload,).model_dump()continue@@ -731,6 +788,9 @@ class FileHelper(WithLogger):file=request[_param],tool=tool.slug,toolkit=tool.toolkit.slug,+ sensitive_file_upload_protection=self._sensitive_file_upload_protection,+ file_upload_path_deny_segments=self._file_upload_path_deny_segments,+ before_file_upload=before_file_upload,).model_dump()continue@@ -743,6 +803,7 @@ class FileHelper(WithLogger):schema=uploadable_variant,request=request[_param],tool=tool,+ before_file_upload=before_file_upload,)continue@@ -755,6 +816,7 @@ class FileHelper(WithLogger):schema=param_schema,request=request[_param],tool=tool,+ before_file_upload=before_file_upload,)continue@@ -777,6 +839,9 @@ class FileHelper(WithLogger):file=item,tool=tool.slug,toolkit=tool.toolkit.slug,+ sensitive_file_upload_protection=self._sensitive_file_upload_protection,+ file_upload_path_deny_segments=self._file_upload_path_deny_segments,+ before_file_upload=before_file_upload,).model_dump())elif isinstance(item, dict):@@ -785,6 +850,7 @@ class FileHelper(WithLogger):schema=items_schema,request=item,tool=tool,+ before_file_upload=before_file_upload,))else:@@ -795,11 +861,18 @@ class FileHelper(WithLogger):return request- def substitute_file_uploads(self, tool: Tool, request: t.Dict) -> t.Dict:+ def substitute_file_uploads(+ self,+ tool: Tool,+ request: t.Dict,+ *,+ before_file_upload: t.Optional[BeforeFileUpload] = None,+ ) -> t.Dict:return self._substitute_file_uploads_recursively(tool=tool,schema=tool.input_parameters,request=request,+ before_file_upload=before_file_upload,)def _is_file_downloadable(self, schema: t.Dict) -> bool:diff --git a/python/composio/core/models/_modifiers.py b/python/composio/core/models/_modifiers.pyindex cb4195dc4..70ba1a5ea 100644--- a/python/composio/core/models/_modifiers.py+++ b/python/composio/core/models/_modifiers.py@@ -65,10 +65,22 @@ class SchemaModifier(t.Protocol):) -> "Tool": ...+class BeforeFileUploadCallable(t.Protocol):+ """Called for each local file path before read/upload (``file_uploadable``)."""++ def __call__(+ self,+ path: str,+ tool: str,+ toolkit: str,+ ) -> t.Union[str, bool]: ...++ModifierSlug: t.TypeAlias = strAfterExecuteModifierL: t.TypeAlias = t.Literal["after_execute"]BeforeExecuteModifierL: t.TypeAlias = t.Literal["before_execute"]SchemaModifierL: t.TypeAlias = t.Literal["schema"]+BeforeFileUploadModifierL: t.TypeAlias = t.Literal["before_file_upload"]class Modifier:@@ -80,6 +92,7 @@ class Modifier:| SchemaModifier| BeforeExecuteMeta| AfterExecuteMeta+ | BeforeFileUploadCallable],type_: (AfterExecuteModifierL@@ -87,6 +100,7 @@ class Modifier:| SchemaModifierL| AfterExecuteMetaModifierL| BeforeExecuteMetaModifierL+ | BeforeFileUploadModifierL),tools: t.List[str],toolkits: t.List[str],@@ -207,6 +221,53 @@ def before_execute(raise ValueError("Either tools or toolkits must be provided")+def before_file_upload(modifier: t.Optional[BeforeFileUploadCallable]) -> Modifier: ...+++def before_file_upload(+ *,+ tools: t.Optional[t.List[str]] = None,+ toolkits: t.Optional[t.List[str]] = None,+) -> t.Callable[[BeforeFileUploadCallable], Modifier]: ...+++def before_file_upload(+ modifier: t.Optional[BeforeFileUploadCallable] = None,+ *,+ tools: t.Optional[t.List[str]] = None,+ toolkits: t.Optional[t.List[str]] = None,+) -> Modifier | t.Callable[[BeforeFileUploadCallable], Modifier]:+ """+ Build a ``Modifier`` for the file-upload hook (same scoping pattern as+ :func:`before_execute`).++ Pass the returned ``Modifier`` in ``modifiers=[...]`` on+ :meth:`composio.core.models.tools.Tools.execute` or ``tools.get``. Multiple+ such modifiers are composed in list order.+ """+ if modifier is not None:+ return Modifier(+ modifier=modifier,+ type_="before_file_upload",+ tools=tools or [],+ toolkits=toolkits or [],+ )++ if tools is not None or toolkits is not None:+ return t.cast(+ t.Callable[[BeforeFileUploadCallable], Modifier],+ functools.partial(+ before_file_upload,+ tools=tools or [],+ toolkits=toolkits or [],+ ),+ )++ raise ValueError("Either tools or toolkits must be provided")++@t.overloaddef schema_modifier(modifier: t.Optional[SchemaModifier]) -> Modifier: ...@@ -327,6 +388,43 @@ def after_execute_meta(Modifiers = t.List[Modifier]+def merge_before_file_upload(+ modifiers: t.Optional[Modifiers],+ tool: str,+ toolkit: str,+) -> t.Optional[BeforeFileUploadCallable]:+ """Compose ``before_file_upload``-type :class:`Modifier`\\ s for this *tool* / *toolkit*.++ Scoping matches :class:`Modifier` (empty ``tools`` and ``toolkits`` = all tools).+ """+ to_chain = [+ m+ for m in (modifiers or [])+ if m.type == "before_file_upload" and m.modifier is not None+ ]+ if not to_chain:+ return None++ def _applies(m: Modifier) -> bool:+ if len(m.tools) == 0 and len(m.toolkits) == 0:+ return True+ return tool in m.tools or toolkit in m.toolkits++ def combined(path: str, tool: str, toolkit: str) -> t.Union[str, bool]:+ p: str = path+ for m in to_chain:+ if not _applies(m):+ continue+ out = t.cast(BeforeFileUploadCallable, m.modifier)(p, tool, toolkit)+ if out is False:+ return False+ if isinstance(out, str):+ p = out+ return p++ return combined++@t.overloaddef apply_modifier_by_type(modifiers: Modifiers,diff --git a/python/composio/core/models/tool_router.py b/python/composio/core/models/tool_router.pyindex 2a0ef9cf3..afeee6a20 100644--- a/python/composio/core/models/tool_router.py+++ b/python/composio/core/models/tool_router.py@@ -361,6 +361,8 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):client: HttpClient,provider: t.Optional["BaseProvider[TTool, TToolCollection]"] = None,auto_upload_download_files: bool = True,+ sensitive_file_upload_protection: bool = True,+ file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,):"""Initialize ToolRouter instance.@@ -368,10 +370,14 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection])::param client: HTTP client for API calls:param provider: Optional provider for tool wrapping:param auto_upload_download_files: Whether to automatically upload and download files. Defaults to True.+ :param sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload.+ :param file_upload_path_deny_segments: Extra path segment names to merge with the built-in denylist."""super().__init__(client)self._provider = providerself._auto_upload_download_files = auto_upload_download_files+ self._sensitive_file_upload_protection = sensitive_file_upload_protection+ self._file_upload_path_deny_segments = file_upload_path_deny_segmentsdef _create_mcp_server_config(self,@@ -804,6 +810,8 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):client=self._client,provider=self._provider,auto_upload_download_files=self._auto_upload_download_files,+ sensitive_file_upload_protection=self._sensitive_file_upload_protection,+ file_upload_path_deny_segments=self._file_upload_path_deny_segments,session_id=session.session_id,mcp=self._create_mcp_server_config(mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),@@ -857,6 +865,8 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):client=self._client,provider=self._provider,auto_upload_download_files=self._auto_upload_download_files,+ sensitive_file_upload_protection=self._sensitive_file_upload_protection,+ file_upload_path_deny_segments=self._file_upload_path_deny_segments,session_id=session.session_id,mcp=self._create_mcp_server_config(mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),diff --git a/python/composio/core/models/tool_router_session.py b/python/composio/core/models/tool_router_session.pyindex 67671b551..6cd1b2c45 100644--- a/python/composio/core/models/tool_router_session.py+++ b/python/composio/core/models/tool_router_session.py@@ -77,6 +77,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):client: HttpClient,provider: t.Optional[BaseProvider[t.Any, t.Any]],auto_upload_download_files: bool,+ sensitive_file_upload_protection: bool = True,+ file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,session_id: str,mcp: t.Any,experimental: "ToolRouterSessionExperimental",@@ -86,6 +88,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):self._client = clientself._provider = providerself._auto_upload_download_files = auto_upload_download_files+ self._sensitive_file_upload_protection = sensitive_file_upload_protection+ self._file_upload_path_deny_segments = file_upload_path_deny_segmentsself.session_id = session_idself.mcp = mcpself.experimental = experimental@@ -108,6 +112,17 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):return Falsereturn len(self._custom_tools_map.by_final_slug) > 0+ def _tool_router_backend_execute(+ self,+ tools_model: t.Any,+ modifiers: t.Optional["Modifiers"] = None,+ ) -> t.Callable[..., t.Any]:+ """Backend execute_meta wrapper with this session's file-upload settings."""+ return tools_model._wrap_execute_tool_for_tool_router(+ session_id=self.session_id,+ modifiers=modifiers,+ )+def tools(self, modifiers: t.Optional["Modifiers"] = None) -> TToolCollection:"""Get provider-wrapped tools for execution with your AI framework.@@ -132,6 +147,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):client=self._client,provider=self._provider,auto_upload_download_files=self._auto_upload_download_files,+ sensitive_file_upload_protection=self._sensitive_file_upload_protection,+ file_upload_path_deny_segments=self._file_upload_path_deny_segments,)router_tools = tools_model.get_raw_tool_router_meta_tools(@@ -159,9 +176,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):if self._has_custom_tools():execute_fn = self._create_routing_execute_fn(tools_model, modifiers)else:- execute_fn = tools_model._wrap_execute_tool_for_tool_router(- session_id=self.session_id,- modifiers=modifiers,+ execute_fn = self._tool_router_backend_execute(+ tools_model, modifiers=modifiers)return t.cast(@@ -182,9 +198,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):Applies before_execute/after_execute modifiers around the overallCOMPOSIO_MULTI_EXECUTE_TOOL call, consistent with the standard path."""- backend_execute = tools_model._wrap_execute_tool_for_tool_router(- session_id=self.session_id,- modifiers=modifiers,+ backend_execute = self._tool_router_backend_execute(+ tools_model, modifiers=modifiers)def routing_execute(slug: str, arguments: t.Dict) -> t.Dict:@@ -251,9 +266,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):tool_items = input_args.get("tools")if not isinstance(tool_items, list) or len(tool_items) == 0:# Fallback: send to backend as-is (no modifiers — caller handles them)- return tools_model._wrap_execute_tool_for_tool_router(- session_id=self.session_id,- )(COMPOSIO_MULTI_EXECUTE_TOOL, input_args)+ return self._tool_router_backend_execute(tools_model)(+ COMPOSIO_MULTI_EXECUTE_TOOL,+ input_args,+ )parsed = [self._parse_tool_item(item) for item in tool_items]@@ -269,9 +285,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):# All remote — just forward entire payload (no modifiers — caller handles them)if not local_items:- return tools_model._wrap_execute_tool_for_tool_router(- session_id=self.session_id,- )(COMPOSIO_MULTI_EXECUTE_TOOL, input_args)+ return self._tool_router_backend_execute(tools_model)(+ COMPOSIO_MULTI_EXECUTE_TOOL,+ input_args,+ )ctx = self._session_contextassert ctx is not None@@ -298,9 +315,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):if remote_indices:remote_tool_items = [tool_items[i] for i in remote_indices]remote_input = {**input_args, "tools": remote_tool_items}- execute_fn = tools_model._wrap_execute_tool_for_tool_router(- session_id=self.session_id,- )+ execute_fn = self._tool_router_backend_execute(tools_model)remote_future = pool.submit(execute_fn,COMPOSIO_MULTI_EXECUTE_TOOL,diff --git a/python/composio/core/models/tools.py b/python/composio/core/models/tools.pyindex 8129dc051..664040898 100644--- a/python/composio/core/models/tools.py+++ b/python/composio/core/models/tools.py@@ -33,6 +33,8 @@ from ._modifiers import (after_execute,apply_modifier_by_type,before_execute,+ before_file_upload,+ merge_before_file_upload,schema_modifier,)@@ -101,6 +103,8 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):file_download_dir: t.Optional[str] = None,toolkit_versions: t.Optional[ToolkitVersionParam] = None,auto_upload_download_files: bool = True,+ sensitive_file_upload_protection: bool = True,+ file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,):"""Initialize the tools resource.@@ -110,11 +114,18 @@ class Tools(Resource, t.Generic[TTool, TToolCollection])::param file_download_dir: Output directory for downloadable files:param toolkit_versions: The versions of the toolkits to use. Defaults to 'latest' if not provided.:param auto_upload_download_files: Whether to automatically upload and download files. Defaults to True.+ :param sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload.+ :param file_upload_path_deny_segments: Extra path segment names to merge with the built-in denylist."""self._client = clientself._custom_tools = CustomTools(client)self._tool_schemas: t.Dict[str, Tool] = {}- self._file_helper = FileHelper(client=self._client, outdir=file_download_dir)+ self._file_helper = FileHelper(+ client=self._client,+ outdir=file_download_dir,+ sensitive_file_upload_protection=sensitive_file_upload_protection,+ file_upload_path_deny_segments=file_upload_path_deny_segments,+ )self._toolkit_versions = toolkit_versionsself._auto_upload_download_files = auto_upload_download_files@@ -369,7 +380,11 @@ class Tools(Resource, t.Generic[TTool, TToolCollection])::return: Provider-specific tool collection (TToolCollection)."""if slug is not None:- return self._get(user_id=user_id, tools=[slug], modifiers=modifiers)+ return self._get(+ user_id=user_id,+ tools=[slug],+ modifiers=modifiers,+ )return self._get(user_id=user_id,tools=tools,@@ -428,6 +443,36 @@ class Tools(Resource, t.Generic[TTool, TToolCollection])::param arguments: The tool arguments:return: Tool execution response"""+ tool = self._tool_schemas.get(slug)+ if tool is None:+ custom_tool = self._custom_tools.get(slug=slug)+ if custom_tool is not None:+ tool = custom_tool.info+ self._tool_schemas[slug] = tool++ if tool is None:+ tool = t.cast(+ Tool,+ self._client.tools.retrieve(+ tool_slug=slug,+ toolkit_versions=none_to_omit(self._toolkit_versions),+ ),+ )+ self._tool_schemas[slug] = tool++ if self._auto_upload_download_files:+ meta_tk = tool.toolkit.slug if tool.toolkit else "unknown"+ bfu = merge_before_file_upload(+ modifiers,+ tool=slug,+ toolkit=meta_tk,+ )+ arguments = self._file_helper.substitute_file_uploads(+ tool=tool,+ request=arguments,+ before_file_upload=bfu,+ )+# Apply before_execute modifiers# Meta tools are always from the 'composio' toolkitprocessed_arguments = arguments@@ -589,7 +634,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection])::param text: The text to pass to the tool.:param version: The version of the tool to execute (overrides the SDK-level toolkit versions for this execution).:param dangerously_skip_version_check: Skip the version check for 'latest' version. This might cause unexpected behavior when new versions are released.- :param modifiers: The modifiers to apply to the tool.+ :param modifiers: The modifiers to apply to the tool (include ``@before_file_upload`` for file path hooks).:return: The response from the tool."""@@ -610,6 +655,19 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):)self._tool_schemas[slug] = tool+ if self._auto_upload_download_files:+ tk = tool.toolkit.slug if tool.toolkit else "unknown"+ bfu = merge_before_file_upload(+ modifiers,+ tool=slug,+ toolkit=tk,+ )+ arguments = self._file_helper.substitute_file_uploads(+ tool=tool,+ request=arguments,+ before_file_upload=bfu,+ )+if modifiers is not None:type_before_exec: t.Literal["before_execute"] = "before_execute"request_params: ToolExecuteParams = {@@ -654,12 +712,6 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):dangerously_skip_version_check = processed_params.get("dangerously_skip_version_check", dangerously_skip_version_check)-- if self._auto_upload_download_files:- arguments = self._file_helper.substitute_file_uploads(- tool=tool,- request=arguments,- )response = (self._execute_custom_tool(slug=slug,@@ -727,5 +779,6 @@ __all__ = ["Modifiers","after_execute","before_execute",+ "before_file_upload","schema_modifier",]diff --git a/python/composio/exceptions.py b/python/composio/exceptions.pyindex 8db2c3c11..2cd408170 100644--- a/python/composio/exceptions.py+++ b/python/composio/exceptions.py@@ -168,6 +168,14 @@ class ErrorUploadingFile(FileError):pass+class SensitiveFilePathBlockedError(FileError):+ """Raised when a local file path is refused before upload (sensitive directory or credential-like name)."""+++class FileUploadAbortedError(FileError):+ """Raised when a ``before_file_upload`` hook returns ``False``."""++class ErrorDownloadingFile(FileError):passdiff --git a/python/composio/sdk.py b/python/composio/sdk.pyindex 09b69e0e5..e8447555c 100644--- a/python/composio/sdk.py+++ b/python/composio/sdk.py@@ -41,6 +41,8 @@ class SDKConfig(te.TypedDict):file_download_dir: te.NotRequired[str]toolkit_versions: te.NotRequired[ToolkitVersionParam]auto_upload_download_files: te.NotRequired[bool]+ sensitive_file_upload_protection: te.NotRequired[bool]+ file_upload_path_deny_segments: te.NotRequired[t.Sequence[str]]class Composio(t.Generic[TTool, TToolCollection], WithLogger):@@ -104,6 +106,8 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):- A string (e.g., 'latest', '20250906_01') to use the same version for all toolkits- None or omitted to use 'latest' as default:param auto_upload_download_files: Whether to automatically upload and download files. Defaults to True.+ :param sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload. Defaults to True.+ :param file_upload_path_deny_segments: Extra path segment names merged with the built-in denylist."""WithLogger.__init__(self)api_key = kwargs.get("api_key", os.environ.get("COMPOSIO_API_KEY"))@@ -130,12 +134,20 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):max_retries=kwargs.get("max_retries", DEFAULT_MAX_RETRIES),)self.provider = actual_provider+ sensitive_file_upload_protection: bool = kwargs.get(+ "sensitive_file_upload_protection", True+ )+ file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = kwargs.get(+ "file_upload_path_deny_segments"+ )self.tools = Tools(client=self._client,provider=actual_provider,file_download_dir=kwargs.get("file_download_dir"),toolkit_versions=toolkit_versions,auto_upload_download_files=kwargs.get("auto_upload_download_files", True),+ sensitive_file_upload_protection=sensitive_file_upload_protection,+ file_upload_path_deny_segments=file_upload_path_deny_segments,)self.toolkits = Toolkits(client=self._client)@@ -154,6 +166,8 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):client=self._client,provider=actual_provider,auto_upload_download_files=kwargs.get("auto_upload_download_files", True),+ sensitive_file_upload_protection=sensitive_file_upload_protection,+ file_upload_path_deny_segments=file_upload_path_deny_segments,)self.create = self.tool_router.createself.use = self.tool_router.usediff --git a/python/composio/utils/sensitive_file_upload_paths.py b/python/composio/utils/sensitive_file_upload_paths.pynew file mode 100644index 000000000..a5d411803--- /dev/null+++ b/python/composio/utils/sensitive_file_upload_paths.py@@ -0,0 +1,93 @@+"""Block accidental upload of local files from well-known secret/credential locations."""++from __future__ import annotations++import re+import typing as t+from pathlib import Path++# Path components that indicate a sensitive directory anywhere in a resolved local path.+BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS: t.Tuple[str, ...] = (+ ".ssh",+ ".aws",+ ".azure",+ ".gnupg",+ ".kube",+ ".docker",+ ".claude", # may contain API keys and project context read by assistants+ ".password-store",+ "keychains",+)++_SECRET_LIKE_BASENAME = re.compile(r"^(\.env(\.|$)|\.netrc$|\.pgpass$)", re.IGNORECASE)+_DEFAULT_PRIVATE_KEY_BASENAME = re.compile(+ r"^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$", re.IGNORECASE+)+++def _normalize_path_segments(file_path: t.Union[str, Path]) -> t.List[str]:+ p = Path(file_path).expanduser()+ try:+ resolved = p.resolve()+ except OSError:+ resolved = p+ parts = [part for part in resolved.as_posix().split("/") if part]+ if parts and parts[0].endswith(":"):+ # Windows path: "C:/Users/..." -> drop drive letter segment+ parts = parts[1:]+ return parts+++def _get_block_reason(+ file_path: t.Union[str, Path],+ additional_deny_segments: t.Optional[t.Sequence[str]] = None,+) -> t.Optional[str]:+ extra = [s.strip() for s in (additional_deny_segments or []) if s and s.strip()]+ deny: t.Set[str] = {s.lower() for s in BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS}+ deny.update(s.lower() for s in extra)++ segments = _normalize_path_segments(file_path)+ # Case-insensitive segment match: lower each path component once per check.+ for seg, key in zip(segments, (s.lower() for s in segments), strict=True):+ if key in deny:+ return f'path segment "{seg}" is in the sensitive file upload denylist'++ if not segments:+ return None+ basename = segments[-1]+ if _SECRET_LIKE_BASENAME.search(basename) or _DEFAULT_PRIVATE_KEY_BASENAME.match(+ basename+ ):+ return (+ f'file name "{basename}" looks like a credential, env, or private key file'+ )+ if basename.lower() == "credentials":+ return 'file name "credentials" is often used for cloud/API credential stores'+ return None+++def is_blocked_sensitive_file_upload_path(+ file_path: t.Union[str, Path],+ additional_deny_segments: t.Optional[t.Sequence[str]] = None,+) -> bool:+ return _get_block_reason(file_path, additional_deny_segments) is not None+++def assert_safe_local_file_upload_path(+ file_path: t.Union[str, Path],+ *,+ enabled: bool = True,+ additional_deny_segments: t.Optional[t.Sequence[str]] = None,+) -> None:+ """Raise SensitiveFilePathBlockedError if *file_path* matches the denylist."""+ if not enabled:+ return+ reason = _get_block_reason(file_path, additional_deny_segments)+ if reason:+ from composio.exceptions import SensitiveFilePathBlockedError++ raise SensitiveFilePathBlockedError(+ f"Refusing to upload: {reason}. "+ "Set sensitive_file_upload_protection=False on Composio if you must "+ "(not recommended), or use a copy outside sensitive locations."+ )diff --git a/python/examples/modifiers.py b/python/examples/modifiers.pyindex 4d990ad31..d1ba0c524 100644--- a/python/examples/modifiers.py+++ b/python/examples/modifiers.py@@ -1,6 +1,12 @@import os-from composio import Composio, after_execute, before_execute, schema_modifier+from composio import (+ Composio,+ after_execute,+ before_execute,+ before_file_upload,+ schema_modifier,+)from composio.types import Tool, ToolExecuteParams, ToolExecutionResponsecomposio = Composio()@@ -17,6 +23,12 @@ def before_execute_modifier(return params+@before_file_upload(tools=["HACKERNEWS_GET_USER"])+def rewrite_upload_path(path: str, tool: str, toolkit: str) -> str:+ """Optional: same pattern as before_execute; use for per-tool file path policy."""+ return path++@after_execute(tools=["HACKERNEWS_GET_USER"])def after_execute_modifier(tool: str,@@ -38,6 +50,7 @@ response = composio.tools.execute(arguments={"username": "pg"},modifiers=[before_execute_modifier,+ rewrite_upload_path,after_execute_modifier,],)diff --git a/python/providers/anthropic/pyproject.toml b/python/providers/anthropic/pyproject.tomlindex 4a9f1b8cd..ee733ea38 100644--- a/python/providers/anthropic/pyproject.toml+++ b/python/providers/anthropic/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-anthropic"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get an array of tools with your Anthropic LLMs."readme = "README.md"requires-python = ">=3.10,<4"diff --git a/python/providers/anthropic/setup.py b/python/providers/anthropic/setup.pyindex 18c299958..4c8392eb3 100644--- a/python/providers/anthropic/setup.py+++ b/python/providers/anthropic/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_anthropic",- version="0.11.5",+ version="0.11.6",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Anthropic LLMs.",diff --git a/python/providers/autogen/pyproject.toml b/python/providers/autogen/pyproject.tomlindex 10e905d81..59c5f5157 100644--- a/python/providers/autogen/pyproject.toml+++ b/python/providers/autogen/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-autogen"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get an array of tools with your autogen agent."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/autogen/setup.py b/python/providers/autogen/setup.pyindex 6b1cd1b47..934a821d5 100644--- a/python/providers/autogen/setup.py+++ b/python/providers/autogen/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_autogen",- version="0.11.5",+ version="0.11.6",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Autogen agent.",diff --git a/python/providers/claude_agent_sdk/pyproject.toml b/python/providers/claude_agent_sdk/pyproject.tomlindex e3d48fd4c..7e3e5dd95 100644--- a/python/providers/claude_agent_sdk/pyproject.toml+++ b/python/providers/claude_agent_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-claude-agent-sdk"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get an array of tools with Claude Code Agents SDK."readme = "README.md"requires-python = ">=3.10,<4"diff --git a/python/providers/claude_agent_sdk/setup.py b/python/providers/claude_agent_sdk/setup.pyindex 497523339..1808f9b09 100644--- a/python/providers/claude_agent_sdk/setup.py+++ b/python/providers/claude_agent_sdk/setup.py@@ -8,7 +8,7 @@ from setuptools import find_packages, setupsetup(name="composio_claude_agent_sdk",- version="0.11.5",+ version="0.11.6",author="Composio",author_email="[email protected]",description="Use Composio to get array of tools for Claude Agent SDK",diff --git a/python/providers/crewai/pyproject.toml b/python/providers/crewai/pyproject.tomlindex ee6e7fd09..a61135070 100644--- a/python/providers/crewai/pyproject.toml+++ b/python/providers/crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-crewai"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get an array of tools with your CrewAI agent."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/crewai/setup.py b/python/providers/crewai/setup.pyindex f91a7f6c4..b33efa7bb 100644--- a/python/providers/crewai/setup.py+++ b/python/providers/crewai/setup.py@@ -6,7 +6,7 @@ from setuptools import setupsetup(name="composio_crewai",- version="0.11.5",+ version="0.11.6",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your CrewAI agent.",diff --git a/python/providers/gemini/pyproject.toml b/python/providers/gemini/pyproject.tomlindex 03d527247..97a8d7d4e 100644--- a/python/providers/gemini/pyproject.toml+++ b/python/providers/gemini/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-gemini"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get an array of tools with your Gemini agent."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/gemini/setup.py b/python/providers/gemini/setup.pyindex efaf6c978..456558fd8 100644--- a/python/providers/gemini/setup.py+++ b/python/providers/gemini/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_gemini",- version="0.11.5",+ version="0.11.6",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Gemini agent.",diff --git a/python/providers/google/pyproject.toml b/python/providers/google/pyproject.tomlindex e4b9603ee..0e4be9ab1 100644--- a/python/providers/google/pyproject.toml+++ b/python/providers/google/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-google"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get an array of tools with your Google AI Python Gemini model."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/google/setup.py b/python/providers/google/setup.pyindex 20dd766b3..816072fa4 100644--- a/python/providers/google/setup.py+++ b/python/providers/google/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_google",- version="0.11.5",+ version="0.11.6",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Google AI Python Gemini model.",diff --git a/python/providers/google_adk/pyproject.toml b/python/providers/google_adk/pyproject.tomlindex 1e4ec722b..ffb6b9325 100644--- a/python/providers/google_adk/pyproject.toml+++ b/python/providers/google_adk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-google-adk"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get an array of tools with your Google AI Python Gemini model."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/google_adk/setup.py b/python/providers/google_adk/setup.pyindex 055bb58ec..00c633072 100644--- a/python/providers/google_adk/setup.py+++ b/python/providers/google_adk/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_google_adk",- version="0.11.5",+ version="0.11.6",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Google AI Python Gemini model.",diff --git a/python/providers/langchain/pyproject.toml b/python/providers/langchain/pyproject.tomlindex 5bc6e9ddf..fa6b1470b 100644--- a/python/providers/langchain/pyproject.toml+++ b/python/providers/langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-langchain"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get an array of tools with your Langchain agent."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/langchain/setup.py b/python/providers/langchain/setup.pyindex 7451dd451..84fdd299b 100644--- a/python/providers/langchain/setup.py+++ b/python/providers/langchain/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_langchain",- version="0.11.5",+ version="0.11.6",author="composio",author_email="[email protected]",description="Use Composio to get an array of tools with your Langchain agent.",diff --git a/python/providers/langgraph/pyproject.toml b/python/providers/langgraph/pyproject.tomlindex 3b35104f8..c544571e7 100644--- a/python/providers/langgraph/pyproject.toml+++ b/python/providers/langgraph/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-langgraph"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get array of tools with LangGraph Agent Workflows."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/langgraph/setup.py b/python/providers/langgraph/setup.pyindex 1ae0a3ce9..9b339ae38 100644--- a/python/providers/langgraph/setup.py+++ b/python/providers/langgraph/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_langgraph",- version="0.11.5",+ version="0.11.6",author="composio",author_email="[email protected]",description="Use Composio to get array of tools with LangGraph Agent Workflows",diff --git a/python/providers/llamaindex/pyproject.toml b/python/providers/llamaindex/pyproject.tomlindex 0e920e397..b9ee668b5 100644--- a/python/providers/llamaindex/pyproject.toml+++ b/python/providers/llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-llamaindex"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get array of tools with LlamaIndex Agent Workflows."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/llamaindex/setup.py b/python/providers/llamaindex/setup.pyindex 06891e91e..b08c2edd9 100644--- a/python/providers/llamaindex/setup.py+++ b/python/providers/llamaindex/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_llamaindex",- version="0.11.5",+ version="0.11.6",author="composio",author_email="[email protected]",description="Use Composio to get array of tools with LlamaIndex Agent Workflows",diff --git a/python/providers/openai/pyproject.toml b/python/providers/openai/pyproject.tomlindex ee74a290e..8e35f5d69 100644--- a/python/providers/openai/pyproject.toml+++ b/python/providers/openai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-openai"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get an array of tools with your OpenAI Function Call."readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/openai/setup.py b/python/providers/openai/setup.pyindex 3b28bd3b0..a67d9e9f1 100644--- a/python/providers/openai/setup.py+++ b/python/providers/openai/setup.py@@ -8,7 +8,7 @@ from setuptools import setupsetup(name="composio_openai",- version="0.11.5",+ version="0.11.6",author="Composio",author_email="[email protected]",description="Use Composio to get an array of tools with your OpenAI Function Call.",diff --git a/python/providers/openai_agents/pyproject.toml b/python/providers/openai_agents/pyproject.tomlindex 8ea2c867d..31dde80f3 100644--- a/python/providers/openai_agents/pyproject.toml+++ b/python/providers/openai_agents/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio-openai-agents"-version = "0.11.5"+version = "0.11.6"description = "Use Composio to get array of strongly typed tools for OpenAI Agents"readme = "README.md"requires-python = ">=3.9,<4"diff --git a/python/providers/openai_agents/setup.py b/python/providers/openai_agents/setup.pyindex c6ea4a3d9..e7e9c013e 100644--- a/python/providers/openai_agents/setup.py+++ b/python/providers/openai_agents/setup.py@@ -8,7 +8,7 @@ from setuptools import find_packages, setupsetup(name="composio_openai_agents",- version="0.11.5",+ version="0.11.6",author="Composio",author_email="[email protected]",description="Use Composio to get array of strongly typed tools for OpenAI Agents",diff --git a/python/pyproject.toml b/python/pyproject.tomlindex 03b55ec7c..c35154e73 100644--- a/python/pyproject.toml+++ b/python/pyproject.toml@@ -1,6 +1,6 @@[project]name = "composio"-version = "0.11.5"+version = "0.11.6"description = "SDK for integrating Composio with your applications."readme = "README.md"requires-python = ">=3.10,<4"diff --git a/python/scripts/generate-docs.py b/python/scripts/generate-docs.pyindex cb316d643..b905f3d8c 100644--- a/python/scripts/generate-docs.py+++ b/python/scripts/generate-docs.py@@ -36,6 +36,7 @@ GITHUB_BASE = "https://github.com/composiohq/composio/blob/next/python"DECORATORS_TO_DOCUMENT = [("before_execute", "composio.core.models._modifiers"),("after_execute", "composio.core.models._modifiers"),+ ("before_file_upload", "composio.core.models._modifiers"),("schema_modifier", "composio.core.models._modifiers"),]diff --git a/python/tests/test_auto_upload_download_files.py b/python/tests/test_auto_upload_download_files.pyindex e4694256e..8af9a0cb8 100644--- a/python/tests/test_auto_upload_download_files.py+++ b/python/tests/test_auto_upload_download_files.py@@ -173,6 +173,71 @@ class TestAutoUploadDownloadFilesEnabled:mock_upload.assert_called_once()+ def test_execute_runs_substitute_before_before_execute(+ self, mock_client, mock_provider+ ):+ """File substitution runs before before_execute modifiers (same order as TypeScript)."""+ from composio.core.models._modifiers import Modifier++ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ auto_upload_download_files=True,+ toolkit_versions={"test_toolkit": "20251201_01"},+ )++ mock_tool = create_mock_tool(+ slug="TEST_TOOL",+ toolkit_slug="test_toolkit",+ input_parameters={+ "type": "object",+ "properties": {+ "file": {"type": "string", "file_uploadable": True},+ },+ },+ output_parameters={"type": "object", "properties": {}},+ )+ tools._tool_schemas["TEST_TOOL"] = mock_tool++ seen_in_modifier: list = []++ def before_modifier(tool: str, toolkit: str, params): # type: ignore[no-untyped-def]+ seen_in_modifier.append(dict(params["arguments"]))+ return params++ modifiers = [+ Modifier(+ modifier=before_modifier, type_="before_execute", tools=[], toolkits=[]+ ),+ ]++ with patch.object(+ tools._file_helper,+ "substitute_file_uploads",+ return_value={"file": "after_substitute"},+ ) as mock_sub:+ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=mock_tool+ ):+ tools.execute(+ slug="TEST_TOOL",+ arguments={"file": "/tmp/x"},+ modifiers=modifiers,+ dangerously_skip_version_check=True,+ )++ mock_sub.assert_called_once()+ assert len(seen_in_modifier) == 1+ assert seen_in_modifier[0] == {"file": "after_substitute"}+def test_execute_calls_substitute_file_downloads(self, mock_client, mock_provider):"""Test that execute calls substitute_file_downloads when enabled."""tools = Tools(diff --git a/python/tests/test_sdk.py b/python/tests/test_sdk.pyindex 749276272..de669408b 100644--- a/python/tests/test_sdk.py+++ b/python/tests/test_sdk.py@@ -57,6 +57,8 @@ class TestComposioSDK:"file_download_dir","toolkit_versions","auto_upload_download_files",+ "sensitive_file_upload_protection",+ "file_upload_path_deny_segments",}assert set(SDKConfig.__annotations__.keys()) == expected_fieldsdiff --git a/python/tests/test_sensitive_file_upload_paths.py b/python/tests/test_sensitive_file_upload_paths.pynew file mode 100644index 000000000..7580c05fb--- /dev/null+++ b/python/tests/test_sensitive_file_upload_paths.py@@ -0,0 +1,79 @@+"""Tests for composio.utils.sensitive_file_upload_paths."""++from __future__ import annotations++import tempfile+from pathlib import Path++import pytest++from composio.exceptions import SensitiveFilePathBlockedError+from composio.utils.sensitive_file_upload_paths import (+ assert_safe_local_file_upload_path,+ is_blocked_sensitive_file_upload_path,+)+++def test_allows_normal_project_files() -> None:+ p = Path("/tmp") / "composio-test" / "document.pdf"+ assert is_blocked_sensitive_file_upload_path(p) is False+ assert_safe_local_file_upload_path(p)+++def test_blocks_common_credential_directory_segments() -> None:+ home = Path.home()+ assert is_blocked_sensitive_file_upload_path(home / ".aws" / "credentials") is True+ assert is_blocked_sensitive_file_upload_path(home / ".ssh" / "id_ed25519") is True+ assert (+ is_blocked_sensitive_file_upload_path(home / ".claude" / "settings.json")+ is True+ )+++def test_blocks_env_style_basenames() -> None:+ assert is_blocked_sensitive_file_upload_path(Path("/app/repo/.env")) is True+ assert is_blocked_sensitive_file_upload_path(Path("/app/repo/.env.local")) is True+++def test_blocks_default_private_key_basenames() -> None:+ assert is_blocked_sensitive_file_upload_path(Path("/tmp/id_ed25519")) is True+++def test_allows_public_key_by_basename() -> None:+ assert is_blocked_sensitive_file_upload_path(Path("/tmp/id_ed25519.pub")) is False+++def test_honors_additional_deny_segments() -> None:+ assert (+ is_blocked_sensitive_file_upload_path(+ Path("/data/secrets/x.txt"), additional_deny_segments=["secrets"]+ )+ is True+ )+ assert (+ is_blocked_sensitive_file_upload_path(+ Path("/data/ok/x.txt"), additional_deny_segments=["secrets"]+ )+ is False+ )+++def test_blocks_after_symlink_resolves_to_sensitive_dir() -> None:+ with tempfile.TemporaryDirectory() as root:+ root_p = Path(root)+ aws_dir = root_p / "nested" / ".aws"+ aws_dir.mkdir(parents=True)+ target = aws_dir / "creds"+ target.write_text("x", encoding="utf-8")+ link = root_p / "innocent-name"+ try:+ link.symlink_to(target)+ except OSError:+ pytest.skip("symlinks not supported")+ assert is_blocked_sensitive_file_upload_path(link) is True+++def test_assert_safe_raises() -> None:+ p = Path.home() / ".ssh" / "id_rsa"+ with pytest.raises(SensitiveFilePathBlockedError):+ assert_safe_local_file_upload_path(p)diff --git a/python/tests/test_tool_execution.py b/python/tests/test_tool_execution.pyindex c65bdfb62..898104f53 100644--- a/python/tests/test_tool_execution.py+++ b/python/tests/test_tool_execution.py@@ -1,5 +1,6 @@"""Test tool execution with toolkit versions and argument serialization."""+import typing as tfrom unittest.mock import Mock, patchimport pytest@@ -845,6 +846,85 @@ class TestToolExecution:assert result["successful"] is Trueassert result["data"]["modified"] is True+ def test_merge_before_file_upload_scopes_by_tool(self):+ from composio.core.models._modifiers import (+ before_file_upload,+ merge_before_file_upload,+ )++ scoped = before_file_upload(tools=["OTHER_TOOL"])(lambda p, t, k: p + "_X")+ fn = merge_before_file_upload([scoped], tool="MY", toolkit="gh")+ assert fn is not None+ assert fn("/a", "MY", "gh") == "/a"++ all_tools = before_file_upload(lambda p, t, k: p + "_Y")+ fn2 = merge_before_file_upload([all_tools], tool="MY", toolkit="gh")+ assert fn2 is not None+ assert fn2("/a", "MY", "gh") == "/a_Y"++ def test_merge_before_file_upload_chains_modifiers(self):+ from composio.core.models._modifiers import (+ before_file_upload,+ merge_before_file_upload,+ )++ m1 = before_file_upload(lambda p, t, k: f"{p}|1")+ m2 = before_file_upload(lambda p, t, k: f"{p}|2")+ fn = merge_before_file_upload([m1, m2], tool="T", toolkit="k")+ assert fn is not None+ assert fn("p", "T", "k") == "p|1|2"++ def test_execute_includes_before_file_upload_modifier_in_compose(+ self,+ ):+ """``before_file_upload`` in ``modifiers`` is composed into substitute_file_uploads."""+ from composio.core.models._modifiers import before_file_upload++ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions={"github": "20251201_01"},+ )++ github_tool = self.create_mock_tool("GITHUB_GET_REPOS", "github")++ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=github_tool+ ):+ mock_client.tools.retrieve.return_value = github_tool++ mock_execute_response = Mock()+ mock_execute_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_execute_response++ cap: t.Dict = {}++ def capture_sub(**kwargs):+ cap["bfu"] = kwargs.get("before_file_upload")+ return kwargs["request"]++ with patch.object(+ tools._file_helper, "substitute_file_uploads", side_effect=capture_sub+ ):+ mod = before_file_upload(lambda p, t, k: f"{p}>")+ tools.execute(+ slug="GITHUB_GET_REPOS",+ arguments={"owner": "a", "repo": "b"},+ modifiers=[mod],+ )++ bfu = cap.get("bfu")+ assert bfu is not None+ assert bfu("/p", "GITHUB_GET_REPOS", "github") == "/p>"+def test_execute_with_environment_variable_toolkit_version(self):"""Test that execute uses environment variable for toolkit version."""import osdiff --git a/python/tests/test_tool_router.py b/python/tests/test_tool_router.pyindex 32a5a0ae4..5d0050fec 100644--- a/python/tests/test_tool_router.py+++ b/python/tests/test_tool_router.py@@ -968,7 +968,11 @@ class TestToolRouter:# Verify Tools was instantiatedmock_tools_class.assert_called_once_with(- client=mock_client, provider=mock_provider, auto_upload_download_files=True+ client=mock_client,+ provider=mock_provider,+ auto_upload_download_files=True,+ sensitive_file_upload_protection=True,+ file_upload_path_deny_segments=None,)# Verify get_raw_tool_router_meta_tools was called@@ -1260,7 +1264,11 @@ class TestToolRouterExecution:# Create a real Tools instance to test the execute functionfrom composio.core.models.tools import Tools as RealTools- real_tools = RealTools(client=mock_client, provider=mock_provider)+ real_tools = RealTools(+ client=mock_client,+ provider=mock_provider,+ auto_upload_download_files=False,+ )execute_fn = real_tools._wrap_execute_tool_for_tool_router(session_id="session_123")@@ -1307,7 +1315,11 @@ class TestToolRouterExecution:from composio.core.models._modifiers import Modifierfrom composio.core.models.tools import Tools as RealTools- real_tools = RealTools(client=mock_client, provider=mock_provider)+ real_tools = RealTools(+ client=mock_client,+ provider=mock_provider,+ auto_upload_download_files=False,+ )modifiers = [Modifier(@@ -1346,7 +1358,11 @@ class TestToolRouterExecution:# Create a real execute functionfrom composio.core.models.tools import Tools as RealTools- real_tools = RealTools(client=mock_client, provider=mock_provider)+ real_tools = RealTools(+ client=mock_client,+ provider=mock_provider,+ auto_upload_download_files=False,+ )execute_fn = real_tools._wrap_execute_tool_for_tool_router(session_id="session_123")diff --git a/ts/docs/advanced/auto-upload-download.md b/ts/docs/advanced/auto-upload-download.mdindex 7416afe6d..25eec542b 100644--- a/ts/docs/advanced/auto-upload-download.md+++ b/ts/docs/advanced/auto-upload-download.md@@ -9,6 +9,37 @@ The file handling system in Composio SDK is:- **Opt-out**: Enabled by default but can be disabled- **Automatic**: Handles file uploads and downloads transparently- **Configurable**: Can be disabled for manual file handling+- **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)++## Security: sensitive local paths++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:++- **`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.+- **`fileUploadPathDenySegments`** — Optional extra path component names (single directory or file name) merged with the built-in list, anywhere in the resolved path.+- **`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.++**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.++**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`).++```typescript+import { Composio } from '@composio/core';++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY!,+ sensitiveFileUploadProtection: true,+ fileUploadPathDenySegments: ['my-team-secrets'],+});++await composio.tools.execute(+ 'YOUR_TOOL',+ { userId: 'u', arguments: { file: '/safe/path/doc.pdf' }, dangerouslySkipVersionCheck: true },+ {+ beforeFileUpload: async ({ path }) => path,+ }+);+```## How It Works@@ -174,19 +205,28 @@ Downloaded files are stored in a temporary directory:The SDK includes specific error types for file operations:```typescript-import { ComposioFileUploadError } from '@composio/core';+import {+ ComposioFileUploadError,+ ComposioSensitiveFilePathBlockedError,+ ComposioFileUploadAbortedError,+} from '@composio/core';try {await composio.tools.execute('your-tool', {+ userId: 'u',arguments: {- file: '/path/to/file.txt'- }+ file: '/path/to/file.txt',+ },+ dangerouslySkipVersionCheck: true,});} catch (error) {- if (error instanceof ComposioFileUploadError) {+ if (error instanceof ComposioSensitiveFilePathBlockedError) {+ console.error('Blocked sensitive path:', error.message);+ } else if (error instanceof ComposioFileUploadAbortedError) {+ console.error('Upload aborted by beforeFileUpload:', error.message);+ } else if (error instanceof ComposioFileUploadError) {console.error('File upload failed:', error.message);- // Handle file upload error- // Possible fixes will be included in error.possibleFixes+ // Possible fixes may be included in error.possibleFixes}throw error;}diff --git a/ts/docs/api/composio.md b/ts/docs/api/composio.mdindex 5d3a314ee..81926afb6 100644--- a/ts/docs/api/composio.md+++ b/ts/docs/api/composio.md@@ -12,6 +12,8 @@ const composio = new Composio({baseURL: 'https://api.composio.dev', // Optional: Custom API endpointallowTracking: true, // Optional: Enable/disable telemetryautoUploadDownloadFiles: true, // Optional: Enable/disable automatic file handling+ sensitiveFileUploadProtection: true, // Optional: block uploads from sensitive paths (Node; default true)+ fileUploadPathDenySegments: undefined, // Optional: extra path component denylistprovider: new OpenAIProvider(), // Optional: Custom provider});```@@ -26,6 +28,8 @@ The `Composio` constructor accepts a configuration object with the following pro| `baseURL` | string | No | `https://api.composio.dev` | The base URL for the Composio API || `allowTracking` | boolean | No | `true` | Whether to allow analytics/tracking || `autoUploadDownloadFiles`| boolean | No | `true` | Whether to automatically handle file operations |+| `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. |+| `fileUploadPathDenySegments` | `string[]` | No | `undefined` | Additional path *components* merged with the built-in denylist. || `provider` | `BaseComposioProvider` | No | `new OpenAIProvider()` | The provider to use for this Composio instance |## Properties@@ -103,3 +107,26 @@ const composio = new Composio({autoUploadDownloadFiles: false,});```++### Per-execution `beforeFileUpload` modifier++Use the **third argument** to `composio.tools.execute` to intercept each file read before upload (in addition to global `sensitiveFileUploadProtection` on the client):++```typescript+import { Composio } from '@composio/core';++const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY! });++await composio.tools.execute(+ 'SOME_FILE_TOOL',+ { userId: 'u', arguments: { file: '/tmp/report.pdf' }, dangerouslySkipVersionCheck: true },+ {+ beforeFileUpload: async ({ path, toolSlug, toolkitSlug }) => {+ // return path, a different path, or false to abort+ return path;+ },+ }+);+```++See [Auto upload and download](./advanced/auto-upload-download.md#security-sensitive-local-paths) for the security model and error types.diff --git a/ts/packages/core/src/composio.ts b/ts/packages/core/src/composio.tsindex 82c821a0b..10f1f3e23 100644--- a/ts/packages/core/src/composio.ts+++ b/ts/packages/core/src/composio.ts@@ -46,6 +46,19 @@ export type ComposioConfig<* @default true*/autoUploadDownloadFiles?: boolean;+ /**+ * When true, local file paths for auto-upload and `files.upload` are checked against+ * a built-in denylist of sensitive path segments (e.g. `.ssh`, `.aws`) and+ * credential-like file names (e.g. `.env`, default SSH private key names). URLs and+ * {@link File} objects are not path-checked.+ * @default true+ */+ sensitiveFileUploadProtection?: boolean;+ /**+ * Extra path components (a single directory or file name) to treat as sensitive when+ * they appear anywhere in the resolved path. Merged with the built-in list.+ */+ fileUploadPathDenySegments?: string[];/*** The tool provider to use for this Composio instance.* @example new OpenAIProvider()@@ -253,6 +266,8 @@ export class Composio<allowTracking: config?.allowTracking ?? CONFIG_DEFAULTS.allowTracking,autoUploadDownloadFiles:config?.autoUploadDownloadFiles ?? CONFIG_DEFAULTS.autoUploadDownloadFiles,+ sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection,+ fileUploadPathDenySegments: config?.fileUploadPathDenySegments,provider: config?.provider ?? this.provider,};@@ -274,7 +289,10 @@ export class Composio<this.toolkits = new Toolkits(this.client);this.triggers = new Triggers(this.client, this.config);this.authConfigs = new AuthConfigs(this.client);- this.files = new Files(this.client);+ this.files = new Files(this.client, {+ sensitiveFileUploadProtection: this.config.sensitiveFileUploadProtection,+ fileUploadPathDenySegments: this.config.fileUploadPathDenySegments,+ });this.connectedAccounts = new ConnectedAccounts(this.client);this.toolRouter = new ToolRouter(this.client, this.config);diff --git a/ts/packages/core/src/errors/FileModifierErrors.ts b/ts/packages/core/src/errors/FileModifierErrors.tsindex 59642e0d4..943da80f2 100644--- a/ts/packages/core/src/errors/FileModifierErrors.ts+++ b/ts/packages/core/src/errors/FileModifierErrors.ts@@ -2,18 +2,53 @@ import { ComposioError, ComposioErrorOptions } from './ComposioError';export const FileModifierErrorCodes = {FILE_UPLOAD_FAILED: 'FILE_UPLOAD_FAILED',+ SENSITIVE_FILE_PATH_BLOCKED: 'SENSITIVE_FILE_PATH_BLOCKED',+ FILE_UPLOAD_ABORTED: 'FILE_UPLOAD_ABORTED',} as const;export class ComposioFileUploadError extends ComposioError {- constructor(- message: string = 'Failed to upload file',- options: Omit<ComposioErrorOptions, 'code'> = {}- ) {+ constructor(message: string = 'Failed to upload file', options: ComposioErrorOptions = {}) {super(message, {...options,- code: FileModifierErrorCodes.FILE_UPLOAD_FAILED,+ code: options.code ?? FileModifierErrorCodes.FILE_UPLOAD_FAILED,possibleFixes: options.possibleFixes || ['Check if the file exists in the location provided'],});this.name = 'ComposioFileUploadError';}}++/**+ * Thrown when a local file path is refused before upload (sensitive directory or+ * credential-like file name). Subclass of {@link ComposioFileUploadError} so existing+ * `instanceof ComposioFileUploadError` handlers still apply.+ */+export class ComposioSensitiveFilePathBlockedError extends ComposioFileUploadError {+ constructor(message: string, options: ComposioErrorOptions = {}) {+ super(message, {+ ...options,+ code: FileModifierErrorCodes.SENSITIVE_FILE_PATH_BLOCKED,+ possibleFixes: options.possibleFixes ?? [+ 'Use a file outside ~/.ssh, ~/.aws, and other credential locations',+ 'Set sensitiveFileUploadProtection: false only if you understand the risk',+ 'Add path segments to block with fileUploadPathDenySegments',+ ],+ });+ this.name = 'ComposioSensitiveFilePathBlockedError';+ }+}++/**+ * Thrown when a `beforeFileUpload` hook returns `false`.+ */+export class ComposioFileUploadAbortedError extends ComposioFileUploadError {+ constructor(message: string, options: ComposioErrorOptions = {}) {+ super(message, {+ ...options,+ code: FileModifierErrorCodes.FILE_UPLOAD_ABORTED,+ possibleFixes: options.possibleFixes ?? [+ 'Change beforeFileUpload to return a file path to upload, or allow the upload to proceed',+ ],+ });+ this.name = 'ComposioFileUploadAbortedError';+ }+}diff --git a/ts/packages/core/src/errors/index.ts b/ts/packages/core/src/errors/index.tsindex b0da52b74..ee047fb35 100644--- a/ts/packages/core/src/errors/index.ts+++ b/ts/packages/core/src/errors/index.ts@@ -36,3 +36,6 @@ export * from './TriggerErrors';// Remote File Errorsexport * from './RemoteFileErrors';++// File modifier / auto upload+export * from './FileModifierErrors';diff --git a/ts/packages/core/src/models/Files.node.ts b/ts/packages/core/src/models/Files.node.tsindex 590987194..db18820ab 100644--- a/ts/packages/core/src/models/Files.node.ts+++ b/ts/packages/core/src/models/Files.node.ts@@ -11,7 +11,19 @@ import { downloadFileFromS3, getFileDataAfterUploadingToS3 } from '../utils/fileimport { telemetry } from '../telemetry/Telemetry';export class Files {- constructor(private readonly client: ComposioClient) {+ private readonly fileUploadPathOptions: {+ sensitiveFileUploadProtection?: boolean;+ fileUploadPathDenySegments?: string[];+ };++ constructor(+ private readonly client: ComposioClient,+ fileUploadPathOptions: {+ sensitiveFileUploadProtection?: boolean;+ fileUploadPathDenySegments?: string[];+ } = {}+ ) {+ this.fileUploadPathOptions = fileUploadPathOptions;telemetry.instrument(this, 'Files');}@@ -45,6 +57,8 @@ export class Files {toolSlug,toolkitSlug,client: this.client,+ sensitiveFileUploadProtection: this.fileUploadPathOptions.sensitiveFileUploadProtection,+ fileUploadPathDenySegments: this.fileUploadPathOptions.fileUploadPathDenySegments,});return fileData;}diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.tsindex 909a2793a..d2352cd37 100644--- a/ts/packages/core/src/models/Tools.ts+++ b/ts/packages/core/src/models/Tools.ts@@ -33,7 +33,6 @@ import { CustomTools } from './CustomTools';import { CustomToolInputParameter, CustomToolOptions } from '../types/customTool.types';import {afterExecuteModifier,- beforeExecuteModifier,ExecuteToolModifiers,SessionExecuteMetaModifiers,ProviderOptions,@@ -71,6 +70,10 @@ export class Tools<private provider: TProvider;private autoUploadDownloadFiles: boolean;private toolkitVersions: ToolkitVersionParam;+ private fileUploadPathOptions: {+ sensitiveFileUploadProtection?: boolean;+ fileUploadPathDenySegments?: string[];+ };constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {if (!client) {@@ -86,6 +89,10 @@ export class Tools<this.autoUploadDownloadFiles =config?.autoUploadDownloadFiles ?? CONFIG_DEFAULTS.autoUploadDownloadFiles;this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;+ this.fileUploadPathOptions = {+ sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection,+ fileUploadPathDenySegments: config?.fileUploadPathDenySegments,+ };// Bind the execute method to ensure correct 'this' contextthis.execute = this.execute.bind(this);// Set the execute method for the provider.@@ -149,7 +156,7 @@ export class Tools<*/private async applyDefaultSchemaModifiers(tools: Tool[]): Promise<Tool[]> {if (this.autoUploadDownloadFiles) {- const fileToolModifier = new FileToolModifier(this.client);+ const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions);return await Promise.all(tools.map(tool =>fileToolModifier.modifyToolSchema(tool.slug, tool.toolkit?.slug ?? 'unknown', tool)@@ -179,12 +186,15 @@ export class Tools<toolkitSlug: string;params: ToolExecuteParams;},- modifier?: beforeExecuteModifier+ modifiers?: ExecuteToolModifiers): Promise<ToolExecuteParams> {let modifiedParams = params;// if auto upload download files is enabled, upload the files to the Composio APIif (this.autoUploadDownloadFiles) {- const fileToolModifier = new FileToolModifier(this.client);+ const fileToolModifier = new FileToolModifier(this.client, {+ ...this.fileUploadPathOptions,+ beforeFileUpload: modifiers?.beforeFileUpload,+ });modifiedParams = await fileToolModifier.fileUploadModifier(tool, {toolSlug,toolkitSlug,@@ -192,9 +202,9 @@ export class Tools<});}// apply the before execute modifiers- if (modifier) {- if (typeof modifier === 'function') {- modifiedParams = await modifier({+ if (modifiers?.beforeExecute) {+ if (typeof modifiers.beforeExecute === 'function') {+ modifiedParams = await modifiers.beforeExecute({toolSlug,toolkitSlug,params: modifiedParams,@@ -230,7 +240,7 @@ export class Tools<let modifiedResult = result;// if auto upload download files is enabled, download the files from the Composio APIif (this.autoUploadDownloadFiles) {- const fileToolModifier = new FileToolModifier(this.client);+ const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions);modifiedResult = await fileToolModifier.fileDownloadModifier(tool, {toolSlug,toolkitSlug,@@ -921,7 +931,7 @@ export class Tools<toolkitSlug,params: executeParams.data,},- modifiers?.beforeExecute+ modifiers);// Execute the tool (custom or composio)diff --git a/ts/packages/core/src/types/modifiers.types.ts b/ts/packages/core/src/types/modifiers.types.tsindex fb9564105..9966c462f 100644--- a/ts/packages/core/src/types/modifiers.types.ts+++ b/ts/packages/core/src/types/modifiers.types.ts@@ -179,6 +179,19 @@ export type afterExecuteModifier = (context: {result: ToolExecuteResponse;}) => Promise<ToolExecuteResponse> | ToolExecuteResponse;+/**+ * Called for each `file_uploadable` value before the SDK reads the file and uploads to storage.+ * For a string, `path` is the local path or URL. For a `File` object, `path` is the file's name; you may return+ * a different filesystem path to upload instead, or return `false` to abort the upload. Throwing an error also aborts.+ */+export type beforeFileUploadModifier = (context: {+ path: string;+ toolSlug: string;+ toolkitSlug: string;+}) => Promise<string | false> | string | false;++type BeforeFileUploadHook = { beforeFileUpload?: beforeFileUploadModifier };+/*** Modifier for altering the tool schema before it's exposed to consumers.*@@ -349,7 +362,7 @@ export type ToolOptions = {* This allows customizing input/output parameters, descriptions, and other metadata.*/modifySchema?: TransformToolSchemaModifier;-};+} & BeforeFileUploadHook;/*** Options for configuring tool execution behavior.@@ -390,7 +403,7 @@ export type ExecuteToolModifiers = {* This allows transforming the response or implementing custom error handling.*/afterExecute?: afterExecuteModifier;-};+} & BeforeFileUploadHook;/*** Type alias for meta tool execution arguments.diff --git a/ts/packages/core/src/utils/fileUtils.node.ts b/ts/packages/core/src/utils/fileUtils.node.tsindex 658ab70bf..3d907e0dc 100644--- a/ts/packages/core/src/utils/fileUtils.node.ts+++ b/ts/packages/core/src/utils/fileUtils.node.ts@@ -7,6 +7,26 @@ import logger from './logger';import { getRandomShortId } from './uuid';import { base64ToUint8Array, uint8ArrayToBase64 } from './buffer';import type { FileDownloadData, FileUploadData } from '../types/files.types';+import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths.node';++/**+ * Options for {@link getFileDataAfterUploadingToS3} (S3 presigned upload from local path, URL, or File).+ */+export type GetFileDataAfterUploadingToS3Options = {+ toolSlug: string;+ toolkitSlug: string;+ client: ComposioClient;+ /**+ * When false, skips the sensitive-path blocklist. URLs and {@link File} objects are never checked.+ * @default true+ */+ sensitiveFileUploadProtection?: boolean;+ /**+ * Extra path segments (one directory/file component) to block anywhere in the resolved path;+ * merged with the built-in list.+ */+ fileUploadPathDenySegments?: string[];+};// Helper function to get file extension from MIME typeconst getExtensionFromMimeType = (mimeType: string): string => {@@ -222,16 +242,22 @@ export const getFileDataAfterUploadingToS3 = async (toolSlug,toolkitSlug,client,- }: {- toolSlug: string;- toolkitSlug: string;- client: ComposioClient;- }+ sensitiveFileUploadProtection,+ fileUploadPathDenySegments,+ }: GetFileDataAfterUploadingToS3Options): Promise<FileUploadData> => {if (!file) {throw new Error('Either path or blob must be provided');}+ if (+ sensitiveFileUploadProtection !== false &&+ typeof file === 'string' &&+ !file.startsWith('http')+ ) {+ assertSafeFileUploadPath(file, { additionalDenySegments: fileUploadPathDenySegments });+ }+const fileData = await readFile(file);logger.debug(`Uploading file to S3...`);const s3key = await uploadFileToS3(diff --git a/ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts b/ts/packages/core/src/utils/modifiers/FileToolModifier.node.tsindex b2d4ce53b..ff6c31efd 100644--- a/ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts+++ b/ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts@@ -6,8 +6,17 @@ import {} from '../../types/tool.types';import ComposioClient from '@composio/client';import logger from '../logger';-import { ComposioFileUploadError } from '../../errors/FileModifierErrors';-import { downloadFileFromS3, getFileDataAfterUploadingToS3 } from '../fileUtils.node';+import {+ ComposioFileUploadAbortedError,+ ComposioFileUploadError,+ ComposioSensitiveFilePathBlockedError,+} from '../../errors/FileModifierErrors';+import type { beforeFileUploadModifier } from '../../types/modifiers.types';+import {+ downloadFileFromS3,+ getFileDataAfterUploadingToS3,+ type GetFileDataAfterUploadingToS3Options,+} from '../fileUtils.node';import {isPlainObject,transformProperties,@@ -28,7 +37,12 @@ const hydrateFiles = async (toolSlug: string;toolkitSlug: string;client: ComposioClient;- }+ } & Pick<+ GetFileDataAfterUploadingToS3Options,+ 'sensitiveFileUploadProtection' | 'fileUploadPathDenySegments'+ > & {+ beforeFileUpload?: beforeFileUploadModifier;+ }): Promise<unknown> => {// ──────────────────────────────────────────────────────────────────────────// 1. Direct file upload@@ -37,11 +51,65 @@ const hydrateFiles = async (// Upload only if the runtime value is a string (i.e., a local path) or blobif (typeof value !== 'string' && !(value instanceof File)) return value;- logger.debug(`Uploading file "${value}"`);+ const runBeforeFileUpload = async (path: string): Promise<string> => {+ if (!ctx.beforeFileUpload) {+ return path;+ }+ const out = await ctx.beforeFileUpload({+ path,+ toolSlug: ctx.toolSlug,+ toolkitSlug: ctx.toolkitSlug,+ });+ if (out === false) {+ throw new ComposioFileUploadAbortedError(+ 'File upload was aborted because beforeFileUpload returned false.'+ );+ }+ return out;+ };++ if (typeof value === 'string') {+ const pathOrUrl = await runBeforeFileUpload(value);+ logger.debug(`Uploading file "${pathOrUrl}"`);+ return getFileDataAfterUploadingToS3(pathOrUrl, {+ toolSlug: ctx.toolSlug,+ toolkitSlug: ctx.toolkitSlug,+ client: ctx.client,+ sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,+ fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,+ });+ }++ // File+ if (ctx.beforeFileUpload) {+ const out = await ctx.beforeFileUpload({+ path: value.name,+ toolSlug: ctx.toolSlug,+ toolkitSlug: ctx.toolkitSlug,+ });+ if (out === false) {+ throw new ComposioFileUploadAbortedError(+ 'File upload was aborted because beforeFileUpload returned false.'+ );+ }+ if (typeof out === 'string' && out !== value.name) {+ logger.debug(`Uploading file from path "${out}" (replaced File: ${value.name})`);+ return getFileDataAfterUploadingToS3(out, {+ toolSlug: ctx.toolSlug,+ toolkitSlug: ctx.toolkitSlug,+ client: ctx.client,+ sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,+ fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,+ });+ }+ }+ logger.debug(`Uploading file "${value.name}"`);return getFileDataAfterUploadingToS3(value, {toolSlug: ctx.toolSlug,toolkitSlug: ctx.toolkitSlug,client: ctx.client,+ sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,+ fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,});}@@ -234,9 +302,17 @@ const hydrateDownloads = async (export class FileToolModifier {private client: ComposioClient;-- constructor(client: ComposioClient) {+ private fileUploadPathOptions: Pick<+ GetFileDataAfterUploadingToS3Options,+ 'sensitiveFileUploadProtection' | 'fileUploadPathDenySegments'+ > & { beforeFileUpload?: beforeFileUploadModifier };++ constructor(+ client: ComposioClient,+ fileUploadPathOptions: FileToolModifier['fileUploadPathOptions'] = {}+ ) {this.client = client;+ this.fileUploadPathOptions = fileUploadPathOptions;}async modifyToolSchema(toolSlug: string, toolkitSlug: string, schema: Tool): Promise<Tool> {@@ -274,9 +350,16 @@ export class FileToolModifier {toolSlug,toolkitSlug,client: this.client,+ ...this.fileUploadPathOptions,});return { ...params, arguments: newArgs as ToolExecuteParams['arguments'] };} catch (error) {+ if (+ error instanceof ComposioSensitiveFilePathBlockedError ||+ error instanceof ComposioFileUploadAbortedError+ ) {+ throw error;+ }throw new ComposioFileUploadError('Failed to upload file', {cause: error,});diff --git a/ts/packages/core/src/utils/sensitiveFileUploadPaths.node.ts b/ts/packages/core/src/utils/sensitiveFileUploadPaths.node.tsnew file mode 100644index 000000000..72506a2e0--- /dev/null+++ b/ts/packages/core/src/utils/sensitiveFileUploadPaths.node.ts@@ -0,0 +1,105 @@+/**+ * Blocks accidental upload of local files from well-known secret/credential locations+ * during auto file upload (and {@link getFileDataAfterUploadingToS3}).+ */+import * as path from 'node:path';+import fs from 'node:fs';+import { ComposioSensitiveFilePathBlockedError } from '../errors/FileModifierErrors';++/**+ * Path segments (a single path component) that indicate a sensitive directory when+ * they appear anywhere in a resolved local path. Compared case-insensitively on Windows.+ */+export const BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS: readonly string[] = [+ '.ssh',+ '.aws',+ '.azure',+ '.gnupg',+ '.kube',+ '.docker',+ '.claude', // may contain API keys and project context read by assistants+ '.password-store',+ 'keychains', // e.g. ~/Library/Keychains+];++const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;+/** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */+const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;++/**+ * Returns normalized path segments, resolving symlinks when the path exists.+ */+function normalizePathSegments(filePath: string): string[] {+ const absolute = path.resolve(filePath);+ let resolved = absolute;+ try {+ if (fs.existsSync(absolute)) {+ resolved = fs.realpathSync(absolute);+ }+ } catch {+ // If realpath fails (e.g. race), use resolved path+ }+ return resolved.split(/[/\\]+/).filter(Boolean);+}++/**+ * True if the path is under a built-in or extra deny segment, or the basename+ * looks like an env / netrc / default SSH private key name.+ */+export function isBlockedSensitiveFileUploadPath(+ filePath: string,+ additionalDenySegments?: string[]+): boolean {+ return getSensitiveFileUploadPathBlockReason(filePath, additionalDenySegments) != null;+}++function getSensitiveFileUploadPathBlockReason(+ filePath: string,+ additionalDenySegments?: string[]+): string | null {+ const segments = normalizePathSegments(filePath);+ const isWin = process.platform === 'win32';+ const deny = new Set(+ [+ ...BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,+ ...(additionalDenySegments ?? []).map(s => s.trim()).filter(Boolean),+ ].map(s => (isWin ? s.toLowerCase() : s))+ );++ // Windows: compare segments case-insensitively; map once instead of toLowerCase per iteration.+ const segmentsForMatch = isWin ? segments.map(s => s.toLowerCase()) : segments;+ for (let i = 0; i < segments.length; i++) {+ if (deny.has(segmentsForMatch[i]!)) {+ return `path segment "${segments[i]}" is in the sensitive file upload denylist`;+ }+ }++ const basename = segments.length > 0 ? segments[segments.length - 1] : '';+ if (basename) {+ if (SECRET_LIKE_BASENAME.test(basename) || DEFAULT_PRIVATE_KEY_BASENAME.test(basename)) {+ return `file name "${basename}" looks like a credential, env, or private key file`;+ }+ if (basename.toLowerCase() === 'credentials') {+ return 'file name "credentials" is often used for cloud/API credential stores';+ }+ }+ return null;+}++/**+ * @throws {ComposioSensitiveFilePathBlockedError} if the path is not allowed+ */+export function assertSafeFileUploadPath(+ filePath: string,+ options?: { additionalDenySegments?: string[] }+): void {+ const reason = getSensitiveFileUploadPathBlockReason(filePath, options?.additionalDenySegments);+ if (reason) {+ throw new ComposioSensitiveFilePathBlockedError(+ `Refusing to upload: ${reason}. ` ++ `To upload from this path anyway, set sensitiveFileUploadProtection: false on Composio ` ++ `(not recommended) or use a copy outside sensitive locations.`,+ { meta: { filePath, reason } }+ );+ }+}diff --git a/ts/packages/core/test/tools/fileModifiers.test.ts b/ts/packages/core/test/tools/fileModifiers.test.tsindex 63b981199..06023bb41 100644--- a/ts/packages/core/test/tools/fileModifiers.test.ts+++ b/ts/packages/core/test/tools/fileModifiers.test.ts@@ -2,7 +2,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { FileToolModifier } from '#file_tool_modifier';import ComposioClient from '@composio/client';import { Tool } from '../../src/types/tool.types';-import { ComposioFileUploadError } from '../../src/errors/FileModifierErrors';+import {+ ComposioFileUploadAbortedError,+ ComposioFileUploadError,+} from '../../src/errors/FileModifierErrors';import * as fileUtils from '../../src/utils/fileUtils.node';import { Tools } from '../../src/models/Tools';import { createTestContext, setupTest, mockToolExecution } from '../utils/toolExecuteUtils';@@ -330,6 +333,59 @@ describe('FileToolModifier', () => {expect(result.arguments?.text).toBe('some text');});+ it('should call beforeFileUpload and use returned path for string files', async () => {+ const mockFileData = {+ name: 'file.txt',+ mimetype: 'text/plain',+ s3key: 'uploads/file.txt',+ };+ vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockResolvedValue(mockFileData);++ const withHook = new FileToolModifier(mockClient, {+ beforeFileUpload: async ({ path, toolSlug, toolkitSlug }) => {+ expect(toolSlug).toBe('test-tool');+ expect(toolkitSlug).toBe('test-toolkit');+ return path.replace('original', 'rewritten');+ },+ });++ const params = {+ arguments: { file: '/path/to/original.txt' },+ userId: 'test-user',+ };++ const result = await withHook.fileUploadModifier(mockTool, {+ toolSlug: 'test-tool',+ toolkitSlug: 'test-toolkit',+ params,+ });++ expect(fileUtils.getFileDataAfterUploadingToS3).toHaveBeenCalledWith(+ '/path/to/rewritten.txt',+ {+ toolSlug: 'test-tool',+ toolkitSlug: 'test-toolkit',+ client: mockClient,+ }+ );+ expect(result.arguments?.file).toEqual(mockFileData);+ });++ it('should throw ComposioFileUploadAbortedError when beforeFileUpload returns false', async () => {+ const withHook = new FileToolModifier(mockClient, {+ beforeFileUpload: async () => false,+ });++ await expect(+ withHook.fileUploadModifier(mockTool, {+ toolSlug: 'test-tool',+ toolkitSlug: 'test-toolkit',+ params: { arguments: { file: '/any/path' }, userId: 'u' },+ })+ ).rejects.toThrow(ComposioFileUploadAbortedError);+ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();+ });+it('should throw ComposioFileUploadError on upload failure', async () => {vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockRejectedValue(new Error('Upload failed')diff --git a/ts/packages/core/test/utils/fileUtils.test.ts b/ts/packages/core/test/utils/fileUtils.test.tsindex 2bad3aaad..67ec74618 100644--- a/ts/packages/core/test/utils/fileUtils.test.ts+++ b/ts/packages/core/test/utils/fileUtils.test.ts@@ -1,6 +1,8 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import * as path from 'node:path';import { getFileDataAfterUploadingToS3, downloadFileFromS3 } from '../../src/utils/fileUtils.node';import ComposioClient from '@composio/client';+import { ComposioSensitiveFilePathBlockedError } from '../../src/errors/FileModifierErrors';// Mock the uuid modulevi.mock('../../src/utils/uuid', () => ({@@ -30,15 +32,15 @@ vi.mock('os', () => ({homedir: vi.fn(() => '/home/test'),}));-// Mock path module-vi.mock('path', () => ({- default: {- join: vi.fn((...args) => args.join('/')),- basename: vi.fn(path => path.split('/').pop()),- },- join: vi.fn((...args) => args.join('/')),- basename: vi.fn(path => path.split('/').pop()),-}));+// Mock path module (keep resolve/join for sensitive path checks; basename stays mocked for fileUtils)+vi.mock('path', async importOriginal => {+ const actual = await importOriginal<typeof import('node:path')>();+ return {+ ...actual,+ default: actual,+ basename: vi.fn((p: string) => p.split('/').pop() ?? p),+ };+});// Mock global fetchconst mockFetch = vi.fn();@@ -367,6 +369,16 @@ describe('fileUtils', () => {// Note: Local file handling tests are covered in the existing fileModifiers.test.tsdescribe('Error handling', () => {+ it('refuses sensitive local paths before read or S3 (built-in denylist)', async () => {+ await expect(+ getFileDataAfterUploadingToS3(path.join('/home/test', '.aws', 'creds'), {+ toolSlug: 'test-tool',+ toolkitSlug: 'test-toolkit',+ client: mockClient,+ })+ ).rejects.toThrow(ComposioSensitiveFilePathBlockedError);+ });+it('should handle fetch errors for URLs', async () => {mockFetch.mockResolvedValue({ok: false,diff --git a/ts/packages/core/test/utils/sensitiveFileUploadPaths.test.ts b/ts/packages/core/test/utils/sensitiveFileUploadPaths.test.tsnew file mode 100644index 000000000..b13fb5144--- /dev/null+++ b/ts/packages/core/test/utils/sensitiveFileUploadPaths.test.ts@@ -0,0 +1,65 @@+import { describe, it, expect } from 'vitest';+import * as path from 'node:path';+import * as os from 'node:os';+import { mkdtempSync, writeFileSync, symlinkSync, rmSync, mkdirSync } from 'node:fs';+import {+ assertSafeFileUploadPath,+ isBlockedSensitiveFileUploadPath,+} from '../../src/utils/sensitiveFileUploadPaths.node';++describe('sensitiveFileUploadPaths', () => {+ it('allows normal project files', () => {+ const p = path.join('/tmp', 'composio-test', 'document.pdf');+ expect(isBlockedSensitiveFileUploadPath(p)).toBe(false);+ expect(() => assertSafeFileUploadPath(p)).not.toThrow();+ });++ it('blocks common credential directory segments', () => {+ expect(isBlockedSensitiveFileUploadPath(path.join(os.homedir(), '.aws', 'credentials'))).toBe(+ true+ );+ expect(isBlockedSensitiveFileUploadPath(path.join(os.homedir(), '.ssh', 'id_ed25519'))).toBe(+ true+ );+ expect(+ isBlockedSensitiveFileUploadPath(path.join(os.homedir(), '.claude', 'settings.json'))+ ).toBe(true);+ });++ it('blocks .env-style basenames', () => {+ expect(isBlockedSensitiveFileUploadPath(path.join('/app', 'repo', '.env'))).toBe(true);+ expect(isBlockedSensitiveFileUploadPath(path.join('/app', 'repo', '.env.local'))).toBe(true);+ });++ it('blocks default private key basenames (defense in depth)', () => {+ expect(isBlockedSensitiveFileUploadPath(path.join('/tmp', 'id_ed25519'))).toBe(true);+ });++ it('does not block public key files by basename', () => {+ expect(isBlockedSensitiveFileUploadPath(path.join('/tmp', 'id_ed25519.pub'))).toBe(false);+ });++ it('honors additional deny segments from config', () => {+ expect(+ isBlockedSensitiveFileUploadPath(path.join('/data', 'secrets', 'x.txt'), ['secrets'])+ ).toBe(true);+ expect(isBlockedSensitiveFileUploadPath(path.join('/data', 'ok', 'x.txt'), ['secrets'])).toBe(+ false+ );+ });++ it('blocks after realpath resolves a symlink into a sensitive directory', () => {+ const root = mkdtempSync(path.join(os.tmpdir(), 'composio-symlink-'));+ try {+ const awsDir = path.join(root, 'nested', '.aws');+ mkdirSync(awsDir, { recursive: true });+ const target = path.join(awsDir, 'creds');+ writeFileSync(target, 'x');+ const link = path.join(root, 'innocent-name');+ symlinkSync(target, link);+ expect(isBlockedSensitiveFileUploadPath(link)).toBe(true);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+});diff --git a/uv.lock b/uv.lockindex 1f8caa17e..00c3b7542 100644--- a/uv.lock+++ b/uv.lock@@ -591,7 +591,7 @@ wheels = [[[package]]name = "composio"-version = "0.11.2"+version = "0.11.6"source = { virtual = "python" }dependencies = [{ name = "composio-client" },@@ -621,7 +621,7 @@ dev = [[package.metadata]requires-dist = [- { name = "composio-client", specifier = "==1.28.0" },+ { name = "composio-client", specifier = "==1.33.0" },{ name = "json-schema-to-pydantic", specifier = ">=0.4.8" },{ name = "openai" },{ name = "pydantic", specifier = ">=2.6.4" },@@ -648,7 +648,7 @@ dev = [[[package]]name = "composio-anthropic"-version = "0.11.2"+version = "0.11.6"source = { virtual = "python/providers/anthropic" }dependencies = [{ name = "anthropic" },@@ -663,7 +663,7 @@ requires-dist = [[[package]]name = "composio-client"-version = "1.28.0"+version = "1.33.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "anyio" },@@ -673,14 +673,14 @@ dependencies = [{ name = "sniffio" },{ name = "typing-extensions" },]-sdist = { url = "https://files.pythonhosted.org/packages/99/45/5f063d364bef7879252c3dab517a42a9f3fdf1ad8943895f5b718c27fd31/composio_client-1.28.0.tar.gz", hash = "sha256:787869c1fba543f07aa26d1f64e5f37e4909465b37af24ec4b5a01fd73115045", size = 209918 }+sdist = { url = "https://files.pythonhosted.org/packages/4b/11/88d09721f03431deb8b055fe39cedb79697e5a72d4342fa033d277b1eb70/composio_client-1.33.0.tar.gz", hash = "sha256:3b92400383ca2454a361e3ad8d55e2b447b47ed3c4cd4910f61466e5933554c1", size = 225669 }wheels = [- { url = "https://files.pythonhosted.org/packages/4e/8c/901f59aaf8674f8bda6da1fbae087eb5209f11a9b26f6118c2be49702d0c/composio_client-1.28.0-py3-none-any.whl", hash = "sha256:8f037d8e66b3bfb3aa701b4d26c8a242d22638031b938a363874ebc41e4710ee", size = 239827 },+ { url = "https://files.pythonhosted.org/packages/93/bc/83efc07964e39109c4471f8873dda98cd16137c8e4e2d4456a8a5d8f9c42/composio_client-1.33.0-py3-none-any.whl", hash = "sha256:8c01f096772272398760f5c553b3444b5706e346b294856f613b092f1d3afd6b", size = 252699 },][[package]]name = "composio-crewai"-version = "0.11.2"+version = "0.11.6"source = { virtual = "python/providers/crewai" }dependencies = [{ name = "composio" },@@ -695,7 +695,7 @@ requires-dist = [[[package]]name = "composio-gemini"-version = "0.11.2"+version = "0.11.6"source = { virtual = "python/providers/gemini" }dependencies = [{ name = "composio" },@@ -710,7 +710,7 @@ requires-dist = [[[package]]name = "composio-google"-version = "0.11.2"+version = "0.11.6"source = { virtual = "python/providers/google" }dependencies = [{ name = "composio" },@@ -725,7 +725,7 @@ requires-dist = [[[package]]name = "composio-google-adk"-version = "0.11.2"+version = "0.11.6"source = { virtual = "python/providers/google_adk" }dependencies = [{ name = "composio" },@@ -740,7 +740,7 @@ requires-dist = [[[package]]name = "composio-langchain"-version = "0.11.2"+version = "0.11.6"source = { virtual = "python/providers/langchain" }dependencies = [{ name = "composio" },@@ -755,7 +755,7 @@ requires-dist = [[[package]]name = "composio-openai"-version = "0.11.2"+version = "0.11.6"source = { virtual = "python/providers/openai" }dependencies = [{ name = "composio" },@@ -770,7 +770,7 @@ requires-dist = [[[package]]name = "composio-openai-agents"-version = "0.11.2"+version = "0.11.6"source = { virtual = "python/providers/openai_agents" }dependencies = [{ name = "composio" },