Fix `preferLocal` argument escaping edge-case on Windows (#1259)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by GitHub · parent 499fe80 · Browse files · 5 files·+269 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+269 added−15 removed
- tests:+212 added−2 removed
- other:+57 added−13 removed
Provenance
- Commit
e771733- Tree
24b4d08- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
499fe80
5 files changed+269 added−15 removed
modified:lib/arguments/command-file.js+48 added-7 removed
123456678918 unmodified lines282930313332333435363738394041425 unmodified lines4849505148525354555621 unmodified lines787980817879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712873 unmodified linesimport {openSync, readSync, closeSync} from 'node:fs';import {Buffer} from 'node:buffer';import path from 'node:path';import process from 'node:process';import {whichCommandSync} from 'which-command';import pathKey from 'path-key';
/*On Windows, `node:child_process` cannot natively run many kinds of files (`.cmd`, `.bat`, shebang scripts, ...): without a shell it resolves neither `PATHEXT` nor shebangs, and it does not escape arguments. We resolve the command to its full file path and escape its arguments ourselves, so those work without an explicit shell, just like on Unix, where the OS handles all of this for us.*/18 unmodified linesconst escapeWindowsCommand = parsed => { // Resolve the file to an absolute path, following its shebang to the interpreter if any const resolvedFile = resolveWithShebang(parsed);
// A directly executable file is spawned as-is, bypassing `cmd.exe` and its escaping // A directly executable file is spawned by its resolved path, bypassing `cmd.exe` and its escaping if (resolvedFile !== undefined && directlyExecutableRegExp.test(resolvedFile)) { if (parsed.options.argv0 === undefined) { parsed.options.argv0 = parsed.file; }
parsed.file = resolvedFile; return parsed; }
/*5 unmodified lines }
const isDoubleEscape = resolvedFile !== undefined && batchFileRegExp.test(resolvedFile); // POSIX separators must become Windows ones (`foo/bar` -> `foo\bar`), otherwise resolution always fails with ENOENT const escapedFile = escapeMetaChars(path.normalize(parsed.file)); const escapedFile = escapeMetaChars(path.normalize(resolvedFile ?? parsed.file)); const escapedArguments = parsed.commandArguments.map(argument => escapeArgument(argument, isDoubleEscape)); const commandLine = `"${[escapedFile, ...escapedArguments].join(' ')}"`;
// Let `node:child_process` pass the already-escaped command line through untouched21 unmodified lines
// Search `PATH` for the command, resolving its Windows executable extension via `PATHEXT`const resolvePath = parsed => { const environment = parsed.options.env || process.env; return whichCommandSync(parsed.file, { cwd: parsed.options.cwd, path: environment[pathKey({env: environment})], }); const cwd = parsed.options.cwd ?? process.cwd(); const environmentPathExt = getWindowsEnvironmentValue(environment, 'PATHEXT'); const commandExtension = path.extname(parsed.file); // Commands with an explicit extension must be tried verbatim so shebang scripts work even when their extension is excluded from PATHEXT. const pathExt = commandExtension === '' ? environmentPathExt : `${commandExtension}${path.delimiter}${environmentPathExt ?? ''}`; if (hasWindowsPathSeparator(parsed.file)) { return whichCommandSync(path.resolve(cwd, parsed.file), {cwd, pathExt}); }
const searchPath = getWindowsEnvironmentValue(environment, 'PATH') ?? getWindowsEnvironmentValue(process.env, 'PATH') ?? ''; const resolveOptions = { cwd, path: searchPath, pathExt, };
return shouldSearchCurrentDirectory(environment) ? whichCommandSync(parsed.file, resolveOptions) : resolvePathDirectories(parsed.file, resolveOptions);};
const hasWindowsPathSeparator = file => file.includes('/') || file.includes('\\') || file.includes(':');
const shouldSearchCurrentDirectory = environment => getWindowsEnvironmentValue(process.env, 'NODEFAULTCURRENTDIRECTORYINEXEPATH') === undefined && getWindowsEnvironmentValue(environment, 'NODEFAULTCURRENTDIRECTORYINEXEPATH') === undefined;
const resolvePathDirectories = (file, {cwd, path: searchPath, pathExt}) => { for (const directory of searchPath.split(path.delimiter)) { const unquotedDirectory = directory.length > 1 && directory.startsWith('"') && directory.endsWith('"') ? directory.slice(1, -1) : directory; if (unquotedDirectory === '') { continue; }
const resolvedFile = whichCommandSync(path.resolve(cwd, unquotedDirectory, file), {cwd, pathExt}); if (resolvedFile !== undefined) { return resolvedFile; } }};
// Node sorts Windows environment keys and uses the first case-insensitive match when spawning.const getWindowsEnvironmentValue = (environment, name) => { const environmentKey = Object.keys(environment).sort().find(key => key.toUpperCase() === name); return environmentKey === undefined ? undefined : environment[environmentKey];};
const SHEBANG_BYTE_LENGTH = 150;
// Read the file's first bytes to find its shebang interpreter, if it has oneconst readShebang = file => {73 unmodified linesmodified:lib/arguments/options.js+8 added-5 removed
12 unmodified lines13 import {normalizeCwd} from './cwd.js';14 import {normalizeFileUrl} from './file-url.js';15 import {normalizeFdSpecificOptions} from './specific.js';16 17+const cmdExeRegExp = /^cmd(?:\.exe)?$/i;18+19 // Normalize the options object, and sometimes also the file paths and arguments.20 // Applies default values, validate allowed options, normalize them.21 export const normalizeOptions = (filePath, rawArguments, rawOptions) => {22 // Prevent prototype pollution by copying only own properties to a null-prototype object23 const sanitizedOptions = {__proto__: null, ...rawOptions};24 sanitizedOptions.cwd = normalizeCwd(sanitizedOptions.cwd);25 const [processedFile, processedArguments, processedOptions] = handleNodeOption(filePath, rawArguments, sanitizedOptions);26+ const fdOptions = normalizeFdSpecificOptions(processedOptions);27+ const options = addDefaultOptions(fdOptions);28+ options.env = getEnv(options);29 25- const {file, commandArguments, options: initialOptions} = parseCommandFile(processedFile, processedArguments, processedOptions);30+ const {file, commandArguments} = parseCommandFile(processedFile, processedArguments, options);31 27- const fdOptions = normalizeFdSpecificOptions(initialOptions);28- const options = addDefaultOptions(fdOptions);32 validateTimeout(options);33 validateEncoding(options);34 validateIpcInputOption(options);35 validateCancelSignal(options);36 validateGracefulCancel(options);37 options.shell = normalizeFileUrl(options.shell);35- options.env = getEnv(options);38 options.killSignal = normalizeKillSignal(options.killSignal);39 options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);40 options.lines = options.lines.map((lines, fdNumber) => lines && !BINARY_ENCODINGS.has(options.encoding) && options.buffer[fdNumber]);41 40- if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {42+ // The file is now an absolute path resolved via `PATHEXT`, so its extension might be uppercase (`cmd.EXE`)43+ if (process.platform === 'win32' && cmdExeRegExp.test(path.basename(file))) {44 // #11645 commandArguments.unshift('/q');46 }47 58 unmodified linesmodified:test/arguments/command-resolution.js+210 added-1 removed
1-import {cp, mkdir} from 'node:fs/promises';1+import {2+ cp,3+ mkdir,4+ unlink,5+ writeFile,6+} from 'node:fs/promises';7 import path from 'node:path';8 import process from 'node:process';9 import test from 'ava';10 import {execa, execaSync} from '../../index.js';159 unmodified lines170 test('Does not mutate arguments nor options', testNoMutation, {});171 test('Does not mutate arguments nor options with a shell', testNoMutation, {shell: true});172 173 if (isWindows) {174+ const nodeOnlyOptions = {175+ extendEnv: false,176+ env: {177+ Path: path.dirname(process.execPath),178+ PathExt: '.EXE',179+ },180+ };181+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 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);215+216+ 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+ });221+222+ 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+ ]);232+233+ 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+ }242+243+ await Promise.all([unlink(currentDirectoryExecutable), unlink(pathExecutable)]);244+ });245+246+ 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());256+257+ const {stdout: currentDirectoryStdoutSync} = execaSync(command, ['--print', 'process.execPath'], options);258+ t.is(currentDirectoryStdoutSync.toLowerCase(), currentDirectoryExecutable.toLowerCase());259+260+ process.env[environmentName] = '1';261+ const {stdout} = await execa(command, ['--print', 'process.execPath'], options);262+ t.is(stdout.toLowerCase(), pathExecutable.toLowerCase());263+264+ const {stdout: stdoutSync} = execaSync(command, ['--print', 'process.execPath'], options);265+ t.is(stdoutSync.toLowerCase(), pathExecutable.toLowerCase());266+ });267+268+ 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+ ]);278+279+ 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+ }288+289+ await Promise.all([unlink(currentDirectoryBatchFile), unlink(pathBatchFile)]);290+ });291+292+ 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');303+304+ const {stdout: stdoutSync} = execaSync(command, options);305+ t.is(stdoutSync, 'PATH');306+307+ delete options.env[environmentName];308+ process.env[environmentName] = '';309+ const {stdout: parentEnvironmentStdout} = await execa(command, options);310+ t.is(parentEnvironmentStdout, 'PATH');311+312+ const {stdout: parentEnvironmentStdoutSync} = execaSync(command, options);313+ t.is(parentEnvironmentStdoutSync, 'PATH');314+ });315+316+ 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+339 // A `.cmd` file needs `cmd.exe`, so its forward-slash path must be normalized to340 // 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, '..')});20 unmodified lines363 364 const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]);365 t.is(stdoutSync, commandArgument);366 });367+368+ 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);373+374+ const {stdout: stdoutSync} = execaSync(command, [commandArgument], nodeOnlyOptions);375+ t.is(stdoutSync, commandArgument);376+ });377+378+ 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+ });382+383+ 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+ };397+398+ try {399+ const {stdout} = await execa('echo-cmd-shim', [commandArgument], options);400+ t.is(stdout, commandArgument);401+402+ 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+ }411+ });412 }413 414 // On Windows, `.cmd`/`.bat` files are run through `cmd.exe`, which interprets several415 // characters specially. Those must be escaped in arguments, otherwise they could expand112 unmodified linesmodified:test/terminate/timeout.js+2 added-1 removed
19 unmodified lines20 });21 t.true(isTerminated);22 t.is(signal, 'SIGTERM');23 t.true(timedOut);24- t.is(originalMessage, 'spawnSync node ETIMEDOUT');24+ // On Windows, the command is spawned using the absolute path resolved via `PATHEXT`, so it appears in Node.js' own error message25+ t.regex(originalMessage, /^spawnSync .*node(?:\.[A-Za-z]+)? ETIMEDOUT$/);26 t.is(shortMessage, `Command timed out after 1 milliseconds: node forever.js\n${originalMessage}`);27 t.is(message, shortMessage);28 });29 48 unmodified linesmodified:package.json+1 added-1 removed
56 unmodified lines57 "human-signals": "^8.0.1",58 "is-plain-obj": "^4.1.0",59 "is-stream": "^4.0.1",60 "npm-run-path": "^6.0.0",61- "path-key": "^4.0.0",61 "pretty-ms": "^9.3.0",62 "signal-exit": "^4.1.0",63 "strip-final-newline": "^4.0.0",64 "which-command": "^0.1.0",7 unmodified lines72 "is-in-ci": "^2.0.0",73 "is-running": "^2.1.0",74 "log-process-errors": "^12.0.1",75 "path-exists": "^5.0.0",76+ "path-key": "^4.0.0",77 "tempfile": "^6.0.1",78 "tsd": "^0.33.0",79 "typescript": "^6.0.3",80 "xo": "^4.0.0"50 unmodified lines