diff --git a/src/commands/manifest/bazel/bin-detect.mts b/src/commands/manifest/bazel/bin-detect.mts index 67292b5b83..c2e27145bc 100644 --- a/src/commands/manifest/bazel/bin-detect.mts +++ b/src/commands/manifest/bazel/bin-detect.mts @@ -18,7 +18,8 @@ import { InputError } from '../../../utils/errors.mts' * Resolve the bazel binary to invoke for `socket manifest bazel`. * * Resolution order: - * 1. If `explicit` is provided, return it iff it exists on disk; else throw. + * 1. SOCKET_CLI_BAZEL_PATH, else `explicit`: return it iff it exists on disk; + * else throw. * 2. Look up `bazelisk` on PATH (preferred — respects `.bazelversion`). * 3. Fall back to `bazel` on PATH. * 4. If neither is found, throw InputError with install instructions. @@ -27,12 +28,18 @@ export async function resolveBazelBinary( explicit: string | undefined, env: NodeJS.ProcessEnv, cwd: string, + // The option that names `explicit`; null for a command with none. + explicitFlag: string | null = '--bazel', ): Promise { + // As the other build tools take theirs from SOCKET_CLI__PATH, ahead of + // a named binary. + const orFlag = explicitFlag ? ` or pass ${explicitFlag}` : '' + const fromEnv = env['SOCKET_CLI_BAZEL_PATH'] + const override = fromEnv || explicit if (isSea()) { - const override = explicit ?? env['SOCKET_CLI_BAZEL_PATH'] if (!override) { throw new InputError( - 'Bazel is not bundled with this standalone Socket CLI. Set SOCKET_CLI_BAZEL_PATH or pass --bazel with an installed native Bazel executable.', + `Bazel is not bundled with this standalone Socket CLI. Set SOCKET_CLI_BAZEL_PATH${orFlag} with an installed native Bazel executable.`, ) } const resolved = path.resolve(cwd, override) @@ -61,11 +68,13 @@ export async function resolveBazelBinary( } return bin } - if (explicit) { - const resolved = path.resolve(cwd, explicit) + if (override) { + const named = + fromEnv || !explicitFlag ? 'SOCKET_CLI_BAZEL_PATH' : explicitFlag + const resolved = path.resolve(cwd, override) if (!existsSync(resolved)) { throw new InputError( - `--bazel path does not exist: ${resolved}. Install bazelisk or bazel, or pass an existing path via --bazel.`, + `${named} path does not exist: ${resolved}. Install bazelisk or bazel, or name an existing path with ${named}.`, ) } return resolveBazelExecutable(resolved) @@ -82,6 +91,6 @@ export async function resolveBazelBinary( throw new InputError( 'Could not find bazelisk or bazel on PATH. ' + 'Install bazelisk (recommended; https://github.com/bazelbuild/bazelisk) ' + - 'or bazel, or pass --bazel .', + `or bazel, or name its path with ${explicitFlag ? `${explicitFlag} or ` : ''}SOCKET_CLI_BAZEL_PATH.`, ) } diff --git a/src/commands/manifest/bazel/bin-detect.test.mts b/src/commands/manifest/bazel/bin-detect.test.mts index b8e89c50f1..ebdbbbdbde 100644 --- a/src/commands/manifest/bazel/bin-detect.test.mts +++ b/src/commands/manifest/bazel/bin-detect.test.mts @@ -53,6 +53,16 @@ describe('resolveBazelBinary', () => { expect(statSync(resolved).ino).toBe(statSync(bin).ino) }) + it('takes SOCKET_CLI_BAZEL_PATH ahead of an explicit path', async () => { + const fromEnv = install('from-env') + const resolved = await resolveBazelBinary( + install('selected'), + getBazelEnvironment({ SOCKET_CLI_BAZEL_PATH: fromEnv }), + cwd, + ) + expect(statSync(resolved).ino).toBe(statSync(fromEnv).ino) + }) + it('prefers Bazelisk over Bazel', async () => { const bazelisk = install('bazelisk') install('bazel') @@ -91,5 +101,25 @@ describe('resolveBazelBinary', () => { await expect( resolveBazelBinary(path.join(cwd, 'missing'), getBazelEnvironment(), cwd), ).rejects.toThrow(/--bazel path does not exist/) + await expect( + resolveBazelBinary( + undefined, + getBazelEnvironment({ + SOCKET_CLI_BAZEL_PATH: path.join(cwd, 'missing'), + }), + cwd, + ), + ).rejects.toThrow(/SOCKET_CLI_BAZEL_PATH path does not exist/) + }) + + it('names only SOCKET_CLI_BAZEL_PATH for a command with no option naming Bazel', async () => { + const missing = resolveBazelBinary( + undefined, + getBazelEnvironment({ PATH: cwd }), + cwd, + null, + ) + await expect(missing).rejects.toThrow(/with SOCKET_CLI_BAZEL_PATH\.$/) + await expect(missing).rejects.not.toThrow(/--bazel/) }) }) diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index eeae13b286..aef300dbd2 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -7,7 +7,7 @@ import { socketFactsRunOptions, } from './generate-recursive-manifests.mts' import { handleManifestConda } from './handle-manifest-conda.mts' -import { runManifestFacts } from './run-manifest-facts.mts' +import { AUTO_MANIFEST_HINTS, runManifestFacts } from './run-manifest-facts.mts' import { ENVIRONMENT_YML, REQUIREMENTS_TXT, @@ -27,12 +27,6 @@ import type { import type { BuildTool } from './scripts/build-tool.mts' import type { OutputKind } from '../../types.mts' -// Auto-manifest reads every build option from the root socket.json. -const AUTO_MANIFEST_HINTS: Omit = { - setupCommand: 'socket manifest setup', - socketJson: SOCKET_JSON, -} - export type GenerateAutoManifestResult = { generatedFiles: string[] } diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 907ff245e7..2feb7f9546 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -1,6 +1,7 @@ import { existsSync, promises as fs } from 'node:fs' import path from 'node:path' +import { resolveBazelBinary } from './bazel/bin-detect.mts' import { buildRootPath, looksLikeSbtBuild, @@ -59,6 +60,12 @@ export const EXCLUDE_PATHS_HINTS: CommandHints = { flags: new Set(), } +// Auto-manifest scans read every build option from the root socket.json. +export const AUTO_MANIFEST_HINTS: Omit = { + setupCommand: 'socket manifest setup', + socketJson: SOCKET_JSON, +} + // The single-build manifest commands take every option as a flag. const FLAG_HINTS: BuildOptionHints = { excludePathsFlag: EXCLUDE_PATHS_FLAG, @@ -126,6 +133,8 @@ type SocketFactsRequest = { includeConfigs?: string | undefined javaHome?: string | undefined reachability?: ReachabilitySettings | undefined + // Bazel only: the target patterns to resolve. + targets?: string[] | undefined verbose: boolean } excludeBase: string @@ -137,7 +146,7 @@ type SocketFactsRequest = { flags: BuildOption[] } root: BuildRoot - tool: BuildTool + tool: BuildTool | 'bazel' } const SOCKET_FACTS_REQUEST_CONTRACT = 1 @@ -258,29 +267,14 @@ export type SocketFactsRunOptions = SocketFactsRequestOptions & { // Standalone JVM builds require SOCKET_CLI_*_PATH because the CLI ships without // JVM tooling. function toSocketFactsRequest( - { - bin, - buildOpts, - cwd, - ecosystem, - entryFile, - excludeBase, - excludeConfigs, - excludePaths, - hints = FLAG_HINTS, - ignoreUnresolved = false, - includeConfigs, - javaHome, - reachability, - verbose = false, - }: SocketFactsRequestOptions, + { bin, ecosystem, ...options }: SocketFactsRequestOptions, context: SocketFactsContext, ): CResult { let resolvedBin: string try { resolvedBin = resolveBuildToolBin( ecosystem, - cwd, + options.cwd, bin || undefined, ecosystem !== 'dotnet' && isSea(), ) @@ -293,33 +287,68 @@ function toSocketFactsRequest( } return { ok: true, - data: { - contract: SOCKET_FACTS_REQUEST_CONTRACT, - config: { - bin: resolvedBin, - buildOpts, - ...(excludeConfigs ? { excludeConfigs } : {}), - ignoreUnresolved, - ...(includeConfigs ? { includeConfigs } : {}), - ...(javaHome && ecosystem !== 'dotnet' ? { javaHome } : {}), - ...(reachability ? { reachability } : {}), - verbose, - }, - excludeBase: path.resolve(excludeBase ?? cwd), - ...(excludePaths?.length ? { excludePaths } : {}), - hints: { - ...hints, - ...(purposeOf(context) === 'reachability' - ? { - continueOnInstallErrorsFlag: - REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, - } - : {}), - flags: [...hints.flags].sort(), - }, - root: { dir: path.resolve(cwd), ...(entryFile ? { entryFile } : {}) }, - tool: ecosystem, + data: socketFactsRequest( + { ...options, bin: resolvedBin, tool: ecosystem }, + context, + ), + } +} + +function socketFactsRequest( + { + bin, + buildOpts, + cwd, + entryFile, + excludeBase, + excludeConfigs, + excludePaths, + hints = FLAG_HINTS, + ignoreUnresolved = false, + includeConfigs, + javaHome, + reachability, + targets, + tool, + verbose = false, + }: Omit & { + bin: string + targets?: string[] | undefined + tool: SocketFactsRequest['tool'] + }, + context: SocketFactsContext, +): SocketFactsRequest { + return { + contract: SOCKET_FACTS_REQUEST_CONTRACT, + config: { + bin, + buildOpts, + ...(excludeConfigs ? { excludeConfigs } : {}), + ignoreUnresolved, + ...(includeConfigs ? { includeConfigs } : {}), + ...(javaHome && tool !== 'dotnet' ? { javaHome } : {}), + ...(reachability ? { reachability } : {}), + ...(targets ? { targets } : {}), + verbose, }, + excludeBase: path.resolve(excludeBase ?? cwd), + ...(excludePaths?.length ? { excludePaths } : {}), + hints: requestHints(hints, context), + root: { dir: path.resolve(cwd), ...(entryFile ? { entryFile } : {}) }, + tool, + } +} + +function requestHints( + hints: BuildOptionHints, + context: SocketFactsContext, +): SocketFactsRequest['hints'] { + return { + ...hints, + ...(purposeOf(context) === 'reachability' + ? { continueOnInstallErrorsFlag: REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG } + : {}), + flags: [...hints.flags].sort(), } } @@ -411,32 +440,16 @@ export async function listBuildProjects({ // Failures set a nonzero exit code. Coana reports build failures. // A staged run leaves its facts in the work directory for keepFacts to place. -export async function runManifestFacts({ - context = {}, - staged = false, - ...options -}: SocketFactsRunOptions & { - staged?: boolean | undefined -}): Promise { - const { cwd, ecosystem, entryFile } = options - if (ecosystem === 'sbt' && !looksLikeSbtBuild(cwd)) { - process.exitCode = 1 - logger.fail( - `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 - } - +async function runSocketFactsRequest( + request: SocketFactsRequest, + // Names the build in a failure Coana could not report. + build: string, + context: SocketFactsContext, + staged: boolean, +): Promise { const { workDir } = context const { message, result } = await runGenerateSocketFacts( - request.data, + request, [ '--purpose', purposeOf(context), @@ -449,7 +462,7 @@ export async function runManifestFacts({ process.exitCode = 1 if (!result) { logger.fail( - `Could not generate Socket facts for the ${ecosystem} project at \`${buildRootPath({ dir: cwd, entryFile })}\`${message ? `: ${message}` : '.'}`, + `Could not generate Socket facts for ${build}${message ? `: ${message}` : '.'}`, ) } return null @@ -476,6 +489,88 @@ export async function runManifestFacts({ return facts } +export async function runManifestFacts({ + context = {}, + staged = false, + ...options +}: SocketFactsRunOptions & { + staged?: boolean | undefined +}): Promise { + const { cwd, ecosystem, entryFile } = options + if (ecosystem === 'sbt' && !looksLikeSbtBuild(cwd)) { + process.exitCode = 1 + logger.fail( + `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 await runSocketFactsRequest( + request.data, + `the ${ecosystem} project at \`${buildRootPath({ dir: cwd, entryFile })}\``, + context, + staged, + ) +} + +// For reachability the targets are compiled, as Bazel makes their jars only +// when it builds them. +export async function runBazelFacts({ + context = {}, + root, + targets, +}: { + context?: SocketFactsContext | undefined + root: string + targets: string[] +}): Promise { + let bin: string + try { + // `--bazel` selects a Bazel scan here, naming no binary. + bin = await resolveBazelBinary(undefined, process.env, root, null) + } catch (e) { + process.exitCode = 1 + logger.fail(getErrorMessageOr(e, 'Could not find Bazel')) + return null + } + const dir = path.resolve(root) + const result = await runSocketFactsRequest( + socketFactsRequest( + { + bin, + buildOpts: [], + cwd: dir, + // Scan create takes none of the build options as flags, and no path is + // excluded. + hints: { ...AUTO_MANIFEST_HINTS, flags: new Set() }, + ...(purposeOf(context) === 'reachability' + ? { reachability: { build: 'compile' } } + : {}), + targets, + tool: 'bazel', + }, + context, + ), + `the Bazel targets ${targets.join(' ')} at \`${dir}\``, + context, + false, + ) + if (result === undefined) { + process.exitCode = 1 + logger.fail( + `Coana found no projects or dependencies in the Bazel targets ${targets.join(' ')}.`, + ) + return null + } + return result +} + // What `--socket-facts-sidecar` reads for the kept build roots. export function socketFactsSidecar( workDir: SocketFactsWorkDir, diff --git a/src/commands/scan/cmd-scan-create.mts b/src/commands/scan/cmd-scan-create.mts index 05d7fa7f46..07a53a24c0 100644 --- a/src/commands/scan/cmd-scan-create.mts +++ b/src/commands/scan/cmd-scan-create.mts @@ -1,4 +1,4 @@ -import { readdirSync } from 'node:fs' +import { existsSync, readdirSync, statSync } from 'node:fs' import path from 'node:path' import { assertValidExcludePaths } from './exclude-paths.mts' @@ -49,6 +49,7 @@ import { socketDashboardLink } from '../../utils/terminal-link.mts' import { detectManifestActions } from '../manifest/detect-manifest-actions.mts' import { EXCLUDE_PATHS_HINTS } from '../manifest/run-manifest-facts.mts' +import type { BazelScan } from './handle-create-new-scan.mts' import type { REPORT_LEVEL } from './types.mts' import type { MeowFlags } from '../../flags.mts' import type { @@ -66,6 +67,15 @@ const DEPRECATED_NO_OP_REACH_FLAGS = new Set([ 'reachLazyMode', ]) +// A Bazel workspace's root holds one of its boundary files (Bazel's +// "Repositories, workspaces, packages, and targets"). +const BAZEL_WORKSPACE_FILES = [ + 'MODULE.bazel', + 'REPO.bazel', + 'WORKSPACE', + 'WORKSPACE.bazel', +] + const description = 'Create a new Socket scan and report' const hidden = false @@ -78,6 +88,12 @@ const generalFlags: MeowFlags = { description: 'Run `socket manifest auto` before collecting manifest files, which generates them for ecosystems that need their build tool to resolve dependencies, such as Scala, Gradle, and Kotlin. See `socket manifest auto --help`. For Gradle, sbt, Maven and .NET, --dynamic-sbom-inference generates a Socket facts SBOM per build root instead.', }, + bazel: { + type: 'boolean', + hidden: true, + description: + 'Scan only the Bazel targets the patterns after `--` name, as `bazel build` takes them, from the workspace root TARGET, for example `socket scan create . --bazel -- //app/... -//app/legacy/...`. Replaces manifest discovery. Supports JVM targets the workspace compiles, Python, JavaScript, Rust and Go targets, with reachability for JVM, Python and JavaScript targets: the scan fails if the patterns match any other target, such as a `java_import`.', + }, branch: { type: 'string', default: '', @@ -199,6 +215,23 @@ function hasSocketFactsFileIn(dir: string): boolean { } } +// A short flag the command declares, alone or with its value attached by `=`. +function isShortFlag(arg: string, flags: MeowFlags): boolean { + const body = arg.slice(1) + return Object.values(flags).some( + ({ shortFlag }) => + !!shortFlag && (body === shortFlag || body.startsWith(`${shortFlag}=`)), + ) +} + +function isBazelWorkspace(dir: string): boolean { + // Bazel counts a boundary file only when it is no directory. + return BAZEL_WORKSPACE_FILES.some(f => { + const file = path.join(dir, f) + return existsSync(file) && !statSync(file).isDirectory() + }) +} + export const cmdScanCreate = { description, hidden, @@ -357,6 +390,12 @@ async function run( const dryRun = !!cli.flags['dryRun'] const uvMembers = !!cli.flags['uvMembers'] + const bazelScan = !!cli.flags['bazel'] + // As Bazel's own command line takes them, after `--`, where a negative + // pattern is no flag; the parser appends them to the TARGETs. + const dashDash = argv.indexOf('--') + const bazelTargets = + bazelScan && dashDash !== -1 ? argv.slice(dashDash + 1) : [] let { autoManifest, @@ -388,7 +427,11 @@ async function run( // Note: This needs meow booleanDefault=undefined. if (typeof autoManifest !== 'boolean') { - if (sockJson.defaults?.scan?.create?.autoManifest !== undefined) { + // A Bazel scan replaces the manifest discovery this default is about. + if ( + !bazelScan && + sockJson.defaults?.scan?.create?.autoManifest !== undefined + ) { autoManifest = sockJson.defaults.scan.create.autoManifest logger.info( `Using default --auto-manifest from ${SOCKET_JSON}:`, @@ -432,7 +475,8 @@ async function run( let updatedInput = false // Accept zero or more paths. Default to cwd() if none given. - let targets = cli.input.length ? cli.input : [] + const input = cli.input.slice(0, cli.input.length - bazelTargets.length) + let targets = input if (!targets.length && !dryRun && interactive) { targets = await suggestTarget() @@ -448,6 +492,18 @@ async function run( targets = ['.'] } + const bazelRoot = + bazelScan && targets.length === 1 + ? path.resolve(cwd, targets[0]!) + : undefined + const isValidBazelRoot = + bazelRoot !== undefined && + isBazelWorkspace(bazelRoot) && + (await validateReachabilityTarget(targets, cwd)).isInsideCwd + const bazel: BazelScan | undefined = isValidBazelRoot + ? { root: bazelRoot, targets: bazelTargets } + : undefined + // We're going to need an api token to suggest data because those suggestions // must come from data we already know. Don't error on missing api token yet. // If the api-token is not set, ignore it for the sake of suggestions. @@ -496,6 +552,7 @@ async function run( !autoManifest && !dynamicSbomInference && !uvMembers && + !bazelScan && !hasFactsFile ) { logger.info( @@ -509,7 +566,7 @@ async function run( ) logger.error('```') logger.error( - ` socket scan create [other flags...] ${orgSlug} ${targets.join(' ')}`, + ` socket scan create [other flags...] --org=${orgSlug}${bazelScan ? ' --bazel' : ''} ${targets.join(' ')}${bazelScan ? ` -- ${bazelTargets.join(' ')}` : ''}`, ) logger.error('```') logger.error('') @@ -603,6 +660,48 @@ async function run( '--uv-members cannot be combined with --auto-manifest or --dynamic-sbom-inference', fail: 'select one source of generated SBOMs', }, + { + nook: true, + test: + !bazelScan || (!autoManifest && !dynamicSbomInference && !uvMembers), + message: + '--bazel scans the Bazel targets alone and cannot be combined with --auto-manifest, --dynamic-sbom-inference or --uv-members', + fail: 'select one source of generated SBOMs', + }, + { + nook: true, + test: !bazelScan || !!bazelTargets.length, + message: + '--bazel needs the target patterns to scan after `--`, for example `socket scan create . --bazel -- //app/... -//app/legacy/...`', + fail: 'no Bazel target patterns', + }, + { + nook: true, + // Before `--` the parser reads a pattern as short flags, and drops those + // the command does not declare. + test: + !bazelScan || + !(dashDash === -1 ? argv : argv.slice(0, dashDash)).some( + a => /^-[^-\d]/.test(a) && !isShortFlag(a, config.flags), + ), + message: + 'A Bazel target pattern before `--` is read as flags: give every pattern after `--`, for example `socket scan create . --bazel -- //app/... -//app/legacy/...`', + fail: 'move the patterns after `--`', + }, + { + nook: true, + test: !bazelScan || !!bazel, + message: + '--bazel needs exactly one TARGET before `--`: a Bazel workspace root inside the working directory. Use --cwd to select a workspace outside it.', + fail: 'provide a Bazel workspace root inside the working directory', + }, + { + nook: true, + test: !bazelScan || !excludePaths.length, + message: + '--bazel selects what to scan by target pattern: leave targets out with a negative pattern such as `-//app/legacy/...` instead of --exclude-paths', + fail: 'drop --exclude-paths', + }, { nook: true, test: !json || !markdown, @@ -676,6 +775,7 @@ async function run( await handleCreateNewScan({ autoManifest: Boolean(autoManifest), + bazel, branchName: branchName as string, commitHash: (commitHash && String(commitHash)) || '', commitMessage: (commitMessage && String(commitMessage)) || '', diff --git a/src/commands/scan/cmd-scan-create.test.mts b/src/commands/scan/cmd-scan-create.test.mts index aa4b5af292..a118980695 100644 --- a/src/commands/scan/cmd-scan-create.test.mts +++ b/src/commands/scan/cmd-scan-create.test.mts @@ -81,6 +81,115 @@ describe('socket scan create', async () => { }, ) + const bazelFixture = path.join( + testPath, + 'fixtures/commands/scan/bazel-workspace', + ) + const bazelBaseArgs = uvBaseArgs.map(a => + a === uvFixture ? bazelFixture : a, + ) + + it( + 'scans Bazel targets from the workspace root, whatever socket.json says of --auto-manifest', + { timeout: 30_000 }, + async () => { + const result = await spawnSocketCli(binCliPath, [ + ...bazelBaseArgs, + '--bazel', + '.', + '--', + '//app/...', + '-//app/legacy/...', + ]) + expect(result.code).toBe(0) + expect(result.stdout).toContain('[DryRun]: Bailing now') + }, + ) + + it( + 'takes a declared short flag with its value before `--` in a Bazel scan', + { timeout: 30_000 }, + async () => { + const withoutBranch = bazelBaseArgs.filter( + (a, i, all) => a !== '--branch' && all[i - 1] !== '--branch', + ) + const result = await spawnSocketCli(binCliPath, [ + ...withoutBranch, + '--bazel', + '-b=main', + '.', + '--', + '//app/...', + ]) + expect(result.code).toBe(0) + expect(result.stdout).toContain('[DryRun]: Bailing now') + }, + ) + + it( + 'rejects a Bazel workspace root outside the working directory', + { timeout: 30_000 }, + async () => { + const result = await spawnSocketCli(binCliPath, [ + ...bazelBaseArgs.map(a => + a === bazelFixture ? path.join(bazelFixture, 'app') : a, + ), + '--bazel', + '..', + '--', + '//app/...', + ]) + expect(result.code).not.toBe(0) + expect(result.stdout + result.stderr).toContain( + 'a Bazel workspace root inside the working directory', + ) + }, + ) + + it.each([ + { + args: ['--bazel', 'app', '--', '//app/...'], + error: 'a Bazel workspace root inside the working directory', + }, + { + args: ['--bazel', '//app/...', '.', '--', '//lib/...'], + error: 'a Bazel workspace root inside the working directory', + }, + { + args: ['--bazel', '--auto-manifest', '.', '--', '//app/...'], + error: 'cannot be combined', + }, + { + args: ['--bazel', '--exclude-paths', 'app', '.', '--', '//app/...'], + error: 'instead of --exclude-paths', + }, + { args: ['--bazel', '.'], error: 'target patterns to scan after `--`' }, + { + args: ['--bazel', '-//app/legacy/...', '.', '--', '//app/...'], + error: 'is read as flags', + }, + { + args: ['--bazel', '-app/legacy/...', '.', '--', '//app/...'], + error: 'is read as flags', + }, + // A pattern of letters only is no short flag the command declares. + { + args: ['--bazel', '-app', '.', '--', '//...'], + error: 'is read as flags', + }, + ])( + 'rejects invalid Bazel scan options: $args', + { timeout: 30_000 }, + async ({ args, error }) => { + const result = await spawnSocketCli(binCliPath, [ + ...bazelBaseArgs, + ...args, + ]) + expect(result.code).not.toBe(0) + expect(result.stdout + result.stderr).toContain(error) + }, + ) + cmdit( ['scan', 'create', FLAG_HELP, FLAG_CONFIG, '{}'], `should support ${FLAG_HELP}`, diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index b1c504a37d..bf0d4ac1b8 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -19,12 +19,13 @@ import constants from '../../constants.mts' import { checkCommandInput } from '../../utils/check-input.mts' import { compressSocketFactsForUpload, + isFactsOnlyTypes, isReachabilityReportPath, snapshotSocketFacts, } from '../../utils/coana.mts' import { findSocketYmlSync } from '../../utils/config.mts' import { debugDir, debugFn } from '../../utils/debug.mts' -import { withTmpDir } from '../../utils/fs.mts' +import { readJson, withTmpDir } from '../../utils/fs.mts' import { logger } from '../../utils/logger.mts' import { getPackageFilesForScan } from '../../utils/path-resolve.mts' import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' @@ -34,6 +35,7 @@ import { detectManifestActions } from '../manifest/detect-manifest-actions.mts' import { generateAutoManifest } from '../manifest/generate_auto_manifest.mts' import { createSocketFactsWorkDir, + runBazelFacts, socketFactsSidecar, } from '../manifest/run-manifest-facts.mts' import { buildToolsFor } from '../manifest/scripts/build-tool.mts' @@ -43,6 +45,7 @@ import type { ReachabilityOptions } from './perform-reachability-analysis.mts' import type { REPORT_LEVEL } from './types.mts' import type { OutputKind } from '../../types.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' +import type { PURL_Type } from '../../utils/ecosystem.mts' import type { Remap } from '../../utils/objects.mts' import type { CommandHints, @@ -90,9 +93,17 @@ export type GeneratedScanFiles = { files: string[] } +// In place of manifest discovery: the scan holds these targets' dependencies +// alone. +export type BazelScan = { + root: string + targets: string[] +} + export type HandleCreateNewScanConfig = { autoManifest: boolean baselineScanId?: string | undefined + bazel?: BazelScan | undefined onDiffReport?: ((diffScanId: string) => Promise) | undefined branchName: string commitHash: string @@ -125,10 +136,43 @@ export type HandleCreateNewScanConfig = { workspace?: string | undefined } +// The ecosystems of Bazel targets Coana analyses for reachability. +const BAZEL_REACHABLE_TYPES: ReadonlySet = new Set([ + 'maven', + 'npm', + 'pypi', +]) +const isBazelReachable = (type: string): type is PURL_Type => + BAZEL_REACHABLE_TYPES.has(type) + +// The ecosystems among the facts' targets that reachability analyses; the +// others' targets are scanned for their dependencies alone. +async function bazelReachableTypes(factsPath: string): Promise { + const facts = (await readJson(factsPath)) as { + projects?: Array<{ id: string; type: string }> + } + const reachable = new Set() + const others: string[] = [] + for (const { id, type } of facts.projects ?? []) { + if (isBazelReachable(type)) { + reachable.add(type) + } else { + others.push(id) + } + } + if (others.length) { + logger.warn( + `Reachability analysis does not support these Bazel targets yet, so the scan holds their dependencies without it: ${others.join(', ')}`, + ) + } + return [...reachable].sort() +} + async function createNewScan( { autoManifest, baselineScanId, + bazel, branchName, commitHash, commitMessage, @@ -142,7 +186,7 @@ async function createNewScan( outputKind, pendingHead, pullRequest, - reach, + reach: requestedReach, readOnly, repoName, report, @@ -177,6 +221,8 @@ async function createNewScan( let factsOnlyTypes: FactsOnlyTypes | undefined let discardedFactsPaths: string[] | undefined + // A Bazel scan narrows it to the ecosystems of its targets. + let reach = requestedReach // Coana's reachability run reads what facts generation keeps in the work // dir, so it lives until the analysis below is done. @@ -192,7 +238,39 @@ async function createNewScan( ) : undefined, } - if (autoManifest || reach.dynamicSbomInference) { + let bazelFacts: string[] | undefined + if (bazel) { + logger.info('Generating Socket facts for the Bazel targets ...') + const result = await runBazelFacts({ + context: factsContext, + root: bazel.root, + targets: bazel.targets, + }) + // As auto-manifest does, so a --json caller gets the failure too. + if (!result) { + throw new Error( + `Socket facts generation failed for the Bazel targets ${bazel.targets.join(' ')}`, + ) + } + // The scan is of the targets alone. + bazelFacts = [result.targetPath] + if (reach.runReachabilityAnalysis) { + const reachable = await bazelReachableTypes(result.targetPath) + // Empty reachEcosystems means every ecosystem, so none left analyses + // none. + const reachEcosystems = reach.reachEcosystems.length + ? reach.reachEcosystems.filter(t => reachable.includes(t)) + : reachable + if (isFactsOnlyTypes(reachable)) { + factsOnlyTypes = reachable + } + reach = { + ...reach, + reachEcosystems, + runReachabilityAnalysis: !!reachEcosystems.length, + } + } + } else if (autoManifest || reach.dynamicSbomInference) { logger.info('Auto-generating manifest files ...') debugFn('notice', 'Manifest auto-generation enabled') @@ -286,6 +364,7 @@ async function createNewScan( const packagePaths = scanFiles ?? + bazelFacts ?? (await withoutDiscardedFacts( await getPackageFilesForScan(scanTargets, supportedFiles, { additionalIgnores: additionalScaIgnores, diff --git a/src/commands/scan/handle-create-new-scan.test.mts b/src/commands/scan/handle-create-new-scan.test.mts index cf5e65dac5..bb68b5ddca 100644 --- a/src/commands/scan/handle-create-new-scan.test.mts +++ b/src/commands/scan/handle-create-new-scan.test.mts @@ -17,6 +17,7 @@ import { makeReachabilityOptions } from '../../../test/reachability-options.mts' import { logger } from '../../utils/logger.mts' import type { HandleCreateNewScanConfig } from './handle-create-new-scan.mts' +import type { PURL_Type } from '../../utils/ecosystem.mts' const { mockFetchCreateOrgFullScan, @@ -27,6 +28,7 @@ const { mockGetPackageFilesForScan, mockPerformReachabilityAnalysis, mockReadOrDefaultSocketJson, + mockRunBazelFacts, } = vi.hoisted(() => ({ mockFetchCreateOrgFullScan: vi.fn(), mockFetchSupportedScanFileNames: vi.fn(), @@ -36,6 +38,7 @@ const { mockGetPackageFilesForScan: vi.fn(), mockPerformReachabilityAnalysis: vi.fn(), mockReadOrDefaultSocketJson: vi.fn(), + mockRunBazelFacts: vi.fn(), })) vi.mock('./fetch-create-org-full-scan.mts', () => ({ @@ -82,6 +85,13 @@ vi.mock('../manifest/generate-recursive-manifests.mts', () => ({ generateRecursiveManifests: mockGenerateRecursiveManifests, })) +vi.mock('../manifest/run-manifest-facts.mts', async importOriginal => ({ + ...(await importOriginal< + typeof import('../manifest/run-manifest-facts.mts') + >()), + runBazelFacts: mockRunBazelFacts, +})) + vi.mock('../manifest/generate_auto_manifest.mts', () => ({ generateAutoManifest: mockGenerateAutoManifest, })) @@ -1059,3 +1069,99 @@ describe('handleCreateNewScan reachability fallback facts files', () => { expect(existsSync(factsPath)).toBe(false) }) }) + +describe('handleCreateNewScan with --bazel', () => { + let dir: string + let factsPath: string + + beforeEach(() => { + vi.clearAllMocks() + dir = mkdtempSync(path.join(tmpdir(), 'socket-bazel-scan-')) + factsPath = path.join(dir, 'bazel.socket.facts.json') + writeFileSync( + factsPath, + JSON.stringify({ + projects: [ + { id: '//java:app', type: 'maven' }, + { id: '//go:app', type: 'golang' }, + ], + }), + ) + mockRunBazelFacts.mockResolvedValue({ + factsPath, + projects: [], + targetPath: factsPath, + }) + mockFetchCreateOrgFullScan.mockResolvedValue({ + data: { id: 'scan-id' }, + ok: true, + }) + mockFetchSupportedScanFileNames.mockResolvedValue({ + data: { size: 1 }, + ok: true, + }) + mockFindSocketYmlSync.mockReturnValue({ ok: true }) + mockPerformReachabilityAnalysis.mockResolvedValue({ + data: { reachabilityReport: factsPath, tier1ReachabilityScanId: 't' }, + ok: true, + }) + }) + + afterEach(() => { + rmSync(dir, { force: true, recursive: true }) + }) + + const bazelConfig = (reachEcosystems: PURL_Type[] = []) => { + const config = createConfig({ + bazel: { root: dir, targets: ['//...'] }, + cwd: dir, + targets: [dir], + }) + config.reach.runReachabilityAnalysis = true + config.reach.reachEcosystems = reachEcosystems + return config + } + + it('analyses only the ecosystems Coana analyses Bazel targets of', async () => { + await handleCreateNewScan(bazelConfig()) + expect(mockPerformReachabilityAnalysis).toHaveBeenCalledWith( + expect.objectContaining({ + factsOnlyTypes: ['maven'], + reachabilityOptions: expect.objectContaining({ + reachEcosystems: ['maven'], + }), + }), + ) + }) + + it('runs no analysis when --reach-ecosystems names none of them', async () => { + await handleCreateNewScan(bazelConfig(['golang'])) + expect(mockPerformReachabilityAnalysis).not.toHaveBeenCalled() + expect(mockFetchCreateOrgFullScan).toHaveBeenCalledWith( + [factsPath], + 'fakeOrg', + expect.anything(), + expect.anything(), + ) + }) + + it('fails the scan when facts generation fails', async () => { + mockRunBazelFacts.mockResolvedValueOnce(null) + await expect(handleCreateNewScan(bazelConfig())).rejects.toThrow( + 'Socket facts generation failed for the Bazel targets //...', + ) + expect(mockFetchCreateOrgFullScan).not.toHaveBeenCalled() + }) + + it('warns of targets reachability does not analyse only when it runs', async () => { + const warn = vi.spyOn(logger, 'warn') + const config = bazelConfig() + config.reach.runReachabilityAnalysis = false + await handleCreateNewScan(config) + expect(warn).not.toHaveBeenCalledWith( + expect.stringContaining('Reachability analysis does not support'), + ) + await handleCreateNewScan(bazelConfig()) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('//go:app')) + }) +}) diff --git a/test/fixtures/commands/scan/bazel-workspace/MODULE.bazel b/test/fixtures/commands/scan/bazel-workspace/MODULE.bazel new file mode 100644 index 0000000000..4e596463b8 --- /dev/null +++ b/test/fixtures/commands/scan/bazel-workspace/MODULE.bazel @@ -0,0 +1 @@ +module(name = "fixture") diff --git a/test/fixtures/commands/scan/bazel-workspace/app/BUILD.bazel b/test/fixtures/commands/scan/bazel-workspace/app/BUILD.bazel new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/fixtures/commands/scan/bazel-workspace/socket.json b/test/fixtures/commands/scan/bazel-workspace/socket.json new file mode 100644 index 0000000000..42fd1e3d41 --- /dev/null +++ b/test/fixtures/commands/scan/bazel-workspace/socket.json @@ -0,0 +1,10 @@ +{ + "version": 1, + "defaults": { + "scan": { + "create": { + "autoManifest": true + } + } + } +}