diff --git a/CHANGELOG.md b/CHANGELOG.md index bc7b68d5a..8cffd31b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ 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] + +### 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. +- `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 ### Changed 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..cc2004f6f 100644 --- a/src/commands/fix/cmd-fix.integration.test.mts +++ b/src/commands/fix/cmd-fix.integration.test.mts @@ -170,7 +170,9 @@ 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. --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 0c2f2409b..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,6 +3,10 @@ import { promises as fs } from 'node:fs' import { beforeEach, describe, expect, it, vi } from 'vitest' import { coanaFix } from './coana-fix.mts' +import { + BUILD_TIMEOUT, + makeDynamicSbomInference, +} from '../../../test/reachability-options.mts' import { logger } from '../../utils/logger.mts' import type { FixConfig } from './types.mts' @@ -101,7 +105,10 @@ describe('socket fix --dynamic-sbom-inference', () => { debug: false, disableExternalToolChecks: false, disableMajorUpdates: false, - dynamicSbomInference: ['maven'], + dynamicSbomInference: makeDynamicSbomInference({ + buildTimeout: BUILD_TIMEOUT, + purlTypes: ['maven'], + }), ecosystems: [], exclude: [], excludePaths: [], @@ -147,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', @@ -163,6 +173,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..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 { @@ -396,21 +396,24 @@ 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, - purlTypes: factsSlot.purlTypes, + ...factsSlot.dynamicSbomInference, findFactsPaths: async () => (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..454dd4322 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. @@ -45,22 +45,24 @@ 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({ + buildTimeout, context, cwd, excludePaths, findFactsPaths, + ignoreUnresolved, purlTypes, tmpDir, -}: { +}: DynamicSbomInference & { context: Omit cwd: string excludePaths: string[] 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) @@ -80,12 +82,17 @@ export async function generateSocketFactsForFix({ ) try { const inferred = await runDynamicSbomInference({ + buildTimeout, context: { ...context, workDir }, cwd, excludePaths, hints: EXCLUDE_PATHS_HINTS, + ignoreUnresolved, 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..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()) @@ -32,17 +33,25 @@ 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: [], findFactsPaths: async () => [existing, fresh].filter(p => existsSync(p)), - purlTypes: ['maven'], + ...makeDynamicSbomInference({ purlTypes: ['maven'] }), tmpDir, }) } + 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') @@ -96,7 +105,7 @@ describe('generateSocketFactsForFix', () => { purpose: 'fix', }, }, - purlTypes: ['maven'], + ...makeDynamicSbomInference({ purlTypes: ['maven'] }), }), ) expect(factsOnlyTypes).toEqual(['maven', 'nuget']) @@ -117,6 +126,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/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/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/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/manifest/handle-manifest-dynamic-sbom-inference.mts b/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts index be8e7acf5..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, @@ -31,8 +35,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/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.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..63bbd03f0 100644 --- a/src/commands/scan/cmd-scan-create.test.mts +++ b/src/commands/scan/cmd-scan-create.test.mts @@ -214,7 +214,9 @@ 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. --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..80f98a2dc 100644 --- a/src/commands/scan/cmd-scan-reach.test.mts +++ b/src/commands/scan/cmd-scan-reach.test.mts @@ -40,7 +40,9 @@ 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. --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 bb68b5ddc..743b12eae 100644 --- a/src/commands/scan/handle-create-new-scan.test.mts +++ b/src/commands/scan/handle-create-new-scan.test.mts @@ -13,7 +13,11 @@ 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 { + BUILD_TIMEOUT, + makeDynamicSbomInference, + makeReachabilityOptions, +} from '../../../test/reachability-options.mts' import { logger } from '../../utils/logger.mts' import type { HandleCreateNewScanConfig } from './handle-create-new-scan.mts' @@ -354,7 +358,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 +404,7 @@ describe('handleCreateNewScan excludePaths', () => { ...createConfig({ autoManifest: true, targets: ['/repo'] }), hints, } - config.reach.dynamicSbomInference = ['maven', 'nuget'] + config.reach.dynamicSbomInference = makeDynamicSbomInference() await handleCreateNewScan(config) @@ -447,12 +451,18 @@ describe('handleCreateNewScan excludePaths', () => { ]) const config = createConfig({ autoManifest: true, targets: ['/repo'] }) - config.reach.dynamicSbomInference = ['nuget'] + 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 } }), @@ -471,7 +481,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, @@ -480,27 +490,26 @@ 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'] + config.reach.dynamicSbomInference = makeDynamicSbomInference() - 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' }, ]) const config = createConfig({ autoManifest: false, targets: ['/repo'] }) - config.reach.dynamicSbomInference = ['maven', 'nuget'] + config.reach.dynamicSbomInference = makeDynamicSbomInference() await handleCreateNewScan(config) @@ -529,7 +538,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) @@ -558,7 +567,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..d77d37166 100644 --- a/src/commands/scan/handle-scan-reach.test.mts +++ b/src/commands/scan/handle-scan-reach.test.mts @@ -1,7 +1,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { handleScanReach } from './handle-scan-reach.mts' -import { makeReachabilityOptions } from '../../../test/reachability-options.mts' +import { + BUILD_TIMEOUT, + makeDynamicSbomInference, + makeReachabilityOptions, +} from '../../../test/reachability-options.mts' import { EXCLUDE_PATHS_HINTS } from '../manifest/run-manifest-facts.mts' const { @@ -344,7 +348,9 @@ describe('handleScanReach', () => { describe('dynamic SBOM inference', () => { const baseReachabilityOptions = { ...makeReachabilityOptions(), - dynamicSbomInference: ['maven', 'nuget'], + dynamicSbomInference: makeDynamicSbomInference({ + buildTimeout: BUILD_TIMEOUT, + }), excludePaths: ['vendor/**'], } @@ -391,7 +397,7 @@ describe('handleScanReach', () => { cwd: '/repo', excludePaths: ['vendor/**'], hints: EXCLUDE_PATHS_HINTS, - purlTypes: ['maven', 'nuget'], + ...makeDynamicSbomInference({ buildTimeout: BUILD_TIMEOUT }), }) 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..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,29 +23,121 @@ 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 = { +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, 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 for none. + buildTimeout: BuildTimeout | undefined + // Unset leaves it to each build's socket.json. + ignoreUnresolved: boolean | undefined + purlTypes: FactsOnlyTypes } export function parseDynamicSbomInferenceFlags(flags: { [flag: string]: unknown -}): FactsOnlyTypes | undefined { - const raw = cmdFlagValueToArray(flags['dynamicSbomInferenceEcosystems']) +}): DynamicSbomInference | undefined { if (!flags['dynamicSbomInference']) { - if (raw.length) { - throw new InputError( - '--dynamic-sbom-inference-ecosystems 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) - return isFactsOnlyTypes(selected) ? selected : FACTS_PURL_TYPES + const selected = parseEcosystemChoices( + cmdFlagValueToArray(flags['dynamicSbomInferenceEcosystems']), + FACTS_PURL_TYPES, + ) + return { + buildTimeout: parseBuildTimeout(flags, DSI_BUILD_TIMEOUT_KEY), + ignoreUnresolved: flags['dynamicSbomInferenceIgnoreUnresolved'] as + | boolean + | undefined, + 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..fbbc867ea 100644 --- a/src/commands/scan/reachability-flags.test.mts +++ b/src/commands/scan/reachability-flags.test.mts @@ -1,43 +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 }, - { flags: { dynamicSbomInference: true }, expected: ['maven', 'nuget'] }, + { name: 'off', flags: {}, expected: undefined }, { + name: 'every ecosystem by default', + flags: { dynamicSbomInference: true }, + expected: DEFAULTS, + }, + { + name: 'one ecosystem, deduplicated', flags: { dynamicSbomInference: true, dynamicSbomInferenceEcosystems: ['NuGet,nuget'], }, - expected: ['nuget'], + expected: { ...DEFAULTS, purlTypes: ['nuget'] }, }, { + name: 'ecosystems across flags', flags: { dynamicSbomInference: true, dynamicSbomInferenceEcosystems: ['maven', 'Maven,NUGET'], }, - expected: ['maven', 'nuget'], + expected: DEFAULTS, + }, + { + name: 'ignoring unresolved dependencies', + flags: { + dynamicSbomInference: true, + dynamicSbomInferenceIgnoreUnresolved: true, + }, + expected: { ...DEFAULTS, ignoreUnresolved: true }, + }, + { + name: 'failing on unresolved dependencies', + flags: { + dynamicSbomInference: true, + dynamicSbomInferenceIgnoreUnresolved: false, + }, + 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 as $expected', ({ 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/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 1309eb1ae..47b892850 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, @@ -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[] } @@ -70,41 +71,43 @@ 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, hints, + ignoreUnresolved, purlTypes, -}: { +}: DynamicSbomInference & { context: SocketFactsContext cwd: string excludePaths: string[] hints: CommandHints - purlTypes: readonly PURL_Type[] }): Promise { const outcomes = await generateRecursiveManifests({ + buildTimeout, context, cwd, excludePaths, hints, + ignoreUnresolved, purlTypes, verbose: false, }) 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..f54c13a8c 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.test.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.test.mts @@ -8,16 +8,20 @@ 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, 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', () => ({ @@ -43,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 }), }) } @@ -69,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, @@ -103,23 +121,29 @@ describe('runDynamicSbomInference', () => { ]) }) + 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'] }, + ])( + '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[] + purlTypes?: FactsOnlyTypes }>([ - { - 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: [ 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/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 70ed0eaa6..e1ed1b256 100644 --- a/test/reachability-options.mts +++ b/test/reachability-options.mts @@ -1,4 +1,25 @@ +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, + } +} // 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..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,109 +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. - --ecosystems Limit fix analysis to specific ecosystems. Accepts space- or comma-separated values and is case-insensitive. Default + --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma s -s to all ecosystems. +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 Skip matching paths from the scan entirely: manifests under these paths are not uploaded, and fixes are not applied +.NET). Defaults to all of them. -to workspaces under them. Patterns are anchored micromatch globs matched relative to the target directory (CWD); `data/postgres/pgdata` matc + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build -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 +(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. -st collection. Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. + --ecosystems Limit fix analysis to specific ecosystems. Accepts space- or comma-separated values and is case-insensitive. Default - --fix-version Override the version of @coana-tech/cli used for fix analysis. Default: 15.15.9. +s to all ecosystems. - --id Provide a list of vulnerability identifiers to compute fixes for: + --exclude-paths Skip matching paths from the scan entirely: manifests under these paths are not uploaded, and fixes are not applied - - GHSA IDs (​https://docs.github.com/en/code-security/security-advisories/working-with-global-security-advisories +to workspaces under them. Patterns are anchored micromatch globs matched relative to the target directory (CWD); `data/postgres/pgdata` matc --from-the-github-advisory-database/about-the-github-advisory-database#about-ghsa-ids​) (e.g., GHSA-xxxx-xxxx-xxxx) +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 - - CVE IDs (​https://cve.mitre.org/cve/identifiers/​) (e.g., CVE-2026-1234) - automatically converted to GHSA +st collection. Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. - - PURLs (​https://github.com/package-url/purl-spec​) (e.g., pkg:npm/package@1.0.0) - automatically converted to GH + --fix-version Override the version of @coana-tech/cli used for fix analysis. Default: 15.15.9. -SA + --id Provide a list of vulnerability identifiers to compute fixes for: - Can be provided as comma separated values or as multiple flags. Cannot be used with --all. + - GHSA IDs (​https://docs.github.com/en/code-security/security-advisories/working-with-global-security-advisories - --include Include workspaces matching these glob patterns. Can be provided as comma separated values or as multiple flags +-from-the-github-advisory-database/about-the-github-advisory-database#about-ghsa-ids​) (e.g., GHSA-xxxx-xxxx-xxxx) - --json Output as JSON + - CVE IDs (​https://cve.mitre.org/cve/identifiers/​) (e.g., CVE-2026-1234) - automatically converted to GHSA - --markdown Output as Markdown + - PURLs (​https://github.com/package-url/purl-spec​) (e.g., pkg:npm/package@1.0.0) - automatically converted to GH - --minimum-release-age Set a minimum age requirement for suggested upgrade versions (e.g., 1h, 2d, 3w). A higher age requirement reduces +SA - the risk of upgrading to malicious versions. For example, setting the value to 1 week (1w) gives ecosystem maintainers one week to remove p + Can be provided as comma separated values or as multiple flags. Cannot be used with --all. -otentially malicious versions. + --include Include workspaces matching these glob patterns. Can be provided as comma separated values or as multiple flags - --no-apply-fixes Compute fixes only, do not apply them. Logs what upgrades would be applied. If combined with --output-file, the outp + --json Output as JSON -ut file will contain the upgrades that would be applied. + --markdown Output as Markdown - --no-major-updates Do not suggest or apply fixes that require major version updates of direct or transitive dependencies + --minimum-release-age Set a minimum age requirement for suggested upgrade versions (e.g., 1h, 2d, 3w). A higher age requirement reduces - --output-file Path to store upgrades as a JSON file at this path. + the risk of upgrading to malicious versions. For example, setting the value to 1 week (1w) gives ecosystem maintainers one week to remove p - --package-managers Limit fix analysis to specific package managers within an ecosystem (e.g. NPM, PNPM, YARN, MAVEN, POETRY). Accepts s +otentially malicious versions. -pace- or comma-separated values and is case-insensitive. When combined with --ecosystems, an artifact must satisfy both filters. + --no-apply-fixes Compute fixes only, do not apply them. Logs what upgrades would be applied. If combined with --output-file, the outp - --pr-limit Maximum number of pull requests to create in CI mode (default 10). Has no effect in local mode. +ut file will contain the upgrades that would be applied. - --range-style Define how dependency version ranges are updated in package.json (default 'preserve'). + --no-major-updates Do not suggest or apply fixes that require major version updates of direct or transitive dependencies - Available styles: + --output-file Path to store upgrades as a JSON file at this path. - * pin - Use the exact version (e.g. 1.2.3) + --package-managers Limit fix analysis to specific package managers within an ecosystem (e.g. NPM, PNPM, YARN, MAVEN, POETRY). Accepts s - * preserve - Retain the existing version range style as-is +pace- or comma-separated values and is case-insensitive. When combined with --ecosystems, an artifact must satisfy both filters. - --show-affected-direct-dependencies List the direct dependencies responsible for introducing transitive vulnerabilities and list the up + --pr-limit Maximum number of pull requests to create in CI mode (default 10). Has no effect in local mode. -dates required to resolve the vulnerabilities + --range-style Define how dependency version ranges are updated in package.json (default 'preserve'). - --silence Silence all output except the final result + Available styles: - + * pin - Use the exact version (e.g. 1.2.3) - Environment Variables (for CI/PR mode) + * preserve - Retain the existing version range style as-is - CI Set to enable CI mode + --show-affected-direct-dependencies List the direct dependencies responsible for introducing transitive vulnerabilities and list the up - SOCKET_CLI_GITHUB_TOKEN GitHub token for PR creation (or GITHUB_TOKEN) +dates required to resolve the vulnerabilities - SOCKET_CLI_GIT_USER_NAME Git username for commits + --silence Silence all output except the final result - SOCKET_CLI_GIT_USER_EMAIL Git email for commits - + + Environment Variables (for CI/PR mode) - Examples + CI Set to enable CI mode - $ socket fix + SOCKET_CLI_GITHUB_TOKEN GitHub token for PR creation (or GITHUB_TOKEN) - $ socket fix --id CVE-2021-23337 + SOCKET_CLI_GIT_USER_NAME Git username for commits - $ socket fix ./path/to/project --range-style pin + SOCKET_CLI_GIT_USER_EMAIL Git email for commits - + 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 550c83391..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,213 +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. - --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) + --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma s -full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman +eparated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget ( -d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. +.NET). Defaults to all of them. - Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build -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 +(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. -oject. A build module or project outside the scan root cannot be excluded. + --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) - --interactive Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, +full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman - defaulting them to cancel/no. +d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. - --json Output as JSON + Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj - --markdown Output as Markdown +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 - --org Force override the organization slug, overrides the default org from config +oject. A build module or project outside the scan root cannot be excluded. - --pull-request Pull request number + --interactive Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, - --reach Run full application reachability analysis + defaulting them to cancel/no. - --read-only Similar to --dry-run except it can read from remote, stops before it would create an actual report + --json Output as JSON - --repo Repository name + --markdown Output as Markdown - --report Wait for the scan creation to complete, then basically run `socket scan report` on it + --org Force override the organization slug, overrides the default org from config - --report-level Which policy level alerts should be reported (default 'error') + --pull-request Pull request number - --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 + --reach Run full application reachability analysis -lp for details. Defaults to true. + --read-only Similar to --dry-run except it can read from remote, stops before it would create an actual report - --tmp Set the visibility (true/false) of the scan in your dashboard. + --repo Repository name - --uv-members Scan each TARGET directory as a uv project, using the versions pinned in its uv.lock or its workspace root uv.lock. + --report Wait for the scan creation to complete, then basically run `socket scan report` on it -Uploads a CycloneDX dependency graph per TARGET in place of manifest discovery, including all extras and dependency groups. Requires uv on P + --report-level Which policy level alerts should be reported (default 'error') -ATH; standalone builds use SOCKET_CLI_UV_PATH. + --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 - --workspace The workspace in the Socket Organization that the repository is in to associate with the full scan. +lp for details. Defaults to true. - + --tmp Set the visibility (true/false) of the scan in your dashboard. - Reachability Options (when --reach is used) + --uv-members Scan each TARGET directory as a uv project, using the versions pinned in its uv.lock or its workspace root uv.lock. - --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul +Uploads a CycloneDX dependency graph per TARGET in place of manifest discovery, including all extras and dependency groups. Requires uv on P -tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau +ATH; standalone builds use SOCKET_CLI_UV_PATH. -lts to all advisories. + --workspace The workspace in the Socket Organization that the repository is in to associate with the full scan. - --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. + Reachability Options (when --reach is used) - --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-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul -m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. +tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau - --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th +lts to all advisories. -at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. + --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. - --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back +512MB, 8GB). The default is 8GB. -to precomputed reachability results. By default, the CLI halts on analysis errors. + --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-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi +m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. -lity results. By default, the CLI halts on installation errors. + --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th - --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version +at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. - catalog / pre-generated SBOM). By default, the CLI halts. + --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back - --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa +to precomputed reachability results. By default, the CLI halts on analysis errors. -ult, the CLI halts. + --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi - --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. +lity results. By default, the CLI halts on installation errors. - --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. + --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version - --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. + catalog / pre-generated SBOM). By default, the CLI halts. - --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director + --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa -y or module cache). Missing dependencies count as installation failures. +ult, the CLI halts. - --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. + --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. - --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp + --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. -orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. + --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. - --reach-fallback-to-regular-scan If reachability analysis fails, continue with a regular SCA scan (without reachability results) instea + --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director -d of halting. By default, the CLI halts on reachability errors. +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-fallback-to-regular-scan If reachability analysis fails, continue with a regular SCA scan (without reachability results) instea - runs to speed up the analysis. +d of halting. By default, the CLI halts on reachability errors. - --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-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d -project. +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-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. +n SBOM carrying stale reachability results. - + --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous - Uploads the specified dependency manifest files for Go, Gradle, JavaScript, + runs to speed up the analysis. - Kotlin, Python, and Scala. Files like "package.json" and "requirements.txt". + --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your - If any folder is specified, the ones found in there recursively are uploaded. +project. - + --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. - Details on TARGET: - + + Uploads the specified dependency manifest files for Go, Gradle, JavaScript, - - Defaults to the current dir (cwd) if none given + Kotlin, Python, and Scala. Files like "package.json" and "requirements.txt". - - Multiple targets can be specified + If any folder is specified, the ones found in there recursively are uploaded. - - 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 + Details on TARGET: - - Dirs MUST be within the current dir (cwd), you can use --cwd to change it + - - Supports globbing such as "**/package.json", "**/requirements.txt", etc. + - Defaults to the current dir (cwd) if none given - - Ignores any file specified in your project's ".gitignore" + - Multiple targets can be specified - - Also a sensible set of default ignores from the "ignore-by-default" module + - 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 - The --repo and --branch flags tell Socket to associate this Scan with that + - Dirs MUST be within the current dir (cwd), you can use --cwd to change it - repo/branch. The names will show up on your dashboard on the Socket website. + - Supports globbing such as "**/package.json", "**/requirements.txt", etc. - + - Ignores any file specified in your project's ".gitignore" - Note: for a first run you probably want to set --default-branch to indicate + - Also a sensible set of default ignores from the "ignore-by-default" module - the default branch name, like "main" or "master". - + + The --repo and --branch flags tell Socket to associate this Scan with that - The "alerts page" (​https://socket.dev/dashboard/org/YOURORG/alerts​) will show + repo/branch. The names will show up on your dashboard on the Socket website. - 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 + Note: for a first run you probably want to set --default-branch to indicate - --set-as-alerts-page flag will default to true to update this. You can prevent + the default branch name, like "main" or "master". - 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. + The "alerts page" (​https://socket.dev/dashboard/org/YOURORG/alerts​) will show - + the results from the last scan designated as the "pending head" on the branch - You can use `socket scan setup` to configure certain repo flag defaults. + 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 - Examples + this by using --no-set-as-alerts-page. This flag is ignored for any branch that - $ socket scan create + is not designated as the "default branch". It is disabled when using --tmp. - $ socket scan create ./proj --json + - $ socket scan create --repo=test-repo --branch=main ./package.json + You can use `socket scan setup` to configure certain repo flag defaults. - $ socket scan create --uv-members ./packages/api ./packages/worker - + + Examples - + $ 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 6f063d190..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,129 +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. - --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) + --dynamic-sbom-inference-ecosystems With --dynamic-sbom-inference: generate Socket facts only for these ecosystems, as either a comma s -full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman +eparated value or as multiple flags; the others keep their manifest files as they are. Supported: maven (Gradle, Maven, and sbt) and nuget ( -d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. +.NET). Defaults to all of them. - Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj + --dynamic-sbom-inference-ignore-unresolved With --dynamic-sbom-inference: warn on unresolved dependencies instead of failing the build -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 +(unresolved deps are not emitted to the facts files); overrides each build's socket.json setting. -oject. A build module or project outside the scan root cannot be excluded. + --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) - --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul +full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman -tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau +d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. -lts to all advisories. + Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj - --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. +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 -512MB, 8GB). The default is 8GB. +oject. A build module or project outside the scan root cannot be excluded. - --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-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul -m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. +tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau - --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th +lts to all advisories. -at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. + --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. - --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back +512MB, 8GB). The default is 8GB. -to precomputed reachability results. By default, the CLI halts on analysis errors. + --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-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi +m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. -lity results. By default, the CLI halts on installation errors. + --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th - --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version +at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. - catalog / pre-generated SBOM). By default, the CLI halts. + --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back - --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa +to precomputed reachability results. By default, the CLI halts on analysis errors. -ult, the CLI halts. + --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi - --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. +lity results. By default, the CLI halts on installation errors. - --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. + --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version - --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. + catalog / pre-generated SBOM). By default, the CLI halts. - --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director + --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa -y or module cache). Missing dependencies count as installation failures. +ult, the CLI halts. - --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. + --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. - --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp + --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. -orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. + --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. - --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d + --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director -eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a +y or module cache). Missing dependencies count as installation failures. -n SBOM carrying stale reachability results. + --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. - --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous + --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp - runs to speed up the analysis. +orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. - --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-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d -project. +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-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. +n SBOM carrying stale reachability results. - + --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous - Runs the Socket reachability analysis without creating a scan in Socket. + runs to speed up the analysis. - The output is written to .socket.facts.json in the current working directory + --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your - unless the --output flag is specified. +project. - + --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. - Note: Manifest files are uploaded to Socket's backend services because the + - reachability analysis requires creating a Software Bill of Materials (SBOM) + Runs the Socket reachability analysis without creating a scan in Socket. - from these files before the analysis can run. + The output is written to .socket.facts.json in the current working directory - + unless the --output flag is specified. - Examples + - $ socket scan reach + Note: Manifest files are uploaded to Socket's backend services because the - $ socket scan reach ./proj + reachability analysis requires creating a Software Bill of Materials (SBOM) - $ socket scan reach ./proj --reach-ecosystems npm,pypi + from these files before the analysis can run. - $ socket scan reach ./monorepo --dynamic-sbom-inference + - $ socket scan reach --output custom-report.json + Examples - $ socket scan reach ./proj --output ./reports/analysis.json + $ socket scan reach - + $ socket scan reach ./proj - + $ 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