Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions docs/commands/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
53 changes: 53 additions & 0 deletions src/commands/ci/gitlab-commit-status-context.mts
Original file line number Diff line number Diff line change
@@ -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<string, string | undefined>,
): boolean {
return (
context.provider === 'gitlab' &&
context.number > 0 &&
envAsBoolean(environment['SOCKET_CLI_ENABLE_GITLAB_COMMIT_STATUS'])
)
}

export function isGitLabMergePipelineCheckEnabled(
context: CiPullRequestContext,
environment: Record<string, string | undefined>,
): boolean {
return (
context.provider === 'gitlab' &&
context.number > 0 &&
envAsBoolean(environment['SOCKET_CLI_ENABLE_GITLAB_MERGE_PIPELINE_CHECK'])
)
}

export function getGitLabCommitStatusContext(
context: CiPullRequestContext,
environment: Record<string, string | undefined>,
): 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'],
}
}
103 changes: 103 additions & 0 deletions src/commands/ci/gitlab-commit-status-context.test.mts
Original file line number Diff line number Diff line change
@@ -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)
})
})
49 changes: 46 additions & 3 deletions src/commands/ci/handle-ci.mts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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<void> {
const pullRequestContext = await detectCiPullRequestContext()
debugFn('notice', 'Starting CI scan')
debugDir('inspect', { autoManifest })

Expand All @@ -28,15 +33,52 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
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<ReturnType<typeof detectCiPullRequestContext>>
repoName: string
}): Promise<void> {
const { number: pullRequest } = pullRequestContext
let baselineScanId: string | undefined

if (pullRequest) {
Expand Down Expand Up @@ -77,7 +119,8 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
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'])
Expand Down
Loading
Loading