Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion src/cli.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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',
)
Comment thread
jdalton marked this conversation as resolved.
Resolved

// Track CLI error for telemetry.
await trackCliError(process.argv, cliStartTime, e, process.exitCode)
Expand Down
40 changes: 38 additions & 2 deletions src/commands/ci/cmd-ci.mts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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
Expand All @@ -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
Expand All @@ -45,6 +63,8 @@ const config: CliCommandConfig = {
Examples
$ ${command}
$ ${command} --auto-manifest
$ ${command} --disable-blocking
$ ${command} --exit-code-on-api-error 5
`,
}

Expand Down Expand Up @@ -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']))
}
12 changes: 9 additions & 3 deletions src/commands/ci/cmd-ci.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(`
Expand Down
3 changes: 2 additions & 1 deletion src/commands/ci/handle-ci.mts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -32,7 +33,7 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
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
Expand Down
5 changes: 2 additions & 3 deletions src/commands/manifest/generate_auto_manifest.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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).`,
)
}
Expand All @@ -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).`,
)
}
Expand Down
9 changes: 8 additions & 1 deletion src/commands/manifest/generate_auto_manifest.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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
})

Expand Down
3 changes: 3 additions & 0 deletions src/commands/scan/handle-create-new-scan.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
Expand Down Expand Up @@ -490,6 +491,7 @@ async function createNewScan(
data: fullScanCResult.data,
},
{
failureKind: 'api',
interactive,
outputKind,
reachabilityFallback,
Expand All @@ -500,6 +502,7 @@ async function createNewScan(
spinner.stop()

await outputCreateNewScan(fullScanCResult, {
failureKind: 'api',
interactive,
outputKind,
reachabilityFallback,
Expand Down
7 changes: 5 additions & 2 deletions src/commands/scan/output-create-new-scan.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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
Expand All @@ -30,14 +32,15 @@ export async function outputCreateNewScan(
options?: CreateNewScanOptions | undefined,
) {
const {
failureKind = 'infrastructure',
interactive = false,
outputKind = 'text',
reachabilityFallback,
spinner = constants.spinner,
} = { __proto__: null, ...options } as CreateNewScanOptions

if (!result.ok) {
process.exitCode = result.code ?? 1
setCiExitCode(failureKind, result.code ?? 1)
}

const wasSpinning = !!spinner?.isSpinning
Expand Down Expand Up @@ -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') {
Expand Down
7 changes: 4 additions & 3 deletions src/commands/scan/output-scan-report.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -120,7 +121,7 @@ export async function outputScanReport(
}: OutputScanReportConfig,
): Promise<void> {
if (!result.ok) {
process.exitCode = result.code ?? 1
setCiExitCode('api', result.code ?? 1)
}

if (!result.ok) {
Expand All @@ -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) {
Expand All @@ -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?
Expand Down
52 changes: 52 additions & 0 deletions src/commands/scan/output-scan-report.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -157,6 +158,7 @@ describe('output-scan-report', () => {
})

afterEach(() => {
setCiExitCodePolicy(undefined)
process.exitCode = originalExitCode
})

Expand Down Expand Up @@ -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)
})
})
})

Expand Down
Loading
Loading