Skip to content

Commit 9d00621

Browse files
committed
fs: resolve symlinks before parent components
The JavaScript implementation of `fs.realpath()` and `fs.realpathSync()` joined a symlink target with the rest of the path through `path.resolve()`, which collapses `..` lexically before the preceding components have been resolved. A link such as `d -> c/../d`, where `c` is itself a symlink, was therefore rewritten back to `d` and the walk never terminated. Keep `.` and `..` in the path while walking it, and apply `..` to the already resolved parent, matching `realpath(3)` and `fs.realpathSync.native()`. Only normalize the final result, and skip caching link targets containing `..`, whose resolution depends on the path walked before them. Fixes: nodejs#60295 Signed-off-by: jazelly <[email protected]>
1 parent 056e2ae commit 9d00621

2 files changed

Lines changed: 194 additions & 11 deletions

File tree

‎lib/fs.js‎

Lines changed: 90 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3318,6 +3318,20 @@ if (isWindows) {
33183318
};
33193319
}
33203320

3321+
function toAbsolutePathPreservingDots(p) {
3322+
if (!pathModule.isAbsolute(p)) {
3323+
const root = splitRoot(p);
3324+
if (isWindows && root.length === 2) {
3325+
return `${pathModule.resolve(root)}${pathModule.sep}${StringPrototypeSlice(p, root.length)}`;
3326+
}
3327+
return `${pathModule.resolve()}${pathModule.sep}${p}`;
3328+
}
3329+
if (isWindows && splitRoot(p).length === 1) {
3330+
return `${pathModule.parse(pathModule.resolve()).root}${StringPrototypeSlice(p, 1)}`;
3331+
}
3332+
return p;
3333+
}
3334+
33213335
/**
33223336
* Returns the resolved pathname.
33233337
* @param {string | Buffer | URL} p
@@ -3336,17 +3350,17 @@ function realpathSync(p, options) {
33363350
p += '';
33373351
}
33383352
validatePath(p);
3339-
p = pathModule.resolve(p);
3353+
p = toAbsolutePathPreservingDots(p);
33403354

33413355
const cache = options[realpathCacheKey];
3342-
const maybeCachedResult = cache?.get(p);
3356+
const original = p;
3357+
const maybeCachedResult = cache?.get(original);
33433358
if (maybeCachedResult) {
33443359
return maybeCachedResult;
33453360
}
33463361

33473362
const seenLinks = new SafeMap();
33483363
const knownHard = new SafeSet();
3349-
const original = p;
33503364
// Whether the symlink this walk resolved last pointed at a pipe or a
33513365
// socket, which is where the walk stops. It cannot be read back from the
33523366
// shared stat buffer, which holds the last stat made anywhere in the
@@ -3382,6 +3396,9 @@ function realpathSync(p, options) {
33823396
while (pos < p.length) {
33833397
// find the next part
33843398
const result = nextPart(p, pos);
3399+
const part = result === -1 ?
3400+
StringPrototypeSlice(p, pos) :
3401+
StringPrototypeSlice(p, pos, result);
33853402
previous = current;
33863403
if (result === -1) {
33873404
const last = StringPrototypeSlice(p, pos);
@@ -3394,6 +3411,19 @@ function realpathSync(p, options) {
33943411
pos = result + 1;
33953412
}
33963413

3414+
if (part === '' || part === '.') {
3415+
current = previous;
3416+
continue;
3417+
}
3418+
if (part === '..') {
3419+
base = pathModule.dirname(previous);
3420+
current = base;
3421+
if (current[current.length - 1] !== CHAR_FORWARD_SLASH &&
3422+
current[current.length - 1] !== CHAR_BACKWARD_SLASH) {
3423+
current += pathModule.sep;
3424+
}
3425+
continue;
3426+
}
33973427
// Continue if not a symlink, break if a pipe/socket
33983428
if (knownHard.has(base) || cache?.get(base) === base) {
33993429
if (reachedPipeOrSocket) {
@@ -3439,14 +3469,30 @@ function realpathSync(p, options) {
34393469
isFileType(targetStats, S_IFSOCK);
34403470
linkTarget = binding.readlink(base, undefined);
34413471
}
3442-
resolvedLink = pathModule.resolve(previous, linkTarget);
3472+
const linkRoot = splitRoot(linkTarget);
3473+
if (pathModule.isAbsolute(linkTarget)) {
3474+
resolvedLink = isWindows && linkRoot.length === 1 ?
3475+
pathModule.resolve(previous, linkRoot) +
3476+
StringPrototypeSlice(linkTarget, linkRoot.length) :
3477+
linkTarget;
3478+
} else if (isWindows && linkRoot.length === 2) {
3479+
resolvedLink = pathModule.resolve(linkRoot) +
3480+
pathModule.sep + StringPrototypeSlice(linkTarget, linkRoot.length);
3481+
} else {
3482+
resolvedLink = `${previous}${linkTarget}`;
3483+
}
34433484

3444-
cache?.set(base, resolvedLink);
3485+
if (StringPrototypeIndexOf(linkTarget, '..') === -1) {
3486+
cache?.set(base, pathModule.resolve(resolvedLink));
3487+
}
34453488
if (!isWindows) seenLinks.set(id, linkTarget);
34463489
}
34473490

34483491
// Resolve the link, then start over
3449-
p = pathModule.resolve(resolvedLink, StringPrototypeSlice(p, pos));
3492+
const remainder = StringPrototypeSlice(p, pos);
3493+
p = remainder.length === 0 ?
3494+
resolvedLink :
3495+
`${resolvedLink}${pathModule.sep}${remainder}`;
34503496

34513497
// Skip over roots
34523498
current = base = splitRoot(p);
@@ -3463,6 +3509,7 @@ function realpathSync(p, options) {
34633509
}
34643510
}
34653511

3512+
p = pathModule.resolve(p);
34663513
cache?.set(original, p);
34673514
return encodeRealpathResult(p, options);
34683515
}
@@ -3515,7 +3562,7 @@ function realpath(p, options, callback) {
35153562
p += '';
35163563
}
35173564
validatePath(p);
3518-
p = pathModule.resolve(p);
3565+
p = toAbsolutePathPreservingDots(p);
35193566

35203567
const seenLinks = new SafeMap();
35213568
const knownHard = new SafeSet();
@@ -3553,11 +3600,14 @@ function realpath(p, options, callback) {
35533600
function LOOP() {
35543601
// Stop if scanned past end of path
35553602
if (pos >= p.length) {
3556-
return callback(null, encodeRealpathResult(p, options));
3603+
return callback(null, encodeRealpathResult(pathModule.resolve(p), options));
35573604
}
35583605

35593606
// find the next part
35603607
const result = nextPart(p, pos);
3608+
const part = result === -1 ?
3609+
StringPrototypeSlice(p, pos) :
3610+
StringPrototypeSlice(p, pos, result);
35613611
previous = current;
35623612
if (result === -1) {
35633613
const last = StringPrototypeSlice(p, pos);
@@ -3570,10 +3620,23 @@ function realpath(p, options, callback) {
35703620
pos = result + 1;
35713621
}
35723622

3623+
if (part === '' || part === '.') {
3624+
current = previous;
3625+
return process.nextTick(LOOP);
3626+
}
3627+
if (part === '..') {
3628+
base = pathModule.dirname(previous);
3629+
current = base;
3630+
if (current[current.length - 1] !== CHAR_FORWARD_SLASH &&
3631+
current[current.length - 1] !== CHAR_BACKWARD_SLASH) {
3632+
current += pathModule.sep;
3633+
}
3634+
return process.nextTick(LOOP);
3635+
}
35733636
// Continue if not a symlink, break if a pipe/socket
35743637
if (knownHard.has(base)) {
35753638
if (reachedPipeOrSocket) {
3576-
return callback(null, encodeRealpathResult(p, options));
3639+
return callback(null, encodeRealpathResult(pathModule.resolve(p), options));
35773640
}
35783641
return process.nextTick(LOOP);
35793642
}
@@ -3617,12 +3680,28 @@ function realpath(p, options, callback) {
36173680
function gotTarget(err, target) {
36183681
if (err) return callback(err);
36193682

3620-
gotResolvedLink(pathModule.resolve(previous, target));
3683+
const linkRoot = splitRoot(target);
3684+
let resolvedLink;
3685+
if (pathModule.isAbsolute(target)) {
3686+
resolvedLink = isWindows && linkRoot.length === 1 ?
3687+
pathModule.resolve(previous, linkRoot) +
3688+
StringPrototypeSlice(target, linkRoot.length) :
3689+
target;
3690+
} else if (isWindows && linkRoot.length === 2) {
3691+
resolvedLink = pathModule.resolve(linkRoot) +
3692+
pathModule.sep + StringPrototypeSlice(target, linkRoot.length);
3693+
} else {
3694+
resolvedLink = `${previous}${target}`;
3695+
}
3696+
gotResolvedLink(resolvedLink);
36213697
}
36223698

36233699
function gotResolvedLink(resolvedLink) {
36243700
// Resolve the link, then start over
3625-
p = pathModule.resolve(resolvedLink, StringPrototypeSlice(p, pos));
3701+
const remainder = StringPrototypeSlice(p, pos);
3702+
p = remainder.length === 0 ?
3703+
resolvedLink :
3704+
`${resolvedLink}${pathModule.sep}${remainder}`;
36263705
current = base = splitRoot(p);
36273706
pos = current.length;
36283707

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
// Flags: --expose-internals
2+
3+
'use strict';
4+
5+
const common = require('../common');
6+
const assert = require('assert');
7+
const { spawnSync } = require('child_process');
8+
const fs = require('fs');
9+
const { realpathCacheKey } = require('internal/fs/utils');
10+
const path = require('path');
11+
const tmpdir = require('../common/tmpdir');
12+
13+
if (process.argv[2] === 'child') {
14+
if (process.argv[4] === 'callback') {
15+
fs.realpath(process.argv[3], common.mustSucceed((result) => {
16+
process.stdout.write(result);
17+
}));
18+
} else {
19+
process.stdout.write(fs.realpathSync(process.argv[3]));
20+
}
21+
} else {
22+
if (!common.canCreateSymLink())
23+
common.skip('insufficient privileges');
24+
25+
tmpdir.refresh();
26+
27+
// Reproduce a symlink target containing `..` after another symlink:
28+
// c -> a/b/c
29+
// d -> c/../d -> a/b/d
30+
// The cache fixture also creates a separate d to ensure that c/../d stays
31+
// distinct from the lexically normalized path d.
32+
const target = tmpdir.resolve('a', 'b', 'd');
33+
fs.mkdirSync(tmpdir.resolve('a', 'b', 'c'), { recursive: true });
34+
fs.mkdirSync(target);
35+
fs.symlinkSync(path.join('a', 'b', 'c'), tmpdir.resolve('c'), 'dir');
36+
fs.symlinkSync(`c${path.sep}..${path.sep}d`, tmpdir.resolve('d'), 'dir');
37+
38+
const cacheRoot = tmpdir.resolve('cache');
39+
const cacheTarget = path.join(cacheRoot, 'a', 'b', 'd');
40+
const cachePlain = path.join(cacheRoot, 'd');
41+
fs.mkdirSync(path.join(cacheRoot, 'a', 'b', 'c'), { recursive: true });
42+
fs.mkdirSync(cacheTarget);
43+
fs.mkdirSync(cachePlain);
44+
fs.symlinkSync(path.join('a', 'b', 'c'), path.join(cacheRoot, 'c'), 'dir');
45+
const cacheDotted = `${cacheRoot}${path.sep}c${path.sep}..${path.sep}d`;
46+
const cacheExpected = fs.realpathSync(cacheTarget);
47+
const plainExpected = fs.realpathSync(cachePlain);
48+
49+
function assertCacheIsolation(first, firstExpected, second, secondExpected) {
50+
const cache = new Map();
51+
const options = { [realpathCacheKey]: cache };
52+
assert.strictEqual(fs.realpathSync(first, options), firstExpected);
53+
assert.strictEqual(fs.realpathSync(second, options), secondExpected);
54+
}
55+
56+
assertCacheIsolation(cacheDotted, cacheExpected, cachePlain, plainExpected);
57+
assertCacheIsolation(cachePlain, plainExpected, cacheDotted, cacheExpected);
58+
59+
// Run realpathSync in a child because the regression does not return.
60+
const result = spawnSync(process.execPath, [
61+
'--expose-internals',
62+
__filename,
63+
'child',
64+
tmpdir.resolve('d'),
65+
], {
66+
encoding: 'utf8',
67+
timeout: common.platformTimeout(5000),
68+
});
69+
70+
assert.ifError(result.error);
71+
assert.strictEqual(result.status, 0, result.stderr);
72+
assert.strictEqual(result.stdout, target);
73+
74+
const directInput = `c${path.sep}..${path.sep}d`;
75+
const directResult = spawnSync(process.execPath, [
76+
'--expose-internals',
77+
__filename,
78+
'child',
79+
directInput,
80+
], {
81+
encoding: 'utf8',
82+
cwd: tmpdir.path,
83+
timeout: common.platformTimeout(5000),
84+
});
85+
86+
assert.ifError(directResult.error);
87+
assert.strictEqual(directResult.status, 0, directResult.stderr);
88+
assert.strictEqual(directResult.stdout, target);
89+
90+
const callbackResult = spawnSync(process.execPath, [
91+
'--expose-internals',
92+
__filename,
93+
'child',
94+
tmpdir.resolve('d'),
95+
'callback',
96+
], {
97+
encoding: 'utf8',
98+
timeout: common.platformTimeout(5000),
99+
});
100+
101+
assert.ifError(callbackResult.error);
102+
assert.strictEqual(callbackResult.status, 0, callbackResult.stderr);
103+
assert.strictEqual(callbackResult.stdout, target);
104+
}

0 commit comments

Comments
 (0)