command-resolution.js
This file
Path
test/arguments/command-resolution.js
318 lines · 16.4 KiB · JavaScript
Last changed by
Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
History of this fileTake it
Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
lines 1–318why, one step back1import {cp, mkdir} from 'node:fs/promises';2import path from 'node:path';3import process from 'node:process';4import test from 'ava';5import {execa, execaSync} from '../../index.js';6import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';78setFixtureDirectory();910const isWindows = process.platform === 'win32';1112// These tests cover the command resolution and argument escaping performed by13// `lib/arguments/command-file.js`, which allows running scripts, `.cmd`/`.bat` files14// and shebang scripts without a shell, and prevents command injection on Windows.15// Most assertions use a roundtrip: an argument is passed in, the subprocess prints16// its own `process.argv` back (see `test/fixtures/echo.js`), and we check it comes17// back byte-identical. This exercises the escaping logic on whichever OS runs the18// test, so Windows escaping is genuinely validated on CI.1920// `echo.js` prints `process.argv.slice(2).join('\n')`21const testRoundtrip = async (t, commandArguments) => {22 const expectedStdout = commandArguments.map(String).join('\n');2324 const {stdout} = await execa('echo.js', commandArguments);25 t.is(stdout, expectedStdout);2627 const {stdout: stdoutSync} = execaSync('echo.js', commandArguments);28 t.is(stdoutSync, expectedStdout);29};3031test('Empty arguments and arguments with spaces', testRoundtrip, ['foo', '', 'bar', 'André Cruz']);32test('Non-string arguments are coerced', testRoundtrip, [1234]);33test('Arguments with shell special characters', testRoundtrip, [34 'foo',35 '()',36 'foo',37 '[]',38 'foo',39 '%!',40 'foo',41 '^<',42 'foo',43 '>&',44 'foo',45 '|;',46 'foo',47 ', ',48 'foo',49 '!=',50 'foo',51 '\\*',52 'foo',53 '"f"',54 'foo',55 '?.',56 'foo',57 '=`',58 'foo',59 '\'',60 'foo',61 '\\"',62 'bar\\',63 '"foo|bar>baz"',64 '"(foo|bar>baz|foz)"',65]);66// Backslashes and double quotes need specific escaping on Windows, so their combinations are the trickiest.67test('Arguments with backslashes', testRoundtrip, ['a\\b', 'a\\\\b', '\\', '\\\\', 'a\\', 'trailing\\']);68test('Arguments with backslashes and double quotes', testRoundtrip, ['a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']);69// Backslashes, double quotes and shell metacharacters combined in a single argument are the trickiest to escape on Windows.70test('Arguments combining backslashes, quotes and metacharacters', testRoundtrip, ['a\\"&b', '\\"()\\', 'c\\\\"|d', '%x%\\', '">&<"']);71test('Arguments with tabs and whitespace', testRoundtrip, ['a\tb', '\t', ' spaces ', ' ']);72// Several consecutive empty and whitespace-only arguments must each be preserved as a distinct argument.73test('Arguments that are empty or whitespace-only', testRoundtrip, ['', '', 'a', '', ' ', '\t', '']);74test('Arguments that look like flags', testRoundtrip, ['-e', '--foo=bar', '--', '-']);75test('Arguments with Unicode characters', testRoundtrip, ['café', '🎉', '日本語', 'naïve']);76// eslint-disable-next-line no-template-curly-in-string77test('Arguments with shell variable syntax', testRoundtrip, ['$HOME', '${x}', '~', 'a=b,c', '`whoami`']);78// Very long arguments must not be truncated nor corrupted by the escaping.79test('Very long arguments', testRoundtrip, ['a'.repeat(10_000), `${'b'.repeat(1000)}\\"${'c'.repeat(1000)}`]);80// A long run of consecutive backslashes right before a double quote (or the end of the81// argument) must be doubled as a whole. This is both the input a length-dependent escaping82// bug corrupts and the one a naive regex backtracks quadratically over, so a correct83// roundtrip here guards correctness and the single-pass linear escaping at once.84test('Arguments with long runs of backslashes before quotes', testRoundtrip, [85 `${'\\'.repeat(1000)}"`,86 '\\'.repeat(1000),87 `a${'\\'.repeat(500)}"b${'\\'.repeat(500)}`,88]);89// Runs of backslashes of every length from 1 to 6, each right before a double quote, then90// each at the very end of the argument. The bug this guards against doubled only the last91// backslash of a run instead of the whole run, so it corrupted every length above 1.92// Passing each length as its own argument pins down exactly which lengths would break.93const backslashRunArguments = [94 ...Array.from({length: 6}, (_, index) => `${'\\'.repeat(index + 1)}"x`),95 ...Array.from({length: 6}, (_, index) => `end${'\\'.repeat(index + 1)}`),96];97test('Arguments with backslash runs of every length', testRoundtrip, backslashRunArguments);98// Consecutive double quotes must each be escaped independently, not collapsed nor paired.99test('Arguments with consecutive double quotes', testRoundtrip, ['""', '"""', 'a""b', '""""']);100// A line break can be passed as an argument to a directly executable file (unlike a `.cmd`101// on Windows, see below). `echo-argv.js` prints its arguments as JSON, so this verifies the102// line break stays within a single argument rather than splitting it in two.103test('Line breaks are kept within a single argument for executables', async t => {104 const commandArguments = ['a\nb', 'a\r\nb', 'c'];105 const {stdout} = await execa('echo-argv.js', commandArguments);106 t.deepEqual(JSON.parse(stdout), commandArguments);107108 const {stdout: stdoutSync} = execaSync('echo-argv.js', commandArguments);109 t.deepEqual(JSON.parse(stdoutSync), commandArguments);110});111112// A command can be resolved from different kinds of file paths. Forward slashes113// work even on Windows, where they are normalized to backslashes.114const testResolvesCommand = async (t, file, options) => {115 const {stdout} = await execa(file, ['foo'], options);116 t.is(stdout, 'foo');117118 const {stdout: stdoutSync} = execaSync(file, ['foo'], options);119 t.is(stdoutSync, 'foo');120};121122test('Runs a command given as an absolute path', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'echo.js'));123test('Runs a command given as a relative path with a custom cwd', testResolvesCommand, './echo.js', {cwd: FIXTURES_DIRECTORY});124test('Runs a command given as a relative POSIX-style subpath', testResolvesCommand, 'test/fixtures/echo.js');125test('Runs a command whose path contains a space', testResolvesCommand, 'command with space.js');126test('Runs a command whose absolute path contains a space', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'command with space.js'));127128// A shebang script can be run without explicitly prepending its interpreter.129// This is emulated on Windows, where shebangs are not natively supported.130// The whole test suite implicitly relies on this (e.g. `echo.js`), so we assert it explicitly.131test('Runs a shebang script without specifying its interpreter', async t => {132 const {stdout} = await execa('echo.js', ['foo']);133 t.is(stdout, 'foo');134135 const {stdout: stdoutSync} = execaSync('echo.js', ['foo']);136 t.is(stdoutSync, 'foo');137});138139// A space between `#!` and the interpreter path (e.g. `#! /usr/bin/env node`) is a valid,140// real-world shebang variation. The reimplemented shebang parser must trim it, otherwise141// on Windows the interpreter would resolve as ` /usr/bin/env` and fail with ENOENT.142test('Runs a shebang script with a space after the "#!"', async t => {143 const {stdout} = await execa('echo-space-shebang.js', ['foo']);144 t.is(stdout, 'foo');145146 const {stdout: stdoutSync} = execaSync('echo-space-shebang.js', ['foo']);147 t.is(stdoutSync, 'foo');148});149150// Neither the caller's arguments array nor its options object should be mutated,151// whether or not a shell is used (each path clones the arguments internally).152const testNoMutation = async (t, options) => {153 const commandArguments = ['foo', 'bar'];154 const optionsCopy = {...options};155156 await execa('echo.js', commandArguments, options);157 t.deepEqual(commandArguments, ['foo', 'bar']);158 t.deepEqual(options, optionsCopy);159160 execaSync('echo.js', commandArguments, options);161 t.deepEqual(commandArguments, ['foo', 'bar']);162 t.deepEqual(options, optionsCopy);163};164165test('Does not mutate arguments nor options', testNoMutation, {});166test('Does not mutate arguments nor options with a shell', testNoMutation, {shell: true});167168if (isWindows) {169 // A bare command name without an extension is resolved using `PATHEXT`.170 test('Resolves command extension using PATHEXT (sync)', t => {171 const {stdout} = execaSync('hello');172 t.is(stdout, 'Hello World');173 });174175 // A `.cmd` file needs `cmd.exe`, so its forward-slash path must be normalized to176 // backslashes, otherwise it fails with ENOENT.177 test('Runs a .cmd file given as a relative POSIX-style subpath', async t => {178 const {stdout} = await execa('fixtures/hello.cmd', {cwd: path.join(FIXTURES_DIRECTORY, '..')});179 t.is(stdout, 'Hello World');180 });181182 /*183 Metacharacters are double-escaped for batch files, since `cmd.exe` interprets them once when the batch file is invoked and once when it re-expands the arguments with `%*`.184 The `cmd`-shims npm generates in `node_modules/.bin/` are the canonical example.185 */186 const setupCmdShim = async () => {187 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');188 await mkdir(binaryDirectory, {recursive: true});189 const shimPath = path.join(binaryDirectory, 'echo-cmd-shim.cmd');190 await cp(path.join(FIXTURES_DIRECTORY, 'echo-cmd-shim.cmd'), shimPath);191 return shimPath;192 };193194 test('Double-escapes metacharacters for node_modules/.bin cmd-shims', async t => {195 const shimPath = await setupCmdShim();196 const commandArgument = '"(foo|bar>baz|foz)"';197 const {stdout} = await execa(shimPath, [commandArgument]);198 t.is(stdout, commandArgument);199200 const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]);201 t.is(stdoutSync, commandArgument);202 });203}204205// On Windows, `.cmd`/`.bat` files are run through `cmd.exe`, which interprets several206// characters specially. Those must be escaped in arguments, otherwise they could expand207// variables or inject commands (the "BatBadBut" class of vulnerabilities). `echo-shim.cmd`208// forwards its arguments to `echo.js`, so the subprocess prints back the exact209// `process.argv` it received: each argument must arrive unchanged and inert.210if (isWindows) {211 const testEscaping = async (t, commandArgument) => {212 const {stdout} = await execa('echo-shim.cmd', [commandArgument]);213 t.is(stdout, commandArgument);214215 const {stdout: stdoutSync} = execaSync('echo-shim.cmd', [commandArgument]);216 t.is(stdoutSync, commandArgument);217 };218219 // A `%VAR%` argument must be passed literally, not expanded by `cmd.exe`.220 test('Does not expand environment variables in arguments', testEscaping, '%PATH%');221 // Delayed expansion (`!VAR!`) must not be interpreted either.222 test('Does not expand delayed environment variables in arguments', testEscaping, '!PATH!');223 // An `&` must not be interpreted as a command separator.224 test('Does not allow command injection via `&` in arguments', testEscaping, 'a&b');225 // A `|` must not be interpreted as a pipe.226 test('Does not allow command injection via `|` in arguments', testEscaping, 'a|whoami');227 // Redirections (`<`, `>`) must not be interpreted.228 test('Does not allow command injection via redirections in arguments', testEscaping, 'a>b<c');229 // Parentheses must not be interpreted as command grouping.230 test('Does not allow command injection via parentheses in arguments', testEscaping, '(whoami)');231 // A quote followed by an injected command must stay inert.232 test('Does not allow command injection via nested quotes in arguments', testEscaping, '"& whoami &"');233 // Double quotes must be preserved.234 test('Preserves double quotes in arguments', testEscaping, 'a"b"c');235 // Carets are the escape character in `cmd.exe` and must be passed literally.236 test('Preserves carets in arguments', testEscaping, 'a^b^^c');237 // Backslashes, including trailing ones, must be preserved next to quotes.238 test('Preserves backslashes and double quotes in arguments', testEscaping, 'a\\"b\\\\"c\\');239240 // Every kind of tricky argument must also roundtrip through `cmd.exe` unchanged, not241 // just be inert. Unlike `echo.js` (which resolves to `node.exe` and bypasses `cmd.exe`),242 // `echo-shim.cmd` forces the `cmd.exe` escaping path. This mirrors the roundtrip tests243 // above, but validates the `cmd.exe`-specific escaping rather than Node's native escaping.244 const testCmdRoundtrip = async (t, commandArguments) => {245 const expectedStdout = commandArguments.join('\n');246247 const {stdout} = await execa('echo-shim.cmd', commandArguments);248 t.is(stdout, expectedStdout);249250 const {stdout: stdoutSync} = execaSync('echo-shim.cmd', commandArguments);251 t.is(stdoutSync, expectedStdout);252 };253254 // eslint-disable-next-line no-template-curly-in-string255 test('Roundtrips shell metacharacters through cmd.exe', testCmdRoundtrip, ['()', '[]', '%!', '^', '<', '>', '|', ';', ',', '=', '`', '*', '?', '$HOME', '${x}', '~']);256 test('Roundtrips backslashes and double quotes through cmd.exe', testCmdRoundtrip, ['a\\b', 'a\\\\b', 'a\\', 'a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']);257 // Long backslash runs must also roundtrip through the `cmd.exe` escaping specifically,258 // which is where the backslash-doubling actually runs. Kept modest to stay under the259 // `cmd.exe` command-line length limit once the backslashes are doubled.260 test('Roundtrips long backslash runs before quotes through cmd.exe', testCmdRoundtrip, [`${'\\'.repeat(200)}"`, '\\'.repeat(200), `a${'\\'.repeat(100)}"b`]);261 // The per-length sweep must roundtrip through `cmd.exe` too, since the corrupted doubling262 // is exactly what this escaping path performs.263 test('Roundtrips backslash runs of every length through cmd.exe', testCmdRoundtrip, backslashRunArguments);264 // Consecutive double quotes must survive the `cmd.exe` escaping, each escaped on its own.265 test('Roundtrips consecutive double quotes through cmd.exe', testCmdRoundtrip, ['""', '"""', 'a""b', '""""']);266 test('Roundtrips arguments with spaces through cmd.exe', testCmdRoundtrip, ['a b', ' '.repeat(3), 'foo bar baz', 'André Cruz']);267268 /*269 `.bat` files re-expand their arguments through `cmd.exe` exactly like `.cmd` files, so they need the same double-escaping.270 `echo-shim.bat` is the `.bat` twin of `echo-shim.cmd`.271 */272 const testBatEscaping = async (t, commandArgument) => {273 const {stdout} = await execa('echo-shim.bat', [commandArgument]);274 t.is(stdout, commandArgument);275276 const {stdout: stdoutSync} = execaSync('echo-shim.bat', [commandArgument]);277 t.is(stdoutSync, commandArgument);278 };279280 // The same nested-quote injection must stay inert when the batch file is a `.bat`.281 test('Does not allow command injection via nested quotes in `.bat` arguments', testBatEscaping, '"& whoami &"');282 // Metacharacters must survive the double `cmd.exe` expansion for `.bat` files too.283 test('Roundtrips shell metacharacters through a `.bat` file', testBatEscaping, '(foo|bar>baz|foz)');284 // A `.bat` file not in `node_modules/.bin/` must still be double-escaped, since the location is irrelevant: any batch file re-expands its arguments.285 test('Does not expand environment variables in `.bat` arguments', testBatEscaping, '%PATH%');286 // Backslashes, double quotes and metacharacters combined are the trickiest to escape, and must survive the double `cmd.exe` expansion of a `.bat` file intact.287 test('Preserves backslashes, quotes and metacharacters in `.bat` arguments', testBatEscaping, 'a\\"&b\\\\"|c\\');288 // Several tricky arguments passed together must each be double-escaped independently and arrive in order, not merged nor reordered.289 test('Roundtrips multiple tricky arguments through a `.bat` file', async t => {290 const commandArguments = ['a b', 'c&d', '"e"', 'f\\"g', '%h%'];291 const expectedStdout = commandArguments.join('\n');292293 const {stdout} = await execa('echo-shim.bat', commandArguments);294 t.is(stdout, expectedStdout);295296 const {stdout: stdoutSync} = execaSync('echo-shim.bat', commandArguments);297 t.is(stdoutSync, expectedStdout);298 });299300 // `cmd.exe` interprets CR and LF as command separators and provides no way to escape301 // them, so those are rejected to prevent command injection.302 test('Rejects arguments containing a line break', t => {303 t.throws(() => execa('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});304 t.throws(() => execaSync('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});305 });306307 // The command itself is validated too, not just its arguments.308 test('Rejects a command containing a line break', t => {309 t.throws(() => execa('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});310 t.throws(() => execaSync('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});311 });312313 // A shell escapes the arguments itself, so the line break rejection does not apply.314 test('Does not reject line breaks when using a shell', async t => {315 await t.notThrowsAsync(execa('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));316 t.notThrows(() => execaSync('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));317 });318}