Skip to content

Commit b075b55

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

16 files changed

Lines changed: 497 additions & 45 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: 91 additions & 4 deletions
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> {
@@ -15,7 +86,8 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
1586
envAsString(environment['GITHUB_REF']),
1687
)
1788
if (githubMatch) {
18-
let baseCommitHash = envAsString(environment['GITHUB_BASE_SHA']) || undefined
89+
let baseCommitHash =
90+
envAsString(environment['GITHUB_BASE_SHA']) || undefined
1991
const eventPath = envAsString(environment['GITHUB_EVENT_PATH'])
2092
if (!baseCommitHash && eventPath) {
2193
try {
@@ -34,6 +106,12 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
34106
baseCommitHash,
35107
number: Number(githubMatch[1]),
36108
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,
37115
}
38116
}
39117

@@ -47,6 +125,10 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
47125
envAsString(environment['CI_MERGE_REQUEST_DIFF_BASE_SHA']) || undefined,
48126
number: gitlabNumber,
49127
provider: 'gitlab',
128+
url: pullRequestUrl(
129+
envAsString(environment['CI_PROJECT_URL']),
130+
`-/merge_requests/${gitlabNumber}`,
131+
),
50132
}
51133
}
52134

@@ -60,11 +142,15 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
60142
envAsString(environment['SYSTEM_PULLREQUEST_TARGETBRANCH']).replace(
61143
/^refs\/heads\//u,
62144
'',
63-
) ||
64-
undefined,
65-
baseCommitHash: undefined,
145+
) || 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/detect-ci-pull-request-context.test.mts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,96 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
22

33
import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts'
44

5+
const { spawn } = vi.hoisted(() => ({ spawn: vi.fn() }))
6+
vi.mock('../../utils/spawn.mts', () => ({ spawn }))
7+
58
afterEach(() => {
69
vi.unstubAllEnvs()
710
})
811

912
beforeEach(() => {
1013
vi.stubEnv('GITHUB_REF', '')
14+
vi.stubEnv('GITHUB_REPOSITORY', '')
15+
vi.stubEnv('GITHUB_SERVER_URL', '')
1116
vi.stubEnv('CI_MERGE_REQUEST_IID', '')
17+
vi.stubEnv('CI_PROJECT_URL', '')
1218
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '')
1319
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTID', '')
20+
vi.stubEnv('BUILD_REPOSITORY_URI', '')
21+
vi.stubEnv('SYSTEM_PULLREQUEST_TARGETREPOSITORYURI', '')
1422
})
1523

1624
describe('detectCiPullRequestContext', () => {
1725
it('detects GitHub pull requests', async () => {
1826
vi.stubEnv('GITHUB_REF', 'refs/pull/42/merge')
27+
vi.stubEnv('GITHUB_REPOSITORY', 'octo/project')
1928
await expect(detectCiPullRequestContext()).resolves.toMatchObject({
2029
number: 42,
2130
provider: 'github',
31+
url: 'https://github.com/octo/project/pull/42',
2232
})
2333
})
2434

2535
it('detects GitLab merge requests', async () => {
2636
vi.stubEnv('CI_MERGE_REQUEST_IID', '17')
37+
vi.stubEnv('CI_PROJECT_URL', 'https://gitlab.example.com/group/project')
2738
await expect(detectCiPullRequestContext()).resolves.toMatchObject({
2839
number: 17,
2940
provider: 'gitlab',
41+
url: 'https://gitlab.example.com/group/project/-/merge_requests/17',
3042
})
3143
})
3244

45+
it('uses the target parent only for a verified Azure validation merge', async () => {
46+
const target = 'a'.repeat(40)
47+
const source = 'b'.repeat(40)
48+
const merge = 'c'.repeat(40)
49+
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTID', '9')
50+
vi.stubEnv('BUILD_SOURCEVERSION', merge)
51+
vi.stubEnv('BUILD_SOURCEBRANCH', 'refs/pull/9/merge')
52+
vi.stubEnv('SYSTEM_PULLREQUEST_SOURCECOMMITID', source)
53+
spawn.mockResolvedValue({ stdout: `${target} ${source}\n` })
54+
expect((await detectCiPullRequestContext()).baseCommitHash).toBe(target)
55+
vi.stubEnv('SYSTEM_PULLREQUEST_SOURCECOMMITID', target)
56+
expect((await detectCiPullRequestContext()).baseCommitHash).toBeUndefined()
57+
})
58+
3359
it.each(['refs/heads/release/v1', 'release/v1'])(
3460
'detects an Azure pull request targeting %s',
3561
async target => {
3662
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '9')
3763
vi.stubEnv('SYSTEM_PULLREQUEST_TARGETBRANCH', target)
64+
vi.stubEnv(
65+
'BUILD_REPOSITORY_URI',
66+
'https://dev.azure.com/acme/platform/_git/widgets',
67+
)
3868
await expect(detectCiPullRequestContext()).resolves.toMatchObject({
3969
baseBranch: 'release/v1',
4070
number: 9,
4171
provider: 'azure',
72+
url: 'https://dev.azure.com/acme/platform/_git/widgets/pullrequest/9',
4273
})
4374
},
4475
)
4576

77+
it.each([
78+
[
79+
'https://github.com/acme/widgets',
80+
'https://github.com/acme/widgets/pull/9',
81+
],
82+
[
83+
'https://github.com.attacker.invalid/acme/widgets',
84+
'https://github.com.attacker.invalid/acme/widgets/pullrequest/9',
85+
],
86+
])(
87+
'uses the Azure repository host to choose its PR URL',
88+
async (repository, url) => {
89+
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '9')
90+
vi.stubEnv('BUILD_REPOSITORY_URI', repository)
91+
await expect(detectCiPullRequestContext()).resolves.toMatchObject({ url })
92+
},
93+
)
94+
4695
it('ignores zero and malformed provider values', async () => {
4796
vi.stubEnv('CI_MERGE_REQUEST_IID', '0')
4897
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTID', 'nope')

‎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)

0 commit comments

Comments
 (0)