diff --git a/CHANGELOG.md b/CHANGELOG.md index 785315fde..6f6f1be50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,10 +8,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added - Catch reachability analyses that stop early: with `--reach-incomplete-analysis-as-error`, `socket scan create --reach` and `socket scan reach` report a vulnerability whose analysis hit the timeout or memory limit before finding a reachable path as an analysis error instead of unreachable. +- Scan many repositories with `--dynamic-sbom-inference` without a `socket.json` in each: `--dynamic-sbom-inference-ignore-unresolved` tolerates unresolved dependencies in every build. A build that cannot be loaded, for example over a missing imported Maven BOM, still fails. ### Changed - Updated the Coana CLI to v `15.15.10`. - `--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..96699d142 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 + +- `socket scan create`, `socket scan reach` and `socket fix` take only + `ignoreUnresolved` as a flag, `--dynamic-sbom-inference-ignore-unresolved` + with `--dynamic-sbom-inference`; set the other fields in `socket.json`. +- `socket manifest dynamic-sbom-inference` takes `--ignore-unresolved`, and + `--verbose` turns on every build's output. +- The ignore-unresolved flag 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..0346f4cf5 100644 --- a/src/commands/fix/cmd-fix.integration.test.mts +++ b/src/commands/fix/cmd-fix.integration.test.mts @@ -53,6 +53,25 @@ describe('socket fix', async () => { // Increase timeout for CI environments and Windows where operations can be slower. const testTimeout = constants.ENV.CI || constants.WIN32 ? 60_000 : 30_000 + cmdit( + [ + 'fix', + '--dynamic-sbom-inference-ignore-unresolved', + '--ignore-unresolved', + 'target', + FLAG_CONFIG, + '{"apiToken":"fakeToken"}', + ], + 'should name the flag that replaces --ignore-unresolved', + async cmd => { + const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + expect(stdout + stderr).toContain( + '`socket fix` takes --dynamic-sbom-inference-ignore-unresolved, with --dynamic-sbom-inference, in place of --ignore-unresolved.', + ) + expect(code, 'should exit with non-zero code').not.toBe(0) + }, + ) + describe('environment variable handling', () => { // Note: The warning messages about missing env vars are only shown when: // 1. NOT in dry-run mode @@ -171,6 +190,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. A build that cannot be loaded, for example over a missing imported Maven BOM, still fails. --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..bf2c7e60f 100644 --- a/src/commands/fix/cmd-fix.mts +++ b/src/commands/fix/cmd-fix.mts @@ -33,9 +33,10 @@ 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' +import { rejectManifestOnlyFlags } from '../scan/reject-manifest-only-flags.mts' import type { MeowFlag, MeowFlags } from '../../flags.mts' import type { @@ -191,7 +192,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: [], @@ -331,7 +332,11 @@ async function run( parentName, importMeta, }, - { allowUnknownFlags: false }, + { + allowUnknownFlags: false, + checkFlags: flags => + rejectManifestOnlyFlags(flags, `${parentName} ${CMD_NAME}`), + }, ) const { 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..113d405a3 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: [], @@ -163,6 +164,20 @@ describe('socket fix --dynamic-sbom-inference', () => { expect(generated.remove).toHaveBeenCalledTimes(1) }) + it('passes --dynamic-sbom-inference-ignore-unresolved on to facts generation', async () => { + await coanaFix({ + ...baseConfig, + dynamicSbomInference: makeDynamicSbomInference({ + ignoreUnresolved: true, + purlTypes: ['maven'], + }), + }) + + expect(mockGenerateSocketFactsForFix).toHaveBeenCalledWith( + expect.objectContaining({ ignoreUnresolved: true, purlTypes: ['maven'] }), + ) + }) + it('runs Coana as without the flag when no build root was found', async () => { mockGenerateSocketFactsForFix.mockResolvedValue(undefined) diff --git a/src/commands/fix/coana-fix.mts b/src/commands/fix/coana-fix.mts index 03f4fffc0..917c51ac4 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 { @@ -403,7 +403,7 @@ async function coanaFixWithFacts( existingPaths: scanFilepaths.filter(isSocketFactsFile), findFactsPaths: async () => (await findScanFilepaths()).filter(isSocketFactsFile), - purlTypes: factsSlot.purlTypes, + ...factsSlot.dynamicSbomInference, tmpDir: factsSlot.tmpDir, }) factsSlot.generated = generated diff --git a/src/commands/fix/generated-socket-facts.mts b/src/commands/fix/generated-socket-facts.mts index 8779e61d8..22ef8366a 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. @@ -53,15 +53,15 @@ export async function generateSocketFactsForFix({ excludePaths, existingPaths, findFactsPaths, + ignoreUnresolved, purlTypes, tmpDir, -}: { +}: DynamicSbomInference & { context: Omit cwd: string excludePaths: string[] existingPaths: string[] findFactsPaths: () => Promise - purlTypes: readonly PURL_Type[] tmpDir: string }): Promise { const originals = await backUp(existingPaths, path.join(tmpDir, 'existing')) @@ -86,6 +86,7 @@ export async function generateSocketFactsForFix({ cwd, excludePaths, hints: EXCLUDE_PATHS_HINTS, + ignoreUnresolved, purlTypes, }) if (!inferred) { diff --git a/src/commands/fix/generated-socket-facts.test.mts b/src/commands/fix/generated-socket-facts.test.mts index df7ae1ae6..43d71d5b4 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()) @@ -43,7 +44,7 @@ describe('generateSocketFactsForFix', () => { excludePaths: [], existingPaths: await factsPaths(), findFactsPaths: factsPaths, - purlTypes: ['maven'], + ...makeDynamicSbomInference({ purlTypes: ['maven'] }), tmpDir, }) } @@ -101,7 +102,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 551b5a2f0..d7032f4f2 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, @@ -303,12 +303,18 @@ async function run( `, } - const cli = meowOrExit({ - argv, - config, - parentName, - importMeta, - }) + const cli = meowOrExit( + { + argv, + config, + parentName, + importMeta, + }, + { + checkFlags: flags => + rejectManifestOnlyFlags(flags, `${parentName} ${CMD_NAME}`), + }, + ) const { commitHash, @@ -388,8 +394,6 @@ async function run( const dynamicSbomInference = parseDynamicSbomInferenceFlags(cli.flags) - warnSocketJsonOnlyFlags(cli.flags, `${parentName} ${CMD_NAME}`) - const dryRun = !!cli.flags['dryRun'] const uvMembers = !!cli.flags['uvMembers'] const bazelScan = !!cli.flags['bazel'] diff --git a/src/commands/scan/cmd-scan-create.test.mts b/src/commands/scan/cmd-scan-create.test.mts index 2c904506a..b60ef13ae 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. A build that cannot be loaded, for example over a missing imported Maven BOM, still fails. --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. @@ -305,6 +306,26 @@ describe('socket scan create', async () => { }, ) + cmdit( + [ + 'scan', + 'create', + '--dynamic-sbom-inference-ignore-unresolved', + '--ignore-unresolved', + 'target', + FLAG_CONFIG, + '{"apiToken":"fakeToken"}', + ], + 'should name the flag that replaces --ignore-unresolved', + async cmd => { + const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + expect(stdout + stderr).toContain( + '`socket scan create` takes --dynamic-sbom-inference-ignore-unresolved, with --dynamic-sbom-inference, in place of --ignore-unresolved.', + ) + expect(code, 'should exit with non-zero code').not.toBe(0) + }, + ) + cmdit( [ 'scan', diff --git a/src/commands/scan/cmd-scan-reach.mts b/src/commands/scan/cmd-scan-reach.mts index 331c56b83..9598e6177 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', @@ -136,14 +136,18 @@ async function run( `, } - const cli = meowOrExit({ - argv, - config, - importMeta, - parentName, - }) - - warnSocketJsonOnlyFlags(cli.flags, `${parentName} ${CMD_NAME}`) + const cli = meowOrExit( + { + argv, + config, + importMeta, + parentName, + }, + { + checkFlags: flags => + rejectManifestOnlyFlags(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 b44372138..eade2715a 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. A build that cannot be loaded, for example over a missing imported Maven BOM, still fails. --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. @@ -301,6 +302,26 @@ describe('socket scan reach', async () => { }, ) + cmdit( + [ + 'scan', + 'reach', + '--dynamic-sbom-inference-ignore-unresolved', + '--ignore-unresolved', + 'target', + FLAG_CONFIG, + '{"apiToken":"fakeToken"}', + ], + 'should name the flag that replaces --ignore-unresolved', + async cmd => { + const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + expect(stdout + stderr).toContain( + '`socket scan reach` takes --dynamic-sbom-inference-ignore-unresolved, with --dynamic-sbom-inference, in place of --ignore-unresolved.', + ) + expect(code, 'should exit with non-zero code').not.toBe(0) + }, + ) + cmdit( [ 'scan', diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index 015fc2dd1..36637361b 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -285,7 +285,7 @@ async function createNewScan( cwd, excludePaths: reach.excludePaths, hints, - purlTypes: reach.dynamicSbomInference, + ...reach.dynamicSbomInference, }) scanTargets = arrayUnique([ ...scanTargets, @@ -303,7 +303,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 457a31316..fde5f75fc 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, @@ -497,7 +502,7 @@ describe('handleCreateNewScan excludePaths', () => { mockGenerateRecursiveManifests.mockResolvedValueOnce(outcomes) const config = createConfig({ autoManifest: false, targets: ['/repo'] }) - config.reach.dynamicSbomInference = ['maven', 'nuget'] + config.reach.dynamicSbomInference = makeDynamicSbomInference() await handleCreateNewScan(config) @@ -527,7 +532,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) @@ -556,7 +561,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 964357e44..efc6abd42 100644 --- a/src/commands/scan/handle-scan-reach.mts +++ b/src/commands/scan/handle-scan-reach.mts @@ -22,9 +22,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 = { @@ -47,9 +47,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 @@ -71,7 +73,7 @@ async function runScanReach( cwd, excludePaths: reachabilityOptions.excludePaths, hints: EXCLUDE_PATHS_HINTS, - purlTypes: dsi.purlTypes, + ...dsi.inference, }) scanTargets = arrayUnique([ ...scanTargets, @@ -179,14 +181,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 f5853dab4..d7cd038a9 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 2acbc25a0..1d13ab988 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, @@ -419,7 +422,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 e4a7b028b..07aa7dced 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. A build that cannot be loaded, for example over a missing imported Maven BOM, still fails.", + }, +} + +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..e621d044f --- /dev/null +++ b/src/commands/scan/reject-manifest-only-flags.mts @@ -0,0 +1,37 @@ +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[] = [] + const ignoreUnresolved = flags['ignoreUnresolved'] + if (ignoreUnresolved !== undefined) { + // Undeclared, so meow passes `--ignore-unresolved=false` as a string. + const negated = + ignoreUnresolved === false || + String(ignoreUnresolved).toLowerCase() === 'false' + parts.push( + `\`${command}\` takes --${negated ? 'no-' : ''}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..abfef9cde --- /dev/null +++ b/src/commands/scan/reject-manifest-only-flags.test.mts @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest' + +import { rejectManifestOnlyFlags } from './reject-manifest-only-flags.mts' +import { meowOrExit } from '../../utils/meow-with-subcommands.mts' + +// The flags as the scan commands' parser reads them: undeclared, so not +// coerced to booleans. +function parse(argv: string[]) { + return meowOrExit({ + argv: [...argv, '--json', '.'], + config: { + commandName: 'create', + description: '', + flags: { json: { type: 'boolean', description: '' } }, + help: () => '', + }, + importMeta: import.meta, + parentName: 'socket scan', + }).flags +} + +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, + ) + }) + + it.for([ + { + argv: ['--ignore-unresolved=true'], + flag: '--dynamic-sbom-inference-ignore-unresolved', + }, + { + argv: ['--no-ignore-unresolved'], + flag: '--no-dynamic-sbom-inference-ignore-unresolved', + }, + { + argv: ['--ignore-unresolved=false'], + flag: '--no-dynamic-sbom-inference-ignore-unresolved', + }, + { + argv: ['--ignore-unresolved=FALSE'], + flag: '--no-dynamic-sbom-inference-ignore-unresolved', + }, + ])('names the matching flag for $argv', ({ argv, flag }) => { + expect(() => + rejectManifestOnlyFlags(parse(argv), 'socket scan create'), + ).toThrow( + `takes ${flag}, with --dynamic-sbom-inference, in place of --ignore-unresolved.`, + ) + }) +}) diff --git a/src/commands/scan/run-dynamic-sbom-inference.mts b/src/commands/scan/run-dynamic-sbom-inference.mts index de21fc959..9fa34b7d1 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 09c777389..4becd3ed1 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'] }, ])( @@ -123,7 +138,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/src/utils/meow-with-subcommands.mts b/src/utils/meow-with-subcommands.mts index f6b2f058b..9d2be9cfc 100644 --- a/src/utils/meow-with-subcommands.mts +++ b/src/utils/meow-with-subcommands.mts @@ -780,6 +780,8 @@ export interface MeowOrExitConfig { export type MeowOrExitOptions = { allowUnknownFlags?: boolean | undefined + // Runs before unknown flags are rejected, so it can explain a known mistake. + checkFlags?: ((flags: Record) => void) | undefined } /** @@ -803,7 +805,7 @@ export function meowOrExit( importMeta, parentName, } = { __proto__: null, ...config } as MeowOrExitConfig - const { allowUnknownFlags = true } = { + const { allowUnknownFlags = true, checkFlags } = { __proto__: null, ...options, } as MeowOrExitOptions @@ -888,6 +890,8 @@ export function meowOrExit( throw new Error('process.exit called') } + checkFlags?.(cli.flags) + // Now test for help state. Run Meow again. If it exits now, it must be due // to wanting to print the help screen. But it would exit(0) and we want a // consistent exit(2) for that case (missing input). diff --git a/test/reachability-options.mts b/test/reachability-options.mts index 101eef0c8..01b3752d9 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 0c3dd1809..874311eec 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.1-rc.0 | cmd: socket fix | org: (not set) | token: (not set) @@ -57,103 +57,109 @@ .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. A build that cannot be loaded, for example - --exclude-paths Skip matching paths from the scan entirely: manifests under these paths are not uploaded, and fixes are not applied + over a missing imported Maven BOM, still fails. -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.10. +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.10. - - 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-scan-create.svg b/test/snapshots/termless/cli.native.socket-help-scan-create.svg index 0e6a94a50..50a0f00f1 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.1-rc.0 | cmd: socket scan create | org: (not set) | token: (not set) @@ -55,215 +55,221 @@ .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. A build that cannot be loaded, for example -d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. + over a missing imported Maven BOM, still fails. - 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. With --reach-incomplete-analysis-as-error, an unreachable + --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th - verdict from an analysis that stopped early is an error too. +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. With --reach-incomplete-analysis-as-error, an unreachable - --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version + verdict from an analysis that stopped early is an error too. - 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-incomplete-analysis-as-error An analysis that stops early (e.g. at --reach-analysis-timeout or --reach-analysis-memory-limit) c +orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. -an report a vulnerability unreachable because it found no path before it stopped. Report such a vulnerability as an analysis error instead. + --reach-fallback-to-regular-scan If reachability analysis fails, continue with a regular SCA scan (without reachability results) instea -Analysis errors halt the scan unless --reach-continue-on-analysis-errors is set. +d of halting. By default, the CLI halts on reachability errors. - --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d + --reach-incomplete-analysis-as-error An analysis that stops early (e.g. at --reach-analysis-timeout or --reach-analysis-memory-limit) c -eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a +an report a vulnerability unreachable because it found no path before it stopped. Report such a vulnerability as an analysis error instead. -n SBOM carrying stale reachability results. +Analysis errors halt the scan unless --reach-continue-on-analysis-errors is set. - --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.10. + 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.10. - 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 5ce93b250..5d104ceed 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.1-rc.0 | cmd: socket scan reach | org: (not set) | token: (not set) @@ -51,131 +51,137 @@ .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. A build that cannot be loaded, for example -d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. + over a missing imported Maven BOM, still fails. - 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. With --reach-incomplete-analysis-as-error, an unreachable + --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th - verdict from an analysis that stopped early is an error too. +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. With --reach-incomplete-analysis-as-error, an unreachable - --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version + verdict from an analysis that stopped early is an error too. - 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-incomplete-analysis-as-error An analysis that stops early (e.g. at --reach-analysis-timeout or --reach-analysis-memory-limit) c + --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. -an report a vulnerability unreachable because it found no path before it stopped. Report such a vulnerability as an analysis error instead. + --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp -Analysis errors halt the scan unless --reach-continue-on-analysis-errors is set. +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-incomplete-analysis-as-error An analysis that stops early (e.g. at --reach-analysis-timeout or --reach-analysis-memory-limit) c -eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a +an report a vulnerability unreachable because it found no path before it stopped. Report such a vulnerability as an analysis error instead. -n SBOM carrying stale reachability results. +Analysis errors halt the scan unless --reach-continue-on-analysis-errors is set. - --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.10. + 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.10. - 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