From 8cf7daefc53af84943fbf6d5d09e8db7e282b16d Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Sat, 28 Nov 2026 17:52:50 +0100 Subject: [PATCH 1/4] feat(scan): scan Bazel targets with --bazel Scans only the Bazel targets the patterns after `--` name, from the workspace root, in place of manifest discovery. Coana resolves the patterns as `bazel build` takes them and generates the Socket facts; reachability analyses the JVM, Python and JavaScript targets. Facts generation passes Coana the run's `--purpose`, as every other build does, and a reachability run compiles the targets. --- CHANGELOG.md | 5 + src/commands/manifest/bazel/bin-detect.mts | 23 +- .../manifest/bazel/bin-detect.test.mts | 30 +++ .../manifest/generate_auto_manifest.mts | 8 +- src/commands/manifest/run-manifest-facts.mts | 233 ++++++++++++------ src/commands/scan/cmd-scan-create.mts | 105 +++++++- src/commands/scan/cmd-scan-create.test.mts | 89 +++++++ src/commands/scan/handle-create-new-scan.mts | 85 ++++++- .../scan/handle-create-new-scan.test.mts | 106 ++++++++ .../scan/bazel-workspace/MODULE.bazel | 1 + .../scan/bazel-workspace/app/BUILD.bazel | 0 .../commands/scan/bazel-workspace/socket.json | 10 + 12 files changed, 605 insertions(+), 90 deletions(-) create mode 100644 test/fixtures/commands/scan/bazel-workspace/MODULE.bazel create mode 100644 test/fixtures/commands/scan/bazel-workspace/app/BUILD.bazel create mode 100644 test/fixtures/commands/scan/bazel-workspace/socket.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 4af608c6ea..b6c5ac5eff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [Unreleased] + +### Changed +- `socket manifest bazel` takes Bazel from `SOCKET_CLI_BAZEL_PATH` ahead of `--bazel`, in every build. + ## [1.18.1](https://github.com/SocketDev/socket-cli/releases/tag/v1.18.1) - 2026-11-30 ### Changed 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 ebe935661c..d58af86024 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, @@ -54,6 +55,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, @@ -120,6 +127,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 @@ -131,7 +140,7 @@ type SocketFactsRequest = { flags: BuildOption[] } root: BuildRoot - tool: BuildTool + tool: BuildTool | 'bazel' } const SOCKET_FACTS_REQUEST_CONTRACT = 1 @@ -248,29 +257,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(), ) @@ -283,33 +277,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(), } } @@ -401,32 +430,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), @@ -439,7 +452,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 @@ -466,6 +479,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 292dedbda8..9b17c9c672 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,15 @@ async function run( targets = ['.'] } + const bazelRoot = + bazelScan && targets.length === 1 + ? path.resolve(cwd, targets[0]!) + : undefined + const bazel: BazelScan | undefined = + bazelRoot && isBazelWorkspace(bazelRoot) + ? { 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 +549,7 @@ async function run( !autoManifest && !dynamicSbomInference && !uvMembers && + !bazelScan && !hasFactsFile ) { logger.info( @@ -509,7 +563,7 @@ async function run( ) logger.error('```') logger.error( - ` socket scan create [other flags...] ${orgSlug} ${targets.join(' ')}`, + ` socket scan create [other flags...] ${orgSlug} ${targets.join(' ')}${bazelScan ? ` -- ${bazelTargets.join(' ')}` : ''}`, ) logger.error('```') logger.error('') @@ -603,6 +657,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 `--`, the root of a Bazel workspace: the directory with its MODULE.bazel, REPO.bazel, WORKSPACE or WORKSPACE.bazel file', + fail: 'no Bazel workspace root', + }, + { + 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 +772,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 ede415185b..ce23277f23 100644 --- a/src/commands/scan/cmd-scan-create.test.mts +++ b/src/commands/scan/cmd-scan-create.test.mts @@ -81,6 +81,95 @@ 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.each([ + { + args: ['--bazel', 'app', '--', '//app/...'], + error: 'the root of a Bazel workspace', + }, + { + args: ['--bazel', '//app/...', '.', '--', '//lib/...'], + error: 'the root of a Bazel workspace', + }, + { + 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 278d223a0a..6e76b26f0e 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -18,12 +18,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' @@ -33,6 +34,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' @@ -42,6 +44,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, @@ -89,8 +92,16 @@ 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 + bazel?: BazelScan | undefined branchName: string commitHash: string commitMessage: string @@ -122,9 +133,42 @@ 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, + bazel, branchName, commitHash, commitMessage, @@ -137,7 +181,7 @@ async function createNewScan( outputKind, pendingHead, pullRequest, - reach, + reach: requestedReach, readOnly, repoName, report, @@ -172,6 +216,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. @@ -186,7 +232,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') @@ -280,6 +358,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 26daecf0b0..ced0d8ecdc 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, })) @@ -1034,3 +1044,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 + } + } + } +} From 9288e55389ee1966e345d2cdb765468062d24d86 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 2 Dec 2026 11:19:09 +0100 Subject: [PATCH 2/4] fix(scan): keep the Bazel workspace root inside the working directory Refuse a --bazel workspace root outside the working directory, as --reach does for its target, and point at --cwd. The repeat-command hint now names the org with --org and includes --bazel. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- src/commands/scan/cmd-scan-create.mts | 17 ++++++++------- src/commands/scan/cmd-scan-create.test.mts | 24 ++++++++++++++++++++-- 3 files changed, 33 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6c5ac5eff..36d1083099 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] ### Changed -- `socket manifest bazel` takes Bazel from `SOCKET_CLI_BAZEL_PATH` ahead of `--bazel`, in every build. +- `socket manifest bazel` gives `SOCKET_CLI_BAZEL_PATH` precedence over `--bazel`. ## [1.18.1](https://github.com/SocketDev/socket-cli/releases/tag/v1.18.1) - 2026-11-30 diff --git a/src/commands/scan/cmd-scan-create.mts b/src/commands/scan/cmd-scan-create.mts index 9b17c9c672..fb2e1612f5 100644 --- a/src/commands/scan/cmd-scan-create.mts +++ b/src/commands/scan/cmd-scan-create.mts @@ -496,10 +496,13 @@ async function run( bazelScan && targets.length === 1 ? path.resolve(cwd, targets[0]!) : undefined - const bazel: BazelScan | undefined = - bazelRoot && isBazelWorkspace(bazelRoot) - ? { root: bazelRoot, targets: bazelTargets } - : 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. @@ -563,7 +566,7 @@ async function run( ) logger.error('```') logger.error( - ` socket scan create [other flags...] ${orgSlug} ${targets.join(' ')}${bazelScan ? ` -- ${bazelTargets.join(' ')}` : ''}`, + ` socket scan create [other flags...] --org=${orgSlug}${bazelScan ? ' --bazel' : ''} ${targets.join(' ')}${bazelScan ? ` -- ${bazelTargets.join(' ')}` : ''}`, ) logger.error('```') logger.error('') @@ -689,8 +692,8 @@ async function run( nook: true, test: !bazelScan || !!bazel, message: - '--bazel needs exactly one TARGET before `--`, the root of a Bazel workspace: the directory with its MODULE.bazel, REPO.bazel, WORKSPACE or WORKSPACE.bazel file', - fail: 'no Bazel workspace root', + '--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, diff --git a/src/commands/scan/cmd-scan-create.test.mts b/src/commands/scan/cmd-scan-create.test.mts index ce23277f23..f31528be58 100644 --- a/src/commands/scan/cmd-scan-create.test.mts +++ b/src/commands/scan/cmd-scan-create.test.mts @@ -126,14 +126,34 @@ describe('socket scan create', async () => { }, ) + 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: 'the root of a Bazel workspace', + error: 'a Bazel workspace root inside the working directory', }, { args: ['--bazel', '//app/...', '.', '--', '//lib/...'], - error: 'the root of a Bazel workspace', + error: 'a Bazel workspace root inside the working directory', }, { args: ['--bazel', '--auto-manifest', '.', '--', '//app/...'], From 5bcb7138cdd5366faf336e6ee4b577a1a15b08d5 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 2 Dec 2026 21:05:00 +0100 Subject: [PATCH 3/4] docs(changelog): drop the Bazel path entry --bazel is hidden, so the release notes leave it out. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36d1083099..4af608c6ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,6 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). -## [Unreleased] - -### Changed -- `socket manifest bazel` gives `SOCKET_CLI_BAZEL_PATH` precedence over `--bazel`. - ## [1.18.1](https://github.com/SocketDev/socket-cli/releases/tag/v1.18.1) - 2026-11-30 ### Changed From da26035e51b08dd58dba5dc955692a3a8101d224 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 2 Dec 2026 21:13:21 +0100 Subject: [PATCH 4/4] style(scan): sort the scan options after the v1.x merge Co-Authored-By: Claude Opus 5.5 --- src/commands/scan/handle-create-new-scan.mts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index 9070be6307..bf0d4ac1b8 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -102,8 +102,8 @@ export type BazelScan = { export type HandleCreateNewScanConfig = { autoManifest: boolean - bazel?: BazelScan | undefined baselineScanId?: string | undefined + bazel?: BazelScan | undefined onDiffReport?: ((diffScanId: string) => Promise) | undefined branchName: string commitHash: string @@ -171,8 +171,8 @@ async function bazelReachableTypes(factsPath: string): Promise { async function createNewScan( { autoManifest, - bazel, baselineScanId, + bazel, branchName, commitHash, commitMessage,