Skip to content
Open
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: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
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 { debugDir, debugFn } from '../../utils/debug.mts'
import {
Expand Down Expand Up @@ -31,6 +32,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 @@ -52,6 +70,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',
})
})
})
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
34 changes: 24 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 { 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'
Expand Down Expand Up @@ -85,6 +86,7 @@ export type GeneratedScanFiles = {

export type HandleCreateNewScanConfig = {
autoManifest: boolean
baselineScanId?: string | undefined
branchName: string
commitHash: string
commitMessage: string
Expand Down Expand Up @@ -116,6 +118,7 @@ export type HandleCreateNewScanConfig = {
async function createNewScan(
{
autoManifest,
baselineScanId,
branchName,
commitHash,
commitMessage,
Expand Down Expand Up @@ -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(
{
Expand Down
13 changes: 13 additions & 0 deletions src/commands/scan/output-diff-scan.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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)}`
Expand Down
44 changes: 44 additions & 0 deletions src/commands/scan/output-diff-scan.test.mts
Original file line number Diff line number Diff line change
@@ -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)
})
})