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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -879,6 +879,9 @@
!/src/utils/github-errors.mts
!/src/utils/github-errors.test.mts
!/src/utils/github.mts
!/src/utils/gitlab.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
!/src/commands/ci/publish-pr-comments.test.mts
!/src/utils/glob-content-dedup.test.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 @@ -20,3 +20,21 @@ and `diff-scans:list` for the diff and its comments.

Set `SOCKET_CLI_DISABLE_OVERVIEW_COMMENT=true` or
`SOCKET_CLI_DISABLE_SECURITY_COMMENT=true` to skip either comment.

GitLab merge request notes are opt-in. Set
`SOCKET_CLI_ENABLE_GITLAB_MR_NOTES=true` in a GitLab merge request pipeline to
let `socket ci` publish and update the same overview and security notes. This
opt-in avoids duplicate notes when a managed Socket integration already posts
them. The pipeline needs `CI_SERVER_URL`, `CI_API_V4_URL`,
`CI_MERGE_REQUEST_IID`, `CI_MERGE_REQUEST_PROJECT_ID`, and
`CI_MERGE_REQUEST_PROJECT_URL`. Notes are written to the target project,
including for merge requests from forks.

For a personal or project access token, set `SOCKET_CLI_GITLAB_TOKEN` (or
`GITLAB_TOKEN`) to a token with the `api` scope and at least Developer access
to the target project. `CI_JOB_TOKEN` cannot create merge request notes through
GitLab's [Notes API](https://docs.gitlab.com/api/notes/) (job-token access is
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.
41 changes: 41 additions & 0 deletions src/commands/ci/handle-ci.mts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts'
import { getDefaultOrgSlug } from './fetch-default-org-slug.mts'
import { publishGitLabMergeRequestNotes } from './publish-gitlab-mr-notes.mts'
import { publishPullRequestComments } from './publish-pr-comments.mts'
import { selectBaselineScan } from './select-baseline-scan.mts'
import constants from '../../constants.mts'
import { setCiExitCode } from '../../utils/ci-exit-code.mts'
import { debugDir, debugFn } from '../../utils/debug.mts'
import { envAsBoolean } from '../../utils/env.mts'
import { errorMessage } from '../../utils/errors.mts'
import {
detectDefaultBranch,
getRepoName,
Expand Down Expand Up @@ -76,6 +78,45 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
pullRequest,
baselineScanId,
onDiffReport: async diffScanId => {
if (
pullRequestContext.provider === 'gitlab' &&
envAsBoolean(process.env['SOCKET_CLI_ENABLE_GITLAB_MR_NOTES'])
) {
// GitLab publication is opt-in because a managed Socket integration may
// already own these notes. Use GitLab's target project ID for fork MRs.
const projectId = process.env['CI_MERGE_REQUEST_PROJECT_ID']
const projectUrl = process.env['CI_MERGE_REQUEST_PROJECT_URL']
const serverUrl = process.env['CI_SERVER_URL']
if (!projectId || !projectUrl || !serverUrl) {
console.error(
'Socket could not publish GitLab merge request notes: missing target project metadata. Check CI_MERGE_REQUEST_PROJECT_ID, CI_MERGE_REQUEST_PROJECT_URL, and CI_SERVER_URL.',
)
return
}
try {
await publishGitLabMergeRequestNotes({
diffScanId,
disableOverview: envAsBoolean(
process.env['SOCKET_CLI_DISABLE_OVERVIEW_COMMENT'],
),
disableSecurity: envAsBoolean(
process.env['SOCKET_CLI_DISABLE_SECURITY_COMMENT'],
),
orgSlug,
mergeRequestIid: pullRequest,
projectId,
projectUrl,
serverUrl,
})
} catch (error) {
debugFn('warn', 'Could not publish GitLab merge request notes', error)
console.error(
'Socket could not publish GitLab merge request notes:',
errorMessage(error),
)
}
return
}
if (
pullRequestContext.provider !== 'github' ||
!owner ||
Expand Down
105 changes: 105 additions & 0 deletions src/commands/ci/publish-gitlab-mr-notes.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { fetchRenderedPullRequestComments } from './publish-pr-comments.mts'
import { getGitLabServerUrl, gitLabApiRequest } from '../../utils/gitlab.mts'

export const GITLAB_OVERVIEW_NOTE_MARKER =
'<!-- socket-overview-comment-actions -->'
export const GITLAB_SECURITY_NOTE_MARKER =
'<!-- socket-security-comment-actions -->'

type GitLabNote = { id: number; body: string; author: { id: number } }
type GitLabUser = { id: number }

async function findNotes(path: string): Promise<GitLabNote[]> {
const notes: GitLabNote[] = []
let page = '1'
do {
const query = new URLSearchParams({ per_page: '100', page })
// Pagination uses the response header from the current page.
// eslint-disable-next-line no-await-in-loop
const result = await gitLabApiRequest<GitLabNote[]>({
path: `${path}?${query}`,
})
notes.push(...result.data)
page = result.nextPage || ''
} while (page)
return notes
}

export async function publishGitLabMergeRequestNotes({
diffScanId,
disableOverview,
disableSecurity,
mergeRequestIid,
orgSlug,
projectId,
projectUrl,
serverUrl,
}: {
diffScanId: string
disableOverview: boolean
disableSecurity: boolean
orgSlug: string
mergeRequestIid: number
projectId: string
projectUrl: string
serverUrl: string
}): Promise<void> {
if (disableOverview && disableSecurity) {
return
}
const gitLabServerUrl = getGitLabServerUrl()
const configuredServerUrl = new URL(serverUrl)
if (configuredServerUrl.origin !== gitLabServerUrl.origin) {
throw new Error(
'GitLab merge request URL must use the same origin as CI_SERVER_URL',
)
}
const targetProjectUrl = new URL(projectUrl)
if (
targetProjectUrl.origin !== gitLabServerUrl.origin ||
targetProjectUrl.username ||
targetProjectUrl.password ||
targetProjectUrl.search ||
targetProjectUrl.hash
) {
throw new Error(
'GitLab merge request URL must use the same origin as CI_SERVER_URL',
)
}
const mergeRequestUrl = new URL(
`-/merge_requests/${mergeRequestIid}`,
`${targetProjectUrl.href.replace(/\/$/u, '')}/`,
)
const { data: actor } = await gitLabApiRequest<GitLabUser>({ path: 'user' })
const comments = await fetchRenderedPullRequestComments({
diffScanId,
orgSlug,
platform: 'gitlab',
pullRequestUrl: mergeRequestUrl.href,
})
const notesPath = `projects/${encodeURIComponent(projectId)}/merge_requests/${mergeRequestIid}/notes`
const notes = await findNotes(notesPath)
async function upsertNote(marker: string, content: string): Promise<void> {
const existing = notes.find(
note => note.author?.id === actor.id && note.body.startsWith(marker),
)
if (!content.trim() && !existing) {
return
}
const body = content.trim() ? `${marker}\n${content}` : marker
if (existing?.body === body) {
return
}
await gitLabApiRequest({
path: existing ? `${notesPath}/${existing.id}` : notesPath,
method: existing ? 'PUT' : 'POST',
body: { body },
})
}

await Promise.all([
disableOverview ||
upsertNote(GITLAB_OVERVIEW_NOTE_MARKER, comments.overview),
disableSecurity || upsertNote(GITLAB_SECURITY_NOTE_MARKER, comments.alerts),
])
}
Loading
Loading