From b4ef271862acb76fdae7c3ba351c5509e99fdb7b Mon Sep 17 00:00:00 2001 From: jdalton Date: Wed, 25 Nov 2026 13:40:03 -0500 Subject: [PATCH] feat(ci): select exact PR scan baselines --- .gitignore | 4 +- src/commands/ci/handle-ci.mts | 19 ++++ src/commands/ci/select-baseline-scan.mts | 57 +++++++++++ src/commands/ci/select-baseline-scan.test.mts | 96 +++++++++++++++++++ src/commands/scan/fetch-list-scans.mts | 14 ++- src/commands/scan/handle-create-new-scan.mts | 34 +++++-- src/commands/scan/output-diff-scan.mts | 13 +++ src/commands/scan/output-diff-scan.test.mts | 44 +++++++++ 8 files changed, 269 insertions(+), 12 deletions(-) create mode 100644 src/commands/ci/select-baseline-scan.mts create mode 100644 src/commands/ci/select-baseline-scan.test.mts create mode 100644 src/commands/scan/output-diff-scan.test.mts diff --git a/.gitignore b/.gitignore index cecf2671d7..3539811ae4 100644 --- a/.gitignore +++ b/.gitignore @@ -475,8 +475,9 @@ !/src/commands/ci/fetch-default-org-slug.test.mts !/src/commands/ci/handle-ci.mts !/src/commands/ci/handle-ci.test.mts -!/src/commands/ci/detect-ci-pull-request-context.mts !/src/commands/ci/detect-ci-pull-request-context.test.mts +!/src/commands/ci/select-baseline-scan.mts +!/src/commands/ci/select-baseline-scan.test.mts !/src/commands/cli.test.mts !/src/commands/config/cmd-config-auto.mts !/src/commands/config/cmd-config-auto.test.mts @@ -1004,6 +1005,7 @@ !/src/commands/scan/output-create-new-scan.test.mts !/src/commands/scan/output-delete-scan.mts !/src/commands/scan/output-diff-scan.mts +!/src/commands/scan/output-diff-scan.test.mts !/src/commands/scan/output-list-scans.mts !/src/commands/scan/output-scan-config-result.mts !/src/commands/scan/output-scan-github.mts diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index 6e0ad3c838..70030ffe7b 100644 --- a/src/commands/ci/handle-ci.mts +++ b/src/commands/ci/handle-ci.mts @@ -1,5 +1,6 @@ import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts' import { getDefaultOrgSlug } from './fetch-default-org-slug.mts' +import { selectBaselineScan } from './select-baseline-scan.mts' import constants from '../../constants.mts' import { debugDir, debugFn } from '../../utils/debug.mts' import { @@ -31,6 +32,23 @@ export async function handleCi(autoManifest: boolean): Promise { const cwd = process.cwd() const branchName = (await gitBranch(cwd)) || (await detectDefaultBranch(cwd)) const repoName = await getRepoName(cwd) + let baselineScanId: string | undefined + + if (pullRequest) { + const baselineCResult = await selectBaselineScan({ + branch: pullRequestContext.baseBranch ?? '', + commitHash: pullRequestContext.baseCommitHash ?? '', + orgSlug, + repo: repoName, + }) + if (!baselineCResult.ok) { + process.exitCode = baselineCResult.code ?? 1 + logger.log(serializeResultJson(baselineCResult)) + return + } + baselineScanId = baselineCResult.data.id + debugFn('notice', `Selected PR baseline scan ${baselineScanId}`) + } debugFn( 'notice', @@ -52,6 +70,7 @@ export async function handleCi(autoManifest: boolean): Promise { // When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false. pendingHead: true, pullRequest, + baselineScanId, reach: { dynamicSbomInference: undefined, excludePaths: [], diff --git a/src/commands/ci/select-baseline-scan.mts b/src/commands/ci/select-baseline-scan.mts new file mode 100644 index 0000000000..86d01af39d --- /dev/null +++ b/src/commands/ci/select-baseline-scan.mts @@ -0,0 +1,57 @@ +import { fetchOrgFullScanList } from '../scan/fetch-list-scans.mts' + +import type { CResult } from '../../types.mts' +import type { FullScanItem } from '@socketsecurity/sdk' + +export type SelectBaselineScanConfig = { + branch: string + commitHash: string + orgSlug: string + repo: string +} + +export function findBaselineScan( + scans: FullScanItem[], + commitHash: string, +): FullScanItem | undefined { + return scans.find(scan => scan.commit_hash === commitHash) +} + +export async function selectBaselineScan({ + branch, + commitHash, + orgSlug, + repo, +}: SelectBaselineScanConfig): Promise> { + if (!commitHash) { + return { + ok: false, + message: 'Cannot select PR scan baseline', + cause: 'The CI checkout does not provide a commit SHA.', + } + } + + const scansCResult = await fetchOrgFullScanList({ + branch, + commitHash, + direction: 'desc', + from_time: '', + orgSlug, + page: 1, + perPage: 1, + repo, + sort: 'created_at', + }) + if (!scansCResult.ok) { + return scansCResult + } + + const scan = findBaselineScan(scansCResult.data.results, commitHash) + return scan + ? { ok: true, data: scan } + : { + ok: false, + message: 'No matching PR scan baseline found', + cause: `No scan exists for commit ${commitHash} on ${repo}/${branch}. Run a scan for the base commit first.`, + } +} diff --git a/src/commands/ci/select-baseline-scan.test.mts b/src/commands/ci/select-baseline-scan.test.mts new file mode 100644 index 0000000000..ac114103bc --- /dev/null +++ b/src/commands/ci/select-baseline-scan.test.mts @@ -0,0 +1,96 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { + findBaselineScan, + selectBaselineScan, +} from './select-baseline-scan.mts' +import { fetchOrgFullScanList } from '../scan/fetch-list-scans.mts' + +vi.mock('../scan/fetch-list-scans.mts', () => ({ + fetchOrgFullScanList: vi.fn(), +})) + +const scan = { + api_url: null, + created_at: '2026-01-01T00:00:00Z', + html_report_url: 'https://socket.dev/report', + id: 'scan-base', + integration_repo_url: null, + integration_type: null, + organization_id: 'org-id', + organization_slug: 'test-org', + repo: 'test-repo', + repository_id: 'repo-id', + repository_slug: 'test-repo', + updated_at: '2026-01-01T00:00:00Z', + commit_hash: 'base-sha', + branch: 'main', +} + +describe('selectBaselineScan', () => { + beforeEach(() => { + vi.mocked(fetchOrgFullScanList).mockReset() + }) + + it('selects the exact commit when the scan list includes nearby scans', () => { + expect( + findBaselineScan( + [{ ...scan, id: 'newer', commit_hash: 'newer-sha' }, scan], + 'base-sha', + ), + ).toEqual(scan) + }) + + it('selects an exact commit scan from the matching repo and branch query', async () => { + vi.mocked(fetchOrgFullScanList).mockResolvedValue({ + ok: true, + data: { results: [scan] }, + }) + await expect( + selectBaselineScan({ + branch: 'main', + commitHash: 'base-sha', + orgSlug: 'test-org', + repo: 'test-repo', + }), + ).resolves.toEqual({ ok: true, data: scan }) + expect(fetchOrgFullScanList).toHaveBeenCalledWith( + expect.objectContaining({ + branch: 'main', + commitHash: 'base-sha', + perPage: 1, + repo: 'test-repo', + }), + ) + }) + + it('fails without a commit SHA', async () => { + await expect( + selectBaselineScan({ + branch: 'main', + commitHash: '', + orgSlug: 'test-org', + repo: 'test-repo', + }), + ).resolves.toMatchObject({ ok: false }) + expect(fetchOrgFullScanList).not.toHaveBeenCalled() + }) + + it('fails closed when the exact commit has no scan', async () => { + vi.mocked(fetchOrgFullScanList).mockResolvedValue({ + ok: true, + data: { results: [scan] }, + }) + await expect( + selectBaselineScan({ + branch: 'main', + commitHash: 'unknown-sha', + orgSlug: 'test-org', + repo: 'test-repo', + }), + ).resolves.toMatchObject({ + ok: false, + message: 'No matching PR scan baseline found', + }) + }) +}) diff --git a/src/commands/scan/fetch-list-scans.mts b/src/commands/scan/fetch-list-scans.mts index 442825aeab..c6d24f32c2 100644 --- a/src/commands/scan/fetch-list-scans.mts +++ b/src/commands/scan/fetch-list-scans.mts @@ -7,6 +7,7 @@ import type { FullScanListResult } from '@socketsecurity/sdk' export type FetchOrgFullScanListConfig = { branch: string + commitHash?: string | undefined direction: string from_time: string orgSlug: string @@ -35,7 +36,17 @@ export async function fetchOrgFullScanList( } const sockSdk = sockSdkCResult.data - const { branch, direction, from_time, orgSlug, page, perPage, repo, sort } = { + const { + branch, + commitHash, + direction, + from_time, + orgSlug, + page, + perPage, + repo, + sort, + } = { __proto__: null, ...config, } as FetchOrgFullScanListConfig @@ -43,6 +54,7 @@ export async function fetchOrgFullScanList( return await handleApiCall( sockSdk.listFullScans(orgSlug, { ...(branch ? { branch } : {}), + ...(commitHash ? { commit_hash: commitHash } : {}), ...(repo ? { repo } : {}), ...(sort ? { sort: sort as 'name' | 'created_at' } : {}), ...(direction ? { direction: direction as 'asc' | 'desc' } : {}), diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index d9af8e8cea..2b7639a23d 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -7,6 +7,7 @@ import { applyFullExcludePaths } from './exclude-paths.mts' import { fetchCreateOrgFullScan } from './fetch-create-org-full-scan.mts' import { fetchSupportedScanFileNames } from './fetch-supported-scan-file-names.mts' import { finalizeTier1Scan } from './finalize-tier1-scan.mts' +import { handleDiffScan } from './handle-diff-scan.mts' import { handleScanReport } from './handle-scan-report.mts' import { outputCreateNewScan } from './output-create-new-scan.mts' import { performReachabilityAnalysis } from './perform-reachability-analysis.mts' @@ -85,6 +86,7 @@ export type GeneratedScanFiles = { export type HandleCreateNewScanConfig = { autoManifest: boolean + baselineScanId?: string | undefined branchName: string commitHash: string commitMessage: string @@ -116,6 +118,7 @@ export type HandleCreateNewScanConfig = { async function createNewScan( { autoManifest, + baselineScanId, branchName, commitHash, commitMessage, @@ -471,16 +474,27 @@ async function createNewScan( if (report && fullScanCResult.ok) { if (scanId) { - await handleScanReport({ - filepath: '-', - fold: constants.FOLD_SETTING_VERSION, - includeLicensePolicy: true, - orgSlug, - outputKind, - reportLevel, - scanId, - short: false, - }) + if (baselineScanId) { + await handleDiffScan({ + depth: 2, + file: '', + id1: baselineScanId, + id2: scanId, + orgSlug, + outputKind, + }) + } else { + await handleScanReport({ + filepath: '-', + fold: constants.FOLD_SETTING_VERSION, + includeLicensePolicy: true, + orgSlug, + outputKind, + reportLevel, + scanId, + short: false, + }) + } } else { await outputCreateNewScan( { diff --git a/src/commands/scan/output-diff-scan.mts b/src/commands/scan/output-diff-scan.mts index 5c51ee54d1..fa813f8d7a 100644 --- a/src/commands/scan/output-diff-scan.mts +++ b/src/commands/scan/output-diff-scan.mts @@ -51,6 +51,19 @@ export async function outputDiffScan( return } + const changedArtifacts = [ + ...result.data.artifacts.added, + ...result.data.artifacts.updated, + ...result.data.artifacts.replaced, + ] + if ( + changedArtifacts.some(artifact => + artifact.alerts?.some(alert => alert.action === 'error'), + ) + ) { + process.exitCode = 1 + } + const dashboardUrl = result.data.diff_report_url const dashboardMessage = dashboardUrl ? `\n View this diff scan in the Socket dashboard: ${colors.cyan(dashboardUrl)}` diff --git a/src/commands/scan/output-diff-scan.test.mts b/src/commands/scan/output-diff-scan.test.mts new file mode 100644 index 0000000000..33864ea7c6 --- /dev/null +++ b/src/commands/scan/output-diff-scan.test.mts @@ -0,0 +1,44 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { outputDiffScan } from './output-diff-scan.mts' + +vi.mock('../../utils/logger.mts', () => ({ + logger: { error: vi.fn(), fail: vi.fn(), info: vi.fn(), log: vi.fn() }, +})) + +const diff = { + after: { id: 'head' }, + artifacts: { + added: [ + { + type: 'npm', + name: 'new-package', + version: '1.0.0', + alerts: [{ action: 'error', type: 'test-alert', key: 'alert-1' }], + }, + ], + removed: [], + replaced: [], + unchanged: [], + updated: [], + }, + before: { id: 'base' }, + directDependenciesChanged: false, + diff_report_url: '', +} + +describe('outputDiffScan', () => { + afterEach(() => { + process.exitCode = 0 + vi.clearAllMocks() + }) + + it('fails for new blocking findings in a PR diff', async () => { + await outputDiffScan({ ok: true, data: diff } as never, { + depth: 0, + file: '', + outputKind: 'json', + }) + expect(process.exitCode).toBe(1) + }) +})