Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions packages/core/src/utils/paths.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,28 @@ describe('resolveToRealPath', () => {

expect(resolveToRealPath(childPath)).toBe(expectedPath);
});

it('should prevent infinite recursion on malicious symlink structures', () => {
const maliciousPath = path.resolve('malicious', 'symlink');

vi.spyOn(fs, 'realpathSync').mockImplementation(() => {
const err = new Error('ENOENT') as NodeJS.ErrnoException;
err.code = 'ENOENT';
throw err;
});

vi.spyOn(fs, 'lstatSync').mockImplementation(
() => ({ isSymbolicLink: () => true }) as fs.Stats,
);

vi.spyOn(fs, 'readlinkSync').mockImplementation(() =>
['..', 'malicious', 'symlink'].join(path.sep),
);

expect(() => resolveToRealPath(maliciousPath)).toThrow(
/Infinite recursion detected/,
);
});
});

describe('normalizePath', () => {
Expand Down
25 changes: 20 additions & 5 deletions packages/core/src/utils/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,11 @@ export function resolveToRealPath(pathStr: string): string {
return robustRealpath(path.resolve(resolvedPath));
}

function robustRealpath(p: string): string {
function robustRealpath(p: string, visited = new Set<string>()): string {
if (visited.has(p)) {
throw new Error(`Infinite recursion detected in robustRealpath: ${p}`);
}
visited.add(p);
try {
return fs.realpathSync(p);
} catch (e: unknown) {
Expand All @@ -385,14 +389,25 @@ function robustRealpath(p: string): string {
if (stat.isSymbolicLink()) {
const target = fs.readlinkSync(p);
const resolvedTarget = path.resolve(path.dirname(p), target);
return robustRealpath(resolvedTarget);
return robustRealpath(resolvedTarget, visited);
}
} catch (lstatError: unknown) {
// Not a symlink, or lstat failed. Re-throw if it's not an expected
// ENOENT (e.g., a permissions error), otherwise resolve parent.
if (
!(
lstatError &&
typeof lstatError === 'object' &&
'code' in lstatError &&
lstatError.code === 'ENOENT'
)
) {
throw lstatError;
}
} catch {
// Not a symlink, or lstat failed. Just resolve parent.
}
const parent = path.dirname(p);
if (parent === p) return p;
return path.join(robustRealpath(parent), path.basename(p));
return path.join(robustRealpath(parent, visited), path.basename(p));
}
throw e;
}
Expand Down
Loading