diff --git a/CHANGELOG.md b/CHANGELOG.md index d6253860b..e2a321023 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added - Socket facts for a self-contained .NET build include its runtime packs. +- Tune reachability per build tool in `socket.json` for `--dynamic-sbom-inference` scans: `reachability.build` compiles the project before the analysis, `reachability.javaHome` (Maven, Gradle, sbt) sets the JDK the analysis assumes, and `reachability.runtimeVersion` (.NET) sets the runtime it starts on. ### Changed - Updated the Coana CLI to v `15.15.4`. diff --git a/docs/dynamic-sbom-inference-settings.md b/docs/dynamic-sbom-inference-settings.md index 4d28e1441..dabf04cb4 100644 --- a/docs/dynamic-sbom-inference-settings.md +++ b/docs/dynamic-sbom-inference-settings.md @@ -77,6 +77,13 @@ Under `defaults.manifest.maven`, `.gradle`, `.sbt` or `.dotnet`, or inside a | `disabled` | `true` skips builds; see below. | | `facts` | Gradle and sbt: `false` skips the build. | | `verbose` | `true` streams the build tool's output. | +| `reachability.build` | `"compile"` builds the project before the analysis, and a failed build fails the scan; `"none"` or unset analyses it unbuilt. | +| `reachability.javaHome` | Maven, Gradle and sbt: the JDK the analysis takes the program to run on, passed to Coana as written. | +| `reachability.runtimeVersion` | .NET: the runtime a framework-dependent build's analysis starts on. `major.minor` takes its latest installed patch; `major.minor.patch[-prerelease]` takes exactly that runtime. | + +Only reachability scans read the `reachability` fields, each cascading on its +own, and only for the build tools they run. An invalid value or a field the +build tool does not take fails the scan. ## Skipping builds diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index 795275d89..fb7a84257 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -8,20 +8,27 @@ import { buildRootPath, } from './scripts/build-tool.mts' import { SOCKET_JSON } from '../../constants.mts' +import { joinAnd, joinOr } from '../../utils/arrays.mts' import { InputError } from '../../utils/errors.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' import { logger } from '../../utils/logger.mts' import { isRecord } from '../../utils/objects.mts' import { + REACHABILITY_BUILDS, + REACHABILITY_FIELDS_BY_TOOL, + mergeBuildToolDefaults, mergeSocketJsonChain, readSocketJsonChain, } from '../../utils/socket-json.mts' +import { isNonEmptyString } from '../../utils/strings.mts' import type { BuildRoot } from './discover-manifest-roots.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { + ReachabilityDefaults, + ReachabilityField, + ReachabilitySettings, SocketJson, - SocketJsonBuildEntry, SocketJsonInDir, } from '../../utils/socket-json.mts' @@ -37,10 +44,93 @@ export type ResolvedBuildRootSettings = { disabledBy: DisabledBy | undefined // The key of the build's own `defaults.manifest.builds` entry. entryKey: string | undefined + // Checks reachability settings in every socket.json that supplies them. + // An invalid setting raises an InputError naming the file and field. + reachability: () => ReachabilitySettings | undefined // The cascaded settings, the build's own entries applied last. sockJson: SocketJson } +// major.minor, or major.minor.patch[-prerelease] as `RuntimeFrameworkVersion` +// takes a .NET runtime, written as SemVer 2.0.0 items 2 and 9 say. +const NUMBER = '(?:0|[1-9][0-9]*)' +const PRERELEASE_IDENTIFIER = `(?:${NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)` +const DOTNET_RUNTIME_VERSION = new RegExp( + `^${NUMBER}\\.${NUMBER}(?:\\.${NUMBER}(?:-${PRERELEASE_IDENTIFIER}(?:\\.${PRERELEASE_IDENTIFIER})*)?)?$`, +) + +const DOTNET_RUNTIME_VERSION_FORMAT = + 'major.minor, such as "8.0", for its latest installed patch, or major.minor.patch[-prerelease], such as "8.0.11", for exactly that runtime' + +const REACHABILITY_FIELDS = { + __proto__: null, + build: { + expected: joinOr(REACHABILITY_BUILDS.map(b => `"${b}"`)), + takes: (value: unknown) => + (REACHABILITY_BUILDS as readonly unknown[]).includes(value), + }, + javaHome: { + expected: 'a JDK path', + takes: isNonEmptyString, + }, + runtimeVersion: { + expected: `a .NET runtime version: ${DOTNET_RUNTIME_VERSION_FORMAT}`, + takes: (value: unknown) => + typeof value === 'string' && DOTNET_RUNTIME_VERSION.test(value), + }, +} satisfies { __proto__: null } & Record< + ReachabilityField, + { + // What a valid value is, as "set it to …" names it. + expected: string + takes: (value: unknown) => boolean + } +> + +type ReachabilityProblem = { + // Undefined when the value is not an object. + field: string | undefined + // Why the tool rejects it, and the remedy. + problem: string +} + +function checkReachability( + tool: BuildTool, + value: unknown, + setting: string, + socketJson: string, +): void { + const { + problems: { 0: first }, + } = parseReachability(tool, value) + if (first) { + const key = + first.field === undefined ? setting : `${setting}.${first.field}` + throw new InputError(`\`${key}\` in ${socketJson} ${first.problem}`) + } +} + +// An invalid setting raises an InputError naming the file. Checks each +// socket.json once per `checked`. +function checkChainReachability( + tool: BuildTool, + chain: readonly SocketJsonInDir[], + checked: Set, +): void { + for (const { dir, sockJson } of chain) { + const key = `${tool}\0${dir}` + if (!checked.has(key)) { + checkReachability( + tool, + sockJson.defaults?.manifest?.[tool]?.reachability, + `defaults.manifest.${tool}.reachability`, + socketJsonPath(dir), + ) + checked.add(key) + } + } +} + // Gradle and sbt name a build by any build file of its directory. function namesBuildFile(key: string): boolean { return BUILD_TOOLS.some(tool => { @@ -66,6 +156,62 @@ function ownEntryKeys( ) } +// The valid fields of `value`, nulls kept, and the problem with each other one. +function parseReachability( + tool: BuildTool, + value: unknown, +): { problems: ReachabilityProblem[]; settings: ReachabilityDefaults } { + const settings: ReachabilityDefaults = {} + if (value === undefined) { + return { problems: [], settings } + } + if (!isRecord(value)) { + return { + problems: [ + { + field: undefined, + problem: `is ${JSON.stringify(value)}; set it to an object, or remove it.`, + }, + ], + settings, + } + } + const fields = REACHABILITY_FIELDS_BY_TOOL[tool] + const problems: ReachabilityProblem[] = [] + for (const { 0: name, 1: fieldValue } of Object.entries(value)) { + const field = fields.find(f => f === name) + if (!field) { + problems.push({ + field: name, + problem: `is not a reachability setting of ${tool} builds, which take ${joinAnd(fields)}; remove it.`, + }) + } else if ( + fieldValue === null || + REACHABILITY_FIELDS[field].takes(fieldValue) + ) { + Object.assign(settings, { [field]: fieldValue }) + } else { + problems.push({ + field, + problem: `is ${JSON.stringify(fieldValue)}; set it to ${REACHABILITY_FIELDS[field].expected}, to null to clear an inherited value, or remove it.`, + }) + } + } + return { problems, settings } +} + +// Without the fields a socket.json cleared with null. +function settingsInEffect( + settings: ReachabilityDefaults, +): ReachabilitySettings | undefined { + const entries = Object.entries(settings).filter( + ({ 1: setting }) => setting !== null && setting !== undefined, + ) + return entries.length + ? (Object.fromEntries(entries) as ReachabilitySettings) + : undefined +} + function validateBuilds({ dir, sockJson }: SocketJsonInDir): void { const builds: unknown = sockJson.defaults?.manifest?.builds if (builds === undefined) { @@ -136,6 +282,7 @@ export function createBuildRootSettingsResolver( const chains = new Map() const resolved = new Map() const validated = new Set() + const reachabilityChecked = new Set() const chainFor = (dir: string): SocketJsonInDir[] => { let chain = chains.get(dir) @@ -159,7 +306,7 @@ export function createBuildRootSettingsResolver( ): ResolvedBuildRootSettings => { const chain = chainFor(root.dir) const merged = mergeSocketJsonChain(chain) - const section: Record = { + let section: Record = { ...merged.defaults?.manifest?.[tool], } let sectionDisabledBy: DisabledBy | undefined @@ -180,9 +327,9 @@ export function createBuildRootSettingsResolver( ? ownEntryKeys(tool, root.dir, builds, root.entryFile)[0] : undefined let entryDisabledBy: DisabledBy | undefined - if (entryKey) { - const entry = builds![entryKey] as SocketJsonBuildEntry - Object.assign(section, entry) + const entry = entryKey ? builds?.[entryKey] : undefined + if (entry) { + section = mergeBuildToolDefaults(section, entry) if (entry.disabled !== undefined) { entryDisabledBy = { dir: root.dir, key: entryKey } } @@ -195,9 +342,29 @@ export function createBuildRootSettingsResolver( disabledBy = directorySkip ? sectionDisabledBy : entryDisabledBy } + let cached: { settings: ReachabilitySettings | undefined } | undefined return { disabledBy, entryKey, + reachability: () => { + if (!cached) { + checkChainReachability(tool, chain, reachabilityChecked) + if (entryKey && entry) { + checkReachability( + tool, + entry['reachability'], + `${buildsSetting(entryKey)}.reachability`, + socketJsonPath(root.dir), + ) + } + cached = { + settings: settingsInEffect( + parseReachability(tool, section['reachability']).settings, + ), + } + } + return cached.settings + }, sockJson: { ...merged, defaults: { diff --git a/src/commands/manifest/build-root-config.test.mts b/src/commands/manifest/build-root-config.test.mts index 998026f51..4a6f2fb6c 100644 --- a/src/commands/manifest/build-root-config.test.mts +++ b/src/commands/manifest/build-root-config.test.mts @@ -10,6 +10,7 @@ import { displayPath, } from './build-root-config.mts' import { InputError } from '../../utils/errors.mts' +import { escapeRegExp } from '../../utils/escape-regexp.mts' import { logger } from '../../utils/logger.mts' describe('createBuildRootSettingsResolver', () => { @@ -35,6 +36,10 @@ describe('createBuildRootSettingsResolver', () => { dir: path.join(scanRoot, dir), entryFile, }) + const dotnet = (dir: string) => ({ + dir: path.join(scanRoot, dir), + entryFile: 'App.sln', + }) beforeEach(async () => { scanRoot = await fs.realpath( @@ -240,4 +245,175 @@ describe('createBuildRootSettingsResolver', () => { createBuildRootSettingsResolver()('maven', maven('legacy')).disabledBy, ).toEqual({ dir: path.join(scanRoot, 'legacy') }) }) + + describe('reachability', () => { + it('cascades each field on its own, the build entry last, and drops cleared ones', async () => { + await write('.', { + maven: { reachability: { build: 'compile', javaHome: '$JDK17' } }, + }) + await write( + 'svc', + { + maven: { reachability: { javaHome: null } }, + builds: { 'pom.xml': { reachability: { javaHome: '$JDK21' } } }, + }, + ['pom.xml', 'svc-alt.pom.xml'], + ) + const resolve = createBuildRootSettingsResolver() + + expect(resolve('maven', maven('svc')).reachability()).toEqual({ + build: 'compile', + javaHome: '$JDK21', + }) + expect( + resolve('maven', maven('svc', 'svc-alt.pom.xml')).reachability(), + ).toEqual({ build: 'compile' }) + }) + + it.for([ + { + name: 'no socket.json sets any', + settings: {}, + files: undefined, + }, + { + name: 'a socket.json clears every field with null', + settings: { maven: { reachability: { build: null } } }, + files: undefined, + }, + { + name: "the build's own entry clears what its directory sets", + settings: { + maven: { reachability: { build: 'compile' } }, + builds: { 'pom.xml': { reachability: { build: null } } }, + }, + files: ['pom.xml'], + }, + ])('is undefined when $name', async ({ files, settings }) => { + await write('.', settings, files) + + expect( + createBuildRootSettingsResolver()('maven', maven('.')).reachability(), + ).toBeUndefined() + }) + + it.for([ + { runtimeVersion: '8.0', valid: true }, + { runtimeVersion: '10.0.1', valid: true }, + { runtimeVersion: '9.0.0-rc.2.24473.5', valid: true }, + { runtimeVersion: '8', valid: false }, + { runtimeVersion: 'net8.0', valid: false }, + { runtimeVersion: '08.0', valid: false }, + { runtimeVersion: '8.0.1.2', valid: false }, + { runtimeVersion: '8.0-rc.1', valid: false }, + { runtimeVersion: '8.0.1+build', valid: false }, + ])( + 'takes the .NET runtime version $runtimeVersion: $valid', + async ({ runtimeVersion, valid }) => { + await write('.', { dotnet: { reachability: { runtimeVersion } } }) + const resolved = createBuildRootSettingsResolver()( + 'dotnet', + dotnet('.'), + ) + + if (valid) { + expect(resolved.reachability()).toEqual({ runtimeVersion }) + } else { + expect(() => resolved.reachability()).toThrow( + /reachability\.runtimeVersion` in .*socket\.json is .*; set it to a \.NET runtime version/, + ) + } + }, + ) + + it.for([ + { + name: 'a field of another tool', + tool: 'maven', + reachability: { runtimeVersion: '8.0' }, + reason: 'is not a reachability setting of maven builds', + }, + { + name: 'a JVM field on dotnet', + tool: 'dotnet', + reachability: { javaHome: '/jdk' }, + reason: 'is not a reachability setting of dotnet builds', + }, + { + name: 'a misspelt field', + tool: 'gradle', + reachability: { java_home: '/jdk' }, + reason: 'is not a reachability setting of gradle builds', + }, + { + name: 'an unknown build', + tool: 'sbt', + reachability: { build: 'test' }, + reason: 'set it to "compile" or "none"', + }, + { + name: 'a JDK that is no string', + tool: 'gradle', + reachability: { javaHome: 17 }, + reason: 'set it to a JDK path', + }, + { + name: 'an empty JDK', + tool: 'maven', + reachability: { javaHome: '' }, + reason: 'set it to a JDK path', + }, + { + name: 'a section that is no object', + tool: 'maven', + reachability: 'compile', + reason: 'set it to an object', + }, + ] as const)( + 'rejects $name, naming the socket.json that sets it', + async ({ reachability, reason, tool }) => { + await write('.', { [tool]: { reachability: {} } }) + await write('nested', { [tool]: { reachability } }) + const root = { dir: path.join(scanRoot, 'nested') } + + expect(() => + createBuildRootSettingsResolver()(tool, root).reachability(), + ).toThrow( + expect.objectContaining({ + constructor: InputError, + message: expect.stringMatching( + new RegExp( + `^\`defaults\\.manifest\\.${tool}\\.reachability.*\\bnested.socket\\.json.*${escapeRegExp(reason)}`, + ), + ), + }), + ) + }, + ) + + it("rejects an invalid setting in a build's own entry, naming the entry", async () => { + await write( + '.', + { builds: { 'pom.xml': { reachability: { runtimeVersion: '8.0' } } } }, + ['pom.xml'], + ) + + expect(() => + createBuildRootSettingsResolver()('maven', maven('.')).reachability(), + ).toThrow( + /^`defaults\.manifest\.builds\["pom\.xml"\]\.reachability\.runtimeVersion` in /, + ) + }) + + it("resolves a build's other settings whatever its reachability holds", async () => { + await write('.', { + maven: { mavenOpts: '-B', reachability: { build: 'always' } }, + }) + + expect( + createBuildRootSettingsResolver()('maven', maven('.')).sockJson.defaults + ?.manifest?.maven?.mavenOpts, + ).toBe('-B') + }) + }) }) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index a7f5b5e2d..a39020928 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -26,6 +26,7 @@ import { DSI_SETUP_COMMAND, createSocketFactsWorkDir, keepFacts, + readsReachabilitySettings, runManifestFacts, } from './run-manifest-facts.mts' import { @@ -53,7 +54,10 @@ import type { } from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' -import type { SocketJson } from '../../utils/socket-json.mts' +import type { + ReachabilitySettings, + SocketJson, +} from '../../utils/socket-json.mts' function normalizePathKey(value: string): string { return value.replaceAll('\\', '/') @@ -83,6 +87,8 @@ export type EcosystemBuildConfig = { ignoreUnresolved: boolean includeConfigs: string javaHome: string | undefined + // Set only by the dynamic SBOM inference walk, on a reachability scan. + reachability?: ReachabilitySettings | undefined // Set when this build root should be skipped entirely (never invoked). skipReason: string | undefined verbose: boolean @@ -94,18 +100,34 @@ export type EcosystemBuildConfig = { // so it skips too. function getSkipReason( ecosystem: BuildTool, - disabled: boolean | undefined, - facts?: boolean | undefined, + section: + | { disabled?: boolean | undefined; facts?: boolean | undefined } + | undefined, ): string | undefined { - if (disabled) { + if (section?.disabled) { return `defaults.manifest.${ecosystem}.disabled is true` } - if (facts === false) { + if ( + (ecosystem === 'gradle' || ecosystem === 'sbt') && + section?.facts === false + ) { return `defaults.manifest.${ecosystem}.facts is false (pom mode)` } return undefined } +// What a build reads: its settings on a reachability scan, unless skipped. +function reachabilityOf( + context: SocketFactsContext, + tool: BuildTool, + settings: ResolvedBuildRootSettings, +): ReachabilitySettings | undefined { + return readsReachabilitySettings(context) && + !getSkipReason(tool, settings.sockJson.defaults?.manifest?.[tool]) + ? settings.reachability() + : undefined +} + type Candidate = { index: number // A build of its own (see hasRootMarker): covered only by the builds that @@ -191,6 +213,7 @@ export function socketFactsRunOptions( ignoreUnresolved: config.ignoreUnresolved, includeConfigs: config.includeConfigs, javaHome: config.javaHome, + reachability: config.reachability, verbose: config.verbose, } } @@ -251,12 +274,13 @@ async function walkTool( ctx.resolveSettings(ecosystem, root) const configs = new Map() const configFor = (candidate: Candidate): EcosystemBuildConfig => { - const { entryKey, sockJson } = resolvedFor(candidate) + const resolved = resolvedFor(candidate) const { dir } = candidate.root // Builds sharing a directory and its settings resolve them once. - return getOrInsert(configs, `${dir}\0${entryKey ?? ''}`, () => - resolveEcosystemConfig(ecosystem, dir, sockJson), - ) + return getOrInsert(configs, `${dir}\0${resolved.entryKey ?? ''}`, () => ({ + ...resolveEcosystemConfig(ecosystem, dir, resolved.sockJson), + reachability: reachabilityOf(ctx.context, ecosystem, resolved), + })) } // 'load' when the build's own entry skips it, 'skip' when a directory @@ -750,7 +774,7 @@ export async function generateRecursiveManifests({ // Invalid settings fail the scan before any build runs. for (const { 0: tool, 1: roots } of candidatesByTool) { for (const root of roots) { - resolveSettings(tool, root) + reachabilityOf(context, tool, resolveSettings(tool, root)) } } // A failure another build excuses leaves the exit code it set. @@ -808,7 +832,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: undefined, - skipReason: getSkipReason(ecosystem, config?.disabled), + skipReason: getSkipReason(ecosystem, config), verbose: Boolean(config?.verbose), } } @@ -822,7 +846,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), + skipReason: getSkipReason(ecosystem, config), verbose: Boolean(config?.verbose), } } @@ -836,7 +860,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), + skipReason: getSkipReason(ecosystem, config), verbose: Boolean(config?.verbose), } } @@ -849,7 +873,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - skipReason: getSkipReason(ecosystem, config?.disabled), + skipReason: getSkipReason(ecosystem, config), verbose: Boolean(config?.verbose), } } diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 50deeda51..407c38dab 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -138,6 +138,14 @@ function relOf(dir: string): string { return path.relative(monorepo, dir).replaceAll('\\', '/') } +function sentReachability() { + return Object.fromEntries( + vi + .mocked(runManifestFacts) + .mock.calls.map(({ 0: opts }) => [opts.ecosystem, opts.reachability]), + ) +} + describe('generateRecursiveManifests', () => { beforeEach(() => { vi.mocked(runManifestFacts).mockReset() @@ -758,6 +766,149 @@ describe('generateRecursiveManifests', () => { expect(javaHomeByCall.get('maven:reactor')).toBeUndefined() }) + describe('reachability settings', () => { + let outer = '' + beforeEach(async () => { + outer = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'dsi-reachability-')), + ) + for (const file of [ + 'dotnet/App.sln', + 'gradle/build.gradle', + 'maven/pom.xml', + 'sbt/build.sbt', + ]) { + // eslint-disable-next-line no-await-in-loop + await fs.mkdir(path.join(outer, path.dirname(file))) + // eslint-disable-next-line no-await-in-loop + await fs.writeFile(path.join(outer, file), '') + } + mockFacts(async ({ cwd }) => ({ + factsPath: path.join(cwd, '.socket.facts.json'), + projects: [], + })) + }) + afterEach(async () => { + await fs.rm(outer, { recursive: true, force: true }) + }) + + it("sends each root's cascaded settings on a reachability scan", async () => { + mockCascade(() => ({ + defaults: { + manifest: { + dotnet: { + reachability: { build: 'compile', runtimeVersion: '8.0' }, + }, + gradle: { + reachability: { build: 'compile', javaHome: '$GRADLE_JDK' }, + }, + maven: { reachability: { build: 'none' } }, + }, + }, + })) + + await generateRecursiveManifests({ + context: { workDir: newWorkDir() }, + cwd: outer, + verbose: false, + }) + + expect(sentReachability()).toStrictEqual({ + dotnet: { build: 'compile', runtimeVersion: '8.0' }, + gradle: { build: 'compile', javaHome: '$GRADLE_JDK' }, + maven: { build: 'none' }, + sbt: undefined, + }) + }) + + it('neither sends nor checks them without a reachability scan', async () => { + mockCascade(() => ({ + defaults: { + manifest: { maven: { reachability: { build: 'always' } } }, + }, + })) + + const outcomes = await generateRecursiveManifests({ + cwd: outer, + verbose: false, + }) + + expect(outcomes.every(o => o.status === 'generated')).toBe(true) + expect(Object.values(sentReachability())).toEqual([ + undefined, + undefined, + undefined, + undefined, + ]) + }) + + it('fails a reachability scan on an invalid setting of a tool it runs, before any build, not of one it does not', async () => { + mockCascade(() => ({ + defaults: { + manifest: { dotnet: { reachability: { runtimeVersion: 'net8.0' } } }, + }, + })) + await expect( + generateRecursiveManifests({ + context: { workDir: newWorkDir() }, + cwd: outer, + purlTypes: ['maven'], + verbose: false, + }), + ).resolves.toBeDefined() + + await expect( + generateRecursiveManifests({ + context: { workDir: newWorkDir() }, + cwd: outer, + purlTypes: ['nuget'], + verbose: false, + }), + ).rejects.toThrow(/reachability\.runtimeVersion` in .* is "net8\.0"/) + + // sbt builds after Gradle and Maven. + mockCascade(() => ({ + defaults: { manifest: { sbt: { reachability: { build: 'always' } } } }, + })) + vi.mocked(runManifestFacts).mockClear() + await expect( + generateRecursiveManifests({ + context: { workDir: newWorkDir() }, + cwd: outer, + purlTypes: ['maven'], + verbose: false, + }), + ).rejects.toThrow(/sbt\.reachability\.build` in .* is "always"/) + expect(runManifestFacts).not.toHaveBeenCalled() + }) + + it.for([ + { + name: 'socket.json disables', + manifest: { + sbt: { disabled: true, reachability: { build: 'always' } }, + }, + }, + { + name: 'generates pom files', + manifest: { + gradle: { facts: false, reachability: { build: 'always' } }, + }, + }, + ])('does not check the settings of a build $name', async ({ manifest }) => { + mockCascade(() => ({ defaults: { manifest } }) as SocketJson) + + await expect( + generateRecursiveManifests({ + context: { workDir: newWorkDir() }, + cwd: outer, + purlTypes: ['maven'], + verbose: false, + }), + ).resolves.toBeDefined() + }) + }) + it('resolves an explicit null override back to the no-restriction default, not a literal null', async () => { mockCascade(dir => dir === dualMarkerDir diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index 9e3f24952..78257258d 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -26,7 +26,8 @@ vi.mock('./run-manifest-facts.mts', async importOriginal => ({ vi.mock('./handle-manifest-conda.mts', () => ({ handleManifestConda: vi.fn(async () => undefined), })) -vi.mock('../../utils/socket-json.mts', () => ({ +vi.mock('../../utils/socket-json.mts', async importOriginal => ({ + ...(await importOriginal()), readOrDefaultSocketJson: vi.fn(() => ({})), })) @@ -409,6 +410,33 @@ describe('generateAutoManifest — JVM facts', () => { expect(callFor('maven')?.entryFile).toBeUndefined() }, ) + + it('neither sends nor checks the reachability settings, which only dynamic SBOM inference reads', async () => { + vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + defaults: { + manifest: { + dotnet: { reachability: { runtimeVersion: 'latest' } }, + maven: { reachability: { build: 'compile' } }, + }, + }, + } as SocketJson) + vi.mocked(convertDotnetToFacts).mockClear() + + await generateAutoManifest({ + context: { + workDir: { dir: '/w', entries: new Map(), purpose: 'reachability' }, + }, + cwd: '/tmp/repo', + detected: { ...baseDetected, dotnet: true, maven: true, count: 2 }, + outputKind: 'text', + verbose: false, + }) + + expect(callFor('maven')?.reachability).toBeUndefined() + expect( + vi.mocked(convertDotnetToFacts).mock.calls[0]?.[0].config, + ).not.toHaveProperty('reachability') + }) }) describe('generateAutoManifest — conda branch', () => { diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 17471f256..ebe935661 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -17,6 +17,7 @@ import { logger } from '../../utils/logger.mts' import type { BuildRoot } from './discover-manifest-roots.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { CResult } from '../../types.mts' +import type { ReachabilitySettings } from '../../utils/socket-json.mts' export type BuildOption = 'excludeConfigs' | 'ignoreUnresolved' | 'verbose' @@ -118,6 +119,7 @@ type SocketFactsRequest = { ignoreUnresolved: boolean includeConfigs?: string | undefined javaHome?: string | undefined + reachability?: ReachabilitySettings | undefined verbose: boolean } excludeBase: string @@ -155,6 +157,13 @@ export function coanaReadsFacts(context: SocketFactsContext): boolean { return purposeOf(context) !== 'upload' } +// Only a reachability scan reads the builds' socket.json reachability settings. +export function readsReachabilitySettings( + context: SocketFactsContext | undefined, +): boolean { + return context !== undefined && purposeOf(context) === 'reachability' +} + async function readResult( resultFile: string, ): Promise<{ error?: string | undefined; result: T | undefined }> { @@ -227,6 +236,7 @@ export type SocketFactsRequestOptions = { includeConfigs?: string | undefined // As written: Coana expands `$VAR` references itself. javaHome?: string | undefined + reachability?: ReachabilitySettings | undefined verbose?: boolean | undefined } @@ -251,6 +261,7 @@ function toSocketFactsRequest( ignoreUnresolved = false, includeConfigs, javaHome, + reachability, verbose = false, }: SocketFactsRequestOptions, context: SocketFactsContext, @@ -281,6 +292,7 @@ function toSocketFactsRequest( ignoreUnresolved, ...(includeConfigs ? { includeConfigs } : {}), ...(javaHome && ecosystem !== 'dotnet' ? { javaHome } : {}), + ...(reachability ? { reachability } : {}), verbose, }, excludeBase: path.resolve(excludeBase ?? cwd), diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 7c8d605b8..e712434ab 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -127,6 +127,24 @@ describe('runManifestFacts', () => { }) }) + it.for([ + { build: 'compile', javaHome: '${JAVA17_HOME}' }, + { build: 'none', runtimeVersion: '8.0.11' }, + ] as const)( + 'sends the reachability settings %j as given', + async reachability => { + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ ...baseArgs, cwd, reachability }) + expect(calls[0]!.request.config.reachability).toEqual(reachability) + }, + ) + + it('sends no reachability settings when none are set', async () => { + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ ...baseArgs, cwd }) + expect(calls[0]!.request.config).not.toHaveProperty('reachability') + }) + it("runs Coana in socket-cli's own cwd, so its logs show paths from there", async () => { coanaAnswers({ status: 'empty' }) await runManifestFacts({ ...baseArgs, cwd }) diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index 2e640f17e..6e46345fd 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -25,10 +25,55 @@ import { debugDir, debugFn } from './debug.mts' import { formatErrorWithDetail } from './errors.mts' import { findUp } from './fs.mts' import { logger } from './logger.mts' +import { isRecord } from './objects.mts' +import { BUILD_TOOLS } from '../commands/manifest/scripts/build-tool.mts' import { SOCKET_JSON, SOCKET_WEBSITE_URL } from '../constants.mts' +import type { BuildTool } from '../commands/manifest/scripts/build-tool.mts' import type { CResult } from '../types.mts' +export const REACHABILITY_BUILDS = ['compile', 'none'] as const + +// Controls whether reachability analysis builds the project first. +// Defaults to "none". +export type ReachabilityBuild = (typeof REACHABILITY_BUILDS)[number] + +// Only reachability scans read these settings. +type ReachabilityValues = { + build: ReachabilityBuild + // JDK the analysis takes the program to run on, as written. + javaHome: string + // The .NET runtime a framework-dependent build's analysis starts on: + // major.minor, or a full version as `RuntimeFrameworkVersion` takes one. + runtimeVersion: string +} + +export type ReachabilityField = keyof ReachabilityValues + +export const REACHABILITY_FIELDS_BY_TOOL = { + __proto__: null, + dotnet: ['build', 'runtimeVersion'], + gradle: ['build', 'javaHome'], + maven: ['build', 'javaHome'], + sbt: ['build', 'javaHome'], +} as const satisfies { __proto__: null } & Record< + BuildTool, + readonly ReachabilityField[] +> + +// A null field clears its inherited value. +export type ReachabilityDefaults = { + [F in (typeof REACHABILITY_FIELDS_BY_TOOL)[Tool][number]]?: + | ReachabilityValues[F] + | undefined + | null +} + +// The settings in effect for a build, which a reachability scan sends Coana. +export type ReachabilitySettings = { + [F in ReachabilityField]?: ReachabilityValues[F] | undefined +} + export interface SocketJson { ' _____ _ _ ': string '| __|___ ___| |_ ___| |_ ': string @@ -75,6 +120,7 @@ export interface SocketJson { excludeConfigs?: string | undefined | null includeConfigs?: string | undefined | null ignoreUnresolved?: boolean | undefined + reachability?: ReachabilityDefaults<'dotnet'> | undefined verbose?: boolean | undefined } gradle?: { @@ -93,6 +139,7 @@ export interface SocketJson { // JDK path; sets JAVA_HOME for this ecosystem's build tool. Supports // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null + reachability?: ReachabilityDefaults<'gradle'> | undefined verbose?: boolean | undefined } maven?: { @@ -108,6 +155,7 @@ export interface SocketJson { // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null mavenOpts?: string | undefined | null + reachability?: ReachabilityDefaults<'maven'> | undefined verbose?: boolean | undefined } sbt?: { @@ -126,6 +174,7 @@ export interface SocketJson { // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null outfile?: string | undefined | null + reachability?: ReachabilityDefaults<'sbt'> | undefined sbtOpts?: string | undefined | null stdout?: boolean | undefined verbose?: boolean | undefined @@ -186,7 +235,23 @@ export async function readOrDefaultSocketJsonUp( return getDefaultSocketJson() } -// Shallow-merges `defaults.manifest.` per ecosystem: fields set in +// A build tool's section merges field by field, and so does each of its +// object-valued fields (`reachability`). +export function mergeBuildToolDefaults>( + base: T | undefined, + override: T, +): T { + const merged: Record = { ...base, ...override } + for (const { 0: key, 1: value } of Object.entries(override)) { + const inherited = base?.[key] + if (isRecord(inherited) && isRecord(value)) { + merged[key] = { ...inherited, ...value } + } + } + return merged as T +} + +// Merges `defaults.manifest.` per ecosystem: fields set in // `override` win, others fall through to `base`. Only this section cascades; // everything else in `defaults` comes from `base` only. function mergeManifestDefaults( @@ -207,24 +272,16 @@ function mergeManifestDefaults( if (overrideManifest.conda) { mergedManifest.conda = { ...baseManifest?.conda, ...overrideManifest.conda } } - if (overrideManifest.dotnet) { - mergedManifest.dotnet = { - ...baseManifest?.dotnet, - ...overrideManifest.dotnet, + for (const tool of BUILD_TOOLS) { + if (overrideManifest[tool]) { + Object.assign(mergedManifest, { + [tool]: mergeBuildToolDefaults( + baseManifest?.[tool], + overrideManifest[tool], + ), + }) } } - if (overrideManifest.gradle) { - mergedManifest.gradle = { - ...baseManifest?.gradle, - ...overrideManifest.gradle, - } - } - if (overrideManifest.maven) { - mergedManifest.maven = { ...baseManifest?.maven, ...overrideManifest.maven } - } - if (overrideManifest.sbt) { - mergedManifest.sbt = { ...baseManifest?.sbt, ...overrideManifest.sbt } - } return { ...base, defaults: { ...base.defaults, manifest: mergedManifest }, diff --git a/src/utils/socket-json.test.mts b/src/utils/socket-json.test.mts index d0ed1c46b..75466061d 100644 --- a/src/utils/socket-json.test.mts +++ b/src/utils/socket-json.test.mts @@ -4,7 +4,11 @@ import path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mergeSocketJsonChain, readSocketJsonChain } from './socket-json.mts' +import { + mergeSocketJsonChain, + readOrDefaultSocketJson, + readSocketJsonChain, +} from './socket-json.mts' import type { SocketJson } from './socket-json.mts' @@ -134,4 +138,54 @@ describe('readSocketJsonChain and mergeSocketJsonChain', () => { excludeConfigs: null, }) }) + + it("cascades a build tool's reachability field by field", async () => { + await writeSocketJson(root, { + version: 1, + defaults: { + manifest: { + dotnet: { reachability: { build: 'compile', runtimeVersion: '8.0' } }, + maven: { reachability: { build: 'compile', javaHome: '/jdk-17' } }, + }, + }, + }) + const buildRoot = path.join(root, 'project') + await fs.mkdir(buildRoot, { recursive: true }) + await writeSocketJson(buildRoot, { + version: 1, + defaults: { + manifest: { + dotnet: { reachability: { runtimeVersion: null } }, + maven: { reachability: { build: 'none' } }, + }, + }, + }) + + const manifest = readSocketJsonCascade(buildRoot).defaults?.manifest + expect(manifest?.maven?.reachability).toEqual({ + build: 'none', + javaHome: '/jdk-17', + }) + expect(manifest?.dotnet?.reachability).toEqual({ + build: 'compile', + runtimeVersion: null, + }) + }) + + it('reads a socket.json whatever its reachability settings hold', async () => { + await writeSocketJson(root, { + version: 1, + defaults: { + manifest: { + dotnet: { reachability: { runtimeVersion: 'net8.0' } }, + maven: { bin: 'mvn', reachability: 'compile' }, + }, + }, + }) + + expect(mavenConfig(readOrDefaultSocketJson(root))?.bin).toBe('mvn') + expect(mavenConfig(readSocketJsonCascade(root))?.reachability).toBe( + 'compile', + ) + }) })