Skip to content

Commit 4225d1b

Browse files
committed
esm: protect ESM loader from prototype pollution
In a previous commit, the loader implementation was modified to be protected against most prototype pollution, but was kept vulnerable to `Array.prototype` pollution. This commit fixes that, the tradeoff is that it modifies the `ESMLoader.prototype.import` return type from an `Array` to an array-like object. Refs: nodejs#45044
1 parent 67828d5 commit 4225d1b

File tree

9 files changed

+120
-28
lines changed

9 files changed

+120
-28
lines changed

doc/contributing/primordials.md

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -363,20 +363,30 @@ Object.defineProperty(Object.prototype, Symbol.isConcatSpreadable, {
363363
// 1. Lookup @@iterator property on `array` (user-mutable if user-provided).
364364
// 2. Lookup @@iterator property on %Array.prototype% (user-mutable).
365365
// 3. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable).
366+
// 4. Lookup `then` property on %Array.Prototype% (user-mutable).
367+
// 5. Lookup `then` property on %Object.Prototype% (user-mutable).
366368
PromiseAll([]); // unsafe
367369

368-
PromiseAll(new SafeArrayIterator([])); // safe
370+
// 1. Lookup `then` property on %Array.Prototype% (user-mutable).
371+
// 2. Lookup `then` property on %Object.Prototype% (user-mutable).
372+
PromiseAll(new SafeArrayIterator([])); // still unsafe
373+
SafePromiseAll([]); // still unsafe
374+
375+
SafePromiseAllReturnVoid([]); // safe
376+
SafePromiseAllReturnArrayLike([]); // safe
369377

370378
const array = [promise];
371379
const set = new SafeSet().add(promise);
372380
// When running one of these functions on a non-empty iterable, it will also:
373-
// 4. Lookup `then` property on `promise` (user-mutable if user-provided).
374-
// 5. Lookup `then` property on `%Promise.prototype%` (user-mutable).
381+
// 1. Lookup `then` property on `promise` (user-mutable if user-provided).
382+
// 2. Lookup `then` property on `%Promise.prototype%` (user-mutable).
383+
// 3. Lookup `then` property on %Array.Prototype% (user-mutable).
384+
// 4. Lookup `then` property on %Object.Prototype% (user-mutable).
375385
PromiseAll(new SafeArrayIterator(array)); // unsafe
376-
377386
PromiseAll(set); // unsafe
378387

379-
SafePromiseAll(array); // safe
388+
SafePromiseAllReturnVoid(array); // safe
389+
SafePromiseAllReturnArrayLike(array); // safe
380390

381391
// Some key differences between `SafePromise[...]` and `Promise[...]` methods:
382392

@@ -385,11 +395,18 @@ SafePromiseAll(array); // safe
385395
SafePromiseAll(ArrayPrototypeMap(array, someFunction));
386396
SafePromiseAll(array, someFunction); // Same as the above, but more efficient.
387397

388-
// 2. SafePromiseAll, SafePromiseAllSettled, SafePromiseAny, and SafePromiseRace
389-
// only support arrays, not iterables. Use ArrayFrom to convert an iterable
390-
// to an array.
391-
SafePromiseAll(set); // ignores set content.
392-
SafePromiseAll(ArrayFrom(set)); // safe
398+
// 2. SafePromiseAll, SafePromiseAllSettled, SafePromiseAny, SafePromiseRace,
399+
// SafePromiseAllReturnArrayLike, SafePromiseAllReturnVoid, and
400+
// SafePromiseAllSettledReturnVoid only support arrays and array-like
401+
// objects, not iterables. Use ArrayFrom to convert an iterable to an array.
402+
SafePromiseAllReturnVoid(set); // ignores set content.
403+
SafePromiseAllReturnVoid(ArrayFrom(set)); // works
404+
405+
// 3. SafePromiseAllReturnArrayLike is safer than SafePromiseAll, however you
406+
// should not use them when its return value is passed to the user as it can
407+
// be surprising for them not to receive a genuine array.
408+
SafePromiseAllReturnArrayLike(array).then((val) => Array.isArray(val)); // false
409+
SafePromiseAll(array).then((val) => Array.isArray(val)); // true
393410
```
394411

395412
</details>

lib/internal/modules/esm/loader.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const {
1414
ObjectDefineProperty,
1515
ObjectSetPrototypeOf,
1616
RegExpPrototypeExec,
17-
SafePromiseAll,
17+
SafePromiseAllReturnArrayLike,
1818
SafeWeakMap,
1919
StringPrototypeSlice,
2020
StringPrototypeToUpperCase,
@@ -516,7 +516,7 @@ class ESMLoader {
516516
.then(({ module }) => module.getNamespace());
517517
}
518518

519-
const namespaces = await SafePromiseAll(jobs);
519+
const namespaces = await SafePromiseAllReturnArrayLike(jobs);
520520

521521
if (!wasArr) { return namespaces[0]; } // We can skip the pairing below
522522

lib/internal/modules/esm/module_job.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ const {
1212
ReflectApply,
1313
RegExpPrototypeExec,
1414
RegExpPrototypeSymbolReplace,
15-
SafePromiseAll,
15+
SafePromiseAllReturnArrayLike,
16+
SafePromiseAllReturnVoid,
1617
SafeSet,
1718
StringPrototypeIncludes,
1819
StringPrototypeSplit,
@@ -80,9 +81,9 @@ class ModuleJob {
8081
});
8182

8283
if (promises !== undefined)
83-
await SafePromiseAll(promises);
84+
await SafePromiseAllReturnVoid(promises);
8485

85-
return SafePromiseAll(dependencyJobs);
86+
return SafePromiseAllReturnArrayLike(dependencyJobs);
8687
};
8788
// Promise for the list of all dependencyJobs.
8889
this.linked = link();
@@ -110,7 +111,7 @@ class ModuleJob {
110111
}
111112
jobsInGraph.add(moduleJob);
112113
const dependencyJobs = await moduleJob.linked;
113-
return SafePromiseAll(dependencyJobs, addJobsToDependencyGraph);
114+
return SafePromiseAllReturnArrayLike(dependencyJobs, addJobsToDependencyGraph);
114115
};
115116
await addJobsToDependencyGraph(this);
116117

lib/internal/per_context/primordials.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,34 @@ primordials.SafePromiseAll = (promises, mapFn) =>
477477
SafePromise.all(arrayToSafePromiseIterable(promises, mapFn)).then(a, b)
478478
);
479479

480+
/**
481+
* Should only be used for internal functions, this would produce similar
482+
* results as `Promise.all` but without prototype pollution, and the return
483+
* value is not a genuine Array but an array-like object.
484+
* @param {Promise<any>[]} promises
485+
* @returns {Promise<any[]>}
486+
*/
487+
primordials.SafePromiseAllReturnArrayLike = async (promises) => {
488+
const { length } = promises;
489+
const returnVal = { __proto__: null, length };
490+
for (let i = 0; i < length; i++) {
491+
returnVal[i] = await promises[i];
492+
}
493+
return returnVal;
494+
};
495+
496+
/**
497+
* Should only be used when we only care about waiting for all the promises to
498+
* resolve, not what value they resolve to.
499+
* @param {Promise<any>[]} promises
500+
* @returns {Promise<void>}
501+
*/
502+
primordials.SafePromiseAllReturnVoid = async (promises) => {
503+
for (let i = 0; i < promises.length; i++) {
504+
await promises[i];
505+
}
506+
};
507+
480508
/**
481509
* @param {Promise<any>[]} promises
482510
* @param {(v: Promise<any>, k: number) => Promise<any>} [mapFn]
@@ -489,6 +517,22 @@ primordials.SafePromiseAllSettled = (promises, mapFn) =>
489517
SafePromise.allSettled(arrayToSafePromiseIterable(promises, mapFn)).then(a, b)
490518
);
491519

520+
/**
521+
* Should only be used when we only care about waiting for all the promises to
522+
* settle, not what value they resolve or reject to.
523+
* @param {Promise<any>[]} promises
524+
* @returns {Promise<void>}
525+
*/
526+
primordials.SafePromiseAllSettledReturnVoid = async (promises) => {
527+
for (let i = 0; i < promises.length; i++) {
528+
try {
529+
await promises[i];
530+
} catch {
531+
// In all settled, we can ignore errors.
532+
}
533+
}
534+
};
535+
492536
/**
493537
* @param {Promise<any>[]} promises
494538
* @param {(v: Promise<any>, k: number) => Promise<any>} [mapFn]

lib/internal/vm/module.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ const {
1111
ObjectGetPrototypeOf,
1212
ObjectSetPrototypeOf,
1313
ReflectApply,
14-
SafePromiseAll,
14+
SafePromiseAllReturnVoid,
1515
SafeWeakMap,
1616
Symbol,
1717
SymbolToStringTag,
@@ -330,7 +330,7 @@ class SourceTextModule extends Module {
330330

331331
try {
332332
if (promises !== undefined) {
333-
await SafePromiseAll(promises);
333+
await SafePromiseAllReturnVoid(promises);
334334
}
335335
} catch (e) {
336336
this.#error = e;

test/es-module/test-cjs-prototype-pollution.js

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,6 @@
22

33
const { mustNotCall, mustCall } = require('../common');
44

5-
Object.defineProperties(Array.prototype, {
6-
// %Promise.all% and %Promise.allSettled% are depending on the value of
7-
// `%Array.prototype%.then`.
8-
then: {},
9-
});
105
Object.defineProperties(Object.prototype, {
116
then: {
127
set: mustNotCall('set %Object.prototype%.then'),

test/parallel/test-eslint-avoid-prototype-pollution.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ new RuleTester({
6363
'new Proxy({}, someFactory())',
6464
'new Proxy({}, { __proto__: null })',
6565
'new Proxy({}, { __proto__: null, ...{} })',
66+
'async function name(){return await SafePromiseAll([])}',
67+
'async function name(){const val = await SafePromiseAll([])}',
6668
],
6769
invalid: [
6870
{
@@ -273,6 +275,14 @@ new RuleTester({
273275
code: 'PromiseAll([])',
274276
errors: [{ message: /\bSafePromiseAll\b/ }]
275277
},
278+
{
279+
code: 'async function fn(){await SafePromiseAll([])}',
280+
errors: [{ message: /\bSafePromiseAllReturnVoid\b/ }]
281+
},
282+
{
283+
code: 'async function fn(){await SafePromiseAllSettled([])}',
284+
errors: [{ message: /\bSafePromiseAllSettledReturnVoid\b/ }]
285+
},
276286
{
277287
code: 'PromiseAllSettled([])',
278288
errors: [{ message: /\bSafePromiseAllSettled\b/ }]

test/parallel/test-primordials-promise.js

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ const assert = require('assert');
77
const {
88
PromisePrototypeThen,
99
SafePromiseAll,
10+
SafePromiseAllReturnArrayLike,
11+
SafePromiseAllReturnVoid,
1012
SafePromiseAllSettled,
13+
SafePromiseAllSettledReturnVoid,
1114
SafePromiseAny,
1215
SafePromisePrototypeFinally,
1316
SafePromiseRace,
@@ -34,9 +37,11 @@ Object.defineProperties(Promise.prototype, {
3437
},
3538
});
3639
Object.defineProperties(Array.prototype, {
37-
// %Promise.all% and %Promise.allSettled% are depending on the value of
38-
// `%Array.prototype%.then`.
39-
then: {},
40+
then: {
41+
configurable: true,
42+
set: common.mustNotCall('set %Array.prototype%.then'),
43+
get: common.mustNotCall('get %Array.prototype%.then'),
44+
},
4045
});
4146
Object.defineProperties(Object.prototype, {
4247
then: {
@@ -48,11 +53,24 @@ Object.defineProperties(Object.prototype, {
4853
assertIsPromise(PromisePrototypeThen(test(), common.mustCall()));
4954
assertIsPromise(SafePromisePrototypeFinally(test(), common.mustCall()));
5055

51-
assertIsPromise(SafePromiseAll([test()]));
52-
assertIsPromise(SafePromiseAllSettled([test()]));
56+
assertIsPromise(SafePromiseAllReturnArrayLike([test()]));
57+
assertIsPromise(SafePromiseAllReturnVoid([test()]));
58+
assertIsPromise(SafePromiseAllSettledReturnVoid([test()]));
5359
assertIsPromise(SafePromiseAny([test()]));
5460
assertIsPromise(SafePromiseRace([test()]));
5561

62+
Object.defineProperties(Array.prototype, {
63+
// %Promise.all% and %Promise.allSettled% are depending on the value of
64+
// `%Array.prototype%.then`.
65+
then: {
66+
__proto__: undefined,
67+
value: undefined,
68+
},
69+
});
70+
71+
assertIsPromise(SafePromiseAll([test()]));
72+
assertIsPromise(SafePromiseAllSettled([test()]));
73+
5674
async function test() {
5775
const catchFn = common.mustCall();
5876
const finallyFn = common.mustCall();

tools/eslint-rules/avoid-prototype-pollution.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,13 @@ module.exports = {
194194
});
195195
},
196196

197+
[`ExpressionStatement>AwaitExpression>${CallExpression(/^(Safe)?PromiseAll(Settled)?$/)}`](node) {
198+
context.report({
199+
node,
200+
message: `Use ${node.callee.name}ReturnVoid`,
201+
});
202+
},
203+
197204
[CallExpression('PromisePrototypeCatch')](node) {
198205
context.report({
199206
node,

0 commit comments

Comments
 (0)