Skip to content
Myr

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

5 files+269 added−15 removed

modified:lib/arguments/command-file.js+48 added-7 removed
modified:lib/arguments/options.js+8 added-5 removed
12 unmodified lines
13import {normalizeCwd} from './cwd.js';14import {normalizeFileUrl} from './file-url.js';15import {normalizeFdSpecificOptions} from './specific.js';1617const cmdExeRegExp = /^cmd(?:\.exe)?$/i;1819// Normalize the options object, and sometimes also the file paths and arguments.20// Applies default values, validate allowed options, normalize them.21export 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);2925 const {file, commandArguments, options: initialOptions} = parseCommandFile(processedFile, processedArguments, processedOptions);30 const {file, commandArguments} = parseCommandFile(processedFile, processedArguments, options);3127 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]);4140 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 lines
modified:test/arguments/command-resolution.js+210 added-1 removed
1import {cp, mkdir} from 'node:fs/promises';1import {2 cp,3 mkdir,4 unlink,5 writeFile,6} from 'node:fs/promises';7import path from 'node:path';8import process from 'node:process';9import test from 'ava';10import {execa, execaSync} from '../../index.js';
159 unmodified lines
170test('Does not mutate arguments nor options', testNoMutation, {});171test('Does not mutate arguments nor options with a shell', testNoMutation, {shell: true});172173if (isWindows) {174 const nodeOnlyOptions = {175 extendEnv: false,176 env: {177 Path: path.dirname(process.execPath),178 PathExt: '.EXE',179 },180 };181182 // 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 });187188 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 });338339 // 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 lines
363364 const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]);365 t.is(stdoutSync, commandArgument);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 }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 expand
112 unmodified lines
modified:test/terminate/timeout.js+2 added-1 removed
19 unmodified lines
20 });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 lines
modified:package.json+1 added-1 removed
56 unmodified lines
57 "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 lines
72 "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