diff --git a/.gitignore b/.gitignore index 24e24c49d..c5a06d116 100644 --- a/.gitignore +++ b/.gitignore @@ -880,6 +880,12 @@ !/src/utils/github-errors.test.mts !/src/utils/github.mts !/src/utils/gitlab.mts +!/src/commands/ci/gitlab-commit-status-context.mts +!/src/commands/ci/gitlab-commit-status-context.test.mts +!/src/commands/ci/publish-gitlab-commit-status.mts +!/src/commands/ci/publish-gitlab-commit-status.test.mts +!/src/commands/scan/diff-scan-verdict.mts +!/src/commands/scan/diff-scan-verdict.test.mts !/src/commands/ci/publish-gitlab-mr-notes.mts !/src/commands/ci/publish-gitlab-mr-notes.test.mts !/src/commands/ci/publish-pr-comments.mts diff --git a/docs/commands/ci.md b/docs/commands/ci.md index e34aff45c..6e5a2bde7 100644 --- a/docs/commands/ci.md +++ b/docs/commands/ci.md @@ -38,3 +38,21 @@ limited to selected endpoints), so it is not sufficient for publishing. Do not expose a long-lived access token to untrusted fork pipelines. The Socket API token still needs `full-scans:list`, `diff-scans:create`, and `diff-scans:list` to fetch the diff and rendered comments. + +GitLab commit status is also opt-in. Set +`SOCKET_CLI_ENABLE_GITLAB_COMMIT_STATUS=true` to publish a status for the +pipeline's `CI_PROJECT_ID` and `CI_COMMIT_SHA`. Merge request pipelines use the +pipeline commit (including a merge train commit); the status description says +either `No blocking findings`, `Blocking findings detected`, or +`Scan did not complete` for an API or infrastructure failure. A successful +scan status links to the diff report when the Socket API returned a report URL. +Status publication errors are reported separately and do not change the scan's +exit status. The GitLab access token needs `api` scope and Developer access to +the pipeline project. `CI_JOB_TOKEN` cannot write commit statuses. + +To change the target project's merge policy, also set +`SOCKET_CLI_ENABLE_GITLAB_MERGE_PIPELINE_CHECK=true`. This separately opts in +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. diff --git a/src/commands/ci/gitlab-commit-status-context.mts b/src/commands/ci/gitlab-commit-status-context.mts new file mode 100644 index 000000000..bfa95be0a --- /dev/null +++ b/src/commands/ci/gitlab-commit-status-context.mts @@ -0,0 +1,53 @@ +import { envAsBoolean } from '../../utils/env.mts' + +import type { CiPullRequestContext } from './detect-ci-pull-request-context.mts' + +export type GitLabCommitStatusContext = { + projectId: string | undefined + targetProjectId: string | undefined + commitSha: string | undefined + sourceBranch: string | undefined +} + +export function isGitLabCommitStatusEnabled( + context: CiPullRequestContext, + environment: Record, +): boolean { + return ( + context.provider === 'gitlab' && + context.number > 0 && + envAsBoolean(environment['SOCKET_CLI_ENABLE_GITLAB_COMMIT_STATUS']) + ) +} + +export function isGitLabMergePipelineCheckEnabled( + context: CiPullRequestContext, + environment: Record, +): boolean { + return ( + context.provider === 'gitlab' && + context.number > 0 && + envAsBoolean(environment['SOCKET_CLI_ENABLE_GITLAB_MERGE_PIPELINE_CHECK']) + ) +} + +export function getGitLabCommitStatusContext( + context: CiPullRequestContext, + environment: Record, +): GitLabCommitStatusContext | undefined { + if (context.provider !== 'gitlab' || context.number <= 0) { + return undefined + } + const mergeTrain = + environment['CI_MERGE_REQUEST_EVENT_TYPE'] === 'merge_train' + return { + commitSha: environment['CI_COMMIT_SHA'], + projectId: environment['CI_PROJECT_ID'], + targetProjectId: environment['CI_MERGE_REQUEST_PROJECT_ID'], + sourceBranch: + mergeTrain || + environment['CI_MERGE_REQUEST_EVENT_TYPE'] === 'merged_result' + ? undefined + : environment['CI_MERGE_REQUEST_SOURCE_BRANCH_NAME'], + } +} diff --git a/src/commands/ci/gitlab-commit-status-context.test.mts b/src/commands/ci/gitlab-commit-status-context.test.mts new file mode 100644 index 000000000..656026bf9 --- /dev/null +++ b/src/commands/ci/gitlab-commit-status-context.test.mts @@ -0,0 +1,103 @@ +import { describe, expect, it } from 'vitest' + +import { + getGitLabCommitStatusContext, + isGitLabCommitStatusEnabled, + isGitLabMergePipelineCheckEnabled, +} from './gitlab-commit-status-context.mts' + +const gitLabMr = { + baseBranch: 'main', + baseCommitHash: 'base', + number: 17, + provider: 'gitlab' as const, +} + +describe('GitLab commit status context', () => { + it('uses the pipeline project and commit for fork merge requests', () => { + expect( + getGitLabCommitStatusContext(gitLabMr, { + CI_PROJECT_ID: 'pipeline-project-id', + CI_MERGE_REQUEST_PROJECT_ID: 'target-project-id', + CI_MERGE_REQUEST_SOURCE_BRANCH_NAME: 'feature', + CI_MERGE_REQUEST_SOURCE_BRANCH_SHA: 'source-sha', + CI_COMMIT_SHA: 'merge-result-sha', + }), + ).toEqual({ + projectId: 'pipeline-project-id', + targetProjectId: 'target-project-id', + commitSha: 'merge-result-sha', + sourceBranch: 'feature', + }) + }) + + it('uses the merge train commit and omits the source ref', () => { + expect( + getGitLabCommitStatusContext(gitLabMr, { + CI_PROJECT_ID: 'target-project-id', + CI_MERGE_REQUEST_PROJECT_ID: 'target-project-id', + CI_MERGE_REQUEST_SOURCE_BRANCH_NAME: 'feature', + CI_MERGE_REQUEST_SOURCE_BRANCH_SHA: 'source-sha', + CI_COMMIT_SHA: 'train-sha', + CI_MERGE_REQUEST_EVENT_TYPE: 'merge_train', + }), + ).toEqual({ + projectId: 'target-project-id', + targetProjectId: 'target-project-id', + commitSha: 'train-sha', + sourceBranch: undefined, + }) + }) + + it('keeps the merge-result pipeline commit and omits the source ref', () => { + expect( + getGitLabCommitStatusContext(gitLabMr, { + CI_PROJECT_ID: 'target-project-id', + CI_MERGE_REQUEST_PROJECT_ID: 'target-project-id', + CI_MERGE_REQUEST_SOURCE_BRANCH_NAME: 'feature', + CI_MERGE_REQUEST_SOURCE_BRANCH_SHA: 'source-sha', + CI_COMMIT_SHA: 'merged-result-sha', + CI_MERGE_REQUEST_EVENT_TYPE: 'merged_result', + }), + ).toEqual({ + projectId: 'target-project-id', + targetProjectId: 'target-project-id', + commitSha: 'merged-result-sha', + sourceBranch: undefined, + }) + }) + + it('returns no status target outside a merge request', () => { + expect( + getGitLabCommitStatusContext( + { ...gitLabMr, number: 0, provider: undefined }, + { CI_COMMIT_SHA: 'sha' }, + ), + ).toBeUndefined() + }) + + it('requires separate opt-ins for commit status and project settings', () => { + const environment = { + SOCKET_CLI_ENABLE_GITLAB_COMMIT_STATUS: 'true', + SOCKET_CLI_ENABLE_GITLAB_MERGE_PIPELINE_CHECK: '', + } + expect(isGitLabCommitStatusEnabled(gitLabMr, environment)).toBe(true) + expect(isGitLabMergePipelineCheckEnabled(gitLabMr, environment)).toBe(false) + expect( + isGitLabMergePipelineCheckEnabled(gitLabMr, { + ...environment, + SOCKET_CLI_ENABLE_GITLAB_MERGE_PIPELINE_CHECK: 'true', + }), + ).toBe(true) + }) + + it('does not enable either integration for a missing merge request', () => { + const noMr = { ...gitLabMr, number: 0 } + const enabled = { + SOCKET_CLI_ENABLE_GITLAB_COMMIT_STATUS: 'true', + SOCKET_CLI_ENABLE_GITLAB_MERGE_PIPELINE_CHECK: 'true', + } + expect(isGitLabCommitStatusEnabled(noMr, enabled)).toBe(false) + expect(isGitLabMergePipelineCheckEnabled(noMr, enabled)).toBe(false) + }) +}) diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index 5bd7cb32b..5519155b4 100644 --- a/src/commands/ci/handle-ci.mts +++ b/src/commands/ci/handle-ci.mts @@ -1,5 +1,9 @@ import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts' import { getDefaultOrgSlug } from './fetch-default-org-slug.mts' +import { + reportGitLabCommitStatusFailure, + withGitLabCommitStatus, +} from './publish-gitlab-commit-status.mts' import { publishGitLabMergeRequestNotes } from './publish-gitlab-mr-notes.mts' import { publishPullRequestComments } from './publish-pr-comments.mts' import { selectBaselineScan } from './select-baseline-scan.mts' @@ -18,6 +22,7 @@ import { serializeResultJson } from '../../utils/serialize-result-json.mts' import { handleCreateNewScan } from '../scan/handle-create-new-scan.mts' export async function handleCi(autoManifest: boolean): Promise { + const pullRequestContext = await detectCiPullRequestContext() debugFn('notice', 'Starting CI scan') debugDir('inspect', { autoManifest }) @@ -28,15 +33,52 @@ export async function handleCi(autoManifest: boolean): Promise { setCiExitCode('api', orgSlugCResult.code ?? 1) // Always assume json mode. logger.log(serializeResultJson(orgSlugCResult)) + await reportGitLabCommitStatusFailure( + pullRequestContext, + 'Socket API unavailable; scan did not complete', + ) return } const orgSlug = orgSlugCResult.data - const pullRequestContext = await detectCiPullRequestContext() - const { number: pullRequest } = pullRequestContext const cwd = process.cwd() const branchName = (await gitBranch(cwd)) || (await detectDefaultBranch(cwd)) const repoName = await getRepoName(cwd) + await withGitLabCommitStatus(pullRequestContext, async onDiffOutcome => { + await runCiScan({ + autoManifest, + branchName, + cwd, + onDiffOutcome, + orgSlug, + pullRequestContext, + repoName, + }) + }) +} + +async function runCiScan({ + autoManifest, + branchName, + cwd, + onDiffOutcome, + orgSlug, + pullRequestContext, + repoName, +}: { + autoManifest: boolean + branchName: string + cwd: string + onDiffOutcome: (outcome: { + blocking: boolean + incomplete: boolean + reportUrl: string | null + }) => void + orgSlug: string + pullRequestContext: Awaited> + repoName: string +}): Promise { + const { number: pullRequest } = pullRequestContext let baselineScanId: string | undefined if (pullRequest) { @@ -77,7 +119,8 @@ export async function handleCi(autoManifest: boolean): Promise { pendingHead: true, pullRequest, baselineScanId, - onDiffReport: async diffScanId => { + onDiffReport: async (diffScanId, outcome) => { + onDiffOutcome(outcome) if ( pullRequestContext.provider === 'gitlab' && envAsBoolean(process.env['SOCKET_CLI_ENABLE_GITLAB_MR_NOTES']) diff --git a/src/commands/ci/publish-gitlab-commit-status.mts b/src/commands/ci/publish-gitlab-commit-status.mts new file mode 100644 index 000000000..e3659febf --- /dev/null +++ b/src/commands/ci/publish-gitlab-commit-status.mts @@ -0,0 +1,182 @@ +import { + getGitLabCommitStatusContext, + isGitLabCommitStatusEnabled, + isGitLabMergePipelineCheckEnabled, +} from './gitlab-commit-status-context.mts' +import { errorMessage } from '../../utils/errors.mts' +import { gitLabApiRequest } from '../../utils/gitlab.mts' + +import type { CiPullRequestContext } from './detect-ci-pull-request-context.mts' + +export async function publishGitLabCommitStatus({ + commitSha, + description, + projectId, + reportUrl, + sourceBranch, + state, +}: { + commitSha: string + description: string + projectId: string + reportUrl: string | null + sourceBranch?: string | undefined + state: 'failed' | 'success' +}): Promise { + await gitLabApiRequest({ + path: `projects/${encodeURIComponent(projectId)}/statuses/${encodeURIComponent(commitSha)}`, + method: 'POST', + body: { + state, + context: 'socket-security-commit-status', + description, + ...(sourceBranch ? { ref: sourceBranch } : {}), + ...(reportUrl ? { target_url: reportUrl } : {}), + }, + }) +} + +export async function enableGitLabMergePipelineCheck({ + projectId, +}: { + projectId: string +}): Promise { + try { + await gitLabApiRequest({ + path: `projects/${encodeURIComponent(projectId)}`, + method: 'PUT', + body: { only_allow_merge_if_pipeline_succeeds: true }, + }) + } catch (error) { + const message = errorMessage(error) + const status = /HTTP \d{3}/u.exec(message)?.[0] + if (status) { + throw new Error( + `GitLab could not enable the merge pipeline check (${status}). Use a valid project access token with api scope and Maintainer access to the target project.`, + ) + } + throw error + } +} + +export async function withGitLabCommitStatus( + context: CiPullRequestContext, + run: ( + onDiffOutcome: (outcome: { + blocking: boolean + incomplete: boolean + reportUrl: string | null + }) => void, + ) => Promise, +): Promise { + const statusEnabled = isGitLabCommitStatusEnabled(context, process.env) + const mergeCheckEnabled = isGitLabMergePipelineCheckEnabled( + context, + process.env, + ) + const target = getGitLabCommitStatusContext(context, process.env) + let status: { + description: string + reportUrl: string | null + state: 'failed' | 'success' + } = { + description: 'Scan did not complete (API or infrastructure error)', + reportUrl: null, + state: 'failed', + } + const setOutcome = (outcome: { + blocking: boolean + incomplete: boolean + reportUrl: string | null + }): void => { + status = { + description: outcome.incomplete + ? 'Diff incomplete; some artifacts could not be evaluated' + : outcome.blocking + ? 'Blocking findings detected' + : 'No blocking findings', + reportUrl: outcome.reportUrl, + state: outcome.incomplete || outcome.blocking ? 'failed' : 'success', + } + } + + try { + await run(setOutcome) + } finally { + if (statusEnabled && !target?.projectId) { + console.error( + 'Socket could not publish GitLab commit status: missing CI_PROJECT_ID.', + ) + } + if (statusEnabled && !target?.commitSha) { + console.error( + 'Socket could not publish GitLab commit status: missing CI_COMMIT_SHA.', + ) + } + if (mergeCheckEnabled && !target?.targetProjectId) { + console.error( + 'Socket could not enable the GitLab merge pipeline check: missing CI_MERGE_REQUEST_PROJECT_ID.', + ) + } + if (mergeCheckEnabled && target?.targetProjectId) { + try { + await enableGitLabMergePipelineCheck({ + projectId: target.targetProjectId, + }) + } catch (error) { + console.error( + 'Socket could not enable the GitLab merge pipeline check. This setting requires Maintainer access:', + errorMessage(error), + ) + } + } + if (statusEnabled && target?.projectId && target.commitSha) { + try { + await publishGitLabCommitStatus({ + commitSha: target.commitSha, + description: status.description, + projectId: target.projectId, + reportUrl: status.reportUrl, + ...(target.sourceBranch ? { sourceBranch: target.sourceBranch } : {}), + state: status.state, + }) + } catch (error) { + console.error( + 'Socket could not publish GitLab commit status:', + errorMessage(error), + ) + } + } + } +} + +export async function reportGitLabCommitStatusFailure( + context: CiPullRequestContext, + description: string, +): Promise { + if (!isGitLabCommitStatusEnabled(context, process.env)) { + return + } + const target = getGitLabCommitStatusContext(context, process.env) + if (!target?.projectId || !target.commitSha) { + console.error( + 'Socket could not publish GitLab commit status: missing CI_PROJECT_ID or CI_COMMIT_SHA.', + ) + return + } + try { + await publishGitLabCommitStatus({ + commitSha: target.commitSha, + description, + projectId: target.projectId, + reportUrl: null, + ...(target.sourceBranch ? { sourceBranch: target.sourceBranch } : {}), + state: 'failed', + }) + } catch (error) { + console.error( + 'Socket could not publish GitLab commit status:', + errorMessage(error), + ) + } +} diff --git a/src/commands/ci/publish-gitlab-commit-status.test.mts b/src/commands/ci/publish-gitlab-commit-status.test.mts new file mode 100644 index 000000000..f8cadd61a --- /dev/null +++ b/src/commands/ci/publish-gitlab-commit-status.test.mts @@ -0,0 +1,254 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { + enableGitLabMergePipelineCheck, + publishGitLabCommitStatus, + withGitLabCommitStatus, +} from './publish-gitlab-commit-status.mts' +import { UNKNOWN_ERROR } from '../../constants.mts' +import { gitLabApiRequest } from '../../utils/gitlab.mts' + +vi.mock('../../utils/gitlab.mts', () => ({ + gitLabApiRequest: vi.fn(), +})) + +describe('GitLab commit status publication', () => { + beforeEach(() => { + vi.resetAllMocks() + vi.mocked(gitLabApiRequest).mockResolvedValue({ data: {} }) + }) + + afterEach(() => vi.unstubAllEnvs()) + + it('publishes a passing status with the report link', async () => { + await publishGitLabCommitStatus({ + commitSha: 'commit-sha', + description: 'No blocking findings', + projectId: 'pipeline/project', + reportUrl: 'https://dashboard.socket.dev/diff/123', + sourceBranch: 'feature', + state: 'success', + }) + expect(gitLabApiRequest).toHaveBeenCalledWith({ + path: 'projects/pipeline%2Fproject/statuses/commit-sha', + method: 'POST', + body: { + state: 'success', + context: 'socket-security-commit-status', + description: 'No blocking findings', + ref: 'feature', + target_url: 'https://dashboard.socket.dev/diff/123', + }, + }) + }) + + it('publishes findings and infrastructure failures as failed with different descriptions', async () => { + await publishGitLabCommitStatus({ + commitSha: 'commit-sha', + description: 'Blocking findings detected', + projectId: '17', + reportUrl: null, + state: 'failed', + }) + expect(gitLabApiRequest).toHaveBeenLastCalledWith({ + path: 'projects/17/statuses/commit-sha', + method: 'POST', + body: { + state: 'failed', + context: 'socket-security-commit-status', + description: 'Blocking findings detected', + }, + }) + + await publishGitLabCommitStatus({ + commitSha: 'commit-sha', + description: 'Scan did not complete (API or infrastructure error)', + projectId: '17', + reportUrl: null, + state: 'failed', + }) + expect(gitLabApiRequest).toHaveBeenLastCalledWith( + expect.objectContaining({ + body: expect.objectContaining({ + description: 'Scan did not complete (API or infrastructure error)', + }), + }), + ) + }) + + it('preserves authorization errors for the caller to report', async () => { + vi.mocked(gitLabApiRequest).mockRejectedValueOnce( + new Error('GitLab could not authorize API access (HTTP 403)'), + ) + await expect( + publishGitLabCommitStatus({ + commitSha: 'commit-sha', + description: 'No blocking findings', + projectId: '17', + reportUrl: null, + state: 'success', + }), + ).rejects.toThrow('HTTP 403') + }) + + it('enables the project merge check only when explicitly invoked', async () => { + await enableGitLabMergePipelineCheck({ projectId: 'target/project' }) + expect(gitLabApiRequest).toHaveBeenCalledWith({ + path: 'projects/target%2Fproject', + method: 'PUT', + body: { only_allow_merge_if_pipeline_succeeds: true }, + }) + }) + + it('uses the independent typed verdict when CLI blocking is disabled', async () => { + vi.stubEnv('SOCKET_CLI_ENABLE_GITLAB_COMMIT_STATUS', 'true') + vi.stubEnv('CI_PROJECT_ID', 'pipeline-project') + vi.stubEnv('CI_COMMIT_SHA', 'pipeline-sha') + vi.stubEnv('CI_MERGE_REQUEST_PROJECT_ID', 'target-project') + await withGitLabCommitStatus( + { + baseBranch: 'main', + baseCommitHash: 'base', + number: 42, + provider: 'gitlab', + }, + async setOutcome => { + setOutcome({ + blocking: true, + incomplete: false, + reportUrl: 'https://dashboard.test/diff/1', + }) + }, + ) + expect(gitLabApiRequest).toHaveBeenCalledWith({ + path: 'projects/pipeline-project/statuses/pipeline-sha', + method: 'POST', + body: expect.objectContaining({ + state: 'failed', + description: 'Blocking findings detected', + target_url: 'https://dashboard.test/diff/1', + }), + }) + }) + + it('publishes failure when the scan path returns without a verdict', async () => { + vi.stubEnv('SOCKET_CLI_ENABLE_GITLAB_COMMIT_STATUS', 'true') + vi.stubEnv('CI_PROJECT_ID', 'pipeline-project') + vi.stubEnv('CI_COMMIT_SHA', 'pipeline-sha') + await withGitLabCommitStatus( + { + baseBranch: 'main', + baseCommitHash: 'base', + number: 42, + provider: 'gitlab', + }, + async () => {}, + ) + expect(gitLabApiRequest).toHaveBeenCalledWith( + expect.objectContaining({ + body: expect.objectContaining({ + state: 'failed', + description: 'Scan did not complete (API or infrastructure error)', + }), + }), + ) + }) + + it('never reports an incomplete diff as clean', async () => { + vi.stubEnv('SOCKET_CLI_ENABLE_GITLAB_COMMIT_STATUS', 'true') + vi.stubEnv('CI_PROJECT_ID', 'pipeline-project') + vi.stubEnv('CI_COMMIT_SHA', 'pipeline-sha') + await withGitLabCommitStatus( + { + baseBranch: 'main', + baseCommitHash: 'base', + number: 42, + provider: 'gitlab', + }, + async setOutcome => { + setOutcome({ + blocking: false, + incomplete: true, + reportUrl: 'https://dashboard.test/diff/incomplete', + }) + }, + ) + expect(gitLabApiRequest).toHaveBeenCalledWith({ + path: 'projects/pipeline-project/statuses/pipeline-sha', + method: 'POST', + body: expect.objectContaining({ + state: 'failed', + description: 'Diff incomplete; some artifacts could not be evaluated', + target_url: 'https://dashboard.test/diff/incomplete', + }), + }) + }) + + it('changes the target project setting only with its separate opt-in', async () => { + vi.stubEnv('SOCKET_CLI_ENABLE_GITLAB_MERGE_PIPELINE_CHECK', 'true') + vi.stubEnv('CI_MERGE_REQUEST_PROJECT_ID', 'target-project') + await withGitLabCommitStatus( + { + baseBranch: 'main', + baseCommitHash: 'base', + number: 42, + provider: 'gitlab', + }, + async () => {}, + ) + expect(gitLabApiRequest).toHaveBeenCalledTimes(1) + expect(gitLabApiRequest).toHaveBeenCalledWith({ + path: 'projects/target-project', + method: 'PUT', + body: { only_allow_merge_if_pipeline_succeeds: true }, + }) + }) + + it('does not publish on a branch pipeline without a merge request', async () => { + vi.stubEnv('SOCKET_CLI_ENABLE_GITLAB_COMMIT_STATUS', 'true') + vi.stubEnv('SOCKET_CLI_ENABLE_GITLAB_MERGE_PIPELINE_CHECK', 'true') + await withGitLabCommitStatus( + { + baseBranch: undefined, + baseCommitHash: undefined, + number: 0, + provider: undefined, + }, + async () => {}, + ) + expect(gitLabApiRequest).not.toHaveBeenCalled() + }) + + it.each([ + [ + 'GitLab could not authorize API access (HTTP 403)', + 'GitLab could not authorize API access (HTTP 403)', + ], + ['', UNKNOWN_ERROR], + ])( + 'reports status API failure %j without throwing into scan handling', + async (message, expected) => { + vi.stubEnv('SOCKET_CLI_ENABLE_GITLAB_COMMIT_STATUS', 'true') + vi.stubEnv('CI_PROJECT_ID', 'pipeline-project') + vi.stubEnv('CI_COMMIT_SHA', 'pipeline-sha') + vi.mocked(gitLabApiRequest).mockRejectedValueOnce(new Error(message)) + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + await expect( + withGitLabCommitStatus( + { + baseBranch: 'main', + baseCommitHash: 'base', + number: 42, + provider: 'gitlab', + }, + async () => {}, + ), + ).resolves.toBeUndefined() + expect(errorSpy).toHaveBeenCalledWith( + 'Socket could not publish GitLab commit status:', + expected, + ) + errorSpy.mockRestore() + }, + ) +}) diff --git a/src/commands/scan/diff-scan-verdict.mts b/src/commands/scan/diff-scan-verdict.mts new file mode 100644 index 000000000..6d204a2ab --- /dev/null +++ b/src/commands/scan/diff-scan-verdict.mts @@ -0,0 +1,33 @@ +import type { DiffScanData } from './fetch-diff-scan.mts' + +export function getDiffScanBlocking( + diffScan: DiffScanData['diff_scan'], + strictBlocking = false, +): boolean { + const changedArtifacts = [ + ...diffScan.artifacts.added, + ...diffScan.artifacts.updated, + ...diffScan.artifacts.replaced, + ] + return ( + changedArtifacts.some(artifact => + artifact.alerts?.some(alert => alert.action === 'error'), + ) || + (strictBlocking && + diffScan.artifacts.unchanged?.some(artifact => + artifact.alerts?.some(alert => alert.action === 'error'), + ) === true) + ) +} + +export function getDiffScanVerdict(diffScan: DiffScanData['diff_scan']): { + blocking: boolean + incomplete: boolean + reportUrl: string | null +} { + return { + blocking: getDiffScanBlocking(diffScan), + incomplete: diffScan.incomplete === true, + reportUrl: diffScan.html_url, + } +} diff --git a/src/commands/scan/diff-scan-verdict.test.mts b/src/commands/scan/diff-scan-verdict.test.mts new file mode 100644 index 000000000..f15a2f3b6 --- /dev/null +++ b/src/commands/scan/diff-scan-verdict.test.mts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' + +import { + getDiffScanBlocking, + getDiffScanVerdict, +} from './diff-scan-verdict.mts' + +import type { DiffScanData } from './fetch-diff-scan.mts' + +const cleanDiff = { + artifacts: { + added: [], + updated: [], + replaced: [], + unchanged: [], + }, +} as unknown as DiffScanData['diff_scan'] + +describe('getDiffScanBlocking', () => { + it('returns false for a clean diff', () => { + expect(getDiffScanBlocking(cleanDiff)).toBe(false) + }) + + it('returns true for blocking findings independent of CLI exit-code policy', () => { + const diff = { + artifacts: { + ...cleanDiff.artifacts, + added: [{ alerts: [{ action: 'error' }] }], + }, + } as unknown as DiffScanData['diff_scan'] + expect(getDiffScanBlocking(diff)).toBe(true) + }) + + it('includes unchanged blocking findings only in strict mode', () => { + const diff = { + artifacts: { + ...cleanDiff.artifacts, + unchanged: [{ alerts: [{ action: 'error' }] }], + }, + } as unknown as DiffScanData['diff_scan'] + expect(getDiffScanBlocking(diff)).toBe(false) + expect(getDiffScanBlocking(diff, true)).toBe(true) + }) + + it('preserves incomplete metadata when no alert artifacts are present', () => { + const diff = { + id: 'diff-id', + before_full_scan: { id: 'before-id' }, + after_full_scan: { id: 'after-id' }, + html_url: 'https://dashboard.test/diff/diff-id', + incomplete: true, + artifacts: { + added: [], + updated: [], + replaced: [], + unchanged: [], + }, + } as unknown as DiffScanData['diff_scan'] + expect(getDiffScanVerdict(diff)).toEqual({ + blocking: false, + incomplete: true, + reportUrl: 'https://dashboard.test/diff/diff-id', + }) + }) +}) diff --git a/src/commands/scan/fetch-diff-scan.mts b/src/commands/scan/fetch-diff-scan.mts index 8e5a3b78d..084532896 100644 --- a/src/commands/scan/fetch-diff-scan.mts +++ b/src/commands/scan/fetch-diff-scan.mts @@ -17,6 +17,7 @@ type ExistingDiffScan = Extract< export type DiffScanData = { diff_scan: { id: string + incomplete?: boolean | undefined before_full_scan: ExistingDiffScan['before'] after_full_scan: ExistingDiffScan['after'] html_url: string | null diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index bf0d4ac1b..039176b4e 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -104,7 +104,16 @@ export type HandleCreateNewScanConfig = { autoManifest: boolean baselineScanId?: string | undefined bazel?: BazelScan | undefined - onDiffReport?: ((diffScanId: string) => Promise) | undefined + onDiffReport?: + | (( + diffScanId: string, + outcome: { + blocking: boolean + incomplete: boolean + reportUrl: string | null + }, + ) => Promise) + | undefined branchName: string commitHash: string commitMessage: string diff --git a/src/commands/scan/handle-diff-scan.mts b/src/commands/scan/handle-diff-scan.mts index c70f5730f..b5a740b42 100644 --- a/src/commands/scan/handle-diff-scan.mts +++ b/src/commands/scan/handle-diff-scan.mts @@ -1,3 +1,4 @@ +import { getDiffScanVerdict } from './diff-scan-verdict.mts' import { fetchDiffScan } from './fetch-diff-scan.mts' import { outputDiffScan } from './output-diff-scan.mts' @@ -43,7 +44,16 @@ export async function handlePrDiffScan({ }: { id1: string id2: string - onDiffReport?: ((diffScanId: string) => Promise) | undefined + onDiffReport?: + | (( + diffScanId: string, + outcome: { + blocking: boolean + incomplete: boolean + reportUrl: string | null + }, + ) => Promise) + | undefined orgSlug: string outputKind: OutputKind }): Promise { @@ -55,6 +65,9 @@ export async function handlePrDiffScan({ strictBlocking: false, }) if (result.ok) { - await onDiffReport?.(result.data.diff_scan.id) + await onDiffReport?.( + result.data.diff_scan.id, + getDiffScanVerdict(result.data.diff_scan), + ) } } diff --git a/src/commands/scan/output-diff-scan.mts b/src/commands/scan/output-diff-scan.mts index d40f236bf..82526bd42 100644 --- a/src/commands/scan/output-diff-scan.mts +++ b/src/commands/scan/output-diff-scan.mts @@ -3,6 +3,7 @@ import util from 'node:util' import colors from 'yoctocolors-cjs' +import { getDiffScanBlocking } from './diff-scan-verdict.mts' import constants from '../../constants.mts' import { setCiExitCode } from '../../utils/ci-exit-code.mts' import { failMsgWithBadge } from '../../utils/fail-msg-with-badge.mts' @@ -39,25 +40,7 @@ export async function outputDiffScan( const diffScan = result.data.diff_scan - const changedArtifacts = [ - ...diffScan.artifacts.added, - ...diffScan.artifacts.updated, - ...diffScan.artifacts.replaced, - ] - if ( - changedArtifacts.some(artifact => - artifact.alerts?.some(alert => alert.action === 'error'), - ) - ) { - setCiExitCode('blocking') - } - - if ( - strictBlocking && - diffScan.artifacts.unchanged?.some(artifact => - artifact.alerts?.some(alert => alert.action === 'error'), - ) - ) { + if (getDiffScanBlocking(diffScan, strictBlocking)) { setCiExitCode('blocking') }