diff --git a/CHANGELOG.md b/CHANGELOG.md index bc7b68d5a..c8ecc40dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts b/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts index 0c2f2409b..c16dea5e8 100644 --- a/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts +++ b/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts @@ -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') { diff --git a/src/commands/fix/coana-fix.mts b/src/commands/fix/coana-fix.mts index 735a67c28..a69d547b5 100644 --- a/src/commands/fix/coana-fix.mts +++ b/src/commands/fix/coana-fix.mts @@ -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, @@ -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() } diff --git a/src/commands/fix/generated-socket-facts.mts b/src/commands/fix/generated-socket-facts.mts index 289be5c2b..69c7b1ce0 100644 --- a/src/commands/fix/generated-socket-facts.mts +++ b/src/commands/fix/generated-socket-facts.mts @@ -45,7 +45,8 @@ async function restoreAll(backups: Backup[]): Promise { } // 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, @@ -60,7 +61,7 @@ export async function generateSocketFactsForFix({ findFactsPaths: () => Promise purlTypes: readonly PURL_Type[] tmpDir: string -}): Promise { +}): Promise { const existingPaths = await findFactsPaths() const originals = await backUp(existingPaths, path.join(tmpDir, 'existing')) const existing = new Set(existingPaths) @@ -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)) diff --git a/src/commands/fix/generated-socket-facts.test.mts b/src/commands/fix/generated-socket-facts.test.mts index 9abc8c3cb..5706ac167 100644 --- a/src/commands/fix/generated-socket-facts.test.mts +++ b/src/commands/fix/generated-socket-facts.test.mts @@ -32,8 +32,8 @@ describe('generateSocketFactsForFix', () => { await fs.rm(tmpDir, { force: true, recursive: true }) }) - async function generate() { - return await generateSocketFactsForFix({ + function generateOrNone() { + return generateSocketFactsForFix({ context: { coanaVersion: '1.2.3', orgSlug: 'acme' }, cwd, excludePaths: [], @@ -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') @@ -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') diff --git a/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts b/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts index be8e7acf5..002fab427 100644 --- a/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts +++ b/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts @@ -31,8 +31,7 @@ export async function handleManifestDynamicSbomInference({ const result: CResult = !outcomes.length ? { - ok: false, - code: 1, + ok: true, message: 'No Gradle, sbt, Maven or .NET build root was found beneath the given directory.', data: outcomes, diff --git a/src/commands/manifest/handle-manifest-dynamic-sbom-inference.test.mts b/src/commands/manifest/handle-manifest-dynamic-sbom-inference.test.mts index ea9753ec3..3990c240d 100644 --- a/src/commands/manifest/handle-manifest-dynamic-sbom-inference.test.mts +++ b/src/commands/manifest/handle-manifest-dynamic-sbom-inference.test.mts @@ -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({ @@ -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: [], diff --git a/src/commands/manifest/output-manifest-dynamic-sbom-inference.mts b/src/commands/manifest/output-manifest-dynamic-sbom-inference.mts index fed721609..d1728e533 100644 --- a/src/commands/manifest/output-manifest-dynamic-sbom-inference.mts +++ b/src/commands/manifest/output-manifest-dynamic-sbom-inference.mts @@ -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')) } diff --git a/src/commands/scan/handle-create-new-scan.test.mts b/src/commands/scan/handle-create-new-scan.test.mts index bb68b5ddc..622594929 100644 --- a/src/commands/scan/handle-create-new-scan.test.mts +++ b/src/commands/scan/handle-create-new-scan.test.mts @@ -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 () => { 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' }, diff --git a/src/commands/scan/run-dynamic-sbom-inference.mts b/src/commands/scan/run-dynamic-sbom-inference.mts index 1309eb1ae..659ad67fc 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.mts @@ -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 factsPaths: string[] } @@ -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. diff --git a/src/commands/scan/run-dynamic-sbom-inference.test.mts b/src/commands/scan/run-dynamic-sbom-inference.test.mts index 82c91757a..a7ef32489 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.test.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.test.mts @@ -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', () => ({ @@ -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: [