Skip to content

Commit dd297c3

Browse files
committed
feat(ci): select exact PR scan baselines
1 parent 025e1e9 commit dd297c3

8 files changed

Lines changed: 293 additions & 12 deletions

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,8 @@
472472
!/src/commands/ci/fetch-default-org-slug.test.mts
473473
!/src/commands/ci/handle-ci.mts
474474
!/src/commands/ci/handle-ci.test.mts
475+
!/src/commands/ci/select-baseline-scan.mts
476+
!/src/commands/ci/select-baseline-scan.test.mts
475477
!/src/commands/cli.test.mts
476478
!/src/commands/config/cmd-config-auto.mts
477479
!/src/commands/config/cmd-config-auto.test.mts
@@ -999,6 +1001,7 @@
9991001
!/src/commands/scan/output-create-new-scan.test.mts
10001002
!/src/commands/scan/output-delete-scan.mts
10011003
!/src/commands/scan/output-diff-scan.mts
1004+
!/src/commands/scan/output-diff-scan.test.mts
10021005
!/src/commands/scan/output-list-scans.mts
10031006
!/src/commands/scan/output-scan-config-result.mts
10041007
!/src/commands/scan/output-scan-github.mts

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

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
import { readFile } from 'node:fs/promises'
2+
13
import { getDefaultOrgSlug } from './fetch-default-org-slug.mts'
4+
import { selectBaselineScan } from './select-baseline-scan.mts'
25
import constants from '../../constants.mts'
36
import { debugDir, debugFn } from '../../utils/debug.mts'
47
import { envAsString } from '../../utils/env.mts'
@@ -42,6 +45,25 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
4245
const cwd = process.cwd()
4346
const branchName = (await gitBranch(cwd)) || (await detectDefaultBranch(cwd))
4447
const repoName = await getRepoName(cwd)
48+
const pullRequest = detectCiPullRequestNumber()
49+
let baselineScanId: string | undefined
50+
51+
if (pullRequest) {
52+
const baseCommitHash = await detectCiBaseCommitHash()
53+
const baselineCResult = await selectBaselineScan({
54+
branch: envAsString(process.env['GITHUB_BASE_REF']),
55+
commitHash: baseCommitHash,
56+
orgSlug,
57+
repo: repoName,
58+
})
59+
if (!baselineCResult.ok) {
60+
process.exitCode = baselineCResult.code ?? 1
61+
logger.log(serializeResultJson(baselineCResult))
62+
return
63+
}
64+
baselineScanId = baselineCResult.data.id
65+
debugFn('notice', `Selected PR baseline scan ${baselineScanId}`)
66+
}
4567

4668
debugFn(
4769
'notice',
@@ -62,7 +84,8 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
6284
outputKind: 'json',
6385
// When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false.
6486
pendingHead: true,
65-
pullRequest: detectCiPullRequestNumber(),
87+
pullRequest,
88+
baselineScanId,
6689
reach: {
6790
dynamicSbomInference: undefined,
6891
excludePaths: [],
@@ -97,3 +120,22 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
97120
tmp: false,
98121
})
99122
}
123+
124+
export async function detectCiBaseCommitHash(): Promise<string> {
125+
const explicit = envAsString(process.env['GITHUB_BASE_SHA'])
126+
if (explicit) {
127+
return explicit
128+
}
129+
const eventPath = envAsString(process.env['GITHUB_EVENT_PATH'])
130+
if (!eventPath) {
131+
return ''
132+
}
133+
try {
134+
const event = JSON.parse(await readFile(eventPath, 'utf8'))
135+
return typeof event?.pull_request?.base?.sha === 'string'
136+
? event.pull_request.base.sha
137+
: ''
138+
} catch {
139+
return ''
140+
}
141+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { fetchOrgFullScanList } from '../scan/fetch-list-scans.mts'
2+
3+
import type { CResult } from '../../types.mts'
4+
import type { FullScanItem } from '@socketsecurity/sdk'
5+
6+
export type SelectBaselineScanConfig = {
7+
branch: string
8+
commitHash: string
9+
orgSlug: string
10+
repo: string
11+
}
12+
13+
export function findBaselineScan(
14+
scans: FullScanItem[],
15+
commitHash: string,
16+
): FullScanItem | undefined {
17+
return scans.find(scan => scan.commit_hash === commitHash)
18+
}
19+
20+
export async function selectBaselineScan({
21+
branch,
22+
commitHash,
23+
orgSlug,
24+
repo,
25+
}: SelectBaselineScanConfig): Promise<CResult<FullScanItem>> {
26+
if (!commitHash) {
27+
return {
28+
ok: false,
29+
message: 'Cannot select PR scan baseline',
30+
cause: 'The CI checkout does not provide a commit SHA.',
31+
}
32+
}
33+
34+
const scansCResult = await fetchOrgFullScanList({
35+
branch,
36+
commitHash,
37+
direction: 'desc',
38+
from_time: '',
39+
orgSlug,
40+
page: 1,
41+
perPage: 1,
42+
repo,
43+
sort: 'created_at',
44+
})
45+
if (!scansCResult.ok) {
46+
return scansCResult
47+
}
48+
49+
const scan = findBaselineScan(scansCResult.data.results, commitHash)
50+
return scan
51+
? { ok: true, data: scan }
52+
: {
53+
ok: false,
54+
message: 'No matching PR scan baseline found',
55+
cause: `No scan exists for commit ${commitHash} on ${repo}/${branch}. Run a scan for the base commit first.`,
56+
}
57+
}
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import { beforeEach, describe, expect, it, vi } from 'vitest'
2+
3+
import {
4+
findBaselineScan,
5+
selectBaselineScan,
6+
} from './select-baseline-scan.mts'
7+
import { fetchOrgFullScanList } from '../scan/fetch-list-scans.mts'
8+
9+
vi.mock('../scan/fetch-list-scans.mts', () => ({
10+
fetchOrgFullScanList: vi.fn(),
11+
}))
12+
13+
const scan = {
14+
api_url: null,
15+
created_at: '2026-01-01T00:00:00Z',
16+
html_report_url: 'https://socket.dev/report',
17+
id: 'scan-base',
18+
integration_repo_url: null,
19+
integration_type: null,
20+
organization_id: 'org-id',
21+
organization_slug: 'test-org',
22+
repo: 'test-repo',
23+
repository_id: 'repo-id',
24+
repository_slug: 'test-repo',
25+
updated_at: '2026-01-01T00:00:00Z',
26+
commit_hash: 'base-sha',
27+
branch: 'main',
28+
}
29+
30+
describe('selectBaselineScan', () => {
31+
beforeEach(() => {
32+
vi.mocked(fetchOrgFullScanList).mockReset()
33+
})
34+
35+
it('selects the exact commit when the scan list includes nearby scans', () => {
36+
expect(
37+
findBaselineScan(
38+
[{ ...scan, id: 'newer', commit_hash: 'newer-sha' }, scan],
39+
'base-sha',
40+
),
41+
).toEqual(scan)
42+
})
43+
44+
it('selects an exact commit scan from the matching repo and branch query', async () => {
45+
vi.mocked(fetchOrgFullScanList).mockResolvedValue({
46+
ok: true,
47+
data: { results: [scan] },
48+
})
49+
await expect(
50+
selectBaselineScan({
51+
branch: 'main',
52+
commitHash: 'base-sha',
53+
orgSlug: 'test-org',
54+
repo: 'test-repo',
55+
}),
56+
).resolves.toEqual({ ok: true, data: scan })
57+
expect(fetchOrgFullScanList).toHaveBeenCalledWith(
58+
expect.objectContaining({
59+
branch: 'main',
60+
commitHash: 'base-sha',
61+
perPage: 1,
62+
repo: 'test-repo',
63+
}),
64+
)
65+
})
66+
67+
it('fails without a commit SHA', async () => {
68+
await expect(
69+
selectBaselineScan({
70+
branch: 'main',
71+
commitHash: '',
72+
orgSlug: 'test-org',
73+
repo: 'test-repo',
74+
}),
75+
).resolves.toMatchObject({ ok: false })
76+
expect(fetchOrgFullScanList).not.toHaveBeenCalled()
77+
})
78+
79+
it('fails closed when the exact commit has no scan', async () => {
80+
vi.mocked(fetchOrgFullScanList).mockResolvedValue({
81+
ok: true,
82+
data: { results: [scan] },
83+
})
84+
await expect(
85+
selectBaselineScan({
86+
branch: 'main',
87+
commitHash: 'unknown-sha',
88+
orgSlug: 'test-org',
89+
repo: 'test-repo',
90+
}),
91+
).resolves.toMatchObject({
92+
ok: false,
93+
message: 'No matching PR scan baseline found',
94+
})
95+
})
96+
})

‎src/commands/scan/fetch-list-scans.mts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import type { FullScanListResult } from '@socketsecurity/sdk'
77

88
export type FetchOrgFullScanListConfig = {
99
branch: string
10+
commitHash?: string | undefined
1011
direction: string
1112
from_time: string
1213
orgSlug: string
@@ -35,14 +36,25 @@ export async function fetchOrgFullScanList(
3536
}
3637
const sockSdk = sockSdkCResult.data
3738

38-
const { branch, direction, from_time, orgSlug, page, perPage, repo, sort } = {
39+
const {
40+
branch,
41+
commitHash,
42+
direction,
43+
from_time,
44+
orgSlug,
45+
page,
46+
perPage,
47+
repo,
48+
sort,
49+
} = {
3950
__proto__: null,
4051
...config,
4152
} as FetchOrgFullScanListConfig
4253

4354
return await handleApiCall(
4455
sockSdk.listFullScans(orgSlug, {
4556
...(branch ? { branch } : {}),
57+
...(commitHash ? { commit_hash: commitHash } : {}),
4658
...(repo ? { repo } : {}),
4759
...(sort ? { sort: sort as 'name' | 'created_at' } : {}),
4860
...(direction ? { direction: direction as 'asc' | 'desc' } : {}),

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

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { applyFullExcludePaths } from './exclude-paths.mts'
77
import { fetchCreateOrgFullScan } from './fetch-create-org-full-scan.mts'
88
import { fetchSupportedScanFileNames } from './fetch-supported-scan-file-names.mts'
99
import { finalizeTier1Scan } from './finalize-tier1-scan.mts'
10+
import { handleDiffScan } from './handle-diff-scan.mts'
1011
import { handleScanReport } from './handle-scan-report.mts'
1112
import { outputCreateNewScan } from './output-create-new-scan.mts'
1213
import { performReachabilityAnalysis } from './perform-reachability-analysis.mts'
@@ -85,6 +86,7 @@ export type GeneratedScanFiles = {
8586

8687
export type HandleCreateNewScanConfig = {
8788
autoManifest: boolean
89+
baselineScanId?: string | undefined
8890
branchName: string
8991
commitHash: string
9092
commitMessage: string
@@ -116,6 +118,7 @@ export type HandleCreateNewScanConfig = {
116118
async function createNewScan(
117119
{
118120
autoManifest,
121+
baselineScanId,
119122
branchName,
120123
commitHash,
121124
commitMessage,
@@ -471,16 +474,27 @@ async function createNewScan(
471474

472475
if (report && fullScanCResult.ok) {
473476
if (scanId) {
474-
await handleScanReport({
475-
filepath: '-',
476-
fold: constants.FOLD_SETTING_VERSION,
477-
includeLicensePolicy: true,
478-
orgSlug,
479-
outputKind,
480-
reportLevel,
481-
scanId,
482-
short: false,
483-
})
477+
if (baselineScanId) {
478+
await handleDiffScan({
479+
depth: 2,
480+
file: '',
481+
id1: baselineScanId,
482+
id2: scanId,
483+
orgSlug,
484+
outputKind,
485+
})
486+
} else {
487+
await handleScanReport({
488+
filepath: '-',
489+
fold: constants.FOLD_SETTING_VERSION,
490+
includeLicensePolicy: true,
491+
orgSlug,
492+
outputKind,
493+
reportLevel,
494+
scanId,
495+
short: false,
496+
})
497+
}
484498
} else {
485499
await outputCreateNewScan(
486500
{

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,19 @@ export async function outputDiffScan(
5151
return
5252
}
5353

54+
const changedArtifacts = [
55+
...result.data.artifacts.added,
56+
...result.data.artifacts.updated,
57+
...result.data.artifacts.replaced,
58+
]
59+
if (
60+
changedArtifacts.some(artifact =>
61+
artifact.alerts?.some(alert => alert.action === 'error'),
62+
)
63+
) {
64+
process.exitCode = 1
65+
}
66+
5467
const dashboardUrl = result.data.diff_report_url
5568
const dashboardMessage = dashboardUrl
5669
? `\n View this diff scan in the Socket dashboard: ${colors.cyan(dashboardUrl)}`

0 commit comments

Comments
 (0)