Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
25 changes: 14 additions & 11 deletions src/tools.js
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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<string>} 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: {
Expand All @@ -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
}


Expand Down
101 changes: 100 additions & 1 deletion test/tools.test.js
Original file line number Diff line number Diff line change
@@ -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"


/**
Expand Down Expand Up @@ -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
}
})
})
Loading