Skip to content
Myr

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

34 files+375 added−37 removed

modified:lib/arguments/command.js+2 added-1 removed
modified:lib/arguments/encoding-option.js+1 added
modified:lib/arguments/options.js+9 added-2 removed
modified:lib/arguments/specific.js+2 added-1 removed
4 unmodified lines
5// 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']}`8export 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};1112 for (const optionName of FD_SPECIFIC_OPTIONS) {13 optionsCopy[optionName] = normalizeFdSpecificOption(options, optionName);14 }
99 unmodified lines
modified:lib/convert/duplex.js+3 added-1 removed
14 unmodified lines
15 onWritableDestroy,16} from './writable.js';1718// Create a `Duplex` stream combining both `subprocess.readable()` and `subprocess.writable()`19export const createDuplex = ({subprocess, concurrentStreams, encoding}, {from, to, binary: binaryOption = true, preserveNewlines = true} = {}) => {19export 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 lines
modified:lib/convert/iterable.js+3 added-5 removed
1 unmodified line
2import {getFromStream} from '../arguments/fd-options.js';3import {iterateOnSubprocessStream} from '../io/iterate.js';45// Convert the subprocess to an async iterable6export const createIterable = (subprocess, encoding, {7 from,8 binary: binaryOption = false,9 preserveNewlines = false,10} = {}) => {6export 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 lines
modified:lib/convert/readable.js+3 added-1 removed
11 unmodified lines
12 destroyOtherStream,13} from './shared.js';1415// Create a `Readable` stream that forwards from `stdout` and awaits the subprocess16export const createReadable = ({subprocess, concurrentStreams, encoding}, {from, binary: binaryOption = true, preserveNewlines = true} = {}) => {16export 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 lines
modified:lib/convert/writable.js+3 added-1 removed
9 unmodified lines
10 destroyOtherStream,11} from './shared.js';1213// Create a `Writable` stream that forwards to `stdin` and awaits the subprocess14export const createWritable = ({subprocess, concurrentStreams}, {to} = {}) => {14export 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 lines
modified:lib/ipc/get-each.js+8 added-2 removed
1import {once, on} from 'node:events';2import {validateIpcMethod, disconnect, getStrictResponseError} from './validation.js';2import {3 validateIpcMethod,4 disconnect,5 getStrictResponseError,6 getIpcOptions,7} from './validation.js';8import {getIpcEmitter, isConnected} from './forward.js';9import {addReference, removeReference} from './reference.js';1011export const internalGetEachMessageOptions = Symbol('internalGetEachMessageOptions');1213// Like `[sub]process.on('message')` but promise-based9export const getEachMessage = (subprocessInfo, options = {}) => {14export 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 lines
modified:lib/ipc/get-one.js+3 added-1 removed
2 unmodified lines
3 validateIpcMethod,4 throwOnEarlyDisconnect,5 disconnect,6 getStrictResponseError,7 getIpcOptions,8} from './validation.js';9import {getIpcEmitter, isConnected} from './forward.js';10import {addReference, removeReference} from './reference.js';1112export const internalGetOneMessageOptions = Symbol('internalGetOneMessageOptions');1314// Like `[sub]process.once('message')` but promise-based14export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, options = {}) => {15export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, rawOptions) => {16 const options = getIpcOptions(rawOptions);17 const {reference = true, filter} = options;18 const {signal} = options[internalGetOneMessageOptions] ?? {};1920 validateIpcMethod({
74 unmodified lines
modified:lib/ipc/graceful.js+3 added-2 removed
31 unmodified lines
32 if (isCancelListening) {33 return;34 }3536 isCancelListening = true;3736 // 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 }4142 isCancelListening = true;4344 if (channel === null) {45 abortOnDisconnect();46 return;47 }
26 unmodified lines
modified:lib/ipc/incoming.js+8 added-2 removed
22 unmodified lines
23// 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.26export 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 }3233 if (!INCOMING_MESSAGES.has(anyProcess)) {
29 unmodified lines
63};6465// If the `message` event is currently debounced, the `disconnect` event must wait for it66export 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 }7273 const incomingMessages = INCOMING_MESSAGES.get(anyProcess);74 while (incomingMessages?.length > 0) {75 // eslint-disable-next-line no-await-in-loop
10 unmodified lines
modified:lib/ipc/ipc-input.js+3 added-1 removed
9 unmodified lines
10 if (!ipc) {11 throw new Error('The `ipcInput` option cannot be set unless the `ipc` option is `true`.');12 }1314 // 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};1718const validateAdvancedInput = ipcInput => {19 try {
11 unmodified lines
31 }32};3334const validateIpcInput = {35 __proto__: null,36 advanced: validateAdvancedInput,37 json: validateJsonInput,38};39
13 unmodified lines
modified:lib/ipc/send.js+3 added-1 removed
2 unmodified lines
3 validateIpcMethod,4 handleEpipeError,5 handleSerializationError,6 disconnect,7 getIpcOptions,8} from './validation.js';9import {startSendMessage, endSendMessage} from './outgoing.js';10import {handleSendStrict, waitForStrictResponse} from './strict.js';1112// 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.15export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, {strict = false} = {}) => {16export 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 lines
modified:lib/ipc/strict.js+1 added-1 removed
99 unmodified lines
100 delete STRICT_RESPONSES[wrappedMessage.id];101 }102};103104const STRICT_RESPONSES = {};104const STRICT_RESPONSES = {__proto__: null};105106const throwOnDisconnect = async (anyProcess, isSubprocess, {signal}) => {107 incrementMaxListeners(anyProcess, 1, signal);108 await once(anyProcess, 'disconnect', {signal});
5 unmodified lines
modified:lib/ipc/validation.js+11 added-1 removed
52 unmodified lines
53export const getAbortDisconnectError = () => new Error(`\`cancelSignal\` aborted: the ${getOtherProcessName(true)} disconnected.`);5455// When the subprocess uses `cancelSignal` but not the current process56export 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};5960// EPIPE can happen when sending a message to a subprocess that is closing but has not disconnected yet61export const handleEpipeError = ({error, methodName, isSubprocess}) => {
46 unmodified lines
108 if (anyProcess.connected) {109 anyProcess.disconnect();110 }111};112113// The options are kept on a null-prototype object, otherwise a polluted `Object.prototype` would inject option values.114// Like destructuring them, `null` throws.115export const getIpcOptions = (options = {}) => {116 if (options === null) {117 throw new TypeError('The options must be an object, not `null`.');118 }119120 return {__proto__: null, ...options};121};
modified:lib/methods/bind.js+1 added-1 removed
7 unmodified lines
8 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};1415const mergeOption = (optionName, boundOptionValue, optionValue) => {16 if (DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue)) {
7 unmodified lines
modified:lib/methods/create.js+3 added-1 removed
48 unmodified lines
49 ? 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 lines
modified:lib/methods/main-async.js+2 added-1 removed
72 unmodified lines
73};7475// 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.78const handleAsyncOptions = ({timeout, signal, ...options}) => {79 if (signal !== undefined) {80 throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');81 }8282 return {...options, timeoutDuration: timeout};83 return {__proto__: null, ...options, timeoutDuration: timeout};84};8586const spawnSubprocessAsync = ({file, commandArguments, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors}) => {87 let subprocess;
149 unmodified lines
modified:lib/methods/node.js+1 added-1 removed
6 unmodified lines
7 if (options.node === false) {8 throw new TypeError('The "node" option cannot be false with `execaNode()`.');9 }1011 return {options: {...options, node: true}};11 return {options: {__proto__: null, ...options, node: true}};12};1314// 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 lines
modified:lib/methods/script.js+1 added-1 removed
9 unmodified lines
10// Main logic for `$.sync`11const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});1213// `$` is like `execa` but with script-friendly options: `{stdin: 'inherit', preferLocal: true}`14const getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});14const getScriptOptions = options => ({options: {__proto__: null, ...getScriptStdinOption(options), ...options}});1516const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined17 ? {stdin: 'inherit'}18 : {};
4 unmodified lines
modified:lib/methods/template.js+5 added-2 removed
122 unmodified lines
123 if (typeOfExpression === 'number') {124 return String(expression);125 }126127 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 }131132 if (expression instanceof ChildProcess || Object.prototype.toString.call(expression) === '[object Promise]') {
3 unmodified lines
136137 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);138};139139const getSubprocessResult = ({stdout}) => {140const 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 lines
modified:lib/pipe/pipe-arguments.js+11 added-5 removed
29 unmodified lines
30};3132const 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 lines
77 throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);78};7980// Force `stdin: 'pipe'` with the destination subprocess82const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});81const mapDestinationArguments = ({options}) => ({82 options: {83 __proto__: null,84 ...options,85 stdin: 'pipe',86 piped: true,87 },88});8990const getSourceStream = (source, from) => {91 try {92 const sourceStream = getFromStream(source, from);
5 unmodified lines
modified:lib/stdio/stdio-option.js+3 added-1 removed
3 unmodified lines
4import {isStdioValueObject} from './type.js';56// 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 values8export const normalizeStdioOption = ({stdio, ipc, buffer, ...options}, verboseInfo, isSync) => {9export 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 lines
modified:test/arguments/encoding-option.js+9 added
35 unmodified lines
36test('cannot pass encoding: UCS2', testInvalidEncoding, 'UCS2', getCorrectEncodingMessage('utf16le'), execa);37test('cannot pass encoding: ucs-2', testInvalidEncoding, 'ucs-2', getCorrectEncodingMessage('utf16le'), execa);38test('cannot pass encoding: UCS-2', testInvalidEncoding, 'UCS-2', getCorrectEncodingMessage('utf16le'), execa);39test('cannot pass encoding: binary', testInvalidEncoding, 'binary', getCorrectEncodingMessage('latin1'), execa);4041test('cannot pass encoding: constructor', testInvalidEncoding, 'constructor', UNKNOWN_ENCODING_MESSAGE, execa);42test('cannot pass encoding: constructor, sync', testInvalidEncoding, 'constructor', UNKNOWN_ENCODING_MESSAGE, execaSync);43test('cannot pass encoding: __proto__', testInvalidEncoding, '__proto__', UNKNOWN_ENCODING_MESSAGE, execa);44test('cannot pass encoding: __proto__, sync', testInvalidEncoding, '__proto__', UNKNOWN_ENCODING_MESSAGE, execaSync);45test('cannot pass encoding: CONSTRUCTOR', testInvalidEncoding, 'CONSTRUCTOR', UNKNOWN_ENCODING_MESSAGE, execa);46test('cannot pass encoding: toString', testInvalidEncoding, 'toString', UNKNOWN_ENCODING_MESSAGE, execa);47test('cannot pass encoding: valueOf', testInvalidEncoding, 'valueOf', UNKNOWN_ENCODING_MESSAGE, execa);48test('cannot pass encoding: hasOwnProperty', testInvalidEncoding, 'hasOwnProperty', UNKNOWN_ENCODING_MESSAGE, execa);
modified:test/arguments/env.js+10 added
36 unmodified lines
37test('do not use process.env with `extendEnv: false` and no `env`, sync', testNoEnvironment, execaSync, {});38test('do not use process.env with `extendEnv: false` and `env: {}`', testNoEnvironment, execa, {env: {}});39test('do not use process.env with `extendEnv: false`, no `env` and `preferLocal`', testNoEnvironment, execa, {preferLocal: true});4041// The `env` option is kept on a null-prototype object, so the properties it inherits are not passed to the subprocess42const 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};4748test('The "env" option does not pass inherited properties', testInheritedEnv, execa);49test('The "env" option does not pass inherited properties, sync', testInheritedEnv, execaSync);5051test('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 lines
added:test/arguments/prototype-pollution.js+195 added
1import path from 'node:path';2import process from 'node:process';3import test from 'ava';4import {pathExists} from 'path-exists';5import tempfile from 'tempfile';6import {7 execa,8 execaSync,9 execaNode,10 $,11} from '../../index.js';12import {setFixtureDirectory, PATH_KEY, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';13import {foobarString} from '../helpers/input.js';1415setFixtureDirectory();16process.env.FOO = 'foo';1718/*19A 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.20Options are therefore always kept on null-prototype objects.21Those tests are serial since they temporarily modify `Object.prototype`.22*/23const pollutePrototype = (t, properties) => {24 t.teardown(() => {25 for (const property of Object.keys(properties)) {26 delete Object.prototype[property];27 }28 });2930 Object.assign(Object.prototype, properties);31};3233const printPath = ['-p', 'process.env.PATH ?? process.env.Path'];34const POLLUTED_LOCAL_DIRECTORY = path.resolve('/pollutedLocalDirectory');35const pollutedBinaryDirectory = path.join(POLLUTED_LOCAL_DIRECTORY, 'node_modules', '.bin');3637// The `preferLocal` and `localDir` options prepend a directory to `PATH`, which decides which file the command resolves to38const testPollutedPreferLocal = async (t, execaMethod) => {39 pollutePrototype(t, {preferLocal: true, localDir: POLLUTED_LOCAL_DIRECTORY});4041 const {stdout} = await execaMethod('node', printPath);42 t.false(stdout.includes(pollutedBinaryDirectory));43};4445test.serial('Polluted "preferLocal" and "localDir" are ignored', testPollutedPreferLocal, execa);46test.serial('Polluted "preferLocal" and "localDir" are ignored, sync', testPollutedPreferLocal, execaSync);4748// `$` sets `preferLocal: true` itself, so only `localDir` can be injected49test.serial('Polluted "localDir" is ignored, $', async t => {50 pollutePrototype(t, {localDir: POLLUTED_LOCAL_DIRECTORY});5152 const {stdout} = await $('node', printPath);53 t.false(stdout.includes(pollutedBinaryDirectory));54});5556// The `stdout` option can redirect the output to an arbitrary file57const testPollutedStdout = async (t, execaMethod) => {58 const filePath = tempfile();59 pollutePrototype(t, {stdout: {file: filePath}});6061 const {stdout} = await execaMethod('noop.js', [foobarString]);62 t.is(stdout, foobarString);63 t.false(await pathExists(filePath));64};6566test.serial('Polluted "stdout" is ignored', testPollutedStdout, execa);67test.serial('Polluted "stdout" is ignored, sync', testPollutedStdout, execaSync);6869// The `stdin` option can feed the contents of an arbitrary file to the subprocess70test.serial('Polluted "stdin" is ignored', async t => {71 pollutePrototype(t, {stdin: {file: 'noop.js'}});7273 const subprocess = execa('stdin.js');74 subprocess.stdin.end(foobarString);75 const {stdout} = await subprocess;76 t.is(stdout, foobarString);77});7879// The `verbose` option can be a function, which Execa calls with each log line80const testPollutedVerbose = async (t, execaMethod) => {81 let isVerboseCalled = false;82 pollutePrototype(t, {83 verbose() {84 isVerboseCalled = true;85 },86 });8788 await execaMethod('noop.js', [foobarString]);89 t.false(isVerboseCalled);90};9192test.serial('Polluted "verbose" is ignored', testPollutedVerbose, execa);93test.serial('Polluted "verbose" is ignored, sync', testPollutedVerbose, execaSync);94test.serial('Polluted "verbose" is ignored, $', testPollutedVerbose, $);95// `execaNode()` resolves the file from the current directory, not from `PATH`96test.serial('Polluted "verbose" is ignored, execaNode()', testPollutedVerbose, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments));97test.serial('Polluted "verbose" is ignored, .pipe()', testPollutedVerbose, (file, commandArguments) => execa('empty.js').pipe(file, commandArguments));9899test.serial('Polluted "extendEnv" is ignored', async t => {100 pollutePrototype(t, {extendEnv: false});101102 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}});103 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);104});105106// `piped` is set by Execa itself, only when using `.pipe()`. It decides which icon the `verbose` option prints.107const testPollutedPiped = async (t, execaMethod) => {108 pollutePrototype(t, {piped: true});109110 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};119120test.serial('Polluted "piped" is ignored', testPollutedPiped, execa);121test.serial('Polluted "piped" is ignored, sync', testPollutedPiped, execaSync);122123/*124`mapArguments()` returns `{options, isSync}`, which are method-specific. Neither is a user-facing option.125A polluted `options` would replace every option at once, and a polluted `isSync` would switch the execution mode.126*/127const testPollutedMappedOptions = async (t, execaMethod) => {128 pollutePrototype(t, {options: {cwd: path.resolve('/')}});129130 const {cwd} = await execaMethod('noop.js', [foobarString]);131 t.is(cwd, process.cwd());132};133134test.serial('Polluted "options" is ignored', testPollutedMappedOptions, execa);135test.serial('Polluted "options" is ignored, sync', testPollutedMappedOptions, execaSync);136137const testPollutedIsSync = async (t, execaMethod) => {138 pollutePrototype(t, {isSync: true});139140 const subprocess = execaMethod('noop.js', [foobarString]);141 t.is(typeof subprocess.kill, 'function');142 const {stdout} = await subprocess;143 t.is(stdout, foobarString);144};145146test.serial('Polluted "isSync" is ignored', testPollutedIsSync, execa);147test.serial('Polluted "isSync" is ignored, $', testPollutedIsSync, $);148test.serial('Polluted "isSync" is ignored, execaNode()', testPollutedIsSync, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments));149150test.serial('Polluted "cancelSignal" is ignored', async t => {151 pollutePrototype(t, {cancelSignal: {}});152153 const {stdout} = await execa('noop.js', [foobarString]);154 t.is(stdout, foobarString);155});156157// 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.158test.serial('Polluted "stdout" is not interpolated in template expressions', t => {159 pollutePrototype(t, {stdout: foobarString});160161 t.throws(() => $`noop.js ${{}}`, {message: /Unexpected "object" in template expression/});162});163164// A result with `stdout: 'ignore'` has no own `stdout` property, so it must not read the polluted one165test.serial('Polluted "stdout" is not read from template expression results', t => {166 pollutePrototype(t, {stdout: foobarString});167168 t.throws(() => $`noop.js ${$({stdio: 'ignore'}).sync`noop.js`}`, {message: /Missing result.stdout/});169});170171/*172Unlike the options, `child_process` intentionally passes the inherited properties of the `env` option to the subprocess.173A polluted `PATH` decides which file the command resolves to, so the environment is kept on a null-prototype object too.174*/175const testPollutedEnvironment = async (t, execaMethod, options) => {176 pollutePrototype(t, {POLLUTED_VARIABLE: 'polluted'});177178 const {stdout} = await execaMethod(process.execPath, ['-p', 'process.env.POLLUTED_VARIABLE'], options);179 t.is(stdout, 'undefined');180};181182test.serial('Polluted environment variables are ignored', testPollutedEnvironment, execa, {});183test.serial('Polluted environment variables are ignored, sync', testPollutedEnvironment, execaSync, {});184test.serial('Polluted environment variables are ignored, extendEnv false', testPollutedEnvironment, execa, {extendEnv: false});185test.serial('Polluted environment variables are ignored, preferLocal', testPollutedEnvironment, execa, {preferLocal: true});186187const testPollutedPath = async (t, execaMethod) => {188 pollutePrototype(t, {[PATH_KEY]: POLLUTED_LOCAL_DIRECTORY});189190 const {stdout} = await execaMethod(process.execPath, printPath, {extendEnv: false});191 t.is(stdout, 'undefined');192};193194test.serial('Polluted PATH is ignored', testPollutedPath, execa);195test.serial('Polluted PATH is ignored, sync', testPollutedPath, execaSync);
added:test/fixtures/graceful-nested.js+7 added
1#!/usr/bin/env node2import {execa, getCancelSignal, sendMessage} from 'execa';34const cancelSignal = await getCancelSignal();5// Neither the messages nor the disconnection of this process' own subprocess must abort its `cancelSignal`6await execa('ipc-send-cancel-shape.js', {ipc: true});7await sendMessage(cancelSignal.aborted);
added:test/fixtures/graceful-none-twice.js+12 added
1#!/usr/bin/env node2import process from 'node:process';3import {getCancelSignal} from 'execa';45// Each call must throw the same error, including when the first one is caught and retried6for (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 node2import {sendMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45// 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.7await sendMessage({type: 'execa:ipc:cancel', message: foobarString});
added:test/fixtures/ipc-send-strict-proto.js+5 added
1#!/usr/bin/env node2import {sendMessage} from '../../index.js';34// Malformed `strict` acknowledgment response, using an `Object.prototype` property as `id`5await sendMessage({type: 'execa:ipc:response', id: 'constructor', message: true});
modified:test/ipc/graceful.js+20 added-1 removed
142 unmodified lines
143 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});149150test('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});155156test.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 lines
219 const {isCanceled, isGracefullyCanceled} = execaSync('empty.js');220 t.false(isCanceled);221 t.false(isGracefullyCanceled);222});223224// 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.226test('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});230231test('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 lines
40 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});4344// 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.46const 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};5051test('Invalid "serialization" option with the "ipcInput" option', testInvalidSerialization, 'invalid');52test('Invalid "serialization" option with the "ipcInput" option, __proto__', testInvalidSerialization, '__proto__');53test('Invalid "serialization" option with the "ipcInput" option, toString', testInvalidSerialization, 'toString');54test('Invalid "serialization" option with the "ipcInput" option, constructor', testInvalidSerialization, 'constructor');5556test('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 lines
modified:test/ipc/strict.js+5 added
225 unmodified lines
226 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});230231test('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});