From e94eda3913a960593b2034683970350345c208c0 Mon Sep 17 00:00:00 2001 From: jdalton Date: Fri, 4 Dec 2026 00:48:20 -0500 Subject: [PATCH] feat(python-cli-parity): add strict blocking to socket ci --- docs/commands/ci.md | 10 ++++ src/commands/ci/cmd-ci.mts | 16 +++++- src/commands/ci/handle-ci.mts | 8 ++- src/commands/scan/diff-scan-verdict.mts | 7 ++- src/commands/scan/handle-create-new-scan.mts | 5 +- src/commands/scan/handle-diff-scan.mts | 6 ++- .../termless/cli.native.socket-help-ci.svg | 52 +++++++++++-------- test/unit/src/commands/ci/cmd-ci.test.mts | 5 +- .../src/commands/ci/handle-ci-skip.test.mts | 20 +++++++ test/unit/src/commands/ci/handle-ci.test.mts | 42 +++++++++++++-- .../commands/scan/diff-scan-verdict.test.mts | 13 +++++ .../commands/scan/output-diff-scan.test.mts | 33 ++++++++++++ 12 files changed, 182 insertions(+), 35 deletions(-) diff --git a/docs/commands/ci.md b/docs/commands/ci.md index 03070900c..e7a067437 100644 --- a/docs/commands/ci.md +++ b/docs/commands/ci.md @@ -8,6 +8,16 @@ nonzero status if the scan fails your security policy. socket ci ``` +On pull requests, use `--strict-blocking` to fail when a blocking alert is +present on an unchanged dependency as well as when the PR introduces one: + +```sh +socket ci --strict-blocking +``` + +Strict blocking is off by default. `--disable-blocking` takes precedence and +keeps findings from failing the job. + Use `--auto-manifest` to include locally generated manifests for supported projects. Run `socket ci --help` for all options. diff --git a/src/commands/ci/cmd-ci.mts b/src/commands/ci/cmd-ci.mts index 880993cb8..59d3610f4 100644 --- a/src/commands/ci/cmd-ci.mts +++ b/src/commands/ci/cmd-ci.mts @@ -34,6 +34,12 @@ const config: CliCommandConfig = { description: 'Return success for findings and infrastructure failures, but keep usage errors non-zero.', }, + strictBlocking: { + type: 'boolean', + default: false, + description: + 'Fail for existing blocking alerts as well as alerts introduced by this PR.', + }, exitCodeOnApiError: { type: 'number', default: 3, @@ -58,7 +64,8 @@ const config: CliCommandConfig = { 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. + usage errors. --strict-blocking also fails for blocking alerts on unchanged + dependencies. --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 @@ -69,6 +76,7 @@ const config: CliCommandConfig = { $ ${command} $ ${command} --auto-manifest $ ${command} --disable-blocking + $ ${command} --strict-blocking $ ${command} --exit-code-on-api-error 5 `, } @@ -121,5 +129,9 @@ async function run( return } - await handleCi(Boolean(cli.flags['autoManifest']), jsonFormat === 'python-v1') + await handleCi( + Boolean(cli.flags['autoManifest']), + jsonFormat === 'python-v1', + Boolean(cli.flags['strictBlocking']), + ) } diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index d578737ae..a1b508174 100644 --- a/src/commands/ci/handle-ci.mts +++ b/src/commands/ci/handle-ci.mts @@ -38,6 +38,7 @@ import type { PythonDiffJsonContext } from '../scan/python-diff-json.mts' export async function handleCi( autoManifest: boolean, pythonJsonFormat = false, + strictBlocking = false, ): Promise { debugFn('notice', 'Starting CI scan') debugDir('inspect', { autoManifest, pythonJsonFormat }) @@ -73,6 +74,7 @@ export async function handleCi( : pullRequestContext.provider === 'azure' ? process.env['BUILD_SOURCEVERSION'] || null : null, + strictBlocking, } if (pythonJsonFormat && !pullRequest) { setCiExitCode('usage') @@ -117,7 +119,7 @@ export async function handleCi( // Only skip when a clean checkout and an authoritative supported-file list // prove this PR has no dependency manifest changes. Auto-manifest generation // can derive dependencies from source/build inputs, so it always scans. - if (pullRequestContext.number && !autoManifest) { + if (pullRequestContext.number && !autoManifest && !strictBlocking) { const supportedFilesCResult = await fetchSupportedScanFileNames({ orgSlug, silence: true, @@ -175,6 +177,7 @@ export async function handleCi( autoManifest, branchName, cwd, + strictBlocking, onDiffOutcome, orgSlug, pullRequestContext, @@ -195,10 +198,12 @@ async function runCiScan({ pythonJsonContext, pythonJsonFormat, repoName, + strictBlocking, }: { autoManifest: boolean branchName: string cwd: string + strictBlocking: boolean onDiffOutcome: (outcome: { blocking: boolean incomplete: boolean @@ -260,6 +265,7 @@ async function runCiScan({ orgSlug, outputKind: 'json', pythonJsonFormat, + strictBlocking, pythonJsonContext, // When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false. pendingHead: true, diff --git a/src/commands/scan/diff-scan-verdict.mts b/src/commands/scan/diff-scan-verdict.mts index 6d204a2ab..e7f36b9ea 100644 --- a/src/commands/scan/diff-scan-verdict.mts +++ b/src/commands/scan/diff-scan-verdict.mts @@ -20,13 +20,16 @@ export function getDiffScanBlocking( ) } -export function getDiffScanVerdict(diffScan: DiffScanData['diff_scan']): { +export function getDiffScanVerdict( + diffScan: DiffScanData['diff_scan'], + strictBlocking = false, +): { blocking: boolean incomplete: boolean reportUrl: string | null } { return { - blocking: getDiffScanBlocking(diffScan), + blocking: getDiffScanBlocking(diffScan, strictBlocking), incomplete: diffScan.incomplete === true, reportUrl: diffScan.html_url, } diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index c440547d5..d2a05e08a 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -43,8 +43,8 @@ import { import { buildToolsFor } from '../manifest/scripts/build-tool.mts' import type { ReachabilityFallback } from './output-create-new-scan.mts' -import type { PythonDiffJsonContext } from './python-diff-json.mts' import type { ReachabilityOptions } from './perform-reachability-analysis.mts' +import type { PythonDiffJsonContext } from './python-diff-json.mts' import type { REPORT_LEVEL } from './types.mts' import type { OutputKind } from '../../types.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' @@ -119,6 +119,7 @@ export type HandleCreateNewScanConfig = { | undefined pythonJsonFormat?: boolean | undefined pythonJsonContext?: PythonDiffJsonContext | undefined + strictBlocking?: boolean | undefined branchName: string commitHash: string commitMessage: string @@ -207,6 +208,7 @@ async function createNewScan( repoName, report, reportLevel, + strictBlocking = false, targets, tmp, workspace, @@ -604,6 +606,7 @@ async function createNewScan( outputKind, pythonJsonFormat, pythonJsonContext, + strictBlocking, }) } else { await handleScanReport({ diff --git a/src/commands/scan/handle-diff-scan.mts b/src/commands/scan/handle-diff-scan.mts index 9778778a6..090dc1aff 100644 --- a/src/commands/scan/handle-diff-scan.mts +++ b/src/commands/scan/handle-diff-scan.mts @@ -50,6 +50,7 @@ export async function handlePrDiffScan({ outputKind, pythonJsonContext = {}, pythonJsonFormat = false, + strictBlocking = false, }: { id1: string id2: string @@ -67,20 +68,21 @@ export async function handlePrDiffScan({ outputKind: OutputKind pythonJsonFormat?: boolean | undefined pythonJsonContext?: PythonDiffJsonContext | undefined + strictBlocking?: boolean | undefined }): Promise { const result = await fetchDiffScan({ id1, id2, orgSlug }) await outputDiffScan(result, { depth: 2, file: '', outputKind, - strictBlocking: false, + strictBlocking, pythonJsonFormat, pythonJsonContext, }) if (result.ok) { await onDiffReport?.( result.data.diff_scan.id, - getDiffScanVerdict(result.data.diff_scan), + getDiffScanVerdict(result.data.diff_scan, strictBlocking), ) } } diff --git a/test/snapshots/termless/cli.native.socket-help-ci.svg b/test/snapshots/termless/cli.native.socket-help-ci.svg index 9e8aa297d..d7af0b86f 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.1-rc.1 | cmd: socket ci | org: (not set) | token: (not set) @@ -25,49 +25,55 @@ --json-format Select a versioned JSON payload. Supported: python-v1 (pull request comparisons only). - + --strict-blocking Fail for existing blocking alerts as well as alerts introduced by this PR. - 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 + This command is intended to use in CI runs to allow automated systems to - Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2 + accept or reject a current build. It will use the default org of the - for usage errors, 3 for infrastructure errors, and 130 for interruption. + Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2 - --disable-blocking returns 0 for findings and runtime failures, but not + for usage errors, 3 for infrastructure errors, and 130 for interruption. - usage errors. --exit-code-on-api-error changes the API failure code. + --disable-blocking returns 0 for findings and runtime failures, but not - + usage errors. --strict-blocking also fails for blocking alerts on unchanged - The --auto-manifest flag does the same as the one from `socket scan create` + dependencies. --exit-code-on-api-error changes the API failure code. - but is not enabled by default since the CI is less likely to be set up with + - all the necessary dev tooling. Enable it if you want the scan to include + The --auto-manifest flag does the same as the one from `socket scan create` - locally generated manifests like for gradle and sbt. + but is not enabled by default since the CI is less likely to be set up with - + all the necessary dev tooling. Enable it if you want the scan to include - Examples + locally generated manifests like for gradle and sbt. - $ socket ci + - $ socket ci --auto-manifest + Examples - $ socket ci --disable-blocking + $ socket ci - $ socket ci --exit-code-on-api-error 5 + $ socket ci --auto-manifest - + $ socket ci --disable-blocking - + $ socket ci --strict-blocking - + $ socket ci --exit-code-on-api-error 5 - \ No newline at end of file + + + + + + + \ No newline at end of file diff --git a/test/unit/src/commands/ci/cmd-ci.test.mts b/test/unit/src/commands/ci/cmd-ci.test.mts index d9dfa2b48..3bad1ad59 100644 --- a/test/unit/src/commands/ci/cmd-ci.test.mts +++ b/test/unit/src/commands/ci/cmd-ci.test.mts @@ -27,13 +27,15 @@ describe('socket ci', async () => { --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. --json-format Select a versioned JSON payload. Supported: python-v1 (pull request comparisons only). + --strict-blocking Fail for existing blocking alerts as well as alerts introduced by this PR. 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. 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. + usage errors. --strict-blocking also fails for blocking alerts on unchanged + dependencies. --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 @@ -44,6 +46,7 @@ describe('socket ci', async () => { $ socket ci $ socket ci --auto-manifest $ socket ci --disable-blocking + $ socket ci --strict-blocking $ socket ci --exit-code-on-api-error 5" `, ) diff --git a/test/unit/src/commands/ci/handle-ci-skip.test.mts b/test/unit/src/commands/ci/handle-ci-skip.test.mts index fa89ea609..ab3c643a2 100644 --- a/test/unit/src/commands/ci/handle-ci-skip.test.mts +++ b/test/unit/src/commands/ci/handle-ci-skip.test.mts @@ -110,3 +110,23 @@ it('keeps normal baseline selection when no supported manifests are discoverable message: 'baseline unavailable', }) }) + +it('evaluates unchanged dependencies in strict blocking mode on a source-only PR', async () => { + mockFetchSupportedScanFileNames.mockResolvedValue({ + ok: true, + data: { npm: { manifest: { pattern: 'package.json' } } }, + }) + mockGetPackageFilesForScan.mockResolvedValue(['package.json']) + mockSelectBaselineScan.mockResolvedValue({ + ok: true, + data: { id: 'baseline' }, + }) + const { handleCi } = await import('../../../../../src/commands/ci/handle-ci.mts') + await handleCi(false, false, true) + expect(mockHandleCreateNewScan).toHaveBeenCalledWith( + expect.objectContaining({ + baselineScanId: 'baseline', + strictBlocking: true, + }), + ) +}) diff --git a/test/unit/src/commands/ci/handle-ci.test.mts b/test/unit/src/commands/ci/handle-ci.test.mts index 1bd909446..32f4fa58a 100644 --- a/test/unit/src/commands/ci/handle-ci.test.mts +++ b/test/unit/src/commands/ci/handle-ci.test.mts @@ -143,6 +143,14 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun vi.stubEnv('SOCKET_CLI_DISABLE_OVERVIEW_COMMENT', '') vi.stubEnv('SOCKET_CLI_DISABLE_SECURITY_COMMENT', '') vi.resetModules() + vi.doMock('../../../../../src/utils/spawn.mts', () => ({ + spawn: vi.fn(async (_command: string, args: string[]) => ({ + stdout: + args?.[0] === 'symbolic-ref' + ? 'feature-branch' + : 'git@github.com:example/project.git', + })), + })) vi.doMock( '../../../../../src/commands/ci/fetch-default-org-slug.mts', () => ({ @@ -177,7 +185,21 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun id: 'diff-id', before_full_scan: { id: 'base' }, after_full_scan: { id: 'test-scan' }, - artifacts: { added: [], updated: [], replaced: [] }, + artifacts: { + added: [], + updated: [], + replaced: [], + unchanged: [ + { + type: 'npm', + name: 'left-pad', + version: '1.0.0', + alerts: [ + { action: 'error', type: 'test-alert', key: 'alert-1' }, + ], + }, + ], + }, html_url: null, }, }, @@ -210,7 +232,12 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun const { handleCi } = await import( '../../../../../src/commands/ci/handle-ci.mts' ) + process.exitCode = 0 await handleCi(false) + expect(process.exitCode).toBe(0) + await handleCi(false, false, true) + expect(process.exitCode).toBe(1) + process.exitCode = 0 expect(comments.map(c => c.body)).toEqual([ expect.stringContaining('API overview'), expect.stringContaining('API alerts'), @@ -220,13 +247,22 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun await handleCi(false) vi.stubEnv('GITHUB_REF', 'refs/heads/main') await handleCi(false) - expect(fetchComments).toHaveBeenCalledTimes(3) - expect(writes).toEqual(['POST', 'POST', 'PATCH', 'PATCH', 'PATCH']) + expect(fetchComments).toHaveBeenCalledTimes(4) + expect(writes).toEqual([ + 'POST', + 'POST', + 'PATCH', + 'PATCH', + 'PATCH', + 'PATCH', + 'PATCH', + ]) expect(comments).toHaveLength(2) } finally { vi.unstubAllEnvs() vi.doUnmock('../../../../../src/commands/ci/fetch-default-org-slug.mts') vi.doUnmock('../../../../../src/commands/ci/select-baseline-scan.mts') + vi.doUnmock('../../../../../src/utils/spawn.mts') vi.doUnmock('../../../../../src/utils/api.mts') vi.doUnmock('../../../../../src/commands/scan/fetch-diff-scan.mts') vi.doUnmock('../../../../../src/commands/scan/handle-scan-report.mts') diff --git a/test/unit/src/commands/scan/diff-scan-verdict.test.mts b/test/unit/src/commands/scan/diff-scan-verdict.test.mts index 9ffffa982..02bc4127f 100644 --- a/test/unit/src/commands/scan/diff-scan-verdict.test.mts +++ b/test/unit/src/commands/scan/diff-scan-verdict.test.mts @@ -62,4 +62,17 @@ describe('getDiffScanBlocking', () => { reportUrl: 'https://dashboard.test/diff/diff-id', }) }) + + it('includes unchanged blockers in the strict provider verdict', () => { + const diff = { + ...cleanDiff, + artifacts: { + ...cleanDiff.artifacts, + unchanged: [{ alerts: [{ action: 'error' }] }], + }, + } as unknown as DiffScanData['diff_scan'] + + expect(getDiffScanVerdict(diff, true)).toMatchObject({ blocking: true }) + expect(getDiffScanVerdict(diff)).toMatchObject({ blocking: false }) + }) }) diff --git a/test/unit/src/commands/scan/output-diff-scan.test.mts b/test/unit/src/commands/scan/output-diff-scan.test.mts index 74116649e..ca30af64a 100644 --- a/test/unit/src/commands/scan/output-diff-scan.test.mts +++ b/test/unit/src/commands/scan/output-diff-scan.test.mts @@ -91,6 +91,39 @@ describe('outputDiffScan strict blocking', () => { expect(process.exitCode).toBe(1) }) + it('applies strict blocking to the PR gate, provider outcome, and Python JSON', async () => { + fetchDiffScan.mockResolvedValue({ + ok: true, + data: { + diff_scan: { ...diff.diff_scan, id: 'diff-id' }, + }, + }) + const onDiffReport = vi.fn() + + await handlePrDiffScan({ + id1: 'before', + id2: 'after', + onDiffReport, + orgSlug: 'example', + outputKind: 'json', + pythonJsonFormat: true, + strictBlocking: true, + }) + + expect(process.exitCode).toBe(1) + expect(onDiffReport).toHaveBeenCalledWith('diff-id', { + blocking: true, + incomplete: false, + reportUrl: '', + }) + expect(logger.log).toHaveBeenCalledWith( + expect.stringContaining('"decision": "fail"'), + ) + expect(logger.log).toHaveBeenCalledWith( + expect.stringContaining('"unchanged_alerts": ['), + ) + }) + it('fails for new blocking alerts in ordinary diff mode', async () => { const changed = structuredClone(diff) changed.diff_scan.artifacts.added.push({