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
32 changes: 29 additions & 3 deletions packages/cli/src/commands/manifest/cmd-manifest-cdxgen.mts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@
import yargsParse from 'yargs-parser'

import { joinAnd } from '@socketsecurity/lib-stable/arrays/join'
import { debugNs } from '@socketsecurity/lib-stable/debug/output'
import { getDefaultLogger } from '@socketsecurity/lib-stable/logger/default'
import { isPath } from '@socketsecurity/lib-stable/paths/normalize'
import { pluralize } from '@socketsecurity/lib-stable/words/pluralize'

import {
describeCdxgenSource,
formatCdxgenFailureMessage,
} from '../../util/dlx/cdxgen-diagnostics.mts'
import {
detectNodejsCdxgenSources,
isNodejsCdxgenType,
Expand Down Expand Up @@ -41,7 +46,7 @@
return arg.toLowerCase()
}

// npx @cyclonedx/cdxgen@11.2.7 --help

Check failure on line 49 in packages/cli/src/commands/manifest/cmd-manifest-cdxgen.mts

View workflow job for this annotation

GitHub Actions / 🔎 Check

socket(max-comment-block-lines)

Comment block runs 70 lines, over the 20-line cap — past this a reader skips it. Keep the constraint or invariant here and move the discussion into `docs/agents.md/**`, linked from a one-line pointer. Bypass: add a `socket-lint: allow long-comment-block` comment.
//
// Options:
// -o, --output Output file. Default bom.json [default: "bom.json"]
Expand Down Expand Up @@ -336,15 +341,36 @@
}
}

// Assume failure until cdxgen reports otherwise, so an unexpected early exit
// cannot be mistaken for a successful scan.
process.exitCode = 1

const { spawnPromise } = await runCdxgen(yargv)
let result
try {
const { spawnPromise } = await runCdxgen(yargv)
result = await spawnPromise
} catch (e) {
// cdxgen runs with stdio: 'inherit', so a failure to start it produces no
// child output at all. Say where we looked and what to try next.
// The message tells the user to re-run with SOCKET_CLI_DEBUG=1, so put the
// underlying error on the 'error' category that flag turns on. Handling it
// here means it never reaches the top level, and nothing else on this path
// logs it, so without this the advice would lead nowhere.
debugNs('error', `cdxgen failed to run while ${describeCdxgenSource()}`, e)
logger.fail(formatCdxgenFailureMessage(e))
return
Comment thread
jdalton marked this conversation as resolved.
Comment thread
jdalton marked this conversation as resolved.
}

// Wait for the spawn promise to resolve and handle the result.
const result = await spawnPromise
if (result.signal) {
process.kill(process.pid, result.signal)
} else if (typeof result.code === 'number') {
process.exit(result.code)
} else {
// Neither an exit code nor a signal. Without this branch the command
// returns here with the exit code armed above and prints nothing at all.
// There is no error to show, so the spawn result is what SOCKET_CLI_DEBUG=1
// has to offer.
debugNs('error', 'cdxgen returned no exit code and no signal', result)
logger.fail(formatCdxgenFailureMessage())
}
}
89 changes: 89 additions & 0 deletions packages/cli/src/util/dlx/cdxgen-diagnostics.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* Diagnostics for the `socket cdxgen` command.
*
* Cdxgen runs as a child process, so when it cannot start there is nothing on
* stdout or stderr to explain why. These helpers turn that into a message that
* names where the CLI looked for cdxgen and what to try next.
*/

import { existsSync } from 'node:fs'

import { errorMessage } from '@socketsecurity/lib-stable/errors/message'

import { resolveCdxgen } from './resolve-binary.mjs'
import { InputError } from '../error/errors-types.mts'

/**
* Describe where the CLI resolved cdxgen from, so an error can say which of
* the two sources actually failed.
*/
export function describeCdxgenSource(): string {
const resolution = resolveCdxgen()
if (resolution.type === 'local') {
return `the local override SOCKET_CLI_CDXGEN_LOCAL_PATH=${resolution.path}`
}
if (resolution.type === 'dlx') {
const { name, version } = resolution.details
return `${name}@${version}, downloaded and cached by Socket's dlx`
}
return "a binary downloaded and cached by Socket's dlx"
}

/**
* Build the message shown when cdxgen fails to produce a result.
*
* Pass the underlying error when there is one. Pass nothing for the case where
* the child process ended without reporting either an exit code or a signal,
* which is the shape that used to exit 1 with no output at all.
*/
export function formatCdxgenFailureMessage(
cause?: unknown | undefined,
): string {
// An InputError is raised with a message already written for the exact thing
// that went wrong, so pass it through. Wrapping it would nest one
// Where/Saw/Fix block inside another, and the generic Fix below would tell
// the user to set SOCKET_CLI_CDXGEN_LOCAL_PATH when a bad value for that
// very variable is what they are being told about.
if (cause instanceof InputError) {
return cause.message
}

const detail = cause
? errorMessage(cause)
: 'the cdxgen process ended without reporting an exit code or a signal'

return [
'socket cdxgen could not run cdxgen.',
` Where: ${describeCdxgenSource()}`,
` Saw: ${detail || 'no error message was reported'}`,
' Fix: Re-run with SOCKET_CLI_DEBUG=1 to see the full error. If cdxgen',
' cannot be downloaded on this machine, install it yourself and',
' point SOCKET_CLI_CDXGEN_LOCAL_PATH at the binary.',
].join('\n')
}

/**
* Build the message shown when SOCKET_CLI_CDXGEN_LOCAL_PATH points at
* something that is not there.
*
* Without this check the override is silently ignored and the failure looks
* identical to a download failure, which makes the override appear to have no
* effect at all.
*/
export function formatMissingCdxgenLocalPathMessage(localPath: string): string {
return [
'SOCKET_CLI_CDXGEN_LOCAL_PATH points at a file that does not exist.',
` Where: ${localPath}`,
' Saw: nothing at that path',
' Fix: Correct the path, or unset SOCKET_CLI_CDXGEN_LOCAL_PATH to let',
' Socket download cdxgen itself. On a CI runner, check that the',
' path exists in the same step that runs socket cdxgen.',
].join('\n')
}

/**
* True when a local cdxgen override is configured but missing from disk.
*/
export function isMissingCdxgenLocalPath(localPath: string): boolean {
return !existsSync(localPath)
}
11 changes: 11 additions & 0 deletions packages/cli/src/util/dlx/spawn-cdxgen.mts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,14 @@
import { detectExecutableType } from '@socketsecurity/lib-stable/dlx/detect'
import { spawn } from '@socketsecurity/lib-stable/process/spawn/child'

import {
formatMissingCdxgenLocalPathMessage,
isMissingCdxgenLocalPath,
} from './cdxgen-diagnostics.mts'
import { defineAutoDispatch, defineVfsSpawn } from './define-tool-spawn.mts'
import { spawnDlx } from './spawn.mts'
import { resolveCdxgen } from './resolve-binary.mjs'
import { InputError } from '../error/errors.mts'
import { buildSystemToolEnv } from '../spawn/system-tool.mts'
import { resolveNodeExecutable } from '../spawn/spawn-node.mts'

Expand All @@ -37,6 +42,12 @@ export async function spawnCdxgenDlx(

// Use local cdxgen if available.
if (resolution.type === 'local') {
// Check the override before spawning. Otherwise a wrong path surfaces as a
// bare ENOENT that never mentions the environment variable, so the
// override looks like it was ignored.
if (isMissingCdxgenLocalPath(resolution.path)) {
throw new InputError(formatMissingCdxgenLocalPathMessage(resolution.path))
}
const detection = detectExecutableType(resolution.path)
const { env: spawnEnv, ...dlxOptions } = {
__proto__: null,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/**
* Unit tests for the cdxgen command's failure reporting.
*
* Purpose: The command arms process.exitCode = 1 before spawning cdxgen, and
* cdxgen itself runs with stdio: 'inherit'. Together that means any path out
* of the spawn that neither exits deliberately nor prints leaves the user with
* exit code 1 and an empty log. These tests cover every one of those paths.
*
* Related Files: - src/commands/manifest/cmd-manifest-cdxgen.mts.
*/

import { beforeEach, describe, expect, it, vi } from 'vitest'

import { cmdManifestCdxgen } from '../../../../src/commands/manifest/cmd-manifest-cdxgen.mts'
import { formatMissingCdxgenLocalPathMessage } from '../../../../src/util/dlx/cdxgen-diagnostics.mts'
import { InputError } from '../../../../src/util/error/errors-types.mts'

const mockLogger = vi.hoisted(() => ({
error: vi.fn(),
fail: vi.fn(),
info: vi.fn(),
log: vi.fn(),
success: vi.fn(),
warn: vi.fn(),
}))

vi.mock(import('@socketsecurity/lib-stable/logger/default'), () => ({
getDefaultLogger: () => mockLogger,
}))

const mockDebugNs = vi.hoisted(() => vi.fn())

vi.mock(
import('@socketsecurity/lib-stable/debug/output'),
async importOriginal => ({
...(await importOriginal()),
debugNs: mockDebugNs,
}),
)

const mockRunCdxgen = vi.hoisted(() => vi.fn())
const mockDetectNodejsCdxgenSources = vi.hoisted(() =>
vi.fn().mockResolvedValue({ hasLockfile: true, hasNodeModules: true }),
)
const mockIsNodejsCdxgenType = vi.hoisted(() => vi.fn().mockReturnValue(true))

vi.mock(import('../../../../src/commands/manifest/run-cdxgen.mts'), () => ({
detectNodejsCdxgenSources: mockDetectNodejsCdxgenSources,
isNodejsCdxgenType: mockIsNodejsCdxgenType,
runCdxgen: mockRunCdxgen,
}))

describe('cmd-manifest-cdxgen failure reporting', () => {
const importMeta = { url: 'file:///test/cmd-manifest-cdxgen.mts' }
const context = { parentName: 'socket manifest' }

beforeEach(() => {
vi.clearAllMocks()
mockDetectNodejsCdxgenSources.mockResolvedValue({
hasLockfile: true,
hasNodeModules: true,
})
mockIsNodejsCdxgenType.mockReturnValue(true)
process.exitCode = undefined
})

describe('never fails silently', () => {
// The command arms process.exitCode = 1 before spawning cdxgen. Every
// way out of the spawn must therefore either exit deliberately or print
// something, otherwise the user gets exit code 1 and an empty log.
it('reports an actionable error when cdxgen cannot be started', async () => {
mockRunCdxgen.mockRejectedValue(new Error('spawn cdxgen ENOENT'))
const mockExit = vi
.spyOn(process, 'exit')
.mockImplementation((() => {}) as unknown)

await cmdManifestCdxgen.run(['.'], importMeta, context)

expect(mockLogger.fail).toHaveBeenCalledTimes(1)
const message = String(mockLogger.fail.mock.calls[0]?.[0] ?? '')
expect(message.trim()).not.toBe('')
expect(message).toContain('socket cdxgen could not run cdxgen.')
expect(message).toContain('spawn cdxgen ENOENT')
expect(process.exitCode).toBe(1)
mockExit.mockRestore()
})

it('reports an actionable error when the spawn itself rejects', async () => {
mockRunCdxgen.mockResolvedValue({
spawnPromise: Promise.reject(new Error('cdxgen download failed')),
})
const mockExit = vi
.spyOn(process, 'exit')
.mockImplementation((() => {}) as unknown)

await cmdManifestCdxgen.run(['.'], importMeta, context)

expect(mockLogger.fail).toHaveBeenCalledTimes(1)
const message = String(mockLogger.fail.mock.calls[0]?.[0] ?? '')
expect(message).toContain('cdxgen download failed')
expect(process.exitCode).toBe(1)
mockExit.mockRestore()
})

it('reports an actionable error when cdxgen ends with no exit code and no signal', async () => {
mockRunCdxgen.mockResolvedValue({
spawnPromise: Promise.resolve({ code: undefined, signal: undefined }),
})
const mockExit = vi
.spyOn(process, 'exit')
.mockImplementation((() => {}) as unknown)

await cmdManifestCdxgen.run(['.'], importMeta, context)

expect(mockExit).not.toHaveBeenCalled()
expect(mockLogger.fail).toHaveBeenCalledTimes(1)
const message = String(mockLogger.fail.mock.calls[0]?.[0] ?? '')
expect(message).toContain('without reporting an exit code or a signal')
expect(process.exitCode).toBe(1)
mockExit.mockRestore()
})

// The failure message tells the user to re-run with SOCKET_CLI_DEBUG=1.
// That flag turns on the 'error' debug category, so the underlying detail
// has to be emitted there or the advice sends them nowhere.
it('makes SOCKET_CLI_DEBUG=1 worth running after a failed spawn', async () => {
const cause = new Error('spawn cdxgen ENOENT')
mockRunCdxgen.mockRejectedValue(cause)
const mockExit = vi
.spyOn(process, 'exit')
.mockImplementation((() => {}) as unknown)

await cmdManifestCdxgen.run(['.'], importMeta, context)

const debugCall = mockDebugNs.mock.calls.find(call => call[0] === 'error')
expect(debugCall).toBeDefined()
expect(debugCall).toContain(cause)
mockExit.mockRestore()
})

it('makes SOCKET_CLI_DEBUG=1 worth running after a resultless exit', async () => {
const spawnResult = { code: undefined, signal: undefined }
mockRunCdxgen.mockResolvedValue({
spawnPromise: Promise.resolve(spawnResult),
})
const mockExit = vi
.spyOn(process, 'exit')
.mockImplementation((() => {}) as unknown)

await cmdManifestCdxgen.run(['.'], importMeta, context)

const debugCall = mockDebugNs.mock.calls.find(call => call[0] === 'error')
expect(debugCall).toBeDefined()
expect(debugCall).toContain(spawnResult)
mockExit.mockRestore()
})

it('prints the missing-override message as written, without wrapping it', async () => {
const explained = formatMissingCdxgenLocalPathMessage('/tmp/acme-cdxgen')
mockRunCdxgen.mockRejectedValue(new InputError(explained))
const mockExit = vi
.spyOn(process, 'exit')
.mockImplementation((() => {}) as unknown)

await cmdManifestCdxgen.run(['.'], importMeta, context)

expect(mockLogger.fail).toHaveBeenCalledTimes(1)
const message = String(mockLogger.fail.mock.calls[0]?.[0] ?? '')
expect(message).toBe(explained)
expect(process.exitCode).toBe(1)
mockExit.mockRestore()
})

it('stays quiet on the success path', async () => {
mockRunCdxgen.mockResolvedValue({
spawnPromise: Promise.resolve({ code: 0, signal: undefined }),
})
const mockExit = vi
.spyOn(process, 'exit')
.mockImplementation((() => {}) as unknown)

await cmdManifestCdxgen.run(['.'], importMeta, context)

expect(mockLogger.fail).not.toHaveBeenCalled()
expect(mockExit).toHaveBeenCalledWith(0)
mockExit.mockRestore()
})
})
})
Loading
Loading