Skip to content
Merged
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,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.
- `socket manifest setup --dynamic-sbom-inference` asks for the reachability settings, so there is no need to edit `socket.json` by hand.

### Changed
- Updated the Coana CLI to v `15.15.5`.
Expand Down
102 changes: 56 additions & 46 deletions src/commands/manifest/build-root-config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ const DOTNET_RUNTIME_VERSION = new RegExp(
`^${NUMBER}\\.${NUMBER}(?:\\.${NUMBER}(?:-${PRERELEASE_IDENTIFIER}(?:\\.${PRERELEASE_IDENTIFIER})*)?)?$`,
)

const DOTNET_RUNTIME_VERSION_FORMAT =
export 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 = {
Expand Down Expand Up @@ -87,11 +87,12 @@ const REACHABILITY_FIELDS = {
}
>

type ReachabilityProblem = {
export type ReachabilityProblem = {
// Undefined when the value is not an object.
field: string | undefined
// Why the tool rejects it, and the remedy.
problem: string
value: unknown
}

function checkReachability(
Expand Down Expand Up @@ -156,50 +157,6 @@ 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,
Expand Down Expand Up @@ -397,6 +354,59 @@ export function displayPath(file: string): string {
return rel.startsWith('..') || path.isAbsolute(rel) ? file : rel || '.'
}

// The valid fields of `value`, nulls kept, and the problem with each other one.
export 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.`,
value,
},
],
settings,
}
}
const fields = reachabilityFieldsOf(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.`,
value: fieldValue,
})
} 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.`,
value: fieldValue,
})
}
}
return { problems, settings }
}

export function reachabilityFieldsOf(
tool: BuildTool,
): readonly ReachabilityField[] {
return REACHABILITY_FIELDS_BY_TOOL[tool]
}

export function socketJsonPath(dir: string): string {
return displayPath(path.join(dir, SOCKET_JSON))
}
202 changes: 199 additions & 3 deletions src/commands/manifest/setup-manifest-config.mts
Original file line number Diff line number Diff line change
@@ -1,18 +1,63 @@
import fs from 'node:fs'
import path from 'node:path'
import { isDeepStrictEqual } from 'node:util'

import {
DOTNET_RUNTIME_VERSION_FORMAT,
parseReachability,
reachabilityFieldsOf,
} from './build-root-config.mts'
import { detectManifestActions } from './detect-manifest-actions.mts'
import { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts'
import { debugDir } from '../../utils/debug.mts'
import { logger } from '../../utils/logger.mts'
import { isRecord } from '../../utils/objects.mts'
import { input, select } from '../../utils/prompts.mts'
import {
readSocketJsonSync,
writeSocketJson,
} from '../../utils/socket-json.mts'

import type { ReachabilityProblem } from './build-root-config.mts'
import type { BuildTool } from './scripts/build-tool.mts'
import type { CResult } from '../../types.mts'
import type { ManifestDefaults } from '../../utils/socket-json.mts'
import type {
ManifestDefaults,
ReachabilityDefaults,
ReachabilityField,
} from '../../utils/socket-json.mts'

type ValuePrompts = {
ask: (current: string) => Promise<string | undefined>
change: string
keep: string
set: string
unset: string
}

const REACHABILITY_VALUE_PROMPTS = {
__proto__: null,
javaHome: {
ask: current =>
askForJavaHome(current, 'What JDK should reachability analysis use?'),
change: 'Use a different Java for reachability analysis?',
keep: 'as the JDK for reachability analysis',
set: 'Set the JDK reachability analysis uses',
unset: 'Leave the JDK for reachability analysis unset',
},
runtimeVersion: {
ask: askForRuntimeVersion,
change:
'Start the reachability analysis of a framework-dependent .NET build on a given runtime?',
keep: 'as the .NET runtime',
set: 'Set the runtime the analysis starts on',
unset:
"Let the analysis take the runtime the build's dotnet rolls forward to",
},
} satisfies { __proto__: null } & Record<
Exclude<ReachabilityField, 'build'>,
ValuePrompts
>

// Whether the prompt was canceled. A blank answer clears a value set before
// with null rather than deleting the key, so it doesn't silently start
Expand Down Expand Up @@ -624,16 +669,35 @@ async function askForBin(
})
}

async function askForJavaHome(defaultName = ''): Promise<string | undefined> {
async function askForJavaHome(
defaultName = '',
question = 'What JDK should this build tool use? Leave blank to use the JDK already on PATH/JAVA_HOME.',
): Promise<string | undefined> {
return await input({
message:
'What JDK should this build tool use? Leave blank to use the JDK already on PATH/JAVA_HOME. Supports $VAR/${VAR}.' +
`${question} Supports $VAR/\${VAR}.` +
(defaultName ? ' (Backspace to leave default)' : ''),
default: defaultName,
required: false,
})
}

async function askForRuntimeVersion(
current: string,
): Promise<string | undefined> {
return await input({
message:
`Which .NET runtime? Enter ${DOTNET_RUNTIME_VERSION_FORMAT}.` +
(current ? ' (Backspace to leave default)' : ''),
default: current,
required: false,
validate: (value: string) =>
!value ||
!parseReachability('dotnet', { runtimeVersion: value }).problems.length ||
`Enter ${DOTNET_RUNTIME_VERSION_FORMAT}.`,
})
}

async function askForVerboseFlag(
current: boolean | undefined,
): Promise<string | undefined> {
Expand Down Expand Up @@ -715,6 +779,138 @@ async function askForIgnoreUnresolvedFlag(
})
}

// The wizard replaces invalid values with the answers, except one the build
// inherits: that one needs fixing in the socket.json that sets it.
function warnInvalidReachability(
tool: BuildTool,
problems: readonly ReachabilityProblem[],
inherited: unknown,
): void {
for (const { field, value } of problems) {
let parent: unknown
let setting: string
let reason: string
if (field === undefined) {
parent = inherited
setting = 'reachability'
reason = 'is not an object'
} else {
parent = isRecord(inherited) ? inherited[field] : undefined
setting = `reachability.${field}`
reason = `is not a value ${tool} builds take`
}
const shown = `\`${setting}\` (${JSON.stringify(value)})`
logger.warn(
isDeepStrictEqual(value, parent)
? `${shown}, which this build inherits, ${reason}; fix it in the socket.json that sets it, or reachability scans fail.`
: `Replacing ${shown}, which ${reason}.`,
)
}
}

// Answering no keeps the value in effect; "none" overrides an inherited
// "compile".
export async function setupReachability(
tool: BuildTool,
config: { reachability?: ReachabilityDefaults | undefined },
inheritedReachability: unknown,
): Promise<CResult<{ canceled: boolean }>> {
const { problems, settings: reachability } = parseReachability(
tool,
config.reachability,
)
warnInvalidReachability(tool, problems, inheritedReachability)
const { settings: inherited } = parseReachability(tool, inheritedReachability)
// An invalid value of its own leaves the inherited one in effect.
const effective = { ...inherited, ...reachability }

const wantsBuild = await select({
message:
'Build project before reachability analysis? Note: A failed build fails the scan.',
choices: [
{
name: 'no',
value: false,
description: 'Analyze the project without building it',
},
{
name: 'yes',
value: true,
description: 'Compile the project before reachability analysis',
},
],
default: effective.build === 'compile',
})
if (wantsBuild === undefined) {
return canceledByUser()
}
if (wantsBuild) {
reachability.build = 'compile'
} else if (inherited.build === 'compile') {
reachability.build = 'none'
} else {
delete reachability.build
}

// Whether the prompt was canceled.
const askValue = async (
field: Exclude<ReachabilityField, 'build'>,
): Promise<boolean> => {
const prompts = REACHABILITY_VALUE_PROMPTS[field]
const current = effective[field]
const wantsValue = await select({
message: prompts.change,
choices: [
{
name: 'no',
value: false,
description: current
? `Keep ${current} ${prompts.keep}${current === inherited[field] ? ', which it inherits' : ''}`
: prompts.unset,
},
{
name: 'yes',
value: true,
description: prompts.set,
},
],
default: !!current,
})
if (wantsValue === undefined) {
return true
}
if (!wantsValue) {
return false
}
const answer = await prompts.ask(current || '')
if (answer === undefined) {
return true
}
if (answer) {
reachability[field] = answer
} else if (inherited[field]) {
// Clears the value rather than inheriting it again.
reachability[field] = null
} else {
delete reachability[field]
}
return false
}
for (const field of reachabilityFieldsOf(tool)) {
// eslint-disable-next-line no-await-in-loop
if (field !== 'build' && (await askValue(field))) {
return canceledByUser()
}
}

if (Object.keys(reachability).length) {
config.reachability = reachability
} else {
delete config.reachability
}
return notCanceled()
}

// Prompts for the facts-only options every facts generator shares: the config
// include/exclude filters and --ignore-unresolved. Mutates `config` in place.
async function setupFactsOptions(
Expand Down
Loading
Loading