Skip to content
Myr

command-resolution.js

This file

Path

test/arguments/command-resolution.js

565 lines · 26.2 KiB · JavaScript

Last changed by

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

History of this file

Take it

1import assert from 'node:assert/strict';2import path from 'node:path';3import process from 'node:process';4import test from 'node:test';5import {6	cp,7	mkdir,8	unlink,9	writeFile,10} from 'node:fs/promises';11import {assertThrows, assertRejects} from '../helpers/assert.js';12import {execa, execaSync} from '../../index.js';13import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';1415setFixtureDirectory();1617const isWindows = process.platform === 'win32';1819// These tests cover the command resolution and argument escaping performed by20// `lib/arguments/command-file.js`, which allows running scripts, `.cmd`/`.bat` files21// and shebang scripts without a shell, and prevents command injection on Windows.22// Most assertions use a roundtrip: an argument is passed in, the subprocess prints23// its own `process.argv` back (see `test/fixtures/echo.js`), and we check it comes24// back byte-identical. This exercises the escaping logic on whichever OS runs the25// test, so Windows escaping is genuinely validated on CI.2627// `echo.js` prints `process.argv.slice(2).join('\n')`28const testRoundtrip = async commandArguments => {29	const expectedStdout = commandArguments.map(String).join('\n');3031	const {stdout} = await execa('echo.js', commandArguments);32	assert.equal(stdout, expectedStdout);3334	const {stdout: stdoutSync} = execaSync('echo.js', commandArguments);35	assert.equal(stdoutSync, expectedStdout);36};3738test('Empty arguments and arguments with spaces', () => testRoundtrip(['foo', '', 'bar', 'André Cruz']));39test('Non-string arguments are coerced', () => testRoundtrip([1234]));40test('Arguments with shell special characters', () => testRoundtrip([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	'\\*',59	'foo',60	'"f"',61	'foo',62	'?.',63	'foo',64	'=`',65	'foo',66	'\'',67	'foo',68	'\\"',69	'bar\\',70	'"foo|bar>baz"',71	'"(foo|bar>baz|foz)"',72]));73// Backslashes and double quotes need specific escaping on Windows, so their combinations are the trickiest.74test('Arguments with backslashes', () => testRoundtrip(['a\\b', 'a\\\\b', '\\', '\\\\', 'a\\', 'trailing\\']));75test('Arguments with backslashes and double quotes', () => testRoundtrip(['a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']));76// Backslashes, double quotes and shell metacharacters combined in a single argument are the trickiest to escape on Windows.77test('Arguments combining backslashes, quotes and metacharacters', () => testRoundtrip(['a\\"&b', '\\"()\\', 'c\\\\"|d', '%x%\\', '">&<"']));78test('Arguments with tabs and whitespace', () => testRoundtrip(['a\tb', '\t', '   spaces   ', ' ']));79// Several consecutive empty and whitespace-only arguments must each be preserved as a distinct argument.80test('Arguments that are empty or whitespace-only', () => testRoundtrip(['', '', 'a', '', ' ', '\t', '']));81test('Arguments that look like flags', () => testRoundtrip(['-e', '--foo=bar', '--', '-']));82test('Arguments with Unicode characters', () => testRoundtrip(['café', '🎉', '日本語', 'naïve']));83// eslint-disable-next-line no-template-curly-in-string84test('Arguments with shell variable syntax', () => testRoundtrip(['$HOME', '${x}', '~', 'a=b,c', '`whoami`']));85// Very long arguments must not be truncated nor corrupted by the escaping.86test('Very long arguments', () => testRoundtrip(['a'.repeat(10_000), `${'b'.repeat(1000)}\\"${'c'.repeat(1000)}`]));87// A long run of consecutive backslashes right before a double quote (or the end of the88// argument) must be doubled as a whole. This is both the input a length-dependent escaping89// bug corrupts and the one a naive regex backtracks quadratically over, so a correct90// roundtrip here guards correctness and the single-pass linear escaping at once.91test('Arguments with long runs of backslashes before quotes', () => testRoundtrip([92	`${'\\'.repeat(1000)}"`,93	'\\'.repeat(1000),94	`a${'\\'.repeat(500)}"b${'\\'.repeat(500)}`,95]));96// Runs of backslashes of every length from 1 to 6, each right before a double quote, then97// each at the very end of the argument. The bug this guards against doubled only the last98// backslash of a run instead of the whole run, so it corrupted every length above 1.99// Passing each length as its own argument pins down exactly which lengths would break.100const backslashRunArguments = [101	...Array.from({length: 6}, (_, index) => `${'\\'.repeat(index + 1)}"x`),102	...Array.from({length: 6}, (_, index) => `end${'\\'.repeat(index + 1)}`),103];104test('Arguments with backslash runs of every length', () => testRoundtrip(backslashRunArguments));105// Consecutive double quotes must each be escaped independently, not collapsed nor paired.106test('Arguments with consecutive double quotes', () => testRoundtrip(['""', '"""', 'a""b', '""""']));107// A line break can be passed as an argument to a directly executable file (unlike a `.cmd`108// on Windows, see below). `echo-argv.js` prints its arguments as JSON, so this verifies the109// line break stays within a single argument rather than splitting it in two.110test('Line breaks are kept within a single argument for executables', async () => {111	const commandArguments = ['a\nb', 'a\r\nb', 'c'];112	const {stdout} = await execa('echo-argv.js', commandArguments);113	assert.deepEqual(JSON.parse(stdout), commandArguments);114115	const {stdout: stdoutSync} = execaSync('echo-argv.js', commandArguments);116	assert.deepEqual(JSON.parse(stdoutSync), commandArguments);117});118119// A command can be resolved from different kinds of file paths. Forward slashes120// work even on Windows, where they are normalized to backslashes.121const testResolvesCommand = async (file, options) => {122	const {stdout} = await execa(file, ['foo'], options);123	assert.equal(stdout, 'foo');124125	const {stdout: stdoutSync} = execaSync(file, ['foo'], options);126	assert.equal(stdoutSync, 'foo');127};128129test('Runs a command given as an absolute path', () => testResolvesCommand(path.join(FIXTURES_DIRECTORY, 'echo.js')));130test('Runs a command given as a relative path with a custom cwd', () => testResolvesCommand('./echo.js', {cwd: FIXTURES_DIRECTORY}));131test('Runs a command given as a relative POSIX-style subpath', () => testResolvesCommand('test/fixtures/echo.js'));132test('Runs a command whose path contains a space', () => testResolvesCommand('command with space.js'));133test('Runs a command whose absolute path contains a space', () => testResolvesCommand(path.join(FIXTURES_DIRECTORY, 'command with space.js')));134135// A shebang script can be run without explicitly prepending its interpreter.136// This is emulated on Windows, where shebangs are not natively supported.137// The whole test suite implicitly relies on this (e.g. `echo.js`), so we assert it explicitly.138test('Runs a shebang script without specifying its interpreter', async () => {139	const {stdout} = await execa('echo.js', ['foo']);140	assert.equal(stdout, 'foo');141142	const {stdout: stdoutSync} = execaSync('echo.js', ['foo']);143	assert.equal(stdoutSync, 'foo');144});145146// A space between `#!` and the interpreter path (e.g. `#! /usr/bin/env node`) is a valid,147// real-world shebang variation. The reimplemented shebang parser must trim it, otherwise148// on Windows the interpreter would resolve as ` /usr/bin/env` and fail with ENOENT.149test('Runs a shebang script with a space after the "#!"', async () => {150	const {stdout} = await execa('echo-space-shebang.js', ['foo']);151	assert.equal(stdout, 'foo');152153	const {stdout: stdoutSync} = execaSync('echo-space-shebang.js', ['foo']);154	assert.equal(stdoutSync, 'foo');155});156157/*158Windows does not support shebangs natively, so Execa parses them itself, by reading the file's first bytes into a fixed-size buffer.159A file which only contains a shebang line, without a trailing newline, is shorter than that buffer, which is zero-filled.160Only the bytes actually read must be parsed, otherwise the interpreter would include those `\0` characters, which does not resolve to any file.161The file is created by the test since Unix cannot execute it, so it must not be used by any other test.162*/163if (isWindows) {164	test('Runs a shebang script shorter than the shebang buffer', async t => {165		const filePath = path.join(FIXTURES_DIRECTORY, 'shebang-only.js');166		await writeFile(filePath, '#!/usr/bin/env node');167		t.after(() => unlink(filePath));168169		const {exitCode, stdout} = await execa('shebang-only.js');170		assert.equal(exitCode, 0);171		assert.equal(stdout, '');172	});173}174175// Neither the caller's arguments array nor its options object should be mutated,176// whether or not a shell is used (each path clones the arguments internally).177const testNoMutation = async options => {178	const commandArguments = ['foo', 'bar'];179	const optionsCopy = {...options};180181	await execa('echo.js', commandArguments, options);182	assert.deepEqual(commandArguments, ['foo', 'bar']);183	assert.deepEqual(options, optionsCopy);184185	execaSync('echo.js', commandArguments, options);186	assert.deepEqual(commandArguments, ['foo', 'bar']);187	assert.deepEqual(options, optionsCopy);188};189190test('Does not mutate arguments nor options', () => testNoMutation({}));191test('Does not mutate arguments nor options with a shell', () => testNoMutation({shell: true}));192193if (isWindows) {194	const nodeOnlyOptions = {195		extendEnv: false,196		env: {197			Path: path.dirname(process.execPath),198			PathExt: '.EXE',199		},200	};201202	// A bare command name without an extension is resolved using `PATHEXT`.203	test('Resolves command extension using PATHEXT (sync)', () => {204		const {stdout} = execaSync('hello');205		assert.equal(stdout, 'Hello World');206	});207208	test('Uses PATHEXT extension order for direct executables', async t => {209		const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');210		await mkdir(binaryDirectory, {recursive: true});211		const command = 'node-extension-order';212		const executablePath = path.join(binaryDirectory, `${command}.exe`);213		const comPath = path.join(binaryDirectory, `${command}.com`);214		await Promise.all([215			cp(process.execPath, executablePath),216			cp(process.execPath, comPath),217		]);218		t.after(async () => {219			await Promise.all([unlink(executablePath), unlink(comPath)]);220		});221		const options = {222			preferLocal: true,223			localDir: FIXTURES_DIRECTORY,224			extendEnv: false,225			env: {226				Path: path.dirname(process.execPath),227				PathExt: '.EXE;.COM',228			},229		};230		const nodeExpression = 'JSON.stringify({executablePath: process.execPath, argv0: process.argv0})';231		const {stdout} = await execa(command, ['--print', nodeExpression], options);232		const {executablePath: actualExecutablePath, argv0} = JSON.parse(stdout);233		assert.equal(actualExecutablePath.toLowerCase(), executablePath.toLowerCase());234		assert.equal(argv0, command);235236		const {stdout: stdoutSync} = execaSync(command, ['--print', nodeExpression], options);237		const {executablePath: actualExecutablePathSync, argv0: argv0Sync} = JSON.parse(stdoutSync);238		assert.equal(actualExecutablePathSync.toLowerCase(), executablePath.toLowerCase());239		assert.equal(argv0Sync, command);240	});241242	test('Respects NoDefaultCurrentDirectoryInExePath', async t => {243		const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');244		await mkdir(binaryDirectory, {recursive: true});245		const command = 'node-current-directory';246		const currentDirectoryExecutable = path.join(FIXTURES_DIRECTORY, `${command}.exe`);247		const pathExecutable = path.join(binaryDirectory, `${command}.exe`);248		await Promise.all([249			cp(process.execPath, currentDirectoryExecutable),250			cp(process.execPath, pathExecutable),251		]);252253		const environmentName = 'NoDefaultCurrentDirectoryInExePath';254		const originalValue = process.env[environmentName];255		delete process.env[environmentName];256		t.after(async () => {257			if (originalValue === undefined) {258				delete process.env[environmentName];259			} else {260				process.env[environmentName] = originalValue;261			}262263			await Promise.all([unlink(currentDirectoryExecutable), unlink(pathExecutable)]);264		});265266		const options = {267			cwd: FIXTURES_DIRECTORY,268			extendEnv: false,269			env: {270				Path: binaryDirectory,271				PathExt: '.EXE',272			},273		};274		const {stdout: currentDirectoryStdout} = await execa(command, ['--print', 'process.execPath'], options);275		assert.equal(currentDirectoryStdout.toLowerCase(), currentDirectoryExecutable.toLowerCase());276277		const {stdout: currentDirectoryStdoutSync} = execaSync(command, ['--print', 'process.execPath'], options);278		assert.equal(currentDirectoryStdoutSync.toLowerCase(), currentDirectoryExecutable.toLowerCase());279280		process.env[environmentName] = '1';281		const {stdout} = await execa(command, ['--print', 'process.execPath'], options);282		assert.equal(stdout.toLowerCase(), pathExecutable.toLowerCase());283284		const {stdout: stdoutSync} = execaSync(command, ['--print', 'process.execPath'], options);285		assert.equal(stdoutSync.toLowerCase(), pathExecutable.toLowerCase());286	});287288	test('Uses the resolved batch file when current-directory search is disabled', async t => {289		const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');290		await mkdir(binaryDirectory, {recursive: true});291		const command = 'batch-current-directory';292		const currentDirectoryBatchFile = path.join(FIXTURES_DIRECTORY, `${command}.cmd`);293		const pathBatchFile = path.join(binaryDirectory, `${command}.cmd`);294		await Promise.all([295			writeFile(currentDirectoryBatchFile, '@echo current directory'),296			writeFile(pathBatchFile, '@echo PATH'),297		]);298299		const environmentName = 'NoDefaultCurrentDirectoryInExePath';300		const originalValue = process.env[environmentName];301		delete process.env[environmentName];302		t.after(async () => {303			if (originalValue === undefined) {304				delete process.env[environmentName];305			} else {306				process.env[environmentName] = originalValue;307			}308309			await Promise.all([unlink(currentDirectoryBatchFile), unlink(pathBatchFile)]);310		});311312		const options = {313			cwd: FIXTURES_DIRECTORY,314			extendEnv: false,315			env: {316				Path: binaryDirectory,317				PathExt: '.CMD',318				[environmentName]: '',319			},320		};321		const {stdout} = await execa(command, options);322		assert.equal(stdout, 'PATH');323324		const {stdout: stdoutSync} = execaSync(command, options);325		assert.equal(stdoutSync, 'PATH');326327		delete options.env[environmentName];328		process.env[environmentName] = '';329		const {stdout: parentEnvironmentStdout} = await execa(command, options);330		assert.equal(parentEnvironmentStdout, 'PATH');331332		const {stdout: parentEnvironmentStdoutSync} = execaSync(command, options);333		assert.equal(parentEnvironmentStdoutSync, 'PATH');334	});335336	test('Does not search PATH for drive-relative commands', async t => {337		const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');338		await mkdir(binaryDirectory, {recursive: true});339		const commandName = 'node-drive-relative';340		const pathExecutable = path.join(binaryDirectory, `${commandName}.exe`);341		await cp(process.execPath, pathExecutable);342		t.after(async () => {343			await unlink(pathExecutable);344		});345		const drive = path.parse(FIXTURES_DIRECTORY).root.slice(0, 2);346		const command = `${drive}${commandName}`;347		const options = {348			cwd: FIXTURES_DIRECTORY,349			extendEnv: false,350			env: {351				Path: binaryDirectory,352				PathExt: '.EXE',353			},354		};355		await assertRejects(execa(command, [], options));356		assertThrows(() => execaSync(command, [], options));357	});358359	// A `.cmd` file needs `cmd.exe`, so its forward-slash path must be normalized to360	// backslashes, otherwise it fails with ENOENT.361	test('Runs a .cmd file given as a relative POSIX-style subpath', async () => {362		const {stdout} = await execa('fixtures/hello.cmd', {cwd: path.join(FIXTURES_DIRECTORY, '..')});363		assert.equal(stdout, 'Hello World');364	});365366	/*367	Metacharacters must survive `cmd.exe` interpreting them twice for batch files: once when the batch file is invoked and once when it re-expands the arguments with `%*`.368	The `cmd`-shims npm generates in `node_modules/.bin/` are the canonical example.369	*/370	const setupCmdShim = async () => {371		const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');372		await mkdir(binaryDirectory, {recursive: true});373		const shimPath = path.join(binaryDirectory, 'echo-cmd-shim.cmd');374		await cp(path.join(FIXTURES_DIRECTORY, 'echo-cmd-shim.cmd'), shimPath);375		return shimPath;376	};377378	test('Escapes metacharacters for node_modules/.bin cmd-shims', async () => {379		const shimPath = await setupCmdShim();380		const commandArgument = '"(foo|bar>baz|foz)"';381		const {stdout} = await execa(shimPath, [commandArgument]);382		assert.equal(stdout, commandArgument);383384		const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]);385		assert.equal(stdoutSync, commandArgument);386	});387388	test('Escapes metacharacters for explicit batch files excluded from PATHEXT', async () => {389		const commandArgument = '"& whoami &"';390		const command = path.join(FIXTURES_DIRECTORY, 'echo-shim.cmd');391		const {stdout} = await execa(command, [commandArgument], nodeOnlyOptions);392		assert.equal(stdout, commandArgument);393394		const {stdout: stdoutSync} = execaSync(command, [commandArgument], nodeOnlyOptions);395		assert.equal(stdoutSync, commandArgument);396	});397398	test('Runs an explicit shebang script excluded from PATHEXT', async () => {399		const command = path.join(FIXTURES_DIRECTORY, 'echo.js');400		await testResolvesCommand(command, nodeOnlyOptions);401	});402403	test('Escapes metacharacters for preferLocal cmd-shims', async () => {404		await setupCmdShim();405		const commandArgument = 'a&whoami';406		const originalPathExt = process.env.PATHEXT;407		process.env.PATHEXT = '.EXE';408		const options = {409			preferLocal: true,410			localDir: FIXTURES_DIRECTORY,411			extendEnv: false,412			env: {413				Path: path.dirname(process.execPath),414				PathExt: '.EXE;.CMD',415			},416		};417418		try {419			const {stdout} = await execa('echo-cmd-shim', [commandArgument], options);420			assert.equal(stdout, commandArgument);421422			const {stdout: stdoutSync} = execaSync('echo-cmd-shim', [commandArgument], options);423			assert.equal(stdoutSync, commandArgument);424		} finally {425			if (originalPathExt === undefined) {426				delete process.env.PATHEXT;427			} else {428				process.env.PATHEXT = originalPathExt;429			}430		}431	});432}433434// On Windows, `.cmd`/`.bat` files are run through `cmd.exe`, which interprets several435// characters specially. Those must be escaped in arguments, otherwise they could expand436// variables or inject commands (the "BatBadBut" class of vulnerabilities). `echo-shim.cmd`437// forwards its arguments to `echo.js`, so the subprocess prints back the exact438// `process.argv` it received: each argument must arrive unchanged and inert.439if (isWindows) {440	const testEscaping = async commandArgument => {441		const {stdout} = await execa('echo-shim.cmd', [commandArgument]);442		assert.equal(stdout, commandArgument);443444		const {stdout: stdoutSync} = execaSync('echo-shim.cmd', [commandArgument]);445		assert.equal(stdoutSync, commandArgument);446	};447448	// A `%VAR%` argument must be passed literally, not expanded by `cmd.exe`.449	test('Does not expand environment variables in arguments', () => testEscaping('%PATH%'));450	// Delayed expansion (`!VAR!`) must not be interpreted either.451	test('Does not expand delayed environment variables in arguments', () => testEscaping('!PATH!'));452	// An `&` must not be interpreted as a command separator.453	test('Does not allow command injection via `&` in arguments', () => testEscaping('a&b'));454	// A `|` must not be interpreted as a pipe.455	test('Does not allow command injection via `|` in arguments', () => testEscaping('a|whoami'));456	// Redirections (`<`, `>`) must not be interpreted.457	test('Does not allow command injection via redirections in arguments', () => testEscaping('a>b<c'));458	// Parentheses must not be interpreted as command grouping.459	test('Does not allow command injection via parentheses in arguments', () => testEscaping('(whoami)'));460	// A quote followed by an injected command must stay inert.461	test('Does not allow command injection via nested quotes in arguments', () => testEscaping('"& whoami &"'));462	// Double quotes must be preserved.463	test('Preserves double quotes in arguments', () => testEscaping('a"b"c'));464	// Carets are the escape character in `cmd.exe` and must be passed literally.465	test('Preserves carets in arguments', () => testEscaping('a^b^^c'));466	// Backslashes, including trailing ones, must be preserved next to quotes.467	test('Preserves backslashes and double quotes in arguments', () => testEscaping('a\\"b\\\\"c\\'));468469	// Every kind of tricky argument must also roundtrip through `cmd.exe` unchanged, not470	// just be inert. Unlike `echo.js` (which resolves to `node.exe` and bypasses `cmd.exe`),471	// `echo-shim.cmd` forces the `cmd.exe` escaping path. This mirrors the roundtrip tests472	// above, but validates the `cmd.exe`-specific escaping rather than Node's native escaping.473	const testCmdRoundtrip = async commandArguments => {474		const expectedStdout = commandArguments.join('\n');475476		const {stdout} = await execa('echo-shim.cmd', commandArguments);477		assert.equal(stdout, expectedStdout);478479		const {stdout: stdoutSync} = execaSync('echo-shim.cmd', commandArguments);480		assert.equal(stdoutSync, expectedStdout);481	};482483	// eslint-disable-next-line no-template-curly-in-string484	test('Roundtrips shell metacharacters through cmd.exe', () => testCmdRoundtrip(['()', '[]', '%!', '^', '<', '>', '|', ';', ',', '=', '`', '*', '?', '$HOME', '${x}', '~']));485	test('Roundtrips backslashes and double quotes through cmd.exe', () => testCmdRoundtrip(['a\\b', 'a\\\\b', 'a\\', 'a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']));486	// Long backslash runs must also roundtrip through the `cmd.exe` escaping specifically,487	// which is where the backslash-doubling actually runs. Kept modest to stay under the488	// `cmd.exe` command-line length limit once the backslashes are doubled.489	test('Roundtrips long backslash runs before quotes through cmd.exe', () => testCmdRoundtrip([`${'\\'.repeat(200)}"`, '\\'.repeat(200), `a${'\\'.repeat(100)}"b`]));490	// The per-length sweep must roundtrip through `cmd.exe` too, since the corrupted doubling491	// is exactly what this escaping path performs.492	test('Roundtrips backslash runs of every length through cmd.exe', () => testCmdRoundtrip(backslashRunArguments));493	// Consecutive double quotes must survive the `cmd.exe` escaping, each escaped on its own.494	test('Roundtrips consecutive double quotes through cmd.exe', () => testCmdRoundtrip(['""', '"""', 'a""b', '""""']));495	test('Roundtrips arguments with spaces through cmd.exe', () => testCmdRoundtrip(['a b', ' '.repeat(3), 'foo bar baz', 'André Cruz']));496497	/*498	`.bat` files re-expand their arguments through `cmd.exe` exactly like `.cmd` files, so they need the same escaping.499	`echo-shim.bat` is the `.bat` twin of `echo-shim.cmd`.500	*/501	const testBatEscaping = async commandArgument => {502		const {stdout} = await execa('echo-shim.bat', [commandArgument]);503		assert.equal(stdout, commandArgument);504505		const {stdout: stdoutSync} = execaSync('echo-shim.bat', [commandArgument]);506		assert.equal(stdoutSync, commandArgument);507	};508509	// The same nested-quote injection must stay inert when the batch file is a `.bat`.510	test('Does not allow command injection via nested quotes in `.bat` arguments', () => testBatEscaping('"& whoami &"'));511	// Metacharacters must survive the double `cmd.exe` expansion for `.bat` files too.512	test('Roundtrips shell metacharacters through a `.bat` file', () => testBatEscaping('(foo|bar>baz|foz)'));513	// A `.bat` file not in `node_modules/.bin/` must still be escaped against the double expansion, since the location is irrelevant: any batch file can re-expand its arguments.514	test('Does not expand environment variables in `.bat` arguments', () => testBatEscaping('%PATH%'));515	// Backslashes, double quotes and metacharacters combined are the trickiest to escape, and must survive the double `cmd.exe` expansion of a `.bat` file intact.516	test('Preserves backslashes, quotes and metacharacters in `.bat` arguments', () => testBatEscaping('a\\"&b\\\\"|c\\'));517	// Several tricky arguments passed together must each be escaped independently and arrive in order, not merged nor reordered.518	test('Roundtrips multiple tricky arguments through a `.bat` file', async () => {519		const commandArguments = ['a b', 'c&d', '"e"', 'f\\"g', '%h%'];520		const expectedStdout = commandArguments.join('\n');521522		const {stdout} = await execa('echo-shim.bat', commandArguments);523		assert.equal(stdout, expectedStdout);524525		const {stdout: stdoutSync} = execaSync('echo-shim.bat', commandArguments);526		assert.equal(stdoutSync, expectedStdout);527	});528529	/*530	Unlike cmd-shims, some batch files read their own arguments with `%1` or `%~1` instead of forwarding them with `%*`, like Maven's `mvn.cmd`.531	`read-arguments.cmd` prints its first argument, then its second one when the first one is `-f`.532	`ECHO` ends lines with CRLF.533	*/534	const testReadArguments = async (commandArguments, expectedLines) => {535		const {stdout} = await execa('read-arguments.cmd', commandArguments);536		assert.deepEqual(stdout.split('\r\n'), expectedLines);537538		const {stdout: stdoutSync} = execaSync('read-arguments.cmd', commandArguments);539		assert.deepEqual(stdoutSync.split('\r\n'), expectedLines);540	};541542	test('Passes arguments to batch files reading them with `%~1`', () => testReadArguments(['-f', 'C:\\repo\\pom.xml'], ['first is -f', 'file is "C:\\repo\\pom.xml"']));543	test('Passes metacharacters to batch files reading them with `%~1`', () => testReadArguments(['-f', 'C:\\my repo\\a&b|c%PATH%.xml'], ['first is -f', 'file is "C:\\my repo\\a&b|c%PATH%.xml"']));544	// Like Rust, only arguments that need quoting are quoted, so `%1` matches what the user passed, like when run from a terminal545	test('Only quotes arguments that need it for batch files reading them with `%1`', () => testReadArguments(['a b'], ['first is "a b"']));546547	// `cmd.exe` interprets CR and LF as command separators and provides no way to escape548	// them, so those are rejected to prevent command injection.549	test('Rejects arguments containing a line break', () => {550		assertThrows(() => execa('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});551		assertThrows(() => execaSync('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});552	});553554	// The command itself is validated too, not just its arguments.555	test('Rejects a command containing a line break', () => {556		assertThrows(() => execa('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});557		assertThrows(() => execaSync('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});558	});559560	// A shell escapes the arguments itself, so the line break rejection does not apply.561	test('Does not reject line breaks when using a shell', async () => {562		await assert.doesNotReject(execa('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));563		assert.doesNotThrow(() => execaSync('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));564	});565}