diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1e31f350b..795ec0750 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -253,13 +253,13 @@ jobs: - name: Install dependencies • Bash if: matrix.shell == 'bash' shell: bash - run: pnpm install --loglevel error + run: pnpm install --loglevel error ${{ runner.os == 'Windows' && '--config.enable-global-virtual-store=false' || '' }} - &test-pwsh-dependencies name: Install dependencies • PowerShell if: matrix.shell == 'pwsh' shell: pwsh - run: pnpm install --loglevel error + run: pnpm install --loglevel error --config.enable-global-virtual-store=false - name: Run full unit and integration suite • Bash if: matrix.suite == 'regular' && matrix.shell == 'bash' diff --git a/.gitignore b/.gitignore index a3dfeb252..da68a5eee 100644 --- a/.gitignore +++ b/.gitignore @@ -367,8 +367,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 diff --git a/package.json b/package.json index 00a66ce0e..8d03c3bfe 100644 --- a/package.json +++ b/package.json @@ -99,7 +99,7 @@ "test:integration": "node scripts/test/integration.mts", "test:integration:ci": "pnpm run test:integration --use-built-dist --bail=1", "test:prepare": "dotenvx -q run -f .env.test -- pnpm run test:prepare:build", - "test:prepare:build": "pnpm run build && del-cli 'test/**/node_modules'", + "test:prepare:build": "pnpm run build:dist:src && del-cli 'test/**/node_modules'", "test:sea": "node scripts/test/native.mts", "test:unit": "dotenvx -q run -f .env.test -- vitest run --config .config/vitest.config.mts", "test:unit:ci": "pnpm run test:unit --bail=1", diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index 624668832..1dba5cc05 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 { setCiExitCode } from '../../utils/ci-exit-code.mts' import { debugDir, debugFn } from '../../utils/debug.mts' @@ -32,6 +33,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', @@ -53,6 +71,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 000000000..86d01af39 --- /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 000000000..ac114103b --- /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/manifest/bazel/python-shim.test.mts b/src/commands/manifest/bazel/python-shim.test.mts index cec4feaac..cc213e314 100644 --- a/src/commands/manifest/bazel/python-shim.test.mts +++ b/src/commands/manifest/bazel/python-shim.test.mts @@ -85,6 +85,7 @@ describe('provisionPythonShim', () => { ), ).rejects.toThrow(/python/) }, + 30_000, ) it.skipIf(!python || process.platform === 'win32')( diff --git a/src/commands/scan/fetch-list-scans.mts b/src/commands/scan/fetch-list-scans.mts index 442825aea..c6d24f32c 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 fe272139a..e06f466be 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 { handlePrDiffScan } 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' @@ -91,6 +92,7 @@ export type GeneratedScanFiles = { export type HandleCreateNewScanConfig = { autoManifest: boolean + baselineScanId?: string | undefined branchName: string commitHash: string commitMessage: string @@ -125,6 +127,7 @@ export type HandleCreateNewScanConfig = { async function createNewScan( { autoManifest, + baselineScanId, branchName, commitHash, commitMessage, @@ -475,16 +478,25 @@ 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 handlePrDiffScan({ + 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/handle-diff-scan.mts b/src/commands/scan/handle-diff-scan.mts index 215967d0f..db96e0f50 100644 --- a/src/commands/scan/handle-diff-scan.mts +++ b/src/commands/scan/handle-diff-scan.mts @@ -33,3 +33,23 @@ export async function handleDiffScan({ strictBlocking, }) } + +export async function handlePrDiffScan({ + id1, + id2, + orgSlug, + outputKind, +}: { + id1: string + id2: string + orgSlug: string + outputKind: OutputKind +}): Promise { + const result = await fetchDiffScan({ id1, id2, orgSlug }) + await outputDiffScan(result, { + depth: 2, + file: '', + outputKind, + strictBlocking: false, + }) +} diff --git a/src/commands/scan/output-diff-scan.mts b/src/commands/scan/output-diff-scan.mts index d07f8b96a..d40f236bf 100644 --- a/src/commands/scan/output-diff-scan.mts +++ b/src/commands/scan/output-diff-scan.mts @@ -4,6 +4,7 @@ import util from 'node:util' import colors from 'yoctocolors-cjs' import constants from '../../constants.mts' +import { setCiExitCode } from '../../utils/ci-exit-code.mts' import { failMsgWithBadge } from '../../utils/fail-msg-with-badge.mts' import { logger } from '../../utils/logger.mts' import { serializeResultJson } from '../../utils/serialize-result-json.mts' @@ -27,10 +28,7 @@ export async function outputDiffScan( }, ): Promise { if (!result.ok) { - process.exitCode = result.code ?? 1 - } - - if (!result.ok) { + setCiExitCode('api', result.code ?? 1) if (outputKind === 'json') { logger.log(serializeResultJson(result)) return @@ -51,16 +49,16 @@ export async function outputDiffScan( artifact.alerts?.some(alert => alert.action === 'error'), ) ) { - process.exitCode = 1 + setCiExitCode('blocking') } - if (strictBlocking) { - const unchangedBlocking = (diffScan.artifacts.unchanged ?? []).filter( - artifact => artifact.alerts?.some(alert => alert.action === 'error'), + if ( + strictBlocking && + diffScan.artifacts.unchanged?.some(artifact => + artifact.alerts?.some(alert => alert.action === 'error'), ) - if (unchangedBlocking.length > 0) { - process.exitCode = 1 - } + ) { + setCiExitCode('blocking') } const dashboardUrl = diffScan.html_url diff --git a/src/commands/scan/output-diff-scan.test.mts b/src/commands/scan/output-diff-scan.test.mts index 65ae46961..3b053cdab 100644 --- a/src/commands/scan/output-diff-scan.test.mts +++ b/src/commands/scan/output-diff-scan.test.mts @@ -1,9 +1,20 @@ import { afterEach, describe, expect, it, vi } from 'vitest' +import { handlePrDiffScan } from './handle-diff-scan.mts' import { outputDiffScan } from './output-diff-scan.mts' +const fetchDiffScan = vi.hoisted(() => vi.fn()) + +vi.mock('./fetch-diff-scan.mts', () => ({ fetchDiffScan })) + vi.mock('../../utils/logger.mts', () => ({ - logger: { error: vi.fn(), fail: vi.fn(), info: vi.fn(), log: vi.fn() }, + logger: { + error: vi.fn(), + fail: vi.fn(), + info: vi.fn(), + log: vi.fn(), + success: vi.fn(), + }, })) const diff = { @@ -34,6 +45,34 @@ describe('outputDiffScan strict blocking', () => { vi.clearAllMocks() }) + it('evaluates the server-side PR diff created from the exact scan IDs', async () => { + fetchDiffScan.mockResolvedValue({ + ok: true, + data: { + diff_scan: { + ...diff.diff_scan, + artifacts: { + ...diff.diff_scan.artifacts, + added: diff.diff_scan.artifacts.unchanged, + unchanged: [], + }, + }, + }, + }) + await handlePrDiffScan({ + id1: 'before', + id2: 'after', + orgSlug: 'example', + outputKind: 'json', + }) + expect(fetchDiffScan).toHaveBeenCalledWith({ + id1: 'before', + id2: 'after', + orgSlug: 'example', + }) + expect(process.exitCode).toBe(1) + }) + it('fails for new blocking alerts in ordinary diff mode', async () => { const changed = structuredClone(diff) changed.diff_scan.artifacts.added.push({ diff --git a/test/release-artifact-download.test.mts b/test/release-artifact-download.test.mts index 2b414ffd5..7d1fcf262 100644 --- a/test/release-artifact-download.test.mts +++ b/test/release-artifact-download.test.mts @@ -119,15 +119,19 @@ describe('verified release artifact download', () => { ) }) - it('requires all platform receipts before collecting an RC', () => { - const fixture = downloadFixture(['socket-2.1.0-rc.0.tgz']) - const result = spawnSync('bash', ['-c', download], { - env: { ...fixture.env, VERSION: '2.1.0-rc.0', NATIVE_RECEIPTS: '{}' }, - encoding: 'utf8', - }) - expect(result.status).not.toBe(0) - expect(result.stderr).toContain('Platform upload receipts') - }) + it( + 'requires all platform receipts before collecting an RC', + { timeout: 30_000 }, + () => { + const fixture = downloadFixture(['socket-2.1.0-rc.0.tgz']) + const result = spawnSync('bash', ['-c', download], { + env: { ...fixture.env, VERSION: '2.1.0-rc.0', NATIVE_RECEIPTS: '{}' }, + encoding: 'utf8', + }) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('Platform upload receipts') + }, + ) it( 'collects the tested launcher and all five independently uploaded platform packages',