Skip to content

Commit 7244a0f

Browse files
committed
feat(python-cli-parity): add strict blocking to socket ci
1 parent 95becc5 commit 7244a0f

11 files changed

Lines changed: 162 additions & 34 deletions

‎docs/commands/ci.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,16 @@ nonzero status if the scan fails your security policy.
88
socket ci
99
```
1010

11+
On pull requests, use `--strict-blocking` to fail when a blocking alert is
12+
present on an unchanged dependency as well as when the PR introduces one:
13+
14+
```sh
15+
socket ci --strict-blocking
16+
```
17+
18+
Strict blocking is off by default. `--disable-blocking` takes precedence and
19+
keeps findings from failing the job.
20+
1121
Use `--auto-manifest` to include locally generated manifests for supported
1222
projects. Run `socket ci --help` for all options.
1323

‎src/commands/ci/cmd-ci.mts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ const config: CliCommandConfig = {
3434
description:
3535
'Return success for findings and infrastructure failures, but keep usage errors non-zero.',
3636
},
37+
strictBlocking: {
38+
type: 'boolean',
39+
default: false,
40+
description:
41+
'Fail for existing blocking alerts as well as alerts introduced by this PR.',
42+
},
3743
exitCodeOnApiError: {
3844
type: 'number',
3945
default: 3,
@@ -58,7 +64,8 @@ const config: CliCommandConfig = {
5864
Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2
5965
for usage errors, 3 for infrastructure errors, and 130 for interruption.
6066
--disable-blocking returns 0 for findings and runtime failures, but not
61-
usage errors. --exit-code-on-api-error changes the API failure code.
67+
usage errors. --strict-blocking also fails for blocking alerts on unchanged
68+
dependencies. --exit-code-on-api-error changes the API failure code.
6269
6370
The --auto-manifest flag does the same as the one from \`socket scan create\`
6471
but is not enabled by default since the CI is less likely to be set up with
@@ -69,6 +76,7 @@ const config: CliCommandConfig = {
6976
$ ${command}
7077
$ ${command} --auto-manifest
7178
$ ${command} --disable-blocking
79+
$ ${command} --strict-blocking
7280
$ ${command} --exit-code-on-api-error 5
7381
`,
7482
}
@@ -121,5 +129,9 @@ async function run(
121129
return
122130
}
123131

124-
await handleCi(Boolean(cli.flags['autoManifest']), jsonFormat === 'python-v1')
132+
await handleCi(
133+
Boolean(cli.flags['autoManifest']),
134+
jsonFormat === 'python-v1',
135+
Boolean(cli.flags['strictBlocking']),
136+
)
125137
}

‎src/commands/ci/cmd-ci.test.mts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,15 @@ describe('socket ci', async () => {
2727
--disable-blocking Return success for findings and infrastructure failures, but keep usage errors non-zero.
2828
--exit-code-on-api-error Exit code for Socket API errors (default: 3). Ignored with --disable-blocking.
2929
--json-format Select a versioned JSON payload. Supported: python-v1 (pull request comparisons only).
30+
--strict-blocking Fail for existing blocking alerts as well as alerts introduced by this PR.
3031
3132
This command is intended to use in CI runs to allow automated systems to
3233
accept or reject a current build. It will use the default org of the
3334
Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2
3435
for usage errors, 3 for infrastructure errors, and 130 for interruption.
3536
--disable-blocking returns 0 for findings and runtime failures, but not
36-
usage errors. --exit-code-on-api-error changes the API failure code.
37+
usage errors. --strict-blocking also fails for blocking alerts on unchanged
38+
dependencies. --exit-code-on-api-error changes the API failure code.
3739
3840
The --auto-manifest flag does the same as the one from \`socket scan create\`
3941
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 () => {
4446
$ socket ci
4547
$ socket ci --auto-manifest
4648
$ socket ci --disable-blocking
49+
$ socket ci --strict-blocking
4750
$ socket ci --exit-code-on-api-error 5"
4851
`,
4952
)

‎src/commands/ci/handle-ci.mts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import type { PythonDiffJsonContext } from '../scan/python-diff-json.mts'
3838
export async function handleCi(
3939
autoManifest: boolean,
4040
pythonJsonFormat = false,
41+
strictBlocking = false,
4142
): Promise<void> {
4243
debugFn('notice', 'Starting CI scan')
4344
debugDir('inspect', { autoManifest, pythonJsonFormat })
@@ -73,6 +74,7 @@ export async function handleCi(
7374
: pullRequestContext.provider === 'azure'
7475
? process.env['BUILD_SOURCEVERSION'] || null
7576
: null,
77+
strictBlocking,
7678
}
7779
if (pythonJsonFormat && !pullRequest) {
7880
setCiExitCode('usage')
@@ -175,6 +177,7 @@ export async function handleCi(
175177
autoManifest,
176178
branchName,
177179
cwd,
180+
strictBlocking,
178181
onDiffOutcome,
179182
orgSlug,
180183
pullRequestContext,
@@ -195,10 +198,12 @@ async function runCiScan({
195198
pythonJsonContext,
196199
pythonJsonFormat,
197200
repoName,
201+
strictBlocking,
198202
}: {
199203
autoManifest: boolean
200204
branchName: string
201205
cwd: string
206+
strictBlocking: boolean
202207
onDiffOutcome: (outcome: {
203208
blocking: boolean
204209
incomplete: boolean
@@ -260,6 +265,7 @@ async function runCiScan({
260265
orgSlug,
261266
outputKind: 'json',
262267
pythonJsonFormat,
268+
strictBlocking,
263269
pythonJsonContext,
264270
// When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false.
265271
pendingHead: true,

‎src/commands/ci/handle-ci.test.mts‎

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,14 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun
143143
vi.stubEnv('SOCKET_CLI_DISABLE_OVERVIEW_COMMENT', '')
144144
vi.stubEnv('SOCKET_CLI_DISABLE_SECURITY_COMMENT', '')
145145
vi.resetModules()
146+
vi.doMock('../../utils/spawn.mts', () => ({
147+
spawn: vi.fn(async (_command: string, args: string[]) => ({
148+
stdout:
149+
args?.[0] === 'symbolic-ref'
150+
? 'feature-branch'
151+
: 'git@github.com:example/project.git',
152+
})),
153+
}))
146154
vi.doMock('./fetch-default-org-slug.mts', () => ({
147155
getDefaultOrgSlug: async () => ({ ok: true, data: 'example' }),
148156
}))
@@ -169,7 +177,21 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun
169177
id: 'diff-id',
170178
before_full_scan: { id: 'base' },
171179
after_full_scan: { id: 'test-scan' },
172-
artifacts: { added: [], updated: [], replaced: [] },
180+
artifacts: {
181+
added: [],
182+
updated: [],
183+
replaced: [],
184+
unchanged: [
185+
{
186+
type: 'npm',
187+
name: 'left-pad',
188+
version: '1.0.0',
189+
alerts: [
190+
{ action: 'error', type: 'test-alert', key: 'alert-1' },
191+
],
192+
},
193+
],
194+
},
173195
html_url: null,
174196
},
175197
},
@@ -191,7 +213,12 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun
191213
}),
192214
}))
193215
const { handleCi } = await import('./handle-ci.mts')
216+
process.exitCode = 0
194217
await handleCi(false)
218+
expect(process.exitCode).toBe(0)
219+
await handleCi(false, false, true)
220+
expect(process.exitCode).toBe(1)
221+
process.exitCode = 0
195222
expect(comments.map(c => c.body)).toEqual([
196223
expect.stringContaining('API overview'),
197224
expect.stringContaining('API alerts'),
@@ -201,13 +228,22 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun
201228
await handleCi(false)
202229
vi.stubEnv('GITHUB_REF', 'refs/heads/main')
203230
await handleCi(false)
204-
expect(fetchComments).toHaveBeenCalledTimes(3)
205-
expect(writes).toEqual(['POST', 'POST', 'PATCH', 'PATCH', 'PATCH'])
231+
expect(fetchComments).toHaveBeenCalledTimes(4)
232+
expect(writes).toEqual([
233+
'POST',
234+
'POST',
235+
'PATCH',
236+
'PATCH',
237+
'PATCH',
238+
'PATCH',
239+
'PATCH',
240+
])
206241
expect(comments).toHaveLength(2)
207242
} finally {
208243
vi.unstubAllEnvs()
209244
vi.doUnmock('./fetch-default-org-slug.mts')
210245
vi.doUnmock('./select-baseline-scan.mts')
246+
vi.doUnmock('../../utils/spawn.mts')
211247
vi.doUnmock('../../utils/api.mts')
212248
vi.doUnmock('../scan/fetch-diff-scan.mts')
213249
vi.doUnmock('../scan/handle-scan-report.mts')

‎src/commands/scan/diff-scan-verdict.mts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,16 @@ export function getDiffScanBlocking(
2020
)
2121
}
2222

23-
export function getDiffScanVerdict(diffScan: DiffScanData['diff_scan']): {
23+
export function getDiffScanVerdict(
24+
diffScan: DiffScanData['diff_scan'],
25+
strictBlocking = false,
26+
): {
2427
blocking: boolean
2528
incomplete: boolean
2629
reportUrl: string | null
2730
} {
2831
return {
29-
blocking: getDiffScanBlocking(diffScan),
32+
blocking: getDiffScanBlocking(diffScan, strictBlocking),
3033
incomplete: diffScan.incomplete === true,
3134
reportUrl: diffScan.html_url,
3235
}

‎src/commands/scan/diff-scan-verdict.test.mts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,17 @@ describe('getDiffScanBlocking', () => {
6262
reportUrl: 'https://dashboard.test/diff/diff-id',
6363
})
6464
})
65+
66+
it('includes unchanged blockers in the strict provider verdict', () => {
67+
const diff = {
68+
...cleanDiff,
69+
artifacts: {
70+
...cleanDiff.artifacts,
71+
unchanged: [{ alerts: [{ action: 'error' }] }],
72+
},
73+
} as unknown as DiffScanData['diff_scan']
74+
75+
expect(getDiffScanVerdict(diff, true)).toMatchObject({ blocking: true })
76+
expect(getDiffScanVerdict(diff)).toMatchObject({ blocking: false })
77+
})
6578
})

‎src/commands/scan/handle-create-new-scan.mts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ import {
4343
import { buildToolsFor } from '../manifest/scripts/build-tool.mts'
4444

4545
import type { ReachabilityFallback } from './output-create-new-scan.mts'
46-
import type { PythonDiffJsonContext } from './python-diff-json.mts'
4746
import type { ReachabilityOptions } from './perform-reachability-analysis.mts'
47+
import type { PythonDiffJsonContext } from './python-diff-json.mts'
4848
import type { REPORT_LEVEL } from './types.mts'
4949
import type { OutputKind } from '../../types.mts'
5050
import type { FactsOnlyTypes } from '../../utils/coana.mts'
@@ -119,6 +119,7 @@ export type HandleCreateNewScanConfig = {
119119
| undefined
120120
pythonJsonFormat?: boolean | undefined
121121
pythonJsonContext?: PythonDiffJsonContext | undefined
122+
strictBlocking?: boolean | undefined
122123
branchName: string
123124
commitHash: string
124125
commitMessage: string
@@ -207,6 +208,7 @@ async function createNewScan(
207208
repoName,
208209
report,
209210
reportLevel,
211+
strictBlocking = false,
210212
targets,
211213
tmp,
212214
workspace,
@@ -604,6 +606,7 @@ async function createNewScan(
604606
outputKind,
605607
pythonJsonFormat,
606608
pythonJsonContext,
609+
strictBlocking,
607610
})
608611
} else {
609612
await handleScanReport({

‎src/commands/scan/handle-diff-scan.mts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ export async function handlePrDiffScan({
5050
outputKind,
5151
pythonJsonContext = {},
5252
pythonJsonFormat = false,
53+
strictBlocking = false,
5354
}: {
5455
id1: string
5556
id2: string
@@ -67,20 +68,21 @@ export async function handlePrDiffScan({
6768
outputKind: OutputKind
6869
pythonJsonFormat?: boolean | undefined
6970
pythonJsonContext?: PythonDiffJsonContext | undefined
71+
strictBlocking?: boolean | undefined
7072
}): Promise<void> {
7173
const result = await fetchDiffScan({ id1, id2, orgSlug })
7274
await outputDiffScan(result, {
7375
depth: 2,
7476
file: '',
7577
outputKind,
76-
strictBlocking: false,
78+
strictBlocking,
7779
pythonJsonFormat,
7880
pythonJsonContext,
7981
})
8082
if (result.ok) {
8183
await onDiffReport?.(
8284
result.data.diff_scan.id,
83-
getDiffScanVerdict(result.data.diff_scan),
85+
getDiffScanVerdict(result.data.diff_scan, strictBlocking),
8486
)
8587
}
8688
}

‎src/commands/scan/output-diff-scan.test.mts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
22

33
import { handlePrDiffScan } from './handle-diff-scan.mts'
44
import { outputDiffScan } from './output-diff-scan.mts'
5+
import { logger } from '../../utils/logger.mts'
56

67
const fetchDiffScan = vi.hoisted(() => vi.fn())
78

@@ -73,6 +74,39 @@ describe('outputDiffScan strict blocking', () => {
7374
expect(process.exitCode).toBe(1)
7475
})
7576

77+
it('applies strict blocking to the PR gate, provider outcome, and Python JSON', async () => {
78+
fetchDiffScan.mockResolvedValue({
79+
ok: true,
80+
data: {
81+
diff_scan: { ...diff.diff_scan, id: 'diff-id' },
82+
},
83+
})
84+
const onDiffReport = vi.fn()
85+
86+
await handlePrDiffScan({
87+
id1: 'before',
88+
id2: 'after',
89+
onDiffReport,
90+
orgSlug: 'example',
91+
outputKind: 'json',
92+
pythonJsonFormat: true,
93+
strictBlocking: true,
94+
})
95+
96+
expect(process.exitCode).toBe(1)
97+
expect(onDiffReport).toHaveBeenCalledWith('diff-id', {
98+
blocking: true,
99+
incomplete: false,
100+
reportUrl: '',
101+
})
102+
expect(logger.log).toHaveBeenCalledWith(
103+
expect.stringContaining('"decision": "fail"'),
104+
)
105+
expect(logger.log).toHaveBeenCalledWith(
106+
expect.stringContaining('"unchanged_alerts": ['),
107+
)
108+
})
109+
76110
it('fails for new blocking alerts in ordinary diff mode', async () => {
77111
const changed = structuredClone(diff)
78112
changed.diff_scan.artifacts.added.push({

0 commit comments

Comments
 (0)