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
fix(cli): enforce sensitive-file upload denylist (GHSA-hp3h-89pf-5q58) (#3763)
Alberto Schiabelfc17c37bf95b
diff --git a/.changeset/cli-file-upload-denylist.md b/.changeset/cli-file-upload-denylist.mdnew file mode 100644index 000000000..249cccec5--- /dev/null+++ b/.changeset/cli-file-upload-denylist.md@@ -0,0 +1,7 @@+---+'@composio/cli': patch+---++Security: the CLI's tool file-upload path now enforces the sensitive-file denylist (issue #3746 / GHSA-hp3h-89pf-5q58). Previously `composio execute`/`composio run` read and uploaded any local path a tool argument pointed at — including `~/.ssh/id_rsa`, `~/.aws/credentials`, and `.env` files — enabling credential exfiltration in agentic workflows via prompt injection. The CLI now calls the shared `assertSafeFileUploadPath` guard from `@composio/core` at the lowest-level file read. URLs and `File` objects are unaffected.++Unlike the core and Python SDKs (which expose a `sensitiveFileUploadProtection` / `sensitive_file_upload_protection` opt-out), the CLI enforces the denylist **unconditionally by design** — the primary attack vector is an agent prompt-injected into supplying its own tool arguments, so a CLI override flag would hand that attacker a trivial bypass. The block error carries CLI-appropriate remediation guidance instead of pointing at the SDK-only flag.diff --git a/.changeset/sensitive-file-upload-guard-shared.md b/.changeset/sensitive-file-upload-guard-shared.mdnew file mode 100644index 000000000..3bf05f217--- /dev/null+++ b/.changeset/sensitive-file-upload-guard-shared.md@@ -0,0 +1,5 @@+---+'@composio/core': minor+---++Export the sensitive-file-upload denylist guard from the package root so downstream packages share one implementation: `assertSafeFileUploadPath`, `isBlockedSensitiveFileUploadPath`, and `BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS`. The guard now routes its filesystem access through the internal `#platform` abstraction (adding a `realpathSync` platform method), so it is edge/workerd-safe and the module carries no static `node:*` imports. Behavior on Node/Bun is unchanged.diff --git a/python/tests/test_files.py b/python/tests/test_files.pyindex 8db242b9a..4b924b230 100644--- a/python/tests/test_files.py+++ b/python/tests/test_files.py@@ -4,6 +4,8 @@ These tests ensure that the FileHelper class correctly handles JSON schemasthat use anyOf, oneOf, allOf, or $ref instead of direct 'type' properties."""+import tempfile+from pathlib import Pathfrom unittest.mock import Mock, patch, MagicMockimport pytest@@ -28,6 +30,7 @@ from composio.exceptions import (ErrorDownloadingFile,ErrorUploadingFile,ResponseTooLargeError,+ SensitiveFilePathBlockedError,)@@ -2793,3 +2796,54 @@ class TestEnhanceSchemaDescriptionsEmptySchema:assert description != "Search term"assert "string" in descriptionassert "required" in description+++class TestFromPathSensitiveGuard:+ """`FileUploadable.from_path` is the single upload primitive in the Python+ SDK; the sensitive-path denylist must fire there before any file read or+ network round-trip (parity with the TS core SDK and the CLI fix for+ issue #3746 / GHSA-hp3h-89pf-5q58)."""++ def test_from_path_blocks_ssh_private_key(self, mock_client):+ p = Path.home() / ".ssh" / "id_rsa"+ with pytest.raises(SensitiveFilePathBlockedError):+ FileUploadable.from_path(+ client=mock_client,+ file=str(p),+ tool="GMAIL_SEND_EMAIL",+ toolkit="gmail",+ )+ # The guard runs before the SDK contacts the API for a presigned URL.+ mock_client.post.assert_not_called()++ def test_from_path_blocks_dotenv_basename(self, mock_client):+ p = Path(tempfile.gettempdir()) / ".env"+ with pytest.raises(SensitiveFilePathBlockedError):+ FileUploadable.from_path(+ client=mock_client,+ file=str(p),+ tool="GMAIL_SEND_EMAIL",+ toolkit="gmail",+ )+ mock_client.post.assert_not_called()++ def test_from_path_opt_out_disables_guard(self, mock_client):+ """`sensitive_file_upload_protection=False` restores the legacy+ (unguarded) behavior; the denylist no longer raises for that path."""+ # A non-existent basename under `.ssh`: the `.ssh` segment still trips the+ # denylist when protection is on, but the file never exists, so with+ # protection off we deterministically hit the missing-file path (no real+ # key read, no network) rather than the block error.+ p = Path.home() / ".ssh" / "composio-does-not-exist-guard-test"+ with pytest.raises(Exception) as exc_info:+ FileUploadable.from_path(+ client=mock_client,+ file=str(p),+ tool="GMAIL_SEND_EMAIL",+ toolkit="gmail",+ sensitive_file_upload_protection=False,+ )+ assert not isinstance(exc_info.value, SensitiveFilePathBlockedError)+ # Guard skipped, so the failure is downstream (missing file), before any+ # presigned-URL request.+ mock_client.post.assert_not_called()diff --git a/ts/packages/cli/src/services/tool-file-uploads.ts b/ts/packages/cli/src/services/tool-file-uploads.tsindex 1f1d73adf..9091e89a6 100644--- a/ts/packages/cli/src/services/tool-file-uploads.ts+++ b/ts/packages/cli/src/services/tool-file-uploads.ts@@ -1,6 +1,7 @@import fs from 'node:fs/promises';import path from 'node:path';import type { Composio as RawComposioClient } from '@composio/client';+import { assertSafeFileUploadPath } from '@composio/core';import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';type JsonSchema = Record<string, unknown>;@@ -146,11 +147,31 @@ const readFileFromUrl = async (url: string) => {};};-const readFileFromDisk = async (filePath: string) => ({- bytes: new Uint8Array(await fs.readFile(filePath)),- fileName: path.basename(filePath),- mimeType: 'application/octet-stream',-});+const readFileFromDisk = async (filePath: string) => {+ // Enforce the sensitive-path denylist at the lowest-level local read, so any+ // caller of this reader (not just `uploadToolInputFiles`) is protected. This+ // is the single canonical guard shared with `@composio/core`; without it the+ // CLI's upload path would silently exfiltrate ~/.ssh/id_rsa, ~/.aws/credentials,+ // .env files, etc. (issue #3746 / GHSA-hp3h-89pf-5q58). URLs and File objects+ // are intentionally not path-checked, matching the core SDK.+ //+ // The CLI intentionally exposes NO opt-out for this guard (unlike the core/Python+ // SDKs' `sensitiveFileUploadProtection` flag): the primary attack vector is an+ // agent that has been prompt-injected into supplying its own tool arguments, so a+ // `--force`/env override would hand that attacker a trivial bypass. Pass a+ // CLI-appropriate remediation so the error does not advertise an SDK-only opt-out.+ assertSafeFileUploadPath(filePath, {+ remediation:+ 'The Composio CLI always enforces this denylist and has no opt-out. To upload this ' ++ 'file, copy it to a location outside sensitive directories (e.g. ~/.ssh, ~/.aws) and ' ++ 'pass the copy instead.',+ });+ return {+ bytes: new Uint8Array(await fs.readFile(filePath)),+ fileName: path.basename(filePath),+ mimeType: 'application/octet-stream',+ };+};const readUploadSource = async (file: string | File) => {if (isFileLike(file)) {diff --git a/ts/packages/cli/test/src/services/tool-file-uploads.test.ts b/ts/packages/cli/test/src/services/tool-file-uploads.test.tsnew file mode 100644index 000000000..38ba73aed--- /dev/null+++ b/ts/packages/cli/test/src/services/tool-file-uploads.test.ts@@ -0,0 +1,112 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import * as os from 'node:os';+import * as path from 'node:path';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import type { Composio as RawComposioClient } from '@composio/client';+import { ComposioSensitiveFilePathBlockedError } from '@composio/core';+import { uploadToolInputFiles } from 'src/services/tool-file-uploads';++// Schema with a single `file_uploadable` attachment field — mirrors tools like+// GMAIL_SEND_EMAIL whose attachment is uploaded from a local path.+const inputSchema = {+ type: 'object',+ properties: {+ attachment: { file_uploadable: true, type: 'string' },+ },+};++const makeClient = (createPresignedURL = vi.fn()) =>+ ({ files: { createPresignedURL } }) as unknown as RawComposioClient;++describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it('refuses to read/upload a path under a sensitive directory (~/.ssh/id_rsa)', async () => {+ const createPresignedURL = vi.fn();+ const client = makeClient(createPresignedURL);++ await expect(+ uploadToolInputFiles({+ toolSlug: 'GMAIL_SEND_EMAIL',+ arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },+ inputSchema,+ client,+ })+ ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError);++ // The guard must fire BEFORE any network round-trip: no presigned URL, no upload.+ expect(createPresignedURL).not.toHaveBeenCalled();+ });++ it('surfaces CLI-appropriate remediation, not the SDK-only opt-out, in the block error', async () => {+ const client = makeClient(vi.fn());++ // The CLI has no `sensitiveFileUploadProtection` opt-out (by design), so the+ // error must not point users at that non-existent knob (issue #3763 review #2/#3).+ await expect(+ uploadToolInputFiles({+ toolSlug: 'GMAIL_SEND_EMAIL',+ arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },+ inputSchema,+ client,+ })+ ).rejects.toThrowError(/has no opt-out/i);++ await expect(+ uploadToolInputFiles({+ toolSlug: 'GMAIL_SEND_EMAIL',+ arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },+ inputSchema,+ client,+ })+ ).rejects.not.toThrowError(/sensitiveFileUploadProtection/);+ });++ it('refuses credential-like basenames (.env) even outside a sensitive directory', async () => {+ const createPresignedURL = vi.fn();+ const client = makeClient(createPresignedURL);++ await expect(+ uploadToolInputFiles({+ toolSlug: 'GMAIL_SEND_EMAIL',+ arguments_: { attachment: path.join(os.tmpdir(), '.env') },+ inputSchema,+ client,+ })+ ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError);+ expect(createPresignedURL).not.toHaveBeenCalled();+ });++ it('still uploads a normal (non-sensitive) local file', async () => {+ const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));+ try {+ const file = path.join(root, 'document.pdf');+ writeFileSync(file, 'hello');++ const createPresignedURL = vi.fn(async () => ({+ new_presigned_url: 'https://s3.example.com/put',+ key: 's3key-123',+ }));+ const client = makeClient(createPresignedURL);+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({ ok: true, statusText: 'OK' }))+ );++ const result = await uploadToolInputFiles({+ toolSlug: 'GMAIL_SEND_EMAIL',+ arguments_: { attachment: file },+ inputSchema,+ client,+ });++ expect(createPresignedURL).toHaveBeenCalledTimes(1);+ expect(result.attachment).toMatchObject({ s3key: 's3key-123', name: 'document.pdf' });+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+});diff --git a/ts/packages/core/src/index.ts b/ts/packages/core/src/index.tsindex 2a9c1f605..fc49040d1 100644--- a/ts/packages/core/src/index.ts+++ b/ts/packages/core/src/index.ts@@ -16,6 +16,15 @@ export type {} from './utils/jsonSchema';export { getExtensionFromMimeType } from './utils/mime';export { normalizeToolArguments } from './utils/toolArguments';+// Sensitive-file-upload denylist guard. This is the single canonical+// implementation; downstream packages (e.g. `@composio/cli`) import it here so+// every local-file upload path enforces the same denylist. Safe in the edge+// bundle: the module routes filesystem access through `#platform`.+export {+ assertSafeFileUploadPath,+ isBlockedSensitiveFileUploadPath,+ BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,+} from './utils/sensitiveFileUploadPaths';export {sanitizeSchemaPropertyKeys,restoreOriginalKeys,diff --git a/ts/packages/core/src/platform/node.ts b/ts/packages/core/src/platform/node.tsindex ab7b110c3..7f6804ef8 100644--- a/ts/packages/core/src/platform/node.ts+++ b/ts/packages/core/src/platform/node.ts@@ -38,6 +38,10 @@ export const platform = {return fs.existsSync(filePath);},+ realpathSync(filePath: string): string {+ return fs.realpathSync(filePath);+ },+mkdirSync(dirPath: string): void {fs.mkdirSync(dirPath, { recursive: true });},diff --git a/ts/packages/core/src/platform/types.ts b/ts/packages/core/src/platform/types.tsindex 87ffb5ad7..1682eebf3 100644--- a/ts/packages/core/src/platform/types.ts+++ b/ts/packages/core/src/platform/types.ts@@ -42,6 +42,16 @@ export interface Platform {*/existsSync(filePath: string): boolean;+ /**+ * Resolves symlinks in a path, returning the canonical absolute path. On Node+ * this is `fs.realpathSync`; on edge runtimes without a filesystem it returns+ * the input path unchanged (best-effort). Used to prevent a symlink from+ * smuggling an upload past the sensitive-path denylist.+ * @param filePath - The path to canonicalize.+ * @returns The resolved path, or the input path if it cannot be resolved.+ */+ realpathSync(filePath: string): string;+/*** Creates a directory at the given path, including parent directories if needed.* @param dirPath - The directory path to create.diff --git a/ts/packages/core/src/platform/workerd.ts b/ts/packages/core/src/platform/workerd.tsindex ee3b3d459..bf57730b8 100644--- a/ts/packages/core/src/platform/workerd.ts+++ b/ts/packages/core/src/platform/workerd.ts@@ -49,6 +49,12 @@ export const platform: Platform = {return false;},+ realpathSync(filePath: string): string {+ // No filesystem in edge runtimes: cannot resolve symlinks, so return the+ // input unchanged. Local-path uploads don't happen on workerd anyway.+ return filePath;+ },+mkdirSync(_dirPath: string): void {// No-op in edge runtimes - directories cannot be created},diff --git a/ts/packages/core/src/utils/fileUtils.node.ts b/ts/packages/core/src/utils/fileUtils.node.tsindex 50f2c8429..bbd28242b 100644--- a/ts/packages/core/src/utils/fileUtils.node.ts+++ b/ts/packages/core/src/utils/fileUtils.node.ts@@ -7,7 +7,7 @@ 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';+import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths';import { assertPathInsideUploadDirs } from './uploadDirAllowlist.node';/**diff --git a/ts/packages/core/src/utils/sensitiveFileUploadPaths.node.ts b/ts/packages/core/src/utils/sensitiveFileUploadPaths.tssimilarity index 67%rename from ts/packages/core/src/utils/sensitiveFileUploadPaths.node.tsrename to ts/packages/core/src/utils/sensitiveFileUploadPaths.tsindex 72506a2e0..da8e01be9 100644--- a/ts/packages/core/src/utils/sensitiveFileUploadPaths.node.ts+++ b/ts/packages/core/src/utils/sensitiveFileUploadPaths.ts@@ -1,9 +1,13 @@/*** Blocks accidental upload of local files from well-known secret/credential locations* during auto file upload (and {@link getFileDataAfterUploadingToS3}).+ *+ * This is the single canonical guard shared by the core SDK and downstream+ * packages (e.g. `@composio/cli`). Filesystem access goes through the `#platform`+ * abstraction so this module stays free of static `node:*` imports and is safe to+ * re-export from the package root (edge/workerd builds included).*/-import * as path from 'node:path';-import fs from 'node:fs';+import { platform } from '#platform';import { ComposioSensitiveFilePathBlockedError } from '../errors/FileModifierErrors';/**@@ -26,15 +30,17 @@ 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;+const isWindows = typeof process !== 'undefined' && process.platform === 'win32';+/*** Returns normalized path segments, resolving symlinks when the path exists.*/function normalizePathSegments(filePath: string): string[] {- const absolute = path.resolve(filePath);+ const absolute = platform.resolvePath(filePath);let resolved = absolute;try {- if (fs.existsSync(absolute)) {- resolved = fs.realpathSync(absolute);+ if (platform.existsSync(absolute)) {+ resolved = platform.realpathSync(absolute);}} catch {// If realpath fails (e.g. race), use resolved path@@ -58,16 +64,15 @@ function getSensitiveFileUploadPathBlockReason(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))+ ].map(s => (isWindows ? s.toLowerCase() : s)));// Windows: compare segments case-insensitively; map once instead of toLowerCase per iteration.- const segmentsForMatch = isWin ? segments.map(s => s.toLowerCase()) : segments;+ const segmentsForMatch = isWindows ? 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`;@@ -86,20 +91,31 @@ function getSensitiveFileUploadPathBlockReason(return null;}+/**+ * Default remediation hint appended to the block message. Assumes an SDK caller+ * that exposes `sensitiveFileUploadProtection`. Callers without such an opt-out+ * (e.g. `@composio/cli`) should pass their own `remediation` so the message does+ * not advertise an option the caller cannot honor.+ */+const DEFAULT_REMEDIATION =+ `To upload from this path anyway, set sensitiveFileUploadProtection: false on Composio ` ++ `(not recommended) or use a copy outside sensitive locations.`;+/*** @throws {ComposioSensitiveFilePathBlockedError} if the path is not allowed*/export function assertSafeFileUploadPath(filePath: string,- options?: { additionalDenySegments?: string[] }+ options?: { additionalDenySegments?: string[]; remediation?: string }): void {const reason = getSensitiveFileUploadPathBlockReason(filePath, options?.additionalDenySegments);if (reason) {+ const remediation = options?.remediation ?? DEFAULT_REMEDIATION;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 } }+ `Refusing to upload: ${reason}. ${remediation}`,+ {+ meta: { filePath, reason },+ });}}diff --git a/ts/packages/core/test/utils/sensitiveFileUploadPaths.test.ts b/ts/packages/core/test/utils/sensitiveFileUploadPaths.test.tsindex b13fb5144..bf52eff0a 100644--- a/ts/packages/core/test/utils/sensitiveFileUploadPaths.test.ts+++ b/ts/packages/core/test/utils/sensitiveFileUploadPaths.test.ts@@ -5,7 +5,8 @@ import { mkdtempSync, writeFileSync, symlinkSync, rmSync, mkdirSync } from 'nodeimport {assertSafeFileUploadPath,isBlockedSensitiveFileUploadPath,-} from '../../src/utils/sensitiveFileUploadPaths.node';+} from '../../src/utils/sensitiveFileUploadPaths';+import * as publicApi from '../../src';describe('sensitiveFileUploadPaths', () => {it('allows normal project files', () => {@@ -48,6 +49,15 @@ describe('sensitiveFileUploadPaths', () => {);});+ it('is re-exported from the package root for downstream consumers (e.g. @composio/cli)', () => {+ // The CLI imports the guard from `@composio/core` to share this one denylist+ // (issue #3746). Lock the public surface so a refactor cannot silently drop it.+ expect(typeof publicApi.assertSafeFileUploadPath).toBe('function');+ expect(typeof publicApi.isBlockedSensitiveFileUploadPath).toBe('function');+ expect(Array.isArray(publicApi.BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS)).toBe(true);+ expect(publicApi.BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS).toContain('.ssh');+ });+it('blocks after realpath resolves a symlink into a sensitive directory', () => {const root = mkdtempSync(path.join(os.tmpdir(), 'composio-symlink-'));try {