Skip to content
Open
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## [Unreleased]

### Changed
- `--dynamic-sbom-inference` can be passed to every repository: one without a .NET, Gradle, Maven or sbt build is scanned as without the flag instead of failing, and `socket manifest dynamic-sbom-inference` reports that no build root was found and exits successfully.

## [1.18.2](https://github.com/SocketDev/socket-cli/releases/tag/v1.18.2) - 2026-12-02

### Changed
Expand Down
16 changes: 16 additions & 0 deletions src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,22 @@ describe('socket fix --dynamic-sbom-inference', () => {
expect(generated.remove).toHaveBeenCalledTimes(1)
})

it('runs Coana as without the flag when no build root was found', async () => {
mockGenerateSocketFactsForFix.mockResolvedValue(undefined)

const result = await coanaFix(baseConfig)

expect(result.ok).toBe(true)
const args = coanaCalls('compute-fixes-and-upgrade-purls')[0]!
expect(args).not.toContain('--use-only-socket-facts-artifacts')
expect(args).not.toContain('--socket-facts-sidecar')
expect(uploadManifestFiles).toHaveBeenCalledWith(
'test-org',
['/test/cwd/app/build.gradle'],
{ pathsRelativeTo: '/test/cwd' },
)
})

it('discovers vulnerabilities only through the generated facts', async () => {
mockSpawnCoana.mockImplementation(async (args: string[]) => {
if (args[0] === 'find-vulnerabilities') {
Expand Down
17 changes: 10 additions & 7 deletions src/commands/fix/coana-fix.mts
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ async function coanaFixWithFacts(
spinner?.stop()
logger.info('Generating Socket facts for each build ...')
}
factsSlot.generated = await generateSocketFactsForFix({
const generated = await generateSocketFactsForFix({
context: { coanaVersion, orgSlug },
cwd,
excludePaths,
Expand All @@ -405,12 +405,15 @@ async function coanaFixWithFacts(
(await findScanFilepaths()).filter(isSocketFactsFile),
tmpDir: factsSlot.tmpDir,
})
scanFilepaths = await withoutDiscardedFacts(
scanFilepaths,
factsSlot.generated.discardedPaths,
)
const known = new Set(scanFilepaths)
scanFilepaths.push(...factsSlot.generated.paths.filter(p => !known.has(p)))
factsSlot.generated = generated
if (generated) {
scanFilepaths = await withoutDiscardedFacts(
scanFilepaths,
generated.discardedPaths,
)
const known = new Set(scanFilepaths)
scanFilepaths.push(...generated.paths.filter(p => !known.has(p)))
}
if (!silence) {
spinner?.start()
}
Expand Down
8 changes: 6 additions & 2 deletions src/commands/fix/generated-socket-facts.mts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ async function restoreAll(backups: Backup[]): Promise<void> {
}

// Backed up so each fix attempt sees the pre-fix build after `git clean`, and
// facts files already present are left as they were found.
// facts files already present are left as they were found. Undefined when no
// build root was discovered, so the fix runs as without facts.
export async function generateSocketFactsForFix({
context,
cwd,
Expand All @@ -60,7 +61,7 @@ export async function generateSocketFactsForFix({
findFactsPaths: () => Promise<string[]>
purlTypes: readonly PURL_Type[]
tmpDir: string
}): Promise<GeneratedSocketFacts> {
}): Promise<GeneratedSocketFacts | undefined> {
const existingPaths = await findFactsPaths()

Choose a reason for hiding this comment

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

[agent] With no build root, everything up to the early return at line 90 is wasted, and that is now a success path: a full repo walk via findFactsPaths(), a backup of the existing facts files, and a work dir. The walk also repeats the one coanaFixWithFacts already did into scanFilepaths.

Cheaper: pass scanFilepaths.filter(isSocketFactsFile) in for this first lookup and keep findFactsPaths for the cleanup in the catch. That also saves the repeated walk when build roots do exist.

const originals = await backUp(existingPaths, path.join(tmpDir, 'existing'))
const existing = new Set(existingPaths)
Expand All @@ -86,6 +87,9 @@ export async function generateSocketFactsForFix({
hints: EXCLUDE_PATHS_HINTS,
purlTypes,
})
if (!inferred.factsOnlyTypes) {
return undefined
}
discardedPaths = inferred.discardedFactsPaths
factsOnlyTypes = inferred.factsOnlyTypes
paths = inferred.factsPaths.map(p => path.resolve(cwd, p))
Expand Down
23 changes: 21 additions & 2 deletions src/commands/fix/generated-socket-facts.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ describe('generateSocketFactsForFix', () => {
await fs.rm(tmpDir, { force: true, recursive: true })
})

async function generate() {
return await generateSocketFactsForFix({
function generateOrNone() {

Choose a reason for hiding this comment

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

[agent] The generateOrNone/generate split exists only to narrow the type, but test files are excluded from tsconfig.json, so the narrowing has no effect (run-dynamic-sbom-inference.test.mts already reads the now-optional field without it). The original single generate() with expect(await generate()).toBeUndefined() would do.

return generateSocketFactsForFix({
context: { coanaVersion: '1.2.3', orgSlug: 'acme' },
cwd,
excludePaths: [],
Expand All @@ -43,6 +43,14 @@ describe('generateSocketFactsForFix', () => {
})
}

async function generate() {
const generated = await generateOrNone()
if (!generated) {
throw new Error('Expected generated facts.')
}
return generated
}

it('restores the generated facts per attempt and the original facts afterwards', async () => {
mockRunDynamicSbomInference.mockImplementation(async () => {
await fs.writeFile(existing, 'regenerated')
Expand Down Expand Up @@ -117,6 +125,17 @@ describe('generateSocketFactsForFix', () => {
expect(JSON.parse(await fs.readFile(sidecarFile, 'utf8'))).toEqual([])
})

it('generates nothing when no build root was discovered', async () => {
mockRunDynamicSbomInference.mockResolvedValue({
discardedFactsPaths: [],
factsOnlyTypes: undefined,
factsPaths: [],
})

expect(await generateOrNone()).toBeUndefined()
expect(await fs.readFile(existing, 'utf8')).toBe('original')
})

it('restores an existing facts file that generation does not rewrite', async () => {
mockRunDynamicSbomInference.mockImplementation(async () => {
await fs.writeFile(fresh, 'generated')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ export async function handleManifestDynamicSbomInference({

const result: CResult<RecursiveManifestOutcome[]> = !outcomes.length
? {
ok: false,
code: 1,
ok: true,

Choose a reason for hiding this comment

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

[agent] With this branch now a success, the nesting does no work: an empty outcomes can't contain a failure, so it no longer has to be checked first. One failure branch plus one success branch whose message depends on outcomes.length does the same. (Upstack adds a third, skipped-failures success case; that fits the same shape with one more message condition.)

message:
'No Gradle, sbt, Maven or .NET build root was found beneath the given directory.',

Choose a reason for hiding this comment

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

[agent] This hardcoded list now becomes the normal success output, and it doesn't match the scan path's joinOr(buildToolLabelsFor(purlTypes)), which prints ".NET, Gradle, Maven, or sbt" (different order and comma). joinOr(buildToolLabelsFor(FACTS_PURL_TYPES)) would keep them in step. Another hardcoded copy is at setup-recursive-manifest-config.mts:1049.

data: outcomes,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ vi.mock('./output-manifest-dynamic-sbom-inference.mts', () => ({
import { handleManifestDynamicSbomInference } from './handle-manifest-dynamic-sbom-inference.mts'

describe('handleManifestDynamicSbomInference', () => {
it('fails closed when no build root is found anywhere', async () => {
it('succeeds without facts when no build root is found anywhere', async () => {
mockGenerateRecursiveManifests.mockResolvedValue([])

await handleManifestDynamicSbomInference({
Expand All @@ -31,8 +31,7 @@ describe('handleManifestDynamicSbomInference', () => {

expect(mockOutputManifestDynamicSbomInference).toHaveBeenCalledWith(
{
ok: false,
code: 1,
ok: true,
message:
'No Gradle, sbt, Maven or .NET build root was found beneath the given directory.',
data: [],
Expand Down
19 changes: 7 additions & 12 deletions src/commands/manifest/output-manifest-dynamic-sbom-inference.mts
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,16 @@ export async function outputManifestDynamicSbomInference(
}

const table = renderTable(result.data)
const lines = [
...(result.message ? [result.message] : []),
...(table ? [table] : []),
summarize(result.data),
]

if (outputKind === 'markdown') {
logger.log(
[
'# Dynamic SBOM inference',
'',
...(table ? [table, ''] : []),
summarize(result.data),
].join('\n'),
)
logger.log(['# Dynamic SBOM inference', ...lines].join('\n\n'))
return
}

if (table) {
logger.log(table)
}
logger.log(summarize(result.data))
logger.log(lines.join('\n'))
}
13 changes: 6 additions & 7 deletions src/commands/scan/handle-create-new-scan.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -480,20 +480,19 @@ describe('handleCreateNewScan excludePaths', () => {
expect(mockFetchCreateOrgFullScan).not.toHaveBeenCalled()
})

it('aborts when --dynamic-sbom-inference finds no build root', async () => {
it('scans without facts when --dynamic-sbom-inference finds no build root', async () => {

Choose a reason for hiding this comment

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

[agent] With the abort gone, this test and the next one ("build roots were found but none generated facts") have the same setup and assertions, differing only in the mocked outcomes. One it.for over [] and [empty, skippedDisabled] would cover both.

mockGenerateRecursiveManifests.mockResolvedValueOnce([])

const config = createConfig({ autoManifest: false, targets: ['/repo'] })
config.reach.dynamicSbomInference = ['maven', 'nuget']

await expect(handleCreateNewScan(config)).rejects.toThrow(
/No .NET, Gradle, Maven, or sbt build root was found/,
)
expect(mockGetPackageFilesForScan).not.toHaveBeenCalled()
expect(mockFetchCreateOrgFullScan).not.toHaveBeenCalled()
await handleCreateNewScan(config)

expect(mockGetPackageFilesForScan).toHaveBeenCalled()
expect(mockFetchCreateOrgFullScan).toHaveBeenCalled()
})

it('does not abort when build roots were found but none generated facts (empty/skippedDisabled), unlike genuinely finding none', async () => {
it('does not abort when build roots were found but none generated facts (empty/skippedDisabled)', async () => {
mockGenerateRecursiveManifests.mockResolvedValueOnce([
{ dir: '/repo/service-a', ecosystem: 'maven', status: 'empty' },
{ dir: '/repo/service-b', ecosystem: 'maven', status: 'skippedDisabled' },
Expand Down
24 changes: 12 additions & 12 deletions src/commands/scan/run-dynamic-sbom-inference.mts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ export type DynamicSbomInferenceResult = {
// Facts files of dropped runs, which the scan must not collect.
discardedFactsPaths: string[]
// Each discovered build root's purl type, generated or not: Coana takes
// these types' artifacts only from facts files.
factsOnlyTypes: FactsOnlyTypes
// these types' artifacts only from facts files. Undefined when no build
// root was discovered.
factsOnlyTypes: FactsOnlyTypes | undefined

Choose a reason for hiding this comment

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

[agent] "No build root" now has two shapes on adjacent layers: here it's a full result with factsOnlyTypes: undefined and empty arrays, and generateSocketFactsForFix checks that field only to turn it into a plain undefined. The type also admits factsOnlyTypes: undefined with non-empty paths, which only the comment rules out.

Simpler: keep factsOnlyTypes: FactsOnlyTypes required and return DynamicSbomInferenceResult | undefined. The fix layer's check becomes if (!inferred), and the scan callers (handle-scan-reach.mts, handle-create-new-scan.mts) need about three ?./?? [], since their locals are already | undefined.

factsPaths: string[]
}

Expand Down Expand Up @@ -93,18 +94,17 @@ export async function runDynamicSbomInference({
const factsOnlyTypes = [
...new Set(outcomes.map(o => PURL_TYPE_BY_TOOL[o.ecosystem])),
]
// No candidates discovered at all (distinct from candidates that were found
// but produced no generated facts - empty/skippedDisabled are already warned
// about elsewhere and are not this kind of mistake).
// A repository without such builds is scanned as without the flag, so the
// flag can be passed to every repository.
if (!isFactsOnlyTypes(factsOnlyTypes)) {
throw new InputError(
[
`No ${joinOr(buildToolLabelsFor(purlTypes))} build root was found.`,
'',
'- Select other ecosystems with --dynamic-sbom-inference-ecosystems, or remove --dynamic-sbom-inference.',
'- Make sure to run it from the correct dir (use --cwd to target another dir).',
].join('\n'),
logger.info(
`No ${joinOr(buildToolLabelsFor(purlTypes))} build root was found, so no Socket facts were generated.`,
)
return {
discardedFactsPaths: [],
factsOnlyTypes: undefined,
factsPaths: [],
}
}
// Fail loud rather than silently proceed with a partial multi-root result:
// matches handleManifestDynamicSbomInference's own check.
Expand Down
41 changes: 25 additions & 16 deletions src/commands/scan/run-dynamic-sbom-inference.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@ import {

import type { PURL_Type } from '../../utils/ecosystem.mts'

const { mockGenerateRecursiveManifests, mockWarn } = vi.hoisted(() => ({
mockGenerateRecursiveManifests: vi.fn(),
mockWarn: vi.fn(),
}))
const { mockGenerateRecursiveManifests, mockInfo, mockWarn } = vi.hoisted(
() => ({
mockGenerateRecursiveManifests: vi.fn(),
mockInfo: vi.fn(),
mockWarn: vi.fn(),
}),
)

vi.mock('../../utils/logger.mts', () => ({
logger: { warn: mockWarn },
logger: { info: mockInfo, warn: mockWarn },
}))

vi.mock('../manifest/generate-recursive-manifests.mts', () => ({
Expand Down Expand Up @@ -103,23 +106,29 @@ describe('runDynamicSbomInference', () => {
])
})

it.for<{ message: string; purlTypes?: PURL_Type[] }>([
{ message: 'No .NET, Gradle, Maven, or sbt build root was found' },
{ message: 'No .NET build root was found', purlTypes: ['nuget'] },
])(
'proceeds without facts when no build root is discovered: $message',
async ({ message, purlTypes }) => {
mockGenerateRecursiveManifests.mockResolvedValueOnce([])

expect(await run('reachability', purlTypes)).toEqual({
discardedFactsPaths: [],
factsOnlyTypes: undefined,
factsPaths: [],
})
expect(mockInfo).toHaveBeenCalledWith(expect.stringContaining(message))
},
)

it.for<{
error: RegExp
name: string
outcomes: object[]
purlTypes?: PURL_Type[]
}>([
{
name: 'no build root was discovered',
outcomes: [],
error: /No .NET, Gradle, Maven, or sbt build root was found/,
},
{
name: 'no build root of the selected ecosystems was discovered',
outcomes: [],
purlTypes: ['nuget'],
error: /No .NET build root was found/,
},
{
name: 'a discovered build root failed to generate facts',
outcomes: [
Expand Down
Loading