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

next
ts 151 lines 5.62 KB
Raw
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 */
10 import { platform } from '#platform';
11 import { ComposioSensitiveFilePathBlockedError } from '../errors/FileModifierErrors';
12
13 /**
14 * Path segments (a single path component) that indicate a sensitive directory when
15 * they appear anywhere in a resolved local path. Matching follows the case sensitivity
16 * of the filesystem containing that path.
17 */
18 export const BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS: readonly string[] = [
19 '.ssh',
20 '.aws',
21 '.azure',
22 '.gnupg',
23 '.kube',
24 '.docker',
25 '.claude', // may contain API keys and project context read by assistants
26 '.password-store',
27 'keychains', // e.g. ~/Library/Keychains
28 ];
29
30 const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;
31 /** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */
32 const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;
33
34 const splitSegments = (aPath: string): string[] => aPath.split(/[/\\]+/).filter(Boolean);
35
36 /**
37 * Returns normalized path segments, resolving symlinks when the path exists.
38 *
39 * Both the written path and the symlink-resolved one are returned, because a
40 * denied segment can be hidden by a symlink in either direction:
41 *
42 * - `~/innocent-name` -> `~/nested/.aws/creds` hides `.aws` from the written
43 * path, so the denylist has to see the resolved one.
44 * - `~/.claude` -> `/state/claude` hides `.claude` from the *resolved* path,
45 * so the denylist also has to see the written one. Dotfile managers
46 * (chezmoi, stow, yadm) and containerised home directories produce exactly
47 * this layout.
48 *
49 * Matching only the resolved path silently turns the denylist off for the
50 * second case.
51 */
52 function normalizePath(filePath: string): {
53 resolvedPath: string;
54 segments: string[];
55 writtenSegments: string[];
56 } {
57 const absolute = platform.resolvePath(filePath);
58 let resolved = absolute;
59 try {
60 if (platform.existsSync(absolute)) {
61 resolved = platform.realpathSync(absolute);
62 }
63 } catch {
64 // If realpath fails (e.g. race), use resolved path
65 }
66 return {
67 resolvedPath: resolved,
68 segments: splitSegments(resolved),
69 writtenSegments: splitSegments(absolute),
70 };
71 }
72
73 /**
74 * True if the path is under a built-in or extra deny segment, or the basename
75 * looks like an env / netrc / default SSH private key name.
76 */
77 export function isBlockedSensitiveFileUploadPath(
78 filePath: string,
79 additionalDenySegments?: string[]
80 ): boolean {
81 return getSensitiveFileUploadPathBlockReason(filePath, additionalDenySegments) != null;
82 }
83
84 function getSensitiveFileUploadPathBlockReason(
85 filePath: string,
86 additionalDenySegments?: string[]
87 ): string | null {
88 const { resolvedPath, segments, writtenSegments } = normalizePath(filePath);
89 const isCaseSensitive = platform.isFileSystemCaseSensitive?.(resolvedPath) ?? true;
90 const normalizeSegment = (segment: string) => (isCaseSensitive ? segment : segment.toLowerCase());
91 const deny = new Set(
92 [
93 ...BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,
94 ...(additionalDenySegments ?? []).map(s => s.trim()).filter(Boolean),
95 ].map(normalizeSegment)
96 );
97
98 for (const candidate of [segments, writtenSegments]) {
99 const segmentsForMatch = isCaseSensitive ? candidate : candidate.map(normalizeSegment);
100 for (let i = 0; i < candidate.length; i++) {
101 if (deny.has(segmentsForMatch[i]!)) {
102 return `path segment "${candidate[i]}" is in the sensitive file upload denylist`;
103 }
104 }
105 }
106
107 // Same two directions as the segment scan: `~/.env -> /state/config` hides a
108 // denied basename from the resolved path, and a symlink pointing *at* a
109 // credential file hides it from the written one.
110 const basenames = [segments.at(-1), writtenSegments.at(-1)].filter(
111 (name): name is string => !!name
112 );
113 for (const basename of basenames) {
114 if (SECRET_LIKE_BASENAME.test(basename) || DEFAULT_PRIVATE_KEY_BASENAME.test(basename)) {
115 return `file name "${basename}" looks like a credential, env, or private key file`;
116 }
117 if (basename.toLowerCase() === 'credentials') {
118 return 'file name "credentials" is often used for cloud/API credential stores';
119 }
120 }
121 return null;
122 }
123
124 /**
125 * Default remediation hint appended to the block message. Assumes an SDK caller
126 * that exposes `sensitiveFileUploadProtection`. Callers without such an opt-out
127 * (e.g. `@composio/cli`) should pass their own `remediation` so the message does
128 * not advertise an option the caller cannot honor.
129 */
130 const DEFAULT_REMEDIATION =
131 `To upload from this path anyway, set sensitiveFileUploadProtection: false on Composio ` +
132 `(not recommended) or use a copy outside sensitive locations.`;
133
134 /**
135 * @throws {ComposioSensitiveFilePathBlockedError} if the path is not allowed
136 */
137 export function assertSafeFileUploadPath(
138 filePath: string,
139 options?: { additionalDenySegments?: string[]; remediation?: string }
140 ): void {
141 const reason = getSensitiveFileUploadPathBlockReason(filePath, options?.additionalDenySegments);
142 if (reason) {
143 const remediation = options?.remediation ?? DEFAULT_REMEDIATION;
144 throw new ComposioSensitiveFilePathBlockedError(
145 `Refusing to upload: ${reason}. ${remediation}`,
146 {
147 meta: { filePath, reason },
148 }
149 );
150 }
151 }