Skip to content

Commit 8dfdee2

Browse files
committed
feat(ci): select exact PR scan baselines
1 parent d57a500 commit 8dfdee2

10 files changed

Lines changed: 372 additions & 30 deletions

‎.gitignore‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,8 +367,9 @@
367367
!/src/commands/ci/fetch-default-org-slug.test.mts
368368
!/src/commands/ci/handle-ci.mts
369369
!/src/commands/ci/handle-ci.test.mts
370-
!/src/commands/ci/detect-ci-pull-request-context.mts
371370
!/src/commands/ci/detect-ci-pull-request-context.test.mts
371+
!/src/commands/ci/select-baseline-scan.mts
372+
!/src/commands/ci/select-baseline-scan.test.mts
372373
!/src/commands/cli.test.mts
373374
!/src/commands/config/cmd-config-auto.mts
374375
!/src/commands/config/cmd-config-auto.test.mts

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts'
22
import { getDefaultOrgSlug } from './fetch-default-org-slug.mts'
3+
import { selectBaselineScan } from './select-baseline-scan.mts'
34
import constants from '../../constants.mts'
45
import { setCiExitCode } from '../../utils/ci-exit-code.mts'
56
import { debugDir, debugFn } from '../../utils/debug.mts'
@@ -32,6 +33,23 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
3233
const cwd = process.cwd()
3334
const branchName = (await gitBranch(cwd)) || (await detectDefaultBranch(cwd))
3435
const repoName = await getRepoName(cwd)
36+
let baselineScanId: string | undefined
37+
38+
if (pullRequest) {
39+
const baselineCResult = await selectBaselineScan({
40+
branch: pullRequestContext.baseBranch ?? '',
41+
commitHash: pullRequestContext.baseCommitHash ?? '',
42+
orgSlug,
43+
repo: repoName,
44+
})
45+
if (!baselineCResult.ok) {
46+
process.exitCode = baselineCResult.code ?? 1
47+
logger.log(serializeResultJson(baselineCResult))
48+
return
49+
}
50+
baselineScanId = baselineCResult.data.id
51+
debugFn('notice', `Selected PR baseline scan ${baselineScanId}`)
52+
}
3553

3654
debugFn(
3755
'notice',
@@ -53,6 +71,7 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
5371
// When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false.
5472
pendingHead: true,
5573
pullRequest,
74+
baselineScanId,
5675
reach: {
5776
dynamicSbomInference: undefined,
5877
excludePaths: [],
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-diff-scan.mts‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
import { queryApiSafeJson } from '../../utils/api.mts'
1+
import { handleApiCall, queryApiSafeJson } from '../../utils/api.mts'
22
import { logger } from '../../utils/logger.mts'
3+
import { setupSdk } from '../../utils/sdk.mts'
34

45
import type { CResult } from '../../types.mts'
5-
import type { SocketSdkSuccessResult } from '@socketsecurity/sdk'
6+
import type { SocketSdkData, SocketSdkSuccessResult } from '@socketsecurity/sdk'
67

78
export async function fetchDiffScan({
89
id1,
@@ -24,3 +25,50 @@ export async function fetchDiffScan({
2425
'a scan diff',
2526
)
2627
}
28+
29+
type PrDiffScanData = Extract<
30+
SocketSdkData<'getDiffScanById'>,
31+
{ diff_scan: unknown }
32+
>
33+
34+
export async function fetchPrDiffScan({
35+
id1,
36+
id2,
37+
orgSlug,
38+
}: {
39+
id1: string
40+
id2: string
41+
orgSlug: string
42+
}): Promise<CResult<PrDiffScanData>> {
43+
const sdk = await setupSdk()
44+
if (!sdk.ok) {
45+
return sdk
46+
}
47+
48+
const created = await handleApiCall(
49+
sdk.data.createOrgDiffScanFromIds(orgSlug, {
50+
before: id1,
51+
after: id2,
52+
on_duplicate: 'update',
53+
}),
54+
{ description: 'creating the pull request diff scan' },
55+
)
56+
if (!created.ok) {
57+
return created
58+
}
59+
60+
const result = await handleApiCall(
61+
sdk.data.getDiffScanById(orgSlug, created.data.diff_scan.id),
62+
{ description: 'the pull request diff scan' },
63+
)
64+
if (!result.ok) {
65+
return result
66+
}
67+
return 'diff_scan' in result.data
68+
? { ok: true, data: result.data }
69+
: {
70+
ok: false,
71+
message: 'Pull request diff scan is still pending',
72+
cause: `Diff scan ${result.data.id} is ${result.data.status}.`,
73+
}
74+
}

‎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: 22 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 { handlePrDiffScan } 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'
@@ -91,6 +92,7 @@ export type GeneratedScanFiles = {
9192

9293
export type HandleCreateNewScanConfig = {
9394
autoManifest: boolean
95+
baselineScanId?: string | undefined
9496
branchName: string
9597
commitHash: string
9698
commitMessage: string
@@ -125,6 +127,7 @@ export type HandleCreateNewScanConfig = {
125127
async function createNewScan(
126128
{
127129
autoManifest,
130+
baselineScanId,
128131
branchName,
129132
commitHash,
130133
commitMessage,
@@ -474,16 +477,25 @@ async function createNewScan(
474477

475478
if (report && fullScanCResult.ok) {
476479
if (scanId) {
477-
await handleScanReport({
478-
filepath: '-',
479-
fold: constants.FOLD_SETTING_VERSION,
480-
includeLicensePolicy: true,
481-
orgSlug,
482-
outputKind,
483-
reportLevel,
484-
scanId,
485-
short: false,
486-
})
480+
if (baselineScanId) {
481+
await handlePrDiffScan({
482+
id1: baselineScanId,
483+
id2: scanId,
484+
orgSlug,
485+
outputKind,
486+
})
487+
} else {
488+
await handleScanReport({
489+
filepath: '-',
490+
fold: constants.FOLD_SETTING_VERSION,
491+
includeLicensePolicy: true,
492+
orgSlug,
493+
outputKind,
494+
reportLevel,
495+
scanId,
496+
short: false,
497+
})
498+
}
487499
} else {
488500
await outputCreateNewScan(
489501
{

0 commit comments

Comments
 (0)