Skip to content
Myr

command-resolution.js

This file

Path

test/arguments/command-resolution.js

527 lines · 23.5 KiB · JavaScript

Last changed by

Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733

History of this file

Take it

Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733

lines 1–6why, one step back
1import {
2 cp,3 mkdir,4 unlink,5 writeFile,6} from 'node:fs/promises';

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 7–173why, one step back
7import path from 'node:path';
8import process from 'node:process';9import test from 'ava';10import {execa, execaSync} from '../../index.js';11import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';1213setFixtureDirectory();1415const isWindows = process.platform === 'win32';1617// These tests cover the command resolution and argument escaping performed by18// `lib/arguments/command-file.js`, which allows running scripts, `.cmd`/`.bat` files19// and shebang scripts without a shell, and prevents command injection on Windows.20// Most assertions use a roundtrip: an argument is passed in, the subprocess prints21// its own `process.argv` back (see `test/fixtures/echo.js`), and we check it comes22// back byte-identical. This exercises the escaping logic on whichever OS runs the23// test, so Windows escaping is genuinely validated on CI.2425// `echo.js` prints `process.argv.slice(2).join('\n')`26const testRoundtrip = async (t, commandArguments) => {27 const expectedStdout = commandArguments.map(String).join('\n');2829 const {stdout} = await execa('echo.js', commandArguments);30 t.is(stdout, expectedStdout);3132 const {stdout: stdoutSync} = execaSync('echo.js', commandArguments);33 t.is(stdoutSync, expectedStdout);34};3536test('Empty arguments and arguments with spaces', testRoundtrip, ['foo', '', 'bar', 'André Cruz']);37test('Non-string arguments are coerced', testRoundtrip, [1234]);38test('Arguments with shell special characters', testRoundtrip, [39 'foo',40 '()',41 'foo',42 '[]',43 'foo',44 '%!',45 'foo',46 '^<',47 'foo',48 '>&',49 'foo',50 '|;',51 'foo',52 ', ',53 'foo',54 '!=',55 'foo',56 '\\*',57 'foo',58 '"f"',59 'foo',60 '?.',61 'foo',62 '=`',63 'foo',64 '\'',65 'foo',66 '\\"',67 'bar\\',68 '"foo|bar>baz"',69 '"(foo|bar>baz|foz)"',70]);71// Backslashes and double quotes need specific escaping on Windows, so their combinations are the trickiest.72test('Arguments with backslashes', testRoundtrip, ['a\\b', 'a\\\\b', '\\', '\\\\', 'a\\', 'trailing\\']);73test('Arguments with backslashes and double quotes', testRoundtrip, ['a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']);74// Backslashes, double quotes and shell metacharacters combined in a single argument are the trickiest to escape on Windows.75test('Arguments combining backslashes, quotes and metacharacters', testRoundtrip, ['a\\"&b', '\\"()\\', 'c\\\\"|d', '%x%\\', '">&<"']);76test('Arguments with tabs and whitespace', testRoundtrip, ['a\tb', '\t', ' spaces ', ' ']);77// Several consecutive empty and whitespace-only arguments must each be preserved as a distinct argument.78test('Arguments that are empty or whitespace-only', testRoundtrip, ['', '', 'a', '', ' ', '\t', '']);79test('Arguments that look like flags', testRoundtrip, ['-e', '--foo=bar', '--', '-']);80test('Arguments with Unicode characters', testRoundtrip, ['café', '🎉', '日本語', 'naïve']);81// eslint-disable-next-line no-template-curly-in-string82test('Arguments with shell variable syntax', testRoundtrip, ['$HOME', '${x}', '~', 'a=b,c', '`whoami`']);83// Very long arguments must not be truncated nor corrupted by the escaping.84test('Very long arguments', testRoundtrip, ['a'.repeat(10_000), `${'b'.repeat(1000)}\\"${'c'.repeat(1000)}`]);85// A long run of consecutive backslashes right before a double quote (or the end of the86// argument) must be doubled as a whole. This is both the input a length-dependent escaping87// bug corrupts and the one a naive regex backtracks quadratically over, so a correct88// roundtrip here guards correctness and the single-pass linear escaping at once.89test('Arguments with long runs of backslashes before quotes', testRoundtrip, [90 `${'\\'.repeat(1000)}"`,91 '\\'.repeat(1000),92 `a${'\\'.repeat(500)}"b${'\\'.repeat(500)}`,93]);94// Runs of backslashes of every length from 1 to 6, each right before a double quote, then95// each at the very end of the argument. The bug this guards against doubled only the last96// backslash of a run instead of the whole run, so it corrupted every length above 1.97// Passing each length as its own argument pins down exactly which lengths would break.98const backslashRunArguments = [99 ...Array.from({length: 6}, (_, index) => `${'\\'.repeat(index + 1)}"x`),100 ...Array.from({length: 6}, (_, index) => `end${'\\'.repeat(index + 1)}`),101];102test('Arguments with backslash runs of every length', testRoundtrip, backslashRunArguments);103// Consecutive double quotes must each be escaped independently, not collapsed nor paired.104test('Arguments with consecutive double quotes', testRoundtrip, ['""', '"""', 'a""b', '""""']);105// A line break can be passed as an argument to a directly executable file (unlike a `.cmd`106// on Windows, see below). `echo-argv.js` prints its arguments as JSON, so this verifies the107// line break stays within a single argument rather than splitting it in two.108test('Line breaks are kept within a single argument for executables', async t => {109 const commandArguments = ['a\nb', 'a\r\nb', 'c'];110 const {stdout} = await execa('echo-argv.js', commandArguments);111 t.deepEqual(JSON.parse(stdout), commandArguments);112113 const {stdout: stdoutSync} = execaSync('echo-argv.js', commandArguments);114 t.deepEqual(JSON.parse(stdoutSync), commandArguments);115});116117// A command can be resolved from different kinds of file paths. Forward slashes118// work even on Windows, where they are normalized to backslashes.119const testResolvesCommand = async (t, file, options) => {120 const {stdout} = await execa(file, ['foo'], options);121 t.is(stdout, 'foo');122123 const {stdout: stdoutSync} = execaSync(file, ['foo'], options);124 t.is(stdoutSync, 'foo');125};126127test('Runs a command given as an absolute path', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'echo.js'));128test('Runs a command given as a relative path with a custom cwd', testResolvesCommand, './echo.js', {cwd: FIXTURES_DIRECTORY});129test('Runs a command given as a relative POSIX-style subpath', testResolvesCommand, 'test/fixtures/echo.js');130test('Runs a command whose path contains a space', testResolvesCommand, 'command with space.js');131test('Runs a command whose absolute path contains a space', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'command with space.js'));132133// A shebang script can be run without explicitly prepending its interpreter.134// This is emulated on Windows, where shebangs are not natively supported.135// The whole test suite implicitly relies on this (e.g. `echo.js`), so we assert it explicitly.136test('Runs a shebang script without specifying its interpreter', async t => {137 const {stdout} = await execa('echo.js', ['foo']);138 t.is(stdout, 'foo');139140 const {stdout: stdoutSync} = execaSync('echo.js', ['foo']);141 t.is(stdoutSync, 'foo');142});143144// A space between `#!` and the interpreter path (e.g. `#! /usr/bin/env node`) is a valid,145// real-world shebang variation. The reimplemented shebang parser must trim it, otherwise146// on Windows the interpreter would resolve as ` /usr/bin/env` and fail with ENOENT.147test('Runs a shebang script with a space after the "#!"', async t => {148 const {stdout} = await execa('echo-space-shebang.js', ['foo']);149 t.is(stdout, 'foo');150151 const {stdout: stdoutSync} = execaSync('echo-space-shebang.js', ['foo']);152 t.is(stdoutSync, 'foo');153});154155// Neither the caller's arguments array nor its options object should be mutated,156// whether or not a shell is used (each path clones the arguments internally).157const testNoMutation = async (t, options) => {158 const commandArguments = ['foo', 'bar'];159 const optionsCopy = {...options};160161 await execa('echo.js', commandArguments, options);162 t.deepEqual(commandArguments, ['foo', 'bar']);163 t.deepEqual(options, optionsCopy);164165 execaSync('echo.js', commandArguments, options);166 t.deepEqual(commandArguments, ['foo', 'bar']);167 t.deepEqual(options, optionsCopy);168};169170test('Does not mutate arguments nor options', testNoMutation, {});171test('Does not mutate arguments nor options with a shell', testNoMutation, {shell: true});172173if (isWindows) {

Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733

lines 174–181why, one step back
174 const nodeOnlyOptions = {
175 extendEnv: false,176 env: {177 Path: path.dirname(process.execPath),178 PathExt: '.EXE',179 },180 };181

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 182–187why, one step back
182 // A bare command name without an extension is resolved using `PATHEXT`.
183 test('Resolves command extension using PATHEXT (sync)', t => {184 const {stdout} = execaSync('hello');185 t.is(stdout, 'Hello World');186 });187

Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733

lines 188–338why, one step back
188 test('Uses PATHEXT extension order for direct executables', async t => {
189 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');190 await mkdir(binaryDirectory, {recursive: true});191 const command = 'node-extension-order';192 const executablePath = path.join(binaryDirectory, `${command}.exe`);193 const comPath = path.join(binaryDirectory, `${command}.com`);194 await Promise.all([195 cp(process.execPath, executablePath),196 cp(process.execPath, comPath),197 ]);198 t.teardown(async () => {199 await Promise.all([unlink(executablePath), unlink(comPath)]);200 });201 const options = {202 preferLocal: true,203 localDir: FIXTURES_DIRECTORY,204 extendEnv: false,205 env: {206 Path: path.dirname(process.execPath),207 PathExt: '.EXE;.COM',208 },209 };210 const nodeExpression = 'JSON.stringify({executablePath: process.execPath, argv0: process.argv0})';211 const {stdout} = await execa(command, ['--print', nodeExpression], options);212 const {executablePath: actualExecutablePath, argv0} = JSON.parse(stdout);213 t.is(actualExecutablePath.toLowerCase(), executablePath.toLowerCase());214 t.is(argv0, command);215216 const {stdout: stdoutSync} = execaSync(command, ['--print', nodeExpression], options);217 const {executablePath: actualExecutablePathSync, argv0: argv0Sync} = JSON.parse(stdoutSync);218 t.is(actualExecutablePathSync.toLowerCase(), executablePath.toLowerCase());219 t.is(argv0Sync, command);220 });221222 test.serial('Respects NoDefaultCurrentDirectoryInExePath', async t => {223 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');224 await mkdir(binaryDirectory, {recursive: true});225 const command = 'node-current-directory';226 const currentDirectoryExecutable = path.join(FIXTURES_DIRECTORY, `${command}.exe`);227 const pathExecutable = path.join(binaryDirectory, `${command}.exe`);228 await Promise.all([229 cp(process.execPath, currentDirectoryExecutable),230 cp(process.execPath, pathExecutable),231 ]);232233 const environmentName = 'NoDefaultCurrentDirectoryInExePath';234 const originalValue = process.env[environmentName];235 delete process.env[environmentName];236 t.teardown(async () => {237 if (originalValue === undefined) {238 delete process.env[environmentName];239 } else {240 process.env[environmentName] = originalValue;241 }242243 await Promise.all([unlink(currentDirectoryExecutable), unlink(pathExecutable)]);244 });245246 const options = {247 cwd: FIXTURES_DIRECTORY,248 extendEnv: false,249 env: {250 Path: binaryDirectory,251 PathExt: '.EXE',252 },253 };254 const {stdout: currentDirectoryStdout} = await execa(command, ['--print', 'process.execPath'], options);255 t.is(currentDirectoryStdout.toLowerCase(), currentDirectoryExecutable.toLowerCase());256257 const {stdout: currentDirectoryStdoutSync} = execaSync(command, ['--print', 'process.execPath'], options);258 t.is(currentDirectoryStdoutSync.toLowerCase(), currentDirectoryExecutable.toLowerCase());259260 process.env[environmentName] = '1';261 const {stdout} = await execa(command, ['--print', 'process.execPath'], options);262 t.is(stdout.toLowerCase(), pathExecutable.toLowerCase());263264 const {stdout: stdoutSync} = execaSync(command, ['--print', 'process.execPath'], options);265 t.is(stdoutSync.toLowerCase(), pathExecutable.toLowerCase());266 });267268 test.serial('Uses the resolved batch file when current-directory search is disabled', async t => {269 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');270 await mkdir(binaryDirectory, {recursive: true});271 const command = 'batch-current-directory';272 const currentDirectoryBatchFile = path.join(FIXTURES_DIRECTORY, `${command}.cmd`);273 const pathBatchFile = path.join(binaryDirectory, `${command}.cmd`);274 await Promise.all([275 writeFile(currentDirectoryBatchFile, '@echo current directory'),276 writeFile(pathBatchFile, '@echo PATH'),277 ]);278279 const environmentName = 'NoDefaultCurrentDirectoryInExePath';280 const originalValue = process.env[environmentName];281 delete process.env[environmentName];282 t.teardown(async () => {283 if (originalValue === undefined) {284 delete process.env[environmentName];285 } else {286 process.env[environmentName] = originalValue;287 }288289 await Promise.all([unlink(currentDirectoryBatchFile), unlink(pathBatchFile)]);290 });291292 const options = {293 cwd: FIXTURES_DIRECTORY,294 extendEnv: false,295 env: {296 Path: binaryDirectory,297 PathExt: '.CMD',298 [environmentName]: '',299 },300 };301 const {stdout} = await execa(command, options);302 t.is(stdout, 'PATH');303304 const {stdout: stdoutSync} = execaSync(command, options);305 t.is(stdoutSync, 'PATH');306307 delete options.env[environmentName];308 process.env[environmentName] = '';309 const {stdout: parentEnvironmentStdout} = await execa(command, options);310 t.is(parentEnvironmentStdout, 'PATH');311312 const {stdout: parentEnvironmentStdoutSync} = execaSync(command, options);313 t.is(parentEnvironmentStdoutSync, 'PATH');314 });315316 test('Does not search PATH for drive-relative commands', async t => {317 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');318 await mkdir(binaryDirectory, {recursive: true});319 const commandName = 'node-drive-relative';320 const pathExecutable = path.join(binaryDirectory, `${commandName}.exe`);321 await cp(process.execPath, pathExecutable);322 t.teardown(async () => {323 await unlink(pathExecutable);324 });325 const drive = path.parse(FIXTURES_DIRECTORY).root.slice(0, 2);326 const command = `${drive}${commandName}`;327 const options = {328 cwd: FIXTURES_DIRECTORY,329 extendEnv: false,330 env: {331 Path: binaryDirectory,332 PathExt: '.EXE',333 },334 };335 await t.throwsAsync(execa(command, [], options));336 t.throws(() => execaSync(command, [], options));337 });338

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 339–365why, one step back
339 // A `.cmd` file needs `cmd.exe`, so its forward-slash path must be normalized to
340 // backslashes, otherwise it fails with ENOENT.341 test('Runs a .cmd file given as a relative POSIX-style subpath', async t => {342 const {stdout} = await execa('fixtures/hello.cmd', {cwd: path.join(FIXTURES_DIRECTORY, '..')});343 t.is(stdout, 'Hello World');344 });345346 /*347 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 `%*`.348 The `cmd`-shims npm generates in `node_modules/.bin/` are the canonical example.349 */350 const setupCmdShim = async () => {351 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');352 await mkdir(binaryDirectory, {recursive: true});353 const shimPath = path.join(binaryDirectory, 'echo-cmd-shim.cmd');354 await cp(path.join(FIXTURES_DIRECTORY, 'echo-cmd-shim.cmd'), shimPath);355 return shimPath;356 };357358 test('Double-escapes metacharacters for node_modules/.bin cmd-shims', async t => {359 const shimPath = await setupCmdShim();360 const commandArgument = '"(foo|bar>baz|foz)"';361 const {stdout} = await execa(shimPath, [commandArgument]);362 t.is(stdout, commandArgument);363364 const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]);365 t.is(stdoutSync, commandArgument);

Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733

lines 366–410why, one step back
366 });
367368 test('Double-escapes explicit batch files excluded from PATHEXT', async t => {369 const commandArgument = '"& whoami &"';370 const command = path.join(FIXTURES_DIRECTORY, 'echo-shim.cmd');371 const {stdout} = await execa(command, [commandArgument], nodeOnlyOptions);372 t.is(stdout, commandArgument);373374 const {stdout: stdoutSync} = execaSync(command, [commandArgument], nodeOnlyOptions);375 t.is(stdoutSync, commandArgument);376 });377378 test('Runs an explicit shebang script excluded from PATHEXT', async t => {379 const command = path.join(FIXTURES_DIRECTORY, 'echo.js');380 await testResolvesCommand(t, command, nodeOnlyOptions);381 });382383 test.serial('Double-escapes metacharacters for preferLocal cmd-shims', async t => {384 await setupCmdShim();385 const commandArgument = 'a&whoami';386 const originalPathExt = process.env.PATHEXT;387 process.env.PATHEXT = '.EXE';388 const options = {389 preferLocal: true,390 localDir: FIXTURES_DIRECTORY,391 extendEnv: false,392 env: {393 Path: path.dirname(process.execPath),394 PathExt: '.EXE;.CMD',395 },396 };397398 try {399 const {stdout} = await execa('echo-cmd-shim', [commandArgument], options);400 t.is(stdout, commandArgument);401402 const {stdout: stdoutSync} = execaSync('echo-cmd-shim', [commandArgument], options);403 t.is(stdoutSync, commandArgument);404 } finally {405 if (originalPathExt === undefined) {406 delete process.env.PATHEXT;407 } else {408 process.env.PATHEXT = originalPathExt;409 }410 }

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 411–527why, one step back
411 });
412}413414// On Windows, `.cmd`/`.bat` files are run through `cmd.exe`, which interprets several415// characters specially. Those must be escaped in arguments, otherwise they could expand416// variables or inject commands (the "BatBadBut" class of vulnerabilities). `echo-shim.cmd`417// forwards its arguments to `echo.js`, so the subprocess prints back the exact418// `process.argv` it received: each argument must arrive unchanged and inert.419if (isWindows) {420 const testEscaping = async (t, commandArgument) => {421 const {stdout} = await execa('echo-shim.cmd', [commandArgument]);422 t.is(stdout, commandArgument);423424 const {stdout: stdoutSync} = execaSync('echo-shim.cmd', [commandArgument]);425 t.is(stdoutSync, commandArgument);426 };427428 // A `%VAR%` argument must be passed literally, not expanded by `cmd.exe`.429 test('Does not expand environment variables in arguments', testEscaping, '%PATH%');430 // Delayed expansion (`!VAR!`) must not be interpreted either.431 test('Does not expand delayed environment variables in arguments', testEscaping, '!PATH!');432 // An `&` must not be interpreted as a command separator.433 test('Does not allow command injection via `&` in arguments', testEscaping, 'a&b');434 // A `|` must not be interpreted as a pipe.435 test('Does not allow command injection via `|` in arguments', testEscaping, 'a|whoami');436 // Redirections (`<`, `>`) must not be interpreted.437 test('Does not allow command injection via redirections in arguments', testEscaping, 'a>b<c');438 // Parentheses must not be interpreted as command grouping.439 test('Does not allow command injection via parentheses in arguments', testEscaping, '(whoami)');440 // A quote followed by an injected command must stay inert.441 test('Does not allow command injection via nested quotes in arguments', testEscaping, '"& whoami &"');442 // Double quotes must be preserved.443 test('Preserves double quotes in arguments', testEscaping, 'a"b"c');444 // Carets are the escape character in `cmd.exe` and must be passed literally.445 test('Preserves carets in arguments', testEscaping, 'a^b^^c');446 // Backslashes, including trailing ones, must be preserved next to quotes.447 test('Preserves backslashes and double quotes in arguments', testEscaping, 'a\\"b\\\\"c\\');448449 // Every kind of tricky argument must also roundtrip through `cmd.exe` unchanged, not450 // just be inert. Unlike `echo.js` (which resolves to `node.exe` and bypasses `cmd.exe`),451 // `echo-shim.cmd` forces the `cmd.exe` escaping path. This mirrors the roundtrip tests452 // above, but validates the `cmd.exe`-specific escaping rather than Node's native escaping.453 const testCmdRoundtrip = async (t, commandArguments) => {454 const expectedStdout = commandArguments.join('\n');455456 const {stdout} = await execa('echo-shim.cmd', commandArguments);457 t.is(stdout, expectedStdout);458459 const {stdout: stdoutSync} = execaSync('echo-shim.cmd', commandArguments);460 t.is(stdoutSync, expectedStdout);461 };462463 // eslint-disable-next-line no-template-curly-in-string464 test('Roundtrips shell metacharacters through cmd.exe', testCmdRoundtrip, ['()', '[]', '%!', '^', '<', '>', '|', ';', ',', '=', '`', '*', '?', '$HOME', '${x}', '~']);465 test('Roundtrips backslashes and double quotes through cmd.exe', testCmdRoundtrip, ['a\\b', 'a\\\\b', 'a\\', 'a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']);466 // Long backslash runs must also roundtrip through the `cmd.exe` escaping specifically,467 // which is where the backslash-doubling actually runs. Kept modest to stay under the468 // `cmd.exe` command-line length limit once the backslashes are doubled.469 test('Roundtrips long backslash runs before quotes through cmd.exe', testCmdRoundtrip, [`${'\\'.repeat(200)}"`, '\\'.repeat(200), `a${'\\'.repeat(100)}"b`]);470 // The per-length sweep must roundtrip through `cmd.exe` too, since the corrupted doubling471 // is exactly what this escaping path performs.472 test('Roundtrips backslash runs of every length through cmd.exe', testCmdRoundtrip, backslashRunArguments);473 // Consecutive double quotes must survive the `cmd.exe` escaping, each escaped on its own.474 test('Roundtrips consecutive double quotes through cmd.exe', testCmdRoundtrip, ['""', '"""', 'a""b', '""""']);475 test('Roundtrips arguments with spaces through cmd.exe', testCmdRoundtrip, ['a b', ' '.repeat(3), 'foo bar baz', 'André Cruz']);476477 /*478 `.bat` files re-expand their arguments through `cmd.exe` exactly like `.cmd` files, so they need the same double-escaping.479 `echo-shim.bat` is the `.bat` twin of `echo-shim.cmd`.480 */481 const testBatEscaping = async (t, commandArgument) => {482 const {stdout} = await execa('echo-shim.bat', [commandArgument]);483 t.is(stdout, commandArgument);484485 const {stdout: stdoutSync} = execaSync('echo-shim.bat', [commandArgument]);486 t.is(stdoutSync, commandArgument);487 };488489 // The same nested-quote injection must stay inert when the batch file is a `.bat`.490 test('Does not allow command injection via nested quotes in `.bat` arguments', testBatEscaping, '"& whoami &"');491 // Metacharacters must survive the double `cmd.exe` expansion for `.bat` files too.492 test('Roundtrips shell metacharacters through a `.bat` file', testBatEscaping, '(foo|bar>baz|foz)');493 // 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.494 test('Does not expand environment variables in `.bat` arguments', testBatEscaping, '%PATH%');495 // Backslashes, double quotes and metacharacters combined are the trickiest to escape, and must survive the double `cmd.exe` expansion of a `.bat` file intact.496 test('Preserves backslashes, quotes and metacharacters in `.bat` arguments', testBatEscaping, 'a\\"&b\\\\"|c\\');497 // Several tricky arguments passed together must each be double-escaped independently and arrive in order, not merged nor reordered.498 test('Roundtrips multiple tricky arguments through a `.bat` file', async t => {499 const commandArguments = ['a b', 'c&d', '"e"', 'f\\"g', '%h%'];500 const expectedStdout = commandArguments.join('\n');501502 const {stdout} = await execa('echo-shim.bat', commandArguments);503 t.is(stdout, expectedStdout);504505 const {stdout: stdoutSync} = execaSync('echo-shim.bat', commandArguments);506 t.is(stdoutSync, expectedStdout);507 });508509 // `cmd.exe` interprets CR and LF as command separators and provides no way to escape510 // them, so those are rejected to prevent command injection.511 test('Rejects arguments containing a line break', t => {512 t.throws(() => execa('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});513 t.throws(() => execaSync('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});514 });515516 // The command itself is validated too, not just its arguments.517 test('Rejects a command containing a line break', t => {518 t.throws(() => execa('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});519 t.throws(() => execaSync('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});520 });521522 // A shell escapes the arguments itself, so the line break rejection does not apply.523 test('Does not reject line breaks when using a shell', async t => {524 await t.notThrowsAsync(execa('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));525 t.notThrows(() => execaSync('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));526 });527}