Improve input validation (#838)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 672c2d7 · Browse files · 10 files·+88 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+88 added−13 removed
- tests:+48 added−0 removed
- other:+40 added−13 removed
Provenance
- Commit
8ee137c- Tree
8787ce9- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
672c2d7
10 files changed+88 added−13 removed
modified:lib/arguments/node.js+2 added-2 removed
1234456788910111234 unmodified linesimport {execPath, execArgv} from 'node:process';import {basename, resolve} from 'node:path';import {execa} from '../async.js';import {handleOptionalArguments} from './options.js';import {normalizeArguments} from './options.js';import {safeNormalizeFileUrl} from './cwd.js';
export function execaNode(file, args, options) { [args, options] = handleOptionalArguments(args, options); [file, args, options] = normalizeArguments(file, args, options);
if (options.node === false) { throw new TypeError('The "node" option cannot be false with `execaNode()`.'); }34 unmodified linesmodified:lib/arguments/options.js+18 added-5 removed
12345678910111212131415161314151617181920212223242526272829303132333470 unmodified linesimport {basename} from 'node:path';import process from 'node:process';import crossSpawn from 'cross-spawn';import {npmRunPathEnv} from 'npm-run-path';import isPlainObject from 'is-plain-obj';import {normalizeForceKillAfterDelay} from '../exit/kill.js';import {validateTimeout} from '../exit/timeout.js';import {handleNodeOption} from './node.js';import {logCommand, verboseDefault} from './verbose.js';import {joinCommand} from './escape.js';import {normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './cwd.js';
export const handleOptionalArguments = (args = [], options = {}) => Array.isArray(args) ? [args, options] : [[], args];
export const handleArguments = (rawFile, rawArgs, rawOptions) => {export const normalizeArguments = (rawFile, rawArgs = [], rawOptions = {}) => { const filePath = safeNormalizeFileUrl(rawFile, 'First argument'); const [args, options] = isPlainObject(rawArgs) ? [[], rawArgs] : [rawArgs, rawOptions];
if (!Array.isArray(args)) { throw new TypeError(`Second argument must be either an array of arguments or an options object: ${args}`); }
if (!isPlainObject(options)) { throw new TypeError(`Last argument must be an options object: ${options}`); }
return [filePath, args, options];};
export const handleArguments = (filePath, rawArgs, rawOptions) => { const {command, escapedCommand} = joinCommand(filePath, rawArgs);
rawOptions.cwd = normalizeCwd(rawOptions.cwd); const [processedFile, processedArgs, processedOptions] = handleNodeOption(filePath, rawArgs, rawOptions);70 unmodified linesmodified:lib/async.js+2 added-2 removed
1 import {setMaxListeners} from 'node:events';2 import childProcess from 'node:child_process';3-import {handleOptionalArguments, handleArguments} from './arguments/options.js';3+import {normalizeArguments, handleArguments} from './arguments/options.js';4 import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';5 import {handleOutput} from './return/output.js';6 import {handleInputAsync, pipeOutputAsync, cleanupStdioStreams} from './stdio/async.js';7 import {spawnedKill} from './exit/kill.js';36 unmodified lines44 return spawned;45 };46 47 const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {48- [rawArgs, rawOptions] = handleOptionalArguments(rawArgs, rawOptions);48+ [rawFile, rawArgs, rawOptions] = normalizeArguments(rawFile, rawArgs, rawOptions);49 const {file, args, command, escapedCommand, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);50 const options = handleAsyncOptions(normalizedOptions);51 return {file, args, command, escapedCommand, options};52 };42 unmodified linesmodified:lib/command.js+4 added
10 unmodified lines11121314151617181920212212 unmodified lines10 unmodified lines return execaSync(file, args, options);}
const parseCommand = command => { if (typeof command !== 'string') { throw new TypeError(`First argument must be a string: ${command}.`); }
const tokens = []; for (const token of command.trim().split(SPACES_REGEXP)) { // Allow spaces to be escaped by a backslash if not meant as a delimiter const previousToken = tokens.at(-1);12 unmodified linesmodified:lib/script.js+11 added-2 removed
1 import {ChildProcess} from 'node:child_process';2+import isPlainObject from 'is-plain-obj';3 import {isBinary, binaryToString} from './utils.js';4 import {execa} from './async.js';5 import {execaSync} from './sync.js';6 7 const create$ = options => {8 function $(templatesOrOptions, ...expressions) {8- if (!Array.isArray(templatesOrOptions)) {9+ if (isPlainObject(templatesOrOptions)) {10 return create$({...options, ...templatesOrOptions});11 }12 13+ if (!Array.isArray(templatesOrOptions)) {14+ throw new TypeError('Please use either $(option) or $`command`.');15+ }16+17 const [file, ...args] = parseTemplates(templatesOrOptions, expressions);18 return execa(file, args, normalizeScriptOptions(options));19 }20 21 $.sync = (templates, ...expressions) => {17- if (!Array.isArray(templates)) {22+ if (isPlainObject(templates)) {23 throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.');24 }25 26+ if (!Array.isArray(templates)) {27+ throw new TypeError('A template string must be used: $.sync`command`.');28+ }29+30 const [file, ...args] = parseTemplates(templates, expressions);31 return execaSync(file, args, normalizeScriptOptions(options));32 };33 93 unmodified linesmodified:lib/sync.js+2 added-2 removed
1 import childProcess from 'node:child_process';2-import {handleOptionalArguments, handleArguments} from './arguments/options.js';2+import {normalizeArguments, handleArguments} from './arguments/options.js';3 import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';4 import {handleOutput} from './return/output.js';5 import {handleInputSync, pipeOutputSync} from './stdio/sync.js';6 import {isFailedExit} from './exit/code.js';43 unmodified lines50 return makeSuccessResult({command, escapedCommand, stdio, options});51 };52 53 const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {54- [rawArgs, rawOptions] = handleOptionalArguments(rawArgs, rawOptions);54+ [rawFile, rawArgs, rawOptions] = normalizeArguments(rawFile, rawArgs, rawOptions);55 const syncOptions = normalizeSyncOptions(rawOptions);56 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, syncOptions);57 validateSyncOptions(options);58 return {file, args, command, escapedCommand, options};9 unmodified linesmodified:test/arguments/options.js+20 added
121 unmodified lines122 test('execa()\'s command argument must be a string or file URL', testInvalidCommand, execa);123 test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, execaSync);124 test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, execaNode);125 126+const testInvalidArgs = async (t, execaMethod) => {127+ t.throws(() => {128+ execaMethod('echo', true);129+ }, {message: /Second argument must be either/});130+};131+132+test('execa()\'s second argument must be an array', testInvalidArgs, execa);133+test('execaSync()\'s second argument must be an array', testInvalidArgs, execaSync);134+test('execaNode()\'s second argument must be an array', testInvalidArgs, execaNode);135+136+const testInvalidOptions = async (t, execaMethod) => {137+ t.throws(() => {138+ execaMethod('echo', [], new Map());139+ }, {message: /Last argument must be an options object/});140+};141+142+test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);143+test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);144+test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);145+146 test('use relative path with \'..\' chars', async t => {147 const pathViaParentDir = join('..', basename(fileURLToPath(new URL('../..', import.meta.url))), 'test', 'fixtures', 'noop.js');148 const {stdout} = await execa(pathViaParentDir, ['foo']);149 t.is(stdout, 'foo');1 unmodified linemodified:test/command.js+20 added
36 unmodified lines37 test('execaCommandSync()', t => {38 const {stdout} = execaCommandSync('echo.js foo bar');39 t.is(stdout, 'foo\nbar');40 });41+42+const testInvalidCommand = (t, execaCommand, invalidArgument) => {43+ t.throws(() => {44+ execaCommand(invalidArgument);45+ }, {message: /First argument must be a string/});46+};47+48+test('execaCommand() must use a string', testInvalidCommand, execaCommand, true);49+test('execaCommandSync() must use a string', testInvalidCommand, execaCommandSync, true);50+test('execaCommand() must have an argument', testInvalidCommand, execaCommand, undefined);51+test('execaCommandSync() must have an argument', testInvalidCommand, execaCommandSync, undefined);52+53+const testInvalidArgs = (t, execaCommand) => {54+ t.throws(() => {55+ execaCommand('echo', ['']);56+ }, {message: /Last argument must be an options object/});57+};58+59+test('execaCommand() must not pass an array of arguments', testInvalidArgs, execaCommand);60+test('execaCommandSync() must not pass an array of arguments', testInvalidArgs, execaCommandSync);modified:test/script.js+8 added
148 unmodified lines149 const {stdout} = await $` echo.js foo bar `;150 t.is(stdout, 'foo\nbar');151 });152 153+test('$ must only use options or templates', t => {154+ t.throws(() => $(true)`noop.js`, {message: /Please use either/});155+});156+157 test('$.sync', t => {158 const {stdout} = $.sync`echo.js foo bar`;159 t.is(stdout, 'foo\nbar');160 });35 unmodified lines196 const {stdout} = $.sync`echo.js ${[foo, 'bar']}`;197 t.is(stdout, 'foo\nbar');198 });199 200+test('$.sync must only templates', t => {201+ t.throws(() => $.sync(true)`noop.js`, {message: /A template string must be used/});202+});203+204 const invalidExpression = test.macro({205 async exec(t, input, expected) {206 await t.throwsAsync(207 async () => $`echo.js ${input}`,59 unmodified linesmodified:package.json+1 added
47 unmodified lines48 "@sindresorhus/merge-streams": "^3.0.0",49 "cross-spawn": "^7.0.3",50 "get-stream": "^8.0.1",51 "human-signals": "^6.0.0",52+ "is-plain-obj": "^4.1.0",53 "is-stream": "^4.0.1",54 "npm-run-path": "^5.2.0",55 "signal-exit": "^4.1.0",56 "strip-final-newline": "^4.0.0"37 unmodified lines