diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cffd31b2..66b6ed132 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added - Scan many repositories with `--dynamic-sbom-inference` without a `socket.json` in each: `--dynamic-sbom-inference-ignore-unresolved` tolerates unresolved dependencies in every build. - `--dynamic-sbom-inference` no longer waits indefinitely on a hung build: a build root whose build tool runs take longer than 3600 seconds in all fails with a message saying so. Set the limit in seconds (e.g. `1800`) with `--dynamic-sbom-inference-build-timeout` on `socket scan create`, `socket scan reach` and `socket fix`, or `--build-timeout` on `socket manifest dynamic-sbom-inference`, and turn it off with `0`. The timeout needs Coana 15.15.10 or newer. +- Keep `--dynamic-sbom-inference` scans going when a build fails with the new `--dynamic-sbom-inference-skip-failed-builds` option (`--skip-failed-builds` on `socket manifest dynamic-sbom-inference`): the failed build and the modules it would have covered are left out with a warning, their manifest files are scanned as without `--dynamic-sbom-inference`, and every other build root still produces its Socket facts. Skipping failed builds needs Coana 15.15.10 or newer. ### Changed - `--dynamic-sbom-inference` can be passed to every repository: one without a .NET, Gradle, Maven or sbt build is scanned as without the flag instead of failing, and `socket manifest dynamic-sbom-inference` reports that no build root was found and exits successfully. diff --git a/docs/dynamic-sbom-inference-settings.md b/docs/dynamic-sbom-inference-settings.md index 570c3c4c0..7065e59a5 100644 --- a/docs/dynamic-sbom-inference-settings.md +++ b/docs/dynamic-sbom-inference-settings.md @@ -14,7 +14,16 @@ asks the same questions interactively and writes the same files. its dependencies, unless another build already loads it. A Maven reactor builds its modules, including ones outside its directory such as `../core`; a Gradle or sbt build builds its subprojects. -3. Fails if any build it runs fails, naming the build. +3. Fails if any build it runs fails, naming the build. With + `--dynamic-sbom-inference-skip-failed-builds` (`--skip-failed-builds` on + `socket manifest dynamic-sbom-inference`), it instead leaves out a build + that fails, with the modules its tool read of it, and goes on. Where the + tool could not read a project's modules, or the failure tells nothing of + them, it leaves out the builds in or under that directory, except Gradle + builds with settings of their own and sbt builds with a `project` + directory of their own. No Socket facts are generated for what it leaves + out: the scan reads those manifest files as it does without + `--dynamic-sbom-inference`, and reachability analysis leaves them out. Settings tell the build tools how to run each build, and which builds not to run. @@ -120,8 +129,8 @@ modules itself. Settings for such a module are ignored, with a warning. | `empty` | Built; nothing to resolve. | | `skippedCovered` | Built as part of another build. | | `skippedDisabled` | Skipped by a setting, or loaded by a skipped build. | - | `failed` | Its build tool failed; the output above it says why. | - | `aborted` | Not run because a build in or above its directory failed. | + | `failed` | Its build tool failed; `reason` and the output above it say why. `skipped` is true when the run went on without it. | + | `aborted` | Not run because a build that may load it failed; `abortedBy` names that build. | 2. For each `failed` build, read the build tool's error and fix the cause in the nearest fitting `socket.json`: `javaHome` for a wrong JDK, `bin` for a diff --git a/src/commands/fix/cmd-fix.integration.test.mts b/src/commands/fix/cmd-fix.integration.test.mts index cc2004f6f..9c9ff978c 100644 --- a/src/commands/fix/cmd-fix.integration.test.mts +++ b/src/commands/fix/cmd-fix.integration.test.mts @@ -173,6 +173,7 @@ describe('socket fix', async () => { --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. + --dynamic-sbom-inference-skip-failed-builds With --dynamic-sbom-inference: leave out a build root that fails to generate Socket facts, and the build roots it holds back, instead of aborting; the scan reads their manifest files as it does without --dynamic-sbom-inference. Other build roots, including builds of their own beneath it, are still built. --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/generated-socket-facts.mts b/src/commands/fix/generated-socket-facts.mts index 454dd4322..b8b802cab 100644 --- a/src/commands/fix/generated-socket-facts.mts +++ b/src/commands/fix/generated-socket-facts.mts @@ -55,6 +55,7 @@ export async function generateSocketFactsForFix({ findFactsPaths, ignoreUnresolved, purlTypes, + skipFailedBuilds, tmpDir, }: DynamicSbomInference & { context: Omit @@ -89,6 +90,7 @@ export async function generateSocketFactsForFix({ hints: EXCLUDE_PATHS_HINTS, ignoreUnresolved, purlTypes, + skipFailedBuilds, }) if (!inferred.factsOnlyTypes) { return undefined diff --git a/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.mts b/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.mts index 6a0933ffa..fb9b5c4ee 100644 --- a/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.mts +++ b/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.mts @@ -37,6 +37,12 @@ const config: CliCommandConfig = { description: "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", }, + skipFailedBuilds: { + type: 'boolean', + default: false, + description: + 'Leave out a build root that fails to generate Socket facts, and the build roots it holds back, instead of failing the run. Other build roots, including builds of their own beneath it, are still built.', + }, verbose: { type: 'boolean', default: false, @@ -89,12 +95,14 @@ async function run( ignoreUnresolved, json, markdown, + skipFailedBuilds, verbose: verboseFlag, } = cli.flags as { dryRun: boolean ignoreUnresolved: boolean | undefined json: boolean markdown: boolean + skipFailedBuilds: boolean verbose: boolean | undefined } const verbose = !!verboseFlag @@ -150,6 +158,7 @@ async function run( excludePaths, ignoreUnresolved, outputKind, + skipFailedBuilds, verbose, }) } 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 f1587a975..e2b7ef486 100644 --- a/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.test.mts +++ b/src/commands/manifest/cmd-manifest-dynamic-sbom-inference.test.mts @@ -38,6 +38,7 @@ describe('socket manifest dynamic-sbom-inference', async () => { --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 --markdown Output as Markdown + --skip-failed-builds Leave out a build root that fails to generate Socket facts, and the build roots it holds back, instead of failing the run. Other build roots, including builds of their own beneath it, are still built. --verbose Print debug messages Examples diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 999ff1f41..526c40e0e 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -25,6 +25,7 @@ import { parseBuildToolOpts } from './parse-build-tool-opts.mts' import { DSI_SETUP_COMMAND, createSocketFactsWorkDir, + generateManifestFacts, keepFacts, readsReachabilitySettings, rootBuildTime, @@ -45,9 +46,11 @@ import type { ResolvedBuildRootSettings } from './build-root-config.mts' import type { BuildRoot, Membership } from './discover-manifest-roots.mts' import type { LoadedBuild } from './load-build.mts' import type { + BuildFailure, BuildOptionHints, BuildTimeout, CommandHints, + FailedBuildProject, RunManifestFactsOutcome, RunManifestFactsResult, SocketFactsContext, @@ -74,11 +77,17 @@ export type RecursiveManifestOutcomeStatus = | 'skippedDisabled' export type RecursiveManifestOutcome = BuildRoot & { + // Of an aborted root: the failed build root that held it back. + abortedBy?: string | undefined // The facts file of a run that was dropped, which no kept run wrote: it holds // no kept build's facts, so it must not be collected. discardedFactsPath?: string | undefined ecosystem: BuildTool factsPath?: string | undefined + // Of a failed root: why, where Coana said, and whether the run went on + // without it. + reason?: string | undefined + skipped?: boolean | undefined status: RecursiveManifestOutcomeStatus } @@ -147,6 +156,17 @@ type Run = Candidate & { // A build skipped by its own `builds` entry, loaded to skip what it loads. type Load = Candidate & LoadedBuild +// What a failed build holds back of the builds not yet run. `members`: the +// builds its tool read, and those in or under a project whose modules it +// could not read, but builds of their own. `directory`: everything in or +// under its directory, when the run does not go on past it or nothing tells +// what its tool read; going on past it, builds of their own still run. +type HeldBack = + | { by: 'directory' } + | { by: 'members'; membership: Membership; unknownDirs: string[] } + +type Failed = { failure: BuildFailure; held: HeldBack } + type WalkContext = { buildTimeout: BuildTimeout | undefined // Every run writes into the work dir, so a dropped run leaves the facts @@ -356,6 +376,20 @@ async function walkTool( const runs = new Map() const loads = new Map() const failures: Candidate[] = [] + const failed = new Map() + const skipped = !!ctx.context.skipFailedBuilds + const fail = async (candidate: Candidate, failure: BuildFailure) => { + failures.push(candidate) + failed.set(candidate.index, { + failure, + held: + skipped && + failure.blame === 'build' && + failure.projects !== 'unreported' + ? await heldMembers(failure.projects, ctx.realCwd) + : { by: 'directory' }, + }) + } // Drops, latest first, each run the others or the skipped builds cover // while every run dropped before stays covered. @@ -448,11 +482,27 @@ async function walkTool( } uncoveredFailures = stillFailed } - const isAborted = (candidate: Candidate) => - uncoveredFailures.some( - failure => - failure !== candidate && - isPathInside(failure.root.dir, candidate.root.dir), + // Going on past a failed build, a build of its own still runs: only running + // it tells whether the failed build would have loaded all it loads. A build + // loading the build of its ancestor loads that build. + const holds = (failure: Candidate, candidate: Candidate): boolean => { + const { held } = failed.get(failure.index)! + if (held.by === 'directory') { + return ( + !(skipped && candidate.marker) && + isPathInside(failure.root.dir, candidate.root.dir) + ) + } + return ( + !candidate.marker && + (isBuildRootCovered(held.membership, ecosystem, candidate.root) || + held.unknownDirs.some(dir => isPathInside(dir, candidate.root.dir)) || + ancestorBuild[candidate.index] === failure) + ) + } + const heldBackBy = (candidate: Candidate): Candidate | undefined => + uncoveredFailures.find( + failure => failure !== candidate && holds(failure, candidate), ) for (;;) { @@ -465,7 +515,7 @@ async function walkTool( runs.has(index) || loads.has(index) || failures.includes(candidate) || - isAborted(candidate) || + heldBackBy(candidate) || isCheaplyCovered(coverage, candidate) || isCheaplyCovered(skippedCoverage, candidate) || skipOf(candidate) === 'skip' || @@ -492,20 +542,21 @@ async function walkTool( loads.set(next.index, { ...next, ...loaded }) unsettled = true } else { - failures.push(next) - logger.fail( - `Could not load ${buildRootPath(next.root)} to tell which builds to skip with it (${why}). Fix its settings, or skip its whole directory instead, with \`${DSI_SETUP_COMMAND}\`.`, - ) + const reason = `Could not load ${buildRootPath(next.root)} to tell which builds to skip with it (${why}). Fix its settings, or skip its whole directory instead, with \`${DSI_SETUP_COMMAND}\`.` + logger.fail(reason) + // eslint-disable-next-line no-await-in-loop + await fail(next, { blame: 'other', reason }) } continue } // eslint-disable-next-line no-await-in-loop const run = await runCandidate(ctx, next, optionsFor(next)) - if (run) { + if ('failure' in run) { + // eslint-disable-next-line no-await-in-loop + await fail(next, run.failure) + } else { runs.set(next.index, run) unsettled = true - } else { - failures.push(next) } } @@ -583,6 +634,15 @@ async function walkTool( } else if (failures.includes(candidate)) { if (uncoveredFailures.includes(candidate)) { status = 'failed' + const { failure } = failed.get(index)! + outcomes.push({ + ...root, + ecosystem, + reason: failure.reason, + skipped, + status, + }) + continue } else { // eslint-disable-next-line no-await-in-loop const loader = await loaderOf(candidate) @@ -599,8 +659,14 @@ async function walkTool( // eslint-disable-next-line no-await-in-loop } else if (await isCovered(skippedCoverage, candidate)) { status = 'skippedDisabled' - } else if (isAborted(candidate)) { - status = 'aborted' + } else if (heldBackBy(candidate)) { + outcomes.push({ + ...root, + abortedBy: buildRootPath(heldBackBy(candidate)!.root), + ecosystem, + status: 'aborted', + }) + continue } else if (skipOf(candidate)) { status = 'skippedDisabled' } else { @@ -622,15 +688,22 @@ async function walkTool( } for (const failure of uncoveredFailures) { - const aborted = candidates.filter( - candidate => - isAborted(candidate) && - !failures.includes(candidate) && - isPathInside(failure.root.dir, candidate.root.dir), - ) - if (aborted.length) { + const path = buildRootPath(failure.root) + const aborted = outcomes.filter(o => o.abortedBy === path) + const { held } = failed.get(failure.index)! + const list = aborted.map(o => `\n - ${buildRootPath(o)}`).join('') + if (skipped) { + const heldBack = !aborted.length + ? '. ' + : held.by === 'members' + ? `, and the ${aborted.length} build root(s) that are its modules or that its build tool could not tell apart from them:${list}\n` + : `, and the ${aborted.length} build root(s) in or under ${displayPath(failure.root.dir)}, which cannot be told apart from its modules:${list}\n` logger.warn( - `Not building ${aborted.length} ${ecosystem} build root(s) in or under ${displayPath(failure.root.dir)}: ${buildRootPath(failure.root)} failed, and without it they cannot be told apart from its modules.`, + `Leaving out ${path} (${ecosystem}), whose build failed${heldBack}No build tool resolved ${aborted.length ? 'them' : 'it'}, so a scan reads ${aborted.length ? 'their' : 'its'} manifest files as it does without --dynamic-sbom-inference.`, + ) + } else if (aborted.length) { + logger.warn( + `Not building ${aborted.length} ${ecosystem} build root(s) in or under ${displayPath(failure.root.dir)}: ${path} failed, and without it they cannot be told apart from its modules.`, ) } } @@ -676,17 +749,33 @@ function runOptions( } } +async function heldMembers( + projects: readonly FailedBuildProject[], + scanRoot: string, +): Promise { + return { + by: 'members', + membership: await membershipOf(projects, scanRoot), + unknownDirs: await Promise.all( + projects + .filter(p => p.modules === 'unknown') + .map(p => realpathOrResolved(p.dir)), + ), + } +} + async function runCandidate( ctx: WalkContext, candidate: Candidate, options: SocketFactsRunOptions, -): Promise { +): Promise { // A run a later build turns out to cover is dropped before its facts are // placed. - const result = await runManifestFacts({ ...options, staged: true }) - if (result === null) { - return undefined + const run = await generateManifestFacts({ ...options, staged: true }) + if (run.status === 'failed') { + return { failure: run.failure } } + const result = run.status === 'generated' ? run.facts : undefined return { ...candidate, membership: result @@ -785,7 +874,8 @@ export async function generateRecursiveManifests({ reachabilityOf(context, tool, resolveSettings(tool, root)) } } - // A failure another build excuses leaves the exit code it set. + // A failure another build excuses, or the run goes on past, leaves the exit + // code it set. const exitCodeBefore = process.exitCode const walk = async (workDir: SocketFactsWorkDir) => { @@ -813,7 +903,7 @@ export async function generateRecursiveManifests({ async dir => await walk(await createSocketFactsWorkDir(dir, 'upload')), ) - if (!outcomes.some(o => o.status === 'failed')) { + if (!outcomes.some(o => o.status === 'failed' && !o.skipped)) { process.exitCode = exitCodeBefore } diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 4e23f8b9e..b39b64210 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -12,17 +12,17 @@ vi.mock('../../utils/socket-json.mts', async importOriginal => ({ })) vi.mock('./run-manifest-facts.mts', async importOriginal => ({ ...(await importOriginal()), + generateManifestFacts: vi.fn(), listBuildProjects: vi.fn(), listDotnetSolutionMembers: vi.fn(async () => undefined), - runManifestFacts: vi.fn(), })) import { generateRecursiveManifests } from './generate-recursive-manifests.mts' import { EXCLUDE_PATHS_HINTS, + generateManifestFacts, listBuildProjects, listDotnetSolutionMembers, - runManifestFacts, } from './run-manifest-facts.mts' import { buildRootPath } from './scripts/build-tool.mts' import { @@ -37,7 +37,8 @@ import { } from '../../utils/socket-json.mts' import type { - RunManifestFactsOutcome, + BuildFailure, + ManifestFactsRun, SocketFactsProject, SocketFactsWorkDir, } from './run-manifest-facts.mts' @@ -86,17 +87,32 @@ function newWorkDir(parent = '/'): SocketFactsWorkDir { } } +// A run's facts, `undefined` for nothing to resolve, `null` for a failure the +// CLI or Coana is blamed for, or a build failure of the customer's. function mockFacts( impl: ( - options: Parameters[0], - ) => Promise, + options: Parameters[0], + ) => Promise, ): void { - vi.mocked(runManifestFacts).mockImplementation( - async (options): Promise => { + vi.mocked(generateManifestFacts).mockImplementation( + async (options): Promise => { const facts = await impl(options) - return ( - facts && { ...facts, targetPath: facts.targetPath ?? facts.factsPath } - ) + if (facts === undefined) { + return { status: 'empty' } + } + if (facts === null) { + return { + failure: { blame: 'other', reason: 'Coana failed.' }, + status: 'failed', + } + } + if ('failure' in facts) { + return { ...facts, status: 'failed' } + } + return { + facts: { ...facts, targetPath: facts.targetPath ?? facts.factsPath }, + status: 'generated', + } }, ) } @@ -134,6 +150,12 @@ function gradleFacts(cwd: string, dirs: string[]) { } } +function reactorFailure( + projects: (BuildFailure & { blame: 'build' })['projects'], +): BuildFailure { + return { blame: 'build', projects, reason: 'Non-resolvable import POM' } +} + function relOf(dir: string): string { return path.relative(monorepo, dir).replaceAll('\\', '/') } @@ -141,14 +163,14 @@ function relOf(dir: string): string { function sentReachability() { return Object.fromEntries( vi - .mocked(runManifestFacts) + .mocked(generateManifestFacts) .mock.calls.map(({ 0: opts }) => [opts.ecosystem, opts.reachability]), ) } describe('generateRecursiveManifests', () => { beforeEach(() => { - vi.mocked(runManifestFacts).mockReset() + vi.mocked(generateManifestFacts).mockReset() vi.mocked(readOrDefaultSocketJson).mockReturnValue({} as SocketJson) mockCascade(() => ({})) }) @@ -176,8 +198,8 @@ describe('generateRecursiveManifests', () => { }) const calledDirs = vi - .mocked(runManifestFacts) - .mock.calls.map(([opts]) => `${opts.ecosystem}:${relOf(opts.cwd)}`) + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: opts }) => `${opts.ecosystem}:${relOf(opts.cwd)}`) .sort() expect(calledDirs).toEqual( [ @@ -248,8 +270,8 @@ describe('generateRecursiveManifests', () => { expect(byDir.get(sharedLib)).toBe('skippedCovered') expect( vi - .mocked(runManifestFacts) - .mock.calls.some(([opts]) => opts.cwd === sharedLib), + .mocked(generateManifestFacts) + .mock.calls.some(({ 0: opts }) => opts.cwd === sharedLib), ).toBe(builtAlone) expect(await fs.readFile(sharedFacts, 'utf8')).toBe('committed') expect( @@ -313,7 +335,9 @@ describe('generateRecursiveManifests', () => { }) expect( - vi.mocked(runManifestFacts).mock.calls.map(([o]) => o.staged), + vi + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: o }) => o.staged), ).toEqual([true, true]) const generated = outcomes.filter(o => o.status === 'generated') expect(generated).toHaveLength(1) @@ -455,7 +479,7 @@ describe('generateRecursiveManifests', () => { const byDir = new Map(outcomes.map(o => [o.dir, o.status])) expect(byDir.get(member)).toBe('skippedCovered') - expect(runManifestFacts).toHaveBeenCalledTimes(1) + expect(generateManifestFacts).toHaveBeenCalledTimes(1) } finally { await fs.rm(outer, { recursive: true, force: true }) } @@ -585,9 +609,9 @@ describe('generateRecursiveManifests', () => { } expect( vi - .mocked(runManifestFacts) - .mock.calls.filter(([opts]) => opts.ecosystem === 'maven') - .map(([opts]) => relOf(opts.cwd)) + .mocked(generateManifestFacts) + .mock.calls.filter(({ 0: opts }) => opts.ecosystem === 'maven') + .map(({ 0: opts }) => relOf(opts.cwd)) .sort(), ).toEqual(['dual-marker-dir', 'reactor']) expect(byKey.get('maven:dual-marker-dir')).toBe('generated') @@ -607,6 +631,163 @@ describe('generateRecursiveManifests', () => { } }) + describe('a failed build', () => { + const members = [ + 'maven:reactor/moduleA', + 'maven:reactor/moduleB', + 'maven:reactor/moduleB/independent-submodule', + ] + + it.for([ + { + name: 'leaves out the modules its build tool read, and builds a build of its own beneath it', + failure: reactorFailure([ + { ...mavenProject(reactor, '.'), modules: 'known' }, + { ...mavenProject(reactor, 'moduleA'), modules: 'known' }, + { ...mavenProject(reactor, 'moduleB'), modules: 'known' }, + ]), + skipFailedBuilds: true, + aborted: ['maven:reactor/moduleA', 'maven:reactor/moduleB'], + skipped: true, + }, + { + name: 'leaves out what is in or under a project whose modules its build tool could not read', + failure: reactorFailure([ + { ...mavenProject(reactor, '.'), modules: 'unknown' }, + ]), + skipFailedBuilds: true, + aborted: members, + skipped: true, + }, + { + name: 'leaves out its whole directory when Coana reports none of it', + failure: reactorFailure('unreported'), + skipFailedBuilds: true, + aborted: members, + skipped: true, + }, + { + name: 'aborts its whole directory without skipping failed builds', + failure: reactorFailure([ + { ...mavenProject(reactor, '.'), modules: 'known' }, + ]), + skipFailedBuilds: false, + aborted: members, + skipped: false, + }, + { + name: 'leaves out its whole directory when Coana or the CLI failed', + failure: { blame: 'other', reason: 'Coana failed.' }, + skipFailedBuilds: true, + aborted: members, + skipped: true, + }, + ] satisfies Array<{ + aborted: string[] + failure: BuildFailure + name: string + skipFailedBuilds: boolean + skipped: boolean + }>)('$name', async ({ aborted, failure, skipFailedBuilds, skipped }) => { + mockFacts(async ({ cwd, ecosystem }) => { + if (ecosystem === 'maven' && cwd === reactor) { + process.exitCode = 1 + return { failure } + } + return { + factsPath: path.join(cwd, '.socket.facts.json'), + projects: [], + } + }) + const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) + + try { + const outcomes = await generateRecursiveManifests({ + context: { skipFailedBuilds }, + cwd: monorepo, + verbose: false, + }) + + const byKey = new Map( + outcomes.map(o => [`${o.ecosystem}:${relOf(o.dir)}`, o]), + ) + expect(byKey.get('maven:reactor')).toMatchObject({ + reason: failure.reason, + skipped, + status: 'failed', + }) + for (const member of members) { + expect(byKey.get(member)).toMatchObject( + aborted.includes(member) + ? { abortedBy: buildRootPath(byKey.get('maven:reactor')!) } + : { status: 'generated' }, + ) + } + expect( + outcomes.filter(o => o.status === 'aborted').map(o => o.abortedBy), + ).toHaveLength(aborted.length) + expect( + warnSpy.mock.calls.filter(c => + /Leaving out \S*reactor\S* \(maven\), whose build failed, and the \d build root\(s\)[^]*a scan reads their manifest files as it does without --dynamic-sbom-inference\.$/.test( + messageText(c[0]), + ), + ), + ).toHaveLength(skipped ? 1 : 0) + expect(process.exitCode).toBe(skipped ? undefined : 1) + } finally { + warnSpy.mockRestore() + } + }) + }) + + it.for([ + { skipFailedBuilds: true, tools: 'generated' }, + { skipFailedBuilds: false, tools: 'aborted' }, + ])( + 'leaves out the directory of a failed build that reports nothing, except a build of its own beneath it (skipping failed builds: $skipFailedBuilds)', + async ({ skipFailedBuilds, tools }) => { + const outer = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'unreported-failure-')), + ) + const sub = path.join(outer, 'sub') + const toolsDir = path.join(outer, 'tools') + try { + await fs.mkdir(sub, { recursive: true }) + await fs.mkdir(toolsDir, { recursive: true }) + await fs.writeFile(path.join(outer, 'settings.gradle'), '') + await fs.writeFile(path.join(sub, 'build.gradle'), '') + await fs.writeFile(path.join(toolsDir, 'settings.gradle'), '') + mockFacts(async ({ cwd }) => + cwd === outer + ? { failure: reactorFailure('unreported') } + : { + factsPath: path.join(cwd, 'gradle.socket.facts.json'), + projects: [], + }, + ) + const warnSpy = vi + .spyOn(logger, 'warn') + .mockImplementation(() => logger) + + try { + const outcomes = await generateRecursiveManifests({ + context: { skipFailedBuilds }, + cwd: outer, + verbose: false, + }) + + const byDir = new Map(outcomes.map(o => [o.dir, o.status])) + expect(byDir.get(sub)).toBe('aborted') + expect(byDir.get(toolsDir)).toBe(tools) + } finally { + warnSpy.mockRestore() + } + } finally { + await fs.rm(outer, { recursive: true, force: true }) + } + }, + ) + it('excuses the failure of a member built on its own before the build that loads it', async () => { const outer = await fs.realpath( await fs.mkdtemp(path.join(tmpdir(), 'misordered-member-')), @@ -674,7 +855,7 @@ describe('generateRecursiveManifests', () => { it('reports a non-fatal empty result distinctly from a failure', async () => { mockFacts(async ({ cwd, ecosystem }) => { if (ecosystem === 'maven' && cwd === dualMarkerDir) { - // No resolvable dependencies; runManifestFacts warns but does not fail. + // No resolvable dependencies, which is not a failure. return undefined } return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } @@ -704,8 +885,8 @@ describe('generateRecursiveManifests', () => { }) const reactorCall = vi - .mocked(runManifestFacts) - .mock.calls.map(([opts]) => opts) + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: opts }) => opts) .find(opts => opts.cwd === reactor) expect(reactorCall).toMatchObject({ excludeBase: await fs.realpath(monorepo), @@ -755,8 +936,8 @@ describe('generateRecursiveManifests', () => { const javaHomeByCall = new Map( vi - .mocked(runManifestFacts) - .mock.calls.map(([opts]) => [ + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: opts }) => [ `${opts.ecosystem}:${relOf(opts.cwd)}`, opts.javaHome, ]), @@ -870,7 +1051,7 @@ describe('generateRecursiveManifests', () => { mockCascade(() => ({ defaults: { manifest: { sbt: { reachability: { build: 'always' } } } }, })) - vi.mocked(runManifestFacts).mockClear() + vi.mocked(generateManifestFacts).mockClear() await expect( generateRecursiveManifests({ context: { workDir: newWorkDir() }, @@ -879,7 +1060,7 @@ describe('generateRecursiveManifests', () => { verbose: false, }), ).rejects.toThrow(/sbt\.reachability\.build` in .* is "always"/) - expect(runManifestFacts).not.toHaveBeenCalled() + expect(generateManifestFacts).not.toHaveBeenCalled() }) it.for([ @@ -935,9 +1116,10 @@ describe('generateRecursiveManifests', () => { }) const call = vi - .mocked(runManifestFacts) + .mocked(generateManifestFacts) .mock.calls.find( - ([opts]) => opts.cwd === dualMarkerDir && opts.ecosystem === 'maven', + ({ 0: opts }) => + opts.cwd === dualMarkerDir && opts.ecosystem === 'maven', ) expect(call?.[0].excludeConfigs).toBe('') expect(call?.[0].javaHome).toBeUndefined() @@ -960,7 +1142,9 @@ describe('generateRecursiveManifests', () => { verbose: false, }) - const calls = vi.mocked(runManifestFacts).mock.calls.map(([opts]) => opts) + const calls = vi + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: opts }) => opts) const verboseByCall = new Map( calls.map(opts => [`${opts.ecosystem}:${relOf(opts.cwd)}`, opts.verbose]), ) @@ -1007,7 +1191,9 @@ describe('generateRecursiveManifests', () => { verbose: false, }) - const calls = vi.mocked(runManifestFacts).mock.calls.map(([opts]) => opts) + const calls = vi + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: opts }) => opts) expect(calls.length).toBeGreaterThan(1) expect( calls.every(opts => opts.ignoreUnresolved === ignoreUnresolved), @@ -1033,8 +1219,8 @@ describe('generateRecursiveManifests', () => { const ignoreByCall = new Map( vi - .mocked(runManifestFacts) - .mock.calls.map(([opts]) => [ + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: opts }) => [ `${opts.ecosystem}:${relOf(opts.cwd)}`, opts.ignoreUnresolved, ]), @@ -1070,9 +1256,9 @@ describe('generateRecursiveManifests', () => { expect(byKey.get('gradle:dual-marker-dir')).toBe('skippedDisabled') expect( vi - .mocked(runManifestFacts) + .mocked(generateManifestFacts) .mock.calls.some( - ([opts]) => + ({ 0: opts }) => opts.cwd === dualMarkerDir && opts.ecosystem === 'gradle', ), ).toBe(false) @@ -1121,9 +1307,9 @@ describe('generateRecursiveManifests', () => { ) expect( vi - .mocked(runManifestFacts) + .mocked(generateManifestFacts) .mock.calls.some( - ([opts]) => + ({ 0: opts }) => opts.ecosystem === 'maven' && opts.cwd.startsWith(reactor) && opts.cwd !== independentSubmodule, @@ -1278,7 +1464,9 @@ describe('generateRecursiveManifests', () => { await generateRecursiveManifests({ cwd: cwdLink, verbose: false }) expect( - vi.mocked(runManifestFacts).mock.calls.map(([opts]) => opts.bin), + vi + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: opts }) => opts.bin), ).toEqual(['ABOVE-BIN']) } finally { await fs.rm(outer, { recursive: true, force: true }) @@ -1294,8 +1482,10 @@ describe('generateRecursiveManifests', () => { const context = { orgSlug: 'acme', workDir: newWorkDir() } await generateRecursiveManifests({ context, cwd: monorepo, verbose: false }) - expect(vi.mocked(runManifestFacts).mock.calls.length).toBeGreaterThan(1) - for (const [opts] of vi.mocked(runManifestFacts).mock.calls) { + expect(vi.mocked(generateManifestFacts).mock.calls.length).toBeGreaterThan( + 1, + ) + for (const [opts] of vi.mocked(generateManifestFacts).mock.calls) { expect(opts.context).toEqual(context) } }) @@ -1312,8 +1502,8 @@ describe('generateRecursiveManifests', () => { }) const calls = vi - .mocked(runManifestFacts) - .mock.calls.map(([opts]) => [ + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: opts }) => [ path.relative(pomNames, opts.cwd).replaceAll('\\', '/'), opts.entryFile, ]) @@ -1371,17 +1561,19 @@ describe('generateRecursiveManifests', () => { const cascadeDirs = vi .mocked(readSocketJsonChain) - .mock.calls.map(([dir]) => dir) + .mock.calls.map(({ 0: dir }) => dir) expect(cascadeDirs.length).toBeGreaterThan(0) expect(cascadeDirs).toEqual([...new Set(cascadeDirs)]) expect( warnSpy.mock.calls.filter(c => messageText(c[0]).includes('--file')), ).toHaveLength(0) expect( - vi.mocked(runManifestFacts).mock.calls.map(([o]) => o.buildOpts), + vi + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: o }) => o.buildOpts), ).toEqual( vi - .mocked(runManifestFacts) + .mocked(generateManifestFacts) .mock.calls.map(() => [ '--file', 'other.xml', @@ -1459,8 +1651,8 @@ describe('generateRecursiveManifests', () => { expect(byDir.get('sub/a')).toBe('skippedCovered') expect( vi - .mocked(runManifestFacts) - .mock.calls.map(([o]) => relativePosixPath(outer, o.cwd)), + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: o }) => relativePosixPath(outer, o.cwd)), ).toEqual(['.', 'sub']) }, ) @@ -1526,8 +1718,8 @@ describe('generateRecursiveManifests', () => { expect(byDir.get('sub/a')).toBe('skippedDisabled') expect( vi - .mocked(runManifestFacts) - .mock.calls.map(([o]) => relativePosixPath(outer, o.cwd)), + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: o }) => relativePosixPath(outer, o.cwd)), ).toEqual(['.']) expect(warnSpy.mock.calls.map(c => messageText(c[0]))).toEqual([ expect.stringMatching( @@ -1563,8 +1755,8 @@ describe('generateRecursiveManifests', () => { const optsByRoot = new Map( vi - .mocked(runManifestFacts) - .mock.calls.map(([o]) => [ + .mocked(generateManifestFacts) + .mock.calls.map(({ 0: o }) => [ path.relative(pomNames, path.join(o.cwd, o.entryFile ?? '')), o.buildOpts, ]), diff --git a/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts b/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts index cc007c31a..d841dfb4e 100644 --- a/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts +++ b/src/commands/manifest/handle-manifest-dynamic-sbom-inference.mts @@ -12,6 +12,7 @@ export async function handleManifestDynamicSbomInference({ excludePaths, ignoreUnresolved, outputKind, + skipFailedBuilds, verbose, }: { buildTimeout: BuildTimeout | undefined @@ -19,10 +20,12 @@ export async function handleManifestDynamicSbomInference({ excludePaths: string[] ignoreUnresolved?: boolean | undefined outputKind: OutputKind + skipFailedBuilds: boolean verbose: boolean }): Promise { const outcomes = await generateRecursiveManifests({ buildTimeout, + context: { skipFailedBuilds }, cwd, excludePaths, ignoreUnresolved, @@ -40,14 +43,21 @@ export async function handleManifestDynamicSbomInference({ 'No Gradle, sbt, Maven or .NET build root was found beneath the given directory.', data: outcomes, } - : outcomes.some(o => o.status === 'failed') + : outcomes.some(o => o.status === 'failed' && !o.skipped) ? { ok: false, code: 1, message: 'One or more build roots failed to generate Socket facts.', data: outcomes, } - : { ok: true, data: outcomes } + : outcomes.some(o => o.status === 'failed') + ? { + ok: true, + message: + 'Left out the build roots that failed, with those they held back.', + data: outcomes, + } + : { ok: true, data: outcomes } await outputManifestDynamicSbomInference(result, outputKind) } 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 3990c240d..21eccb2bd 100644 --- a/src/commands/manifest/handle-manifest-dynamic-sbom-inference.test.mts +++ b/src/commands/manifest/handle-manifest-dynamic-sbom-inference.test.mts @@ -18,78 +18,90 @@ vi.mock('./output-manifest-dynamic-sbom-inference.mts', () => ({ import { handleManifestDynamicSbomInference } from './handle-manifest-dynamic-sbom-inference.mts' -describe('handleManifestDynamicSbomInference', () => { - it('succeeds without facts when no build root is found anywhere', async () => { - mockGenerateRecursiveManifests.mockResolvedValue([]) - - await handleManifestDynamicSbomInference({ - cwd: '/repo', - excludePaths: [], - outputKind: 'text', - verbose: false, - }) +const generated = { + dir: '/repo/service-a', + ecosystem: 'maven', + factsPath: '/repo/service-a/.socket.facts.json', + status: 'generated', +} - expect(mockOutputManifestDynamicSbomInference).toHaveBeenCalledWith( - { +describe('handleManifestDynamicSbomInference', () => { + it.for([ + { + name: 'succeeds without facts when no build root is found anywhere', + outcomes: [], + skipFailedBuilds: false, + result: { ok: true, message: 'No Gradle, sbt, Maven or .NET build root was found beneath the given directory.', - data: [], }, - 'text', - ) - }) - - it('fails when one or more discovered build roots failed to generate facts', async () => { - const outcomes = [ - { - dir: '/repo/service-a', - ecosystem: 'maven', - factsPath: '/repo/service-a/.socket.facts.json', - status: 'generated', - }, - { dir: '/repo/service-b', ecosystem: 'maven', status: 'failed' }, - ] - mockGenerateRecursiveManifests.mockResolvedValue(outcomes) - - await handleManifestDynamicSbomInference({ - cwd: '/repo', - excludePaths: [], - outputKind: 'text', - verbose: false, - }) - - expect(mockOutputManifestDynamicSbomInference).toHaveBeenCalledWith( - { + }, + { + name: 'fails when a discovered build root failed to generate facts', + outcomes: [ + generated, + { + dir: '/repo/service-b', + ecosystem: 'maven', + skipped: false, + status: 'failed', + }, + ], + skipFailedBuilds: true, + result: { ok: false, code: 1, message: 'One or more build roots failed to generate Socket facts.', - data: outcomes, }, - 'text', - ) - }) - - it('succeeds when every discovered build root generated facts', async () => { - const outcomes = [ - { - dir: '/repo/service-a', - ecosystem: 'maven', - factsPath: '/repo/service-a/.socket.facts.json', - status: 'generated', + }, + { + name: 'succeeds, saying so, when the run went on past every failed build root', + outcomes: [ + generated, + { + dir: '/repo/service-b', + ecosystem: 'maven', + skipped: true, + status: 'failed', + }, + { + abortedBy: '/repo/service-b/pom.xml', + dir: '/repo/service-b/module', + ecosystem: 'maven', + status: 'aborted', + }, + ], + skipFailedBuilds: true, + result: { + ok: true, + message: + 'Left out the build roots that failed, with those they held back.', }, - ] + }, + { + name: 'succeeds when every discovered build root generated facts', + outcomes: [generated], + skipFailedBuilds: false, + result: { ok: true }, + }, + ])('$name', async ({ outcomes, result, skipFailedBuilds }) => { mockGenerateRecursiveManifests.mockResolvedValue(outcomes) await handleManifestDynamicSbomInference({ + buildTimeout: undefined, cwd: '/repo', excludePaths: [], outputKind: 'json', + skipFailedBuilds, verbose: false, }) + expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith( + expect.objectContaining({ context: { skipFailedBuilds } }), + ) expect(mockOutputManifestDynamicSbomInference).toHaveBeenCalledWith( - { ok: true, data: outcomes }, + { ...result, data: outcomes }, 'json', ) }) diff --git a/src/commands/manifest/output-manifest-dynamic-sbom-inference.mts b/src/commands/manifest/output-manifest-dynamic-sbom-inference.mts index d1728e533..0f51d5d09 100644 --- a/src/commands/manifest/output-manifest-dynamic-sbom-inference.mts +++ b/src/commands/manifest/output-manifest-dynamic-sbom-inference.mts @@ -12,7 +12,7 @@ function renderTable(outcomes: readonly RecursiveManifestOutcome[]): string { .filter(o => o.status !== 'skippedCovered') .map( o => - `- ${buildRootPath(o)} (${o.ecosystem}): ${o.status}${o.factsPath ? ` -> ${o.factsPath}` : ''}`, + `- ${buildRootPath(o)} (${o.ecosystem}): ${o.status}${o.skipped ? ' (left out)' : ''}${o.factsPath ? ` -> ${o.factsPath}` : ''}${o.abortedBy ? ` (held back by ${o.abortedBy})` : ''}`, ) .join('\n') } diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 5ce493318..042ec4c3c 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -74,6 +74,9 @@ export function rootBuildTime( return timeout && { spentMs: 0, timeout } } +// The first Coana release that reports what a failed build's tool read of it. +export const SKIP_FAILED_BUILDS_MIN_COANA_VERSION = '15.15.10' + export const DSI_SETUP_COMMAND = 'socket manifest setup --dynamic-sbom-inference' @@ -131,6 +134,9 @@ export type SocketFactsContext = { coanaVersion?: string | undefined disableDependencyDownloads?: boolean | undefined orgSlug?: string | undefined + // The run goes on past a build that fails, so Coana must report what the + // build's tool read of it. + skipFailedBuilds?: boolean | undefined workDir?: SocketFactsWorkDir | undefined } @@ -138,6 +144,23 @@ export type SocketFactsContext = { // build file even when absent. export type SocketFactsProject = { buildFiles: string[]; dir: string } +// A project of a failed build, and whether its build tool read the modules it +// aggregates. +export type FailedBuildProject = SocketFactsProject & { + modules: 'known' | 'unknown' +} + +// Why a build root failed. `build`: its build failed, and its tool read +// `projects` of it, which a Coana before SKIP_FAILED_BUILDS_MIN_COANA_VERSION +// leaves unreported. `other`: Coana, Socket's backend or the CLI failed. +export type BuildFailure = + | { + blame: 'build' + projects: FailedBuildProject[] | 'unreported' + reason: string + } + | { blame: 'other'; reason: string } + export type RunManifestFactsResult = { // Where Coana wrote the facts: in the work dir with one, else `targetPath`. factsPath: string @@ -185,7 +208,19 @@ const SOCKET_FACTS_REQUEST_CONTRACT = 1 type SocketFactsResult = | (RunManifestFactsResult & { status: 'generated' }) | { status: 'empty' } - | { status: 'failed' } + | { + blame: 'backend' | 'coana' | 'customer' + // Only of a customer's failure, from SKIP_FAILED_BUILDS_MIN_COANA_VERSION. + projects?: FailedBuildProject[] | undefined + reason: string + status: 'failed' + } + +// What a build root's run gave: its facts, nothing to resolve, or a failure. +export type ManifestFactsRun = + | { facts: RunManifestFactsResult; status: 'generated' } + | { status: 'empty' } + | { failure: BuildFailure; status: 'failed' } type SolutionMembers = | { members: string[] | null; status: 'members' } @@ -226,16 +261,37 @@ async function readResult( } } +function buildFailureOf( + result: Extract, +): BuildFailure { + return result.blame === 'customer' + ? { + blame: 'build', + projects: result.projects ?? 'unreported', + reason: result.reason, + } + : { blame: 'other', reason: result.reason } +} + +function cliFailed(reason: string): ManifestFactsRun { + process.exitCode = 1 + logger.fail(reason) + return { failure: { blame: 'other', reason }, status: 'failed' } +} + function minimumCoanaVersion( - offline: boolean, + context: SocketFactsContext, buildTime: RootBuildTime | undefined, ): string { return [ SOCKET_FACTS_MIN_COANA_VERSION, - ...(offline ? [OFFLINE_SOCKET_FACTS_MIN_COANA_VERSION] : []), + ...(context.disableDependencyDownloads + ? [OFFLINE_SOCKET_FACTS_MIN_COANA_VERSION] + : []), ...(buildTime?.timeout.source === 'flag' ? [BUILD_TIMEOUT_MIN_COANA_VERSION] : []), + ...(context.skipFailedBuilds ? [SKIP_FAILED_BUILDS_MIN_COANA_VERSION] : []), ].reduce((a, b) => (semver.gt(b, a) ? b : a)) } @@ -289,7 +345,7 @@ async function runGenerateSocketFacts( started = performance.now() }, coanaVersion: context.coanaVersion, - minimumVersion: minimumCoanaVersion(offline, buildTime), + minimumVersion: minimumCoanaVersion(context, buildTime), // Redirect Coana's logs to stderr to keep the command's stdout // machine-readable. stdio: ['inherit', 2, 'inherit'], @@ -525,7 +581,7 @@ async function runSocketFactsRequest( context: SocketFactsContext, staged: boolean, buildTime: RootBuildTime | undefined, -): Promise { +): Promise { const { workDir } = context const { message, result } = await runGenerateSocketFacts( request, @@ -538,24 +594,23 @@ async function runSocketFactsRequest( buildTime, ) - if (!result || result.status === 'failed') { + if (!result) { + return cliFailed( + `Could not generate Socket facts for ${build}${message ? `: ${message}` : '.'}`, + ) + } + if (result.status === 'failed') { + // Coana logged the reason. process.exitCode = 1 - if (!result) { - logger.fail( - `Could not generate Socket facts for ${build}${message ? `: ${message}` : '.'}`, - ) - } - return null + return { failure: buildFailureOf(result), status: 'failed' } } if (result.status === 'empty') { - return undefined + return { status: 'empty' } } if (coanaReadsFacts(context) && !result.sidecarEntry) { - process.exitCode = 1 - logger.fail( + return cliFailed( `Coana returned no sidecar entry for \`${result.targetPath}\`, which reachability analysis and socket fix need. This is a Coana bug; please report it to Socket.`, ) - return null } const facts: RunManifestFactsResult = { factsPath: result.factsPath, @@ -566,30 +621,27 @@ async function runSocketFactsRequest( if (!staged) { await keepFacts(workDir, facts) } - return facts + return { facts, status: 'generated' } } -export async function runManifestFacts({ +// runManifestFacts, with why a failed run failed. +export async function generateManifestFacts({ context = {}, staged = false, ...options }: SocketFactsRunOptions & { staged?: boolean | undefined -}): Promise { +}): Promise { const { cwd, ecosystem, entryFile } = options if (ecosystem === 'sbt' && !looksLikeSbtBuild(cwd)) { - process.exitCode = 1 - logger.fail( + return cliFailed( `No sbt build found at \`${cwd}\` (expected a build.sbt file or a project directory).`, ) - return null } const request = toSocketFactsRequest(options, context) if (!request.ok) { - process.exitCode = 1 - logger.fail(`${request.message}: ${request.cause}`) - return null + return cliFailed(`${request.message}: ${request.cause}`) } return await runSocketFactsRequest( request.data, @@ -600,6 +652,17 @@ export async function runManifestFacts({ ) } +export async function runManifestFacts( + options: SocketFactsRunOptions & { staged?: boolean | undefined }, +): Promise { + const run = await generateManifestFacts(options) + return run.status === 'generated' + ? run.facts + : run.status === 'empty' + ? undefined + : null +} + // For reachability the targets are compiled, as Bazel makes their jars only // when it builds them. export async function runBazelFacts({ @@ -621,7 +684,7 @@ export async function runBazelFacts({ return null } const dir = path.resolve(root) - const result = await runSocketFactsRequest( + const run = await runSocketFactsRequest( socketFactsRequest( { bin, @@ -643,14 +706,14 @@ export async function runBazelFacts({ false, undefined, ) - if (result === undefined) { + if (run.status === 'empty') { process.exitCode = 1 logger.fail( `Coana found no projects or dependencies in the Bazel targets ${targets.join(' ')}.`, ) return null } - return result + return run.status === 'generated' ? run.facts : null } // What `--socket-facts-sidecar` reads for the kept build roots. diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index dad2b802c..25ce8b5a7 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -10,6 +10,8 @@ vi.mock('../../utils/coana/release.mts', () => ({ })) import { + SKIP_FAILED_BUILDS_MIN_COANA_VERSION, + generateManifestFacts, keepFacts, listBuildProjects, listDotnetSolutionMembers, @@ -371,6 +373,43 @@ describe('runManifestFacts', () => { ).toBeNull() expect(spawnCoana).not.toHaveBeenCalled() }) + + it.for([ + { + name: 'the build, with the projects its tool read', + result: { + blame: 'customer', + projects: [{ ...mavenProject(cwd, '.'), modules: 'unknown' }], + reason: 'Non-resolvable import POM', + }, + failure: { + blame: 'build', + projects: [{ ...mavenProject(cwd, '.'), modules: 'unknown' }], + reason: 'Non-resolvable import POM', + }, + }, + { + name: 'the build, on a Coana that reports none of it', + result: { blame: 'customer', reason: 'Non-resolvable import POM' }, + failure: { + blame: 'build', + projects: 'unreported', + reason: 'Non-resolvable import POM', + }, + }, + { + name: 'Coana', + result: { blame: 'coana', reason: 'crashed' }, + failure: { blame: 'other', reason: 'crashed' }, + }, + ])('blames a failure Coana blames on $name', async ({ failure, result }) => { + coanaAnswers({ ...result, status: 'failed' }, false) + expect(await generateManifestFacts({ ...baseArgs, cwd })).toEqual({ + failure, + status: 'failed', + }) + expect(process.exitCode).toBe(1) + }) }) describe('keepFacts', () => { @@ -518,11 +557,26 @@ describe('listBuildProjects', () => { }) }) - it.for([true, false])( - 'lists and generates offline on Coana 15.15.8 only when its context disables downloads (%s)', - async disableDependencyDownloads => { - const context = { disableDependencyDownloads } - const minimumVersion = disableDependencyDownloads ? '15.15.8' : '15.15.4' + it.for([ + { name: 'online', context: {}, minimumVersion: '15.15.4' }, + { + name: 'offline', + context: { disableDependencyDownloads: true }, + minimumVersion: '15.15.8', + }, + { + name: 'past failed builds', + context: { skipFailedBuilds: true }, + minimumVersion: SKIP_FAILED_BUILDS_MIN_COANA_VERSION, + }, + { + name: 'offline and past failed builds', + context: { disableDependencyDownloads: true, skipFailedBuilds: true }, + minimumVersion: SKIP_FAILED_BUILDS_MIN_COANA_VERSION, + }, + ])( + 'lists and generates $name on the Coana that supports it', + async ({ context, minimumVersion }) => { coanaAnswers({ projects: [], status: 'listed' }) await listBuildProjects({ ...listArgs, context, cwd }) coanaAnswers({ @@ -534,7 +588,7 @@ describe('listBuildProjects', () => { await runManifestFacts({ ...baseArgs, context, cwd, staged: true }) for (const { args } of calls) { expect(args.includes('--disable-dependency-downloads')).toBe( - disableDependencyDownloads, + !!context.disableDependencyDownloads, ) } for (const { 2: options } of vi.mocked(spawnCoana).mock.calls) { diff --git a/src/commands/scan/cmd-scan-create.test.mts b/src/commands/scan/cmd-scan-create.test.mts index 63bbd03f0..1c42c3428 100644 --- a/src/commands/scan/cmd-scan-create.test.mts +++ b/src/commands/scan/cmd-scan-create.test.mts @@ -217,6 +217,7 @@ describe('socket scan create', async () => { --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. + --dynamic-sbom-inference-skip-failed-builds With --dynamic-sbom-inference: leave out a build root that fails to generate Socket facts, and the build roots it holds back, instead of aborting; the scan reads their manifest files as it does without --dynamic-sbom-inference. Other build roots, including builds of their own beneath it, are still built. --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.test.mts b/src/commands/scan/cmd-scan-reach.test.mts index 80f98a2dc..1c05c170d 100644 --- a/src/commands/scan/cmd-scan-reach.test.mts +++ b/src/commands/scan/cmd-scan-reach.test.mts @@ -43,6 +43,7 @@ describe('socket scan reach', async () => { --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. + --dynamic-sbom-inference-skip-failed-builds With --dynamic-sbom-inference: leave out a build root that fails to generate Socket facts, and the build roots it holds back, instead of aborting; the scan reads their manifest files as it does without --dynamic-sbom-inference. Other build roots, including builds of their own beneath it, are still built. --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/reachability-flags.mts b/src/commands/scan/reachability-flags.mts index a36ef677c..b1e1636d7 100644 --- a/src/commands/scan/reachability-flags.mts +++ b/src/commands/scan/reachability-flags.mts @@ -104,6 +104,11 @@ export const dynamicSbomInferenceFlags: MeowFlags = { 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.", }, + dynamicSbomInferenceSkipFailedBuilds: { + type: 'boolean', + description: + 'With --dynamic-sbom-inference: leave out a build root that fails to generate Socket facts, and the build roots it holds back, instead of aborting; the scan reads their manifest files as it does without --dynamic-sbom-inference. Other build roots, including builds of their own beneath it, are still built.', + }, } export type DynamicSbomInference = { @@ -112,6 +117,8 @@ export type DynamicSbomInference = { // Unset leaves it to each build's socket.json. ignoreUnresolved: boolean | undefined purlTypes: FactsOnlyTypes + // Goes on past a build root whose build fails. + skipFailedBuilds: boolean } export function parseDynamicSbomInferenceFlags(flags: { @@ -137,6 +144,7 @@ export function parseDynamicSbomInferenceFlags(flags: { | boolean | undefined, purlTypes: isFactsOnlyTypes(selected) ? selected : FACTS_PURL_TYPES, + skipFailedBuilds: !!flags['dynamicSbomInferenceSkipFailedBuilds'], } } diff --git a/src/commands/scan/reachability-flags.test.mts b/src/commands/scan/reachability-flags.test.mts index fbbc867ea..56ff75d13 100644 --- a/src/commands/scan/reachability-flags.test.mts +++ b/src/commands/scan/reachability-flags.test.mts @@ -13,6 +13,7 @@ const DEFAULTS = { buildTimeout: { flag: DSI_FLAG, seconds: 3600, source: 'default' }, ignoreUnresolved: undefined, purlTypes: ['maven', 'nuget'], + skipFailedBuilds: false, } const EXPECTED_FORMAT = @@ -58,6 +59,14 @@ describe('parseDynamicSbomInferenceFlags', () => { }, expected: { ...DEFAULTS, ignoreUnresolved: false }, }, + { + name: 'skipping failed builds', + flags: { + dynamicSbomInference: true, + dynamicSbomInferenceSkipFailedBuilds: true, + }, + expected: { ...DEFAULTS, skipFailedBuilds: true }, + }, { name: 'a build timeout', flags: { @@ -100,6 +109,12 @@ describe('parseDynamicSbomInferenceFlags', () => { error: '--dynamic-sbom-inference-ignore-unresolved requires --dynamic-sbom-inference', }, + { + name: 'skipping failed builds without --dynamic-sbom-inference', + flags: { dynamicSbomInferenceSkipFailedBuilds: true }, + error: + '--dynamic-sbom-inference-skip-failed-builds requires --dynamic-sbom-inference', + }, { name: 'a build timeout without --dynamic-sbom-inference', flags: { dynamicSbomInferenceBuildTimeout: '0' }, diff --git a/src/commands/scan/run-dynamic-sbom-inference.mts b/src/commands/scan/run-dynamic-sbom-inference.mts index 47b892850..e782333cd 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.mts @@ -1,6 +1,6 @@ import path from 'node:path' -import { joinOr } from '../../utils/arrays.mts' +import { joinAnd, joinOr } from '../../utils/arrays.mts' import { isFactsOnlyTypes } from '../../utils/coana.mts' import { InputError } from '../../utils/errors.mts' import { realpathOrResolved } from '../../utils/fs.mts' @@ -44,12 +44,16 @@ function checkFactsForCoana( hasFacts: boolean, ): void { const hasDisabled = outcomes.some(o => o.status === 'skippedDisabled') + const hasFailed = outcomes.some(o => o.status === 'failed') // Coana (15.14.1) refuses a facts-only reachability run without any facts. if (forReachability && !hasFacts) { throw new InputError( [ 'No build root produced Socket facts, which reachability analysis with --dynamic-sbom-inference needs.', '', + ...(hasFailed + ? ['- Fix the build roots that failed (see the errors above).'] + : []), ...(hasDisabled ? [ `- Re-enable the builds that socket.json skips (\`${DSI_SETUP_COMMAND}\` walks you through it).`, @@ -60,9 +64,15 @@ function checkFactsForCoana( ].join('\n'), ) } - if (hasDisabled) { + const leftOut = [ + ...(hasDisabled ? ['the build roots socket.json skips'] : []), + ...(hasFailed + ? ['the build roots that failed, with those they held back'] + : []), + ] + if (leftOut.length) { logger.warn( - 'The analysis leaves out the build roots socket.json skips: with --dynamic-sbom-inference, it takes their dependencies only from Socket facts.', + `The analysis leaves out ${joinAnd(leftOut)}: with --dynamic-sbom-inference, it takes their dependencies only from Socket facts.`, ) } } @@ -78,6 +88,7 @@ export async function runDynamicSbomInference({ hints, ignoreUnresolved, purlTypes, + skipFailedBuilds, }: DynamicSbomInference & { context: SocketFactsContext cwd: string @@ -86,7 +97,7 @@ export async function runDynamicSbomInference({ }): Promise { const outcomes = await generateRecursiveManifests({ buildTimeout, - context, + context: { ...context, skipFailedBuilds }, cwd, excludePaths, hints, @@ -111,13 +122,18 @@ export async function runDynamicSbomInference({ } // Fail loud rather than silently proceed with a partial multi-root result: // matches handleManifestDynamicSbomInference's own check. - if (outcomes.some(o => o.status === 'failed')) { + if (outcomes.some(o => o.status === 'failed' && !o.skipped)) { throw new InputError( [ 'One or more independent build roots failed to generate Socket facts; aborting (see the errors above).', '', `- To fix a build's settings or skip it, run \`${DSI_SETUP_COMMAND}\`.`, `- The settings are documented at ${DSI_SETTINGS_DOCS_URL}.`, + ...(skipFailedBuilds + ? [] + : [ + '- To leave out a build root whose build fails and go on with the others, add --dynamic-sbom-inference-skip-failed-builds.', + ]), ].join('\n'), ) } diff --git a/src/commands/scan/run-dynamic-sbom-inference.test.mts b/src/commands/scan/run-dynamic-sbom-inference.test.mts index f54c13a8c..04f808809 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.test.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.test.mts @@ -10,6 +10,7 @@ import { } from './run-dynamic-sbom-inference.mts' import { makeDynamicSbomInference } from '../../../test/reachability-options.mts' +import type { DynamicSbomInference } from './reachability-flags.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' const { mockGenerateRecursiveManifests, mockInfo, mockWarn } = vi.hoisted( @@ -45,16 +46,12 @@ function workDirFor(purpose: Purpose) { type Purpose = 'fix' | 'reachability' | 'upload' -function run( - purpose: Purpose, - purlTypes: FactsOnlyTypes = ['maven', 'nuget'], - ignoreUnresolved?: boolean | undefined, -) { +function run(purpose: Purpose, overrides?: Partial) { return runDynamicSbomInference({ context: { ...context, workDir: workDirFor(purpose) }, cwd: '/repo', excludePaths: ['vendor/**'], - ...makeDynamicSbomInference({ ignoreUnresolved, purlTypes }), + ...makeDynamicSbomInference(overrides), }) } @@ -70,11 +67,12 @@ describe('runDynamicSbomInference', () => { await run(purpose) + const { skipFailedBuilds, ...inference } = makeDynamicSbomInference() expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith({ - context: { ...context, workDir: workDirFor(purpose) }, + context: { ...context, skipFailedBuilds, workDir: workDirFor(purpose) }, cwd: '/repo', excludePaths: ['vendor/**'], - ...makeDynamicSbomInference(), + ...inference, verbose: false, }) }, @@ -85,7 +83,7 @@ describe('runDynamicSbomInference', () => { async ignoreUnresolved => { mockGenerateRecursiveManifests.mockResolvedValueOnce([generated]) - await run('upload', undefined, ignoreUnresolved) + await run('upload', { ignoreUnresolved }) expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith( expect.objectContaining({ ignoreUnresolved }), @@ -129,7 +127,7 @@ describe('runDynamicSbomInference', () => { async ({ message, purlTypes }) => { mockGenerateRecursiveManifests.mockResolvedValueOnce([]) - expect(await run('reachability', purlTypes)).toEqual({ + expect(await run('reachability', purlTypes && { purlTypes })).toEqual({ discardedFactsPaths: [], factsOnlyTypes: undefined, factsPaths: [], @@ -143,13 +141,33 @@ describe('runDynamicSbomInference', () => { name: string outcomes: object[] purlTypes?: FactsOnlyTypes + skipFailedBuilds?: boolean }>([ { - name: 'a discovered build root failed to generate facts', + name: 'a build root failed, naming the option to go on past it', outcomes: [ generated, - { dir: '/repo/b', ecosystem: 'maven', status: 'failed' }, + { + dir: '/repo/b', + ecosystem: 'maven', + skipped: false, + status: 'failed', + }, ], + error: /--dynamic-sbom-inference-skip-failed-builds/, + }, + { + name: 'a build root failed that the run did not go on past', + outcomes: [ + generated, + { + dir: '/repo/b', + ecosystem: 'maven', + skipped: false, + status: 'failed', + }, + ], + skipFailedBuilds: true, error: /one or more independent build roots failed/i, }, { @@ -160,17 +178,33 @@ describe('runDynamicSbomInference', () => { ], error: /Re-enable the builds that socket.json skips/, }, + { + name: 'every build root failed and was left out, for reachability', + outcomes: [ + { dir: '/repo/a', ecosystem: 'maven', skipped: true, status: 'failed' }, + ], + skipFailedBuilds: true, + error: /Fix the build roots that failed/, + }, { name: 'the selected ecosystems produced no facts for reachability', outcomes: [{ dir: '/repo/a', ecosystem: 'dotnet', status: 'empty' }], purlTypes: ['nuget'], error: /select other ecosystems with --dynamic-sbom-inference-ecosystems/, }, - ])('throws when $name', async ({ error, outcomes, purlTypes }) => { - mockGenerateRecursiveManifests.mockResolvedValueOnce(outcomes) + ])( + 'throws when $name', + async ({ error, outcomes, purlTypes, skipFailedBuilds }) => { + mockGenerateRecursiveManifests.mockResolvedValueOnce(outcomes) - await expect(run('reachability', purlTypes)).rejects.toThrow(error) - }) + await expect( + run('reachability', { + ...(purlTypes && { purlTypes }), + ...(skipFailedBuilds && { skipFailedBuilds }), + }), + ).rejects.toThrow(error) + }, + ) it.for([ { @@ -194,17 +228,31 @@ describe('runDynamicSbomInference', () => { }, ) - it('warns that build roots socket.json skips are left out', async () => { + it.for([ + { + name: 'build roots socket.json skips', + outcome: { status: 'skippedDisabled' }, + warning: /leaves out the build roots socket.json skips:/, + }, + { + name: 'build roots that failed', + outcome: { skipped: true, status: 'failed' }, + warning: + /leaves out the build roots that failed, with those they held back:/, + }, + ])('warns that $name are left out', async ({ outcome, warning }) => { mockGenerateRecursiveManifests.mockResolvedValueOnce([ generated, - { dir: '/repo/b', ecosystem: 'maven', status: 'skippedDisabled' }, + { dir: '/repo/b', ecosystem: 'maven', ...outcome }, ]) - await run('reachability') + const result = await run('reachability', { + purlTypes: ['maven'], + skipFailedBuilds: true, + }) - expect(mockWarn).toHaveBeenCalledWith( - expect.stringMatching(/leaves out the build roots socket.json skips/), - ) + expect(result.factsPaths).toEqual([generated.factsPath]) + expect(mockWarn).toHaveBeenCalledWith(expect.stringMatching(warning)) }) }) diff --git a/test/reachability-options.mts b/test/reachability-options.mts index e1ed1b256..48b5d2f17 100644 --- a/test/reachability-options.mts +++ b/test/reachability-options.mts @@ -17,6 +17,7 @@ export function makeDynamicSbomInference( buildTimeout: undefined, ignoreUnresolved: undefined, purlTypes: ['maven', 'nuget'], + skipFailedBuilds: false, ...overrides, } } diff --git a/test/snapshots/termless/cli.native.socket-help-fix.svg b/test/snapshots/termless/cli.native.socket-help-fix.svg index 032b17736..1e1c9e621 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) @@ -67,103 +67,109 @@ (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. Default + --dynamic-sbom-inference-skip-failed-builds With --dynamic-sbom-inference: leave out a build root that fails to generate Socket facts, -s to all ecosystems. +and the build roots it holds back, instead of aborting; the scan reads their manifest files as it does without --dynamic-sbom-inference. Oth - --exclude-paths Skip matching paths from the scan entirely: manifests under these paths are not uploaded, and fixes are not applied +er build roots, including builds of their own beneath it, are still built. -to workspaces under them. Patterns are anchored micromatch globs matched relative to the target directory (CWD); `data/postgres/pgdata` matc + --ecosystems Limit fix analysis to specific ecosystems. Accepts space- or comma-separated values and is case-insensitive. Default -hes that exact path, `**/pgdata` matches at any depth. Use this to skip directories the current user cannot read so they do not abort manife +s to all ecosystems. -st collection. Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. + --exclude-paths Skip matching paths from the scan entirely: manifests under these paths are not uploaded, and fixes are not applied - --fix-version Override the version of @coana-tech/cli used for fix analysis. Default: 15.15.9. +to workspaces under them. Patterns are anchored micromatch globs matched relative to the target directory (CWD); `data/postgres/pgdata` matc - --id Provide a list of vulnerability identifiers to compute fixes for: +hes that exact path, `**/pgdata` matches at any depth. Use this to skip directories the current user cannot read so they do not abort manife - - GHSA IDs (​https://docs.github.com/en/code-security/security-advisories/working-with-global-security-advisories +st collection. Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. --from-the-github-advisory-database/about-the-github-advisory-database#about-ghsa-ids​) (e.g., GHSA-xxxx-xxxx-xxxx) + --fix-version Override the version of @coana-tech/cli used for fix analysis. Default: 15.15.9. - - CVE IDs (​https://cve.mitre.org/cve/identifiers/​) (e.g., CVE-2026-1234) - automatically converted to GHSA + --id Provide a list of vulnerability identifiers to compute fixes for: - - PURLs (​https://github.com/package-url/purl-spec​) (e.g., pkg:npm/package@1.0.0) - automatically converted to GH + - GHSA IDs (​https://docs.github.com/en/code-security/security-advisories/working-with-global-security-advisories -SA +-from-the-github-advisory-database/about-the-github-advisory-database#about-ghsa-ids​) (e.g., GHSA-xxxx-xxxx-xxxx) - Can be provided as comma separated values or as multiple flags. Cannot be used with --all. + - CVE IDs (​https://cve.mitre.org/cve/identifiers/​) (e.g., CVE-2026-1234) - automatically converted to GHSA - --include Include workspaces matching these glob patterns. Can be provided as comma separated values or as multiple flags + - PURLs (​https://github.com/package-url/purl-spec​) (e.g., pkg:npm/package@1.0.0) - automatically converted to GH - --json Output as JSON +SA - --markdown Output as Markdown + Can be provided as comma separated values or as multiple flags. Cannot be used with --all. - --minimum-release-age Set a minimum age requirement for suggested upgrade versions (e.g., 1h, 2d, 3w). A higher age requirement reduces + --include Include workspaces matching these glob patterns. Can be provided as comma separated values or as multiple flags - the risk of upgrading to malicious versions. For example, setting the value to 1 week (1w) gives ecosystem maintainers one week to remove p + --json Output as JSON -otentially malicious versions. + --markdown Output as Markdown - --no-apply-fixes Compute fixes only, do not apply them. Logs what upgrades would be applied. If combined with --output-file, the outp + --minimum-release-age Set a minimum age requirement for suggested upgrade versions (e.g., 1h, 2d, 3w). A higher age requirement reduces -ut file will contain the upgrades that would be applied. + the risk of upgrading to malicious versions. For example, setting the value to 1 week (1w) gives ecosystem maintainers one week to remove p - --no-major-updates Do not suggest or apply fixes that require major version updates of direct or transitive dependencies +otentially malicious versions. - --output-file Path to store upgrades as a JSON file at this path. + --no-apply-fixes Compute fixes only, do not apply them. Logs what upgrades would be applied. If combined with --output-file, the outp - --package-managers Limit fix analysis to specific package managers within an ecosystem (e.g. NPM, PNPM, YARN, MAVEN, POETRY). Accepts s +ut file will contain the upgrades that would be applied. -pace- or comma-separated values and is case-insensitive. When combined with --ecosystems, an artifact must satisfy both filters. + --no-major-updates Do not suggest or apply fixes that require major version updates of direct or transitive dependencies - --pr-limit Maximum number of pull requests to create in CI mode (default 10). Has no effect in local mode. + --output-file Path to store upgrades as a JSON file at this path. - --range-style Define how dependency version ranges are updated in package.json (default 'preserve'). + --package-managers Limit fix analysis to specific package managers within an ecosystem (e.g. NPM, PNPM, YARN, MAVEN, POETRY). Accepts s - Available styles: +pace- or comma-separated values and is case-insensitive. When combined with --ecosystems, an artifact must satisfy both filters. - * pin - Use the exact version (e.g. 1.2.3) + --pr-limit Maximum number of pull requests to create in CI mode (default 10). Has no effect in local mode. - * preserve - Retain the existing version range style as-is + --range-style Define how dependency version ranges are updated in package.json (default 'preserve'). - --show-affected-direct-dependencies List the direct dependencies responsible for introducing transitive vulnerabilities and list the up + Available styles: -dates required to resolve the vulnerabilities + * pin - Use the exact version (e.g. 1.2.3) - --silence Silence all output except the final result + * preserve - Retain the existing version range style as-is - + --show-affected-direct-dependencies List the direct dependencies responsible for introducing transitive vulnerabilities and list the up - Environment Variables (for CI/PR mode) +dates required to resolve the vulnerabilities - CI Set to enable CI mode + --silence Silence all output except the final result - SOCKET_CLI_GITHUB_TOKEN GitHub token for PR creation (or GITHUB_TOKEN) + - SOCKET_CLI_GIT_USER_NAME Git username for commits + Environment Variables (for CI/PR mode) - SOCKET_CLI_GIT_USER_EMAIL Git email for commits + CI Set to enable CI mode - + SOCKET_CLI_GITHUB_TOKEN GitHub token for PR creation (or GITHUB_TOKEN) - Examples + SOCKET_CLI_GIT_USER_NAME Git username for commits - $ socket fix + SOCKET_CLI_GIT_USER_EMAIL Git email for commits - $ socket fix --id CVE-2021-23337 + - $ socket fix ./path/to/project --range-style pin + Examples - + $ socket fix - + $ socket fix --id CVE-2021-23337 - + $ socket fix ./path/to/project --range-style pin - \ No newline at end of file + + + + + + + \ No newline at end of file diff --git a/test/snapshots/termless/cli.native.socket-help-manifest-dynamic-sbom-inference.svg b/test/snapshots/termless/cli.native.socket-help-manifest-dynamic-sbom-inference.svg index 191408ebb..078589ced 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) @@ -57,25 +57,29 @@ --markdown Output as Markdown - --verbose Print debug messages + --skip-failed-builds Leave out a build root that fails to generate Socket facts, and the build roots it holds back, instead of failing - +the run. Other build roots, including builds of their own beneath it, are still built. - 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 ade56a574..c915898bb 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) @@ -65,207 +65,213 @@ (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) + --dynamic-sbom-inference-skip-failed-builds With --dynamic-sbom-inference: leave out a build root that fails to generate Socket facts, -full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman +and the build roots it holds back, instead of aborting; the scan reads their manifest files as it does without --dynamic-sbom-inference. Oth -d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. +er build roots, including builds of their own beneath it, are still built. - Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj + --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) -ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr +full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman -oject. A build module or project outside the scan root cannot be excluded. +d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. - --interactive Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, + Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj - defaulting them to cancel/no. +ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr - --json Output as JSON +oject. A build module or project outside the scan root cannot be excluded. - --markdown Output as Markdown + --interactive Allow for interactive elements, asking for input. Use --no-interactive to prevent any input questions, - --org Force override the organization slug, overrides the default org from config + defaulting them to cancel/no. - --pull-request Pull request number + --json Output as JSON - --reach Run full application reachability analysis + --markdown Output as Markdown - --read-only Similar to --dry-run except it can read from remote, stops before it would create an actual report + --org Force override the organization slug, overrides the default org from config - --repo Repository name + --pull-request Pull request number - --report Wait for the scan creation to complete, then basically run `socket scan report` on it + --reach Run full application reachability analysis - --report-level Which policy level alerts should be reported (default 'error') + --read-only Similar to --dry-run except it can read from remote, stops before it would create an actual report - --set-as-alerts-page When true and if this is the "default branch" then this Scan will be the one reflected on your alerts page. See he + --repo Repository name -lp for details. Defaults to true. + --report Wait for the scan creation to complete, then basically run `socket scan report` on it - --tmp Set the visibility (true/false) of the scan in your dashboard. + --report-level Which policy level alerts should be reported (default 'error') - --uv-members Scan each TARGET directory as a uv project, using the versions pinned in its uv.lock or its workspace root uv.lock. + --set-as-alerts-page When true and if this is the "default branch" then this Scan will be the one reflected on your alerts page. See he -Uploads a CycloneDX dependency graph per TARGET in place of manifest discovery, including all extras and dependency groups. Requires uv on P +lp for details. Defaults to true. -ATH; standalone builds use SOCKET_CLI_UV_PATH. + --tmp Set the visibility (true/false) of the scan in your dashboard. - --workspace The workspace in the Socket Organization that the repository is in to associate with the full scan. + --uv-members Scan each TARGET directory as a uv project, using the versions pinned in its uv.lock or its workspace root uv.lock. - +Uploads a CycloneDX dependency graph per TARGET in place of manifest discovery, including all extras and dependency groups. Requires uv on P - Reachability Options (when --reach is used) +ATH; standalone builds use SOCKET_CLI_UV_PATH. - --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul + --workspace The workspace in the Socket Organization that the repository is in to associate with the full scan. -tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau + -lts to all advisories. + Reachability Options (when --reach is used) - --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. + --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul -512MB, 8GB). The default is 8GB. +tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau - --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 +lts to all advisories. -m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. + --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. - --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th +512MB, 8GB). The default is 8GB. -at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. + --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 - --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back +m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. -to precomputed reachability results. By default, the CLI halts on analysis errors. + --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th - --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi +at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. -lity results. By default, the CLI halts on installation errors. + --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back - --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version +to precomputed reachability results. By default, the CLI halts on analysis errors. - catalog / pre-generated SBOM). By default, the CLI halts. + --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi - --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa +lity results. By default, the CLI halts on installation errors. -ult, the CLI halts. + --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version - --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. + catalog / pre-generated SBOM). By default, the CLI halts. - --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. + --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa - --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. +ult, the CLI halts. - --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director + --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. -y or module cache). Missing dependencies count as installation failures. + --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. - --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. + --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. - --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp + --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director -orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. +y or module cache). Missing dependencies count as installation failures. - --reach-fallback-to-regular-scan If reachability analysis fails, continue with a regular SCA scan (without reachability results) instea + --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. -d of halting. By default, the CLI halts on reachability errors. + --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp - --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d +orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. -eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a + --reach-fallback-to-regular-scan If reachability analysis fails, continue with a regular SCA scan (without reachability results) instea -n SBOM carrying stale reachability results. +d of halting. By default, the CLI halts on reachability errors. - --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous + --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d - runs to speed up the analysis. +eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a - --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your +n SBOM carrying stale reachability results. -project. + --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous - --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. + runs to speed up the analysis. - + --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your - Uploads the specified dependency manifest files for Go, Gradle, JavaScript, +project. - Kotlin, Python, and Scala. Files like "package.json" and "requirements.txt". + --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. - If any folder is specified, the ones found in there recursively are uploaded. - + + Uploads the specified dependency manifest files for Go, Gradle, JavaScript, - Details on TARGET: + Kotlin, Python, and Scala. Files like "package.json" and "requirements.txt". - + If any folder is specified, the ones found in there recursively are uploaded. - - Defaults to the current dir (cwd) if none given + - - Multiple targets can be specified + Details on TARGET: - - If a target is a file, only that file is checked + - - If it is a dir, the dir is scanned for any supported manifest files + - Defaults to the current dir (cwd) if none given - - Dirs MUST be within the current dir (cwd), you can use --cwd to change it + - Multiple targets can be specified - - Supports globbing such as "**/package.json", "**/requirements.txt", etc. + - If a target is a file, only that file is checked - - Ignores any file specified in your project's ".gitignore" + - If it is a dir, the dir is scanned for any supported manifest files - - Also a sensible set of default ignores from the "ignore-by-default" module + - Dirs MUST be within the current dir (cwd), you can use --cwd to change it - + - Supports globbing such as "**/package.json", "**/requirements.txt", etc. - The --repo and --branch flags tell Socket to associate this Scan with that + - Ignores any file specified in your project's ".gitignore" - repo/branch. The names will show up on your dashboard on the Socket website. + - Also a sensible set of default ignores from the "ignore-by-default" module - Note: for a first run you probably want to set --default-branch to indicate + The --repo and --branch flags tell Socket to associate this Scan with that - the default branch name, like "main" or "master". + repo/branch. The names will show up on your dashboard on the Socket website. - The "alerts page" (​https://socket.dev/dashboard/org/YOURORG/alerts​) will show + Note: for a first run you probably want to set --default-branch to indicate - the results from the last scan designated as the "pending head" on the branch + the default branch name, like "main" or "master". - configured on Socket to be the "default branch". When creating a scan the + - --set-as-alerts-page flag will default to true to update this. You can prevent + The "alerts page" (​https://socket.dev/dashboard/org/YOURORG/alerts​) will show - this by using --no-set-as-alerts-page. This flag is ignored for any branch that + the results from the last scan designated as the "pending head" on the branch - is not designated as the "default branch". It is disabled when using --tmp. + configured on Socket to be the "default branch". When creating a scan the - + --set-as-alerts-page flag will default to true to update this. You can prevent - You can use `socket scan setup` to configure certain repo flag defaults. + this by using --no-set-as-alerts-page. This flag is ignored for any branch that - + is not designated as the "default branch". It is disabled when using --tmp. - Examples + - $ socket scan create + You can use `socket scan setup` to configure certain repo flag defaults. - $ socket scan create ./proj --json + - $ socket scan create --repo=test-repo --branch=main ./package.json + Examples - $ socket scan create --uv-members ./packages/api ./packages/worker + $ socket scan create - + $ socket scan create ./proj --json - + $ socket scan create --repo=test-repo --branch=main ./package.json - + $ socket scan create --uv-members ./packages/api ./packages/worker - \ No newline at end of file + + + + + + + \ No newline at end of file diff --git a/test/snapshots/termless/cli.native.socket-help-scan-reach.svg b/test/snapshots/termless/cli.native.socket-help-scan-reach.svg index f5e6f9ead..050b84ca0 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) @@ -61,123 +61,129 @@ (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) + --dynamic-sbom-inference-skip-failed-builds With --dynamic-sbom-inference: leave out a build root that fails to generate Socket facts, -full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman +and the build roots it holds back, instead of aborting; the scan reads their manifest files as it does without --dynamic-sbom-inference. Oth -d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. +er build roots, including builds of their own beneath it, are still built. - Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj + --exclude-paths List of glob patterns to exclude from the scan, including SCA/SBOM manifest discovery and (when --reach is enabled) -ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr +full application reachability analysis. Patterns are anchored micromatch globs matched relative to the Socket scan root, which is the comman -oject. A build module or project outside the scan root cannot be excluded. +d working directory (`--cwd` if set), not the reachability target: `tests` matches only `<cwd>/tests`; use `**/tests` to match at any depth. - --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul + Negation patterns (`!path`) are not supported. Accepts a comma-separated value or multiple flags. An excluded JVM build module or .NET proj -tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau +ect is not analysed as a project of its own, but where a project that is not excluded depends on it, its code is analysed as part of that pr -lts to all advisories. +oject. A build module or project outside the scan root cannot be excluded. - --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. + --reach-advisories List of advisories to run reachability analysis for, as GHSA or CVE IDs, either as a comma separated value or as mul -512MB, 8GB). The default is 8GB. +tiple flags. CVE IDs are converted to GHSA IDs through the GitHub API. Vulnerabilities from other advisories get unknown reachability. Defau - --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 +lts to all advisories. -m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. + --reach-analysis-memory-limit The maximum memory for the reachability analysis as a whole number optionally followed by MB or GB (e.g. - --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th +512MB, 8GB). The default is 8GB. -at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. + --reach-analysis-timeout Set the timeout for the reachability analysis as a whole number optionally followed by s, m or h (e.g. 90s, 10 - --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back +m, 1h). Defaults to 10m. Split analysis runs may cause the total scan time to exceed this timeout significantly. -to precomputed reachability results. By default, the CLI halts on analysis errors. + --reach-concurrency Set the maximum number of concurrent reachability analysis runs. It is recommended to choose a concurrency level th - --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi +at ensures each analysis run has at least the --reach-analysis-memory-limit amount of memory available. -lity results. By default, the CLI halts on installation errors. + --reach-continue-on-analysis-errors Continue reachability analysis when errors occur (timeouts, OOM, parse errors, etc.), falling back - --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version +to precomputed reachability results. By default, the CLI halts on analysis errors. - catalog / pre-generated SBOM). By default, the CLI halts. + --reach-continue-on-install-errors Continue reachability analysis when package installation fails, falling back to precomputed reachabi - --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa +lity results. By default, the CLI halts on installation errors. -ult, the CLI halts. + --reach-continue-on-missing-lock-files Continue reachability analysis when a Gradle or SBT project is missing its lock file (or version - --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. + catalog / pre-generated SBOM). By default, the CLI halts. - --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. + --reach-continue-on-no-source-files Continue reachability analysis when a workspace contains no source files for its ecosystem. By defa - --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. +ult, the CLI halts. - --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director + --reach-debug Enable debug mode for reachability analysis. Provides verbose logging from the reachability CLI. -y or module cache). Missing dependencies count as installation failures. + --reach-detailed-analysis-log-file A log file with detailed analysis logs is written to root of each analyzed workspace. - --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. + --reach-disable-analytics Disable reachability analytics sharing with Socket. Also disables caching-based optimizations. - --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp + --reach-disable-dependency-downloads Only analyze dependencies that are already installed (e.g. in the project's .venv, vendor director -orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. +y or module cache). Missing dependencies count as installation failures. - --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d + --reach-disable-external-tool-checks Disable external tool checks during reachability analysis. -eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a + --reach-ecosystems List of ecosystems to conduct reachability analysis on, as either a comma separated value or as multiple flags. Supp -n SBOM carrying stale reachability results. +orted: cargo, composer, gem, golang, maven, npm, nuget, pypi. Defaults to all supported ecosystems. - --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous + --reach-retain-facts-file Keep the `.socket.facts.json` reachability report that the analysis writes to the scan directory instead of d - runs to speed up the analysis. +eleting it after a successful scan. Delete it once inspected: later reachability scans ignore it, but a scan without --reach uploads it as a - --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your +n SBOM carrying stale reachability results. -project. + --reach-skip-cache Skip caching-based optimizations. By default, the reachability analysis will use cached configurations from previous - --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. + runs to speed up the analysis. - + --reach-use-only-pregenerated-sboms When using this option, the scan is created based only on pre-generated CDX and SPDX files in your - Runs the Socket reachability analysis without creating a scan in Socket. +project. - The output is written to .socket.facts.json in the current working directory + --reach-version Override the version of @coana-tech/cli used for reachability analysis. Default: 15.15.9. - unless the --output flag is specified. - + + Runs the Socket reachability analysis without creating a scan in Socket. - Note: Manifest files are uploaded to Socket's backend services because the + The output is written to .socket.facts.json in the current working directory - reachability analysis requires creating a Software Bill of Materials (SBOM) + unless the --output flag is specified. - from these files before the analysis can run. - + + Note: Manifest files are uploaded to Socket's backend services because the - Examples + reachability analysis requires creating a Software Bill of Materials (SBOM) - $ socket scan reach + from these files before the analysis can run. - $ socket scan reach ./proj + - $ socket scan reach ./proj --reach-ecosystems npm,pypi + Examples - $ socket scan reach ./monorepo --dynamic-sbom-inference + $ socket scan reach - $ socket scan reach --output custom-report.json + $ socket scan reach ./proj - $ socket scan reach ./proj --output ./reports/analysis.json + $ socket scan reach ./proj --reach-ecosystems npm,pypi - + $ socket scan reach ./monorepo --dynamic-sbom-inference - + $ socket scan reach --output custom-report.json - + $ socket scan reach ./proj --output ./reports/analysis.json - \ No newline at end of file + + + + + + + \ No newline at end of file