@devries-cameron20 / composio Mirror · read-only / commits / 3721d040f
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 11:00 UTC

fix(core): reject unsafe mount paths in RemoteFile.save() in both SDKs (#4487)

Closes #4453 and supersedes #4460. Validate server-provided filenames before `RemoteFile.save()` creates directories or writes a file. Empty names and dot components now raise a validation error. Both SDKs validate the stripped basename, including trailing dots exposed by Unicode whitespace, while retaining raw checks for control characters and trailing ASCII spaces. TypeScript recognizes both separators and initial drive prefixes (`C:report.txt` becomes `report.txt`). Its whitespace rules match Python: U+0085 is stripped and U+FEFF is preserved. `RemoteFile.filename` stays non-throwing for download error reporting; explicit save paths retain their existing behavior. The TypeScript extractor is intentionally smaller than `PureWindowsPath`: it keeps dot components literal and does not interpret UNC anchors. For example, TypeScript rejects `sub/.` while Python reduces it to `sub`. TypeScript rejects lone surrogates rather than depending on Python filesystem encoding behavior. Merged current `next` cleanly and addressed both Greptile findings. Added a patch changeset for `@composio/core`. ## Verification - TypeScript: `vitest run` targeting `safePath.test.ts` and `RemoteFile.test.ts`: **103 passed**. - Python: `pytest python/tests/test_safe_path.py python/tests/test_tool_router_session_files.py`: **129 passed, 1 skipped** (Windows-only casing test on macOS). - New regressions failed before the fixes: 14 TypeScript utility cases, 5 TypeScript save cases, and 4 Python cases. - Core TypeScript checks passed, including type tests. - Focused Oxlint, Prettier, Ruff lint/format checks passed. - Agent-skills, skill-routing, and changeset validators passed. Save tests verify actual file bytes and exact filenames, plus no directory creation when validation fails. The UTF-8 length regression accepts 32 emoji and rejects 33, so it detects code-unit counting errors.

Alberto Schiabel committed Sep 24, 2026 at 13:12 UTC 3721d040f51f5958cf4980862fc8dbd6d8dc0d8d
8 files changed +525 -14
.changeset/remote-file-save-safe-basename.md new
+9
@@ -0,0 +1,9 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Validate the server-supplied mount path before `RemoteFile.save()` turns it into a filename. A `mountRelativePath` of `""`, `"."`, `"sub/."`, `"foo/.."` or `".."` made the default save path equal the download directory or its parent, which surfaced as an unhandled `EISDIR` from `writeFileSync` after the directory had already been created. These now throw a `ValidationError` naming the offending mount path, before any `mkdir` or write. An explicit `path` passed by the caller is unaffected.
6 +
7 +The new `safeBasename` helper applies the filename safety checks used by the Python SDK: both `/` and `\` count as separators, and NUL or control characters, Windows-reserved characters and device names, trailing spaces or dots, invalid Unicode and names over 128 UTF-8 bytes are rejected. `RemoteFile.filename` now also splits on both separators, so a Windows-style mount path reduces to the same display name on every platform.
8 +
9 +Drive-relative paths such as `C:report.txt` reduce to `report.txt`. Whitespace stripping follows Python rules, preserving U+FEFF. Both SDKs also reject trailing dots exposed by stripping Unicode whitespace.
python/composio/utils/safe_path.py
+10 -3
@@ -159,6 +159,12 @@ def safe_basename(name: str, *, label: str = "filename") -> str:
159 both basename to ``""``, which makes an output path equal to its own
160 directory and surfaces as ``IsADirectoryError`` at write time.
161
162 + The usability check runs on the *stripped* basename, because that is the
163 + value that gets written: ``str.strip`` removes Unicode whitespace, so
164 + ``"\\u00a0.\\u00a0"`` would otherwise pass a check on the raw segment and
165 + then be written as ``"."``. The hazard checks that follow stay on the raw
166 + segment so that a trailing ASCII space or dot is refused, not trimmed away.
167 +
168 :raises UnsafePathComponentError: when ``name`` yields no usable basename or
169 is unsafe to write.
170 """
@@ -168,7 +174,8 @@ def safe_basename(name: str, *, label: str = "filename") -> str:
174 )
175
176 raw_basename = PureWindowsPath(name).name
171 - if not raw_basename or not raw_basename.strip() or set(raw_basename) == {"."}:
177 + basename = raw_basename.strip()
178 + if not basename or set(basename) == {"."}:
179 raise UnsafePathComponentError(
180 f"Path traversal detected: {label} {name!r} leaves no usable "
181 "basename to write to."
@@ -182,12 +189,12 @@ def safe_basename(name: str, *, label: str = "filename") -> str:
189 f"Refusing to write {label} containing characters reserved by "
190 f"Windows: {name!r}"
191 )
185 - if raw_basename.endswith((" ", ".")):
192 + # Stripping Unicode whitespace can expose a trailing dot on the written name.
193 + if raw_basename.endswith((" ", ".")) or basename.endswith("."):
194 raise UnsafePathComponentError(
195 f"Refusing to write {label} ending in a space or dot: {name!r}"
196 )
197
190 - basename = raw_basename.strip()
198 try:
199 encoded_length = len(os.fsencode(basename))
200 except UnicodeEncodeError as e:
python/tests/test_safe_path.py
+41 -1
@@ -139,6 +139,39 @@ class TestIsInsideDir:
139
140
141 class TestSafeBasename:
142 + @pytest.mark.parametrize(
143 + ("value", "expected"),
144 + [
145 + ("report.pdf", "report.pdf"),
146 + ("output/report.pdf", "report.pdf"),
147 + ("archive.tar.gz", "archive.tar.gz"),
148 + (".gitignore", ".gitignore"),
149 + ("..\\..\\evil", "evil"),
150 + (" report.pdf", "report.pdf"),
151 + ("café.txt", "café.txt"),
152 + ("C:report.txt", "report.txt"),
153 + ("\ufeffreport.txt", "\ufeffreport.txt"),
154 + ("\u0085report.txt\u0085", "report.txt"),
155 + ],
156 + )
157 + def test_reduces_to_the_basename(self, value, expected):
158 + assert safe_basename(value) == expected
159 +
160 + @pytest.mark.parametrize("value", ["", ".", "..", "...", "foo/..", "/", " "])
161 + def test_rejects_names_with_no_usable_basename(self, value):
162 + with pytest.raises(UnsafePathComponentError, match="no usable basename"):
163 + safe_basename(value)
164 +
165 + @pytest.mark.parametrize(
166 + "value",
167 + ["\u00a0.\u00a0", ".\u00a0", "\u00a0.", "\u2007..\u2007", "\u2028.\u2029"],
168 + )
169 + def test_rejects_whitespace_wrapped_dot_runs(self, value):
170 + """``str.strip`` removes Unicode whitespace, so these are written as
171 + ``.`` or ``..``: the usability check must see the stripped value."""
172 + with pytest.raises(UnsafePathComponentError, match="no usable basename"):
173 + safe_basename(value)
174 +
175 @pytest.mark.parametrize(
176 "value",
177 ["NUL.tar.gz", "COM1.log.bak", "COM¹.txt", "LPT³.data"],
@@ -149,7 +182,14 @@ class TestSafeBasename:
182
183 @pytest.mark.parametrize(
184 "value",
152 - ["report?.txt", "report.txt:payload", "report.txt.", "report.txt "],
185 + [
186 + "report?.txt",
187 + "report.txt:payload",
188 + "report.txt.",
189 + "report.txt ",
190 + "report.\u00a0",
191 + "report.\u0085",
192 + ],
193 )
194 def test_rejects_windows_invalid_names_on_every_platform(self, value):
195 with pytest.raises(UnsafePathComponentError):
python/tests/test_tool_router_session_files.py
+50 -3
@@ -283,11 +283,20 @@ class TestRemoteFile:
283 assert Path(out_path).read_bytes() == b"saved content"
284 assert out_path.endswith("output.txt")
285
286 - def test_save_default_location(self, tmp_path):
286 + @pytest.mark.parametrize(
287 + ("mount_relative_path", "expected_name"),
288 + [
289 + ("report.pdf", "report.pdf"),
290 + ("C:report.txt", "report.txt"),
291 + ("\ufeffreport.txt", "\ufeffreport.txt"),
292 + ("\u0085report.txt\u0085", "report.txt"),
293 + ],
294 + )
295 + def test_save_default_location(self, tmp_path, mount_relative_path, expected_name):
296 """Test save() without path uses default directory."""
297 rf = RemoteFile(
298 expires_at="2026-01-01",
290 - mount_relative_path="report.pdf",
299 + mount_relative_path=mount_relative_path,
300 sandbox_mount_prefix="/mnt/files",
301 download_url="https://example.com/file",
302 )
@@ -295,7 +304,7 @@ class TestRemoteFile:
304 with patch("pathlib.Path.home", return_value=tmp_path):
305 out_path = rf.save()
306
298 - expected = tmp_path / ".composio" / "files" / "report.pdf"
307 + expected = tmp_path / ".composio" / "files" / expected_name
308 assert Path(out_path) == expected
309 assert expected.read_bytes() == b"pdf content"
310
@@ -319,6 +328,44 @@ class TestRemoteFile:
328 # The check raises before mkdir/write, so nothing was written under tmp_path.
329 assert not (tmp_path / ".composio").exists()
330
331 + @pytest.mark.parametrize(
332 + "mount_relative_path", ["", ".", "\u00a0.\u00a0", "\u2007..\u2007"]
333 + )
334 + def test_save_default_location_rejects_unusable_basename(
335 + self, tmp_path, mount_relative_path
336 + ):
337 + """A mount path that strips down to ``.`` or ``..`` would make the
338 + save path equal the download directory or its parent; each must be a
339 + ``ValidationError`` raised before anything touches the disk, not an
340 + ``IsADirectoryError`` from ``write_bytes``."""
341 + rf = RemoteFile(
342 + expires_at="2026-01-01",
343 + mount_relative_path=mount_relative_path,
344 + sandbox_mount_prefix="/mnt/files",
345 + download_url="https://example.com/file",
346 + )
347 +
348 + with patch.object(rf, "buffer", return_value=b"should not be written"):
349 + with patch("pathlib.Path.home", return_value=tmp_path):
350 + with pytest.raises(ValidationError, match="Path traversal detected"):
351 + rf.save()
352 +
353 + assert not (tmp_path / ".composio").exists()
354 +
355 + @pytest.mark.parametrize("mount_relative_path", ["report.\u00a0", "report.\u0085"])
356 + def test_save_rejects_dot_exposed_by_stripping(self, tmp_path, mount_relative_path):
357 + rf = RemoteFile(
358 + expires_at="2026-01-01",
359 + mount_relative_path=mount_relative_path,
360 + sandbox_mount_prefix="/mnt/files",
361 + download_url="https://example.com/file",
362 + )
363 + with patch.object(rf, "buffer", return_value=b"should not be written"):
364 + with patch("pathlib.Path.home", return_value=tmp_path):
365 + with pytest.raises(ValidationError, match="ending in a space or dot"):
366 + rf.save()
367 + assert not (tmp_path / ".composio").exists()
368 +
369
370 class TestResponseDerivedUrlsAreGuarded:
371 """`download_url` and `upload_url` are response fields, so they are guarded.
ts/packages/core/src/models/RemoteFile.ts
+23 -7
@@ -14,6 +14,7 @@ import {
14 ValidationError,
15 } from '../errors';
16 import { readResponseBodyWithLimit } from '../utils/readResponseBody';
17 +import { safeBasename, untrustedBasename } from '../utils/safePath';
18
19 /**
20 * Represents a file stored in a tool router session's file mount.
@@ -77,9 +78,20 @@ export class RemoteFile {
78 return new RemoteFile(parsed.data);
79 }
80
80 - /** Filename extracted from the mount path (e.g. "report.pdf" from "output/report.pdf") */
81 + /**
82 + * Filename extracted from the mount path (e.g. "report.pdf" from "output/report.pdf").
83 + *
84 + * Deliberately non-throwing: this is a display value, and `downloadBytes()`
85 + * reads it while constructing `RemoteFileDownloadError`. A validator here
86 + * would replace a genuine download error with a validation error thrown from
87 + * inside the error constructor. {@link save} validates instead, at the point
88 + * the value actually becomes a path.
89 + *
90 + * Both `/` and `\` count as separators, as in the Python SDK, so a mount path
91 + * crafted for a Windows target is reduced the same way on every platform.
92 + */
93 get filename(): string {
82 - return platform.basename(this.mountRelativePath);
94 + return untrustedBasename(this.mountRelativePath);
95 }
96
97 private downloadError(message: string, cause: unknown, response?: Response) {
@@ -163,6 +175,7 @@ export class RemoteFile {
175 * @param path - Local path to save the file. If omitted, saves to the Composio temp directory using the filename from the mount path.
176 * @returns The absolute path where the file was saved
177 * @throws Error if file system is not supported or the save fails
178 + * @throws ValidationError if `path` is omitted and the mount path yields no usable filename
179 */
180 async save(path?: string): Promise<string> {
181 if (!platform.supportsFileSystem) {
@@ -178,13 +191,16 @@ export class RemoteFile {
191 throw new Error('Cannot determine save location: home directory is not available');
192 }
193
194 + // An explicit `path` is the caller's own. The default branch builds a path
195 + // out of `mountRelativePath`, a server-controlled response field, so it is
196 + // validated first (SEC-316, mirroring the Python SDK): a value such as `""`,
197 + // `"."` or `"foo/.."` would otherwise make `savePath` its own directory or
198 + // the parent, and fail with a raw `EISDIR` only after `mkdirSync` had run.
199 + const defaultDir = platform.joinPath(homeDir, COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
200 const savePath =
182 - path ?? platform.joinPath(homeDir, COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME, this.filename);
201 + path ?? platform.joinPath(defaultDir, safeBasename(this.mountRelativePath, 'mount path'));
202
184 - const dir =
185 - path != null
186 - ? getParentDir(savePath)
187 - : platform.joinPath(homeDir, COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
203 + const dir = path != null ? getParentDir(savePath) : defaultDir;
204 if (dir && !platform.existsSync(dir)) {
205 platform.mkdirSync(dir);
206 }
ts/packages/core/src/utils/safePath.ts new
+172
@@ -0,0 +1,172 @@
1 +/**
2 + * Filename containment for untrusted input.
3 + *
4 + * Every field of an API response is untrusted, including filenames. When such a
5 + * value becomes part of a filesystem path it must pass through this module
6 + * first, and validation must happen before any `mkdir` or write so a rejected
7 + * value leaves nothing behind on disk.
8 + *
9 + * TypeScript counterpart of `safe_basename` in `python/composio/utils/safe_path.py`.
10 + * The two use the same validation order and whitespace rules. Path extraction
11 + * is intentionally limited here; see `untrustedBasename`.
12 + *
13 + * Pure string logic with no filesystem access: no static `node:*` imports, so
14 + * it is usable from edge/workerd builds.
15 + */
16 +import { ValidationError } from '../errors/ValidationErrors';
17 +
18 +/**
19 + * Upper bound on a filename, well under the 255-byte limit common to
20 + * ext4/APFS/NTFS. Keeps a long server-supplied name from failing with a raw
21 + * `ENAMETOOLONG` mid-write. Matches `MAX_COMPONENT_LENGTH` in the Python SDK.
22 + */
23 +export const MAX_FILENAME_BYTES = 128;
24 +
25 +/**
26 + * Reserved DOS device names. Writing to one on Windows targets the device
27 + * rather than a file. Rejected on every platform so behavior does not diverge
28 + * between a POSIX developer machine and a Windows deployment.
29 + */
30 +const WINDOWS_RESERVED_NAMES: ReadonlySet<string> = new Set([
31 + 'CON',
32 + 'PRN',
33 + 'AUX',
34 + 'NUL',
35 + ...Array.from({ length: 9 }, (_, i) => `COM${i + 1}`),
36 + ...Array.from({ length: 9 }, (_, i) => `LPT${i + 1}`),
37 + ...['¹', '²', '³'].flatMap(superscript => [`COM${superscript}`, `LPT${superscript}`]),
38 +]);
39 +
40 +/** Control characters and characters reserved by Windows. */
41 +const WINDOWS_INVALID_CHARS = /[\u0000-\u001f<>:"|?*]/;
42 +
43 +/**
44 + * Python str.strip() whitespace: Unicode White_Space plus U+001C–U+001F.
45 + * Unlike JavaScript trim(), this includes U+0085 and preserves U+FEFF.
46 + */
47 +const PYTHON_WHITESPACE =
48 + '[\\u0009-\\u000d\\u001c-\\u0020\\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]';
49 +const SURROUNDING_WHITESPACE = new RegExp(`^${PYTHON_WHITESPACE}+|${PYTHON_WHITESPACE}+$`, 'g');
50 +
51 +/**
52 + * Returns the last path segment of `value`, treating both `/` and `\` as
53 + * separators, or `''` when there is none.
54 + *
55 + * `path.basename()` on POSIX only splits on `/`, so a name crafted for a
56 + * Windows target (`..\..\evil`) comes back intact on macOS and Linux. Splitting
57 + * on both and removing an initial drive prefix also handles `C:report.txt`.
58 + * This is not a full `PureWindowsPath` parser: dot components stay literal,
59 + * and UNC anchors are not interpreted.
60 + *
61 + * Never throws: this is a display value as well as the input to
62 + * {@link safeBasename}, and it is read while constructing download errors.
63 + */
64 +export function untrustedBasename(value: string): string {
65 + const segments = value.replace(/^[a-z]:/i, '').split(/[/\\]+/);
66 + // Trailing separators name the same file: `a/b/` and `a/b` both basename to `b`.
67 + while (segments.length > 0 && segments[segments.length - 1] === '') {
68 + segments.pop();
69 + }
70 + return segments[segments.length - 1] ?? '';
71 +}
72 +
73 +/**
74 + * True when `value` contains a surrogate code unit that is not part of a valid
75 + * pair. Such a string cannot be encoded as UTF-8; `TextEncoder` silently
76 + * substitutes U+FFFD, which would write a file under a name the response never
77 + * specified. `String.prototype.isWellFormed()` is ES2024 and this package
78 + * targets es2022, hence the manual scan.
79 + */
80 +function hasLoneSurrogate(value: string): boolean {
81 + for (let i = 0; i < value.length; i++) {
82 + const code = value.charCodeAt(i);
83 + if (code >= 0xd800 && code <= 0xdbff) {
84 + const next = value.charCodeAt(i + 1);
85 + if (!(next >= 0xdc00 && next <= 0xdfff)) {
86 + return true;
87 + }
88 + i++;
89 + } else if (code >= 0xdc00 && code <= 0xdfff) {
90 + return true;
91 + }
92 + }
93 + return false;
94 +}
95 +
96 +/**
97 + * Collapses an untrusted filename to a bare, writable basename.
98 + *
99 + * Applies, in order: no usable basename (empty or a run of dots once
100 + * surrounding whitespace is stripped), NUL bytes, control and Windows-reserved
101 + * characters, trailing space or dot, invalid Unicode, a byte-length bound, and
102 + * reserved device names. This is the order `safe_basename` uses in the Python
103 + * SDK. This implementation rejects lone surrogates rather than relying on
104 + * Python filesystem encoding behavior.
105 + *
106 + * Names that leave no usable basename are refused rather than replaced with a
107 + * generated one: a response that cannot name its own file is malformed or
108 + * hostile, and inventing a name would hide that. `""`, `"."` and `".."` make
109 + * an output path equal to, or escape, its own directory, which surfaces as a
110 + * raw `EISDIR` at write time instead of a validation error.
111 + *
112 + * The usability check runs on the *trimmed* basename because that is what gets
113 + * written: Python-compatible stripping removes whitespace, so `"\u00a0.\u00a0"` would
114 + * otherwise pass a check on the raw segment and then be written as `"."`. The
115 + * hazard checks that follow run on the raw segment so a trailing ASCII space or
116 + * dot is refused, not trimmed away. Check the stripped value for trailing dots
117 + * too, since stripping whitespace can expose one.
118 + *
119 + * @param name - The untrusted filename or relative path to reduce.
120 + * @param label - How the value is described in error messages.
121 + * @returns The validated bare basename, with surrounding whitespace trimmed.
122 + * @throws ValidationError if `name` yields no usable basename or is unsafe to write.
123 + */
124 +export function safeBasename(name: string, label: string = 'filename'): string {
125 + const rawBasename = untrustedBasename(name);
126 + const basename = rawBasename.replace(SURROUNDING_WHITESPACE, '');
127 +
128 + if (!basename || /^\.+$/.test(basename)) {
129 + throw new ValidationError(
130 + `Path traversal detected: ${label} ${JSON.stringify(name)} leaves no usable basename to write to.`
131 + );
132 + }
133 + if (rawBasename.includes('\u0000')) {
134 + throw new ValidationError(
135 + `Refusing to write ${label} containing a NUL byte: ${JSON.stringify(name)}`
136 + );
137 + }
138 + if (WINDOWS_INVALID_CHARS.test(rawBasename)) {
139 + throw new ValidationError(
140 + `Refusing to write ${label} containing characters reserved by Windows: ${JSON.stringify(name)}`
141 + );
142 + }
143 + if (rawBasename.endsWith(' ') || rawBasename.endsWith('.') || basename.endsWith('.')) {
144 + throw new ValidationError(
145 + `Refusing to write ${label} ending in a space or dot: ${JSON.stringify(name)}`
146 + );
147 + }
148 + if (hasLoneSurrogate(basename)) {
149 + throw new ValidationError(
150 + `Refusing to write ${label} containing invalid Unicode: ${JSON.stringify(name)}`
151 + );
152 + }
153 +
154 + const encodedLength = new TextEncoder().encode(basename).length;
155 + if (encodedLength > MAX_FILENAME_BYTES) {
156 + throw new ValidationError(
157 + `Refusing to write ${label} longer than ${MAX_FILENAME_BYTES} bytes: ` +
158 + `${JSON.stringify(basename.slice(0, 32))}... (${encodedLength} bytes)`
159 + );
160 + }
161 +
162 + // Compare everything before the first dot: on Windows `NUL.tar.gz` opens the
163 + // null device just as `NUL` does, so extensions provide no protection.
164 + const deviceName = basename.split('.', 1)[0].replace(/ +$/, '').toUpperCase();
165 + if (WINDOWS_RESERVED_NAMES.has(deviceName)) {
166 + throw new ValidationError(
167 + `Refusing to write ${label} that is a reserved device name: ${JSON.stringify(name)}`
168 + );
169 + }
170 +
171 + return basename;
172 +}
ts/packages/core/test/models/RemoteFile.test.ts
+85
@@ -283,5 +283,90 @@ describe('RemoteFile', () => {
283 const written = platform.readFileSync(savePath) as Uint8Array;
284 expect(new Uint8Array(written)).toEqual(content);
285 });
286 +
287 + describe('default location', () => {
288 + // `save()` without a path derives the filename from `mountRelativePath`,
289 + // a server-controlled response field. These cover the SEC-316 guard the
290 + // Python SDK already applies; see `src/utils/safePath.ts`.
291 + const content = new Uint8Array([1, 2, 3]);
292 + let homeDir: string;
293 + let composioDir: string;
294 +
295 + beforeEach(async () => {
296 + const { mkdtempSync } = await import('node:fs');
297 + const { join } = await import('node:path');
298 + const { tmpdir } = await import('node:os');
299 + const { platform } = await import('../../src/platform/node');
300 +
301 + homeDir = mkdtempSync(join(tmpdir(), 'composio-remote-file-home-'));
302 + composioDir = join(homeDir, '.composio');
303 + vi.spyOn(platform, 'homedir').mockReturnValue(homeDir);
304 +
305 + globalThis.fetch = vi.fn().mockResolvedValue({
306 + ok: true,
307 + arrayBuffer: () => Promise.resolve(content.buffer),
308 + });
309 + });
310 +
311 + afterEach(async () => {
312 + vi.restoreAllMocks();
313 + const { rmSync } = await import('node:fs');
314 + rmSync(homeDir, { recursive: true, force: true });
315 + });
316 +
317 + it.each([
318 + ['out/report.pdf', 'report.pdf'],
319 + ['C:report.txt', 'report.txt'],
320 + ['\ufeffreport.txt', '\ufeffreport.txt'],
321 + ['\u0085report.txt\u0085', 'report.txt'],
322 + ])(
323 + 'should save %j under the default directory as %j',
324 + async (mountRelativePath, expectedName) => {
325 + const { platform } = await import('../../src/platform/node');
326 + const { join } = await import('node:path');
327 + const file = new RemoteFile({ ...validCamelCaseData, mountRelativePath });
328 +
329 + const result = await file.save();
330 +
331 + expect(result).toBe(join(composioDir, 'files', expectedName));
332 + expect(new Uint8Array(platform.readFileSync(result) as Uint8Array)).toEqual(content);
333 + }
334 + );
335 +
336 + // Each of these would make the save path equal its own directory (or the
337 + // parent), which previously surfaced as an unhandled `EISDIR` from
338 + // `writeFileSync` after the directory had already been created.
339 + it.each(['', '.', 'sub/.', 'foo/..', '..', '\u00a0.\u00a0', '\u2007..\u2007'])(
340 + 'should reject mountRelativePath %j with a ValidationError',
341 + async mountRelativePath => {
342 + const { platform } = await import('../../src/platform/node');
343 + const file = new RemoteFile({ ...validCamelCaseData, mountRelativePath });
344 +
345 + await expect(file.save()).rejects.toThrow(ValidationError);
346 + await expect(file.save()).rejects.toThrow(/leaves no usable basename/);
347 + expect(platform.existsSync(composioDir)).toBe(false);
348 + }
349 + );
350 +
351 + it.each(['report.\u00a0', 'report.\u0085'])(
352 + 'should reject a trailing dot exposed by stripping %j before creating directories',
353 + async mountRelativePath => {
354 + const { platform } = await import('../../src/platform/node');
355 + const file = new RemoteFile({ ...validCamelCaseData, mountRelativePath });
356 + await expect(file.save()).rejects.toThrow(/ending in a space or dot/);
357 + expect(platform.existsSync(composioDir)).toBe(false);
358 + }
359 + );
360 +
361 + it('should still honor an explicit path when the mount path is unusable', async () => {
362 + const { platform } = await import('../../src/platform/node');
363 + const { join } = await import('node:path');
364 + const file = new RemoteFile({ ...validCamelCaseData, mountRelativePath: '..' });
365 + const savePath = join(homeDir, 'explicit.pdf');
366 +
367 + await expect(file.save(savePath)).resolves.toBe(savePath);
368 + expect(platform.existsSync(savePath)).toBe(true);
369 + });
370 + });
371 });
372 });
ts/packages/core/test/utils/safePath.test.ts new
+135
@@ -0,0 +1,135 @@
1 +/**
2 + * Tests for the filename containment primitive in `src/utils/safePath.ts`.
3 + *
4 + * Covers the filename safety policy shared with `TestSafeBasename` in
5 + * `python/tests/test_safe_path.py`.
6 + */
7 +import { describe, it, expect } from 'vitest';
8 +import { MAX_FILENAME_BYTES, safeBasename, untrustedBasename } from '../../src/utils/safePath';
9 +import { ValidationError } from '../../src/errors';
10 +
11 +describe('untrustedBasename', () => {
12 + it.each([
13 + ['report.pdf', 'report.pdf'],
14 + ['C:report.txt', 'report.txt'],
15 + ['c:report.txt', 'report.txt'],
16 + ['C:', ''],
17 + ['output/report.pdf', 'report.pdf'],
18 + ['output/report.pdf/', 'report.pdf'],
19 + ['..\\..\\evil', 'evil'],
20 + ['C:\\Users\\me\\report.pdf', 'report.pdf'],
21 + ['', ''],
22 + ['/', ''],
23 + ['sub/.', '.'],
24 + ['foo/..', '..'],
25 + ])('reduces %j to %j without throwing', (input, expected) => {
26 + expect(untrustedBasename(input)).toBe(expected);
27 + });
28 +});
29 +
30 +describe('safeBasename', () => {
31 + describe('accepts legitimate filenames', () => {
32 + it.each([
33 + ['report.pdf', 'report.pdf'],
34 + ['C:report.txt', 'report.txt'],
35 + ['c:report.txt', 'report.txt'],
36 + ['\ufeffreport.txt', '\ufeffreport.txt'],
37 + ['report.txt\ufeff', 'report.txt\ufeff'],
38 + ['\u0085report.txt\u0085', 'report.txt'],
39 + ['output/report.pdf', 'report.pdf'],
40 + ['output/subdir/data.json', 'data.json'],
41 + ['/absolute/report.pdf', 'report.pdf'],
42 + ['output/report.pdf/', 'report.pdf'],
43 + ['..\\..\\evil', 'evil'],
44 + ['archive.tar.gz', 'archive.tar.gz'],
45 + ['.gitignore', '.gitignore'],
46 + [' report.pdf', 'report.pdf'],
47 + ['café.txt', 'café.txt'],
48 + ['😀.png', '😀.png'],
49 + ])('reduces %j to %j', (input, expected) => {
50 + expect(safeBasename(input)).toBe(expected);
51 + });
52 +
53 + it('accepts a filename at the byte limit', () => {
54 + const name = 'x'.repeat(MAX_FILENAME_BYTES);
55 + expect(safeBasename(name)).toBe(name);
56 + });
57 + });
58 +
59 + describe('rejects names that leave no usable basename', () => {
60 + // Each of these would make the save path equal its own directory or the
61 + // parent, surfacing as a raw EISDIR at write time.
62 + it.each(['', '.', '..', '...', 'sub/.', 'foo/..', './', '/', '//', ' ', 'C:'])(
63 + 'rejects %j',
64 + input => {
65 + expect(() => safeBasename(input)).toThrow(ValidationError);
66 + expect(() => safeBasename(input)).toThrow(/leaves no usable basename/);
67 + }
68 + );
69 +
70 + // Python-compatible whitespace stripping would write these as `.` or `..`:
71 + // the usability check has to see the trimmed value, not the raw segment.
72 + it.each([
73 + '\u00a0.\u00a0',
74 + '.\u00a0',
75 + '\u00a0.',
76 + '\u2007..\u2007',
77 + '\u2028.\u2029',
78 + '\u0085..\u0085',
79 + '\u001c..\u001f',
80 + ])('rejects whitespace-wrapped %j, which trims to a dot run', input => {
81 + expect(() => safeBasename(input)).toThrow(/leaves no usable basename/);
82 + });
83 + });
84 +
85 + describe('rejects unsafe names', () => {
86 + it.each(['report\u0000.pdf', 'report.pdf\u0000.exe'])('rejects NUL byte in %j', input => {
87 + expect(() => safeBasename(input)).toThrow(/NUL byte/);
88 + });
89 +
90 + it.each([
91 + 'report?.txt',
92 + 'report.txt:payload',
93 + 'report<1>.txt',
94 + 'a|b.txt',
95 + 'tab\there.txt',
96 + '\u001creport.txt\u001f',
97 + 'output/C:report.txt',
98 + ])('rejects Windows-reserved characters in %j on every platform', input => {
99 + expect(() => safeBasename(input)).toThrow(/reserved by Windows/);
100 + });
101 +
102 + it.each(['report.txt.', 'report.txt ', '\ufeff..', 'report.\u00a0', 'report.\u0085'])(
103 + 'rejects trailing space or dot in %j',
104 + input => {
105 + expect(() => safeBasename(input)).toThrow(/ending in a space or dot/);
106 + }
107 + );
108 +
109 + it.each(['NUL', 'nul', 'NUL.tar.gz', 'COM1.log.bak', 'COM¹.txt', 'LPT³.data', 'aux.txt'])(
110 + 'rejects reserved device name %j with any extension',
111 + input => {
112 + expect(() => safeBasename(input)).toThrow(/reserved device name/);
113 + }
114 + );
115 +
116 + it('rejects a filename over the byte limit', () => {
117 + expect(() => safeBasename('x'.repeat(MAX_FILENAME_BYTES + 1))).toThrow(/longer than/);
118 + });
119 +
120 + it('measures the limit in bytes, not code units', () => {
121 + // Each emoji is two UTF-16 code units but four UTF-8 bytes.
122 + expect(safeBasename('😀'.repeat(32))).toBe('😀'.repeat(32));
123 + expect(() => safeBasename('😀'.repeat(33))).toThrow(/longer than/);
124 + });
125 +
126 + it('rejects a lone surrogate, which cannot be encoded as UTF-8', () => {
127 + expect(() => safeBasename('report-\ud800.txt')).toThrow(/invalid Unicode/);
128 + expect(() => safeBasename('report-\udc00.txt')).toThrow(/invalid Unicode/);
129 + });
130 + });
131 +
132 + it('names the value in the error using the given label', () => {
133 + expect(() => safeBasename('..', 'mount path')).toThrow(/mount path/);
134 + });
135 +});