diff --git a/.gitignore b/.gitignore index 3d333045c..8d793d140 100644 --- a/.gitignore +++ b/.gitignore @@ -1130,6 +1130,8 @@ !/src/utils/bin.mts !/src/utils/check-input.mts !/src/utils/cmd.mts +!/src/utils/ci-exit-code.mts +!/src/utils/ci-exit-code.test.mts !/src/utils/coana/ !/src/utils/coana/** !/src/utils/coana-release.test.mts diff --git a/src/cli.mts b/src/cli.mts index ff268a189..199304309 100755 --- a/src/cli.mts +++ b/src/cli.mts @@ -7,6 +7,7 @@ import { messageWithCauses, stackWithCauses } from 'pony-cause' import { rootAliases, rootCommands } from './commands.mts' import constants from './constants.mts' +import { hasCiExitCodePolicy, setCiExitCode } from './utils/ci-exit-code.mts' import { debugDir, debugFn } from './utils/debug.mts' import { AuthError, InputError, captureException } from './utils/errors.mts' import { failMsgWithBadge } from './utils/fail-msg-with-badge.mts' @@ -47,10 +48,20 @@ void (async () => { { aliases: rootAliases }, ) + if (constants.abortSignal.aborted && hasCiExitCodePolicy()) { + setCiExitCode('interrupted') + } + // Track successful CLI completion. await trackCliComplete(process.argv, cliStartTime, process.exitCode) } catch (e) { - process.exitCode = 1 + setCiExitCode( + e instanceof InputError + ? 'usage' + : constants.abortSignal.aborted + ? 'interrupted' + : 'infrastructure', + ) // Track CLI error for telemetry. await trackCliError(process.argv, cliStartTime, e, process.exitCode) diff --git a/src/commands/ci/cmd-ci.mts b/src/commands/ci/cmd-ci.mts index 1b5432879..81e76c896 100644 --- a/src/commands/ci/cmd-ci.mts +++ b/src/commands/ci/cmd-ci.mts @@ -1,6 +1,10 @@ import { handleCi } from './handle-ci.mts' import constants from '../../constants.mts' import { commonFlags } from '../../flags.mts' +import { + setCiExitCode, + setCiExitCodePolicy, +} from '../../utils/ci-exit-code.mts' import { logger } from '../../utils/logger.mts' import { meowOrExit } from '../../utils/meow-with-subcommands.mts' import { getFlagListOutput } from '../../utils/output-formatting.mts' @@ -24,6 +28,18 @@ const config: CliCommandConfig = { description: 'Auto generate manifest files where detected? See autoManifest flag in `socket scan create`', }, + disableBlocking: { + type: 'boolean', + default: false, + description: + 'Return success for findings and infrastructure failures, but keep usage errors non-zero.', + }, + exitCodeOnApiError: { + type: 'number', + default: 3, + description: + 'Exit code for Socket API errors (default: 3). Ignored with --disable-blocking.', + }, }, help: (command, _config) => ` Usage @@ -34,8 +50,10 @@ const config: CliCommandConfig = { This command is intended to use in CI runs to allow automated systems to accept or reject a current build. It will use the default org of the - Socket API token. The exit code will be non-zero when the scan does not pass - your security policy. + Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2 + for usage errors, 3 for infrastructure errors, and 130 for interruption. + --disable-blocking returns 0 for findings and runtime failures, but not + usage errors. --exit-code-on-api-error changes the API failure code. The --auto-manifest flag does the same as the one from \`socket scan create\` but is not enabled by default since the CI is less likely to be set up with @@ -45,6 +63,8 @@ const config: CliCommandConfig = { Examples $ ${command} $ ${command} --auto-manifest + $ ${command} --disable-blocking + $ ${command} --exit-code-on-api-error 5 `, } @@ -73,5 +93,21 @@ async function run( return } + const exitCodeOnApiError = Number(cli.flags['exitCodeOnApiError']) + setCiExitCodePolicy({ + disableBlocking: Boolean(cli.flags['disableBlocking']), + exitCodeOnApiError, + }) + + if ( + !Number.isInteger(exitCodeOnApiError) || + exitCodeOnApiError < 0 || + exitCodeOnApiError > 255 + ) { + logger.fail('--exit-code-on-api-error must be an integer from 0 to 255.') + setCiExitCode('usage') + return + } + await handleCi(Boolean(cli.flags['autoManifest'])) } diff --git a/src/commands/ci/cmd-ci.test.mts b/src/commands/ci/cmd-ci.test.mts index 03d104f54..b429e6761 100644 --- a/src/commands/ci/cmd-ci.test.mts +++ b/src/commands/ci/cmd-ci.test.mts @@ -24,11 +24,15 @@ describe('socket ci', async () => { Options --auto-manifest Auto generate manifest files where detected? See autoManifest flag in \`socket scan create\` + --disable-blocking Return success for findings and infrastructure failures, but keep usage errors non-zero. + --exit-code-on-api-error Exit code for Socket API errors (default: 3). Ignored with --disable-blocking. This command is intended to use in CI runs to allow automated systems to accept or reject a current build. It will use the default org of the - Socket API token. The exit code will be non-zero when the scan does not pass - your security policy. + Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2 + for usage errors, 3 for infrastructure errors, and 130 for interruption. + --disable-blocking returns 0 for findings and runtime failures, but not + usage errors. --exit-code-on-api-error changes the API failure code. The --auto-manifest flag does the same as the one from \`socket scan create\` but is not enabled by default since the CI is less likely to be set up with @@ -37,7 +41,9 @@ describe('socket ci', async () => { Examples $ socket ci - $ socket ci --auto-manifest" + $ socket ci --auto-manifest + $ socket ci --disable-blocking + $ socket ci --exit-code-on-api-error 5" `, ) expect(`\n ${stderr}`).toMatchInlineSnapshot(` diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index 1cc43733f..ce4d39fac 100644 --- a/src/commands/ci/handle-ci.mts +++ b/src/commands/ci/handle-ci.mts @@ -1,5 +1,6 @@ import { getDefaultOrgSlug } from './fetch-default-org-slug.mts' import constants from '../../constants.mts' +import { setCiExitCode } from '../../utils/ci-exit-code.mts' import { debugDir, debugFn } from '../../utils/debug.mts' import { envAsString } from '../../utils/env.mts' import { @@ -32,7 +33,7 @@ export async function handleCi(autoManifest: boolean): Promise { if (!orgSlugCResult.ok) { debugFn('warn', 'Failed to get default org slug') debugDir('inspect', { orgSlugCResult }) - process.exitCode = orgSlugCResult.code ?? 1 + setCiExitCode('api', orgSlugCResult.code ?? 1) // Always assume json mode. logger.log(serializeResultJson(orgSlugCResult)) return diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index a45fa2673..ac498d250 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -18,7 +18,6 @@ import { REQUIREMENTS_TXT, SOCKET_JSON, } from '../../constants.mts' -import { InputError } from '../../utils/errors.mts' import { logger } from '../../utils/logger.mts' import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' @@ -52,7 +51,7 @@ function abortFactsRunIfFailed( outcome: RunManifestFactsOutcome, ): void { if (outcome === null) { - throw new InputError( + throw new Error( `Auto-manifest generation failed for the ${ecosystem} project; aborting (see the errors above).`, ) } @@ -63,7 +62,7 @@ function abortManifestRunIfFailed( beforeExitCode: string | number | undefined, ): void { if (process.exitCode && process.exitCode !== beforeExitCode) { - throw new InputError( + throw new Error( `Auto-manifest generation failed for the ${ecosystem} project; aborting (see the errors above).`, ) } diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index f4a5e4b1b..7f86b229f 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -387,7 +387,14 @@ describe('generateAutoManifest — conda branch', () => { outputKind: 'text', verbose: false, }), - ).rejects.toThrow(/Auto-manifest generation failed for the conda project/) + ).rejects.toThrowError( + expect.objectContaining({ + message: expect.stringContaining( + 'Auto-manifest generation failed for the conda project', + ), + name: 'Error', + }), + ) process.exitCode = undefined }) diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index d9af8e8ce..c1a04796f 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -249,6 +249,7 @@ async function createNewScan( debugFn('warn', 'Failed to fetch supported scan file names') debugDir('inspect', { supportedFilesCResult }) await outputCreateNewScan(supportedFilesCResult, { + failureKind: 'api', interactive, outputKind, }) @@ -490,6 +491,7 @@ async function createNewScan( data: fullScanCResult.data, }, { + failureKind: 'api', interactive, outputKind, reachabilityFallback, @@ -500,6 +502,7 @@ async function createNewScan( spinner.stop() await outputCreateNewScan(fullScanCResult, { + failureKind: 'api', interactive, outputKind, reachabilityFallback, diff --git a/src/commands/scan/output-create-new-scan.mts b/src/commands/scan/output-create-new-scan.mts index e4ebd8652..2a6f0321f 100644 --- a/src/commands/scan/output-create-new-scan.mts +++ b/src/commands/scan/output-create-new-scan.mts @@ -2,6 +2,7 @@ import open from 'open' import terminalLink from 'terminal-link' import constants from '../../constants.mts' +import { setCiExitCode } from '../../utils/ci-exit-code.mts' import { failMsgWithBadge } from '../../utils/fail-msg-with-badge.mts' import { logger } from '../../utils/logger.mts' import { confirm } from '../../utils/prompts.mts' @@ -17,6 +18,7 @@ export type ReachabilityFallback = { } export type CreateNewScanOptions = { + failureKind?: 'api' | 'infrastructure' | undefined interactive?: boolean | undefined outputKind?: OutputKind | undefined // Set when --reach-fallback-to-regular-scan downgraded the run, so machine @@ -30,6 +32,7 @@ export async function outputCreateNewScan( options?: CreateNewScanOptions | undefined, ) { const { + failureKind = 'infrastructure', interactive = false, outputKind = 'text', reachabilityFallback, @@ -37,7 +40,7 @@ export async function outputCreateNewScan( } = { __proto__: null, ...options } as CreateNewScanOptions if (!result.ok) { - process.exitCode = result.code ?? 1 + setCiExitCode(failureKind, result.code ?? 1) } const wasSpinning = !!spinner?.isSpinning @@ -65,7 +68,7 @@ export async function outputCreateNewScan( if (!result.data.id) { logger.fail('Did not receive a scan ID from the API.') - process.exitCode = 1 + setCiExitCode('api') } if (outputKind === 'markdown') { diff --git a/src/commands/scan/output-scan-report.mts b/src/commands/scan/output-scan-report.mts index 1addf9bae..0a48f3701 100644 --- a/src/commands/scan/output-scan-report.mts +++ b/src/commands/scan/output-scan-report.mts @@ -9,6 +9,7 @@ import constants, { REPORT_LEVEL_DEFER, } from '../../constants.mts' import { joinAnd } from '../../utils/arrays.mts' +import { setCiExitCode } from '../../utils/ci-exit-code.mts' import { failMsgWithBadge } from '../../utils/fail-msg-with-badge.mts' import { logger } from '../../utils/logger.mts' import { mapToObject } from '../../utils/map-to-object.mts' @@ -120,7 +121,7 @@ export async function outputScanReport( }: OutputScanReportConfig, ): Promise { if (!result.ok) { - process.exitCode = result.code ?? 1 + setCiExitCode('api', result.code ?? 1) } if (!result.ok) { @@ -143,7 +144,7 @@ export async function outputScanReport( if (!scanReport.ok) { // Note: This means generation failed, it does not reflect the healthy state. - process.exitCode = scanReport.code ?? 1 + setCiExitCode('infrastructure', scanReport.code ?? 1) // If report generation somehow failed then .data should not be set. if (outputKind === OUTPUT_JSON) { @@ -156,7 +157,7 @@ export async function outputScanReport( if (!scanReport.data.healthy) { // When report contains healthy: false, process should exit with non-zero code. - process.exitCode = 1 + setCiExitCode('blocking') } // I don't think we emit the default error message with banner for an unhealthy report, do we? diff --git a/src/commands/scan/output-scan-report.test.mts b/src/commands/scan/output-scan-report.test.mts index 49b41e7b6..8159f9255 100644 --- a/src/commands/scan/output-scan-report.test.mts +++ b/src/commands/scan/output-scan-report.test.mts @@ -6,6 +6,7 @@ import { toMarkdownReport, } from './output-scan-report.mts' import { SOCKET_WEBSITE_URL } from '../../constants.mjs' +import { setCiExitCodePolicy } from '../../utils/ci-exit-code.mts' import type { ScanReport } from './generate-report.mts' @@ -157,6 +158,7 @@ describe('output-scan-report', () => { }) afterEach(() => { + setCiExitCodePolicy(undefined) process.exitCode = originalExitCode }) @@ -211,6 +213,56 @@ describe('output-scan-report', () => { expect(process.exitCode).toBeUndefined() }) + + it('lets --disable-blocking make an unhealthy report non-blocking', async () => { + setCiExitCodePolicy({ disableBlocking: true }) + mockGenerateReport.mockReturnValue({ + ok: true, + data: getUnhealthyReport(), + }) + + await outputScanReport( + { + ok: true, + data: { scan: [] }, + } as any, + { + orgSlug: 'test-org', + scanId: 'test-scan', + includeLicensePolicy: false, + outputKind: 'json', + filepath: '-', + fold: 'none', + reportLevel: 'error', + short: false, + }, + ) + + expect(process.exitCode).toBe(0) + }) + + it('remaps API failures to the configured code', async () => { + setCiExitCodePolicy({ + disableBlocking: false, + exitCodeOnApiError: 42, + }) + + await outputScanReport( + { ok: false, message: 'API failure' }, + { + orgSlug: 'test-org', + scanId: 'test-scan', + includeLicensePolicy: false, + outputKind: 'json', + filepath: '-', + fold: 'none', + reportLevel: 'error', + short: false, + }, + ) + + expect(process.exitCode).toBe(42) + }) }) }) diff --git a/src/utils/ci-exit-code.mts b/src/utils/ci-exit-code.mts new file mode 100644 index 000000000..a470657df --- /dev/null +++ b/src/utils/ci-exit-code.mts @@ -0,0 +1,65 @@ +import constants from '../constants.mts' + +export type CiExitCodePolicy = { + disableBlocking: boolean + exitCodeOnApiError?: number | undefined +} + +export type CiExitCodeKind = + | 'api' + | 'blocking' + | 'infrastructure' + | 'interrupted' + | 'usage' + +export const ciExitCodeState: { policy?: CiExitCodePolicy | undefined } = {} + +export function setCiExitCodePolicy( + policy?: CiExitCodePolicy | undefined, +): void { + ciExitCodeState.policy = policy +} + +export function hasCiExitCodePolicy(): boolean { + return ciExitCodeState.policy !== undefined +} + +export function setCiExitCode( + kind: CiExitCodeKind, + fallback: number = 1, +): void { + const { policy } = ciExitCodeState + if (!policy) { + process.exitCode = fallback + return + } + + if (kind !== 'usage' && constants.abortSignal.aborted) { + kind = 'interrupted' + } + + if (kind === 'usage') { + process.exitCode = 2 + return + } + + if (policy.disableBlocking) { + process.exitCode = 0 + return + } + + switch (kind) { + case 'api': + process.exitCode = policy.exitCodeOnApiError ?? 3 + return + case 'blocking': + process.exitCode = 1 + return + case 'infrastructure': + process.exitCode = 3 + return + case 'interrupted': + process.exitCode = 130 + return + } +} diff --git a/src/utils/ci-exit-code.test.mts b/src/utils/ci-exit-code.test.mts new file mode 100644 index 000000000..eea5014e6 --- /dev/null +++ b/src/utils/ci-exit-code.test.mts @@ -0,0 +1,63 @@ +import { afterEach, describe, expect, it } from 'vitest' + +import { setCiExitCode, setCiExitCodePolicy } from './ci-exit-code.mts' + +describe('ci-exit-code', () => { + const originalExitCode = process.exitCode + + afterEach(() => { + setCiExitCodePolicy(undefined) + process.exitCode = originalExitCode + }) + + it('uses distinct codes for findings and infrastructure failures', () => { + setCiExitCodePolicy({ disableBlocking: false }) + + setCiExitCode('blocking') + expect(process.exitCode).toBe(1) + + setCiExitCode('infrastructure') + expect(process.exitCode).toBe(3) + }) + + it('uses the configured exit code for API failures', () => { + setCiExitCodePolicy({ + disableBlocking: false, + exitCodeOnApiError: 42, + }) + + setCiExitCode('api') + + expect(process.exitCode).toBe(42) + }) + + it('lets disable blocking override findings and infrastructure failures', () => { + setCiExitCodePolicy({ disableBlocking: true }) + + for (const kind of [ + 'api', + 'blocking', + 'infrastructure', + 'interrupted', + ] as const) { + setCiExitCode(kind) + expect(process.exitCode).toBe(0) + } + }) + + it('keeps usage errors non-remappable', () => { + setCiExitCodePolicy({ disableBlocking: true, exitCodeOnApiError: 0 }) + + setCiExitCode('usage') + + expect(process.exitCode).toBe(2) + }) + + it('preserves existing behavior without a CI policy', () => { + setCiExitCodePolicy(undefined) + + setCiExitCode('api', 17) + + expect(process.exitCode).toBe(17) + }) +}) diff --git a/test/snapshots/termless/cli.native.socket-help-ci.svg b/test/snapshots/termless/cli.native.socket-help-ci.svg index 08b2cc7bc..9b72c0574 100644 --- a/test/snapshots/termless/cli.native.socket-help-ci.svg +++ b/test/snapshots/termless/cli.native.socket-help-ci.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.0-rc.0 | cmd: socket ci | org: (not set) | token: (not set) @@ -19,41 +19,53 @@ --auto-manifest Auto generate manifest files where detected? See autoManifest flag in `socket scan create` - + --disable-blocking Return success for findings and infrastructure failures, but keep usage errors non-zero. - This command is intended to use in CI runs to allow automated systems to + --exit-code-on-api-error Exit code for Socket API errors (default: 3). Ignored with --disable-blocking. - accept or reject a current build. It will use the default org of the + - Socket API token. The exit code will be non-zero when the scan does not pass + This command is intended to use in CI runs to allow automated systems to - your security policy. + accept or reject a current build. It will use the default org of the - + Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2 - The --auto-manifest flag does the same as the one from `socket scan create` + for usage errors, 3 for infrastructure errors, and 130 for interruption. - but is not enabled by default since the CI is less likely to be set up with + --disable-blocking returns 0 for findings and runtime failures, but not - all the necessary dev tooling. Enable it if you want the scan to include + usage errors. --exit-code-on-api-error changes the API failure code. - locally generated manifests like for gradle and sbt. - + + The --auto-manifest flag does the same as the one from `socket scan create` - Examples + but is not enabled by default since the CI is less likely to be set up with - $ socket ci + all the necessary dev tooling. Enable it if you want the scan to include - $ socket ci --auto-manifest + locally generated manifests like for gradle and sbt. - + Examples - + $ socket ci - + $ socket ci --auto-manifest + $ socket ci --disable-blocking + + $ socket ci --exit-code-on-api-error 5 + + + + + + + + + - \ No newline at end of file + \ No newline at end of file