diff --git a/.gitignore b/.gitignore index 7dd4d1664..2d2880b2a 100644 --- a/.gitignore +++ b/.gitignore @@ -371,6 +371,8 @@ !/src/commands/ci/fetch-default-org-slug.test.mts !/src/commands/ci/handle-ci.mts !/src/commands/ci/handle-ci.test.mts +!/src/commands/ci/pr-ignore-commands.test.mts +!/src/commands/ci/handle-ci-skip.test.mts !/src/commands/ci/detect-ci-pull-request-context.test.mts !/src/commands/ci/select-baseline-scan.mts !/src/commands/ci/select-baseline-scan.test.mts diff --git a/src/commands/ci/cmd-ci.mts b/src/commands/ci/cmd-ci.mts index 59d3610f4..0beb9a1fe 100644 --- a/src/commands/ci/cmd-ci.mts +++ b/src/commands/ci/cmd-ci.mts @@ -40,12 +40,24 @@ const config: CliCommandConfig = { description: 'Fail for existing blocking alerts as well as alerts introduced by this PR.', }, + disableIgnore: { + type: 'boolean', + default: false, + description: + 'Ignore no PR comments and do not show @SocketSecurity ignore instructions.', + }, exitCodeOnApiError: { type: 'number', default: 3, description: 'Exit code for Socket API errors (default: 3). Ignored with --disable-blocking.', }, + ignoreAuthorization: { + type: 'string', + default: 'enforce', + description: + 'Authorization policy for PR ignore commands: enforce (default), strict, or off.', + }, jsonFormat: { type: 'string', description: @@ -77,6 +89,8 @@ const config: CliCommandConfig = { $ ${command} --auto-manifest $ ${command} --disable-blocking $ ${command} --strict-blocking + $ ${command} --disable-ignore + $ ${command} --ignore-authorization strict $ ${command} --exit-code-on-api-error 5 `, } @@ -129,9 +143,20 @@ async function run( return } + const ignoreAuthorization = String(cli.flags['ignoreAuthorization'] ?? 'enforce') + if (!['enforce', 'strict', 'off'].includes(ignoreAuthorization)) { + logger.fail('--ignore-authorization must be enforce, strict, or off.') + setCiExitCode('usage') + return + } + await handleCi( Boolean(cli.flags['autoManifest']), jsonFormat === 'python-v1', Boolean(cli.flags['strictBlocking']), + { + authorization: ignoreAuthorization as 'enforce' | 'strict' | 'off', + disabled: Boolean(cli.flags['disableIgnore']), + }, ) } diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index bd123b31a..8985a60a3 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 { + markPrIgnoreCommandsProcessed, + readPrIgnoreCommands, +} from './pr-ignore-commands.mts' import { reportGitLabCommitStatusFailure, withGitLabCommitStatus, @@ -34,11 +38,16 @@ import { } from '../scan/python-diff-json.mts' import type { PythonDiffJsonContext } from '../scan/python-diff-json.mts' +import type { IgnoreAuthorization } from './pr-ignore-commands.mts' export async function handleCi( autoManifest: boolean, pythonJsonFormat = false, strictBlocking = false, + ignoreSettings: { + authorization?: IgnoreAuthorization | undefined + disabled?: boolean | undefined + } = {}, ): Promise { debugFn('notice', 'Starting CI scan') debugDir('inspect', { autoManifest, pythonJsonFormat }) @@ -183,6 +192,8 @@ export async function handleCi( pullRequestContext, pythonJsonContext, pythonJsonFormat, + ignoreAuthorization: ignoreSettings.authorization ?? 'enforce', + disableIgnore: ignoreSettings.disabled ?? false, repoName, }) }) @@ -192,6 +203,8 @@ async function runCiScan({ autoManifest, branchName, cwd, + disableIgnore, + ignoreAuthorization, onDiffOutcome, orgSlug, pullRequestContext, @@ -213,6 +226,8 @@ async function runCiScan({ pullRequestContext: Awaited> pythonJsonContext: PythonDiffJsonContext pythonJsonFormat: boolean + ignoreAuthorization: IgnoreAuthorization + disableIgnore: boolean repoName: string }): Promise { const { number: pullRequest } = pullRequestContext @@ -266,6 +281,13 @@ async function runCiScan({ debugDir('inspect', { orgSlug, cwd, branchName, repoName }) const [owner, repo] = (constants.ENV.GITHUB_REPOSITORY || '').split('/') + const ignoreCommands = baselineScanId + ? await readPrIgnoreCommands({ + authorization: ignoreAuthorization, + context: pullRequestContext, + disabled: disableIgnore, + }) + : [] await handleCreateNewScan({ autoManifest, branchName, @@ -286,6 +308,7 @@ async function runCiScan({ pendingHead: true, pullRequest, pullRequestUrl: pullRequestContext.url, + prIgnoreCommands: ignoreCommands, baselineScanId, onDiffReport: async (diffScanId, outcome) => { onDiffOutcome(outcome) @@ -302,6 +325,10 @@ async function runCiScan({ 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.', ) + await markPrIgnoreCommandsProcessed({ + commands: ignoreCommands, + context: pullRequestContext, + }) return } try { @@ -314,6 +341,8 @@ async function runCiScan({ process.env['SOCKET_CLI_DISABLE_SECURITY_COMMENT'], ), orgSlug, + ignoreCommands, + disableIgnore, mergeRequestIid: pullRequest, projectId, projectUrl, @@ -326,6 +355,10 @@ async function runCiScan({ errorMessage(error), ) } + await markPrIgnoreCommandsProcessed({ + commands: ignoreCommands, + context: pullRequestContext, + }) return } if ( @@ -334,6 +367,10 @@ async function runCiScan({ !repo || !constants.ENV.SOCKET_CLI_GITHUB_TOKEN ) { + await markPrIgnoreCommandsProcessed({ + commands: ignoreCommands, + context: pullRequestContext, + }) return } try { @@ -346,6 +383,8 @@ async function runCiScan({ process.env['SOCKET_CLI_DISABLE_SECURITY_COMMENT'], ), orgSlug, + ignoreCommands, + disableIgnore, owner, pullRequest, repo, @@ -357,6 +396,10 @@ async function runCiScan({ 'Socket could not publish the scan comments. Check the Socket API scopes and GitHub pull request write permission.\n', ) } + await markPrIgnoreCommandsProcessed({ + commands: ignoreCommands, + context: pullRequestContext, + }) }, reach: { dynamicSbomInference: undefined, diff --git a/src/commands/ci/pr-ignore-commands.mts b/src/commands/ci/pr-ignore-commands.mts new file mode 100644 index 000000000..4dd94c673 --- /dev/null +++ b/src/commands/ci/pr-ignore-commands.mts @@ -0,0 +1,461 @@ +import { getOctokit } from '../../utils/github.mts' +import { gitLabApiRequest } from '../../utils/gitlab.mts' +import { logger } from '../../utils/logger.mts' +import { isValidEcosystem } from '../../utils/ecosystem.mts' + +import type { CResult } from '../../types.mts' +import type { CiPullRequestContext } from './detect-ci-pull-request-context.mts' +import type { DiffScanData } from '../scan/fetch-diff-scan.mts' + +export type IgnoreAuthorization = 'enforce' | 'strict' | 'off' + +export type PrIgnoreCommand = { + commentId: number + ignoreAll: boolean + packageName?: string | undefined + version?: string | undefined + author: string +} + +type IgnoreComment = { + id: number + body: string + author: string + authorId: number + authorAssociation?: string | undefined +} + +type ParsedCommand = Omit + +const GITHUB_WRITE_PERMISSIONS = new Set(['admin', 'maintain', 'write']) +const GITLAB_MEMBER_PAGE_SIZE = 100 +const GITLAB_MEMBER_PAGE_LIMIT = 10 +const GITLAB_MIN_WRITE_ACCESS = 30 + +export function parsePrIgnoreCommand( + body: string, +): ParsedCommand[] | undefined { + const firstLine = body.split(/\r?\n/u, 1)[0]?.trim() + if (!firstLine) return undefined + + if (/^@SocketSecurity ignore-all$/iu.test(firstLine)) { + return [{ ignoreAll: true }] + } + + const [mention, action, ...targets] = firstLine.split(/\s+/u) + if ( + mention?.toLowerCase() !== '@socketsecurity' || + action?.toLowerCase() !== 'ignore' || + !targets.length + ) + return undefined + const commands: ParsedCommand[] = [] + for (const target of targets) { + const separator = target.lastIndexOf('@') + if (separator <= 0 || separator === target.length - 1) return undefined + commands.push({ + ignoreAll: false, + packageName: target.slice(0, separator), + version: target.slice(separator + 1), + }) + } + return commands +} + +function githubContext(context: CiPullRequestContext): + | { + owner: string + repo: string + } + | undefined { + const [owner, repo, ...extra] = ( + process.env['GITHUB_REPOSITORY'] || '' + ).split('/') + if ( + context.provider !== 'github' || + !context.number || + !owner || + !repo || + extra.length + ) { + return undefined + } + return { owner, repo } +} + +async function githubIgnoreComments( + context: CiPullRequestContext, +): Promise { + const repository = githubContext(context) + if (!repository) return [] + try { + const octokit = getOctokit() + const comments = await octokit.paginate(octokit.issues.listComments, { + ...repository, + issue_number: context.number, + per_page: 100, + }) + return comments.flatMap(comment => { + const parsed = parsePrIgnoreCommand(comment.body ?? '') + const author = comment.user?.login + const authorId = comment.user?.id + if (!parsed || !author || !Number.isSafeInteger(authorId) || !authorId) { + return [] + } + return [ + { + id: comment.id, + body: comment.body ?? '', + author, + authorId, + authorAssociation: comment.author_association, + }, + ] + }) + } catch { + logger.warn( + 'Could not read GitHub PR ignore comments; no commands were applied.', + ) + return [] + } +} + +async function gitLabIgnoreComments( + context: CiPullRequestContext, +): Promise { + const projectId = process.env['CI_MERGE_REQUEST_PROJECT_ID'] + if (context.provider !== 'gitlab' || !context.number || !projectId) return [] + const comments: IgnoreComment[] = [] + let page = '1' + try { + for (let count = 0; page && count < 100; count++) { + // eslint-disable-next-line no-await-in-loop + const result = await gitLabApiRequest< + Array<{ + id: number + body?: string + author?: { id?: number; username?: string } + }> + >({ + path: `projects/${encodeURIComponent(projectId)}/merge_requests/${context.number}/notes?per_page=100&page=${page}`, + readOnly: true, + }) + for (const note of result.data) { + const author = note.author?.username + const authorId = note.author?.id + if ( + parsePrIgnoreCommand(note.body ?? '') && + author && + Number.isSafeInteger(authorId) && + authorId + ) { + comments.push({ + id: note.id, + body: note.body ?? '', + author, + authorId, + }) + } + } + if (!result.nextPage) return comments + page = result.nextPage + } + if (page) { + logger.warn( + 'GitLab returned more than 100 pages of MR notes; ignore commands were skipped.', + ) + } + } catch { + logger.warn( + 'Could not read GitLab MR ignore comments; no commands were applied.', + ) + } + return [] +} + +async function githubPermission( + context: CiPullRequestContext, + author: string, +): Promise { + const repository = githubContext(context) + if (!repository) return false + try { + const result = await getOctokit().repos.getCollaboratorPermissionLevel({ + ...repository, + username: author, + }) + return GITHUB_WRITE_PERMISSIONS.has( + String(result.data.permission).toLowerCase(), + ) + } catch (error) { + const status = (error as { status?: number } | undefined)?.status + if (status === 404) return false + logger.warn( + `Could not verify GitHub repository permission for ${author}; ignore command rejected${status === 401 || status === 403 ? ` (HTTP ${status})` : ''}.`, + ) + return undefined + } +} + +async function gitLabMemberAccess( + context: CiPullRequestContext, +): Promise | undefined> { + const projectId = process.env['CI_MERGE_REQUEST_PROJECT_ID'] + if (context.provider !== 'gitlab' || !projectId) return undefined + const access = new Map() + try { + for (let page = 1; page <= GITLAB_MEMBER_PAGE_LIMIT; page++) { + // eslint-disable-next-line no-await-in-loop + const result = await gitLabApiRequest< + Array<{ id?: number; access_level?: number }> + >({ + path: `projects/${encodeURIComponent(projectId)}/members/all?per_page=${GITLAB_MEMBER_PAGE_SIZE}&page=${page}`, + readOnly: true, + }) + for (const member of result.data) { + if (Number.isSafeInteger(member.id) && member.id) { + access.set(member.id, member.access_level ?? 0) + } + } + if (result.data.length < GITLAB_MEMBER_PAGE_SIZE) return access + } + logger.warn( + 'GitLab project member list exceeded the verification limit; ignore commands were rejected.', + ) + } catch { + logger.warn( + 'Could not verify GitLab project members; ignore commands were rejected.', + ) + } + return undefined +} + +export async function readPrIgnoreCommands({ + authorization, + context, + disabled, +}: { + authorization: IgnoreAuthorization + context: CiPullRequestContext + disabled: boolean +}): Promise { + if (disabled || !context.number) return [] + const comments = + context.provider === 'github' + ? await githubIgnoreComments(context) + : context.provider === 'gitlab' + ? await gitLabIgnoreComments(context) + : [] + if (!comments.length) return [] + + const access = + context.provider === 'gitlab' && authorization !== 'off' + ? await gitLabMemberAccess(context) + : undefined + const commands: PrIgnoreCommand[] = [] + for (const comment of comments) { + let authorized = authorization === 'off' + if (authorization !== 'off' && context.provider === 'github') { + // eslint-disable-next-line no-await-in-loop + const permission = await githubPermission(context, comment.author) + authorized = + permission === true || + (permission === undefined && + authorization === 'enforce' && + comment.authorAssociation === 'OWNER') + } else if (authorization !== 'off' && access) { + authorized = + (access.get(comment.authorId) ?? 0) >= GITLAB_MIN_WRITE_ACCESS + } + if (!authorized) { + logger.warn( + `Skipping @SocketSecurity ignore command from ${comment.author}; write access could not be verified.`, + ) + continue + } + const parsed = parsePrIgnoreCommand(comment.body) + for (const command of parsed ?? []) { + commands.push({ + commentId: comment.id, + author: comment.author, + ...command, + }) + } + } + return commands +} + +function parsePackageReference(reference: string): { + type?: string + name: string +} { + const separator = reference.indexOf('/') + if (separator > 0) { + const type = reference.slice(0, separator) + if (isValidEcosystem(type)) { + return { type, name: reference.slice(separator + 1) } + } + } + return { name: reference } +} + +function ignoreMatchesReference( + reference: string, + version: string | undefined, + command: PrIgnoreCommand, +): boolean { + if (command.ignoreAll) return true + const target = parsePackageReference(reference) + const selector = parsePackageReference(command.packageName ?? '') + return ( + target.name === selector.name && + (!selector.type || selector.type === target.type) && + (command.version === '*' || version === command.version) + ) +} + +export function applyPrIgnoreCommands( + data: CResult, + commands: PrIgnoreCommand[], +): CResult { + if (!commands.length || !data.ok) return data + const diffScan = data.data.diff_scan + const filterArtifacts = ( + artifacts: T[], + ): T[] => + artifacts.map(artifact => { + const namespace = artifact.namespace?.replace(/^\/+|\/+$/gu, '') + const packageName = namespace + ? `${namespace}/${artifact.name ?? ''}` + : (artifact.name ?? '') + const reference = artifact.type + ? `${artifact.type}/${packageName}` + : packageName + if (!artifact.alerts) return artifact + return { + ...artifact, + alerts: commands.some(command => + ignoreMatchesReference(reference, artifact.version, command), + ) + ? [] + : artifact.alerts, + } + }) + const artifacts = diffScan.artifacts + return { + ...data, + data: { + ...data.data, + diff_scan: { + ...diffScan, + artifacts: { + ...artifacts, + added: filterArtifacts(artifacts.added), + removed: filterArtifacts(artifacts.removed), + replaced: filterArtifacts(artifacts.replaced), + ...(artifacts.unchanged === undefined + ? {} + : { + unchanged: + artifacts.unchanged === null + ? null + : filterArtifacts(artifacts.unchanged), + }), + updated: filterArtifacts(artifacts.updated), + }, + }, + }, + } +} + +export function filterPrAlertComment( + body: string, + commands: PrIgnoreCommand[], +): string { + if (!commands.length) return body + const lines = body.split(/\r?\n/u) + const output: string[] = [] + let ignoredSection = false + for (const line of lines) { + const marker = line.trim() + if (marker.startsWith('', + 'lodash finding', + '', + '', + 'left-pad finding', + '', + ].join('\n') + expect( + filterPrAlertComment(comment, [ + { + commentId: 7, + author: 'reviewer', + ignoreAll: false, + packageName: 'npm/lodash', + version: '1.0.0', + }, + ]), + ).toContain('left-pad finding') + expect( + filterPrAlertComment(comment, [ + { + commentId: 7, + author: 'reviewer', + ignoreAll: false, + packageName: 'npm/left-pad/lodash', + version: '1.0.0', + }, + ]), + ).toContain('lodash finding') + }) +}) + +describe('readPrIgnoreCommands authorization', () => { + it('honors a GitHub commenter with verified write permission', async () => { + const commands = await readPrIgnoreCommands({ + authorization: 'enforce', + context: githubContext, + disabled: false, + }) + expect(commands).toMatchObject([ + { commentId: 7, author: 'reviewer', packageName: 'npm/lodash' }, + ]) + }) + + it('rejects denied or unverifiable GitHub commenters, except verified repo owners in enforce mode', async () => { + mocks.githubPermission.mockResolvedValueOnce({ + data: { permission: 'read' }, + }) + expect( + await readPrIgnoreCommands({ + authorization: 'enforce', + context: githubContext, + disabled: false, + }), + ).toEqual([]) + + mocks.githubPermission.mockRejectedValueOnce( + Object.assign(new Error('provider response'), { status: 403 }), + ) + expect( + await readPrIgnoreCommands({ + authorization: 'strict', + context: githubContext, + disabled: false, + }), + ).toEqual([]) + + mocks.githubComments = [ + githubComment(undefined, { author_association: 'OWNER' }), + ] + mocks.githubPermission.mockRejectedValueOnce( + Object.assign(new Error('provider response'), { status: 403 }), + ) + expect( + await readPrIgnoreCommands({ + authorization: 'enforce', + context: githubContext, + disabled: false, + }), + ).toHaveLength(1) + }) + + it('requires GitLab Developer access and fails closed when membership is unavailable', async () => { + mocks.gitLabRequest.mockImplementation(async ({ path }) => { + if (String(path).includes('/notes?')) { + return { data: [gitLabNote()] } + } + return { data: [{ id: 8, access_level: 30 }] } + }) + expect( + await readPrIgnoreCommands({ + authorization: 'enforce', + context: gitLabContext, + disabled: false, + }), + ).toHaveLength(1) + + mocks.gitLabRequest.mockImplementation(async ({ path }) => { + if (String(path).includes('/notes?')) { + return { data: [gitLabNote()] } + } + return { data: [{ id: 8, access_level: 20 }] } + }) + expect( + await readPrIgnoreCommands({ + authorization: 'strict', + context: gitLabContext, + disabled: false, + }), + ).toEqual([]) + + mocks.gitLabRequest.mockImplementation(async ({ path }) => { + if (String(path).includes('/notes?')) { + return { data: [gitLabNote()] } + } + throw new Error('do not expose provider response') + }) + expect( + await readPrIgnoreCommands({ + authorization: 'enforce', + context: gitLabContext, + disabled: false, + }), + ).toEqual([]) + }) + + it('disables reads and marks accepted commands as handled', async () => { + expect( + await readPrIgnoreCommands({ + authorization: 'off', + context: githubContext, + disabled: true, + }), + ).toEqual([]) + expect(mocks.getOctokit).not.toHaveBeenCalled() + + await markPrIgnoreCommandsProcessed({ + context: githubContext, + commands: [ + { + commentId: 7, + author: 'reviewer', + ignoreAll: false, + packageName: 'npm/lodash', + version: '1.0.0', + }, + ], + }) + expect(mocks.githubCreateReaction).toHaveBeenCalledWith( + expect.objectContaining({ content: '+1', comment_id: 7 }), + ) + + await markPrIgnoreCommandsProcessed({ + context: gitLabContext, + commands: [ + { + commentId: 7, + author: 'reviewer', + ignoreAll: true, + }, + ], + }) + expect(mocks.gitLabRequest).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'POST', + body: { name: 'thumbsup' }, + }), + ) + }) +}) diff --git a/src/commands/ci/publish-gitlab-mr-notes.mts b/src/commands/ci/publish-gitlab-mr-notes.mts index a2c10e51c..4e02895d8 100644 --- a/src/commands/ci/publish-gitlab-mr-notes.mts +++ b/src/commands/ci/publish-gitlab-mr-notes.mts @@ -1,5 +1,8 @@ import { fetchRenderedPullRequestComments } from './publish-pr-comments.mts' import { getGitLabServerUrl, gitLabApiRequest } from '../../utils/gitlab.mts' +import { filterPrAlertComment } from './pr-ignore-commands.mts' + +import type { PrIgnoreCommand } from './pr-ignore-commands.mts' export const GITLAB_OVERVIEW_NOTE_MARKER = '' @@ -27,8 +30,10 @@ async function findNotes(path: string): Promise { export async function publishGitLabMergeRequestNotes({ diffScanId, + disableIgnore = false, disableOverview, disableSecurity, + ignoreCommands = [], mergeRequestIid, orgSlug, projectId, @@ -36,9 +41,11 @@ export async function publishGitLabMergeRequestNotes({ serverUrl, }: { diffScanId: string + disableIgnore?: boolean | undefined disableOverview: boolean disableSecurity: boolean orgSlug: string + ignoreCommands?: PrIgnoreCommand[] | undefined mergeRequestIid: number projectId: string projectUrl: string @@ -76,6 +83,7 @@ export async function publishGitLabMergeRequestNotes({ orgSlug, platform: 'gitlab', pullRequestUrl: mergeRequestUrl.href, + includeIgnoreCommands: !disableIgnore, }) const notesPath = `projects/${encodeURIComponent(projectId)}/merge_requests/${mergeRequestIid}/notes` const notes = await findNotes(notesPath) @@ -97,9 +105,24 @@ export async function publishGitLabMergeRequestNotes({ }) } + const alerts = filterPrAlertComment( + comments.alerts, + disableIgnore ? [] : ignoreCommands, + ) await Promise.all([ disableOverview || upsertNote(GITLAB_OVERVIEW_NOTE_MARKER, comments.overview), - disableSecurity || upsertNote(GITLAB_SECURITY_NOTE_MARKER, comments.alerts), + disableSecurity || + !( + alerts.trim() || + (!disableIgnore && ignoreCommands.length > 0) || + notes.some( + note => + note.author?.id === actor.id && + note.body.startsWith(GITLAB_SECURITY_NOTE_MARKER), + ) + ) + ? Promise.resolve() + : upsertNote(GITLAB_SECURITY_NOTE_MARKER, alerts), ]) } diff --git a/src/commands/ci/publish-pr-comments.mts b/src/commands/ci/publish-pr-comments.mts index b9c7dc0e2..13f3c6283 100644 --- a/src/commands/ci/publish-pr-comments.mts +++ b/src/commands/ci/publish-pr-comments.mts @@ -1,5 +1,8 @@ import { queryApiSafeJson } from '../../utils/api.mts' import { upsertPullRequestComment } from '../../utils/github.mts' +import { filterPrAlertComment } from './pr-ignore-commands.mts' + +import type { PrIgnoreCommand } from './pr-ignore-commands.mts' export const PR_OVERVIEW_COMMENT_MARKER = '' @@ -8,6 +11,7 @@ export const PR_SECURITY_COMMENT_MARKER = export async function fetchRenderedPullRequestComments({ diffScanId, + includeIgnoreCommands = true, orgSlug, platform, pullRequestUrl, @@ -16,11 +20,12 @@ export async function fetchRenderedPullRequestComments({ orgSlug: string platform: 'github' | 'gitlab' pullRequestUrl: string + includeIgnoreCommands?: boolean | undefined }): Promise<{ overview: string; alerts: string }> { const query = new URLSearchParams({ platform, pull_request_url: pullRequestUrl, - bot_commands: 'false', + bot_commands: String(includeIgnoreCommands), }) // SDK 4.3.0 does not expose this operation yet. const result = await queryApiSafeJson<{ @@ -41,8 +46,10 @@ export async function fetchRenderedPullRequestComments({ export async function publishPullRequestComments({ diffScanId, + disableIgnore = false, disableOverview, disableSecurity, + ignoreCommands = [], orgSlug, owner, pullRequest, @@ -50,9 +57,11 @@ export async function publishPullRequestComments({ serverUrl, }: { diffScanId: string + disableIgnore?: boolean | undefined disableOverview: boolean disableSecurity: boolean orgSlug: string + ignoreCommands?: PrIgnoreCommand[] | undefined owner: string pullRequest: number repo: string @@ -70,7 +79,12 @@ export async function publishPullRequestComments({ orgSlug, platform: 'github', pullRequestUrl: pullRequestUrl.href, + includeIgnoreCommands: !disableIgnore, }) + const alerts = filterPrAlertComment( + comments.alerts, + disableIgnore ? [] : ignoreCommands, + ) if (!disableOverview && comments.overview.trim()) { await upsertPullRequestComment({ @@ -82,9 +96,12 @@ export async function publishPullRequestComments({ }) } - if (!disableSecurity && comments.alerts.trim()) { + if ( + !disableSecurity && + (alerts.trim() || (!disableIgnore && ignoreCommands.length > 0)) + ) { await upsertPullRequestComment({ - body: `${PR_SECURITY_COMMENT_MARKER}\n${comments.alerts}`, + body: `${PR_SECURITY_COMMENT_MARKER}${alerts ? `\n${alerts}` : ''}`, marker: PR_SECURITY_COMMENT_MARKER, owner, pullRequest, diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index a12c68c25..0516529e4 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -42,6 +42,7 @@ import { } from '../manifest/run-manifest-facts.mts' import { buildToolsFor } from '../manifest/scripts/build-tool.mts' +import type { PrIgnoreCommand } from '../ci/pr-ignore-commands.mts' import type { ReachabilityFallback } from './output-create-new-scan.mts' import type { ReachabilityOptions } from './perform-reachability-analysis.mts' import type { PythonDiffJsonContext } from './python-diff-json.mts' @@ -138,6 +139,7 @@ export type HandleCreateNewScanConfig = { pendingHead: boolean pullRequest: number pullRequestUrl?: string | undefined + prIgnoreCommands?: PrIgnoreCommand[] | undefined outputKind: OutputKind reach: Remap< ReachabilityOptions & { @@ -205,6 +207,7 @@ async function createNewScan( orgSlug, outputKind, pendingHead, + prIgnoreCommands = [], pullRequest, pullRequestUrl, pythonJsonContext, @@ -608,6 +611,7 @@ async function createNewScan( if (baselineScanId) { await handlePrDiffScan({ externalHref: pullRequestUrl, + ignoreCommands: prIgnoreCommands, id1: baselineScanId, id2: scanId, onDiffReport, diff --git a/src/commands/scan/handle-diff-scan.mts b/src/commands/scan/handle-diff-scan.mts index a7eae247c..6f36948f9 100644 --- a/src/commands/scan/handle-diff-scan.mts +++ b/src/commands/scan/handle-diff-scan.mts @@ -1,9 +1,11 @@ import { getDiffScanVerdict } from './diff-scan-verdict.mts' import { fetchDiffScan } from './fetch-diff-scan.mts' import { outputDiffScan } from './output-diff-scan.mts' +import { applyPrIgnoreCommands } from '../ci/pr-ignore-commands.mts' import type { PythonDiffJsonContext } from './python-diff-json.mts' import type { OutputKind } from '../../types.mts' +import type { PrIgnoreCommand } from '../ci/pr-ignore-commands.mts' export async function handleDiffScan({ depth, @@ -46,6 +48,7 @@ export async function handlePrDiffScan({ externalHref, id1, id2, + ignoreCommands = [], onDiffReport, orgSlug, outputKind, @@ -54,6 +57,7 @@ export async function handlePrDiffScan({ strictBlocking = false, }: { externalHref?: string | undefined + ignoreCommands?: PrIgnoreCommand[] | undefined id1: string id2: string onDiffReport?: @@ -72,12 +76,13 @@ export async function handlePrDiffScan({ pythonJsonContext?: PythonDiffJsonContext | undefined strictBlocking?: boolean | undefined }): Promise { - const result = await fetchDiffScan({ + const fetched = await fetchDiffScan({ ...(externalHref ? { externalHref } : {}), id1, id2, orgSlug, }) + const result = applyPrIgnoreCommands(fetched, ignoreCommands) await outputDiffScan(result, { depth: 2, file: '', diff --git a/src/utils/gitlab.mts b/src/utils/gitlab.mts index c2a67bce1..9e778119c 100644 --- a/src/utils/gitlab.mts +++ b/src/utils/gitlab.mts @@ -5,13 +5,16 @@ export type GitLabApiResponse = { nextPage?: string } -function getGitLabAuth(): { header: string; value: string } { +function getGitLabAuth(readOnly = false): { header: string; value: string } { const token = process.env['SOCKET_CLI_GITLAB_TOKEN'] || process.env['GITLAB_TOKEN'] if (token) { return { header: 'PRIVATE-TOKEN', value: token } } if (process.env['CI_JOB_TOKEN']) { + if (readOnly) { + return { header: 'JOB-TOKEN', value: process.env['CI_JOB_TOKEN'] } + } throw new Error( 'GitLab CI_JOB_TOKEN cannot write merge request notes. Set SOCKET_CLI_GITLAB_TOKEN to a project access token with api scope and Developer access.', ) @@ -63,13 +66,18 @@ export async function gitLabApiRequest({ body, method = 'GET', path, + readOnly = false, }: { body?: unknown method?: 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT' path: string + readOnly?: boolean | undefined }): Promise> { const apiUrl = getGitLabApiUrl() - const token = getGitLabAuth() + if (readOnly && method !== 'GET') { + throw new Error('Read-only GitLab API requests must use GET') + } + const token = getGitLabAuth(readOnly) const safePath = path.replace(/^\/+/, '') const url = new URL(safePath, `${apiUrl.href.replace(/\/$/u, '')}/`) if ( diff --git a/test/snapshots/termless/cli.native.socket-help-ci.svg b/test/snapshots/termless/cli.native.socket-help-ci.svg index d7af0b86f..741ee593f 100644 --- a/test/snapshots/termless/cli.native.socket-help-ci.svg +++ b/test/snapshots/termless/cli.native.socket-help-ci.svg @@ -1,4 +1,4 @@ - + CLI: v2.1.1-rc.1 | cmd: socket ci | org: (not set) | token: (not set) @@ -21,59 +21,67 @@ --disable-blocking Return success for findings and infrastructure failures, but keep usage errors non-zero. - --exit-code-on-api-error Exit code for Socket API errors (default: 3). Ignored with --disable-blocking. + --disable-ignore Ignore no PR comments and do not show @SocketSecurity ignore instructions. - --json-format Select a versioned JSON payload. Supported: python-v1 (pull request comparisons only). + --exit-code-on-api-error Exit code for Socket API errors (default: 3). Ignored with --disable-blocking. - --strict-blocking Fail for existing blocking alerts as well as alerts introduced by this PR. + --ignore-authorization Authorization policy for PR ignore commands: enforce (default), strict, or off. - + --json-format Select a versioned JSON payload. Supported: python-v1 (pull request comparisons only). - This command is intended to use in CI runs to allow automated systems to + --strict-blocking Fail for existing blocking alerts as well as alerts introduced by this PR. - accept or reject a current build. It will use the default org of the + - Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2 + This command is intended to use in CI runs to allow automated systems to - for usage errors, 3 for infrastructure errors, and 130 for interruption. + accept or reject a current build. It will use the default org of the - --disable-blocking returns 0 for findings and runtime failures, but not + Socket API token. Exit codes are 0 for success, 1 for blocking findings, 2 - usage errors. --strict-blocking also fails for blocking alerts on unchanged + for usage errors, 3 for infrastructure errors, and 130 for interruption. - dependencies. --exit-code-on-api-error changes the API failure code. + --disable-blocking returns 0 for findings and runtime failures, but not - + usage errors. --strict-blocking also fails for blocking alerts on unchanged - The --auto-manifest flag does the same as the one from `socket scan create` + dependencies. --exit-code-on-api-error changes the API failure code. - but is not enabled by default since the CI is less likely to be set up with + - all the necessary dev tooling. Enable it if you want the scan to include + The --auto-manifest flag does the same as the one from `socket scan create` - locally generated manifests like for gradle and sbt. + but is not enabled by default since the CI is less likely to be set up with - + all the necessary dev tooling. Enable it if you want the scan to include - Examples + locally generated manifests like for gradle and sbt. - $ socket ci + - $ socket ci --auto-manifest + Examples - $ socket ci --disable-blocking + $ socket ci - $ socket ci --strict-blocking + $ socket ci --auto-manifest - $ socket ci --exit-code-on-api-error 5 + $ socket ci --disable-blocking - + $ socket ci --strict-blocking - + $ socket ci --disable-ignore - + $ socket ci --ignore-authorization strict - + $ socket ci --exit-code-on-api-error 5 - \ No newline at end of file + + + + + + + + + \ No newline at end of file diff --git a/test/unit/src/commands/ci/cmd-ci.test.mts b/test/unit/src/commands/ci/cmd-ci.test.mts index 3bad1ad59..418b2b4d2 100644 --- a/test/unit/src/commands/ci/cmd-ci.test.mts +++ b/test/unit/src/commands/ci/cmd-ci.test.mts @@ -25,7 +25,9 @@ describe('socket ci', async () => { Options --auto-manifest Auto generate manifest files where detected? See autoManifest flag in \`socket scan create\` --disable-blocking Return success for findings and infrastructure failures, but keep usage errors non-zero. + --disable-ignore Ignore no PR comments and do not show @SocketSecurity ignore instructions. --exit-code-on-api-error Exit code for Socket API errors (default: 3). Ignored with --disable-blocking. + --ignore-authorization Authorization policy for PR ignore commands: enforce (default), strict, or off. --json-format Select a versioned JSON payload. Supported: python-v1 (pull request comparisons only). --strict-blocking Fail for existing blocking alerts as well as alerts introduced by this PR. @@ -47,6 +49,8 @@ describe('socket ci', async () => { $ socket ci --auto-manifest $ socket ci --disable-blocking $ socket ci --strict-blocking + $ socket ci --disable-ignore + $ socket ci --ignore-authorization strict $ socket ci --exit-code-on-api-error 5" `, ) diff --git a/test/unit/src/commands/ci/handle-ci-flow.test.mts b/test/unit/src/commands/ci/handle-ci-flow.test.mts index de800b936..b0178954c 100644 --- a/test/unit/src/commands/ci/handle-ci-flow.test.mts +++ b/test/unit/src/commands/ci/handle-ci-flow.test.mts @@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({ handleCreateNewScan: vi.fn(), publishPullRequestComments: vi.fn(), publishGitLabMergeRequestNotes: vi.fn(), + readPrIgnoreCommands: vi.fn(), selectBaselineScan: vi.fn(), setCiExitCode: vi.fn(), loggerLog: vi.fn(), @@ -41,6 +42,10 @@ vi.mock('../../../../../src/commands/ci/publish-pr-comments.mts', () => ({ vi.mock('../../../../../src/commands/ci/publish-gitlab-mr-notes.mts', () => ({ publishGitLabMergeRequestNotes: mocks.publishGitLabMergeRequestNotes, })) +vi.mock('../../../../../src/commands/ci/pr-ignore-commands.mts', async importOriginal => ({ + ...(await importOriginal()), + readPrIgnoreCommands: mocks.readPrIgnoreCommands, +})) vi.mock('../../../../../src/commands/ci/select-baseline-scan.mts', () => ({ selectBaselineScan: mocks.selectBaselineScan, })) @@ -102,6 +107,7 @@ beforeEach(() => { mocks.constants.ENV.SOCKET_CLI_GITHUB_TOKEN = '' mocks.getDefaultOrgSlug.mockResolvedValue({ ok: true, data: 'socket' }) mocks.detectCiPullRequestContext.mockResolvedValue({ number: 0 }) + mocks.readPrIgnoreCommands.mockResolvedValue([]) mocks.gitBranch.mockResolvedValue('feature/test') mocks.getRepoName.mockResolvedValue('socket-cli') mocks.selectBaselineScan.mockResolvedValue({ ok: true, data: { id: 'base' } }) @@ -186,6 +192,7 @@ describe('CI scan orchestration', () => { baselineScanId: 'base', branchName: 'feature/test', pendingHead: true, + prIgnoreCommands: [], pullRequest: 42, }) await scanOptions.onDiffReport('diff-123', cleanOutcome) diff --git a/test/unit/src/commands/ci/publish-gitlab-mr-notes.test.mts b/test/unit/src/commands/ci/publish-gitlab-mr-notes.test.mts index c2092d42c..333b487ff 100644 --- a/test/unit/src/commands/ci/publish-gitlab-mr-notes.test.mts +++ b/test/unit/src/commands/ci/publish-gitlab-mr-notes.test.mts @@ -63,6 +63,7 @@ describe('publishGitLabMergeRequestNotes', () => { diffScanId: 'diff-id', orgSlug: 'example', platform: 'gitlab', + includeIgnoreCommands: true, pullRequestUrl: 'https://gitlab.example.test/target/project/-/merge_requests/42', }) diff --git a/test/unit/src/commands/ci/publish-pr-comments.test.mts b/test/unit/src/commands/ci/publish-pr-comments.test.mts index 95cc30ef4..759ccc609 100644 --- a/test/unit/src/commands/ci/publish-pr-comments.test.mts +++ b/test/unit/src/commands/ci/publish-pr-comments.test.mts @@ -49,7 +49,7 @@ describe('publishPullRequestComments', () => { expect(Object.fromEntries(url.searchParams)).toEqual({ platform: 'github', pull_request_url: 'https://github.com/SocketDev/socket-cli/pull/42', - bot_commands: 'false', + bot_commands: 'true', }) expect(upsertPullRequestComment).toHaveBeenNthCalledWith(1, { body: `${PR_OVERVIEW_COMMENT_MARKER}\nDependency summary`,