From fa9ef3f421bcaef747736aefee3e6d54a23bb266 Mon Sep 17 00:00:00 2001 From: jdalton Date: Fri, 4 Dec 2026 00:39:29 -0500 Subject: [PATCH] feat(python-cli-parity): add SCM scan context and Azure CI --- docs/commands/ci.md | 14 +++ .../ci/detect-ci-pull-request-context.mts | 89 ++++++++++++++++++- src/commands/ci/handle-ci.mts | 50 +++++++---- .../scan/fetch-create-org-full-scan.mts | 45 ++++++---- .../scan/fetch-create-org-full-scan.test.mts | 48 ++++++++++ src/commands/scan/fetch-diff-scan.mts | 3 + src/commands/scan/handle-create-new-scan.mts | 12 +++ src/commands/scan/handle-diff-scan.mts | 9 +- src/commands/scan/handle-scan-report.mts | 4 + src/commands/scan/output-scan-report.mts | 47 +++++++++- .../detect-ci-pull-request-context.test.mts | 49 ++++++++++ test/unit/src/commands/ci/handle-ci.test.mts | 43 ++++++++- .../commands/scan/fetch-diff-scan.test.mts | 30 +++++++ .../commands/scan/output-diff-scan.test.mts | 30 +++++++ .../commands/scan/output-scan-report.test.mts | 34 +++++++ workflows/azure-pipelines.yml | 28 ++++++ 16 files changed, 493 insertions(+), 42 deletions(-) create mode 100644 src/commands/scan/fetch-create-org-full-scan.test.mts create mode 100644 workflows/azure-pipelines.yml diff --git a/docs/commands/ci.md b/docs/commands/ci.md index e7a067437..6223841b0 100644 --- a/docs/commands/ci.md +++ b/docs/commands/ci.md @@ -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. diff --git a/src/commands/ci/detect-ci-pull-request-context.mts b/src/commands/ci/detect-ci-pull-request-context.mts index 168ee1746..e3ac512ed 100644 --- a/src/commands/ci/detect-ci-pull-request-context.mts +++ b/src/commands/ci/detect-ci-pull-request-context.mts @@ -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 { + 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 { @@ -35,6 +106,12 @@ export async function detectCiPullRequestContext(): Promise { onDiffOutcome(outcome) diff --git a/src/commands/scan/fetch-create-org-full-scan.mts b/src/commands/scan/fetch-create-org-full-scan.mts index 4a0569f4e..54f4aeb5d 100644 --- a/src/commands/scan/fetch-create-org-full-scan.mts +++ b/src/commands/scan/fetch-create-org-full-scan.mts @@ -8,7 +8,9 @@ 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[2] export type FetchCreateOrgFullScanConfigs = { branchName: string @@ -16,6 +18,8 @@ export type FetchCreateOrgFullScanConfigs = { commitMessage: string committers: string pullRequest: number + integrationType?: FullScanCreateOptions['integration_type'] + integrationOrgSlug?: string | undefined repoName: string scanType: string | undefined workspace?: string | undefined @@ -40,6 +44,8 @@ export async function fetchCreateOrgFullScan( commitHash, commitMessage, committers, + integrationOrgSlug, + integrationType, pullRequest, repoName, scanType, @@ -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' }, ) } diff --git a/src/commands/scan/fetch-create-org-full-scan.test.mts b/src/commands/scan/fetch-create-org-full-scan.test.mts new file mode 100644 index 000000000..acd4927a9 --- /dev/null +++ b/src/commands/scan/fetch-create-org-full-scan.test.mts @@ -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) => 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, + }), + ) + }) +}) diff --git a/src/commands/scan/fetch-diff-scan.mts b/src/commands/scan/fetch-diff-scan.mts index 084532896..b873b6a46 100644 --- a/src/commands/scan/fetch-diff-scan.mts +++ b/src/commands/scan/fetch-diff-scan.mts @@ -36,10 +36,12 @@ function sleep(ms: number): Promise { } export async function fetchDiffScan({ + externalHref, id1, id2, orgSlug, }: { + externalHref?: string | undefined id1: string id2: string orgSlug: string @@ -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', }, ) diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index d2a05e08a..a12c68c25 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -132,9 +132,12 @@ export type HandleCreateNewScanConfig = { // name; none by default. hints?: CommandHints | undefined interactive: boolean + integrationType?: 'azure' | 'github' | 'gitlab' | undefined + integrationOrgSlug?: string | undefined orgSlug: string pendingHead: boolean pullRequest: number + pullRequestUrl?: string | undefined outputKind: OutputKind reach: Remap< ReachabilityOptions & { @@ -195,12 +198,15 @@ async function createNewScan( cwd, defaultBranch, hints = { flags: new Set() }, + integrationOrgSlug, + integrationType, interactive, onDiffReport, orgSlug, outputKind, pendingHead, pullRequest, + pullRequestUrl, pythonJsonContext, pythonJsonFormat = false, reach: requestedReach, @@ -537,6 +543,8 @@ async function createNewScan( commitMessage, committers, pullRequest, + integrationType, + integrationOrgSlug, repoName, branchName, scanType: @@ -599,6 +607,7 @@ async function createNewScan( if (scanId) { if (baselineScanId) { await handlePrDiffScan({ + externalHref: pullRequestUrl, id1: baselineScanId, id2: scanId, onDiffReport, @@ -615,6 +624,9 @@ async function createNewScan( includeLicensePolicy: true, orgSlug, outputKind, + incompleteDiffContext: pythonJsonFormat + ? (pythonJsonContext ?? {}) + : undefined, reportLevel, scanId, short: false, diff --git a/src/commands/scan/handle-diff-scan.mts b/src/commands/scan/handle-diff-scan.mts index 090dc1aff..a7eae247c 100644 --- a/src/commands/scan/handle-diff-scan.mts +++ b/src/commands/scan/handle-diff-scan.mts @@ -43,6 +43,7 @@ export async function handleDiffScan({ } export async function handlePrDiffScan({ + externalHref, id1, id2, onDiffReport, @@ -52,6 +53,7 @@ export async function handlePrDiffScan({ pythonJsonFormat = false, strictBlocking = false, }: { + externalHref?: string | undefined id1: string id2: string onDiffReport?: @@ -70,7 +72,12 @@ export async function handlePrDiffScan({ pythonJsonContext?: PythonDiffJsonContext | undefined strictBlocking?: boolean | undefined }): Promise { - const result = await fetchDiffScan({ id1, id2, orgSlug }) + const result = await fetchDiffScan({ + ...(externalHref ? { externalHref } : {}), + id1, + id2, + orgSlug, + }) await outputDiffScan(result, { depth: 2, file: '', diff --git a/src/commands/scan/handle-scan-report.mts b/src/commands/scan/handle-scan-report.mts index 5c4f86fb2..f46071b9c 100644 --- a/src/commands/scan/handle-scan-report.mts +++ b/src/commands/scan/handle-scan-report.mts @@ -1,10 +1,12 @@ import { fetchScanData } from './fetch-report-data.mts' import { outputScanReport } from './output-scan-report.mts' +import type { PythonDiffJsonContext } from './python-diff-json.mts' import type { FOLD_SETTING, REPORT_LEVEL } from './types.mts' import type { OutputKind } from '../../types.mts' export type HandleScanReportConfig = { + incompleteDiffContext?: PythonDiffJsonContext | undefined orgSlug: string scanId: string includeLicensePolicy: boolean @@ -23,6 +25,7 @@ export async function handleScanReport({ fold, gitlabSecurityFile, includeLicensePolicy, + incompleteDiffContext, orgSlug, outputKind, reportLevel, @@ -35,6 +38,7 @@ export async function handleScanReport({ await outputScanReport(scanDataCResult, { filepath, + incompleteDiffContext, fold, scanId: scanId, includeLicensePolicy, diff --git a/src/commands/scan/output-scan-report.mts b/src/commands/scan/output-scan-report.mts index b5cfd3f89..c3923aaed 100644 --- a/src/commands/scan/output-scan-report.mts +++ b/src/commands/scan/output-scan-report.mts @@ -3,6 +3,7 @@ import path from 'node:path' import { generateReport } from './generate-report.mts' import { createGitLabDependencyReport } from './gitlab-dependency-report.mts' +import { createPythonDiffJsonFailure } from './python-diff-json.mts' import constants, { EXT_JSON, FOLD_SETTING_NONE, @@ -21,11 +22,13 @@ import { walkNestedMap } from '../../utils/walk-nested-map.mts' import { pluralize } from '../../utils/words.mts' import type { ReportLeafNode, ScanReport } from './generate-report.mts' +import type { PythonDiffJsonContext } from './python-diff-json.mts' import type { FOLD_SETTING, REPORT_LEVEL } from './types.mts' import type { CResult, OutputKind } from '../../types.mts' import type { SocketArtifact } from '../../utils/alert/artifact.mts' export type OutputScanReportConfig = { + incompleteDiffContext?: PythonDiffJsonContext | undefined orgSlug: string scanId: string includeLicensePolicy: boolean @@ -119,6 +122,7 @@ export async function outputScanReport( fold, gitlabSecurityFile, includeLicensePolicy, + incompleteDiffContext, orgSlug, outputKind, reportLevel, @@ -132,7 +136,19 @@ export async function outputScanReport( if (!result.ok) { if (outputKind === OUTPUT_JSON) { - logger.log(serializeResultJson(result)) + logger.log( + incompleteDiffContext + ? JSON.stringify( + createPythonDiffJsonFailure( + result.message, + result.cause, + incompleteDiffContext, + ), + null, + 2, + ) + : serializeResultJson(result), + ) return } logger.fail(failMsgWithBadge(result.message, result.cause)) @@ -181,7 +197,19 @@ export async function outputScanReport( // If report generation somehow failed then .data should not be set. if (outputKind === OUTPUT_JSON) { - logger.log(serializeResultJson(scanReport)) + logger.log( + incompleteDiffContext + ? JSON.stringify( + createPythonDiffJsonFailure( + scanReport.message, + scanReport.cause, + incompleteDiffContext, + ), + null, + 2, + ) + : serializeResultJson(scanReport), + ) return } logger.fail(failMsgWithBadge(scanReport.message, scanReport.cause)) @@ -193,6 +221,21 @@ export async function outputScanReport( setCiExitCode('blocking') } + if (incompleteDiffContext) { + logger.log( + JSON.stringify( + createPythonDiffJsonFailure( + 'Scan comparison could not be completed', + 'No reliable PR baseline was available.', + incompleteDiffContext, + ), + null, + 2, + ), + ) + return + } + // I don't think we emit the default error message with banner for an unhealthy report, do we? // if (!scanReport.data.healthy) { // logger.fail(failMsgWithBadge(scanReport.message, scanReport.cause)) diff --git a/test/unit/src/commands/ci/detect-ci-pull-request-context.test.mts b/test/unit/src/commands/ci/detect-ci-pull-request-context.test.mts index e551c7a72..8cc03ebc9 100644 --- a/test/unit/src/commands/ci/detect-ci-pull-request-context.test.mts +++ b/test/unit/src/commands/ci/detect-ci-pull-request-context.test.mts @@ -2,47 +2,96 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { detectCiPullRequestContext } from '../../../../../src/commands/ci/detect-ci-pull-request-context.mts' +const { spawn } = vi.hoisted(() => ({ spawn: vi.fn() })) +vi.mock('../../../../../src/utils/spawn.mts', () => ({ spawn })) + afterEach(() => { vi.unstubAllEnvs() }) beforeEach(() => { vi.stubEnv('GITHUB_REF', '') + vi.stubEnv('GITHUB_REPOSITORY', '') + vi.stubEnv('GITHUB_SERVER_URL', '') vi.stubEnv('CI_MERGE_REQUEST_IID', '') + vi.stubEnv('CI_PROJECT_URL', '') vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '') vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTID', '') + vi.stubEnv('BUILD_REPOSITORY_URI', '') + vi.stubEnv('SYSTEM_PULLREQUEST_TARGETREPOSITORYURI', '') }) describe('detectCiPullRequestContext', () => { it('detects GitHub pull requests', async () => { vi.stubEnv('GITHUB_REF', 'refs/pull/42/merge') + vi.stubEnv('GITHUB_REPOSITORY', 'octo/project') await expect(detectCiPullRequestContext()).resolves.toMatchObject({ number: 42, provider: 'github', + url: 'https://github.com/octo/project/pull/42', }) }) it('detects GitLab merge requests', async () => { vi.stubEnv('CI_MERGE_REQUEST_IID', '17') + vi.stubEnv('CI_PROJECT_URL', 'https://gitlab.example.com/group/project') await expect(detectCiPullRequestContext()).resolves.toMatchObject({ number: 17, provider: 'gitlab', + url: 'https://gitlab.example.com/group/project/-/merge_requests/17', }) }) + it('uses the target parent only for a verified Azure validation merge', async () => { + const target = 'a'.repeat(40) + const source = 'b'.repeat(40) + const merge = 'c'.repeat(40) + vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTID', '9') + vi.stubEnv('BUILD_SOURCEVERSION', merge) + vi.stubEnv('BUILD_SOURCEBRANCH', 'refs/pull/9/merge') + vi.stubEnv('SYSTEM_PULLREQUEST_SOURCECOMMITID', source) + spawn.mockResolvedValue({ stdout: `${target} ${source}\n` }) + expect((await detectCiPullRequestContext()).baseCommitHash).toBe(target) + vi.stubEnv('SYSTEM_PULLREQUEST_SOURCECOMMITID', target) + expect((await detectCiPullRequestContext()).baseCommitHash).toBeUndefined() + }) + it.each(['refs/heads/release/v1', 'release/v1'])( 'detects an Azure pull request targeting %s', async target => { vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '9') vi.stubEnv('SYSTEM_PULLREQUEST_TARGETBRANCH', target) + vi.stubEnv( + 'BUILD_REPOSITORY_URI', + 'https://dev.azure.com/acme/platform/_git/widgets', + ) await expect(detectCiPullRequestContext()).resolves.toMatchObject({ baseBranch: 'release/v1', number: 9, provider: 'azure', + url: 'https://dev.azure.com/acme/platform/_git/widgets/pullrequest/9', }) }, ) + it.each([ + [ + 'https://github.com/acme/widgets', + 'https://github.com/acme/widgets/pull/9', + ], + [ + 'https://github.com.attacker.invalid/acme/widgets', + 'https://github.com.attacker.invalid/acme/widgets/pullrequest/9', + ], + ])( + 'uses the Azure repository host to choose its PR URL', + async (repository, url) => { + vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '9') + vi.stubEnv('BUILD_REPOSITORY_URI', repository) + await expect(detectCiPullRequestContext()).resolves.toMatchObject({ url }) + }, + ) + it('ignores zero and malformed provider values', async () => { vi.stubEnv('CI_MERGE_REQUEST_IID', '0') vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTID', 'nope') diff --git a/test/unit/src/commands/ci/handle-ci.test.mts b/test/unit/src/commands/ci/handle-ci.test.mts index 32f4fa58a..048d71c1f 100644 --- a/test/unit/src/commands/ci/handle-ci.test.mts +++ b/test/unit/src/commands/ci/handle-ci.test.mts @@ -10,6 +10,7 @@ const githubEnvironmentKeys = [ 'GITHUB_BASE_SHA', 'GITHUB_EVENT_PATH', 'GITHUB_REF', + 'GITHUB_REPOSITORY', ] as const let originalGithubEnvironment: Map @@ -97,6 +98,8 @@ describe('detectCiPullRequestContext', () => { it('uses GH_TOKEN to publish the finished CI report and update comments on rerun', async () => { const comments: Array<{ id: number; body: string }> = [] const writes: string[] = [] + let reportExitCode: number | undefined + let baselineAvailable = true const server = createServer(async (request, response) => { response.setHeader('content-type', 'application/json') const list = '/repos/example/project/issues/42/comments' @@ -160,7 +163,14 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun vi.doMock( '../../../../../src/commands/ci/select-baseline-scan.mts', () => ({ - selectBaselineScan: async () => ({ ok: true, data: { id: 'base' } }), + selectBaselineScan: async () => + baselineAvailable + ? { ok: true, data: { id: 'base' } } + : { + ok: false, + message: 'No matching PR scan baseline found', + cause: 'No scan exists for the target commit.', + }, }), ) const fetchComments = vi.fn(async () => ({ @@ -208,7 +218,11 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun vi.doMock( '../../../../../src/commands/scan/handle-scan-report.mts', () => ({ - handleScanReport: async () => {}, + handleScanReport: async () => { + if (reportExitCode !== undefined) { + process.exitCode = reportExitCode + } + }, }), ) vi.doMock( @@ -257,6 +271,31 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun 'PATCH', 'PATCH', ]) + baselineAvailable = false + process.exitCode = 0 + vi.stubEnv('GITHUB_REF', '') + vi.stubEnv('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', '42') + vi.stubEnv('SYSTEM_PULLREQUEST_TARGETBRANCH', 'refs/heads/main') + vi.stubEnv( + 'BUILD_REPOSITORY_URI', + 'https://dev.azure.com/acme/platform/_git/project', + ) + await handleCi(false) + expect(fetchComments).toHaveBeenCalledTimes(4) + expect(process.exitCode).toBe(3) + reportExitCode = 2 + await handleCi(false) + expect(process.exitCode).toBe(2) + process.exitCode = 0 + expect(writes).toEqual([ + 'POST', + 'POST', + 'PATCH', + 'PATCH', + 'PATCH', + 'PATCH', + 'PATCH', + ]) expect(comments).toHaveLength(2) } finally { vi.unstubAllEnvs() diff --git a/test/unit/src/commands/scan/fetch-diff-scan.test.mts b/test/unit/src/commands/scan/fetch-diff-scan.test.mts index 76970db51..c5be124b9 100644 --- a/test/unit/src/commands/scan/fetch-diff-scan.test.mts +++ b/test/unit/src/commands/scan/fetch-diff-scan.test.mts @@ -89,4 +89,34 @@ describe('fetchDiffScan', () => { expect(result).toEqual({ ok: true, data: DIFF_SCAN }) expect(nock.isDone()).toBe(true) }) + + it('associates a pull request URL with the diff scan', async () => { + nock(BASE_HOST) + .post('/v0/orgs/test-org/diff-scans/from-ids', { + external_href: + 'https://dev.azure.com/acme/platform/_git/widgets/pullrequest/17', + }) + .query({ + before: 'scan-before', + after: 'scan-after', + on_duplicate: 'update', + }) + .reply(200, { diff_scan: { id: 'diff-1' } }) + + nock(BASE_HOST) + .get('/v0/orgs/test-org/diff-scans/diff-1') + .query({ cached: 'true' }) + .reply(200, DIFF_SCAN) + + const result = await fetchDiffScan({ + externalHref: + 'https://dev.azure.com/acme/platform/_git/widgets/pullrequest/17', + id1: 'scan-before', + id2: 'scan-after', + orgSlug: 'test-org', + }) + + expect(result).toEqual({ ok: true, data: DIFF_SCAN }) + expect(nock.isDone()).toBe(true) + }) }) diff --git a/test/unit/src/commands/scan/output-diff-scan.test.mts b/test/unit/src/commands/scan/output-diff-scan.test.mts index ca30af64a..1329cbf38 100644 --- a/test/unit/src/commands/scan/output-diff-scan.test.mts +++ b/test/unit/src/commands/scan/output-diff-scan.test.mts @@ -141,6 +141,36 @@ describe('outputDiffScan strict blocking', () => { expect(process.exitCode).toBe(1) }) + it('passes the PR URL to diff scan creation', async () => { + fetchDiffScan.mockResolvedValue({ + ok: true, + data: { + diff_scan: { + id: 'diff-id', + before_full_scan: { id: 'before' }, + after_full_scan: { id: 'after' }, + artifacts: { added: [], updated: [], replaced: [] }, + html_url: null, + }, + }, + }) + + await handlePrDiffScan({ + externalHref: 'https://github.com/example/project/pull/42', + id1: 'before', + id2: 'after', + orgSlug: 'example', + outputKind: 'json', + }) + + expect(fetchDiffScan).toHaveBeenCalledWith({ + externalHref: 'https://github.com/example/project/pull/42', + id1: 'before', + id2: 'after', + orgSlug: 'example', + }) + }) + it('fails when an unchanged alert blocks under strict mode', async () => { await outputDiffScan({ ok: true, data: diff } as never, { depth: 0, diff --git a/test/unit/src/commands/scan/output-scan-report.test.mts b/test/unit/src/commands/scan/output-scan-report.test.mts index 45b4447e9..bc9949b81 100644 --- a/test/unit/src/commands/scan/output-scan-report.test.mts +++ b/test/unit/src/commands/scan/output-scan-report.test.mts @@ -329,6 +329,40 @@ describe('output-scan-report', () => { expect(process.exitCode).toBeUndefined() }) + it('reports an incomplete Python diff while preserving a blocking full scan', async () => { + const log = vi.spyOn(logger, 'log').mockImplementation(() => {}) + try { + mockGenerateReport.mockReturnValue({ + ok: true, + data: getUnhealthyReport(), + }) + await outputScanReport( + { ok: true, data: { scan: [] } }, + { + orgSlug: 'test-org', + scanId: 'test-scan', + includeLicensePolicy: false, + outputKind: 'json', + filepath: '-', + fold: 'none', + reportLevel: 'error', + short: false, + incompleteDiffContext: { repo: 'example/project' }, + }, + ) + expect(log).toHaveBeenCalledTimes(1) + expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toMatchObject({ + schema_version: 'python-v1', + comparison_status: 'incomplete', + decision: 'unknown', + repo: 'example/project', + }) + expect(process.exitCode).toBe(1) + } finally { + log.mockRestore() + } + }) + it('lets --disable-blocking make an unhealthy report non-blocking', async () => { setCiExitCodePolicy({ disableBlocking: true }) mockGenerateReport.mockReturnValue({ diff --git a/workflows/azure-pipelines.yml b/workflows/azure-pipelines.yml new file mode 100644 index 000000000..525e907cf --- /dev/null +++ b/workflows/azure-pipelines.yml @@ -0,0 +1,28 @@ +# Socket scan-only example for Azure Pipelines. +# Azure Repos PR validation is configured with a branch policy; the `pr` trigger +# below applies to GitHub repositories hosted by Azure Pipelines. +trigger: + branches: + include: + - '*' + +pr: + branches: + include: + - '*' + +pool: + vmImage: ubuntu-latest + +steps: + - checkout: self + fetchDepth: 0 + + - task: NodeTool@0 + inputs: + versionSpec: '22.x' + + - script: npx --yes socket ci + displayName: Socket dependency scan + env: + SOCKET_CLI_API_TOKEN: $(SOCKET_CLI_API_TOKEN)