Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
19 changes: 19 additions & 0 deletions src/commands/ci/handle-ci.mts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -32,6 +33,23 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
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',
Expand All @@ -53,6 +71,7 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
// When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false.
pendingHead: true,
pullRequest,
baselineScanId,
reach: {
dynamicSbomInference: undefined,
excludePaths: [],
Expand Down
57 changes: 57 additions & 0 deletions src/commands/ci/select-baseline-scan.mts
Original file line number Diff line number Diff line change
@@ -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<CResult<FullScanItem>> {
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)
Comment thread
jdalton marked this conversation as resolved.
Resolved
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.`,
}
}
96 changes: 96 additions & 0 deletions src/commands/ci/select-baseline-scan.test.mts
Original file line number Diff line number Diff line change
@@ -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',
})
})
})
1 change: 1 addition & 0 deletions src/commands/manifest/bazel/python-shim.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ describe('provisionPythonShim', () => {
),
).rejects.toThrow(/python/)
},
30_000,
)

it.skipIf(!python || process.platform === 'win32')(
Expand Down
14 changes: 13 additions & 1 deletion src/commands/scan/fetch-list-scans.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -35,14 +36,25 @@ 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

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' } : {}),
Expand Down
32 changes: 22 additions & 10 deletions src/commands/scan/handle-create-new-scan.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -91,6 +92,7 @@ export type GeneratedScanFiles = {

export type HandleCreateNewScanConfig = {
autoManifest: boolean
baselineScanId?: string | undefined
branchName: string
commitHash: string
commitMessage: string
Expand Down Expand Up @@ -125,6 +127,7 @@ export type HandleCreateNewScanConfig = {
async function createNewScan(
{
autoManifest,
baselineScanId,
branchName,
commitHash,
commitMessage,
Expand Down Expand Up @@ -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(
{
Expand Down
20 changes: 20 additions & 0 deletions src/commands/scan/handle-diff-scan.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
const result = await fetchDiffScan({ id1, id2, orgSlug })
await outputDiffScan(result, {
depth: 2,
file: '',
outputKind,
strictBlocking: false,
})
}
Loading
Loading