Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 12 additions & 3 deletions docs/dynamic-sbom-inference-settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<module>../core</module>`; 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.
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/commands/fix/cmd-fix.integration.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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: <coana-version>.
Expand Down
2 changes: 2 additions & 0 deletions src/commands/fix/generated-socket-facts.mts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export async function generateSocketFactsForFix({
findFactsPaths,
ignoreUnresolved,
purlTypes,
skipFailedBuilds,
tmpDir,
}: DynamicSbomInference & {
context: Omit<SocketFactsContext, 'workDir'>
Expand Down Expand Up @@ -89,6 +90,7 @@ export async function generateSocketFactsForFix({
hints: EXCLUDE_PATHS_HINTS,
ignoreUnresolved,
purlTypes,
skipFailedBuilds,
})
if (!inferred.factsOnlyTypes) {
return undefined
Expand Down
9 changes: 9 additions & 0 deletions src/commands/manifest/cmd-manifest-dynamic-sbom-inference.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -150,6 +158,7 @@ async function run(
excludePaths,
ignoreUnresolved,
outputKind,
skipFailedBuilds,
verbose,
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
148 changes: 119 additions & 29 deletions src/commands/manifest/generate-recursive-manifests.mts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { parseBuildToolOpts } from './parse-build-tool-opts.mts'
import {
DSI_SETUP_COMMAND,
createSocketFactsWorkDir,
generateManifestFacts,
keepFacts,
readsReachabilitySettings,
rootBuildTime,
Expand All @@ -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,
Expand All @@ -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
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -356,6 +376,20 @@ async function walkTool(
const runs = new Map<number, Run>()
const loads = new Map<number, Load>()
const failures: Candidate[] = []
const failed = new Map<number, Failed>()
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.
Expand Down Expand Up @@ -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 (;;) {
Expand All @@ -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' ||
Expand All @@ -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)
}
}

Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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.`,
)
}
}
Expand Down Expand Up @@ -676,17 +749,33 @@ function runOptions(
}
}

async function heldMembers(
projects: readonly FailedBuildProject[],
scanRoot: string,
): Promise<HeldBack> {
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<Run | undefined> {
): Promise<Run | { failure: BuildFailure }> {
// 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
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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
}

Expand Down
Loading
Loading