@devries-cameron20 / composio-1 / commits / fc17c37bf
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(cli): enforce sensitive-file upload denylist (GHSA-hp3h-89pf-5q58) (#3763)

This PR: - fixes #3746 / GHSA-hp3h-89pf-5q58 — the CLI's tool file-upload path bypassed the sensitive-file denylist - **root cause:** the denylist was enforced at the *caller* layer, so `@composio/cli`'s duplicate upload path (`readFileFromDisk`) read and uploaded any local path a tool argument pointed at — `~/.ssh/id_rsa`, `~/.aws/credentials`, `.env`, etc. — enabling credential exfiltration via `composio execute` / `composio run` (incl. LLM-driven agents hit by prompt injection) - **unified fix:** one canonical guard, exported from `@composio/core` and enforced at the read primitive in every SDK - `core`: the guard now routes fs/path access through the internal `#platform` abstraction (adds a `realpathSync` method), so it carries **no static `node:*` imports** and is exported from the package root: `assertSafeFileUploadPath`, `isBlockedSensitiveFileUploadPath`, `BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS` - `cli`: `readFileFromDisk` calls the shared `assertSafeFileUploadPath` before `fs.readFile`; URLs and `File` objects are unaffected (matches core) - `python`: already routes all uploads through the guarded `FileUploadable.from_path` — no functional change; adds regression tests for parity - supersedes #3755, which exported the then-node-only guard from core's **main** `index.ts` and would have injected `node:fs` into the shared `dist/index.mjs` (the workerd/edge-light entry), likely breaking Cloudflare Workers / Vercel Edge - changesets: `@composio/core` minor (new public exports), `@composio/cli` patch (security fix) ## Verification - core: full suite passes (997), incl. new root-export + realpath-symlink cases - **edge bundle stays clean**: built `dist/index.mjs` has no static `node:*` imports and reaches the platform only via `#platform` - cli: new regression test drives the real `uploadToolInputFiles → readFileFromDisk → guard` chain — `~/.ssh/id_rsa` and `.env` throw `ComposioSensitiveFilePathBlockedError` before any `createPresignedURL` call; a normal file still uploads - python: `test_files.py` + sensitive-path suite pass (145), incl. 3 new `from_path` guard tests - `tsgo` typecheck + eslint clean for core and cli

Alberto Schiabel committed Jul 7, 2026 at 00:30 UTC fc17c37bf95b7ece5c038cb7e2ab7e3e4a064e3a
12 files changed +274 -20
.changeset/cli-file-upload-denylist.md new
+7
@@ -0,0 +1,7 @@
1 +---
2 +'@composio/cli': patch
3 +---
4 +
5 +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.
6 +
7 +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.
.changeset/sensitive-file-upload-guard-shared.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +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.
python/tests/test_files.py
+54
@@ -4,6 +4,8 @@ These tests ensure that the FileHelper class correctly handles JSON schemas
4 that use anyOf, oneOf, allOf, or $ref instead of direct 'type' properties.
5 """
6
7 +import tempfile
8 +from pathlib import Path
9 from unittest.mock import Mock, patch, MagicMock
10
11 import pytest
@@ -28,6 +30,7 @@ from composio.exceptions import (
30 ErrorDownloadingFile,
31 ErrorUploadingFile,
32 ResponseTooLargeError,
33 + SensitiveFilePathBlockedError,
34 )
35
36
@@ -2793,3 +2796,54 @@ class TestEnhanceSchemaDescriptionsEmptySchema:
2796 assert description != "Search term"
2797 assert "string" in description
2798 assert "required" in description
2799 +
2800 +
2801 +class TestFromPathSensitiveGuard:
2802 + """`FileUploadable.from_path` is the single upload primitive in the Python
2803 + SDK; the sensitive-path denylist must fire there before any file read or
2804 + network round-trip (parity with the TS core SDK and the CLI fix for
2805 + issue #3746 / GHSA-hp3h-89pf-5q58)."""
2806 +
2807 + def test_from_path_blocks_ssh_private_key(self, mock_client):
2808 + p = Path.home() / ".ssh" / "id_rsa"
2809 + with pytest.raises(SensitiveFilePathBlockedError):
2810 + FileUploadable.from_path(
2811 + client=mock_client,
2812 + file=str(p),
2813 + tool="GMAIL_SEND_EMAIL",
2814 + toolkit="gmail",
2815 + )
2816 + # The guard runs before the SDK contacts the API for a presigned URL.
2817 + mock_client.post.assert_not_called()
2818 +
2819 + def test_from_path_blocks_dotenv_basename(self, mock_client):
2820 + p = Path(tempfile.gettempdir()) / ".env"
2821 + with pytest.raises(SensitiveFilePathBlockedError):
2822 + FileUploadable.from_path(
2823 + client=mock_client,
2824 + file=str(p),
2825 + tool="GMAIL_SEND_EMAIL",
2826 + toolkit="gmail",
2827 + )
2828 + mock_client.post.assert_not_called()
2829 +
2830 + def test_from_path_opt_out_disables_guard(self, mock_client):
2831 + """`sensitive_file_upload_protection=False` restores the legacy
2832 + (unguarded) behavior; the denylist no longer raises for that path."""
2833 + # A non-existent basename under `.ssh`: the `.ssh` segment still trips the
2834 + # denylist when protection is on, but the file never exists, so with
2835 + # protection off we deterministically hit the missing-file path (no real
2836 + # key read, no network) rather than the block error.
2837 + p = Path.home() / ".ssh" / "composio-does-not-exist-guard-test"
2838 + with pytest.raises(Exception) as exc_info:
2839 + FileUploadable.from_path(
2840 + client=mock_client,
2841 + file=str(p),
2842 + tool="GMAIL_SEND_EMAIL",
2843 + toolkit="gmail",
2844 + sensitive_file_upload_protection=False,
2845 + )
2846 + assert not isinstance(exc_info.value, SensitiveFilePathBlockedError)
2847 + # Guard skipped, so the failure is downstream (missing file), before any
2848 + # presigned-URL request.
2849 + mock_client.post.assert_not_called()
ts/packages/cli/src/services/tool-file-uploads.ts
+26 -5
@@ -1,6 +1,7 @@
1 import fs from 'node:fs/promises';
2 import path from 'node:path';
3 import type { Composio as RawComposioClient } from '@composio/client';
4 +import { assertSafeFileUploadPath } from '@composio/core';
5 import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
6
7 type JsonSchema = Record<string, unknown>;
@@ -146,11 +147,31 @@ const readFileFromUrl = async (url: string) => {
147 };
148 };
149
149 -const readFileFromDisk = async (filePath: string) => ({
150 - bytes: new Uint8Array(await fs.readFile(filePath)),
151 - fileName: path.basename(filePath),
152 - mimeType: 'application/octet-stream',
153 -});
150 +const readFileFromDisk = async (filePath: string) => {
151 + // Enforce the sensitive-path denylist at the lowest-level local read, so any
152 + // caller of this reader (not just `uploadToolInputFiles`) is protected. This
153 + // is the single canonical guard shared with `@composio/core`; without it the
154 + // CLI's upload path would silently exfiltrate ~/.ssh/id_rsa, ~/.aws/credentials,
155 + // .env files, etc. (issue #3746 / GHSA-hp3h-89pf-5q58). URLs and File objects
156 + // are intentionally not path-checked, matching the core SDK.
157 + //
158 + // The CLI intentionally exposes NO opt-out for this guard (unlike the core/Python
159 + // SDKs' `sensitiveFileUploadProtection` flag): the primary attack vector is an
160 + // agent that has been prompt-injected into supplying its own tool arguments, so a
161 + // `--force`/env override would hand that attacker a trivial bypass. Pass a
162 + // CLI-appropriate remediation so the error does not advertise an SDK-only opt-out.
163 + assertSafeFileUploadPath(filePath, {
164 + remediation:
165 + 'The Composio CLI always enforces this denylist and has no opt-out. To upload this ' +
166 + 'file, copy it to a location outside sensitive directories (e.g. ~/.ssh, ~/.aws) and ' +
167 + 'pass the copy instead.',
168 + });
169 + return {
170 + bytes: new Uint8Array(await fs.readFile(filePath)),
171 + fileName: path.basename(filePath),
172 + mimeType: 'application/octet-stream',
173 + };
174 +};
175
176 const readUploadSource = async (file: string | File) => {
177 if (isFileLike(file)) {
ts/packages/cli/test/src/services/tool-file-uploads.test.ts new
+112
@@ -0,0 +1,112 @@
1 +import { afterEach, describe, expect, it, vi } from 'vitest';
2 +import * as os from 'node:os';
3 +import * as path from 'node:path';
4 +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
5 +import type { Composio as RawComposioClient } from '@composio/client';
6 +import { ComposioSensitiveFilePathBlockedError } from '@composio/core';
7 +import { uploadToolInputFiles } from 'src/services/tool-file-uploads';
8 +
9 +// Schema with a single `file_uploadable` attachment field — mirrors tools like
10 +// GMAIL_SEND_EMAIL whose attachment is uploaded from a local path.
11 +const inputSchema = {
12 + type: 'object',
13 + properties: {
14 + attachment: { file_uploadable: true, type: 'string' },
15 + },
16 +};
17 +
18 +const makeClient = (createPresignedURL = vi.fn()) =>
19 + ({ files: { createPresignedURL } }) as unknown as RawComposioClient;
20 +
21 +describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
22 + afterEach(() => {
23 + vi.unstubAllGlobals();
24 + vi.restoreAllMocks();
25 + });
26 +
27 + it('refuses to read/upload a path under a sensitive directory (~/.ssh/id_rsa)', async () => {
28 + const createPresignedURL = vi.fn();
29 + const client = makeClient(createPresignedURL);
30 +
31 + await expect(
32 + uploadToolInputFiles({
33 + toolSlug: 'GMAIL_SEND_EMAIL',
34 + arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
35 + inputSchema,
36 + client,
37 + })
38 + ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError);
39 +
40 + // The guard must fire BEFORE any network round-trip: no presigned URL, no upload.
41 + expect(createPresignedURL).not.toHaveBeenCalled();
42 + });
43 +
44 + it('surfaces CLI-appropriate remediation, not the SDK-only opt-out, in the block error', async () => {
45 + const client = makeClient(vi.fn());
46 +
47 + // The CLI has no `sensitiveFileUploadProtection` opt-out (by design), so the
48 + // error must not point users at that non-existent knob (issue #3763 review #2/#3).
49 + await expect(
50 + uploadToolInputFiles({
51 + toolSlug: 'GMAIL_SEND_EMAIL',
52 + arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
53 + inputSchema,
54 + client,
55 + })
56 + ).rejects.toThrowError(/has no opt-out/i);
57 +
58 + await expect(
59 + uploadToolInputFiles({
60 + toolSlug: 'GMAIL_SEND_EMAIL',
61 + arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
62 + inputSchema,
63 + client,
64 + })
65 + ).rejects.not.toThrowError(/sensitiveFileUploadProtection/);
66 + });
67 +
68 + it('refuses credential-like basenames (.env) even outside a sensitive directory', async () => {
69 + const createPresignedURL = vi.fn();
70 + const client = makeClient(createPresignedURL);
71 +
72 + await expect(
73 + uploadToolInputFiles({
74 + toolSlug: 'GMAIL_SEND_EMAIL',
75 + arguments_: { attachment: path.join(os.tmpdir(), '.env') },
76 + inputSchema,
77 + client,
78 + })
79 + ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError);
80 + expect(createPresignedURL).not.toHaveBeenCalled();
81 + });
82 +
83 + it('still uploads a normal (non-sensitive) local file', async () => {
84 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
85 + try {
86 + const file = path.join(root, 'document.pdf');
87 + writeFileSync(file, 'hello');
88 +
89 + const createPresignedURL = vi.fn(async () => ({
90 + new_presigned_url: 'https://s3.example.com/put',
91 + key: 's3key-123',
92 + }));
93 + const client = makeClient(createPresignedURL);
94 + vi.stubGlobal(
95 + 'fetch',
96 + vi.fn(async () => ({ ok: true, statusText: 'OK' }))
97 + );
98 +
99 + const result = await uploadToolInputFiles({
100 + toolSlug: 'GMAIL_SEND_EMAIL',
101 + arguments_: { attachment: file },
102 + inputSchema,
103 + client,
104 + });
105 +
106 + expect(createPresignedURL).toHaveBeenCalledTimes(1);
107 + expect(result.attachment).toMatchObject({ s3key: 's3key-123', name: 'document.pdf' });
108 + } finally {
109 + rmSync(root, { recursive: true, force: true });
110 + }
111 + });
112 +});
ts/packages/core/src/index.ts
+9
@@ -16,6 +16,15 @@ export type {
16 } from './utils/jsonSchema';
17 export { getExtensionFromMimeType } from './utils/mime';
18 export { normalizeToolArguments } from './utils/toolArguments';
19 +// Sensitive-file-upload denylist guard. This is the single canonical
20 +// implementation; downstream packages (e.g. `@composio/cli`) import it here so
21 +// every local-file upload path enforces the same denylist. Safe in the edge
22 +// bundle: the module routes filesystem access through `#platform`.
23 +export {
24 + assertSafeFileUploadPath,
25 + isBlockedSensitiveFileUploadPath,
26 + BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,
27 +} from './utils/sensitiveFileUploadPaths';
28 export {
29 sanitizeSchemaPropertyKeys,
30 restoreOriginalKeys,
ts/packages/core/src/platform/node.ts
+4
@@ -38,6 +38,10 @@ export const platform = {
38 return fs.existsSync(filePath);
39 },
40
41 + realpathSync(filePath: string): string {
42 + return fs.realpathSync(filePath);
43 + },
44 +
45 mkdirSync(dirPath: string): void {
46 fs.mkdirSync(dirPath, { recursive: true });
47 },
ts/packages/core/src/platform/types.ts
+10
@@ -42,6 +42,16 @@ export interface Platform {
42 */
43 existsSync(filePath: string): boolean;
44
45 + /**
46 + * Resolves symlinks in a path, returning the canonical absolute path. On Node
47 + * this is `fs.realpathSync`; on edge runtimes without a filesystem it returns
48 + * the input path unchanged (best-effort). Used to prevent a symlink from
49 + * smuggling an upload past the sensitive-path denylist.
50 + * @param filePath - The path to canonicalize.
51 + * @returns The resolved path, or the input path if it cannot be resolved.
52 + */
53 + realpathSync(filePath: string): string;
54 +
55 /**
56 * Creates a directory at the given path, including parent directories if needed.
57 * @param dirPath - The directory path to create.
ts/packages/core/src/platform/workerd.ts
+6
@@ -49,6 +49,12 @@ export const platform: Platform = {
49 return false;
50 },
51
52 + realpathSync(filePath: string): string {
53 + // No filesystem in edge runtimes: cannot resolve symlinks, so return the
54 + // input unchanged. Local-path uploads don't happen on workerd anyway.
55 + return filePath;
56 + },
57 +
58 mkdirSync(_dirPath: string): void {
59 // No-op in edge runtimes - directories cannot be created
60 },
ts/packages/core/src/utils/fileUtils.node.ts
+1 -1
@@ -7,7 +7,7 @@ import logger from './logger';
7 import { getRandomShortId } from './uuid';
8 import { base64ToUint8Array, uint8ArrayToBase64 } from './buffer';
9 import type { FileDownloadData, FileUploadData } from '../types/files.types';
10 -import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths.node';
10 +import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths';
11 import { assertPathInsideUploadDirs } from './uploadDirAllowlist.node';
12
13 /**
ts/packages/core/src/utils/sensitiveFileUploadPaths.ts renamed
+29 -13
@@ -1,9 +1,13 @@
1 /**
2 * Blocks accidental upload of local files from well-known secret/credential locations
3 * during auto file upload (and {@link getFileDataAfterUploadingToS3}).
4 + *
5 + * This is the single canonical guard shared by the core SDK and downstream
6 + * packages (e.g. `@composio/cli`). Filesystem access goes through the `#platform`
7 + * abstraction so this module stays free of static `node:*` imports and is safe to
8 + * re-export from the package root (edge/workerd builds included).
9 */
5 -import * as path from 'node:path';
6 -import fs from 'node:fs';
10 +import { platform } from '#platform';
11 import { ComposioSensitiveFilePathBlockedError } from '../errors/FileModifierErrors';
12
13 /**
@@ -26,15 +30,17 @@ const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;
30 /** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */
31 const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;
32
33 +const isWindows = typeof process !== 'undefined' && process.platform === 'win32';
34 +
35 /**
36 * Returns normalized path segments, resolving symlinks when the path exists.
37 */
38 function normalizePathSegments(filePath: string): string[] {
33 - const absolute = path.resolve(filePath);
39 + const absolute = platform.resolvePath(filePath);
40 let resolved = absolute;
41 try {
36 - if (fs.existsSync(absolute)) {
37 - resolved = fs.realpathSync(absolute);
42 + if (platform.existsSync(absolute)) {
43 + resolved = platform.realpathSync(absolute);
44 }
45 } catch {
46 // If realpath fails (e.g. race), use resolved path
@@ -58,16 +64,15 @@ function getSensitiveFileUploadPathBlockReason(
64 additionalDenySegments?: string[]
65 ): string | null {
66 const segments = normalizePathSegments(filePath);
61 - const isWin = process.platform === 'win32';
67 const deny = new Set(
68 [
69 ...BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,
70 ...(additionalDenySegments ?? []).map(s => s.trim()).filter(Boolean),
66 - ].map(s => (isWin ? s.toLowerCase() : s))
71 + ].map(s => (isWindows ? s.toLowerCase() : s))
72 );
73
74 // Windows: compare segments case-insensitively; map once instead of toLowerCase per iteration.
70 - const segmentsForMatch = isWin ? segments.map(s => s.toLowerCase()) : segments;
75 + const segmentsForMatch = isWindows ? segments.map(s => s.toLowerCase()) : segments;
76 for (let i = 0; i < segments.length; i++) {
77 if (deny.has(segmentsForMatch[i]!)) {
78 return `path segment "${segments[i]}" is in the sensitive file upload denylist`;
@@ -86,20 +91,31 @@ function getSensitiveFileUploadPathBlockReason(
91 return null;
92 }
93
94 +/**
95 + * Default remediation hint appended to the block message. Assumes an SDK caller
96 + * that exposes `sensitiveFileUploadProtection`. Callers without such an opt-out
97 + * (e.g. `@composio/cli`) should pass their own `remediation` so the message does
98 + * not advertise an option the caller cannot honor.
99 + */
100 +const DEFAULT_REMEDIATION =
101 + `To upload from this path anyway, set sensitiveFileUploadProtection: false on Composio ` +
102 + `(not recommended) or use a copy outside sensitive locations.`;
103 +
104 /**
105 * @throws {ComposioSensitiveFilePathBlockedError} if the path is not allowed
106 */
107 export function assertSafeFileUploadPath(
108 filePath: string,
94 - options?: { additionalDenySegments?: string[] }
109 + options?: { additionalDenySegments?: string[]; remediation?: string }
110 ): void {
111 const reason = getSensitiveFileUploadPathBlockReason(filePath, options?.additionalDenySegments);
112 if (reason) {
113 + const remediation = options?.remediation ?? DEFAULT_REMEDIATION;
114 throw new ComposioSensitiveFilePathBlockedError(
99 - `Refusing to upload: ${reason}. ` +
100 - `To upload from this path anyway, set sensitiveFileUploadProtection: false on Composio ` +
101 - `(not recommended) or use a copy outside sensitive locations.`,
102 - { meta: { filePath, reason } }
115 + `Refusing to upload: ${reason}. ${remediation}`,
116 + {
117 + meta: { filePath, reason },
118 + }
119 );
120 }
121 }
ts/packages/core/test/utils/sensitiveFileUploadPaths.test.ts
+11 -1
@@ -5,7 +5,8 @@ import { mkdtempSync, writeFileSync, symlinkSync, rmSync, mkdirSync } from 'node
5 import {
6 assertSafeFileUploadPath,
7 isBlockedSensitiveFileUploadPath,
8 -} from '../../src/utils/sensitiveFileUploadPaths.node';
8 +} from '../../src/utils/sensitiveFileUploadPaths';
9 +import * as publicApi from '../../src';
10
11 describe('sensitiveFileUploadPaths', () => {
12 it('allows normal project files', () => {
@@ -48,6 +49,15 @@ describe('sensitiveFileUploadPaths', () => {
49 );
50 });
51
52 + it('is re-exported from the package root for downstream consumers (e.g. @composio/cli)', () => {
53 + // The CLI imports the guard from `@composio/core` to share this one denylist
54 + // (issue #3746). Lock the public surface so a refactor cannot silently drop it.
55 + expect(typeof publicApi.assertSafeFileUploadPath).toBe('function');
56 + expect(typeof publicApi.isBlockedSensitiveFileUploadPath).toBe('function');
57 + expect(Array.isArray(publicApi.BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS)).toBe(true);
58 + expect(publicApi.BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS).toContain('.ssh');
59 + });
60 +
61 it('blocks after realpath resolves a symlink into a sensitive directory', () => {
62 const root = mkdtempSync(path.join(os.tmpdir(), 'composio-symlink-'));
63 try {