From 5a06340a0f158196d8c772c8b2dffa9e00df8845 Mon Sep 17 00:00:00 2001 From: Adva Oren Date: Wed, 18 Nov 2026 14:36:02 +0200 Subject: [PATCH 1/4] fix(tools): use cross-spawn for Windows commands Replace blanket shell execution and pre-quoting with cross-spawn 7.0.6 for the shared Python, Maven, and Gradle invocation helper. Preserve synchronous stdout, thrown failures, environment handling, and the 10 MiB output buffer. Add real-process contract tests and focused Windows Node 22/24 CI. Keep the Python venv-placement change independent in PR #696. Implements TC-7561 Assisted-by: OpenCode (GPT-6.1 Sol) Signed-off-by: Adva Oren --- .github/workflows/test.yml | 28 +++++++++++- package-lock.json | 7 +-- package.json | 1 + src/tools.js | 24 ++++++----- test/tools.test.js | 87 +++++++++++++++++++++++++++++++++++++- 5 files changed, 128 insertions(+), 19 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e4fe00f0..77ee90d2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,6 +15,33 @@ concurrency: cancel-in-progress: true jobs: + windows-command-tests: + runs-on: windows-latest + name: Windows command invocation (Node ${{ matrix.node }}) + strategy: + matrix: + node: ['22', '24'] + steps: + - name: Checkout sources + uses: actions/checkout@v7 + + - name: Install node ${{ matrix.node }} + uses: actions/setup-node@v7 + with: + node-version: ${{ matrix.node }} + cache: npm + + - name: Install latest npm + run: npm install -g npm@11.11.1 + + - name: Install project modules + run: npm ci + + # The full provider suite currently needs Linux-only tools (including skopeo). + # Exercise real native, batch, and npm-shim execution here, without mocking Windows. + - name: Test command invocation on Windows + run: npm run tests -- test/tools.test.js --grep "^invokeCommand" + test: runs-on: ubuntu-latest name: Lint and test project @@ -120,4 +147,3 @@ jobs: use_oidc: true flags: unit-tests files: ./coverage/lcov.info - diff --git a/package-lock.json b/package-lock.json index afef3911..b3542304 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..e95d0443 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..b207f9ae 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,15 @@ 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) { + throw Object.assign(result.error, result) + } + 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..44bfbbdf 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,84 @@ 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 the error code used by providers to detect unavailable tools. */ + test('throws ENOENT for an unavailable tool', () => { + expect(() => invokeCommand('trustify-da-command-that-does-not-exist', [])) + .to.throw().with.property('code', 'ENOENT') + }) + + /** Catches treating a killed process with null status as successful. */ + test('throws when a tool times out', () => { + expect(() => invokeCommand(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { timeout: 100 })) + .to.throw().with.property('code', 'ETIMEDOUT') + }) + + /** 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 + } + }) +}) From 5ecd32247f6637a907b1b62d0bcc87bc2b627996 Mon Sep 17 00:00:00 2001 From: Adva Oren Date: Wed, 18 Nov 2026 15:23:32 +0200 Subject: [PATCH 2/4] ci: remove native Windows invocation jobs Keep unit CI on Linux; the shared integration workflow already has Windows and macOS runners. Retain Windows-only contract tests for manual runs; they remain skipped on Linux, not counted as passing. The initial Windows jobs failed during checkout of existing OCI fixture filenames containing colons, before any invocation tests ran. Do not include the proposed sparse-checkout workaround. Fix-specific native Windows results remain unverified. Implements TC-7561 Assisted-by: OpenCode (GPT-6.1 Sol) Signed-off-by: Adva Oren --- .github/workflows/test.yml | 28 +--------------------------- 1 file changed, 1 insertion(+), 27 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 77ee90d2..e4fe00f0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,33 +15,6 @@ concurrency: cancel-in-progress: true jobs: - windows-command-tests: - runs-on: windows-latest - name: Windows command invocation (Node ${{ matrix.node }}) - strategy: - matrix: - node: ['22', '24'] - steps: - - name: Checkout sources - uses: actions/checkout@v7 - - - name: Install node ${{ matrix.node }} - uses: actions/setup-node@v7 - with: - node-version: ${{ matrix.node }} - cache: npm - - - name: Install latest npm - run: npm install -g npm@11.11.1 - - - name: Install project modules - run: npm ci - - # The full provider suite currently needs Linux-only tools (including skopeo). - # Exercise real native, batch, and npm-shim execution here, without mocking Windows. - - name: Test command invocation on Windows - run: npm run tests -- test/tools.test.js --grep "^invokeCommand" - test: runs-on: ubuntu-latest name: Lint and test project @@ -147,3 +120,4 @@ jobs: use_oidc: true flags: unit-tests files: ./coverage/lcov.info + From 0f0a345919930d2ffa142400a4774a7aec63f786 Mon Sep 17 00:00:00 2001 From: Adva Oren Date: Wed, 18 Nov 2026 17:10:24 +0200 Subject: [PATCH 3/4] fix(tools): avoid circular spawn errors Exclude the nested error reference when enriching spawn failures so JSON serialization preserves diagnostic fields without a cycle. Cover missing executables and timeouts with real-process assertions. Implements TC-7561 Signed-off-by: Adva Oren --- src/tools.js | 3 ++- test/tools.test.js | 30 ++++++++++++++++++++++-------- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/src/tools.js b/src/tools.js index b207f9ae..a9f01084 100644 --- a/src/tools.js +++ b/src/tools.js @@ -258,7 +258,8 @@ export function invokeCommand(bin, args, 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) { - throw Object.assign(result.error, result) + 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) diff --git a/test/tools.test.js b/test/tools.test.js index 44bfbbdf..6816250a 100644 --- a/test/tools.test.js +++ b/test/tools.test.js @@ -235,16 +235,30 @@ suite('invokeCommand', function () { }) }) - /** Catches losing the error code used by providers to detect unavailable tools. */ - test('throws ENOENT for an unavailable tool', () => { - expect(() => invokeCommand('trustify-da-command-that-does-not-exist', [])) - .to.throw().with.property('code', 'ENOENT') + /** 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 treating a killed process with null status as successful. */ - test('throws when a tool times out', () => { - expect(() => invokeCommand(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { timeout: 100 })) - .to.throw().with.property('code', 'ETIMEDOUT') + /** 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. */ From 597c9919b15ddadd9e8880c1502522a437054ed9 Mon Sep 17 00:00:00 2001 From: Adva Oren Date: Wed, 18 Nov 2026 17:15:14 +0200 Subject: [PATCH 4/4] build(deps): allow compatible cross-spawn updates Use ^7.0.6 for consumers while retaining the locked 7.0.6 version for reproducible repository installs. No resolved dependency changes. Implements TC-7561 Signed-off-by: Adva Oren --- package-lock.json | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index b3542304..cfd4231f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "license": "Apache-2.0", "dependencies": { "@yarnpkg/parsers": "^3.1.0", - "cross-spawn": "7.0.6", + "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/package.json b/package.json index e95d0443..1d102756 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ }, "dependencies": { "@yarnpkg/parsers": "^3.1.0", - "cross-spawn": "7.0.6", + "cross-spawn": "^7.0.6", "eslint-import-resolver-typescript": "^4.4.4", "fast-glob": "^3.3.3", "fast-xml-parser": "^5.3.4",