diff --git a/package-lock.json b/package-lock.json index afef3911..cfd4231f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "license": "Apache-2.0", "dependencies": { "@yarnpkg/parsers": "^3.1.0", + "cross-spawn": "^7.0.6", "eslint-import-resolver-typescript": "^4.4.4", "fast-glob": "^3.3.3", "fast-xml-parser": "^5.3.4", @@ -1787,7 +1788,6 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, "license": "MIT", "dependencies": { "path-key": "^3.1.0", @@ -1802,14 +1802,12 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, "license": "ISC" }, "node_modules/cross-spawn/node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -3369,7 +3367,6 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -3604,7 +3601,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -3617,7 +3613,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" diff --git a/package.json b/package.json index d472dd25..1d102756 100644 --- a/package.json +++ b/package.json @@ -50,6 +50,7 @@ }, "dependencies": { "@yarnpkg/parsers": "^3.1.0", + "cross-spawn": "^7.0.6", "eslint-import-resolver-typescript": "^4.4.4", "fast-glob": "^3.3.3", "fast-xml-parser": "^5.3.4", diff --git a/src/tools.js b/src/tools.js index 4909f9ba..a9f01084 100644 --- a/src/tools.js +++ b/src/tools.js @@ -1,8 +1,8 @@ -import { execFileSync } from "child_process"; import fs from 'node:fs' import path from 'node:path' import { EOL } from "os"; +import spawn from 'cross-spawn' import { HttpsProxyAgent } from "https-proxy-agent"; import { PackageURL } from "packageurl-js"; @@ -232,20 +232,14 @@ export function resolveBinary(globalBinary, localWrapper, startDir, opts = {}) { /** this method invokes command string in a process in a synchronous way. * @param {string} bin - the command to be invoked * @param {Array} args - the args to pass to the binary - * @param {import('child_process').ExecFileOptionsWithStringEncoding} [opts={}] + * @param {import('child_process').SpawnSyncOptionsWithStringEncoding} [opts={}] * @returns {string} */ export function invokeCommand(bin, args, opts={}) { - // .bat and .cmd files can't be executed in windows with execFileSync without {shell: true}, so we - // special case them here to keep the amount of escaping we need to do to a minimum. + // Let cross-spawn handle Windows batch wrappers and npm shims without enabling shell:true + // or pre-quoting native executable paths/arguments. Batch files still require cmd.exe: // https://nodejs.org/docs/latest-v20.x/api/child_process.html#spawning-bat-and-cmd-files-on-windows // https://github.com/nodejs/node/issues/52681#issuecomment-2076426887 - if (process.platform === 'win32') { - opts = {...opts, shell: true} - args = args.map(arg => handleSpacesInPath(arg)) - bin = handleSpacesInPath(bin) - } - opts = { ...opts, env: { @@ -261,7 +255,16 @@ export function invokeCommand(bin, args, opts={}) { maxBuffer: 10 * 1024 * 1024 // 10MB buffer }; - return execFileSync(bin, args, {...{stdio: 'pipe', encoding: 'utf-8'}, ...opts}) + const result = spawn.sync(bin, args, {stdio: 'pipe', encoding: 'utf-8', ...opts}) + // Unlike execFileSync, spawn.sync returns failures instead of throwing them. + if (result.error) { + const { error, ...rest } = result + throw Object.assign(error, rest) + } + if (result.status !== 0) { + throw Object.assign(new Error(`Command failed: ${bin} ${args.join(' ')}\n${result.stderr || ''}`), result) + } + return result.stdout } diff --git a/test/tools.test.js b/test/tools.test.js index 8d4fd376..6816250a 100644 --- a/test/tools.test.js +++ b/test/tools.test.js @@ -1,8 +1,12 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' + import { expect } from 'chai' import esmock from 'esmock' import { afterEach } from 'mocha' -import { getCustom, getCustomPath } from "../src/tools.js" +import { getCustom, getCustomPath, invokeCommand } from "../src/tools.js" /** @@ -192,3 +196,98 @@ suite('testing the various tools and utility functions', () => { }) + +suite('invokeCommand', function () { + this.timeout(10000) + const windowsTest = process.platform === 'win32' ? test : test.skip + let directory + + suiteSetup(() => { + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'trustify-da tools &-')) + }) + + suiteTeardown(() => fs.rmSync(directory, { recursive: true, force: true })) + + /** Catches shell interpretation/pre-quoting of native paths and dropped cwd/stdin options. */ + test('passes literal arguments to native executables in paths with spaces and ampersands', () => { + const bin = path.join(directory, path.basename(process.execPath)) + fs.copyFileSync(process.execPath, bin) + const args = ['a&b', 'two words', '', 'a"b', '%PATH%', '!value!', 'tail\\'] + const script = 'process.stdout.write(JSON.stringify({args:process.argv.slice(1),cwd:process.cwd(),input:require("node:fs").readFileSync(0,"utf8")}))' + const result = JSON.parse(invokeCommand(bin, ['-e', script, '--', ...args], { + cwd: directory, input: 'stdin content' + })) + expect(result).to.deep.equal({ args, cwd: fs.realpathSync(directory), input: 'stdin content' }) + }) + + /** Catches reverting our output buffer to spawnSync's 1 MiB default. */ + test('captures dependency-tree output larger than 1 MiB', () => { + const result = invokeCommand(process.execPath, ['-e', 'process.stdout.write("x".repeat(2 * 1024 * 1024))']) + expect(result).to.equal('x'.repeat(2 * 1024 * 1024)) + }) + + /** Catches returning stdout instead of throwing when a tool exits unsuccessfully. */ + test('throws nonzero exits with captured output and status', () => { + const run = () => invokeCommand(process.execPath, ['-e', + 'require("node:fs").writeSync(1,"partial output");require("node:fs").writeSync(2,"tool failed");process.exit(7)']) + expect(run).to.throw(Error, 'tool failed').that.includes({ + status: 7, stdout: 'partial output', stderr: 'tool failed' + }) + }) + + /** Catches losing spawn details or creating a circular error during enrichment. */ + test('throws a serializable ENOENT for an unavailable tool', () => { + let error + try { + invokeCommand('trustify-da-command-that-does-not-exist', []) + } catch (caught) { + error = caught + } + expect(error).to.be.instanceOf(Error).with.property('code', 'ENOENT') + expect(error).to.include.all.keys('status', 'stdout', 'stderr') + expect(() => JSON.stringify(error)).not.to.throw() + }) + + /** Catches accepting a killed process or making its timeout error circular. */ + test('throws a serializable error when a tool times out', () => { + let error + try { + invokeCommand(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { timeout: 100 }) + } catch (caught) { + error = caught + } + expect(error).to.be.instanceOf(Error).with.property('code', 'ETIMEDOUT') + expect(error).to.include.all.keys('status', 'stdout', 'stderr') + expect(() => JSON.stringify(error)).not.to.throw() + }) + + /** Exercises real cmd.exe wrapper execution, not a reconstruction of its escaped command string. */ + windowsTest('runs Maven/Gradle-style batch wrappers', () => { + for (const name of ['mvnw.cmd', 'gradlew.bat']) { + const wrapper = path.join(directory, name) + fs.writeFileSync(wrapper, '@echo off\r\necho %1\r\n') + expect(invokeCommand(wrapper, ['project path & data'], { cwd: directory }).trim()) + .to.equal('"project path & data"') + } + }) + + /** Exercises npm shim reparsing and PATHEXT lookup for both explicit and extensionless names. */ + windowsTest('runs npm .bin shims with literal arguments', () => { + const shimDirectory = path.join(directory, 'node_modules', '.bin') + fs.mkdirSync(shimDirectory, { recursive: true }) + const script = path.join(directory, 'argv.cjs') + fs.writeFileSync(script, 'process.stdout.write(JSON.stringify(process.argv.slice(2)))') + const shim = path.join(shimDirectory, 'argv.cmd') + fs.writeFileSync(shim, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`) + const args = ['project path & data', '"(foo|bar>baz)"', '', '%PATH%', '!value!'] + const originalPath = process.env.PATH + try { + process.env.PATH = `${shimDirectory}${path.delimiter}${originalPath}` + for (const command of ['argv', 'argv.cmd']) { + expect(JSON.parse(invokeCommand(command, args, { cwd: directory }))).to.deep.equal(args) + } + } finally { + process.env.PATH = originalPath + } + }) +})