Skip to content

Commit cf05b37

Browse files
authored
fix(filesystem): resolve Unicode-equivalent paths (#4638)
Signed-off-by: KXH <shepherdlaurie238@gmail.com>
1 parent 642a911 commit cf05b37

2 files changed

Lines changed: 94 additions & 8 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import fs from 'fs/promises';
2+
import os from 'os';
3+
import path from 'path';
4+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
5+
import { setAllowedDirectories, validatePath } from '../lib.js';
6+
7+
describe('Unicode-equivalent filesystem paths', () => {
8+
let testDirectory: string;
9+
10+
beforeEach(async () => {
11+
testDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-unicode-paths-'));
12+
setAllowedDirectories([testDirectory]);
13+
});
14+
15+
afterEach(async () => {
16+
setAllowedDirectories([]);
17+
await fs.rm(testDirectory, { recursive: true, force: true });
18+
});
19+
20+
it('resolves an existing decomposed path from a composed request', async () => {
21+
const onDiskDirectory = 'de\u0301marche';
22+
const onDiskFile = 're\u0301sume\u0301.txt';
23+
await fs.mkdir(path.join(testDirectory, onDiskDirectory));
24+
await fs.writeFile(path.join(testDirectory, onDiskDirectory, onDiskFile), 'content');
25+
26+
const resolved = await validatePath(path.join(testDirectory, 'd\u00e9marche', 'r\u00e9sum\u00e9.txt'));
27+
28+
expect(resolved).toBe(await fs.realpath(path.join(testDirectory, onDiskDirectory, onDiskFile)));
29+
});
30+
31+
it('preserves a new basename after resolving a Unicode-equivalent parent', async () => {
32+
const onDiskDirectory = 'de\u0301marche';
33+
await fs.mkdir(path.join(testDirectory, onDiskDirectory));
34+
35+
const resolved = await validatePath(path.join(testDirectory, 'd\u00e9marche', 'new.txt'));
36+
37+
expect(resolved).toBe(path.join(await fs.realpath(path.join(testDirectory, onDiskDirectory)), 'new.txt'));
38+
});
39+
40+
it('rejects ambiguous canonically equivalent entries', async () => {
41+
const composed = 'caf\u00e9';
42+
const decomposed = 'cafe\u0301';
43+
await fs.mkdir(path.join(testDirectory, composed));
44+
await fs.mkdir(path.join(testDirectory, decomposed));
45+
46+
await expect(validatePath(path.join(testDirectory, 'cafe\u0341', 'file.txt')))
47+
.rejects.toThrow('Ambiguous Unicode path component');
48+
});
49+
});

‎src/filesystem/lib.ts‎

Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,46 @@ function resolveRelativePathAgainstAllowedDirectories(relativePath: string): str
9696
}
9797

9898
// Security & Validation Functions
99+
async function resolveUnicodeEquivalentPath(absolutePath: string): Promise<string> {
100+
const allowedDirectory = [...allowedDirectories]
101+
.sort((left, right) => right.length - left.length)
102+
.find(directory => isPathWithinAllowedDirectories(normalizePath(absolutePath), [directory]));
103+
104+
if (!allowedDirectory) {
105+
return absolutePath;
106+
}
107+
108+
let currentPath = await fs.realpath(allowedDirectory);
109+
const relativeParts = path.relative(allowedDirectory, absolutePath).split(path.sep).filter(Boolean);
110+
111+
for (let index = 0; index < relativeParts.length; index++) {
112+
const requestedPart = relativeParts[index];
113+
const entries = (await fs.readdir(currentPath)) ?? [];
114+
const exactMatch = entries.find(entry => entry === requestedPart);
115+
const equivalentMatches = exactMatch
116+
? [exactMatch]
117+
: entries.filter(entry => entry.normalize('NFC') === requestedPart.normalize('NFC'));
118+
119+
if (equivalentMatches.length > 1) {
120+
throw new Error(`Ambiguous Unicode path component: ${requestedPart}`);
121+
}
122+
123+
if (equivalentMatches.length === 0) {
124+
if (index === relativeParts.length - 1) {
125+
return path.join(currentPath, requestedPart);
126+
}
127+
throw new Error(`Parent directory does not exist: ${path.join(currentPath, requestedPart)}`);
128+
}
129+
130+
currentPath = await fs.realpath(path.join(currentPath, equivalentMatches[0]));
131+
if (!isPathWithinAllowedDirectories(normalizePath(currentPath), allowedDirectories)) {
132+
throw new Error(`Access denied - symlink target outside allowed directories: ${currentPath} not in ${allowedDirectories.join(', ')}`);
133+
}
134+
}
135+
136+
return currentPath;
137+
}
138+
99139
export async function validatePath(requestedPath: string): Promise<string> {
100140
const expandedPath = expandHome(requestedPath);
101141
const absolute = path.isAbsolute(expandedPath)
@@ -123,16 +163,13 @@ export async function validatePath(requestedPath: string): Promise<string> {
123163
// Security: For new files that don't exist yet, verify parent directory
124164
// This ensures we can't create files in unauthorized locations
125165
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
126-
const parentDir = path.dirname(absolute);
127166
try {
128-
const realParentPath = await fs.realpath(parentDir);
129-
const normalizedParent = normalizePath(realParentPath);
130-
if (!isPathWithinAllowedDirectories(normalizedParent, allowedDirectories)) {
131-
throw new Error(`Access denied - parent directory outside allowed directories: ${realParentPath} not in ${allowedDirectories.join(', ')}`);
167+
return await resolveUnicodeEquivalentPath(absolute);
168+
} catch (resolutionError) {
169+
if ((resolutionError as NodeJS.ErrnoException).code === 'ENOENT') {
170+
throw new Error(`Parent directory does not exist: ${path.dirname(absolute)}`);
132171
}
133-
return absolute;
134-
} catch {
135-
throw new Error(`Parent directory does not exist: ${parentDir}`);
172+
throw resolutionError;
136173
}
137174
}
138175
throw error;

0 commit comments

Comments
 (0)