Harden some things
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 67acf60 · Browse files · 34 files·+375 added−37 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
34 files+375 added−37 removed
- tests:+282 added−1 removed
- other:+93 added−36 removed
Provenance
- Commit
4a0a121- Tree
0ce5afa- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
67acf60
34 files changed+375 added−37 removed
modified:lib/arguments/command.js+2 added-1 removed
7 unmodified lines891011121213141516174 unmodified lines7 unmodified linesexport const handleCommand = (filePath, rawArguments, rawOptions) => { const startTime = getStartTime(); const {command, escapedCommand} = joinCommand(filePath, rawArguments); const verbose = normalizeFdSpecificOption(rawOptions, 'verbose'); // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values const verboseInfo = getVerboseInfo(verbose, escapedCommand, {...rawOptions}); const verboseInfo = getVerboseInfo(verbose, escapedCommand, {__proto__: null, ...rawOptions}); logCommand(escapedCommand, verboseInfo); return { command, escapedCommand,4 unmodified linesmodified:lib/arguments/encoding-option.js+1 added
37 unmodified lines3839404142434445465 unmodified lines37 unmodified lines }};
const ENCODING_ALIASES = { __proto__: null, // eslint-disable-next-line unicorn/text-encoding-identifier-case 'utf-8': 'utf8', 'utf-16le': 'utf16le', 'ucs-2': 'utf16le',5 unmodified linesmodified:lib/arguments/options.js+9 added-2 removed
86 unmodified lines8788899091929394959697919899931001011021031049 unmodified lines86 unmodified lines ipc, serialization,});
/*Keep a null prototype, otherwise a polluted `Object.prototype` would inject environment variables.Unlike the other options, `child_process` intentionally passes the inherited properties of `env` to the subprocess, so they are the ones which must not leak. This includes `PATH`, which decides which file the command resolves to.`npmRunPathEnv()` returns a plain object, so this is applied to its result too.*/const getEnv = options => ({__proto__: null, ...computeEnv(options)});
const getEnv = ({env: envOption, extendEnv, preferLocal, node, localDirectory, nodePath}) => {const computeEnv = ({env: envOption, extendEnv, preferLocal, node, localDirectory, nodePath}) => { // Spread `envOption` even when it is `undefined`, so `extendEnv: false` results in an empty environment instead of inheriting `process.env` const env = extendEnv ? {...process.env, ...envOption} : {...envOption}; const env = {__proto__: null, ...(extendEnv && process.env), ...envOption};
if (preferLocal || node) { return npmRunPathEnv({ env,9 unmodified linesmodified:lib/arguments/specific.js+2 added-1 removed
4 unmodified lines5 // Some options can have different values for `stdout`/`stderr`/`fd3`.6 // This normalizes those to array of values.7 // For example, `{verbose: {stdout: 'none', stderr: 'full'}}` becomes `{verbose: ['none', 'none', 'full']}`8 export const normalizeFdSpecificOptions = options => {9+ // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values9- const optionsCopy = {...options};10+ const optionsCopy = {__proto__: null, ...options};11 12 for (const optionName of FD_SPECIFIC_OPTIONS) {13 optionsCopy[optionName] = normalizeFdSpecificOption(options, optionName);14 }99 unmodified linesmodified:lib/convert/duplex.js+3 added-1 removed
14 unmodified lines15 onWritableDestroy,16 } from './writable.js';17 18 // Create a `Duplex` stream combining both `subprocess.readable()` and `subprocess.writable()`19-export const createDuplex = ({subprocess, concurrentStreams, encoding}, {from, to, binary: binaryOption = true, preserveNewlines = true} = {}) => {19+export const createDuplex = ({subprocess, concurrentStreams, encoding}, options) => {20+ // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values21+ const {from, to, binary: binaryOption = true, preserveNewlines = true} = {__proto__: null, ...options};22 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);23 const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);24 const {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams);25 const {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary);46 unmodified linesmodified:lib/convert/iterable.js+3 added-5 removed
1 unmodified line2 import {getFromStream} from '../arguments/fd-options.js';3 import {iterateOnSubprocessStream} from '../io/iterate.js';4 5 // Convert the subprocess to an async iterable6-export const createIterable = (subprocess, encoding, {7- from,8- binary: binaryOption = false,9- preserveNewlines = false,10-} = {}) => {6+export const createIterable = (subprocess, encoding, options) => {7+ // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values8+ const {from, binary: binaryOption = false, preserveNewlines = false} = {__proto__: null, ...options};9 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);10 const subprocessStdout = getFromStream(subprocess, from);11 const onStdoutData = iterateOnSubprocessStream({12 subprocessStdout,20 unmodified linesmodified:lib/convert/readable.js+3 added-1 removed
11 unmodified lines12 destroyOtherStream,13 } from './shared.js';14 15 // Create a `Readable` stream that forwards from `stdout` and awaits the subprocess16-export const createReadable = ({subprocess, concurrentStreams, encoding}, {from, binary: binaryOption = true, preserveNewlines = true} = {}) => {16+export const createReadable = ({subprocess, concurrentStreams, encoding}, options) => {17+ // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values18+ const {from, binary: binaryOption = true, preserveNewlines = true} = {__proto__: null, ...options};19 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);20 const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);21 const {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary);22 const {read, onStdoutDataDone} = getReadableMethods({109 unmodified linesmodified:lib/convert/writable.js+3 added-1 removed
9 unmodified lines10 destroyOtherStream,11 } from './shared.js';12 13 // Create a `Writable` stream that forwards to `stdin` and awaits the subprocess14-export const createWritable = ({subprocess, concurrentStreams}, {to} = {}) => {14+export const createWritable = ({subprocess, concurrentStreams}, options) => {15+ // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values16+ const {to} = {__proto__: null, ...options};17 const {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams);18 const writable = new Writable({19 ...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal),20 destroy: callbackify(onWritableDestroy.bind(undefined, {93 unmodified linesmodified:lib/ipc/get-each.js+8 added-2 removed
1 import {once, on} from 'node:events';2-import {validateIpcMethod, disconnect, getStrictResponseError} from './validation.js';2+import {3+ validateIpcMethod,4+ disconnect,5+ getStrictResponseError,6+ getIpcOptions,7+} from './validation.js';8 import {getIpcEmitter, isConnected} from './forward.js';9 import {addReference, removeReference} from './reference.js';10 11 export const internalGetEachMessageOptions = Symbol('internalGetEachMessageOptions');12 13 // Like `[sub]process.on('message')` but promise-based9-export const getEachMessage = (subprocessInfo, options = {}) => {14+export const getEachMessage = (subprocessInfo, rawOptions) => {15+ const options = getIpcOptions(rawOptions);16 const {reference = true} = options;17 // Internal callers can stop the IPC listener without exposing cancellation or pipe-awaiting options as public API.18 const {signal, shouldAwait = !subprocessInfo.isSubprocess} = options[internalGetEachMessageOptions] ?? {};19 100 unmodified linesmodified:lib/ipc/get-one.js+3 added-1 removed
2 unmodified lines3 validateIpcMethod,4 throwOnEarlyDisconnect,5 disconnect,6 getStrictResponseError,7+ getIpcOptions,8 } from './validation.js';9 import {getIpcEmitter, isConnected} from './forward.js';10 import {addReference, removeReference} from './reference.js';11 12 export const internalGetOneMessageOptions = Symbol('internalGetOneMessageOptions');13 14 // Like `[sub]process.once('message')` but promise-based14-export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, options = {}) => {15+export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, rawOptions) => {16+ const options = getIpcOptions(rawOptions);17 const {reference = true, filter} = options;18 const {signal} = options[internalGetOneMessageOptions] ?? {};19 20 validateIpcMethod({74 unmodified linesmodified:lib/ipc/graceful.js+3 added-2 removed
31 unmodified lines32 if (isCancelListening) {33 return;34 }35 36- isCancelListening = true;37-36+ // This is validated before the flag is set, so that a call which throws keeps failing on subsequent calls37 if (!ipc) {38 throwOnMissingParent();39 return;40 }41 42+ isCancelListening = true;43+44 if (channel === null) {45 abortOnDisconnect();46 return;47 }26 unmodified linesmodified:lib/ipc/incoming.js+8 added-2 removed
22 unmodified lines23 // The default behavior does not allow users to realize they made that mistake.24 // To solve those problems, instead of buffering messages, we debounce them.25 // The `message` event so it is emitted at most once per macrotask.26 export const onMessage = async ({anyProcess, channel, isSubprocess, ipcEmitter}, wrappedMessage) => {27+ // `gracefulCancel` messages are only ever sent by the current process to its subprocess.28+ // Only the subprocess must interpret them, otherwise a subprocess could abort its parent's own `cancelSignal`, or make it silently drop a message.27- if (handleStrictResponse(wrappedMessage) || handleAbort(wrappedMessage)) {29+ if (handleStrictResponse(wrappedMessage) || (isSubprocess && handleAbort(wrappedMessage))) {30 return;31 }32 33 if (!INCOMING_MESSAGES.has(anyProcess)) {29 unmodified lines63 };64 65 // If the `message` event is currently debounced, the `disconnect` event must wait for it66 export const onDisconnect = async ({anyProcess, channel, isSubprocess, ipcEmitter, boundOnMessage}) => {67+ // Like `gracefulCancel` messages, only the disconnection from the parent process aborts `getCancelSignal()`.68+ // Otherwise, disconnecting from one of the current process' own subprocesses would abort it.69+ if (isSubprocess) {65- abortOnDisconnect();70+ abortOnDisconnect();71+ }72 73 const incomingMessages = INCOMING_MESSAGES.get(anyProcess);74 while (incomingMessages?.length > 0) {75 // eslint-disable-next-line no-await-in-loop10 unmodified linesmodified:lib/ipc/ipc-input.js+3 added-1 removed
9 unmodified lines10 if (!ipc) {11 throw new Error('The `ipcInput` option cannot be set unless the `ipc` option is `true`.');12 }13 14+ // An invalid `serialization` option is reported by `node:child_process` when spawning, like when `ipcInput` is not used14- validateIpcInput[serialization](ipcInput);15+ validateIpcInput[serialization]?.(ipcInput);16 };17 18 const validateAdvancedInput = ipcInput => {19 try {11 unmodified lines31 }32 };33 34 const validateIpcInput = {35+ __proto__: null,36 advanced: validateAdvancedInput,37 json: validateJsonInput,38 };39 13 unmodified linesmodified:lib/ipc/send.js+3 added-1 removed
2 unmodified lines3 validateIpcMethod,4 handleEpipeError,5 handleSerializationError,6 disconnect,7+ getIpcOptions,8 } from './validation.js';9 import {startSendMessage, endSendMessage} from './outgoing.js';10 import {handleSendStrict, waitForStrictResponse} from './strict.js';11 12 // Like `[sub]process.send()` but promise-based.13 // We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.14 // Users would still need to `await subprocess` after the method is done.15 // Also, this would prevent `unhandledRejection` event from being emitted, making it silent.15-export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, {strict = false} = {}) => {16+export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, options) => {17+ const {strict = false} = getIpcOptions(options);18 const methodName = 'sendMessage';19 validateIpcMethod({20 methodName,21 isSubprocess,72 unmodified linesmodified:lib/ipc/strict.js+1 added-1 removed
99 unmodified lines100 delete STRICT_RESPONSES[wrappedMessage.id];101 }102 };103 104-const STRICT_RESPONSES = {};104+const STRICT_RESPONSES = {__proto__: null};105 106 const throwOnDisconnect = async (anyProcess, isSubprocess, {signal}) => {107 incrementMaxListeners(anyProcess, 1, signal);108 await once(anyProcess, 'disconnect', {signal});5 unmodified linesmodified:lib/ipc/validation.js+11 added-1 removed
52 unmodified lines53 export const getAbortDisconnectError = () => new Error(`\`cancelSignal\` aborted: the ${getOtherProcessName(true)} disconnected.`);54 55 // When the subprocess uses `cancelSignal` but not the current process56 export const throwOnMissingParent = () => {57- throw new Error('`getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option.');57+ throw new Error('`getCancelSignal()` cannot be used without setting the `gracefulCancel` option to `true`.');58 };59 60 // EPIPE can happen when sending a message to a subprocess that is closing but has not disconnected yet61 export const handleEpipeError = ({error, methodName, isSubprocess}) => {46 unmodified lines108 if (anyProcess.connected) {109 anyProcess.disconnect();110 }111 };112+113+// The options are kept on a null-prototype object, otherwise a polluted `Object.prototype` would inject option values.114+// Like destructuring them, `null` throws.115+export const getIpcOptions = (options = {}) => {116+ if (options === null) {117+ throw new TypeError('The options must be an object, not `null`.');118+ }119+120+ return {__proto__: null, ...options};121+};modified:lib/methods/bind.js+1 added-1 removed
7 unmodified lines8 const mergedOptions = Object.fromEntries(Object.entries(options).map(([optionName, optionValue]) => [9 optionName,10 mergeOption(optionName, safeBoundOptions[optionName], optionValue),11 ]));12- return {...safeBoundOptions, ...mergedOptions};12+ return {__proto__: null, ...safeBoundOptions, ...mergedOptions};13 };14 15 const mergeOption = (optionName, boundOptionValue, optionValue) => {16 if (DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue)) {7 unmodified linesmodified:lib/methods/create.js+3 added-1 removed
48 unmodified lines49 ? parseTemplates(firstArgument, nextArguments)50 : [firstArgument, ...nextArguments];51 const [initialFile, initialArguments, initialOptions] = normalizeParameters(...callArguments);52 const mergedOptions = mergeOptions(mergeOptions(deepOptions, boundOptions), initialOptions);53+ // `mapArguments()` returns a plain object, so its result is read from a null-prototype copy.54+ // Otherwise a polluted `Object.prototype` would replace every option, or switch the execution mode.55 const {56 options = mergedOptions,57 isSync = false,56- } = mapArguments({options: mergedOptions});58+ } = {__proto__: null, ...mapArguments({options: mergedOptions})};59 return {60 file: initialFile,61 commandArguments: initialArguments,62 options,3 unmodified linesmodified:lib/methods/main-async.js+2 added-1 removed
72 unmodified lines73 };74 75 // Options normalization logic specific to async methods.76 // Prevent passing the `timeout` option directly to `child_process.spawn()`.77+// The returned object keeps a null prototype, otherwise a polluted `Object.prototype` would inject option values.78 const handleAsyncOptions = ({timeout, signal, ...options}) => {79 if (signal !== undefined) {80 throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');81 }82 82- return {...options, timeoutDuration: timeout};83+ return {__proto__: null, ...options, timeoutDuration: timeout};84 };85 86 const spawnSubprocessAsync = ({file, commandArguments, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors}) => {87 let subprocess;149 unmodified linesmodified:lib/methods/node.js+1 added-1 removed
6 unmodified lines7 if (options.node === false) {8 throw new TypeError('The "node" option cannot be false with `execaNode()`.');9 }10 11- return {options: {...options, node: true}};11+ return {options: {__proto__: null, ...options, node: true}};12 };13 14 // Applies the `node: true` option, and the related `nodePath`/`nodeOptions` options.15 // Modifies the file commands/arguments to ensure the same Node binary and flags are re-used.48 unmodified linesmodified:lib/methods/script.js+1 added-1 removed
9 unmodified lines10 // Main logic for `$.sync`11 const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});12 13 // `$` is like `execa` but with script-friendly options: `{stdin: 'inherit', preferLocal: true}`14-const getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});14+const getScriptOptions = options => ({options: {__proto__: null, ...getScriptStdinOption(options), ...options}});15 16 const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined17 ? {stdin: 'inherit'}18 : {};4 unmodified linesmodified:lib/methods/template.js+5 added-2 removed
122 unmodified lines123 if (typeOfExpression === 'number') {124 return String(expression);125 }126 127- if (isPlainObject(expression) && ('stdout' in expression || 'isMaxBuffer' in expression)) {127+ // Only own properties are checked: a polluted `Object.prototype.stdout` must not turn any plain object into a subprocess result128+ if (isPlainObject(expression) && (Object.hasOwn(expression, 'stdout') || Object.hasOwn(expression, 'isMaxBuffer'))) {129 return getSubprocessResult(expression);130 }131 132 if (expression instanceof ChildProcess || Object.prototype.toString.call(expression) === '[object Promise]') {3 unmodified lines136 137 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);138 };139 139-const getSubprocessResult = ({stdout}) => {140+const getSubprocessResult = result => {141+ // Read the own property only: results with `stdout: 'ignore'` have no `stdout` property, which must not be read from a polluted prototype142+ const stdout = Object.hasOwn(result, 'stdout') ? result.stdout : undefined;143 if (typeof stdout === 'string') {144 return stdout;145 }146 10 unmodified linesmodified:lib/pipe/pipe-arguments.js+11 added-5 removed
29 unmodified lines30 };31 32 const getDestinationStream = (boundOptions, createNested, pipeArguments) => {33 try {34- const {35- destination,36- pipeOptions: {from, to, unpipeSignal} = {},37- } = getDestination(boundOptions, createNested, ...pipeArguments);34+ const {destination, pipeOptions} = getDestination(boundOptions, createNested, ...pipeArguments);35+ // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values36+ const {from, to, unpipeSignal} = {__proto__: null, ...pipeOptions};37 const destinationStream = getToStream(destination, to);38 return {39 destination,40 destinationStream,36 unmodified lines77 throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);78 };79 80 // Force `stdin: 'pipe'` with the destination subprocess82-const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});81+const mapDestinationArguments = ({options}) => ({82+ options: {83+ __proto__: null,84+ ...options,85+ stdin: 'pipe',86+ piped: true,87+ },88+});89 90 const getSourceStream = (source, from) => {91 try {92 const sourceStream = getFromStream(source, from);5 unmodified linesmodified:lib/stdio/stdio-option.js+3 added-1 removed
3 unmodified lines4 import {isStdioValueObject} from './type.js';5 6 // Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`.7 // Also normalize the `stdio` option.8+// A rest pattern is not used to read the other options, since the object it creates inherits from `Object.prototype`, which a prototype pollution could then use to inject option values8-export const normalizeStdioOption = ({stdio, ipc, buffer, ...options}, verboseInfo, isSync) => {9+export const normalizeStdioOption = (options, verboseInfo, isSync) => {10+ const {stdio, ipc, buffer} = options;11 const stdioArray = getStdioArray(stdio, options).map((stdioOption, fdNumber) => addDefaultValue(stdioOption, fdNumber));12 validateIpcStdioOption(stdioArray);13 return isSync14 ? normalizeStdioSync(stdioArray, buffer, verboseInfo)83 unmodified linesmodified:test/arguments/encoding-option.js+9 added
35 unmodified lines36 test('cannot pass encoding: UCS2', testInvalidEncoding, 'UCS2', getCorrectEncodingMessage('utf16le'), execa);37 test('cannot pass encoding: ucs-2', testInvalidEncoding, 'ucs-2', getCorrectEncodingMessage('utf16le'), execa);38 test('cannot pass encoding: UCS-2', testInvalidEncoding, 'UCS-2', getCorrectEncodingMessage('utf16le'), execa);39 test('cannot pass encoding: binary', testInvalidEncoding, 'binary', getCorrectEncodingMessage('latin1'), execa);40+41+test('cannot pass encoding: constructor', testInvalidEncoding, 'constructor', UNKNOWN_ENCODING_MESSAGE, execa);42+test('cannot pass encoding: constructor, sync', testInvalidEncoding, 'constructor', UNKNOWN_ENCODING_MESSAGE, execaSync);43+test('cannot pass encoding: __proto__', testInvalidEncoding, '__proto__', UNKNOWN_ENCODING_MESSAGE, execa);44+test('cannot pass encoding: __proto__, sync', testInvalidEncoding, '__proto__', UNKNOWN_ENCODING_MESSAGE, execaSync);45+test('cannot pass encoding: CONSTRUCTOR', testInvalidEncoding, 'CONSTRUCTOR', UNKNOWN_ENCODING_MESSAGE, execa);46+test('cannot pass encoding: toString', testInvalidEncoding, 'toString', UNKNOWN_ENCODING_MESSAGE, execa);47+test('cannot pass encoding: valueOf', testInvalidEncoding, 'valueOf', UNKNOWN_ENCODING_MESSAGE, execa);48+test('cannot pass encoding: hasOwnProperty', testInvalidEncoding, 'hasOwnProperty', UNKNOWN_ENCODING_MESSAGE, execa);modified:test/arguments/env.js+10 added
36 unmodified lines37 test('do not use process.env with `extendEnv: false` and no `env`, sync', testNoEnvironment, execaSync, {});38 test('do not use process.env with `extendEnv: false` and `env: {}`', testNoEnvironment, execa, {env: {}});39 test('do not use process.env with `extendEnv: false`, no `env` and `preferLocal`', testNoEnvironment, execa, {preferLocal: true});40 41+// The `env` option is kept on a null-prototype object, so the properties it inherits are not passed to the subprocess42+const testInheritedEnv = async (t, execaMethod) => {43+ const env = Object.assign(Object.create({FOO: 'foo'}), {BAR: 'bar'});44+ const {stdout} = await execaMethod(process.execPath, [environmentFile], {env, extendEnv: false});45+ t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);46+};47+48+test('The "env" option does not pass inherited properties', testInheritedEnv, execa);49+test('The "env" option does not pass inherited properties, sync', testInheritedEnv, execaSync);50+51 test('use extend environment with `extendEnv: true` and `shell: true`', async t => {52 process.env.TEST = 'test';53 const command = isWindows ? 'echo %TEST%' : 'echo $TEST';54 const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});3 unmodified linesadded:test/arguments/prototype-pollution.js+195 added
1+import path from 'node:path';2+import process from 'node:process';3+import test from 'ava';4+import {pathExists} from 'path-exists';5+import tempfile from 'tempfile';6+import {7+ execa,8+ execaSync,9+ execaNode,10+ $,11+} from '../../index.js';12+import {setFixtureDirectory, PATH_KEY, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';13+import {foobarString} from '../helpers/input.js';14+15+setFixtureDirectory();16+process.env.FOO = 'foo';17+18+/*19+A polluted `Object.prototype` must not inject option values. Otherwise, any prototype pollution elsewhere in the process would let an attacker redirect the command, its input or its output.20+Options are therefore always kept on null-prototype objects.21+Those tests are serial since they temporarily modify `Object.prototype`.22+*/23+const pollutePrototype = (t, properties) => {24+ t.teardown(() => {25+ for (const property of Object.keys(properties)) {26+ delete Object.prototype[property];27+ }28+ });29+30+ Object.assign(Object.prototype, properties);31+};32+33+const printPath = ['-p', 'process.env.PATH ?? process.env.Path'];34+const POLLUTED_LOCAL_DIRECTORY = path.resolve('/pollutedLocalDirectory');35+const pollutedBinaryDirectory = path.join(POLLUTED_LOCAL_DIRECTORY, 'node_modules', '.bin');36+37+// The `preferLocal` and `localDir` options prepend a directory to `PATH`, which decides which file the command resolves to38+const testPollutedPreferLocal = async (t, execaMethod) => {39+ pollutePrototype(t, {preferLocal: true, localDir: POLLUTED_LOCAL_DIRECTORY});40+41+ const {stdout} = await execaMethod('node', printPath);42+ t.false(stdout.includes(pollutedBinaryDirectory));43+};44+45+test.serial('Polluted "preferLocal" and "localDir" are ignored', testPollutedPreferLocal, execa);46+test.serial('Polluted "preferLocal" and "localDir" are ignored, sync', testPollutedPreferLocal, execaSync);47+48+// `$` sets `preferLocal: true` itself, so only `localDir` can be injected49+test.serial('Polluted "localDir" is ignored, $', async t => {50+ pollutePrototype(t, {localDir: POLLUTED_LOCAL_DIRECTORY});51+52+ const {stdout} = await $('node', printPath);53+ t.false(stdout.includes(pollutedBinaryDirectory));54+});55+56+// The `stdout` option can redirect the output to an arbitrary file57+const testPollutedStdout = async (t, execaMethod) => {58+ const filePath = tempfile();59+ pollutePrototype(t, {stdout: {file: filePath}});60+61+ const {stdout} = await execaMethod('noop.js', [foobarString]);62+ t.is(stdout, foobarString);63+ t.false(await pathExists(filePath));64+};65+66+test.serial('Polluted "stdout" is ignored', testPollutedStdout, execa);67+test.serial('Polluted "stdout" is ignored, sync', testPollutedStdout, execaSync);68+69+// The `stdin` option can feed the contents of an arbitrary file to the subprocess70+test.serial('Polluted "stdin" is ignored', async t => {71+ pollutePrototype(t, {stdin: {file: 'noop.js'}});72+73+ const subprocess = execa('stdin.js');74+ subprocess.stdin.end(foobarString);75+ const {stdout} = await subprocess;76+ t.is(stdout, foobarString);77+});78+79+// The `verbose` option can be a function, which Execa calls with each log line80+const testPollutedVerbose = async (t, execaMethod) => {81+ let isVerboseCalled = false;82+ pollutePrototype(t, {83+ verbose() {84+ isVerboseCalled = true;85+ },86+ });87+88+ await execaMethod('noop.js', [foobarString]);89+ t.false(isVerboseCalled);90+};91+92+test.serial('Polluted "verbose" is ignored', testPollutedVerbose, execa);93+test.serial('Polluted "verbose" is ignored, sync', testPollutedVerbose, execaSync);94+test.serial('Polluted "verbose" is ignored, $', testPollutedVerbose, $);95+// `execaNode()` resolves the file from the current directory, not from `PATH`96+test.serial('Polluted "verbose" is ignored, execaNode()', testPollutedVerbose, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments));97+test.serial('Polluted "verbose" is ignored, .pipe()', testPollutedVerbose, (file, commandArguments) => execa('empty.js').pipe(file, commandArguments));98+99+test.serial('Polluted "extendEnv" is ignored', async t => {100+ pollutePrototype(t, {extendEnv: false});101+102+ const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}});103+ t.deepEqual(stdout.split('\n'), ['foo', 'bar']);104+});105+106+// `piped` is set by Execa itself, only when using `.pipe()`. It decides which icon the `verbose` option prints.107+const testPollutedPiped = async (t, execaMethod) => {108+ pollutePrototype(t, {piped: true});109+110+ const verboseObjects = [];111+ await execaMethod('noop.js', [foobarString], {112+ verbose(verboseLine, verboseObject) {113+ verboseObjects.push(verboseObject);114+ },115+ });116+ t.true(verboseObjects.length > 0);117+ t.true(verboseObjects.every(({piped}) => piped === false));118+};119+120+test.serial('Polluted "piped" is ignored', testPollutedPiped, execa);121+test.serial('Polluted "piped" is ignored, sync', testPollutedPiped, execaSync);122+123+/*124+`mapArguments()` returns `{options, isSync}`, which are method-specific. Neither is a user-facing option.125+A polluted `options` would replace every option at once, and a polluted `isSync` would switch the execution mode.126+*/127+const testPollutedMappedOptions = async (t, execaMethod) => {128+ pollutePrototype(t, {options: {cwd: path.resolve('/')}});129+130+ const {cwd} = await execaMethod('noop.js', [foobarString]);131+ t.is(cwd, process.cwd());132+};133+134+test.serial('Polluted "options" is ignored', testPollutedMappedOptions, execa);135+test.serial('Polluted "options" is ignored, sync', testPollutedMappedOptions, execaSync);136+137+const testPollutedIsSync = async (t, execaMethod) => {138+ pollutePrototype(t, {isSync: true});139+140+ const subprocess = execaMethod('noop.js', [foobarString]);141+ t.is(typeof subprocess.kill, 'function');142+ const {stdout} = await subprocess;143+ t.is(stdout, foobarString);144+};145+146+test.serial('Polluted "isSync" is ignored', testPollutedIsSync, execa);147+test.serial('Polluted "isSync" is ignored, $', testPollutedIsSync, $);148+test.serial('Polluted "isSync" is ignored, execaNode()', testPollutedIsSync, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments));149+150+test.serial('Polluted "cancelSignal" is ignored', async t => {151+ pollutePrototype(t, {cancelSignal: {}});152+153+ const {stdout} = await execa('noop.js', [foobarString]);154+ t.is(stdout, foobarString);155+});156+157+// Template expressions detect subprocess results with their `stdout`/`isMaxBuffer` properties. Using the `in` operator would let a polluted `Object.prototype.stdout` turn any plain object into an interpolated command argument.158+test.serial('Polluted "stdout" is not interpolated in template expressions', t => {159+ pollutePrototype(t, {stdout: foobarString});160+161+ t.throws(() => $`noop.js ${{}}`, {message: /Unexpected "object" in template expression/});162+});163+164+// A result with `stdout: 'ignore'` has no own `stdout` property, so it must not read the polluted one165+test.serial('Polluted "stdout" is not read from template expression results', t => {166+ pollutePrototype(t, {stdout: foobarString});167+168+ t.throws(() => $`noop.js ${$({stdio: 'ignore'}).sync`noop.js`}`, {message: /Missing result.stdout/});169+});170+171+/*172+Unlike the options, `child_process` intentionally passes the inherited properties of the `env` option to the subprocess.173+A polluted `PATH` decides which file the command resolves to, so the environment is kept on a null-prototype object too.174+*/175+const testPollutedEnvironment = async (t, execaMethod, options) => {176+ pollutePrototype(t, {POLLUTED_VARIABLE: 'polluted'});177+178+ const {stdout} = await execaMethod(process.execPath, ['-p', 'process.env.POLLUTED_VARIABLE'], options);179+ t.is(stdout, 'undefined');180+};181+182+test.serial('Polluted environment variables are ignored', testPollutedEnvironment, execa, {});183+test.serial('Polluted environment variables are ignored, sync', testPollutedEnvironment, execaSync, {});184+test.serial('Polluted environment variables are ignored, extendEnv false', testPollutedEnvironment, execa, {extendEnv: false});185+test.serial('Polluted environment variables are ignored, preferLocal', testPollutedEnvironment, execa, {preferLocal: true});186+187+const testPollutedPath = async (t, execaMethod) => {188+ pollutePrototype(t, {[PATH_KEY]: POLLUTED_LOCAL_DIRECTORY});189+190+ const {stdout} = await execaMethod(process.execPath, printPath, {extendEnv: false});191+ t.is(stdout, 'undefined');192+};193+194+test.serial('Polluted PATH is ignored', testPollutedPath, execa);195+test.serial('Polluted PATH is ignored, sync', testPollutedPath, execaSync);added:test/fixtures/graceful-nested.js+7 added
1+#!/usr/bin/env node2+import {execa, getCancelSignal, sendMessage} from 'execa';3+4+const cancelSignal = await getCancelSignal();5+// Neither the messages nor the disconnection of this process' own subprocess must abort its `cancelSignal`6+await execa('ipc-send-cancel-shape.js', {ipc: true});7+await sendMessage(cancelSignal.aborted);added:test/fixtures/graceful-none-twice.js+12 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {getCancelSignal} from 'execa';4+5+// Each call must throw the same error, including when the first one is caught and retried6+for (let index = 0; index < 2; index++) {7+ try {8+ await getCancelSignal();9+ } catch {10+ process.stdout.write('threw\n');11+ }12+}added:test/fixtures/ipc-send-cancel-shape.js+7 added
1+#!/usr/bin/env node2+import {sendMessage} from '../../index.js';3+import {foobarString} from '../helpers/input.js';4+5+// This has the same shape as the message Execa sends internally to apply `gracefulCancel`.6+// Since it is sent by the subprocess, it is a user message, not an Execa one.7+await sendMessage({type: 'execa:ipc:cancel', message: foobarString});added:test/fixtures/ipc-send-strict-proto.js+5 added
1+#!/usr/bin/env node2+import {sendMessage} from '../../index.js';3+4+// Malformed `strict` acknowledgment response, using an `Object.prototype` property as `id`5+await sendMessage({type: 'execa:ipc:response', id: 'constructor', message: true});modified:test/ipc/graceful.js+20 added-1 removed
142 unmodified lines143 t.false(isGracefullyCanceled);144 t.false(isTerminated);145 t.is(exitCode, 1);146 t.deepEqual(ipcOutput, []);147- t.true(stderr.includes('Error: `getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option.'));147+ t.true(stderr.includes('Error: `getCancelSignal()` cannot be used without setting the `gracefulCancel` option to `true`.'));148 });149 150+test('getCancelSignal() fails on every call if no IPC', async t => {151+ const {exitCode, stdout} = await execa('graceful-none-twice.js', {stripFinalNewline: false});152+ t.is(exitCode, 0);153+ t.is(stdout, 'threw\nthrew\n');154+});155+156 test.serial('getCancelSignal() hangs if cancelSignal without gracefulCancel', async t => {157 const controller = new AbortController();158 const {timedOut, isCanceled, isGracefullyCanceled, signal, ipcOutput} = await t.throwsAsync(execa('graceful-wait.js', {ipc: true, cancelSignal: controller.signal, timeout: 1e3}));159 t.true(timedOut);59 unmodified lines219 const {isCanceled, isGracefullyCanceled} = execaSync('empty.js');220 t.false(isCanceled);221 t.false(isGracefullyCanceled);222 });223+224+// Execa wraps `gracefulCancel` messages with an internal type, which is only ever sent by the current process to its subprocess.225+// A subprocess must not be able to send it in the other direction, since this would abort the parent process' own `cancelSignal`, or silently drop the message.226+test('Subprocess messages with the internal graceful cancellation shape are kept', async t => {227+ const {ipcOutput} = await execa('ipc-send-cancel-shape.js', {ipc: true});228+ t.deepEqual(ipcOutput, [{type: 'execa:ipc:cancel', message: foobarString}]);229+});230+231+test('Graceful cancelSignal is not aborted by the subprocess\' own subprocess', async t => {232+ const controller = new AbortController();233+ const {ipcOutput} = await execa('graceful-nested.js', {cancelSignal: controller.signal, gracefulCancel: true});234+ t.deepEqual(ipcOutput, [false]);235+});modified:test/ipc/ipc-input.js+12 added
39 unmodified lines40 t.is(message, 'The `ipcInput` option is not serializable with JSON.');41 t.is(cause.message, 'Do not know how to serialize a BigInt');42 });43 44+// An invalid `serialization` option must not crash the `ipcInput` validation, which is keyed by it.45+// `Object.prototype` properties are the trickiest values, since those are found on any object.46+const testInvalidSerialization = async (t, serialization) => {47+ const {code} = await t.throwsAsync(execa('empty.js', {ipcInput: foobarString, serialization}));48+ t.is(code, 'ERR_INVALID_ARG_VALUE');49+};50+51+test('Invalid "serialization" option with the "ipcInput" option', testInvalidSerialization, 'invalid');52+test('Invalid "serialization" option with the "ipcInput" option, __proto__', testInvalidSerialization, '__proto__');53+test('Invalid "serialization" option with the "ipcInput" option, toString', testInvalidSerialization, 'toString');54+test('Invalid "serialization" option with the "ipcInput" option, constructor', testInvalidSerialization, 'constructor');55+56 test('Handles "ipcInput" option during sending', async t => {57 const {message, cause} = await t.throwsAsync(execa('empty.js', {ipcInput: 0n}));58 t.true(message.includes('subprocess.sendMessage()\'s argument type is invalid: the message cannot be serialized: 0.'));59 t.true(cause.cause.message.includes('The "message" argument must be one of type string'));6 unmodified linesmodified:test/ipc/strict.js+5 added
225 unmodified lines226 t.false(isTerminated);227 t.true(stderr.includes('Error: sendMessage() failed: the parent process is sending a message too, instead of listening to incoming messages.'));228 t.deepEqual(ipcOutput, []);229 });230+231+test('Ignores "strict" responses with an Object.prototype property as id', async t => {232+ const {ipcOutput} = await execa('ipc-send-strict-proto.js', {ipc: true});233+ t.deepEqual(ipcOutput, []);234+});