From c8985b4ecb6280e249994152860726ef3df44588 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 2 Dec 2026 23:51:01 +0100 Subject: [PATCH 1/3] fix(scan): scan without facts when no build root is found `--dynamic-sbom-inference` failed scan create, scan reach and fix when a repository had no .NET, Gradle, Maven or sbt build, so the flag could not be passed to every repository. They now log that no build root was found and continue as without the flag, and `socket manifest dynamic-sbom-inference` reports it and exits successfully. --- CHANGELOG.md | 5 +++ .../coana-fix-dynamic-sbom-inference.test.mts | 16 ++++++++ src/commands/fix/coana-fix.mts | 17 ++++---- src/commands/fix/generated-socket-facts.mts | 8 +++- .../fix/generated-socket-facts.test.mts | 23 ++++++++++- ...handle-manifest-dynamic-sbom-inference.mts | 3 +- ...e-manifest-dynamic-sbom-inference.test.mts | 5 +-- ...output-manifest-dynamic-sbom-inference.mts | 19 ++++----- .../scan/handle-create-new-scan.test.mts | 13 +++--- .../scan/run-dynamic-sbom-inference.mts | 24 +++++------ .../scan/run-dynamic-sbom-inference.test.mts | 41 +++++++++++-------- 11 files changed, 111 insertions(+), 63 deletions(-) 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: [ From 3ac31b0184479253394ade0c1a6083357eb4d431 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 2 Dec 2026 23:58:51 +0100 Subject: [PATCH 2/3] feat(scan): add --dynamic-sbom-inference-ignore-unresolved Scanning many repositories with --dynamic-sbom-inference needed a socket.json in each to tolerate unresolved dependencies. The new flag on scan create, scan reach and fix applies to every build and overrides socket.json, as --ignore-unresolved does on the manifest command. The scan commands do not declare --ignore-unresolved, --exclude-configs, --include-configs or --verbose, so each could take the scan target as its value. They are now rejected with a pointer to the flag or socket.json setting to use instead. DynamicSbomInference now carries the selected ecosystems and the ignore-unresolved override together. --- CHANGELOG.md | 4 + docs/dynamic-sbom-inference-settings.md | 11 + src/commands/fix/cmd-fix.integration.test.mts | 1 + src/commands/fix/cmd-fix.mts | 4 +- .../coana-fix-dynamic-sbom-inference.test.mts | 3 +- src/commands/fix/coana-fix.mts | 12 +- src/commands/fix/generated-socket-facts.mts | 7 +- .../fix/generated-socket-facts.test.mts | 5 +- src/commands/fix/types.mts | 6 +- .../generate-recursive-manifests.test.mts | 31 +-- src/commands/scan/cmd-scan-create.mts | 8 +- src/commands/scan/cmd-scan-create.test.mts | 1 + src/commands/scan/cmd-scan-reach.mts | 8 +- src/commands/scan/cmd-scan-reach.test.mts | 1 + src/commands/scan/handle-create-new-scan.mts | 6 +- .../scan/handle-create-new-scan.test.mts | 25 ++- src/commands/scan/handle-scan-reach.mts | 18 +- src/commands/scan/handle-scan-reach.test.mts | 9 +- .../scan/perform-reachability-analysis.mts | 5 +- .../perform-reachability-analysis.test.mts | 7 +- src/commands/scan/reachability-flags.mts | 30 ++- src/commands/scan/reachability-flags.test.mts | 35 ++- .../scan/reject-manifest-only-flags.mts | 32 +++ .../scan/reject-manifest-only-flags.test.mts | 46 ++++ .../scan/run-dynamic-sbom-inference.mts | 7 +- .../scan/run-dynamic-sbom-inference.test.mts | 27 ++- .../scan/warn-socket-json-only-flags.mts | 26 --- test/reachability-options.mts | 12 ++ .../termless/cli.native.socket-help-fix.svg | 102 ++++----- .../cli.native.socket-help-scan-create.svg | 202 +++++++++--------- .../cli.native.socket-help-scan-reach.svg | 122 ++++++----- 31 files changed, 500 insertions(+), 313 deletions(-) create mode 100644 src/commands/scan/reject-manifest-only-flags.mts create mode 100644 src/commands/scan/reject-manifest-only-flags.test.mts delete mode 100644 src/commands/scan/warn-socket-json-only-flags.mts diff --git a/CHANGELOG.md b/CHANGELOG.md index c8ecc40dc..2048d2594 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Added +- Scan many repositories with `--dynamic-sbom-inference` without a `socket.json` in each: `--dynamic-sbom-inference-ignore-unresolved` tolerates unresolved dependencies in every build. + ### 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. +- `socket scan create` and `socket scan reach` now reject `--ignore-unresolved`, `--exclude-configs`, `--include-configs` and `--verbose` instead of ignoring them, as each could swallow the scan target. ## [1.18.2](https://github.com/SocketDev/socket-cli/releases/tag/v1.18.2) - 2026-12-02 diff --git a/docs/dynamic-sbom-inference-settings.md b/docs/dynamic-sbom-inference-settings.md index dabf04cb4..570c3c4c0 100644 --- a/docs/dynamic-sbom-inference-settings.md +++ b/docs/dynamic-sbom-inference-settings.md @@ -85,6 +85,17 @@ Only reachability scans read the `reachability` fields, each cascading on its own, and only for the build tools they run. An invalid value or a field the build tool does not take fails the scan. +## On the command line + +Only `ignoreUnresolved` also has a flag that overrides `socket.json`; set the +other fields there. + +- `socket scan create`, `socket scan reach` and `socket fix` take + `--dynamic-sbom-inference-ignore-unresolved` with `--dynamic-sbom-inference`; + `socket manifest dynamic-sbom-inference` takes `--ignore-unresolved`. +- It applies to every build and wins over every `socket.json`, a build's own + `builds` entry included. The `--no-` form sets it to `false`. + ## Skipping builds | To skip | Set | Effect | diff --git a/src/commands/fix/cmd-fix.integration.test.mts b/src/commands/fix/cmd-fix.integration.test.mts index 3f84f4df8..50677686f 100644 --- a/src/commands/fix/cmd-fix.integration.test.mts +++ b/src/commands/fix/cmd-fix.integration.test.mts @@ -171,6 +171,7 @@ describe('socket fix', async () => { --disable-external-tool-checks Disable external tool checks during fix analysis. --dynamic-sbom-inference For Gradle, sbt, Maven and .NET: generate a Socket facts SBOM (produced directly by each package manager) per independent build root, instead of one synthetic root. Fixes are then attributed to the projects/modules that actually resolve each vulnerable dependency. The generated files are removed afterwards. --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma separated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget (.NET). Defaults to all of them. + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build (unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. --ecosystems Limit fix analysis to specific ecosystems. Accepts space- or comma-separated values and is case-insensitive. Defaults to all ecosystems. --exclude-paths Skip matching paths from the scan entirely: manifests under these paths are not uploaded, and fixes are not applied to workspaces under them. Patterns are anchored micromatch globs matched relative to the target directory (CWD); \`data/postgres/pgdata\` matches that exact path, \`**/pgdata\` matches at any depth. Use this to skip directories the current user cannot read so they do not abort manifest collection. Negation patterns (\`!path\`) are not supported. Accepts a comma-separated value or multiple flags. --fix-version Override the version of @coana-tech/cli used for fix analysis. Default: . diff --git a/src/commands/fix/cmd-fix.mts b/src/commands/fix/cmd-fix.mts index c0aac19ee..7c37df8fb 100644 --- a/src/commands/fix/cmd-fix.mts +++ b/src/commands/fix/cmd-fix.mts @@ -33,7 +33,7 @@ import { getDefaultOrgSlug } from '../ci/fetch-default-org-slug.mts' import { assertValidExcludePaths } from '../scan/exclude-paths.mts' import { DYNAMIC_SBOM_INFERENCE_DESCRIPTION, - dynamicSbomInferenceEcosystemsFlags, + dynamicSbomInferenceFlags, parseDynamicSbomInferenceFlags, } from '../scan/reachability-flags.mts' @@ -191,7 +191,7 @@ Available styles: default: false, description: `${DYNAMIC_SBOM_INFERENCE_DESCRIPTION} Fixes are then attributed to the projects/modules that actually resolve each vulnerable dependency. The generated files are removed afterwards.`, }, - ...dynamicSbomInferenceEcosystemsFlags, + ...dynamicSbomInferenceFlags, ecosystems: { type: 'string', default: [], 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 c16dea5e8..0e8e37b2f 100644 --- a/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts +++ b/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts @@ -3,6 +3,7 @@ import { promises as fs } from 'node:fs' import { beforeEach, describe, expect, it, vi } from 'vitest' import { coanaFix } from './coana-fix.mts' +import { makeDynamicSbomInference } from '../../../test/reachability-options.mts' import { logger } from '../../utils/logger.mts' import type { FixConfig } from './types.mts' @@ -101,7 +102,7 @@ describe('socket fix --dynamic-sbom-inference', () => { debug: false, disableExternalToolChecks: false, disableMajorUpdates: false, - dynamicSbomInference: ['maven'], + dynamicSbomInference: makeDynamicSbomInference({ purlTypes: ['maven'] }), ecosystems: [], exclude: [], excludePaths: [], diff --git a/src/commands/fix/coana-fix.mts b/src/commands/fix/coana-fix.mts index a69d547b5..adbe69985 100644 --- a/src/commands/fix/coana-fix.mts +++ b/src/commands/fix/coana-fix.mts @@ -60,9 +60,9 @@ import { withoutDiscardedFacts } from '../scan/run-dynamic-sbom-inference.mts' import type { GeneratedSocketFacts } from './generated-socket-facts.mts' import type { FixConfig } from './types.mts' import type { CResult } from '../../types.mts' -import type { FactsOnlyTypes } from '../../utils/coana.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' import type { Spinner } from '../../utils/spinner.mts' +import type { DynamicSbomInference } from '../scan/reachability-flags.mts' type DiscoverGhsaIdsOptions = { coanaVersion?: string | undefined @@ -283,18 +283,18 @@ function formatNotAppliedFixes(notApplied: NotAppliedFix[]): string { } type GeneratedSocketFactsSlot = { + dynamicSbomInference: DynamicSbomInference generated?: GeneratedSocketFacts | undefined - purlTypes: FactsOnlyTypes tmpDir: string } export async function coanaFix(fixConfig: FixConfig): Promise { - const purlTypes = fixConfig.dynamicSbomInference - if (!purlTypes) { + const { dynamicSbomInference } = fixConfig + if (!dynamicSbomInference) { return await coanaFixWithFacts(fixConfig, undefined) } return await withTmpDir('socket-fix-facts-', async tmpDir => { - const slot: GeneratedSocketFactsSlot = { purlTypes, tmpDir } + const slot: GeneratedSocketFactsSlot = { dynamicSbomInference, tmpDir } try { return await coanaFixWithFacts(fixConfig, slot) } finally { @@ -400,7 +400,7 @@ async function coanaFixWithFacts( context: { coanaVersion, orgSlug }, cwd, excludePaths, - purlTypes: factsSlot.purlTypes, + ...factsSlot.dynamicSbomInference, findFactsPaths: async () => (await findScanFilepaths()).filter(isSocketFactsFile), tmpDir: factsSlot.tmpDir, diff --git a/src/commands/fix/generated-socket-facts.mts b/src/commands/fix/generated-socket-facts.mts index 69c7b1ce0..b73c5982a 100644 --- a/src/commands/fix/generated-socket-facts.mts +++ b/src/commands/fix/generated-socket-facts.mts @@ -9,8 +9,8 @@ import { import { runDynamicSbomInference } from '../scan/run-dynamic-sbom-inference.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' -import type { PURL_Type } from '../../utils/ecosystem.mts' import type { SocketFactsContext } from '../manifest/run-manifest-facts.mts' +import type { DynamicSbomInference } from '../scan/reachability-flags.mts' export type GeneratedSocketFacts = { // Facts files of dropped runs, which Coana must not read. @@ -52,14 +52,14 @@ export async function generateSocketFactsForFix({ cwd, excludePaths, findFactsPaths, + ignoreUnresolved, purlTypes, tmpDir, -}: { +}: DynamicSbomInference & { context: Omit cwd: string excludePaths: string[] findFactsPaths: () => Promise - purlTypes: readonly PURL_Type[] tmpDir: string }): Promise { const existingPaths = await findFactsPaths() @@ -85,6 +85,7 @@ export async function generateSocketFactsForFix({ cwd, excludePaths, hints: EXCLUDE_PATHS_HINTS, + ignoreUnresolved, purlTypes, }) if (!inferred.factsOnlyTypes) { diff --git a/src/commands/fix/generated-socket-facts.test.mts b/src/commands/fix/generated-socket-facts.test.mts index 5706ac167..9f6a715e6 100644 --- a/src/commands/fix/generated-socket-facts.test.mts +++ b/src/commands/fix/generated-socket-facts.test.mts @@ -5,6 +5,7 @@ import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { generateSocketFactsForFix } from './generated-socket-facts.mts' +import { makeDynamicSbomInference } from '../../../test/reachability-options.mts' const mockRunDynamicSbomInference = vi.hoisted(() => vi.fn()) @@ -38,7 +39,7 @@ describe('generateSocketFactsForFix', () => { cwd, excludePaths: [], findFactsPaths: async () => [existing, fresh].filter(p => existsSync(p)), - purlTypes: ['maven'], + ...makeDynamicSbomInference({ purlTypes: ['maven'] }), tmpDir, }) } @@ -104,7 +105,7 @@ describe('generateSocketFactsForFix', () => { purpose: 'fix', }, }, - purlTypes: ['maven'], + ...makeDynamicSbomInference({ purlTypes: ['maven'] }), }), ) expect(factsOnlyTypes).toEqual(['maven', 'nuget']) diff --git a/src/commands/fix/types.mts b/src/commands/fix/types.mts index be5a3af66..3bf03888b 100644 --- a/src/commands/fix/types.mts +++ b/src/commands/fix/types.mts @@ -1,7 +1,7 @@ -import type { FactsOnlyTypes } from '../../utils/coana.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' import type { RangeStyle } from '../../utils/semver.mts' import type { Spinner } from '../../utils/spinner.mts' +import type { DynamicSbomInference } from '../scan/reachability-flags.mts' export type FixConfig = { all: boolean @@ -13,8 +13,8 @@ export type FixConfig = { debug: boolean disableExternalToolChecks: boolean disableMajorUpdates: boolean - // The ecosystems to generate Socket facts for; undefined when off. - dynamicSbomInference: FactsOnlyTypes | undefined + // Undefined when off. + dynamicSbomInference: DynamicSbomInference | undefined ecosystems: PURL_Type[] exclude: string[] excludePaths: string[] diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 407c38dab..4e23f8b9e 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -977,18 +977,25 @@ describe('generateRecursiveManifests', () => { ) }) - it.each([true, false])( - 'lets an explicit ignoreUnresolved (%s) override every build root socket.json', - async ignoreUnresolved => { - mockCascade(dir => - dir === dualMarkerDir - ? { - defaults: { - manifest: { maven: { ignoreUnresolved: !ignoreUnresolved } }, - }, - } - : {}, - ) + it.for( + [true, false].flatMap(ignoreUnresolved => [ + { + ignoreUnresolved, + manifest: { maven: { ignoreUnresolved: !ignoreUnresolved } }, + name: 'tool defaults', + }, + { + ignoreUnresolved, + manifest: { + builds: { 'pom.xml': { ignoreUnresolved: !ignoreUnresolved } }, + }, + name: "a build's own entry", + }, + ]), + )( + 'lets an explicit ignoreUnresolved ($ignoreUnresolved) override socket.json $name', + async ({ ignoreUnresolved, manifest }) => { + mockOwnSettings({ [dualMarkerDir]: { defaults: { manifest } } }) mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], diff --git a/src/commands/scan/cmd-scan-create.mts b/src/commands/scan/cmd-scan-create.mts index 07a53a24c..da50711c7 100644 --- a/src/commands/scan/cmd-scan-create.mts +++ b/src/commands/scan/cmd-scan-create.mts @@ -11,7 +11,7 @@ import { outputCreateNewScan } from './output-create-new-scan.mts' import { resolveReachAdvisories } from './reach-advisories.mts' import { DYNAMIC_SBOM_INFERENCE_DESCRIPTION, - dynamicSbomInferenceEcosystemsFlags, + dynamicSbomInferenceFlags, excludePathsFlag, parseDynamicSbomInferenceFlags, reachabilityFlags, @@ -20,10 +20,10 @@ import { isOmittedReachValue, reachMemoryLimitToMb, } from './reachability-units.mts' +import { rejectManifestOnlyFlags } from './reject-manifest-only-flags.mts' import { suggestOrgSlug } from './suggest-org-slug.mts' import { suggestTarget } from './suggest_target.mts' import { validateReachabilityTarget } from './validate-reachability-target.mts' -import { warnSocketJsonOnlyFlags } from './warn-socket-json-only-flags.mts' import constants, { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { commonFlags, outputFlags } from '../../flags.mts' import { checkCommandInput } from '../../utils/check-input.mts' @@ -134,7 +134,7 @@ const generalFlags: MeowFlags = { default: false, description: `${DYNAMIC_SBOM_INFERENCE_DESCRIPTION} Combine with --reach to split the reachability analysis per project/module.`, }, - ...dynamicSbomInferenceEcosystemsFlags, + ...dynamicSbomInferenceFlags, interactive: { type: 'boolean', default: true, @@ -386,7 +386,7 @@ async function run( const dynamicSbomInference = parseDynamicSbomInferenceFlags(cli.flags) - warnSocketJsonOnlyFlags(cli.flags, `${parentName} ${CMD_NAME}`) + rejectManifestOnlyFlags(cli.flags, `${parentName} ${CMD_NAME}`) const dryRun = !!cli.flags['dryRun'] const uvMembers = !!cli.flags['uvMembers'] diff --git a/src/commands/scan/cmd-scan-create.test.mts b/src/commands/scan/cmd-scan-create.test.mts index a11898069..2912d34fd 100644 --- a/src/commands/scan/cmd-scan-create.test.mts +++ b/src/commands/scan/cmd-scan-create.test.mts @@ -215,6 +215,7 @@ describe('socket scan create', async () => { --default-branch Set the default branch of the repository to the branch of this full-scan. Should only need to be done once, for example for the "main" or "master" branch. --dynamic-sbom-inference For Gradle, sbt, Maven and .NET: generate a Socket facts SBOM (produced directly by each package manager) per independent build root, instead of one synthetic root. Combine with --reach to split the reachability analysis per project/module. --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma separated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget (.NET). Defaults to all of them. + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build (unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the command working directory (\`--cwd\` if set), not the reachability target: \`tests\` matches only \`/tests\`; use \`**/tests\` to match at any depth. Negation patterns (\`!path\`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET project is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that project. A build module or project outside the scan root cannot be excluded. --interactive Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, defaulting them to cancel/no. diff --git a/src/commands/scan/cmd-scan-reach.mts b/src/commands/scan/cmd-scan-reach.mts index a0526a97c..6040117bd 100644 --- a/src/commands/scan/cmd-scan-reach.mts +++ b/src/commands/scan/cmd-scan-reach.mts @@ -5,14 +5,14 @@ import { handleScanReach } from './handle-scan-reach.mts' import { resolveReachAdvisories } from './reach-advisories.mts' import { DYNAMIC_SBOM_INFERENCE_DESCRIPTION, - dynamicSbomInferenceEcosystemsFlags, + dynamicSbomInferenceFlags, excludePathsFlag, parseDynamicSbomInferenceFlags, reachabilityFlags, } from './reachability-flags.mts' +import { rejectManifestOnlyFlags } from './reject-manifest-only-flags.mts' import { suggestTarget } from './suggest_target.mts' import { validateReachabilityTarget } from './validate-reachability-target.mts' -import { warnSocketJsonOnlyFlags } from './warn-socket-json-only-flags.mts' import constants from '../../constants.mts' import { commonFlags, outputFlags } from '../../flags.mts' import { checkCommandInput } from '../../utils/check-input.mts' @@ -50,7 +50,7 @@ const reachabilityFlagsForReach: MeowFlags = { default: false, description: `${DYNAMIC_SBOM_INFERENCE_DESCRIPTION} The reachability analysis is split per project/module accordingly.`, }, - ...dynamicSbomInferenceEcosystemsFlags, + ...dynamicSbomInferenceFlags, // Fallback targets scan creation, which this command never performs. reachFallbackToRegularScan: { type: 'boolean', @@ -143,7 +143,7 @@ async function run( parentName, }) - warnSocketJsonOnlyFlags(cli.flags, `${parentName} ${CMD_NAME}`) + rejectManifestOnlyFlags(cli.flags, `${parentName} ${CMD_NAME}`) const { cwd: cwdOverride, diff --git a/src/commands/scan/cmd-scan-reach.test.mts b/src/commands/scan/cmd-scan-reach.test.mts index 9eb0c170c..810a9f103 100644 --- a/src/commands/scan/cmd-scan-reach.test.mts +++ b/src/commands/scan/cmd-scan-reach.test.mts @@ -41,6 +41,7 @@ describe('socket scan reach', async () => { Reachability Options --dynamic-sbom-inference For Gradle, sbt, Maven and .NET: generate a Socket facts SBOM (produced directly by each package manager) per independent build root, instead of one synthetic root. The reachability analysis is split per project/module accordingly. --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma separated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget (.NET). Defaults to all of them. + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build (unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the command working directory (\`--cwd\` if set), not the reachability target: \`tests\` matches only \`/tests\`; use \`**/tests\` to match at any depth. Negation patterns (\`!path\`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET project is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that project. A build module or project outside the scan root cannot be excluded. --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as multiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defaults to all advisories. --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. 512MB, 8GB). The default is 8GB. diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index bf0d4ac1b..6421c5004 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -284,7 +284,7 @@ async function createNewScan( cwd, excludePaths: reach.excludePaths, hints, - purlTypes: reach.dynamicSbomInference, + ...reach.dynamicSbomInference, }) scanTargets = Array.from( new Set([...scanTargets, ...dynamicResult.factsPaths]), @@ -301,7 +301,9 @@ async function createNewScan( if (reach.dynamicSbomInference) { // Already generated recursively above; resolving cwd's own build // root a second time would race on the same facts file. - for (const tool of buildToolsFor(reach.dynamicSbomInference)) { + for (const tool of buildToolsFor( + reach.dynamicSbomInference.purlTypes, + )) { detected[tool] = false } } diff --git a/src/commands/scan/handle-create-new-scan.test.mts b/src/commands/scan/handle-create-new-scan.test.mts index 622594929..64a4b282c 100644 --- a/src/commands/scan/handle-create-new-scan.test.mts +++ b/src/commands/scan/handle-create-new-scan.test.mts @@ -13,7 +13,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { finalizeTier1Scan } from './finalize-tier1-scan.mts' import { handleCreateNewScan } from './handle-create-new-scan.mts' import { outputCreateNewScan } from './output-create-new-scan.mts' -import { makeReachabilityOptions } from '../../../test/reachability-options.mts' +import { + makeDynamicSbomInference, + makeReachabilityOptions, +} from '../../../test/reachability-options.mts' import { logger } from '../../utils/logger.mts' import type { HandleCreateNewScanConfig } from './handle-create-new-scan.mts' @@ -354,7 +357,7 @@ describe('handleCreateNewScan excludePaths', () => { ]) const config = createConfig({ autoManifest: false, targets: ['/repo'] }) - config.reach.dynamicSbomInference = ['maven', 'nuget'] + config.reach.dynamicSbomInference = makeDynamicSbomInference() await handleCreateNewScan(config) @@ -400,7 +403,7 @@ describe('handleCreateNewScan excludePaths', () => { ...createConfig({ autoManifest: true, targets: ['/repo'] }), hints, } - config.reach.dynamicSbomInference = ['maven', 'nuget'] + config.reach.dynamicSbomInference = makeDynamicSbomInference() await handleCreateNewScan(config) @@ -447,7 +450,9 @@ describe('handleCreateNewScan excludePaths', () => { ]) const config = createConfig({ autoManifest: true, targets: ['/repo'] }) - config.reach.dynamicSbomInference = ['nuget'] + config.reach.dynamicSbomInference = makeDynamicSbomInference({ + purlTypes: ['nuget'], + }) await handleCreateNewScan(config) @@ -471,7 +476,7 @@ describe('handleCreateNewScan excludePaths', () => { ]) const config = createConfig({ autoManifest: false, targets: ['/repo'] }) - config.reach.dynamicSbomInference = ['maven', 'nuget'] + config.reach.dynamicSbomInference = makeDynamicSbomInference() await expect(handleCreateNewScan(config)).rejects.toThrow( /one or more independent build roots failed/i, @@ -484,7 +489,7 @@ describe('handleCreateNewScan excludePaths', () => { mockGenerateRecursiveManifests.mockResolvedValueOnce([]) const config = createConfig({ autoManifest: false, targets: ['/repo'] }) - config.reach.dynamicSbomInference = ['maven', 'nuget'] + config.reach.dynamicSbomInference = makeDynamicSbomInference() await handleCreateNewScan(config) @@ -499,7 +504,7 @@ describe('handleCreateNewScan excludePaths', () => { ]) const config = createConfig({ autoManifest: false, targets: ['/repo'] }) - config.reach.dynamicSbomInference = ['maven', 'nuget'] + config.reach.dynamicSbomInference = makeDynamicSbomInference() await handleCreateNewScan(config) @@ -528,7 +533,7 @@ describe('handleCreateNewScan excludePaths', () => { ) const config = createConfig({ autoManifest: false, targets: ['/repo'] }) - config.reach.dynamicSbomInference = ['maven', 'nuget'] + config.reach.dynamicSbomInference = makeDynamicSbomInference() config.reach.runReachabilityAnalysis = true await handleCreateNewScan(config) @@ -557,7 +562,9 @@ describe('handleCreateNewScan excludePaths', () => { }, ]) const config = createConfig({ autoManifest: false, targets: ['/repo'] }) - config.reach.dynamicSbomInference = ['maven'] + config.reach.dynamicSbomInference = makeDynamicSbomInference({ + purlTypes: ['maven'], + }) config.reach.runReachabilityAnalysis = true config.reach.reachDisableDependencyDownloads = true diff --git a/src/commands/scan/handle-scan-reach.mts b/src/commands/scan/handle-scan-reach.mts index ba936eb54..de3643b00 100644 --- a/src/commands/scan/handle-scan-reach.mts +++ b/src/commands/scan/handle-scan-reach.mts @@ -21,9 +21,9 @@ import { } from '../manifest/run-manifest-facts.mts' import type { ReachabilityOptions } from './perform-reachability-analysis.mts' +import type { DynamicSbomInference } from './reachability-flags.mts' import type { DynamicSbomInferenceResult } from './run-dynamic-sbom-inference.mts' import type { OutputKind } from '../../types.mts' -import type { FactsOnlyTypes } from '../../utils/coana.mts' import type { SocketFactsWorkDir } from '../manifest/run-manifest-facts.mts' export type HandleScanReachConfig = { @@ -46,9 +46,11 @@ async function runScanReach( reachabilityOptions, targets, }: HandleScanReachConfig, - // The ecosystems --dynamic-sbom-inference generates facts for, with the - // work dir Coana's run reads. - dsi: { purlTypes: FactsOnlyTypes; workDir: SocketFactsWorkDir } | undefined, + // What --dynamic-sbom-inference generates facts for, with the work dir + // Coana's run reads. + dsi: + | { inference: DynamicSbomInference; workDir: SocketFactsWorkDir } + | undefined, ) { const { spinner } = constants @@ -70,7 +72,7 @@ async function runScanReach( cwd, excludePaths: reachabilityOptions.excludePaths, hints: EXCLUDE_PATHS_HINTS, - purlTypes: dsi.purlTypes, + ...dsi.inference, }) scanTargets = Array.from( new Set([...scanTargets, ...dynamicResult.factsPaths]), @@ -177,14 +179,14 @@ async function runScanReach( export async function handleScanReach( config: HandleScanReachConfig, ): Promise { - const purlTypes = config.reachabilityOptions.dynamicSbomInference + const inference = config.reachabilityOptions.dynamicSbomInference // Coana's run reads what facts generation keeps in the work dir. - return purlTypes + return inference ? await withTmpDir( 'socket-dynamic-sbom-inference-', async dir => await runScanReach(config, { - purlTypes, + inference, workDir: await createSocketFactsWorkDir(dir, 'reachability'), }), ) diff --git a/src/commands/scan/handle-scan-reach.test.mts b/src/commands/scan/handle-scan-reach.test.mts index 1bb079985..c532e25e5 100644 --- a/src/commands/scan/handle-scan-reach.test.mts +++ b/src/commands/scan/handle-scan-reach.test.mts @@ -1,7 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { handleScanReach } from './handle-scan-reach.mts' -import { makeReachabilityOptions } from '../../../test/reachability-options.mts' +import { + makeDynamicSbomInference, + makeReachabilityOptions, +} from '../../../test/reachability-options.mts' import { EXCLUDE_PATHS_HINTS } from '../manifest/run-manifest-facts.mts' const { @@ -344,7 +347,7 @@ describe('handleScanReach', () => { describe('dynamic SBOM inference', () => { const baseReachabilityOptions = { ...makeReachabilityOptions(), - dynamicSbomInference: ['maven', 'nuget'], + dynamicSbomInference: makeDynamicSbomInference(), excludePaths: ['vendor/**'], } @@ -391,7 +394,7 @@ describe('handleScanReach', () => { cwd: '/repo', excludePaths: ['vendor/**'], hints: EXCLUDE_PATHS_HINTS, - purlTypes: ['maven', 'nuget'], + ...makeDynamicSbomInference(), }) expect(mockGetPackageFilesForScan).toHaveBeenCalledWith( [ diff --git a/src/commands/scan/perform-reachability-analysis.mts b/src/commands/scan/perform-reachability-analysis.mts index e141237f9..81c008367 100644 --- a/src/commands/scan/perform-reachability-analysis.mts +++ b/src/commands/scan/perform-reachability-analysis.mts @@ -19,6 +19,7 @@ import { setupSdk } from '../../utils/sdk.mts' import { socketDevLink } from '../../utils/terminal-link.mts' import { fetchOrganization } from '../organization/fetch-organization-list.mts' +import type { DynamicSbomInference } from './reachability-flags.mts' import type { CResult, OutputKind } from '../../types.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' @@ -27,8 +28,8 @@ import type { SocketFactsSidecarEntry } from '../manifest/run-manifest-facts.mts import type { StdioOptions } from 'node:child_process' export type ReachabilityOptions = { - // The ecosystems to generate Socket facts for; undefined when off. - dynamicSbomInference: FactsOnlyTypes | undefined + // Undefined when off. + dynamicSbomInference: DynamicSbomInference | undefined excludePaths: string[] // GHSA IDs. Empty means all advisories. reachAdvisories: string[] diff --git a/src/commands/scan/perform-reachability-analysis.test.mts b/src/commands/scan/perform-reachability-analysis.test.mts index 55c862b97..85ba32161 100644 --- a/src/commands/scan/perform-reachability-analysis.test.mts +++ b/src/commands/scan/perform-reachability-analysis.test.mts @@ -21,7 +21,10 @@ import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { performReachabilityAnalysis } from './perform-reachability-analysis.mts' -import { makeReachabilityOptions } from '../../../test/reachability-options.mts' +import { + makeDynamicSbomInference, + makeReachabilityOptions, +} from '../../../test/reachability-options.mts' import type { ReachabilityAnalysisOptions, @@ -407,7 +410,7 @@ describe('performReachabilityAnalysis --use-only-socket-facts-artifacts gating', it('writes no sidecar without facts-only types or sidecar entries', async () => { const args = await coanaArgsFor(scanCwd, { - dynamicSbomInference: ['maven', 'nuget'], + dynamicSbomInference: makeDynamicSbomInference(), }) expect(args).not.toContain('--socket-facts-sidecar') }) diff --git a/src/commands/scan/reachability-flags.mts b/src/commands/scan/reachability-flags.mts index 8f8361383..8ba7e2539 100644 --- a/src/commands/scan/reachability-flags.mts +++ b/src/commands/scan/reachability-flags.mts @@ -21,29 +21,51 @@ import type { FactsOnlyTypes } from '../../utils/coana.mts' export const DYNAMIC_SBOM_INFERENCE_DESCRIPTION = 'For Gradle, sbt, Maven and .NET: generate a Socket facts SBOM (produced directly by each package manager) per independent build root, instead of one synthetic root.' -// Not in reachabilityFlags: it applies to a `scan create` without --reach too. -export const dynamicSbomInferenceEcosystemsFlags: MeowFlags = { +// Not in reachabilityFlags: they apply to a `scan create` without --reach too. +export const dynamicSbomInferenceFlags: MeowFlags = { dynamicSbomInferenceEcosystems: { type: 'string', isMultiple: true, description: `With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma separated value or as multiple flags; the others keep their manifest files as they are. Supported: ${joinAnd(FACTS_PURL_TYPES.map(t => `${t} (${joinAnd(buildToolLabelsFor([t]))})`))}. Defaults to all of them.`, }, + dynamicSbomInferenceIgnoreUnresolved: { + type: 'boolean', + description: + "With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build (unresolved deps are not emitted to the facts files); overrides each build's socket.json setting.", + }, +} + +export type DynamicSbomInference = { + // Unset leaves it to each build's socket.json. + ignoreUnresolved: boolean | undefined + purlTypes: FactsOnlyTypes } export function parseDynamicSbomInferenceFlags(flags: { [flag: string]: unknown -}): FactsOnlyTypes | undefined { +}): DynamicSbomInference | undefined { const raw = cmdFlagValueToArray(flags['dynamicSbomInferenceEcosystems']) + const ignoreUnresolved = flags['dynamicSbomInferenceIgnoreUnresolved'] as + | boolean + | undefined if (!flags['dynamicSbomInference']) { if (raw.length) { throw new InputError( '--dynamic-sbom-inference-ecosystems requires --dynamic-sbom-inference', ) } + if (ignoreUnresolved !== undefined) { + throw new InputError( + '--dynamic-sbom-inference-ignore-unresolved requires --dynamic-sbom-inference', + ) + } return undefined } const selected = parseEcosystemChoices(raw, FACTS_PURL_TYPES) - return isFactsOnlyTypes(selected) ? selected : FACTS_PURL_TYPES + return { + ignoreUnresolved, + purlTypes: isFactsOnlyTypes(selected) ? selected : FACTS_PURL_TYPES, + } } export const reachabilityFlags: MeowFlags = { diff --git a/src/commands/scan/reachability-flags.test.mts b/src/commands/scan/reachability-flags.test.mts index 5b0f9ef36..f8dd3f42d 100644 --- a/src/commands/scan/reachability-flags.test.mts +++ b/src/commands/scan/reachability-flags.test.mts @@ -5,22 +5,39 @@ import { parseDynamicSbomInferenceFlags } from './reachability-flags.mts' describe('parseDynamicSbomInferenceFlags', () => { it.for([ { flags: {}, expected: undefined }, - { flags: { dynamicSbomInference: true }, expected: ['maven', 'nuget'] }, + { + flags: { dynamicSbomInference: true }, + expected: { ignoreUnresolved: undefined, purlTypes: ['maven', 'nuget'] }, + }, { flags: { dynamicSbomInference: true, dynamicSbomInferenceEcosystems: ['NuGet,nuget'], }, - expected: ['nuget'], + expected: { ignoreUnresolved: undefined, purlTypes: ['nuget'] }, }, { flags: { dynamicSbomInference: true, dynamicSbomInferenceEcosystems: ['maven', 'Maven,NUGET'], }, - expected: ['maven', 'nuget'], + expected: { ignoreUnresolved: undefined, purlTypes: ['maven', 'nuget'] }, + }, + { + flags: { + dynamicSbomInference: true, + dynamicSbomInferenceIgnoreUnresolved: true, + }, + expected: { ignoreUnresolved: true, purlTypes: ['maven', 'nuget'] }, + }, + { + flags: { + dynamicSbomInference: true, + dynamicSbomInferenceIgnoreUnresolved: false, + }, + expected: { ignoreUnresolved: false, purlTypes: ['maven', 'nuget'] }, }, - ])('reads $flags as $expected', ({ expected, flags }) => { + ])('reads $flags', ({ expected, flags }) => { expect(parseDynamicSbomInferenceFlags(flags)).toEqual(expected) }) @@ -30,6 +47,16 @@ describe('parseDynamicSbomInferenceFlags', () => { error: '--dynamic-sbom-inference-ecosystems requires --dynamic-sbom-inference', }, + { + flags: { dynamicSbomInferenceIgnoreUnresolved: true }, + error: + '--dynamic-sbom-inference-ignore-unresolved requires --dynamic-sbom-inference', + }, + { + flags: { dynamicSbomInferenceIgnoreUnresolved: false }, + error: + '--dynamic-sbom-inference-ignore-unresolved requires --dynamic-sbom-inference', + }, { flags: { dynamicSbomInference: true, diff --git a/src/commands/scan/reject-manifest-only-flags.mts b/src/commands/scan/reject-manifest-only-flags.mts new file mode 100644 index 000000000..641574db5 --- /dev/null +++ b/src/commands/scan/reject-manifest-only-flags.mts @@ -0,0 +1,32 @@ +import { joinAnd } from '../../utils/arrays.mts' +import { InputError } from '../../utils/errors.mts' +import { camelToKebab } from '../../utils/strings.mts' +import { DSI_SETUP_COMMAND } from '../manifest/run-manifest-facts.mts' + +// Build options the scan commands read from each build's socket.json. +const SOCKET_JSON_ONLY_FLAGS = ['excludeConfigs', 'includeConfigs', 'verbose'] + +// `socket manifest ` takes these as flags. The scan commands do not +// declare them, so each would take the next argument, which can be the scan +// target, as its value. +export function rejectManifestOnlyFlags( + flags: Record, + command: string, +): void { + const parts: string[] = [] + if (flags['ignoreUnresolved'] !== undefined) { + parts.push( + `\`${command}\` takes --dynamic-sbom-inference-ignore-unresolved, with --dynamic-sbom-inference, in place of --ignore-unresolved.`, + ) + } + const given = SOCKET_JSON_ONLY_FLAGS.filter(name => flags[name] !== undefined) + if (given.length) { + const them = given.length === 1 ? 'it' : 'them' + parts.push( + `\`${command}\` reads ${joinAnd(given.map(name => `--${camelToKebab(name)}`))} from each build's socket.json instead of taking ${them} as ${given.length === 1 ? 'a flag' : 'flags'}. Set ${them} there, for example with \`${DSI_SETUP_COMMAND}\`.`, + ) + } + if (parts.length) { + throw new InputError(parts.join(' ')) + } +} diff --git a/src/commands/scan/reject-manifest-only-flags.test.mts b/src/commands/scan/reject-manifest-only-flags.test.mts new file mode 100644 index 000000000..580a239f0 --- /dev/null +++ b/src/commands/scan/reject-manifest-only-flags.test.mts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' + +import { rejectManifestOnlyFlags } from './reject-manifest-only-flags.mts' + +describe('rejectManifestOnlyFlags', () => { + it('passes flags the scan commands take', () => { + expect(() => + rejectManifestOnlyFlags( + { + dynamicSbomInference: true, + dynamicSbomInferenceIgnoreUnresolved: true, + }, + 'socket scan create', + ), + ).not.toThrow() + }) + + it.for([ + { + error: + '`socket scan create` takes --dynamic-sbom-inference-ignore-unresolved, with --dynamic-sbom-inference, in place of --ignore-unresolved.', + flags: { ignoreUnresolved: true }, + name: '--ignore-unresolved', + }, + { + error: + "`socket scan create` reads --verbose from each build's socket.json instead of taking it as a flag. Set it there, for example with `socket manifest setup --dynamic-sbom-inference`.", + flags: { verbose: false }, + name: '--no-verbose', + }, + { + error: + "`socket scan create` takes --dynamic-sbom-inference-ignore-unresolved, with --dynamic-sbom-inference, in place of --ignore-unresolved. `socket scan create` reads --exclude-configs and --include-configs from each build's socket.json instead of taking them as flags. Set them there, for example with `socket manifest setup --dynamic-sbom-inference`.", + flags: { + excludeConfigs: 'test*', + ignoreUnresolved: true, + includeConfigs: 'compile', + }, + name: 'several flags', + }, + ])('rejects $name', ({ error, flags }) => { + expect(() => rejectManifestOnlyFlags(flags, 'socket scan create')).toThrow( + error, + ) + }) +}) diff --git a/src/commands/scan/run-dynamic-sbom-inference.mts b/src/commands/scan/run-dynamic-sbom-inference.mts index 659ad67fc..59c9bce85 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.mts @@ -15,8 +15,8 @@ import { buildToolLabelsFor, } from '../manifest/scripts/build-tool.mts' +import type { DynamicSbomInference } from './reachability-flags.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' -import type { PURL_Type } from '../../utils/ecosystem.mts' import type { RecursiveManifestOutcome } from '../manifest/generate-recursive-manifests.mts' import type { CommandHints, @@ -75,19 +75,20 @@ export async function runDynamicSbomInference({ cwd, excludePaths, hints, + ignoreUnresolved, purlTypes, -}: { +}: DynamicSbomInference & { context: SocketFactsContext cwd: string excludePaths: string[] hints: CommandHints - purlTypes: readonly PURL_Type[] }): Promise { const outcomes = await generateRecursiveManifests({ context, cwd, excludePaths, hints, + ignoreUnresolved, purlTypes, verbose: false, }) diff --git a/src/commands/scan/run-dynamic-sbom-inference.test.mts b/src/commands/scan/run-dynamic-sbom-inference.test.mts index a7ef32489..f54c13a8c 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.test.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.test.mts @@ -8,8 +8,9 @@ import { runDynamicSbomInference, withoutDiscardedFacts, } from './run-dynamic-sbom-inference.mts' +import { makeDynamicSbomInference } from '../../../test/reachability-options.mts' -import type { PURL_Type } from '../../utils/ecosystem.mts' +import type { FactsOnlyTypes } from '../../utils/coana.mts' const { mockGenerateRecursiveManifests, mockInfo, mockWarn } = vi.hoisted( () => ({ @@ -46,13 +47,14 @@ type Purpose = 'fix' | 'reachability' | 'upload' function run( purpose: Purpose, - purlTypes: readonly PURL_Type[] = ['maven', 'nuget'], + purlTypes: FactsOnlyTypes = ['maven', 'nuget'], + ignoreUnresolved?: boolean | undefined, ) { return runDynamicSbomInference({ context: { ...context, workDir: workDirFor(purpose) }, cwd: '/repo', excludePaths: ['vendor/**'], - purlTypes, + ...makeDynamicSbomInference({ ignoreUnresolved, purlTypes }), }) } @@ -72,12 +74,25 @@ describe('runDynamicSbomInference', () => { context: { ...context, workDir: workDirFor(purpose) }, cwd: '/repo', excludePaths: ['vendor/**'], - purlTypes: ['maven', 'nuget'], + ...makeDynamicSbomInference(), verbose: false, }) }, ) + it.for([true, false])( + 'passes --dynamic-sbom-inference-ignore-unresolved (%s) on to every build', + async ignoreUnresolved => { + mockGenerateRecursiveManifests.mockResolvedValueOnce([generated]) + + await run('upload', undefined, ignoreUnresolved) + + expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith( + expect.objectContaining({ ignoreUnresolved }), + ) + }, + ) + it('returns only the generated facts paths, ignoring empty and skipped roots', async () => { mockGenerateRecursiveManifests.mockResolvedValueOnce([ generated, @@ -106,7 +121,7 @@ describe('runDynamicSbomInference', () => { ]) }) - it.for<{ message: string; purlTypes?: PURL_Type[] }>([ + it.for<{ message: string; purlTypes?: FactsOnlyTypes }>([ { message: 'No .NET, Gradle, Maven, or sbt build root was found' }, { message: 'No .NET build root was found', purlTypes: ['nuget'] }, ])( @@ -127,7 +142,7 @@ describe('runDynamicSbomInference', () => { error: RegExp name: string outcomes: object[] - purlTypes?: PURL_Type[] + purlTypes?: FactsOnlyTypes }>([ { name: 'a discovered build root failed to generate facts', diff --git a/src/commands/scan/warn-socket-json-only-flags.mts b/src/commands/scan/warn-socket-json-only-flags.mts deleted file mode 100644 index 310310267..000000000 --- a/src/commands/scan/warn-socket-json-only-flags.mts +++ /dev/null @@ -1,26 +0,0 @@ -import { logger } from '../../utils/logger.mts' -import { camelToKebab } from '../../utils/strings.mts' -import { DSI_SETUP_COMMAND } from '../manifest/run-manifest-facts.mts' - -// Build options that `socket manifest ` takes as flags but the scan -// commands read from each build's socket.json, so passing them does nothing. -const SOCKET_JSON_ONLY_FLAGS = [ - 'excludeConfigs', - 'ignoreUnresolved', - 'includeConfigs', - 'verbose', -] - -export function warnSocketJsonOnlyFlags( - flags: Record, - command: string, -): void { - const ignored = SOCKET_JSON_ONLY_FLAGS.filter( - name => flags[name] !== undefined, - ).map(name => `--${camelToKebab(name)}`) - if (ignored.length) { - logger.warn( - `Ignoring ${ignored.join(', ')}: \`${command}\` reads build options from each build's socket.json. Set them there, for example with \`${DSI_SETUP_COMMAND}\`.`, - ) - } -} diff --git a/test/reachability-options.mts b/test/reachability-options.mts index 70ed0eaa6..f45738200 100644 --- a/test/reachability-options.mts +++ b/test/reachability-options.mts @@ -1,4 +1,16 @@ import type { ReachabilityOptions } from '../src/commands/scan/perform-reachability-analysis.mts' +import type { DynamicSbomInference } from '../src/commands/scan/reachability-flags.mts' + +// --dynamic-sbom-inference for every ecosystem, with only what a test sets. +export function makeDynamicSbomInference( + overrides: Partial = {}, +): DynamicSbomInference { + return { + ignoreUnresolved: undefined, + purlTypes: ['maven', 'nuget'], + ...overrides, + } +} // Mirrors the CLI flag defaults, so a test spreads this and sets only what it // exercises. diff --git a/test/snapshots/termless/cli.native.socket-help-fix.svg b/test/snapshots/termless/cli.native.socket-help-fix.svg index 480e3367b..abb0a0976 100644 --- a/test/snapshots/termless/cli.native.socket-help-fix.svg +++ b/test/snapshots/termless/cli.native.socket-help-fix.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.0-rc.0 | cmd: socket fix | org: (not set) | token: (not set) @@ -57,103 +57,107 @@ .NET). Defaults to all of them. - --ecosystems Limit fix analysis to specific ecosystems. Accepts space- or comma-separated values and is case-insensitive. Default + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build -s to all ecosystems. +(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. - --exclude-paths Skip matching paths from the scan entirely: manifests under these paths are not uploaded, and fixes are not applied + --ecosystems Limit fix analysis to specific ecosystems. Accepts space- or comma-separated values and is case-insensitive. Default -to workspaces under them. Patterns are anchored micromatch globs matched relative to the target directory (CWD); `data/postgres/pgdata` matc +s to all ecosystems. -hes that exact path, `**/pgdata` matches at any depth. Use this to skip directories the current user cannot read so they do not abort manife + --exclude-paths Skip matching paths from the scan entirely: manifests under these paths are not uploaded, and fixes are not applied -st collection. Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. +to workspaces under them. Patterns are anchored micromatch globs matched relative to the target directory (CWD); `data/postgres/pgdata` matc - --fix-version Override the version of @coana-tech/cli used for fix analysis. Default: 15.15.9. +hes that exact path, `**/pgdata` matches at any depth. Use this to skip directories the current user cannot read so they do not abort manife - --id Provide a list of vulnerability identifiers to compute fixes for: +st collection. Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. - - GHSA IDs (​https://docs.github.com/en/code-security/security-advisories/working-with-global-security-advisories + --fix-version Override the version of @coana-tech/cli used for fix analysis. Default: 15.15.9. --from-the-github-advisory-database/about-the-github-advisory-database#about-ghsa-ids​) (e.g., GHSA-xxxx-xxxx-xxxx) + --id Provide a list of vulnerability identifiers to compute fixes for: - - CVE IDs (​https://cve.mitre.org/cve/identifiers/​) (e.g., CVE-2026-1234) - automatically converted to GHSA + - GHSA IDs (​https://docs.github.com/en/code-security/security-advisories/working-with-global-security-advisories - - PURLs (​https://github.com/package-url/purl-spec​) (e.g., pkg:npm/package@1.0.0) - automatically converted to GH +-from-the-github-advisory-database/about-the-github-advisory-database#about-ghsa-ids​) (e.g., GHSA-xxxx-xxxx-xxxx) -SA + - CVE IDs (​https://cve.mitre.org/cve/identifiers/​) (e.g., CVE-2026-1234) - automatically converted to GHSA - Can be provided as comma separated values or as multiple flags. Cannot be used with --all. + - PURLs (​https://github.com/package-url/purl-spec​) (e.g., pkg:npm/package@1.0.0) - automatically converted to GH - --include Include workspaces matching these glob patterns. Can be provided as comma separated values or as multiple flags +SA - --json Output as JSON + Can be provided as comma separated values or as multiple flags. Cannot be used with --all. - --markdown Output as Markdown + --include Include workspaces matching these glob patterns. Can be provided as comma separated values or as multiple flags - --minimum-release-age Set a minimum age requirement for suggested upgrade versions (e.g., 1h, 2d, 3w). A higher age requirement reduces + --json Output as JSON - the risk of upgrading to malicious versions. For example, setting the value to 1 week (1w) gives ecosystem maintainers one week to remove p + --markdown Output as Markdown -otentially malicious versions. + --minimum-release-age Set a minimum age requirement for suggested upgrade versions (e.g., 1h, 2d, 3w). A higher age requirement reduces - --no-apply-fixes Compute fixes only, do not apply them. Logs what upgrades would be applied. If combined with --output-file, the outp + the risk of upgrading to malicious versions. For example, setting the value to 1 week (1w) gives ecosystem maintainers one week to remove p -ut file will contain the upgrades that would be applied. +otentially malicious versions. - --no-major-updates Do not suggest or apply fixes that require major version updates of direct or transitive dependencies + --no-apply-fixes Compute fixes only, do not apply them. Logs what upgrades would be applied. If combined with --output-file, the outp - --output-file Path to store upgrades as a JSON file at this path. +ut file will contain the upgrades that would be applied. - --package-managers Limit fix analysis to specific package managers within an ecosystem (e.g. NPM, PNPM, YARN, MAVEN, POETRY). Accepts s + --no-major-updates Do not suggest or apply fixes that require major version updates of direct or transitive dependencies -pace- or comma-separated values and is case-insensitive. When combined with --ecosystems, an artifact must satisfy both filters. + --output-file Path to store upgrades as a JSON file at this path. - --pr-limit Maximum number of pull requests to create in CI mode (default 10). Has no effect in local mode. + --package-managers Limit fix analysis to specific package managers within an ecosystem (e.g. NPM, PNPM, YARN, MAVEN, POETRY). Accepts s - --range-style Define how dependency version ranges are updated in package.json (default 'preserve'). +pace- or comma-separated values and is case-insensitive. When combined with --ecosystems, an artifact must satisfy both filters. - Available styles: + --pr-limit Maximum number of pull requests to create in CI mode (default 10). Has no effect in local mode. - * pin - Use the exact version (e.g. 1.2.3) + --range-style Define how dependency version ranges are updated in package.json (default 'preserve'). - * preserve - Retain the existing version range style as-is + Available styles: - --show-affected-direct-dependencies List the direct dependencies responsible for introducing transitive vulnerabilities and list the up + * pin - Use the exact version (e.g. 1.2.3) -dates required to resolve the vulnerabilities + * preserve - Retain the existing version range style as-is - --silence Silence all output except the final result + --show-affected-direct-dependencies List the direct dependencies responsible for introducing transitive vulnerabilities and list the up - +dates required to resolve the vulnerabilities - Environment Variables (for CI/PR mode) + --silence Silence all output except the final result - CI Set to enable CI mode + - SOCKET_CLI_GITHUB_TOKEN GitHub token for PR creation (or GITHUB_TOKEN) + Environment Variables (for CI/PR mode) - SOCKET_CLI_GIT_USER_NAME Git username for commits + CI Set to enable CI mode - SOCKET_CLI_GIT_USER_EMAIL Git email for commits + SOCKET_CLI_GITHUB_TOKEN GitHub token for PR creation (or GITHUB_TOKEN) - + SOCKET_CLI_GIT_USER_NAME Git username for commits - Examples + SOCKET_CLI_GIT_USER_EMAIL Git email for commits - $ socket fix + - $ socket fix --id CVE-2021-23337 + Examples - $ socket fix ./path/to/project --range-style pin + $ socket fix - + $ socket fix --id CVE-2021-23337 - + $ socket fix ./path/to/project --range-style pin - \ No newline at end of file + + + + + \ No newline at end of file diff --git a/test/snapshots/termless/cli.native.socket-help-scan-create.svg b/test/snapshots/termless/cli.native.socket-help-scan-create.svg index 550c83391..543ad78f3 100644 --- a/test/snapshots/termless/cli.native.socket-help-scan-create.svg +++ b/test/snapshots/termless/cli.native.socket-help-scan-create.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.0-rc.0 | cmd: socket scan create | org: (not set) | token: (not set) @@ -55,207 +55,211 @@ .NET). Defaults to all of them. - --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build -full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman +(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. -d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. + --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) - Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj +full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman -ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr +d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. -oject. A build module or project outside the scan root cannot be excluded. + Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj - --interactive Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, +ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr - defaulting them to cancel/no. +oject. A build module or project outside the scan root cannot be excluded. - --json Output as JSON + --interactive Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, - --markdown Output as Markdown + defaulting them to cancel/no. - --org Force override the organization slug, overrides the default org from config + --json Output as JSON - --pull-request Pull request number + --markdown Output as Markdown - --reach Run full application reachability analysis + --org Force override the organization slug, overrides the default org from config - --read-only Similar to --dry-run except it can read from remote, stops before it would create an actual report + --pull-request Pull request number - --repo Repository name + --reach Run full application reachability analysis - --report Wait for the scan creation to complete, then basically run `socket scan report` on it + --read-only Similar to --dry-run except it can read from remote, stops before it would create an actual report - --report-level Which policy level alerts should be reported (default 'error') + --repo Repository name - --set-as-alerts-page When true and if this is the "default branch" then this Scan will be the one reflected on your alerts page. See he + --report Wait for the scan creation to complete, then basically run `socket scan report` on it -lp for details. Defaults to true. + --report-level Which policy level alerts should be reported (default 'error') - --tmp Set the visibility (true/false) of the scan in your dashboard. + --set-as-alerts-page When true and if this is the "default branch" then this Scan will be the one reflected on your alerts page. See he - --uv-members Scan each TARGET directory as a uv project, using the versions pinned in its uv.lock or its workspace root uv.lock. +lp for details. Defaults to true. -Uploads a CycloneDX dependency graph per TARGET in place of manifest discovery, including all extras and dependency groups. Requires uv on P + --tmp Set the visibility (true/false) of the scan in your dashboard. -ATH; standalone builds use SOCKET_CLI_UV_PATH. + --uv-members Scan each TARGET directory as a uv project, using the versions pinned in its uv.lock or its workspace root uv.lock. - --workspace The workspace in the Socket Organization that the repository is in to associate with the full scan. +Uploads a CycloneDX dependency graph per TARGET in place of manifest discovery, including all extras and dependency groups. Requires uv on P - +ATH; standalone builds use SOCKET_CLI_UV_PATH. - Reachability Options (when --reach is used) + --workspace The workspace in the Socket Organization that the repository is in to associate with the full scan. - --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul + -tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau + Reachability Options (when --reach is used) -lts to all advisories. + --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul - --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. +tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau -512MB, 8GB). The default is 8GB. +lts to all advisories. - --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 + --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. -m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. +512MB, 8GB). The default is 8GB. - --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th + --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 -at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. +m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. - --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back + --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th -to precomputed reachability results. By default, the CLI halts on analysis errors. +at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. - --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi + --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back -lity results. By default, the CLI halts on installation errors. +to precomputed reachability results. By default, the CLI halts on analysis errors. - --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version + --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi - catalog / pre-generated SBOM). By default, the CLI halts. +lity results. By default, the CLI halts on installation errors. - --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa + --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version -ult, the CLI halts. + catalog / pre-generated SBOM). By default, the CLI halts. - --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. + --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa - --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. +ult, the CLI halts. - --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. + --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. - --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director + --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. -y or module cache). Missing dependencies count as installation failures. + --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. - --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. + --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director - --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp +y or module cache). Missing dependencies count as installation failures. -orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. + --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. - --reach-fallback-to-regular-scan If reachability analysis fails, continue with a regular SCA scan (without reachability results) instea + --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp -d of halting. By default, the CLI halts on reachability errors. +orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. - --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d + --reach-fallback-to-regular-scan If reachability analysis fails, continue with a regular SCA scan (without reachability results) instea -eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a +d of halting. By default, the CLI halts on reachability errors. -n SBOM carrying stale reachability results. + --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d - --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous +eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a - runs to speed up the analysis. +n SBOM carrying stale reachability results. - --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your + --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous -project. + runs to speed up the analysis. - --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. + --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your - +project. - Uploads the specified dependency manifest files for Go, Gradle, JavaScript, + --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. - Kotlin, Python, and Scala. Files like "package.json" and "requirements.txt". + - If any folder is specified, the ones found in there recursively are uploaded. + Uploads the specified dependency manifest files for Go, Gradle, JavaScript, - + Kotlin, Python, and Scala. Files like "package.json" and "requirements.txt". - Details on TARGET: + If any folder is specified, the ones found in there recursively are uploaded. - - Defaults to the current dir (cwd) if none given + Details on TARGET: - - Multiple targets can be specified + - - If a target is a file, only that file is checked + - Defaults to the current dir (cwd) if none given - - If it is a dir, the dir is scanned for any supported manifest files + - Multiple targets can be specified - - Dirs MUST be within the current dir (cwd), you can use --cwd to change it + - If a target is a file, only that file is checked - - Supports globbing such as "**/package.json", "**/requirements.txt", etc. + - If it is a dir, the dir is scanned for any supported manifest files - - Ignores any file specified in your project's ".gitignore" + - Dirs MUST be within the current dir (cwd), you can use --cwd to change it - - Also a sensible set of default ignores from the "ignore-by-default" module + - Supports globbing such as "**/package.json", "**/requirements.txt", etc. - + - Ignores any file specified in your project's ".gitignore" - The --repo and --branch flags tell Socket to associate this Scan with that + - Also a sensible set of default ignores from the "ignore-by-default" module - repo/branch. The names will show up on your dashboard on the Socket website. - + + The --repo and --branch flags tell Socket to associate this Scan with that - Note: for a first run you probably want to set --default-branch to indicate + repo/branch. The names will show up on your dashboard on the Socket website. - the default branch name, like "main" or "master". - + + Note: for a first run you probably want to set --default-branch to indicate - The "alerts page" (​https://socket.dev/dashboard/org/YOURORG/alerts​) will show + the default branch name, like "main" or "master". - the results from the last scan designated as the "pending head" on the branch + - configured on Socket to be the "default branch". When creating a scan the + The "alerts page" (​https://socket.dev/dashboard/org/YOURORG/alerts​) will show - --set-as-alerts-page flag will default to true to update this. You can prevent + the results from the last scan designated as the "pending head" on the branch - this by using --no-set-as-alerts-page. This flag is ignored for any branch that + configured on Socket to be the "default branch". When creating a scan the - is not designated as the "default branch". It is disabled when using --tmp. + --set-as-alerts-page flag will default to true to update this. You can prevent - + this by using --no-set-as-alerts-page. This flag is ignored for any branch that - You can use `socket scan setup` to configure certain repo flag defaults. + is not designated as the "default branch". It is disabled when using --tmp. - Examples + You can use `socket scan setup` to configure certain repo flag defaults. - $ socket scan create + - $ socket scan create ./proj --json + Examples - $ socket scan create --repo=test-repo --branch=main ./package.json + $ socket scan create - $ socket scan create --uv-members ./packages/api ./packages/worker + $ socket scan create ./proj --json - + $ socket scan create --repo=test-repo --branch=main ./package.json - + $ socket scan create --uv-members ./packages/api ./packages/worker - \ No newline at end of file + + + + + \ No newline at end of file diff --git a/test/snapshots/termless/cli.native.socket-help-scan-reach.svg b/test/snapshots/termless/cli.native.socket-help-scan-reach.svg index 6f063d190..5a1e69e9b 100644 --- a/test/snapshots/termless/cli.native.socket-help-scan-reach.svg +++ b/test/snapshots/termless/cli.native.socket-help-scan-reach.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.0-rc.0 | cmd: socket scan reach | org: (not set) | token: (not set) @@ -51,123 +51,127 @@ .NET). Defaults to all of them. - --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build -full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman +(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. -d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. + --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) - Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj +full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman -ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr +d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. -oject. A build module or project outside the scan root cannot be excluded. + Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj - --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul +ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr -tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau +oject. A build module or project outside the scan root cannot be excluded. -lts to all advisories. + --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul - --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. +tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau -512MB, 8GB). The default is 8GB. +lts to all advisories. - --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 + --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. -m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. +512MB, 8GB). The default is 8GB. - --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th + --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 -at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. +m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. - --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back + --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th -to precomputed reachability results. By default, the CLI halts on analysis errors. +at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. - --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi + --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back -lity results. By default, the CLI halts on installation errors. +to precomputed reachability results. By default, the CLI halts on analysis errors. - --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version + --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi - catalog / pre-generated SBOM). By default, the CLI halts. +lity results. By default, the CLI halts on installation errors. - --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa + --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version -ult, the CLI halts. + catalog / pre-generated SBOM). By default, the CLI halts. - --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. + --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa - --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. +ult, the CLI halts. - --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. + --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. - --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director + --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. -y or module cache). Missing dependencies count as installation failures. + --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. - --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. + --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director - --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp +y or module cache). Missing dependencies count as installation failures. -orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. + --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. - --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d + --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp -eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a +orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. -n SBOM carrying stale reachability results. + --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d - --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous +eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a - runs to speed up the analysis. +n SBOM carrying stale reachability results. - --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your + --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous -project. + runs to speed up the analysis. - --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. + --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your - +project. - Runs the Socket reachability analysis without creating a scan in Socket. + --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. - The output is written to .socket.facts.json in the current working directory + - unless the --output flag is specified. + Runs the Socket reachability analysis without creating a scan in Socket. - + The output is written to .socket.facts.json in the current working directory - Note: Manifest files are uploaded to Socket's backend services because the + unless the --output flag is specified. - reachability analysis requires creating a Software Bill of Materials (SBOM) + - from these files before the analysis can run. + Note: Manifest files are uploaded to Socket's backend services because the - + reachability analysis requires creating a Software Bill of Materials (SBOM) - Examples + from these files before the analysis can run. - $ socket scan reach + - $ socket scan reach ./proj + Examples - $ socket scan reach ./proj --reach-ecosystems npm,pypi + $ socket scan reach - $ socket scan reach ./monorepo --dynamic-sbom-inference + $ socket scan reach ./proj - $ socket scan reach --output custom-report.json + $ socket scan reach ./proj --reach-ecosystems npm,pypi - $ socket scan reach ./proj --output ./reports/analysis.json + $ socket scan reach ./monorepo --dynamic-sbom-inference - + $ socket scan reach --output custom-report.json - + $ socket scan reach ./proj --output ./reports/analysis.json - \ No newline at end of file + + + + + \ No newline at end of file From 68edae16c5570ccff07840c7aab9fa6e2f29e64f Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Thu, 3 Dec 2026 00:07:34 +0100 Subject: [PATCH 3/3] feat(scan): add a build timeout to --dynamic-sbom-inference A hung build tool could stall --dynamic-sbom-inference indefinitely. Each build root now has a timeout covering all of its build tool runs together: --dynamic-sbom-inference-build-timeout on scan create, scan reach and fix, and --build-timeout on the manifest command. Values use the format of --reach-analysis-timeout, and 0 turns the timeout off. Coana applies the timeout. A Coana too old to take one gets no default, and setting the flag requires the first Coana that applies it. --- CHANGELOG.md | 1 + src/commands/fix/cmd-fix.integration.test.mts | 1 + .../coana-fix-dynamic-sbom-inference.test.mts | 15 +- src/commands/fix/generated-socket-facts.mts | 2 + .../cmd-manifest-dynamic-sbom-inference.mts | 8 + ...d-manifest-dynamic-sbom-inference.test.mts | 1 + .../manifest/generate-recursive-manifests.mts | 11 +- ...handle-manifest-dynamic-sbom-inference.mts | 4 + src/commands/manifest/run-manifest-facts.mts | 90 +++++++- .../manifest/run-manifest-facts.test.mts | 131 ++++++++++- src/commands/scan/cmd-scan-create.test.mts | 1 + src/commands/scan/cmd-scan-reach.test.mts | 1 + .../scan/handle-create-new-scan.test.mts | 7 +- src/commands/scan/handle-scan-reach.test.mts | 7 +- src/commands/scan/reachability-flags.mts | 102 +++++++-- src/commands/scan/reachability-flags.test.mts | 124 +++++++++- .../scan/run-dynamic-sbom-inference.mts | 2 + src/utils/coana/release.mts | 9 + test/reachability-options.mts | 9 + .../termless/cli.native.socket-help-fix.svg | 116 +++++----- ...t-help-manifest-dynamic-sbom-inference.svg | 40 ++-- .../cli.native.socket-help-scan-create.svg | 216 +++++++++--------- .../cli.native.socket-help-scan-reach.svg | 136 +++++------ 23 files changed, 754 insertions(+), 280 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2048d2594..8cffd31b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added - Scan many repositories with `--dynamic-sbom-inference` without a `socket.json` in each: `--dynamic-sbom-inference-ignore-unresolved` tolerates unresolved dependencies in every build. +- `--dynamic-sbom-inference` no longer waits indefinitely on a hung build: a build root whose build tool runs take longer than 3600 seconds in all fails with a message saying so. Set the limit in seconds (e.g. `1800`) with `--dynamic-sbom-inference-build-timeout` on `socket scan create`, `socket scan reach` and `socket fix`, or `--build-timeout` on `socket manifest dynamic-sbom-inference`, and turn it off with `0`. The timeout needs Coana 15.15.10 or newer. ### 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. diff --git a/src/commands/fix/cmd-fix.integration.test.mts b/src/commands/fix/cmd-fix.integration.test.mts index 50677686f..cc2004f6f 100644 --- a/src/commands/fix/cmd-fix.integration.test.mts +++ b/src/commands/fix/cmd-fix.integration.test.mts @@ -170,6 +170,7 @@ describe('socket fix', async () => { --debug Enable debug logging in the Coana-based Socket Fix CLI invocation. --disable-external-tool-checks Disable external tool checks during fix analysis. --dynamic-sbom-inference For Gradle, sbt, Maven and .NET: generate a Socket facts SBOM (produced directly by each package manager) per independent build root, instead of one synthetic root. Fixes are then attributed to the projects/modules that actually resolve each vulnerable dependency. The generated files are removed afterwards. + --dynamic-sbom-inference-build-timeout With --dynamic-sbom-inference: set the timeout for each build root's build tool runs, taken together, as a whole number of seconds (e.g. 1800), optionally followed by s, m or h. A root that runs past it fails, and 0 means no timeout. Defaults to 3600. --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma separated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget (.NET). Defaults to all of them. --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build (unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. --ecosystems Limit fix analysis to specific ecosystems. Accepts space- or comma-separated values and is case-insensitive. Defaults to all ecosystems. 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 0e8e37b2f..f72f82279 100644 --- a/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts +++ b/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts @@ -3,7 +3,10 @@ import { promises as fs } from 'node:fs' import { beforeEach, describe, expect, it, vi } from 'vitest' import { coanaFix } from './coana-fix.mts' -import { makeDynamicSbomInference } from '../../../test/reachability-options.mts' +import { + BUILD_TIMEOUT, + makeDynamicSbomInference, +} from '../../../test/reachability-options.mts' import { logger } from '../../utils/logger.mts' import type { FixConfig } from './types.mts' @@ -102,7 +105,10 @@ describe('socket fix --dynamic-sbom-inference', () => { debug: false, disableExternalToolChecks: false, disableMajorUpdates: false, - dynamicSbomInference: makeDynamicSbomInference({ purlTypes: ['maven'] }), + dynamicSbomInference: makeDynamicSbomInference({ + buildTimeout: BUILD_TIMEOUT, + purlTypes: ['maven'], + }), ecosystems: [], exclude: [], excludePaths: [], @@ -148,7 +154,10 @@ describe('socket fix --dynamic-sbom-inference', () => { expect(result.ok).toBe(true) expect(mockGenerateSocketFactsForFix).toHaveBeenCalledWith( - expect.objectContaining({ purlTypes: ['maven'] }), + expect.objectContaining({ + buildTimeout: BUILD_TIMEOUT, + purlTypes: ['maven'], + }), ) expect(uploadManifestFiles).toHaveBeenCalledWith( 'test-org', diff --git a/src/commands/fix/generated-socket-facts.mts b/src/commands/fix/generated-socket-facts.mts index b73c5982a..454dd4322 100644 --- a/src/commands/fix/generated-socket-facts.mts +++ b/src/commands/fix/generated-socket-facts.mts @@ -48,6 +48,7 @@ async function restoreAll(backups: Backup[]): Promise { // 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({ + buildTimeout, context, cwd, excludePaths, @@ -81,6 +82,7 @@ export async function generateSocketFactsForFix({ ) try { const inferred = await runDynamicSbomInference({ + buildTimeout, context: { ...context, workDir }, cwd, excludePaths, diff --git a/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.mts b/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.mts index e88262563..6a0933ffa 100644 --- a/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.mts +++ b/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.mts @@ -11,6 +11,11 @@ import { logger } from '../../utils/logger.mts' import { meowOrExit } from '../../utils/meow-with-subcommands.mts' import { getFlagListOutput } from '../../utils/output-formatting.mts' import { assertValidExcludePaths } from '../scan/exclude-paths.mts' +import { + MANIFEST_BUILD_TIMEOUT_KEY, + buildTimeoutFlags, + parseBuildTimeout, +} from '../scan/reachability-flags.mts' import type { CliCommandConfig, @@ -26,6 +31,7 @@ const config: CliCommandConfig = { ...commonFlags, ...outputFlags, ...excludePathsFlag, + ...buildTimeoutFlags(MANIFEST_BUILD_TIMEOUT_KEY), ignoreUnresolved: { type: 'boolean', description: @@ -131,6 +137,7 @@ async function run( const excludePaths = cmdFlagValueToArray(cli.flags['excludePaths']) assertValidExcludePaths(excludePaths) + const buildTimeout = parseBuildTimeout(cli.flags, MANIFEST_BUILD_TIMEOUT_KEY) if (dryRun) { logger.log(constants.DRY_RUN_BAILING_NOW) @@ -138,6 +145,7 @@ async function run( } await handleManifestDynamicSbomInference({ + buildTimeout, cwd, excludePaths, ignoreUnresolved, diff --git a/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.test.mts b/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.test.mts index 93579dcf1..f1587a975 100644 --- a/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.test.mts +++ b/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.test.mts @@ -33,6 +33,7 @@ describe('socket manifest dynamic-sbom-inference', async () => { CWD itself. Options + --build-timeout Set the timeout for each build root's build tool runs, taken together, as a whole number of seconds (e.g. 1800), optionally followed by s, m or h. A root that runs past it fails, and 0 means no timeout. Defaults to 3600. --exclude-paths List of glob patterns to exclude from manifest/facts generation. Patterns are anchored micromatch globs matched relative to CWD (\`--cwd\` if set): \`tests\` matches only \`/tests\`; use \`**/tests\` to match at any depth. Negation patterns (\`!path\`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET project is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that project. A build module or project outside CWD cannot be excluded. --ignore-unresolved Warn on unresolved dependencies instead of failing the run (unresolved deps are not emitted to the facts files); overrides each build's socket.json setting --json Output as JSON diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index a39020928..999ff1f41 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -27,6 +27,7 @@ import { createSocketFactsWorkDir, keepFacts, readsReachabilitySettings, + rootBuildTime, runManifestFacts, } from './run-manifest-facts.mts' import { @@ -45,6 +46,7 @@ import type { BuildRoot, Membership } from './discover-manifest-roots.mts' import type { LoadedBuild } from './load-build.mts' import type { BuildOptionHints, + BuildTimeout, CommandHints, RunManifestFactsOutcome, RunManifestFactsResult, @@ -146,6 +148,7 @@ type Run = Candidate & { type Load = Candidate & LoadedBuild type WalkContext = { + buildTimeout: BuildTimeout | undefined // Every run writes into the work dir, so a dropped run leaves the facts // file at its target as it was. context: SocketFactsContext & { workDir: SocketFactsWorkDir } @@ -650,7 +653,8 @@ async function warnUnappliedEntry( ) } -// Shared by listing and generation, so both run the same Coana, org and hints. +// Shared by a build root's listings and generation, so they run the same Coana, +// org and hints, and draw on one build time. function runOptions( ctx: WalkContext, ecosystem: BuildTool, @@ -666,6 +670,7 @@ function runOptions( excludePaths: ctx.excludePaths, hints: dsiHints(ctx.hints, root.dir), }), + buildTime: rootBuildTime(ctx.buildTimeout), ignoreUnresolved: ctx.ignoreUnresolved ?? dirConfig.ignoreUnresolved, verbose: ctx.verbose || dirConfig.verbose, } @@ -736,6 +741,7 @@ export async function buildUncoveredRoot({ // A failure fails the walk only when no kept or skipped build loads it. export async function generateRecursiveManifests({ + buildTimeout, context = {}, cwd, excludePaths, @@ -744,6 +750,8 @@ export async function generateRecursiveManifests({ purlTypes, verbose, }: { + // Every build root's, unset for none. + buildTimeout: BuildTimeout | undefined // Without a work dir, the walk writes into one of its own. context?: SocketFactsContext | undefined cwd: string @@ -782,6 +790,7 @@ export async function generateRecursiveManifests({ const walk = async (workDir: SocketFactsWorkDir) => { const ctx: WalkContext = { + buildTimeout, context: { ...context, workDir }, excludePaths, hints, diff --git a/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts b/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts index 002fab427..cc007c31a 100644 --- a/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts +++ b/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts @@ -3,15 +3,18 @@ import { outputManifestDynamicSbomInference } from './output-manifest-dynamic-sb import { EXCLUDE_PATHS_FLAG } from './run-manifest-facts.mts' import type { RecursiveManifestOutcome } from './generate-recursive-manifests.mts' +import type { BuildTimeout } from './run-manifest-facts.mts' import type { CResult, OutputKind } from '../../types.mts' export async function handleManifestDynamicSbomInference({ + buildTimeout, cwd, excludePaths, ignoreUnresolved, outputKind, verbose, }: { + buildTimeout: BuildTimeout | undefined cwd: string excludePaths: string[] ignoreUnresolved?: boolean | undefined @@ -19,6 +22,7 @@ export async function handleManifestDynamicSbomInference({ verbose: boolean }): Promise { const outcomes = await generateRecursiveManifests({ + buildTimeout, cwd, excludePaths, ignoreUnresolved, diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 2feb7f954..5ce493318 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -1,6 +1,8 @@ import { existsSync, promises as fs } from 'node:fs' import path from 'node:path' +import semver from 'semver' + import { resolveBazelBinary } from './bazel/bin-detect.mts' import { buildRootPath, @@ -19,6 +21,7 @@ import { logger } from '../../utils/logger.mts' import type { BuildRoot } from './discover-manifest-roots.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { CResult } from '../../types.mts' +import type { ResolvedCoana } from '../../utils/coana/release.mts' import type { ReachabilitySettings } from '../../utils/socket-json.mts' export type BuildOption = 'excludeConfigs' | 'ignoreUnresolved' | 'verbose' @@ -45,6 +48,32 @@ const SOCKET_FACTS_MIN_COANA_VERSION = '15.15.4' // `--disable-dependency-downloads`. const OFFLINE_SOCKET_FACTS_MIN_COANA_VERSION = '15.15.8' +// The first Coana release whose `generate-socket-facts` request takes a build +// timeout. +const BUILD_TIMEOUT_MIN_COANA_VERSION = '15.15.10' + +// How long all the build tool runs for one build root may take together. +export type BuildTimeout = { + // The option that sets it. + flag: string + seconds: number + // A Coana too old to apply a timeout the user set fails the command; the + // default goes only to a Coana that applies it. + source: 'default' | 'flag' +} + +// A build root's timeout, and what its Coana runs so far took of it. +export type RootBuildTime = { + spentMs: number + timeout: BuildTimeout +} + +export function rootBuildTime( + timeout: BuildTimeout | undefined, +): RootBuildTime | undefined { + return timeout && { spentMs: 0, timeout } +} + export const DSI_SETUP_COMMAND = 'socket manifest setup --dynamic-sbom-inference' @@ -137,9 +166,11 @@ type SocketFactsRequest = { targets?: string[] | undefined verbose: boolean } + buildTimeout?: { seconds: number; spentMs: number } | undefined excludeBase: string excludePaths?: string[] | undefined hints: Omit & { + buildTimeoutFlag?: string | undefined // Reachability scans only: reachability cannot install a dependency that // `ignoreUnresolved` lets through, so it must be told to continue too. continueOnInstallErrorsFlag?: string | undefined @@ -195,16 +226,48 @@ async function readResult( } } +function minimumCoanaVersion( + offline: boolean, + buildTime: RootBuildTime | undefined, +): string { + return [ + SOCKET_FACTS_MIN_COANA_VERSION, + ...(offline ? [OFFLINE_SOCKET_FACTS_MIN_COANA_VERSION] : []), + ...(buildTime?.timeout.source === 'flag' + ? [BUILD_TIMEOUT_MIN_COANA_VERSION] + : []), + ].reduce((a, b) => (semver.gt(b, a) ? b : a)) +} + +function requestFor( + request: SocketFactsRequest, + buildTime: RootBuildTime | undefined, + coana: ResolvedCoana, +): SocketFactsRequest { + if (!buildTime || !coana.atLeast(BUILD_TIMEOUT_MIN_COANA_VERSION)) { + return request + } + const { spentMs, timeout } = buildTime + return { + ...request, + buildTimeout: { seconds: timeout.seconds, spentMs }, + hints: { ...request.hints, buildTimeoutFlag: timeout.flag }, + } +} + +// Each run for a root draws on the root's build time, which socket-cli counts +// from when Coana starts, after it is downloaded. async function runGenerateSocketFacts( request: SocketFactsRequest, flags: string[], context: SocketFactsContext, + buildTime: RootBuildTime | undefined, ): Promise<{ message?: string | undefined; result: T | undefined }> { const offline = !!context.disableDependencyDownloads return await withTmpDir('socket-facts-request-', async tmpDir => { const requestFile = path.join(tmpDir, 'request.json') const resultFile = path.join(tmpDir, 'result.json') - await fs.writeFile(requestFile, JSON.stringify(request), 'utf8') + let started: number | undefined const spawned = await spawnCoana( [ 'generate-socket-facts', @@ -217,15 +280,25 @@ async function runGenerateSocketFacts( ], context.orgSlug, { + async beforeSpawn(coana) { + await fs.writeFile( + requestFile, + JSON.stringify(requestFor(request, buildTime, coana)), + 'utf8', + ) + started = performance.now() + }, coanaVersion: context.coanaVersion, - minimumVersion: offline - ? OFFLINE_SOCKET_FACTS_MIN_COANA_VERSION - : SOCKET_FACTS_MIN_COANA_VERSION, + minimumVersion: minimumCoanaVersion(offline, buildTime), // Redirect Coana's logs to stderr to keep the command's stdout // machine-readable. stdio: ['inherit', 2, 'inherit'], }, ) + if (buildTime && started !== undefined) { + // Coana takes whole milliseconds. + buildTime.spentMs += Math.round(performance.now() - started) + } const { error, result } = await readResult(resultFile) const failure = spawned.ok ? undefined @@ -240,6 +313,9 @@ async function runGenerateSocketFacts( export type SocketFactsRequestOptions = { bin?: string | undefined buildOpts: string[] + // Shared by every Coana run for the build root; unset, the runs have no + // timeout. + buildTime?: RootBuildTime | undefined cwd: string ecosystem: BuildTool // The file in `cwd` to build: Maven's POM (unset leaves Maven's default), @@ -403,6 +479,7 @@ export async function listDotnetSolutionMembers({ request.data, ['--list-members'], context, + options.buildTime, ) if (result?.status !== 'members') { return [] @@ -428,6 +505,7 @@ export async function listBuildProjects({ request.data, ['--list-projects'], context, + options.buildTime, ) if (!result) { logger.fail( @@ -446,6 +524,7 @@ async function runSocketFactsRequest( build: string, context: SocketFactsContext, staged: boolean, + buildTime: RootBuildTime | undefined, ): Promise { const { workDir } = context const { message, result } = await runGenerateSocketFacts( @@ -456,6 +535,7 @@ async function runSocketFactsRequest( ...(workDir ? ['--work-dir', workDir.dir] : []), ], context, + buildTime, ) if (!result || result.status === 'failed') { @@ -516,6 +596,7 @@ export async function runManifestFacts({ `the ${ecosystem} project at \`${buildRootPath({ dir: cwd, entryFile })}\``, context, staged, + options.buildTime, ) } @@ -560,6 +641,7 @@ export async function runBazelFacts({ `the Bazel targets ${targets.join(' ')} at \`${dir}\``, context, false, + undefined, ) if (result === undefined) { process.exitCode = 1 diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 87f940c1c..dad2b802c 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -2,6 +2,7 @@ import { promises as fs } from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' +import semver from 'semver' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('../../utils/coana/release.mts', () => ({ @@ -12,13 +13,15 @@ import { keepFacts, listBuildProjects, listDotnetSolutionMembers, + rootBuildTime, runManifestFacts, } from './run-manifest-facts.mts' import { mavenProject } from '../../../test/socket-facts-projects.mts' import { spawnCoana } from '../../utils/coana/release.mts' import { logger } from '../../utils/logger.mts' -import type { SocketFactsWorkDir } from './run-manifest-facts.mts' +import type { BuildTimeout, SocketFactsWorkDir } from './run-manifest-facts.mts' +import type { ResolvedCoana } from '../../utils/coana/release.mts' type Call = { args: string[]; request: any } @@ -34,9 +37,18 @@ const baseArgs = { let cwd = '' let calls: Call[] = [] +// The Coana spawnCoana resolves; local, as new as any, unless a test says. +let coana: ResolvedCoana = { atLeast: () => true } +let runMs = 0 + +function coanaRelease(version: string): ResolvedCoana { + return { atLeast: minimum => semver.gte(version, minimum) } +} function coanaWritesResultFile(text: string | undefined, ok = true): void { - vi.mocked(spawnCoana).mockImplementation(async args => { + vi.mocked(spawnCoana).mockImplementation(async (args, _org, options) => { + await options?.beforeSpawn?.(coana) + await new Promise(resolve => setTimeout(resolve, runMs)) const list = [...args] const request = JSON.parse( await fs.readFile(list[list.indexOf('--request') + 1]!, 'utf8'), @@ -63,6 +75,8 @@ beforeEach(async () => { await fs.mkdtemp(path.join(tmpdir(), 'run-manifest-facts-')), ) calls = [] + coana = { atLeast: () => true } + runMs = 0 vi.mocked(spawnCoana).mockReset() process.exitCode = undefined }) @@ -565,3 +579,116 @@ describe('listBuildProjects', () => { expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() }) }) + +function timeout(source: BuildTimeout['source'], seconds = 3600): BuildTimeout { + return { flag: '--build-timeout', seconds, source } +} + +function listSharedMembers(cwd: string, seconds: number) { + return listDotnetSolutionMembers({ + buildOpts: [], + buildTime: rootBuildTime(timeout('default', seconds)), + cwd, + entryFile: 'Shared.sln', + }) +} + +describe('build timeout', () => { + const SENT = { + buildTimeout: { seconds: 3600, spentMs: 0 }, + buildTimeoutFlag: '--build-timeout', + } + + it.for([ + { + name: 'the default to a Coana that applies it', + buildTimeout: timeout('default'), + offline: false, + runs: '15.15.10', + minimumVersion: '15.15.4', + sent: SENT, + }, + { + name: 'no default to an older Coana', + buildTimeout: timeout('default'), + offline: false, + runs: '15.15.9', + minimumVersion: '15.15.4', + sent: undefined, + }, + { + name: 'a timeout the user set, which needs a Coana that applies it', + buildTimeout: timeout('flag'), + offline: false, + runs: '15.15.10', + minimumVersion: '15.15.10', + sent: SENT, + }, + { + name: 'a timeout the user set, offline too', + buildTimeout: timeout('flag'), + offline: true, + runs: '15.15.10', + minimumVersion: '15.15.10', + sent: SENT, + }, + { + name: 'the default, offline', + buildTimeout: timeout('default'), + offline: true, + runs: '15.15.9', + minimumVersion: '15.15.8', + sent: undefined, + }, + { + name: 'nothing without a timeout', + buildTimeout: undefined, + offline: false, + runs: '15.15.10', + minimumVersion: '15.15.4', + sent: undefined, + }, + ])( + 'sends $name', + async ({ buildTimeout, minimumVersion, offline, runs, sent }) => { + coana = coanaRelease(runs) + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ + ...baseArgs, + buildTime: rootBuildTime(buildTimeout), + context: { disableDependencyDownloads: offline }, + cwd, + }) + const { request } = calls[0]! + expect(request.buildTimeout).toEqual(sent?.buildTimeout) + expect(request.hints.buildTimeoutFlag).toEqual(sent?.buildTimeoutFlag) + expect(vi.mocked(spawnCoana).mock.calls[0]![2]?.minimumVersion).toBe( + minimumVersion, + ) + }, + ) + + it("charges every Coana run for a root to the root's one timeout", async () => { + const buildTime = rootBuildTime(timeout('default')) + const members = { buildOpts: [], buildTime, cwd, entryFile: 'App.sln' } + runMs = 50 + coanaAnswers({ members: ['/r/A/A.csproj'], status: 'members' }) + await listDotnetSolutionMembers(members) + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ ...members, buildTime, ecosystem: 'dotnet' }) + const { 0: listing, 1: generation } = calls.map( + c => c.request.buildTimeout.spentMs, + ) + expect(listing).toBe(0) + expect(generation).toBeGreaterThanOrEqual(50) + expect(buildTime!.spentMs).toBeGreaterThanOrEqual(generation + 50) + expect(Number.isInteger(buildTime!.spentMs)).toBe(true) + }) + + it("lists a solution's members once, whichever root's timeout the listing ran in", async () => { + coanaAnswers({ members: ['/r/A/A.csproj'], status: 'members' }) + expect(await listSharedMembers(cwd, 3600)).toEqual(['/r/A/A.csproj']) + expect(await listSharedMembers(cwd, 300)).toEqual(['/r/A/A.csproj']) + expect(spawnCoana).toHaveBeenCalledOnce() + }) +}) diff --git a/src/commands/scan/cmd-scan-create.test.mts b/src/commands/scan/cmd-scan-create.test.mts index 2912d34fd..63bbd03f0 100644 --- a/src/commands/scan/cmd-scan-create.test.mts +++ b/src/commands/scan/cmd-scan-create.test.mts @@ -214,6 +214,7 @@ describe('socket scan create', async () => { --cwd working directory, defaults to process.cwd() --default-branch Set the default branch of the repository to the branch of this full-scan. Should only need to be done once, for example for the "main" or "master" branch. --dynamic-sbom-inference For Gradle, sbt, Maven and .NET: generate a Socket facts SBOM (produced directly by each package manager) per independent build root, instead of one synthetic root. Combine with --reach to split the reachability analysis per project/module. + --dynamic-sbom-inference-build-timeout With --dynamic-sbom-inference: set the timeout for each build root's build tool runs, taken together, as a whole number of seconds (e.g. 1800), optionally followed by s, m or h. A root that runs past it fails, and 0 means no timeout. Defaults to 3600. --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma separated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget (.NET). Defaults to all of them. --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build (unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the command working directory (\`--cwd\` if set), not the reachability target: \`tests\` matches only \`/tests\`; use \`**/tests\` to match at any depth. Negation patterns (\`!path\`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET project is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that project. A build module or project outside the scan root cannot be excluded. diff --git a/src/commands/scan/cmd-scan-reach.test.mts b/src/commands/scan/cmd-scan-reach.test.mts index 810a9f103..80f98a2dc 100644 --- a/src/commands/scan/cmd-scan-reach.test.mts +++ b/src/commands/scan/cmd-scan-reach.test.mts @@ -40,6 +40,7 @@ describe('socket scan reach', async () => { Reachability Options --dynamic-sbom-inference For Gradle, sbt, Maven and .NET: generate a Socket facts SBOM (produced directly by each package manager) per independent build root, instead of one synthetic root. The reachability analysis is split per project/module accordingly. + --dynamic-sbom-inference-build-timeout With --dynamic-sbom-inference: set the timeout for each build root's build tool runs, taken together, as a whole number of seconds (e.g. 1800), optionally followed by s, m or h. A root that runs past it fails, and 0 means no timeout. Defaults to 3600. --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma separated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget (.NET). Defaults to all of them. --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build (unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the command working directory (\`--cwd\` if set), not the reachability target: \`tests\` matches only \`/tests\`; use \`**/tests\` to match at any depth. Negation patterns (\`!path\`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET project is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that project. A build module or project outside the scan root cannot be excluded. diff --git a/src/commands/scan/handle-create-new-scan.test.mts b/src/commands/scan/handle-create-new-scan.test.mts index 64a4b282c..743b12eae 100644 --- a/src/commands/scan/handle-create-new-scan.test.mts +++ b/src/commands/scan/handle-create-new-scan.test.mts @@ -14,6 +14,7 @@ import { finalizeTier1Scan } from './finalize-tier1-scan.mts' import { handleCreateNewScan } from './handle-create-new-scan.mts' import { outputCreateNewScan } from './output-create-new-scan.mts' import { + BUILD_TIMEOUT, makeDynamicSbomInference, makeReachabilityOptions, } from '../../../test/reachability-options.mts' @@ -451,13 +452,17 @@ describe('handleCreateNewScan excludePaths', () => { const config = createConfig({ autoManifest: true, targets: ['/repo'] }) config.reach.dynamicSbomInference = makeDynamicSbomInference({ + buildTimeout: BUILD_TIMEOUT, purlTypes: ['nuget'], }) await handleCreateNewScan(config) expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith( - expect.objectContaining({ purlTypes: ['nuget'] }), + expect.objectContaining({ + buildTimeout: BUILD_TIMEOUT, + purlTypes: ['nuget'], + }), ) expect(mockGenerateAutoManifest).toHaveBeenCalledWith( expect.objectContaining({ detected: { count: 0, dotnet: false } }), diff --git a/src/commands/scan/handle-scan-reach.test.mts b/src/commands/scan/handle-scan-reach.test.mts index c532e25e5..d77d37166 100644 --- a/src/commands/scan/handle-scan-reach.test.mts +++ b/src/commands/scan/handle-scan-reach.test.mts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { handleScanReach } from './handle-scan-reach.mts' import { + BUILD_TIMEOUT, makeDynamicSbomInference, makeReachabilityOptions, } from '../../../test/reachability-options.mts' @@ -347,7 +348,9 @@ describe('handleScanReach', () => { describe('dynamic SBOM inference', () => { const baseReachabilityOptions = { ...makeReachabilityOptions(), - dynamicSbomInference: makeDynamicSbomInference(), + dynamicSbomInference: makeDynamicSbomInference({ + buildTimeout: BUILD_TIMEOUT, + }), excludePaths: ['vendor/**'], } @@ -394,7 +397,7 @@ describe('handleScanReach', () => { cwd: '/repo', excludePaths: ['vendor/**'], hints: EXCLUDE_PATHS_HINTS, - ...makeDynamicSbomInference(), + ...makeDynamicSbomInference({ buildTimeout: BUILD_TIMEOUT }), }) expect(mockGetPackageFilesForScan).toHaveBeenCalledWith( [ diff --git a/src/commands/scan/reachability-flags.mts b/src/commands/scan/reachability-flags.mts index 8ba7e2539..a36ef677c 100644 --- a/src/commands/scan/reachability-flags.mts +++ b/src/commands/scan/reachability-flags.mts @@ -7,6 +7,7 @@ import { parseEcosystemChoices, } from '../../utils/ecosystem.mts' import { InputError } from '../../utils/errors.mts' +import { camelToKebab } from '../../utils/strings.mts' import { FACTS_PURL_TYPES, buildToolLabelsFor, @@ -14,6 +15,7 @@ import { import type { MeowFlags } from '../../flags.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' +import type { BuildTimeout } from '../manifest/run-manifest-facts.mts' // Shared prefix so each command can append what the SBOMs are used for, which // differs: reachability is optional on `scan create` and always on for @@ -21,8 +23,77 @@ import type { FactsOnlyTypes } from '../../utils/coana.mts' export const DYNAMIC_SBOM_INFERENCE_DESCRIPTION = 'For Gradle, sbt, Maven and .NET: generate a Socket facts SBOM (produced directly by each package manager) per independent build root, instead of one synthetic root.' +const DEFAULT_BUILD_TIMEOUT_SECONDS = 3600 + +const DSI_BUILD_TIMEOUT_KEY = 'dynamicSbomInferenceBuildTimeout' + +export const MANIFEST_BUILD_TIMEOUT_KEY = 'buildTimeout' + +const SECONDS_BY_UNIT: Record = { + __proto__: null, + h: 3600, + m: 60, + s: 1, +} as unknown as Record + +const TIMEOUT_FORMAT = + 'a whole number of seconds (e.g. 1800), optionally followed by s, m or h' + +// Meow leaves an unset flag undefined, and an unset list empty. +function isGiven(value: unknown): boolean { + return Array.isArray(value) + ? !!cmdFlagValueToArray(value).length + : value !== undefined +} + +// Takes what Coana's `parseAnalysisTimeoutSeconds` (packages/cli/src/internal/ +// parse-cli-units.ts) takes for the --analysis-timeout that +// --reach-analysis-timeout is passed on as. The request carries whole seconds, +// so socket-cli parses the flag itself. +function parseTimeoutSeconds(flag: string, value: string): number { + const match = /^(\d+)([a-zA-Z]*)$/.exec(value.trim()) + const unit = match ? (match[2] || 's').toLowerCase() : '' + if (!match || !(unit in SECONDS_BY_UNIT)) { + throw new InputError( + `Invalid ${flag} value "${value}". Expected ${TIMEOUT_FORMAT}.`, + ) + } + return Number(match[1]) * SECONDS_BY_UNIT[unit]! +} + +// The flag, under its meow key, that sets each build root's build timeout. +export function buildTimeoutFlags(key: string, scope = ''): MeowFlags { + const description = `set the timeout for each build root's build tool runs, taken together, as ${TIMEOUT_FORMAT}. A root that runs past it fails, and 0 means no timeout. Defaults to ${DEFAULT_BUILD_TIMEOUT_SECONDS}.` + return { + [key]: { + type: 'string', + description: scope + ? `${scope}: ${description}` + : `${description[0]!.toUpperCase()}${description.slice(1)}`, + }, + } +} + +export function parseBuildTimeout( + flags: { [flag: string]: unknown }, + key: string, +): BuildTimeout | undefined { + const flag = `--${camelToKebab(key)}` + const raw = flags[key] + if (raw === undefined) { + return { + flag, + seconds: DEFAULT_BUILD_TIMEOUT_SECONDS, + source: 'default', + } + } + const seconds = parseTimeoutSeconds(flag, String(raw)) + return seconds ? { flag, seconds, source: 'flag' } : undefined +} + // Not in reachabilityFlags: they apply to a `scan create` without --reach too. export const dynamicSbomInferenceFlags: MeowFlags = { + ...buildTimeoutFlags(DSI_BUILD_TIMEOUT_KEY, 'With --dynamic-sbom-inference'), dynamicSbomInferenceEcosystems: { type: 'string', isMultiple: true, @@ -36,6 +107,8 @@ export const dynamicSbomInferenceFlags: MeowFlags = { } export type DynamicSbomInference = { + // Unset for none. + buildTimeout: BuildTimeout | undefined // Unset leaves it to each build's socket.json. ignoreUnresolved: boolean | undefined purlTypes: FactsOnlyTypes @@ -44,26 +117,25 @@ export type DynamicSbomInference = { export function parseDynamicSbomInferenceFlags(flags: { [flag: string]: unknown }): DynamicSbomInference | undefined { - const raw = cmdFlagValueToArray(flags['dynamicSbomInferenceEcosystems']) - const ignoreUnresolved = flags['dynamicSbomInferenceIgnoreUnresolved'] as - | boolean - | undefined if (!flags['dynamicSbomInference']) { - if (raw.length) { - throw new InputError( - '--dynamic-sbom-inference-ecosystems requires --dynamic-sbom-inference', - ) - } - if (ignoreUnresolved !== undefined) { - throw new InputError( - '--dynamic-sbom-inference-ignore-unresolved requires --dynamic-sbom-inference', - ) + for (const key of Object.keys(dynamicSbomInferenceFlags)) { + if (isGiven(flags[key])) { + throw new InputError( + `--${camelToKebab(key)} requires --dynamic-sbom-inference`, + ) + } } return undefined } - const selected = parseEcosystemChoices(raw, FACTS_PURL_TYPES) + const selected = parseEcosystemChoices( + cmdFlagValueToArray(flags['dynamicSbomInferenceEcosystems']), + FACTS_PURL_TYPES, + ) return { - ignoreUnresolved, + buildTimeout: parseBuildTimeout(flags, DSI_BUILD_TIMEOUT_KEY), + ignoreUnresolved: flags['dynamicSbomInferenceIgnoreUnresolved'] as + | boolean + | undefined, purlTypes: isFactsOnlyTypes(selected) ? selected : FACTS_PURL_TYPES, } } diff --git a/src/commands/scan/reachability-flags.test.mts b/src/commands/scan/reachability-flags.test.mts index f8dd3f42d..fbbc867ea 100644 --- a/src/commands/scan/reachability-flags.test.mts +++ b/src/commands/scan/reachability-flags.test.mts @@ -1,70 +1,176 @@ import { describe, expect, it } from 'vitest' -import { parseDynamicSbomInferenceFlags } from './reachability-flags.mts' +import { + MANIFEST_BUILD_TIMEOUT_KEY, + buildTimeoutFlags, + parseBuildTimeout, + parseDynamicSbomInferenceFlags, +} from './reachability-flags.mts' + +const DSI_FLAG = '--dynamic-sbom-inference-build-timeout' + +const DEFAULTS = { + buildTimeout: { flag: DSI_FLAG, seconds: 3600, source: 'default' }, + ignoreUnresolved: undefined, + purlTypes: ['maven', 'nuget'], +} + +const EXPECTED_FORMAT = + 'Expected a whole number of seconds (e.g. 1800), optionally followed by s, m or h.' describe('parseDynamicSbomInferenceFlags', () => { it.for([ - { flags: {}, expected: undefined }, + { name: 'off', flags: {}, expected: undefined }, { + name: 'every ecosystem by default', flags: { dynamicSbomInference: true }, - expected: { ignoreUnresolved: undefined, purlTypes: ['maven', 'nuget'] }, + expected: DEFAULTS, }, { + name: 'one ecosystem, deduplicated', flags: { dynamicSbomInference: true, dynamicSbomInferenceEcosystems: ['NuGet,nuget'], }, - expected: { ignoreUnresolved: undefined, purlTypes: ['nuget'] }, + expected: { ...DEFAULTS, purlTypes: ['nuget'] }, }, { + name: 'ecosystems across flags', flags: { dynamicSbomInference: true, dynamicSbomInferenceEcosystems: ['maven', 'Maven,NUGET'], }, - expected: { ignoreUnresolved: undefined, purlTypes: ['maven', 'nuget'] }, + expected: DEFAULTS, }, { + name: 'ignoring unresolved dependencies', flags: { dynamicSbomInference: true, dynamicSbomInferenceIgnoreUnresolved: true, }, - expected: { ignoreUnresolved: true, purlTypes: ['maven', 'nuget'] }, + expected: { ...DEFAULTS, ignoreUnresolved: true }, }, { + name: 'failing on unresolved dependencies', flags: { dynamicSbomInference: true, dynamicSbomInferenceIgnoreUnresolved: false, }, - expected: { ignoreUnresolved: false, purlTypes: ['maven', 'nuget'] }, + expected: { ...DEFAULTS, ignoreUnresolved: false }, + }, + { + name: 'a build timeout', + flags: { + dynamicSbomInference: true, + dynamicSbomInferenceBuildTimeout: '900', + }, + expected: { + ...DEFAULTS, + buildTimeout: { flag: DSI_FLAG, seconds: 900, source: 'flag' }, + }, + }, + { + name: 'no build timeout', + flags: { + dynamicSbomInference: true, + dynamicSbomInferenceBuildTimeout: '0', + }, + expected: { ...DEFAULTS, buildTimeout: undefined }, }, - ])('reads $flags', ({ expected, flags }) => { + ])('reads $name', ({ expected, flags }) => { expect(parseDynamicSbomInferenceFlags(flags)).toEqual(expected) }) it.for([ { + name: 'ecosystems without --dynamic-sbom-inference', flags: { dynamicSbomInferenceEcosystems: ['maven'] }, error: '--dynamic-sbom-inference-ecosystems requires --dynamic-sbom-inference', }, { + name: 'ignoring unresolved dependencies without --dynamic-sbom-inference', flags: { dynamicSbomInferenceIgnoreUnresolved: true }, error: '--dynamic-sbom-inference-ignore-unresolved requires --dynamic-sbom-inference', }, { + name: 'failing on unresolved dependencies without --dynamic-sbom-inference', flags: { dynamicSbomInferenceIgnoreUnresolved: false }, error: '--dynamic-sbom-inference-ignore-unresolved requires --dynamic-sbom-inference', }, { + name: 'a build timeout without --dynamic-sbom-inference', + flags: { dynamicSbomInferenceBuildTimeout: '0' }, + error: `${DSI_FLAG} requires --dynamic-sbom-inference`, + }, + { + name: 'an unknown ecosystem', flags: { dynamicSbomInference: true, dynamicSbomInferenceEcosystems: ['maven,npm'], }, error: 'Invalid ecosystem: "npm". Valid values are: maven and nuget', }, - ])('rejects $flags', ({ error, flags }) => { + { + name: 'a build timeout that is no whole number', + flags: { + dynamicSbomInference: true, + dynamicSbomInferenceBuildTimeout: '1.5', + }, + error: `Invalid ${DSI_FLAG} value "1.5". ${EXPECTED_FORMAT}`, + }, + ])('rejects $name', ({ error, flags }) => { expect(() => parseDynamicSbomInferenceFlags(flags)).toThrow(error) }) }) + +describe('parseBuildTimeout', () => { + // As Coana's parseAnalysisTimeoutSeconds reads --analysis-timeout. + it.for([ + { + name: 'the default when unset', + value: undefined, + expected: { flag: '--build-timeout', seconds: 3600, source: 'default' }, + }, + { name: 'a bare number as seconds', value: '600', expected: 600 }, + { name: 'seconds', value: '90s', expected: 90 }, + { name: 'minutes', value: '10m', expected: 600 }, + { name: 'hours', value: '2h', expected: 7200 }, + { name: 'a unit in capitals', value: '10M', expected: 600 }, + { name: 'surrounding whitespace', value: ' 300 ', expected: 300 }, + { name: 'none for 0', value: '0', expected: undefined }, + { name: 'none for 0 with a unit', value: '0h', expected: undefined }, + ])('reads $name', ({ expected, value }) => { + expect( + parseBuildTimeout( + { [MANIFEST_BUILD_TIMEOUT_KEY]: value }, + MANIFEST_BUILD_TIMEOUT_KEY, + ), + ).toEqual( + typeof expected === 'number' + ? { flag: '--build-timeout', seconds: expected, source: 'flag' } + : expected, + ) + }) + + it.for(['', '-5', '10ms', '1.5h', 'abc', 'm'])('rejects %j', value => { + expect(() => + parseBuildTimeout( + { [MANIFEST_BUILD_TIMEOUT_KEY]: value }, + MANIFEST_BUILD_TIMEOUT_KEY, + ), + ).toThrow(`Invalid --build-timeout value "${value}". ${EXPECTED_FORMAT}`) + }) + + it('describes the flag in plain seconds', () => { + expect(buildTimeoutFlags(MANIFEST_BUILD_TIMEOUT_KEY)).toEqual({ + buildTimeout: { + type: 'string', + description: + "Set the timeout for each build root's build tool runs, taken together, as a whole number of seconds (e.g. 1800), optionally followed by s, m or h. A root that runs past it fails, and 0 means no timeout. Defaults to 3600.", + }, + }) + }) +}) diff --git a/src/commands/scan/run-dynamic-sbom-inference.mts b/src/commands/scan/run-dynamic-sbom-inference.mts index 59c9bce85..47b892850 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.mts @@ -71,6 +71,7 @@ function checkFactsForCoana( // build root of the selected ecosystems under `cwd`. Without a work dir, the // facts are only uploaded. export async function runDynamicSbomInference({ + buildTimeout, context, cwd, excludePaths, @@ -84,6 +85,7 @@ export async function runDynamicSbomInference({ hints: CommandHints }): Promise { const outcomes = await generateRecursiveManifests({ + buildTimeout, context, cwd, excludePaths, diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index 3f71a3df2..074e7e2a7 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -71,7 +71,12 @@ type CoanaComponent = { type CoanaDownload = { ok: true } | { ok: false; status: number } +// The Coana about to run. A local one counts as new enough for anything. +export type ResolvedCoana = { atLeast: (version: string) => boolean } + type CoanaSpawnOptions = { + // Prepares what the command passes by what the Coana that runs it reads. + beforeSpawn?: ((coana: ResolvedCoana) => Promise) | undefined coanaVersion?: string | undefined cwd?: string | URL | undefined env?: Record | undefined @@ -447,6 +452,7 @@ export async function spawnCoana( options?: CoanaSpawnOptions | undefined, ): Promise> { const { + beforeSpawn, coanaVersion, cwd, env: spawnEnv, @@ -506,6 +512,7 @@ export async function spawnCoana( } let scriptPath = localPath + let coana: ResolvedCoana = { atLeast: () => true } if (!scriptPath) { const coanaDir = await getCoanaCliDir( coanaVersion || COANA_CLI_VERSION, @@ -525,7 +532,9 @@ export async function spawnCoana( } } scriptPath = coanaCliWrapperPath(dir) + coana = { atLeast: minimum => semver.gte(version, minimum) } } + await beforeSpawn?.(coana) // A local path may name a native binary. const isBinary = !scriptPath.endsWith('.js') && !scriptPath.endsWith('.mjs') diff --git a/test/reachability-options.mts b/test/reachability-options.mts index f45738200..e1ed1b256 100644 --- a/test/reachability-options.mts +++ b/test/reachability-options.mts @@ -1,11 +1,20 @@ +import type { BuildTimeout } from '../src/commands/manifest/run-manifest-facts.mts' import type { ReachabilityOptions } from '../src/commands/scan/perform-reachability-analysis.mts' import type { DynamicSbomInference } from '../src/commands/scan/reachability-flags.mts' +// A build timeout set on the command line. +export const BUILD_TIMEOUT: BuildTimeout = { + flag: '--dynamic-sbom-inference-build-timeout', + seconds: 300, + source: 'flag', +} + // --dynamic-sbom-inference for every ecosystem, with only what a test sets. export function makeDynamicSbomInference( overrides: Partial = {}, ): DynamicSbomInference { return { + buildTimeout: undefined, ignoreUnresolved: undefined, purlTypes: ['maven', 'nuget'], ...overrides, diff --git a/test/snapshots/termless/cli.native.socket-help-fix.svg b/test/snapshots/termless/cli.native.socket-help-fix.svg index abb0a0976..032b17736 100644 --- a/test/snapshots/termless/cli.native.socket-help-fix.svg +++ b/test/snapshots/termless/cli.native.socket-help-fix.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.0-rc.0 | cmd: socket fix | org: (not set) | token: (not set) @@ -51,113 +51,119 @@ le dependency. The generated files are removed afterwards. - --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma s + --dynamic-sbom-inference-build-timeout With --dynamic-sbom-inference: set the timeout for each build root's build tool runs, taken toge -eparated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget ( +ther, as a whole number of seconds (e.g. 1800), optionally followed by s, m or h. A root that runs past it fails, and 0 means no timeout. De -.NET). Defaults to all of them. +faults to 3600. - --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build + --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma s -(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. +eparated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget ( - --ecosystems Limit fix analysis to specific ecosystems. Accepts space- or comma-separated values and is case-insensitive. Default +.NET). Defaults to all of them. -s to all ecosystems. + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build - --exclude-paths Skip matching paths from the scan entirely: manifests under these paths are not uploaded, and fixes are not applied +(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. -to workspaces under them. Patterns are anchored micromatch globs matched relative to the target directory (CWD); `data/postgres/pgdata` matc + --ecosystems Limit fix analysis to specific ecosystems. Accepts space- or comma-separated values and is case-insensitive. Default -hes that exact path, `**/pgdata` matches at any depth. Use this to skip directories the current user cannot read so they do not abort manife +s to all ecosystems. -st collection. Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. + --exclude-paths Skip matching paths from the scan entirely: manifests under these paths are not uploaded, and fixes are not applied - --fix-version Override the version of @coana-tech/cli used for fix analysis. Default: 15.15.9. +to workspaces under them. Patterns are anchored micromatch globs matched relative to the target directory (CWD); `data/postgres/pgdata` matc - --id Provide a list of vulnerability identifiers to compute fixes for: +hes that exact path, `**/pgdata` matches at any depth. Use this to skip directories the current user cannot read so they do not abort manife - - GHSA IDs (​https://docs.github.com/en/code-security/security-advisories/working-with-global-security-advisories +st collection. Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. --from-the-github-advisory-database/about-the-github-advisory-database#about-ghsa-ids​) (e.g., GHSA-xxxx-xxxx-xxxx) + --fix-version Override the version of @coana-tech/cli used for fix analysis. Default: 15.15.9. - - CVE IDs (​https://cve.mitre.org/cve/identifiers/​) (e.g., CVE-2026-1234) - automatically converted to GHSA + --id Provide a list of vulnerability identifiers to compute fixes for: - - PURLs (​https://github.com/package-url/purl-spec​) (e.g., pkg:npm/package@1.0.0) - automatically converted to GH + - GHSA IDs (​https://docs.github.com/en/code-security/security-advisories/working-with-global-security-advisories -SA +-from-the-github-advisory-database/about-the-github-advisory-database#about-ghsa-ids​) (e.g., GHSA-xxxx-xxxx-xxxx) - Can be provided as comma separated values or as multiple flags. Cannot be used with --all. + - CVE IDs (​https://cve.mitre.org/cve/identifiers/​) (e.g., CVE-2026-1234) - automatically converted to GHSA - --include Include workspaces matching these glob patterns. Can be provided as comma separated values or as multiple flags + - PURLs (​https://github.com/package-url/purl-spec​) (e.g., pkg:npm/package@1.0.0) - automatically converted to GH - --json Output as JSON +SA - --markdown Output as Markdown + Can be provided as comma separated values or as multiple flags. Cannot be used with --all. - --minimum-release-age Set a minimum age requirement for suggested upgrade versions (e.g., 1h, 2d, 3w). A higher age requirement reduces + --include Include workspaces matching these glob patterns. Can be provided as comma separated values or as multiple flags - the risk of upgrading to malicious versions. For example, setting the value to 1 week (1w) gives ecosystem maintainers one week to remove p + --json Output as JSON -otentially malicious versions. + --markdown Output as Markdown - --no-apply-fixes Compute fixes only, do not apply them. Logs what upgrades would be applied. If combined with --output-file, the outp + --minimum-release-age Set a minimum age requirement for suggested upgrade versions (e.g., 1h, 2d, 3w). A higher age requirement reduces -ut file will contain the upgrades that would be applied. + the risk of upgrading to malicious versions. For example, setting the value to 1 week (1w) gives ecosystem maintainers one week to remove p - --no-major-updates Do not suggest or apply fixes that require major version updates of direct or transitive dependencies +otentially malicious versions. - --output-file Path to store upgrades as a JSON file at this path. + --no-apply-fixes Compute fixes only, do not apply them. Logs what upgrades would be applied. If combined with --output-file, the outp - --package-managers Limit fix analysis to specific package managers within an ecosystem (e.g. NPM, PNPM, YARN, MAVEN, POETRY). Accepts s +ut file will contain the upgrades that would be applied. -pace- or comma-separated values and is case-insensitive. When combined with --ecosystems, an artifact must satisfy both filters. + --no-major-updates Do not suggest or apply fixes that require major version updates of direct or transitive dependencies - --pr-limit Maximum number of pull requests to create in CI mode (default 10). Has no effect in local mode. + --output-file Path to store upgrades as a JSON file at this path. - --range-style Define how dependency version ranges are updated in package.json (default 'preserve'). + --package-managers Limit fix analysis to specific package managers within an ecosystem (e.g. NPM, PNPM, YARN, MAVEN, POETRY). Accepts s - Available styles: +pace- or comma-separated values and is case-insensitive. When combined with --ecosystems, an artifact must satisfy both filters. - * pin - Use the exact version (e.g. 1.2.3) + --pr-limit Maximum number of pull requests to create in CI mode (default 10). Has no effect in local mode. - * preserve - Retain the existing version range style as-is + --range-style Define how dependency version ranges are updated in package.json (default 'preserve'). - --show-affected-direct-dependencies List the direct dependencies responsible for introducing transitive vulnerabilities and list the up + Available styles: -dates required to resolve the vulnerabilities + * pin - Use the exact version (e.g. 1.2.3) - --silence Silence all output except the final result + * preserve - Retain the existing version range style as-is - + --show-affected-direct-dependencies List the direct dependencies responsible for introducing transitive vulnerabilities and list the up - Environment Variables (for CI/PR mode) +dates required to resolve the vulnerabilities - CI Set to enable CI mode + --silence Silence all output except the final result - SOCKET_CLI_GITHUB_TOKEN GitHub token for PR creation (or GITHUB_TOKEN) + - SOCKET_CLI_GIT_USER_NAME Git username for commits + Environment Variables (for CI/PR mode) - SOCKET_CLI_GIT_USER_EMAIL Git email for commits + CI Set to enable CI mode - + SOCKET_CLI_GITHUB_TOKEN GitHub token for PR creation (or GITHUB_TOKEN) - Examples + SOCKET_CLI_GIT_USER_NAME Git username for commits - $ socket fix + SOCKET_CLI_GIT_USER_EMAIL Git email for commits - $ socket fix --id CVE-2021-23337 + - $ socket fix ./path/to/project --range-style pin + Examples - + $ socket fix - + $ socket fix --id CVE-2021-23337 - + $ socket fix ./path/to/project --range-style pin - \ No newline at end of file + + + + + + + \ No newline at end of file diff --git a/test/snapshots/termless/cli.native.socket-help-manifest-dynamic-sbom-inference.svg b/test/snapshots/termless/cli.native.socket-help-manifest-dynamic-sbom-inference.svg index 4af23bc96..191408ebb 100644 --- a/test/snapshots/termless/cli.native.socket-help-manifest-dynamic-sbom-inference.svg +++ b/test/snapshots/termless/cli.native.socket-help-manifest-dynamic-sbom-inference.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.0-rc.0 | cmd: socket manifest dynamic-sbom-inference | org: (not set) | token: (not set) @@ -35,43 +35,47 @@ Options - --exclude-paths List of glob patterns to exclude from manifest/facts generation. Patterns are anchored micromatch globs matched rela + --build-timeout Set the timeout for each build root's build tool runs, taken together, as a whole number of seconds (e.g. 1800), opt -tive to CWD (`--cwd` if set): `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. Negation patterns (`!path`) are not +ionally followed by s, m or h. A root that runs past it fails, and 0 means no timeout. Defaults to 3600. -supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET project is not analysed as a project of i + --exclude-paths List of glob patterns to exclude from manifest/facts generation. Patterns are anchored micromatch globs matched rela -ts own, but where a project that is not excluded depends on it, its code is analysed as part of that project. A build module or project outs +tive to CWD (`--cwd` if set): `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. Negation patterns (`!path`) are not -ide CWD cannot be excluded. +supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET project is not analysed as a project of i - --ignore-unresolved Warn on unresolved dependencies instead of failing the run (unresolved deps are not emitted to the facts files); ov +ts own, but where a project that is not excluded depends on it, its code is analysed as part of that project. A build module or project outs -errides each build's socket.json setting +ide CWD cannot be excluded. - --json Output as JSON + --ignore-unresolved Warn on unresolved dependencies instead of failing the run (unresolved deps are not emitted to the facts files); ov - --markdown Output as Markdown +errides each build's socket.json setting - --verbose Print debug messages + --json Output as JSON - + --markdown Output as Markdown - Examples + --verbose Print debug messages - $ socket manifest dynamic-sbom-inference + Examples - $ socket manifest dynamic-sbom-inference ./monorepo - + + $ socket manifest dynamic-sbom-inference - + $ socket manifest dynamic-sbom-inference ./monorepo - \ No newline at end of file + + + + + \ No newline at end of file diff --git a/test/snapshots/termless/cli.native.socket-help-scan-create.svg b/test/snapshots/termless/cli.native.socket-help-scan-create.svg index 543ad78f3..ade56a574 100644 --- a/test/snapshots/termless/cli.native.socket-help-scan-create.svg +++ b/test/snapshots/termless/cli.native.socket-help-scan-create.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.0-rc.0 | cmd: socket scan create | org: (not set) | token: (not set) @@ -49,217 +49,223 @@ independent build root, instead of one synthetic root. Combine with --reach to split the reachability analysis per project/module. - --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma s + --dynamic-sbom-inference-build-timeout With --dynamic-sbom-inference: set the timeout for each build root's build tool runs, taken toge -eparated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget ( +ther, as a whole number of seconds (e.g. 1800), optionally followed by s, m or h. A root that runs past it fails, and 0 means no timeout. De -.NET). Defaults to all of them. +faults to 3600. - --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build + --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma s -(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. +eparated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget ( - --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) +.NET). Defaults to all of them. -full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build -d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. +(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. - Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj + --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) -ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr +full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman -oject. A build module or project outside the scan root cannot be excluded. +d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. - --interactive Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, + Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj - defaulting them to cancel/no. +ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr - --json Output as JSON +oject. A build module or project outside the scan root cannot be excluded. - --markdown Output as Markdown + --interactive Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, - --org Force override the organization slug, overrides the default org from config + defaulting them to cancel/no. - --pull-request Pull request number + --json Output as JSON - --reach Run full application reachability analysis + --markdown Output as Markdown - --read-only Similar to --dry-run except it can read from remote, stops before it would create an actual report + --org Force override the organization slug, overrides the default org from config - --repo Repository name + --pull-request Pull request number - --report Wait for the scan creation to complete, then basically run `socket scan report` on it + --reach Run full application reachability analysis - --report-level Which policy level alerts should be reported (default 'error') + --read-only Similar to --dry-run except it can read from remote, stops before it would create an actual report - --set-as-alerts-page When true and if this is the "default branch" then this Scan will be the one reflected on your alerts page. See he + --repo Repository name -lp for details. Defaults to true. + --report Wait for the scan creation to complete, then basically run `socket scan report` on it - --tmp Set the visibility (true/false) of the scan in your dashboard. + --report-level Which policy level alerts should be reported (default 'error') - --uv-members Scan each TARGET directory as a uv project, using the versions pinned in its uv.lock or its workspace root uv.lock. + --set-as-alerts-page When true and if this is the "default branch" then this Scan will be the one reflected on your alerts page. See he -Uploads a CycloneDX dependency graph per TARGET in place of manifest discovery, including all extras and dependency groups. Requires uv on P +lp for details. Defaults to true. -ATH; standalone builds use SOCKET_CLI_UV_PATH. + --tmp Set the visibility (true/false) of the scan in your dashboard. - --workspace The workspace in the Socket Organization that the repository is in to associate with the full scan. + --uv-members Scan each TARGET directory as a uv project, using the versions pinned in its uv.lock or its workspace root uv.lock. - +Uploads a CycloneDX dependency graph per TARGET in place of manifest discovery, including all extras and dependency groups. Requires uv on P - Reachability Options (when --reach is used) +ATH; standalone builds use SOCKET_CLI_UV_PATH. - --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul + --workspace The workspace in the Socket Organization that the repository is in to associate with the full scan. -tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau + -lts to all advisories. + Reachability Options (when --reach is used) - --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. + --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul -512MB, 8GB). The default is 8GB. +tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau - --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 +lts to all advisories. -m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. + --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. - --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th +512MB, 8GB). The default is 8GB. -at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. + --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 - --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back +m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. -to precomputed reachability results. By default, the CLI halts on analysis errors. + --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th - --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi +at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. -lity results. By default, the CLI halts on installation errors. + --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back - --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version +to precomputed reachability results. By default, the CLI halts on analysis errors. - catalog / pre-generated SBOM). By default, the CLI halts. + --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi - --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa +lity results. By default, the CLI halts on installation errors. -ult, the CLI halts. + --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version - --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. + catalog / pre-generated SBOM). By default, the CLI halts. - --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. + --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa - --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. +ult, the CLI halts. - --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director + --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. -y or module cache). Missing dependencies count as installation failures. + --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. - --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. + --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. - --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp + --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director -orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. +y or module cache). Missing dependencies count as installation failures. - --reach-fallback-to-regular-scan If reachability analysis fails, continue with a regular SCA scan (without reachability results) instea + --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. -d of halting. By default, the CLI halts on reachability errors. + --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp - --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d +orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. -eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a + --reach-fallback-to-regular-scan If reachability analysis fails, continue with a regular SCA scan (without reachability results) instea -n SBOM carrying stale reachability results. +d of halting. By default, the CLI halts on reachability errors. - --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous + --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d - runs to speed up the analysis. +eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a - --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your +n SBOM carrying stale reachability results. -project. + --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous - --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. + runs to speed up the analysis. - + --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your - Uploads the specified dependency manifest files for Go, Gradle, JavaScript, +project. - Kotlin, Python, and Scala. Files like "package.json" and "requirements.txt". + --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. - If any folder is specified, the ones found in there recursively are uploaded. - + + Uploads the specified dependency manifest files for Go, Gradle, JavaScript, - Details on TARGET: + Kotlin, Python, and Scala. Files like "package.json" and "requirements.txt". - + If any folder is specified, the ones found in there recursively are uploaded. - - Defaults to the current dir (cwd) if none given + - - Multiple targets can be specified + Details on TARGET: - - If a target is a file, only that file is checked + - - If it is a dir, the dir is scanned for any supported manifest files + - Defaults to the current dir (cwd) if none given - - Dirs MUST be within the current dir (cwd), you can use --cwd to change it + - Multiple targets can be specified - - Supports globbing such as "**/package.json", "**/requirements.txt", etc. + - If a target is a file, only that file is checked - - Ignores any file specified in your project's ".gitignore" + - If it is a dir, the dir is scanned for any supported manifest files - - Also a sensible set of default ignores from the "ignore-by-default" module + - Dirs MUST be within the current dir (cwd), you can use --cwd to change it - + - Supports globbing such as "**/package.json", "**/requirements.txt", etc. - The --repo and --branch flags tell Socket to associate this Scan with that + - Ignores any file specified in your project's ".gitignore" - repo/branch. The names will show up on your dashboard on the Socket website. + - Also a sensible set of default ignores from the "ignore-by-default" module - Note: for a first run you probably want to set --default-branch to indicate + The --repo and --branch flags tell Socket to associate this Scan with that - the default branch name, like "main" or "master". + repo/branch. The names will show up on your dashboard on the Socket website. - The "alerts page" (​https://socket.dev/dashboard/org/YOURORG/alerts​) will show + Note: for a first run you probably want to set --default-branch to indicate - the results from the last scan designated as the "pending head" on the branch + the default branch name, like "main" or "master". - configured on Socket to be the "default branch". When creating a scan the + - --set-as-alerts-page flag will default to true to update this. You can prevent + The "alerts page" (​https://socket.dev/dashboard/org/YOURORG/alerts​) will show - this by using --no-set-as-alerts-page. This flag is ignored for any branch that + the results from the last scan designated as the "pending head" on the branch - is not designated as the "default branch". It is disabled when using --tmp. + configured on Socket to be the "default branch". When creating a scan the - + --set-as-alerts-page flag will default to true to update this. You can prevent - You can use `socket scan setup` to configure certain repo flag defaults. + this by using --no-set-as-alerts-page. This flag is ignored for any branch that - + is not designated as the "default branch". It is disabled when using --tmp. - Examples + - $ socket scan create + You can use `socket scan setup` to configure certain repo flag defaults. - $ socket scan create ./proj --json + - $ socket scan create --repo=test-repo --branch=main ./package.json + Examples - $ socket scan create --uv-members ./packages/api ./packages/worker + $ socket scan create - + $ socket scan create ./proj --json - + $ socket scan create --repo=test-repo --branch=main ./package.json - + $ socket scan create --uv-members ./packages/api ./packages/worker - \ No newline at end of file + + + + + + + \ No newline at end of file diff --git a/test/snapshots/termless/cli.native.socket-help-scan-reach.svg b/test/snapshots/termless/cli.native.socket-help-scan-reach.svg index 5a1e69e9b..f5e6f9ead 100644 --- a/test/snapshots/termless/cli.native.socket-help-scan-reach.svg +++ b/test/snapshots/termless/cli.native.socket-help-scan-reach.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.0-rc.0 | cmd: socket scan reach | org: (not set) | token: (not set) @@ -45,133 +45,139 @@ independent build root, instead of one synthetic root. The reachability analysis is split per project/module accordingly. - --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma s + --dynamic-sbom-inference-build-timeout With --dynamic-sbom-inference: set the timeout for each build root's build tool runs, taken toge -eparated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget ( +ther, as a whole number of seconds (e.g. 1800), optionally followed by s, m or h. A root that runs past it fails, and 0 means no timeout. De -.NET). Defaults to all of them. +faults to 3600. - --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build + --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma s -(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. +eparated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget ( - --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) +.NET). Defaults to all of them. -full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build -d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. +(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. - Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj + --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) -ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr +full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman -oject. A build module or project outside the scan root cannot be excluded. +d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. - --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul + Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj -tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau +ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr -lts to all advisories. +oject. A build module or project outside the scan root cannot be excluded. - --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. + --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul -512MB, 8GB). The default is 8GB. +tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau - --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 +lts to all advisories. -m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. + --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. - --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th +512MB, 8GB). The default is 8GB. -at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. + --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 - --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back +m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. -to precomputed reachability results. By default, the CLI halts on analysis errors. + --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th - --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi +at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. -lity results. By default, the CLI halts on installation errors. + --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back - --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version +to precomputed reachability results. By default, the CLI halts on analysis errors. - catalog / pre-generated SBOM). By default, the CLI halts. + --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi - --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa +lity results. By default, the CLI halts on installation errors. -ult, the CLI halts. + --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version - --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. + catalog / pre-generated SBOM). By default, the CLI halts. - --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. + --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa - --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. +ult, the CLI halts. - --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director + --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. -y or module cache). Missing dependencies count as installation failures. + --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. - --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. + --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. - --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp + --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director -orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. +y or module cache). Missing dependencies count as installation failures. - --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d + --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. -eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a + --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp -n SBOM carrying stale reachability results. +orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. - --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous + --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d - runs to speed up the analysis. +eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a - --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your +n SBOM carrying stale reachability results. -project. + --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous - --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. + runs to speed up the analysis. - + --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your - Runs the Socket reachability analysis without creating a scan in Socket. +project. - The output is written to .socket.facts.json in the current working directory + --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. - unless the --output flag is specified. - + + Runs the Socket reachability analysis without creating a scan in Socket. - Note: Manifest files are uploaded to Socket's backend services because the + The output is written to .socket.facts.json in the current working directory - reachability analysis requires creating a Software Bill of Materials (SBOM) + unless the --output flag is specified. - from these files before the analysis can run. - + + Note: Manifest files are uploaded to Socket's backend services because the - Examples + reachability analysis requires creating a Software Bill of Materials (SBOM) - $ socket scan reach + from these files before the analysis can run. - $ socket scan reach ./proj + - $ socket scan reach ./proj --reach-ecosystems npm,pypi + Examples - $ socket scan reach ./monorepo --dynamic-sbom-inference + $ socket scan reach - $ socket scan reach --output custom-report.json + $ socket scan reach ./proj - $ socket scan reach ./proj --output ./reports/analysis.json + $ socket scan reach ./proj --reach-ecosystems npm,pypi - + $ socket scan reach ./monorepo --dynamic-sbom-inference - + $ socket scan reach --output custom-report.json - + $ socket scan reach ./proj --output ./reports/analysis.json - \ No newline at end of file + + + + + + + \ No newline at end of file