Skip to content

Commit e3c51dc

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

13 files changed

Lines changed: 350 additions & 41 deletions

‎docs/commands/ci.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,11 @@ 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.

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

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,49 @@ export type CiPullRequestContext = {
77
baseCommitHash: string | undefined
88
number: number
99
provider: 'azure' | 'github' | 'gitlab' | undefined
10+
url?: string | undefined
11+
}
12+
13+
function repositoryUrl(value: string): URL | undefined {
14+
try {
15+
const url = new URL(value)
16+
if (
17+
!['https:', 'http:'].includes(url.protocol) ||
18+
!url.hostname ||
19+
url.username ||
20+
url.password ||
21+
url.search ||
22+
url.hash
23+
) {
24+
return undefined
25+
}
26+
url.pathname = url.pathname.replace(/\/+$/u, '')
27+
return url
28+
} catch {
29+
return undefined
30+
}
31+
}
32+
33+
function pullRequestUrl(repository: string, path: string): string | undefined {
34+
const url = repositoryUrl(repository)
35+
if (!url) {
36+
return undefined
37+
}
38+
url.pathname = `${url.pathname}/${path}`
39+
return url.href
40+
}
41+
42+
function azurePullRequestUrl(
43+
repository: string,
44+
number: number,
45+
): string | undefined {
46+
const url = repositoryUrl(repository)
47+
if (!url) {
48+
return undefined
49+
}
50+
const path =
51+
url.hostname.toLowerCase() === 'github.com' ? 'pull' : 'pullrequest'
52+
return pullRequestUrl(url.href, `${path}/${number}`)
1053
}
1154

1255
export async function detectCiPullRequestContext(): Promise<CiPullRequestContext> {
@@ -15,7 +58,8 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
1558
envAsString(environment['GITHUB_REF']),
1659
)
1760
if (githubMatch) {
18-
let baseCommitHash = envAsString(environment['GITHUB_BASE_SHA']) || undefined
61+
let baseCommitHash =
62+
envAsString(environment['GITHUB_BASE_SHA']) || undefined
1963
const eventPath = envAsString(environment['GITHUB_EVENT_PATH'])
2064
if (!baseCommitHash && eventPath) {
2165
try {
@@ -34,6 +78,12 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
3478
baseCommitHash,
3579
number: Number(githubMatch[1]),
3680
provider: 'github',
81+
url: envAsString(environment['GITHUB_REPOSITORY'])
82+
? pullRequestUrl(
83+
`${envAsString(environment['GITHUB_SERVER_URL']) || 'https://github.com'}/${envAsString(environment['GITHUB_REPOSITORY'])}`,
84+
`pull/${githubMatch[1]}`,
85+
)
86+
: undefined,
3787
}
3888
}
3989

@@ -47,6 +97,10 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
4797
envAsString(environment['CI_MERGE_REQUEST_DIFF_BASE_SHA']) || undefined,
4898
number: gitlabNumber,
4999
provider: 'gitlab',
100+
url: pullRequestUrl(
101+
envAsString(environment['CI_PROJECT_URL']),
102+
`-/merge_requests/${gitlabNumber}`,
103+
),
50104
}
51105
}
52106

@@ -60,11 +114,15 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
60114
envAsString(environment['SYSTEM_PULLREQUEST_TARGETBRANCH']).replace(
61115
/^refs\/heads\//u,
62116
'',
63-
) ||
64-
undefined,
117+
) || undefined,
65118
baseCommitHash: undefined,
66119
number: azureNumber,
67120
provider: 'azure',
121+
url: azurePullRequestUrl(
122+
envAsString(environment['BUILD_REPOSITORY_URI']) ||
123+
envAsString(environment['SYSTEM_PULLREQUEST_TARGETREPOSITORYURI']),
124+
azureNumber,
125+
),
68126
}
69127
}
70128

@@ -73,5 +131,6 @@ export async function detectCiPullRequestContext(): Promise<CiPullRequestContext
73131
baseCommitHash: undefined,
74132
number: 0,
75133
provider: undefined,
134+
url: undefined,
76135
}
77136
}

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,34 @@ afterEach(() => {
88

99
beforeEach(() => {
1010
vi.stubEnv('GITHUB_REF', '')
11+
vi.stubEnv('GITHUB_REPOSITORY', '')
12+
vi.stubEnv('GITHUB_SERVER_URL', '')
1113
vi.stubEnv('CI_MERGE_REQUEST_IID', '')
14+
vi.stubEnv('CI_PROJECT_URL', '')
1215
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '')
1316
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTID', '')
17+
vi.stubEnv('BUILD_REPOSITORY_URI', '')
18+
vi.stubEnv('SYSTEM_PULLREQUEST_TARGETREPOSITORYURI', '')
1419
})
1520

1621
describe('detectCiPullRequestContext', () => {
1722
it('detects GitHub pull requests', async () => {
1823
vi.stubEnv('GITHUB_REF', 'refs/pull/42/merge')
24+
vi.stubEnv('GITHUB_REPOSITORY', 'octo/project')
1925
await expect(detectCiPullRequestContext()).resolves.toMatchObject({
2026
number: 42,
2127
provider: 'github',
28+
url: 'https://github.com/octo/project/pull/42',
2229
})
2330
})
2431

2532
it('detects GitLab merge requests', async () => {
2633
vi.stubEnv('CI_MERGE_REQUEST_IID', '17')
34+
vi.stubEnv('CI_PROJECT_URL', 'https://gitlab.example.com/group/project')
2735
await expect(detectCiPullRequestContext()).resolves.toMatchObject({
2836
number: 17,
2937
provider: 'gitlab',
38+
url: 'https://gitlab.example.com/group/project/-/merge_requests/17',
3039
})
3140
})
3241

@@ -35,14 +44,37 @@ describe('detectCiPullRequestContext', () => {
3544
async target => {
3645
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '9')
3746
vi.stubEnv('SYSTEM_PULLREQUEST_TARGETBRANCH', target)
47+
vi.stubEnv(
48+
'BUILD_REPOSITORY_URI',
49+
'https://dev.azure.com/acme/platform/_git/widgets',
50+
)
3851
await expect(detectCiPullRequestContext()).resolves.toMatchObject({
3952
baseBranch: 'release/v1',
4053
number: 9,
4154
provider: 'azure',
55+
url: 'https://dev.azure.com/acme/platform/_git/widgets/pullrequest/9',
4256
})
4357
},
4458
)
4559

60+
it.each([
61+
[
62+
'https://github.com/acme/widgets',
63+
'https://github.com/acme/widgets/pull/9',
64+
],
65+
[
66+
'https://github.com.attacker.invalid/acme/widgets',
67+
'https://github.com.attacker.invalid/acme/widgets/pullrequest/9',
68+
],
69+
])(
70+
'uses the Azure repository host to choose its PR URL',
71+
async (repository, url) => {
72+
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '9')
73+
vi.stubEnv('BUILD_REPOSITORY_URI', repository)
74+
await expect(detectCiPullRequestContext()).resolves.toMatchObject({ url })
75+
},
76+
)
77+
4678
it('ignores zero and malformed provider values', async () => {
4779
vi.stubEnv('CI_MERGE_REQUEST_IID', '0')
4880
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTID', 'nope')

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

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ async function runCiScan({
217217
}): Promise<void> {
218218
const { number: pullRequest } = pullRequestContext
219219
let baselineScanId: string | undefined
220+
let incompleteBaseline = false
220221

221222
if (pullRequest) {
222223
const baselineCResult = await selectBaselineScan({
@@ -226,24 +227,36 @@ async function runCiScan({
226227
repo: repoName,
227228
})
228229
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),
230+
const canScanWithoutAzureBaseline =
231+
pullRequestContext.provider === 'azure' &&
232+
baselineCResult.code === undefined &&
233+
(baselineCResult.message === 'Cannot select PR scan baseline' ||
234+
baselineCResult.message === 'No matching PR scan baseline found')
235+
if (!canScanWithoutAzureBaseline) {
236+
process.exitCode = baselineCResult.code ?? 1
237+
logger.log(
238+
pythonJsonFormat
239+
? `${JSON.stringify(
240+
createPythonDiffJsonFailure(
241+
baselineCResult.message,
242+
baselineCResult.cause,
243+
pythonJsonContext,
244+
),
245+
null,
246+
2,
247+
)}\n`
248+
: serializeResultJson(baselineCResult),
249+
)
250+
return
251+
}
252+
incompleteBaseline = true
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 and this run will exit with an infrastructure error.`,
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)
@@ -376,4 +392,7 @@ async function runCiScan({
376392
// Don't set 'tmp' when 'pendingHead' is true.
377393
tmp: false,
378394
})
395+
if (incompleteBaseline) {
396+
setCiExitCode('infrastructure', 3)
397+
}
379398
}

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

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ describe('detectCiPullRequestContext', () => {
9797
it('uses GH_TOKEN to publish the finished CI report and update comments on rerun', async () => {
9898
const comments: Array<{ id: number; body: string }> = []
9999
const writes: string[] = []
100+
let baselineAvailable = true
100101
const server = createServer(async (request, response) => {
101102
response.setHeader('content-type', 'application/json')
102103
const list = '/repos/example/project/issues/42/comments'
@@ -155,7 +156,14 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun
155156
getDefaultOrgSlug: async () => ({ ok: true, data: 'example' }),
156157
}))
157158
vi.doMock('./select-baseline-scan.mts', () => ({
158-
selectBaselineScan: async () => ({ ok: true, data: { id: 'base' } }),
159+
selectBaselineScan: async () =>
160+
baselineAvailable
161+
? { ok: true, data: { id: 'base' } }
162+
: {
163+
ok: false,
164+
message: 'No matching PR scan baseline found',
165+
cause: 'No scan exists for the target commit.',
166+
},
159167
}))
160168
const fetchComments = vi.fn(async () => ({
161169
ok: true,
@@ -238,6 +246,27 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun
238246
'PATCH',
239247
'PATCH',
240248
])
249+
baselineAvailable = false
250+
process.exitCode = 0
251+
vi.stubEnv('GITHUB_REF', '')
252+
vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '42')
253+
vi.stubEnv('SYSTEM_PULLREQUEST_TARGETBRANCH', 'refs/heads/main')
254+
vi.stubEnv(
255+
'BUILD_REPOSITORY_URI',
256+
'https://dev.azure.com/acme/platform/_git/project',
257+
)
258+
await handleCi(false)
259+
expect(fetchComments).toHaveBeenCalledTimes(4)
260+
expect(process.exitCode).toBe(3)
261+
expect(writes).toEqual([
262+
'POST',
263+
'POST',
264+
'PATCH',
265+
'PATCH',
266+
'PATCH',
267+
'PATCH',
268+
'PATCH',
269+
])
241270
expect(comments).toHaveLength(2)
242271
} finally {
243272
vi.unstubAllEnvs()

0 commit comments

Comments
 (0)