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
39 changes: 6 additions & 33 deletions src/commands/cdxgen/cmd-cdxgen.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,7 @@ import constants, {
FLAG_JSON,
FLAG_MARKDOWN,
} from '../../../src/constants.mts'
import {
cmdit,
hasCdxgenHelpContent,
hasSocketBanner,
spawnSocketCli,
} from '../../../test/utils.mts'
import { cmdit, spawnCdxgenHelp, spawnSocketCli } from '../../../test/utils.mts'

describe('socket cdxgen', async () => {
const { binCliPath } = constants
Expand All @@ -21,33 +16,11 @@ describe('socket cdxgen', async () => {
['cdxgen', FLAG_HELP, FLAG_CONFIG, '{}'],
`should support ${FLAG_HELP}`,
async cmd => {
const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd)

// Note: cdxgen may output help info to stdout or stderr depending on environment.
// In some CI environments, the help might not be captured properly.
// We check both streams to ensure we catch the output regardless of where it appears.
const combinedOutput = stdout + stderr

// Note: Socket CLI banner may appear in stderr while cdxgen output is in stdout.
// This is expected behavior as the banner is informational output.

// Note: We avoid snapshot testing here as cdxgen's help output format may change.
// On Windows CI, cdxgen might not output help properly or might not be installed.
// We check for either cdxgen help content OR just the Socket banner.
const hasSocketCommand = combinedOutput.includes('socket cdxgen')

// Test passes if either:
// 1. We got cdxgen help output (normal case).
// 2. We got Socket CLI banner with command (Windows CI where cdxgen might not work).
const hasCdxgenWorked = hasCdxgenHelpContent(combinedOutput)
const hasFallbackOutput =
hasSocketBanner(combinedOutput) && hasSocketCommand

expect(hasCdxgenWorked || hasFallbackOutput).toBe(true)
expect(
process.platform === 'win32' ? [0, 1, 127] : [0],
'help should return normally or tolerate a missing Windows DLX command',
).toContain(code)
const { code, stderr, stdout } = await spawnCdxgenHelp(cmd)
expect(code).toBe(0)
expect(stdout + stderr).toContain('CycloneDX Generator')
expect(stdout + stderr).toContain('cdxgen [command]')
expect(stderr).toContain('`socket cdxgen`')
},
)

Expand Down
130 changes: 15 additions & 115 deletions src/commands/manifest/cmd-manifest-cdxgen.test.mts
Original file line number Diff line number Diff line change
@@ -1,20 +1,7 @@
import path from 'node:path'

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

import {
cleanOutput,
cmdit,
hasCdxgenHelpContent,
hasSocketBanner,
spawnSocketCli,
testPath,
} from '../../../test/utils.mts'
import constants, {
FLAG_HELP,
FLAG_VERSION,
REDACTED,
} from '../../constants.mts'
import { cleanOutput, cmdit, spawnCdxgenHelp } from '../../../test/utils.mts'
import constants, { FLAG_HELP } from '../../constants.mts'
import { LOG_SYMBOLS } from '../../utils/logger.mts'
import { spawn } from '../../utils/spawn.mts'

Expand Down Expand Up @@ -56,106 +43,19 @@
}

describe('command forwarding', async () => {
cmdit(
['manifest', 'cdxgen', FLAG_HELP],
`should support ${FLAG_HELP}`,
async cmd => {
const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd, {
// Need to pass it on as env because --config will break cdxgen.
env: { SOCKET_CLI_CONFIG: '{}' },
})

// Note: cdxgen may output help info to stdout or stderr depending on environment.
// In some CI environments, the help might not be captured properly.
// We check both streams to ensure we catch the output regardless of where it appears.
const combinedOutput = stdout + stderr

if (combinedOutput.includes('CycloneDX Generator')) {
const cdxgenOutput = combinedOutput
.replace(/(?<=CycloneDX\s+Generator\s+)[\d.]+/, REDACTED)
.replace(/(?<=Node\.js,\s+Version:\s+)[\d.]+/, REDACTED)

// Check that help output contains expected cdxgen header.
// This validates that cdxgen is properly forwarding the --help flag.
expect(cdxgenOutput).toContain(`CycloneDX Generator ${REDACTED}`)
expect(cdxgenOutput).toContain(
`Runtime: Node.js, Version: ${REDACTED}`,
)
}

// Note: Socket CLI banner may appear in stderr while cdxgen output is in stdout.
// This is expected behavior as the banner is informational output.
if (hasSocketBanner(stderr)) {
const redactedStderr = stderr
.replace(/CLI:\s+v[\d.]+/, `CLI: ${REDACTED}`)
.replace(/token:\s+[^,]+/, `token: ${REDACTED}`)
.replace(/org:\s+[^)]+/, `org: ${REDACTED}`)
.replace(/cwd:\s+[^\n]+/, `cwd: ${REDACTED}`)

expect(redactedStderr).toContain('_____ _ _')
expect(redactedStderr).toContain(`CLI: ${REDACTED}`)
}

// Note: We avoid snapshot testing here as cdxgen's help output format may change.
// On Windows CI, cdxgen might not output help properly or might not be installed.
// We check for either cdxgen help content OR just the Socket banner.
const hasSocketCommand = combinedOutput.includes(
'socket manifest cdxgen',
)

// Test passes if either:
// 1. We got cdxgen help output (normal case).
// 2. We got Socket CLI banner with command (Windows CI where cdxgen might not work).
const hasCdxgenWorked = hasCdxgenHelpContent(combinedOutput)
const hasFallbackOutput =
hasSocketBanner(combinedOutput) && hasSocketCommand

expect(hasCdxgenWorked || hasFallbackOutput).toBe(true)
expect(
process.platform === 'win32' ? [0, 1, 127] : [0],
'help should return normally or tolerate a missing Windows DLX command',
).toContain(code)
expect(combinedOutput, 'banner includes base command').toContain(
'`socket manifest cdxgen`',
)
},
{ timeout: 60_000 },
)

it.skipIf(process.platform === 'win32')(
'should forward known flags to cdxgen',
{
// Increase timeout for CI environments where cdxgen downloads can be slow.
timeout: 60_000,
},
async () => {
for (const command of ['-h', FLAG_HELP]) {
// eslint-disable-next-line no-await-in-loop
const result = await spawn(
constants.execPath,
[binCliPath, 'manifest', 'cdxgen', command],
spawnOpts,
)

// Note: cdxgen may output help info to stdout or stderr depending on environment.
// In some CI environments, the help might not be captured properly.
// We check both streams to ensure we catch the output regardless of where it appears.
const combinedOutput = result.stdout + result.stderr

// Note: We avoid snapshot testing here as cdxgen's help output format may change.
// On Windows CI, cdxgen might not output help properly or might not be installed.
// We check for either cdxgen help content OR just the Socket banner.

// Test passes if either:
// 1. We got cdxgen help output (normal case).
// 2. We got Socket CLI banner (Windows CI where cdxgen might not work).
const hasCdxgenWorked = hasCdxgenHelpContent(combinedOutput)
const hasFallbackOutput = hasSocketBanner(combinedOutput)

expect(hasCdxgenWorked || hasFallbackOutput).toBe(true)
}
},
)
for (const flag of ['-h', FLAG_HELP]) {
cmdit(
['manifest', 'cdxgen', flag],
'forwards help to cdxgen',
async cmd => {
const { code, stderr, stdout } = await spawnCdxgenHelp(cmd)
expect(code).toBe(0)

Check failure on line 52 in src/commands/manifest/cmd-manifest-cdxgen.test.mts

View workflow job for this annotation

GitHub Actions / 🧪 Tests • windows-2022 • Node 24 • pwsh

src/commands/manifest/cmd-manifest-cdxgen.test.mts > socket manifest cdxgen > command forwarding > forwards help to cdxgen: `manifest cdxgen -h`

AssertionError: expected 1 to be +0 // Object.is equality - Expected + Received - 0 + 1 ❯ src/commands/manifest/cmd-manifest-cdxgen.test.mts:52:24
expect(stdout + stderr).toContain('CycloneDX Generator')
expect(stdout + stderr).toContain('cdxgen [command]')
expect(stderr).toContain('`socket manifest cdxgen`')
},
)
}

it('should not forward an unknown short flag to cdxgen', async () => {
const command = '-u'
Expand Down
53 changes: 22 additions & 31 deletions test/utils.mts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
Expand All @@ -6,8 +7,6 @@ import { it } from 'vitest'

import constants, {
COANA_CLI_VERSION,
FLAG_HELP,
FLAG_VERSION,
SOCKET_CLI_API_TOKEN_VARIABLES,
} from '../src/constants.mts'
import { type SpawnOptions, spawn } from '../src/utils/spawn.mts'
Expand Down Expand Up @@ -143,35 +142,27 @@ export function cleanOutput(output: string): string {
)
}

/**
* Check if output contains cdxgen help content.
* Used to verify cdxgen command executed with help flag.
*/
export function hasCdxgenHelpContent(output: string): boolean {
// Check for various cdxgen help indicators.
// Must have cdxgen or CycloneDX AND at least one help flag indicator.
const hasCdxgenMention =
output.includes('CycloneDX') || output.includes('cdxgen')
const hasHelpFlags =
output.includes(FLAG_HELP) ||
output.includes(FLAG_VERSION) ||
// cdxgen-specific flags.
output.includes('--output') ||
output.includes('--type')

return hasCdxgenMention && hasHelpFlags
}

/**
* Check if output contains the Socket CLI banner.
* The banner appears as ASCII art in the stderr output.
* Note: The banner contains either '*' (when --config is used) or '.' (when no config is used).
*/
export function hasSocketBanner(output: string): boolean {
// Check for Socket banner ASCII art lines.
// The banner is always printed as a complete block, never partial.
// Just check for the most distinctive first line.
return output.includes('_____ _ _')
export async function spawnCdxgenHelp(args: string[]) {
const cwd = await mkdtemp(path.join(os.tmpdir(), 'socket-cdxgen-help-'))
try {
// Outside the pnpm workspace, npx can run the pinned devDependency locally.
await writeFile(path.join(cwd, 'package.json'), '{"private":true}')
await symlink(
path.resolve(testPath, '../node_modules'),
path.join(cwd, 'node_modules'),
'junction',
)
return await spawnSocketCli(constants.binCliPath, args, {
cwd,
env: {
SOCKET_CLI_CONFIG: '{}',
npm_config_offline: 'true',
npm_config_cache: path.join(cwd, '.npm-cache'),
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Offline npx may skip local cdxgen

Medium Severity

The temp project’s package.json is only {"private":true}, while npx is invoked as @cyclonedx/cdxgen@&lt;pinned version&gt; with npm_config_offline=true and npm_config_cache pointed at a fresh empty directory. If npm exec does not treat the symlinked install as satisfying that spec (common when the package is not a declared dependency, or when a versioned spec still loads a packument), the fetch fails immediately with ENOTCACHED instead of printing help, so the new code === 0 / CycloneDX Generator assertions fail.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b152fa4. Configure here.

})
} finally {
await rm(cwd, { recursive: true, force: true })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Temp cleanup can wipe node_modules

High Severity

spawnCdxgenHelp junctions the repository node_modules into a temp directory and then rms that directory recursively in finally. On Windows a junction is a reparse point; fs.rm({ recursive: true }) has treated EPERM as “not empty” and descended into the target, which would delete the real install rather than only the temp junction. Cleanup errors are also uncaught, so a locked handle after npx can fail an otherwise passing test.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b152fa4. Configure here.

}
}

export type TestCollectorOptions = Exclude<Parameters<typeof it>[1], undefined>
Expand Down
Loading