Skip to content

Commit de13fd2

Browse files
author
unknown
committed
Fix UNC path validation: cover all corruption sites on Windows
PR modelcontextprotocol#3921 fixes isPathWithinAllowedDirectories for UNC paths, but three other sites in the filesystem server also corrupt UNC paths via path.resolve or preserve them incorrectly through path.normalize: 1. path-validation.ts::normalizePossiblyUNCPath path.normalize preserves trailing separators on UNC paths on Windows (unlike path.resolve for drive paths), so 'normalizedDir + path.sep' produces a double separator that startsWith() never matches. Strip the trailing separator to harmonize. 2. lib.ts::validatePath Calls path.resolve(expandedPath) before the allowed-directory check, which on Windows corrupts UNC paths into drive-relative paths (\\\\server\\share -> C:\\server\\share). Skip path.resolve for UNC paths and let normalizePath handle them. 3. index.ts bootstrap Same path.resolve corruption when normalizing allowed directories at server startup, before they are stored via setAllowedDirectories. Same guard applied. All non-UNC paths retain existing behavior (path.resolve + normalize). Tests added: - 4 tests in path-validation.test.ts for the trailing-separator case - 6 tests in lib.test.ts for validatePath end-to-end on UNC, gated behind process.platform === 'win32' and using the existing fs mock pattern - Bug modelcontextprotocol#3 (bootstrap) has no direct unit test since UNC access in CI is not available, but the fix applies the same principle as validatePath and is logically covered. Fixes modelcontextprotocol#3756 Supersedes modelcontextprotocol#3921
1 parent 4503e2d commit de13fd2

5 files changed

Lines changed: 168 additions & 5 deletions

File tree

‎src/filesystem/__tests__/lib.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,64 @@ describe('Lib Functions', () => {
228228
process.cwd = originalCwd;
229229
}
230230
});
231+
232+
// Tests for UNC path resolution (bug #3 in the companion PR):
233+
// validatePath calls path.resolve() on the absolute path before the
234+
// allowed-directory check. On Windows, path.resolve corrupts UNC paths
235+
// (\\server\share becomes C:\server\share via path.normalize stripping
236+
// a leading backslash). Without the UNC guard, every UNC access throws
237+
// "Access denied" even when the UNC directory is explicitly allowed.
238+
describe('UNC path handling on Windows', () => {
239+
beforeEach(() => {
240+
if (process.platform !== 'win32') return;
241+
setAllowedDirectories(['\\\\server\\share\\project']);
242+
// Simulate fs.realpath returning the UNC path as-is
243+
mockFs.realpath.mockImplementation(async (p: any) => p.toString());
244+
});
245+
246+
it('accepts UNC file path within allowed UNC directory', async () => {
247+
if (process.platform !== 'win32') return;
248+
const testPath = '\\\\server\\share\\project\\file.txt';
249+
const result = await validatePath(testPath);
250+
expect(result).toBe(testPath);
251+
});
252+
253+
it('accepts UNC directory path matching allowed UNC exactly', async () => {
254+
if (process.platform !== 'win32') return;
255+
const testPath = '\\\\server\\share\\project';
256+
const result = await validatePath(testPath);
257+
expect(result).toBe(testPath);
258+
});
259+
260+
it('accepts nested UNC subdirectory within allowed UNC', async () => {
261+
if (process.platform !== 'win32') return;
262+
const testPath = '\\\\server\\share\\project\\src\\sub\\deep.ts';
263+
const result = await validatePath(testPath);
264+
expect(result).toBe(testPath);
265+
});
266+
267+
it('rejects UNC path outside allowed UNC directory', async () => {
268+
if (process.platform !== 'win32') return;
269+
const testPath = '\\\\server\\share\\other\\file.txt';
270+
await expect(validatePath(testPath))
271+
.rejects.toThrow('Access denied - path outside allowed directories');
272+
});
273+
274+
it('rejects UNC path on a different server', async () => {
275+
if (process.platform !== 'win32') return;
276+
const testPath = '\\\\other-server\\share\\project\\file.txt';
277+
await expect(validatePath(testPath))
278+
.rejects.toThrow('Access denied - path outside allowed directories');
279+
});
280+
281+
it('accepts UNC file path when allowed UNC has trailing separator', async () => {
282+
if (process.platform !== 'win32') return;
283+
setAllowedDirectories(['\\\\server\\share\\project\\']);
284+
const testPath = '\\\\server\\share\\project\\file.txt';
285+
const result = await validatePath(testPath);
286+
expect(result).toBe(testPath);
287+
});
288+
});
231289
});
232290
});
233291

‎src/filesystem/__tests__/path-validation.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,68 @@ describe('Path Validation', () => {
439439
expect(isPathWithinAllowedDirectories('\\\\other\\share\\project', allowed)).toBe(false);
440440
}
441441
});
442+
443+
it('allows UNC path within allowed UNC directory', () => {
444+
if (path.sep === '\\') {
445+
const allowed = ['\\\\server\\share\\project'];
446+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\project\\subdir\\file.txt', allowed)).toBe(true);
447+
}
448+
});
449+
450+
it('blocks UNC path outside allowed UNC directory', () => {
451+
if (path.sep === '\\') {
452+
const allowed = ['\\\\server\\share\\project'];
453+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\other', allowed)).toBe(false);
454+
expect(isPathWithinAllowedDirectories('\\\\other\\share\\project', allowed)).toBe(false);
455+
}
456+
});
457+
458+
it('allows exact UNC path match', () => {
459+
if (path.sep === '\\') {
460+
const allowed = ['\\\\server\\share\\project'];
461+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\project', allowed)).toBe(true);
462+
}
463+
});
464+
465+
// Tests for UNC trailing-slash regression (bug #2 in the companion PR):
466+
// path.normalize preserves trailing separators on UNC paths on Windows,
467+
// while path.resolve strips them for drive paths. Without harmonization,
468+
// the `normalizedDir + path.sep` comparison produces a double separator
469+
// that startsWith() never matches, making every access fail even when
470+
// the allowed directory is configured with a trailing backslash.
471+
it('allows file inside allowed UNC directory with trailing separator', () => {
472+
if (path.sep === '\\') {
473+
const allowed = ['\\\\server\\share\\project\\'];
474+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\project\\file.txt', allowed)).toBe(true);
475+
}
476+
});
477+
478+
it('allows subdirectories inside allowed UNC directory with trailing separator', () => {
479+
if (path.sep === '\\') {
480+
const allowed = ['\\\\server\\share\\project\\'];
481+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\project\\src\\index.ts', allowed)).toBe(true);
482+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\project\\deeply\\nested\\file', allowed)).toBe(true);
483+
}
484+
});
485+
486+
it('allows exact match against allowed UNC directory with trailing separator', () => {
487+
if (path.sep === '\\') {
488+
const allowed = ['\\\\server\\share\\project\\'];
489+
// Path without trailing separator
490+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\project', allowed)).toBe(true);
491+
// Path with trailing separator
492+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\project\\', allowed)).toBe(true);
493+
}
494+
});
495+
496+
it('blocks sibling UNC paths with common prefix when allowed has trailing separator', () => {
497+
if (path.sep === '\\') {
498+
const allowed = ['\\\\server\\share\\project\\'];
499+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\project2', allowed)).toBe(false);
500+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\project_backup', allowed)).toBe(false);
501+
expect(isPathWithinAllowedDirectories('\\\\server\\share\\projectile', allowed)).toBe(false);
502+
}
503+
});
442504
});
443505

444506
describe('Symlink Tests', () => {

‎src/filesystem/index.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,10 @@ if (args.length === 0) {
4545
let allowedDirectories = (await Promise.all(
4646
args.map(async (dir) => {
4747
const expanded = expandHome(dir);
48-
const absolute = path.resolve(expanded);
48+
// UNC-aware: path.resolve corrupts UNC paths (\\server\share becomes
49+
// C:\server\share on Windows). Skip it for UNC paths and let normalizePath
50+
// handle them. Same fix applied in lib.ts validatePath.
51+
const absolute = expanded.startsWith('\\\\') ? expanded : path.resolve(expanded);
4952
const normalizedOriginal = normalizePath(absolute);
5053
try {
5154
// Security: Resolve symlinks in allowed directories during startup

‎src/filesystem/lib.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,14 @@ function resolveRelativePathAgainstAllowedDirectories(relativePath: string): str
9898
// Security & Validation Functions
9999
export async function validatePath(requestedPath: string): Promise<string> {
100100
const expandedPath = expandHome(requestedPath);
101+
// UNC-aware resolution: path.resolve() on Windows corrupts UNC paths
102+
// (\\server\share becomes C:\server\share via path.normalize stripping
103+
// a leading backslash, then path.resolve treating it as drive-relative).
104+
// For UNC paths we skip path.resolve entirely and let normalizePath handle
105+
// them. PR #3921 only patched isPathWithinAllowedDirectories; validatePath
106+
// needs the same treatment upstream of it.
101107
const absolute = path.isAbsolute(expandedPath)
102-
? path.resolve(expandedPath)
108+
? (expandedPath.startsWith('\\\\') ? expandedPath : path.resolve(expandedPath))
103109
: resolveRelativePathAgainstAllowedDirectories(expandedPath);
104110

105111
const normalizedRequested = normalizePath(absolute);

‎src/filesystem/path-validation.ts‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,42 @@
11
import path from 'path';
22

3+
/**
4+
* Checks if a path is a UNC path (e.g. \\server\share).
5+
*/
6+
function isUNCPath(p: string): boolean {
7+
return p.startsWith('\\\\');
8+
}
9+
10+
/**
11+
* Normalizes a path that may be a UNC path on Windows.
12+
*
13+
* On Windows, path.normalize can strip one leading backslash from UNC paths
14+
* (e.g. \\server\share becomes \server\share), and then path.resolve
15+
* interprets it as a drive-relative path (e.g. C:\server\share). This
16+
* function preserves the UNC prefix through normalization.
17+
*/
18+
function normalizePossiblyUNCPath(p: string): string {
19+
if (isUNCPath(p)) {
20+
let normalized = path.normalize(p);
21+
// path.normalize may strip a leading backslash from UNC paths
22+
if (!normalized.startsWith('\\\\')) {
23+
normalized = '\\' + normalized;
24+
}
25+
// path.normalize preserves trailing separators for UNC paths on Windows,
26+
// while path.resolve (used for non-UNC paths below) strips them. Harmonize
27+
// here: without stripping, `normalizedDir + path.sep` in the caller produces
28+
// a double separator that startsWith() never matches.
29+
if (normalized.length > 2 && normalized.endsWith(path.sep)) {
30+
normalized = normalized.slice(0, -1);
31+
}
32+
return normalized;
33+
}
34+
return path.resolve(path.normalize(p));
35+
}
36+
337
/**
438
* Checks if an absolute path is within any of the allowed directories.
5-
*
39+
*
640
* @param absolutePath - The absolute path to check (will be normalized)
741
* @param allowedDirectories - Array of absolute allowed directory paths (will be normalized)
842
* @returns true if the path is within an allowed directory, false otherwise
@@ -27,7 +61,7 @@ export function isPathWithinAllowedDirectories(absolutePath: string, allowedDire
2761
// Normalize the input path
2862
let normalizedPath: string;
2963
try {
30-
normalizedPath = path.resolve(path.normalize(absolutePath));
64+
normalizedPath = normalizePossiblyUNCPath(absolutePath);
3165
} catch {
3266
return false;
3367
}
@@ -51,7 +85,7 @@ export function isPathWithinAllowedDirectories(absolutePath: string, allowedDire
5185
// Normalize the allowed directory
5286
let normalizedDir: string;
5387
try {
54-
normalizedDir = path.resolve(path.normalize(dir));
88+
normalizedDir = normalizePossiblyUNCPath(dir);
5589
} catch {
5690
return false;
5791
}

0 commit comments

Comments
 (0)