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
14 changes: 14 additions & 0 deletions docs/commands/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,17 @@ to requiring successful pipelines before merge. It updates the target project
(`CI_MERGE_REQUEST_PROJECT_ID`) and requires Maintainer access. Leave this
variable unset if Socket should report scan results without changing project
settings.

Azure Pipelines can run `socket ci` with the example in
[`workflows/azure-pipelines.yml`](../../workflows/azure-pipelines.yml). Define
`SOCKET_CLI_API_TOKEN` as a secret pipeline variable. For Azure Repos, add the
pipeline as a build validation branch policy; Azure Repos does not use YAML `pr`
triggers. If a PR base scan is unavailable, `socket ci` still uploads and
reports a full scan, but skips PR diff comments and diff-based blocking until a
reliable baseline exists.

Azure validation builds use the target parent of the merge commit when the
other parent matches the PR source commit. The diff scan carries the PR URL.
The full-scan API accepts the provider and PR number only for PR attribution.
With `--json-format python-v1`, a missing baseline produces an incomplete
comparison. An upload error or blocking scan keeps its own exit code.
89 changes: 88 additions & 1 deletion src/commands/ci/detect-ci-pull-request-context.mts
Original file line number Diff line number Diff line change
@@ -1,12 +1,83 @@
import { readFile } from 'node:fs/promises'

import { envAsString } from '../../utils/env.mts'
import { spawn } from '../../utils/spawn.mts'

export type CiPullRequestContext = {
baseBranch: string | undefined
baseCommitHash: string | undefined
number: number
provider: 'azure' | 'github' | 'gitlab' | undefined
url?: string | undefined
}

function repositoryUrl(value: string): URL | undefined {
try {
const url = new URL(value)
if (
!['https:', 'http:'].includes(url.protocol) ||
!url.hostname ||
url.username ||
url.password ||
url.search ||
url.hash
) {
return undefined
}
url.pathname = url.pathname.replace(/\/+$/u, '')
return url
} catch {
return undefined
}
}

function pullRequestUrl(repository: string, path: string): string | undefined {
const url = repositoryUrl(repository)
if (!url) {
return undefined
}
url.pathname = `${url.pathname}/${path}`
return url.href
}

function azurePullRequestUrl(
repository: string,
number: number,
): string | undefined {
const url = repositoryUrl(repository)
if (!url) {
return undefined
}
const path =
url.hostname.toLowerCase() === 'github.com' ? 'pull' : 'pullrequest'
return pullRequestUrl(url.href, `${path}/${number}`)
}

async function azureBaseCommit(number: number): Promise<string | undefined> {
const merge = process.env['BUILD_SOURCEVERSION']
const source = process.env['SYSTEM_PULLREQUEST_SOURCECOMMITID']
if (
process.env['BUILD_SOURCEBRANCH'] !== `refs/pull/${number}/merge` ||
!merge ||
!/^[a-f0-9]{40}$/iu.test(merge) ||
!source
) {
return undefined
}
try {
const result = await spawn('git', ['show', '-s', '--format=%P', merge])
const parents = result.stdout.trim().split(' ')
if (
parents.length === 2 &&
parents[1] === source &&
/^[a-f0-9]{40}$/iu.test(parents[0] ?? '')
) {
return parents[0]
}
} catch {
// A shallow checkout may lack the validation merge or its parents.
}
return undefined
}

export async function detectCiPullRequestContext(): Promise<CiPullRequestContext> {
Expand Down Expand Up @@ -35,6 +106,12 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
baseCommitHash,
number: Number(githubMatch[1]),
provider: 'github',
url: envAsString(environment['GITHUB_REPOSITORY'])
? pullRequestUrl(
`${envAsString(environment['GITHUB_SERVER_URL']) || 'https://github.com'}/${envAsString(environment['GITHUB_REPOSITORY'])}`,
`pull/${githubMatch[1]}`,
)
: undefined,
}
}

Expand All @@ -48,6 +125,10 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
envAsString(environment['CI_MERGE_REQUEST_DIFF_BASE_SHA']) || undefined,
number: gitlabNumber,
provider: 'gitlab',
url: pullRequestUrl(
envAsString(environment['CI_PROJECT_URL']),
`-/merge_requests/${gitlabNumber}`,
),
}
}

Expand All @@ -62,9 +143,14 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
/^refs\/heads\//u,
'',
) || undefined,
baseCommitHash: undefined,
baseCommitHash: await azureBaseCommit(azureNumber),
number: azureNumber,
provider: 'azure',
url: azurePullRequestUrl(
envAsString(environment['BUILD_REPOSITORY_URI']) ||
envAsString(environment['SYSTEM_PULLREQUEST_TARGETREPOSITORYURI']),
azureNumber,
),
}
}

Expand All @@ -73,5 +159,6 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
baseCommitHash: undefined,
number: 0,
provider: undefined,
url: undefined,
}
}
50 changes: 33 additions & 17 deletions src/commands/ci/handle-ci.mts
Original file line number Diff line number Diff line change
Expand Up @@ -226,24 +226,37 @@ async function runCiScan({
repo: repoName,
})
if (!baselineCResult.ok) {
process.exitCode = baselineCResult.code ?? 1
logger.log(
pythonJsonFormat
? `${JSON.stringify(
createPythonDiffJsonFailure(
baselineCResult.message,
baselineCResult.cause,
pythonJsonContext,
),
null,
2,
)}\n`
: serializeResultJson(baselineCResult),
const canScanWithoutAzureBaseline =
pullRequestContext.provider === 'azure' &&
baselineCResult.code === undefined &&
(baselineCResult.message === 'Cannot select PR scan baseline' ||
baselineCResult.message === 'No matching PR scan baseline found')
if (!canScanWithoutAzureBaseline) {
process.exitCode = baselineCResult.code ?? 1
logger.log(
pythonJsonFormat
? `${JSON.stringify(
createPythonDiffJsonFailure(
baselineCResult.message,
baselineCResult.cause,
pythonJsonContext,
),
null,
2,
)}\n`
: serializeResultJson(baselineCResult),
)
return
}
// A later scan error or blocking verdict takes precedence.
setCiExitCode('infrastructure', 3)
logger.warn(
`Socket could not find a reliable Azure PR base scan (${baselineCResult.cause}). Continuing with a scan-only result; the PR verdict is incomplete.`,
)
return
} else {
baselineScanId = baselineCResult.data.id
debugFn('notice', `Selected PR baseline scan ${baselineScanId}`)
}
baselineScanId = baselineCResult.data.id
debugFn('notice', `Selected PR baseline scan ${baselineScanId}`)
}

debugFn(
Expand All @@ -252,7 +265,7 @@ async function runCiScan({
)
debugDir('inspect', { orgSlug, cwd, branchName, repoName })

const [owner, repo] = constants.ENV.GITHUB_REPOSITORY.split('/')
const [owner, repo] = (constants.ENV.GITHUB_REPOSITORY || '').split('/')
await handleCreateNewScan({
autoManifest,
branchName,
Expand All @@ -263,13 +276,16 @@ async function runCiScan({
defaultBranch: false,
interactive: false,
orgSlug,
integrationType: pullRequestContext.provider,
integrationOrgSlug: orgSlug,
outputKind: 'json',
pythonJsonFormat,
strictBlocking,
pythonJsonContext,
// When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false.
pendingHead: true,
pullRequest,
pullRequestUrl: pullRequestContext.url,
baselineScanId,
onDiffReport: async (diffScanId, outcome) => {
onDiffOutcome(outcome)
Expand Down
45 changes: 26 additions & 19 deletions src/commands/scan/fetch-create-org-full-scan.mts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@ import { setupSdk } from '../../utils/sdk.mts'

import type { CResult } from '../../types.mts'
import type { SetupSdkOptions } from '../../utils/sdk.mts'
import type { FullScanResult } from '@socketsecurity/sdk'
import type { FullScanResult, SocketSdk } from '@socketsecurity/sdk'

type FullScanCreateOptions = Parameters<SocketSdk['createFullScan']>[2]

export type FetchCreateOrgFullScanConfigs = {
branchName: string
commitHash: string
commitMessage: string
committers: string
pullRequest: number
integrationType?: FullScanCreateOptions['integration_type']
integrationOrgSlug?: string | undefined
repoName: string
scanType: string | undefined
workspace?: string | undefined
Expand All @@ -40,6 +44,8 @@ export async function fetchCreateOrgFullScan(
commitHash,
commitMessage,
committers,
integrationOrgSlug,
integrationType,
pullRequest,
repoName,
scanType,
Expand Down Expand Up @@ -73,25 +79,26 @@ export async function fetchCreateOrgFullScan(
)
}

const createParams: FullScanCreateOptions = {
pathsRelativeTo: cwd,
...(branchName ? { branch: branchName } : {}),
...(commitHash ? { commit_hash: commitHash } : {}),
...(commitMessage ? { commit_message: commitMessage } : {}),
...(committers ? { committers } : {}),
...(defaultBranch !== undefined
? { make_default_branch: defaultBranch }
: {}),
...(pullRequest ? { pull_request: pullRequest } : {}),
...(integrationType ? { integration_type: integrationType } : {}),
...(integrationOrgSlug ? { integration_org_slug: integrationOrgSlug } : {}),
...(scanType ? { scan_type: scanType } : {}),
repo: repoName,
...(workspace ? { workspace } : {}),
...(pendingHead !== undefined ? { set_as_pending_head: pendingHead } : {}),
...(tmp !== undefined ? { tmp } : {}),
}
return await handleApiCall(
sockSdk.createFullScan(orgSlug, packagePaths, {
pathsRelativeTo: cwd,
...(branchName ? { branch: branchName } : {}),
...(commitHash ? { commit_hash: commitHash } : {}),
...(commitMessage ? { commit_message: commitMessage } : {}),
...(committers ? { committers } : {}),
...(defaultBranch !== undefined
? { make_default_branch: defaultBranch }
: {}),
...(pullRequest ? { pull_request: pullRequest } : {}),
...(scanType ? { scan_type: scanType } : {}),
repo: repoName,
...(workspace ? { workspace } : {}),
...(pendingHead !== undefined
? { set_as_pending_head: pendingHead }
: {}),
...(tmp !== undefined ? { tmp } : {}),
}),
sockSdk.createFullScan(orgSlug, packagePaths, createParams),
{ description: 'to create a scan' },
)
}
48 changes: 48 additions & 0 deletions src/commands/scan/fetch-create-org-full-scan.test.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'

const mocks = vi.hoisted(() => ({
createFullScan: vi.fn(),
}))

vi.mock('../../utils/api.mts', () => ({
handleApiCall: async (request: Promise<unknown>) => await request,
}))

vi.mock('../../utils/sdk.mts', () => ({
setupSdk: async () => ({
ok: true,
data: { createFullScan: mocks.createFullScan },
}),
}))

import { fetchCreateOrgFullScan } from './fetch-create-org-full-scan.mts'

describe('fetchCreateOrgFullScan', () => {
beforeEach(() => {
mocks.createFullScan.mockReset().mockResolvedValue({ ok: true, data: {} })
})

it('uploads the SCM integration context with the full scan', async () => {
await fetchCreateOrgFullScan(['package.json'], 'socket-org', {
branchName: 'feature',
commitHash: 'head-sha',
commitMessage: '',
committers: '',
integrationType: 'azure',
integrationOrgSlug: 'socket-org',
pullRequest: 42,
repoName: 'widgets',
scanType: undefined,
})

expect(mocks.createFullScan).toHaveBeenCalledWith(
'socket-org',
['package.json'],
expect.objectContaining({
integration_type: 'azure',
integration_org_slug: 'socket-org',
pull_request: 42,
}),
)
})
})
3 changes: 3 additions & 0 deletions src/commands/scan/fetch-diff-scan.mts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,12 @@ function sleep(ms: number): Promise<void> {
}

export async function fetchDiffScan({
externalHref,
id1,
id2,
orgSlug,
}: {
externalHref?: string | undefined
id1: string
id2: string
orgSlug: string
Expand All @@ -57,6 +59,7 @@ export async function fetchDiffScan({
`orgs/${encodeURIComponent(orgSlug)}/diff-scans/from-ids?${createQuery}`,
{
method: 'POST',
...(externalHref ? { body: { external_href: externalHref } } : {}),
description: 'a scan diff creation',
},
)
Expand Down
Loading
Loading