Skip to content

Commit fa9ef3f

Browse files
committed
feat(python-cli-parity): add SCM scan context and Azure CI
1 parent e94eda3 commit fa9ef3f

16 files changed

Lines changed: 493 additions & 42 deletions

‎docs/commands/ci.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,17 @@ to requiring successful pipelines before merge. It updates the target project
8080
(`CI_MERGE_REQUEST_PROJECT_ID`) and requires Maintainer access. Leave this
8181
variable unset if Socket should report scan results without changing project
8282
settings.
83+
84+
Azure Pipelines can run `socket ci` with the example in
85+
[`workflows/azure-pipelines.yml`](../../workflows/azure-pipelines.yml). Define
86+
`SOCKET_CLI_API_TOKEN` as a secret pipeline variable. For Azure Repos, add the
87+
pipeline as a build validation branch policy; Azure Repos does not use YAML `pr`
88+
triggers. If a PR base scan is unavailable, `socket ci` still uploads and
89+
reports a full scan, but skips PR diff comments and diff-based blocking until a
90+
reliable baseline exists.
91+
92+
Azure validation builds use the target parent of the merge commit when the
93+
other parent matches the PR source commit. The diff scan carries the PR URL.
94+
The full-scan API accepts the provider and PR number only for PR attribution.
95+
With `--json-format python-v1`, a missing baseline produces an incomplete
96+
comparison. An upload error or blocking scan keeps its own exit code.

‎src/commands/ci/detect-ci-pull-request-context.mts‎

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,83 @@
11
import { readFile } from 'node:fs/promises'
22

33
import { envAsString } from '../../utils/env.mts'
4+
import { spawn } from '../../utils/spawn.mts'
45

56
export type CiPullRequestContext = {
67
baseBranch: string | undefined
78
baseCommitHash: string | undefined
89
number: number
910
provider: 'azure' | 'github' | 'gitlab' | undefined
11+
url?: string | undefined
12+
}
13+
14+
function repositoryUrl(value: string): URL | undefined {
15+
try {
16+
const url = new URL(value)
17+
if (
18+
!['https:', 'http:'].includes(url.protocol) ||
19+
!url.hostname ||
20+
url.username ||
21+
url.password ||
22+
url.search ||
23+
url.hash
24+
) {
25+
return undefined
26+
}
27+
url.pathname = url.pathname.replace(/\/+$/u, '')
28+
return url
29+
} catch {
30+
return undefined
31+
}
32+
}
33+
34+
function pullRequestUrl(repository: string, path: string): string | undefined {
35+
const url = repositoryUrl(repository)
36+
if (!url) {
37+
return undefined
38+
}
39+
url.pathname = `${url.pathname}/${path}`
40+
return url.href
41+
}
42+
43+
function azurePullRequestUrl(
44+
repository: string,
45+
number: number,
46+
): string | undefined {
47+
const url = repositoryUrl(repository)
48+
if (!url) {
49+
return undefined
50+
}
51+
const path =
52+
url.hostname.toLowerCase() === 'github.com' ? 'pull' : 'pullrequest'
53+
return pullRequestUrl(url.href, `${path}/${number}`)
54+
}
55+
56+
async function azureBaseCommit(number: number): Promise<string | undefined> {
57+
const merge = process.env['BUILD_SOURCEVERSION']
58+
const source = process.env['SYSTEM_PULLREQUEST_SOURCECOMMITID']
59+
if (
60+
process.env['BUILD_SOURCEBRANCH'] !== `refs/pull/${number}/merge` ||
61+
!merge ||
62+
!/^[a-f0-9]{40}$/iu.test(merge) ||
63+
!source
64+
) {
65+
return undefined
66+
}
67+
try {
68+
const result = await spawn('git', ['show', '-s', '--format=%P', merge])
69+
const parents = result.stdout.trim().split(' ')
70+
if (
71+
parents.length === 2 &&
72+
parents[1] === source &&
73+
/^[a-f0-9]{40}$/iu.test(parents[0] ?? '')
74+
) {
75+
return parents[0]
76+
}
77+
} catch {
78+
// A shallow checkout may lack the validation merge or its parents.
79+
}
80+
return undefined
1081
}
1182

1283
export async function detectCiPullRequestContext(): Promise<CiPullRequestContext> {
@@ -35,6 +106,12 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
35106
baseCommitHash,
36107
number: Number(githubMatch[1]),
37108
provider: 'github',
109+
url: envAsString(environment['GITHUB_REPOSITORY'])
110+
? pullRequestUrl(
111+
`${envAsString(environment['GITHUB_SERVER_URL']) || 'https://github.com'}/${envAsString(environment['GITHUB_REPOSITORY'])}`,
112+
`pull/${githubMatch[1]}`,
113+
)
114+
: undefined,
38115
}
39116
}
40117

@@ -48,6 +125,10 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
48125
envAsString(environment['CI_MERGE_REQUEST_DIFF_BASE_SHA']) || undefined,
49126
number: gitlabNumber,
50127
provider: 'gitlab',
128+
url: pullRequestUrl(
129+
envAsString(environment['CI_PROJECT_URL']),
130+
`-/merge_requests/${gitlabNumber}`,
131+
),
51132
}
52133
}
53134

@@ -62,9 +143,14 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
62143
/^refs\/heads\//u,
63144
'',
64145
) || undefined,
65-
baseCommitHash: undefined,
146+
baseCommitHash: await azureBaseCommit(azureNumber),
66147
number: azureNumber,
67148
provider: 'azure',
149+
url: azurePullRequestUrl(
150+
envAsString(environment['BUILD_REPOSITORY_URI']) ||
151+
envAsString(environment['SYSTEM_PULLREQUEST_TARGETREPOSITORYURI']),
152+
azureNumber,
153+
),
68154
}
69155
}
70156

@@ -73,5 +159,6 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
73159
baseCommitHash: undefined,
74160
number: 0,
75161
provider: undefined,
162+
url: undefined,
76163
}
77164
}

‎src/commands/ci/handle-ci.mts‎

Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -226,24 +226,37 @@ async function runCiScan({
226226
repo: repoName,
227227
})
228228
if (!baselineCResult.ok) {
229-
process.exitCode = baselineCResult.code ?? 1
230-
logger.log(
231-
pythonJsonFormat
232-
? `${JSON.stringify(
233-
createPythonDiffJsonFailure(
234-
baselineCResult.message,
235-
baselineCResult.cause,
236-
pythonJsonContext,
237-
),
238-
null,
239-
2,
240-
)}\n`
241-
: serializeResultJson(baselineCResult),
229+
const canScanWithoutAzureBaseline =
230+
pullRequestContext.provider === 'azure' &&
231+
baselineCResult.code === undefined &&
232+
(baselineCResult.message === 'Cannot select PR scan baseline' ||
233+
baselineCResult.message === 'No matching PR scan baseline found')
234+
if (!canScanWithoutAzureBaseline) {
235+
process.exitCode = baselineCResult.code ?? 1
236+
logger.log(
237+
pythonJsonFormat
238+
? `${JSON.stringify(
239+
createPythonDiffJsonFailure(
240+
baselineCResult.message,
241+
baselineCResult.cause,
242+
pythonJsonContext,
243+
),
244+
null,
245+
2,
246+
)}\n`
247+
: serializeResultJson(baselineCResult),
248+
)
249+
return
250+
}
251+
// A later scan error or blocking verdict takes precedence.
252+
setCiExitCode('infrastructure', 3)
253+
logger.warn(
254+
`Socket could not find a reliable Azure PR base scan (${baselineCResult.cause}). Continuing with a scan-only result; the PR verdict is incomplete.`,
242255
)
243-
return
256+
} else {
257+
baselineScanId = baselineCResult.data.id
258+
debugFn('notice', `Selected PR baseline scan ${baselineScanId}`)
244259
}
245-
baselineScanId = baselineCResult.data.id
246-
debugFn('notice', `Selected PR baseline scan ${baselineScanId}`)
247260
}
248261

249262
debugFn(
@@ -252,7 +265,7 @@ async function runCiScan({
252265
)
253266
debugDir('inspect', { orgSlug, cwd, branchName, repoName })
254267

255-
const [owner, repo] = constants.ENV.GITHUB_REPOSITORY.split('/')
268+
const [owner, repo] = (constants.ENV.GITHUB_REPOSITORY || '').split('/')
256269
await handleCreateNewScan({
257270
autoManifest,
258271
branchName,
@@ -263,13 +276,16 @@ async function runCiScan({
263276
defaultBranch: false,
264277
interactive: false,
265278
orgSlug,
279+
integrationType: pullRequestContext.provider,
280+
integrationOrgSlug: orgSlug,
266281
outputKind: 'json',
267282
pythonJsonFormat,
268283
strictBlocking,
269284
pythonJsonContext,
270285
// When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false.
271286
pendingHead: true,
272287
pullRequest,
288+
pullRequestUrl: pullRequestContext.url,
273289
baselineScanId,
274290
onDiffReport: async (diffScanId, outcome) => {
275291
onDiffOutcome(outcome)

‎src/commands/scan/fetch-create-org-full-scan.mts‎

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,18 @@ import { setupSdk } from '../../utils/sdk.mts'
88

99
import type { CResult } from '../../types.mts'
1010
import type { SetupSdkOptions } from '../../utils/sdk.mts'
11-
import type { FullScanResult } from '@socketsecurity/sdk'
11+
import type { FullScanResult, SocketSdk } from '@socketsecurity/sdk'
12+
13+
type FullScanCreateOptions = Parameters<SocketSdk['createFullScan']>[2]
1214

1315
export type FetchCreateOrgFullScanConfigs = {
1416
branchName: string
1517
commitHash: string
1618
commitMessage: string
1719
committers: string
1820
pullRequest: number
21+
integrationType?: FullScanCreateOptions['integration_type']
22+
integrationOrgSlug?: string | undefined
1923
repoName: string
2024
scanType: string | undefined
2125
workspace?: string | undefined
@@ -40,6 +44,8 @@ export async function fetchCreateOrgFullScan(
4044
commitHash,
4145
commitMessage,
4246
committers,
47+
integrationOrgSlug,
48+
integrationType,
4349
pullRequest,
4450
repoName,
4551
scanType,
@@ -73,25 +79,26 @@ export async function fetchCreateOrgFullScan(
7379
)
7480
}
7581

82+
const createParams: FullScanCreateOptions = {
83+
pathsRelativeTo: cwd,
84+
...(branchName ? { branch: branchName } : {}),
85+
...(commitHash ? { commit_hash: commitHash } : {}),
86+
...(commitMessage ? { commit_message: commitMessage } : {}),
87+
...(committers ? { committers } : {}),
88+
...(defaultBranch !== undefined
89+
? { make_default_branch: defaultBranch }
90+
: {}),
91+
...(pullRequest ? { pull_request: pullRequest } : {}),
92+
...(integrationType ? { integration_type: integrationType } : {}),
93+
...(integrationOrgSlug ? { integration_org_slug: integrationOrgSlug } : {}),
94+
...(scanType ? { scan_type: scanType } : {}),
95+
repo: repoName,
96+
...(workspace ? { workspace } : {}),
97+
...(pendingHead !== undefined ? { set_as_pending_head: pendingHead } : {}),
98+
...(tmp !== undefined ? { tmp } : {}),
99+
}
76100
return await handleApiCall(
77-
sockSdk.createFullScan(orgSlug, packagePaths, {
78-
pathsRelativeTo: cwd,
79-
...(branchName ? { branch: branchName } : {}),
80-
...(commitHash ? { commit_hash: commitHash } : {}),
81-
...(commitMessage ? { commit_message: commitMessage } : {}),
82-
...(committers ? { committers } : {}),
83-
...(defaultBranch !== undefined
84-
? { make_default_branch: defaultBranch }
85-
: {}),
86-
...(pullRequest ? { pull_request: pullRequest } : {}),
87-
...(scanType ? { scan_type: scanType } : {}),
88-
repo: repoName,
89-
...(workspace ? { workspace } : {}),
90-
...(pendingHead !== undefined
91-
? { set_as_pending_head: pendingHead }
92-
: {}),
93-
...(tmp !== undefined ? { tmp } : {}),
94-
}),
101+
sockSdk.createFullScan(orgSlug, packagePaths, createParams),
95102
{ description: 'to create a scan' },
96103
)
97104
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { beforeEach, describe, expect, it, vi } from 'vitest'
2+
3+
const mocks = vi.hoisted(() => ({
4+
createFullScan: vi.fn(),
5+
}))
6+
7+
vi.mock('../../utils/api.mts', () => ({
8+
handleApiCall: async (request: Promise<unknown>) => await request,
9+
}))
10+
11+
vi.mock('../../utils/sdk.mts', () => ({
12+
setupSdk: async () => ({
13+
ok: true,
14+
data: { createFullScan: mocks.createFullScan },
15+
}),
16+
}))
17+
18+
import { fetchCreateOrgFullScan } from './fetch-create-org-full-scan.mts'
19+
20+
describe('fetchCreateOrgFullScan', () => {
21+
beforeEach(() => {
22+
mocks.createFullScan.mockReset().mockResolvedValue({ ok: true, data: {} })
23+
})
24+
25+
it('uploads the SCM integration context with the full scan', async () => {
26+
await fetchCreateOrgFullScan(['package.json'], 'socket-org', {
27+
branchName: 'feature',
28+
commitHash: 'head-sha',
29+
commitMessage: '',
30+
committers: '',
31+
integrationType: 'azure',
32+
integrationOrgSlug: 'socket-org',
33+
pullRequest: 42,
34+
repoName: 'widgets',
35+
scanType: undefined,
36+
})
37+
38+
expect(mocks.createFullScan).toHaveBeenCalledWith(
39+
'socket-org',
40+
['package.json'],
41+
expect.objectContaining({
42+
integration_type: 'azure',
43+
integration_org_slug: 'socket-org',
44+
pull_request: 42,
45+
}),
46+
)
47+
})
48+
})

‎src/commands/scan/fetch-diff-scan.mts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,12 @@ function sleep(ms: number): Promise<void> {
3636
}
3737

3838
export async function fetchDiffScan({
39+
externalHref,
3940
id1,
4041
id2,
4142
orgSlug,
4243
}: {
44+
externalHref?: string | undefined
4345
id1: string
4446
id2: string
4547
orgSlug: string
@@ -57,6 +59,7 @@ export async function fetchDiffScan({
5759
`orgs/${encodeURIComponent(orgSlug)}/diff-scans/from-ids?${createQuery}`,
5860
{
5961
method: 'POST',
62+
...(externalHref ? { body: { external_href: externalHref } } : {}),
6063
description: 'a scan diff creation',
6164
},
6265
)

0 commit comments

Comments
 (0)