diff --git a/docs/commands/scan/report.md b/docs/commands/scan/report.md index fdc65b17f..e52471ced 100644 --- a/docs/commands/scan/report.md +++ b/docs/commands/scan/report.md @@ -87,3 +87,28 @@ socket scan create --report The bot posts to Slack's `chat.postMessage` API. It checks both the HTTP status and Slack's JSON `ok` response. Rate limits and API errors are reported without printing the token or changing the scan decision. + +## Jira CI tasks + +The scan creation report flow can create one Jira Task per report with findings. +Reruns for the same repository, branch, pull request, and commit update the +existing task. If CI cannot provide a commit SHA, reruns use the stable +repository, branch, and pull request identity instead. Store the API token in +your CI secret store and enable Jira only for trusted jobs: + +```sh +export SOCKET_JIRA_ENABLED=true +# Set SOCKET_JIRA_CONFIG_JSON from your CI secret store. +socket ci +``` + +Store a JSON value like this in `SOCKET_JIRA_CONFIG_JSON`: + +```json +{"url":"https://example.atlassian.net","email":"bot@example.com","api_token":"","project":"SEC"} +``` + +`SOCKET_JIRA_CONFIG_JSON` requires an HTTPS Jira base URL, the Atlassian account +email, an API token, and a Jira project key. Notifications include the Socket +report link, package, alert, source, and manifest details. Jira lookup or +delivery failures are reported as warnings and do not change the scan result. diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index d578737ae..420add674 100644 --- a/src/commands/ci/handle-ci.mts +++ b/src/commands/ci/handle-ci.mts @@ -25,6 +25,7 @@ import { import { logger } from '../../utils/logger.mts' import { getPackageFilesForScan } from '../../utils/path-resolve.mts' import { serializeResultJson } from '../../utils/serialize-result-json.mts' +import { spawn } from '../../utils/spawn.mts' import { fetchSupportedScanFileNames } from '../scan/fetch-supported-scan-file-names.mts' import { handleCreateNewScan } from '../scan/handle-create-new-scan.mts' import { @@ -247,12 +248,30 @@ async function runCiScan({ ) debugDir('inspect', { orgSlug, cwd, branchName, repoName }) + // Branch builds also carry a revision, even without a PR context. + let commitHash = + pythonJsonContext.commitSha || + process.env['GITHUB_SHA'] || + process.env['CI_COMMIT_SHA'] || + process.env['BUILD_SOURCEVERSION'] || + '' + if (!commitHash) { + try { + const revision = await spawn('git', ['rev-parse', '--verify', 'HEAD'], { + cwd, + }) + commitHash = revision.stdout.trim() + } catch { + debugFn('notice', 'No Git revision is available for this scan') + } + } + const [owner, repo] = constants.ENV.GITHUB_REPOSITORY.split('/') await handleCreateNewScan({ autoManifest, branchName, commitMessage: '', - commitHash: '', + commitHash, committers: '', cwd, defaultBranch: false, diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index 742ace902..5b4c2ed32 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -629,6 +629,8 @@ async function createNewScan( notificationContext: { repository: repoName, branch: branchName, + pullRequest, + commitSha: commitHash || undefined, reachabilityEnabled, reachabilityFacts: notificationReachabilityFacts, }, @@ -646,6 +648,8 @@ async function createNewScan( notificationContext: { repository: repoName, branch: branchName, + pullRequest, + commitSha: commitHash || undefined, reachabilityEnabled, reachabilityFacts: notificationReachabilityFacts, }, diff --git a/src/commands/scan/notifications/dispatch.mts b/src/commands/scan/notifications/dispatch.mts new file mode 100644 index 000000000..6a8501f80 --- /dev/null +++ b/src/commands/scan/notifications/dispatch.mts @@ -0,0 +1,52 @@ +import { isJiraEnabled, sendJiraTaskNotification } from './jira.mts' +import { sendSlackBotNotifications } from './slack-bot.mts' +import { + getSlackNotificationConfig, + isSlackNotificationConfigured, + sendSlackWebhookNotifications, +} from './slack-webhook.mts' +import { logger } from '../../../utils/logger.mts' + +import type { NotificationReport } from './report.mts' + +type NotificationProvider = { + name: string + isEnabled: () => boolean + send: (report: NotificationReport) => Promise +} + +const notificationProviders: NotificationProvider[] = [ + { + name: 'Jira', + isEnabled: isJiraEnabled, + send: sendJiraTaskNotification, + }, + { + name: 'Slack', + isEnabled: isSlackNotificationConfigured, + send: async report => { + const config = getSlackNotificationConfig() ?? null + await sendSlackWebhookNotifications(report, config) + await sendSlackBotNotifications(report, config) + }, + }, +] + +/** Deliver reports to each independently configured notification provider. */ +export async function dispatchScanNotifications( + report: NotificationReport, +): Promise { + for (const provider of notificationProviders) { + if (!provider.isEnabled()) { + continue + } + try { + // eslint-disable-next-line no-await-in-loop -- Providers are dispatched independently in order. + await provider.send(report) + } catch { + logger.warn( + `${provider.name} notification delivery failed; scan policy is unchanged.`, + ) + } + } +} diff --git a/src/commands/scan/notifications/jira.mts b/src/commands/scan/notifications/jira.mts new file mode 100644 index 000000000..39463b648 --- /dev/null +++ b/src/commands/scan/notifications/jira.mts @@ -0,0 +1,399 @@ +import { createHash } from 'node:crypto' + +import { apiFetch } from '../../../utils/api.mts' +import { logger } from '../../../utils/logger.mts' + +import type { NotificationFinding, NotificationReport } from './report.mts' + +type JiraConfig = { + url: string + email: string + api_token: string + project: string + baseUrl: string +} + +type AdfNode = Record + +const REQUEST_TIMEOUT_MS = 10_000 + +export function isJiraEnabled(): boolean { + return process.env['SOCKET_JIRA_ENABLED']?.toLowerCase() === 'true' +} + +function parseConfig(): JiraConfig | undefined { + const raw = process.env['SOCKET_JIRA_CONFIG_JSON'] + if (!raw) { + return undefined + } + + let value: unknown + try { + value = JSON.parse(raw) + } catch { + return undefined + } + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return undefined + } + + const config = value as Record + const { url, email, api_token: apiToken, project } = config + if ( + typeof url !== 'string' || + !url.trim() || + typeof email !== 'string' || + !email.trim() || + typeof apiToken !== 'string' || + !apiToken.trim() || + typeof project !== 'string' || + !/^[A-Za-z][A-Za-z0-9_-]*$/u.test(project) + ) { + return undefined + } + + try { + const jiraUrl = new URL(url) + if ( + jiraUrl.protocol !== 'https:' || + jiraUrl.username || + jiraUrl.password || + jiraUrl.search || + jiraUrl.hash + ) { + return undefined + } + jiraUrl.pathname = `${jiraUrl.pathname.replace(/\/+$/u, '')}/rest/api/3` + return { + url: jiraUrl.href.replace(/\/$/u, ''), + baseUrl: jiraUrl.href.replace(/\/$/u, ''), + email: email.trim(), + api_token: apiToken, + project, + } + } catch { + return undefined + } +} + +function safeLink(value: string | undefined): string | undefined { + if (!value) { + return undefined + } + try { + const url = new URL(value) + return ['https:', 'http:'].includes(url.protocol) && + !url.username && + !url.password + ? url.href + : undefined + } catch { + return undefined + } +} + +function makeCell(text: string): AdfNode { + return { + type: 'tableCell', + content: [ + { + type: 'paragraph', + content: text ? [{ type: 'text', text }] : [], + }, + ], + } +} + +function makeLinkCell(text: string, href: string): AdfNode { + return { + type: 'tableCell', + content: [ + { + type: 'paragraph', + content: [ + { + type: 'text', + text, + marks: [{ type: 'link', attrs: { href } }], + }, + ], + }, + ], + } +} + +function sourceText(finding: NotificationFinding): string { + return ( + finding.introducedBy + ?.map(([source]) => source) + .filter(Boolean) + .join('\n') ?? '' + ) +} + +function manifestText(finding: NotificationFinding): string { + return ( + finding.manifests || + finding.introducedBy + ?.map(([, manifests]) => manifests) + .filter(Boolean) + .join('\n') || + '' + ) +} + +function packageText(finding: NotificationFinding): string { + return ( + finding.purl || + `${finding.ecosystem}/${finding.packageName}@${finding.version}` + ) +} + +function adfTable(findings: NotificationFinding[]): AdfNode { + const rows = [ + { + type: 'tableRow', + content: [ + makeCell('Alert'), + makeCell('Package'), + makeCell('Introduced by'), + makeCell('Manifest File'), + makeCell('CI'), + ], + }, + ...findings.map(finding => { + const packageName = packageText(finding) + const packageUrl = safeLink(finding.url) + const advisory = finding.advisoryId ? ` (${finding.advisoryId})` : '' + return { + type: 'tableRow', + content: [ + makeCell(`${finding.alertType}${advisory}`), + packageUrl + ? makeLinkCell(packageName, packageUrl) + : makeCell(packageName), + makeCell(sourceText(finding)), + makeCell(manifestText(finding)), + makeCell(finding.action === 'error' ? '🚫' : '⚠️'), + ], + } + }), + ] + return { type: 'table', content: rows } +} + +function createSummary(report: NotificationReport): string { + const parts = ['Security Issues found in Socket Security results'] + if (report.pullRequest !== undefined && report.pullRequest !== 0) { + parts.push(`for PR ${report.pullRequest}`) + } + if (report.commitSha) { + parts.push(`- ${report.commitSha.slice(0, 8)}`) + } + return parts.join(' ') +} + +function createDescription(report: NotificationReport): AdfNode { + const scanUrl = safeLink(report.scanUrl) + return { + type: 'doc', + version: 1, + content: [ + { + type: 'paragraph', + content: [ + { type: 'text', text: 'Security issues were found in this scan:' }, + ], + }, + ...(scanUrl + ? [ + { + type: 'paragraph', + content: [ + { + type: 'text', + text: 'View Socket Security scan results', + marks: [{ type: 'link', attrs: { href: scanUrl } }], + }, + ], + }, + ] + : []), + adfTable(report.findings), + ], + } +} + +function createLabel(config: JiraConfig, report: NotificationReport): string { + const commitSha = + report.commitSha?.trim() || + process.env['GITHUB_SHA']?.trim() || + process.env['CI_COMMIT_SHA']?.trim() || + process.env['BUILDKITE_COMMIT']?.trim() || + process.env['BITBUCKET_COMMIT']?.trim() || + process.env['CIRCLE_SHA1']?.trim() || + process.env['TRAVIS_COMMIT']?.trim() + const key = JSON.stringify({ + project: config.project, + repository: report.repository ?? '', + branch: report.branch ?? '', + pullRequest: report.pullRequest ?? '', + // When CI cannot provide a SHA, keep a stable key for that repository, + // branch, and PR. Scan IDs change every run and would create duplicates. + commitSha: + commitSha || + `missing-commit:${report.branch ?? ''}:${report.pullRequest ?? ''}`, + }) + return `socket-cli-${createHash('sha256').update(key).digest('hex').slice(0, 32)}` +} + +function authorization(config: JiraConfig): string { + const value = Buffer.from(`${config.email}:${config.api_token}`).toString( + 'base64', + ) + return `Basic ${value}` +} + +function jiraHeaders(config: JiraConfig): Record { + return { + accept: 'application/json', + authorization: authorization(config), + 'content-type': 'application/json', + } +} + +async function findExistingIssue( + config: JiraConfig, + label: string, +): Promise<{ ok: true; key?: string } | { ok: false }> { + const searchUrl = new URL(`${config.baseUrl}/search/jql`) + searchUrl.searchParams.set( + 'jql', + `project = "${config.project}" AND labels = "${label}"`, + ) + searchUrl.searchParams.set('fields', 'key') + searchUrl.searchParams.set('maxResults', '2') + + const response = await apiFetch(searchUrl.href, { + method: 'GET', + headers: jiraHeaders(config), + rejectRedirects: true, + timeout: REQUEST_TIMEOUT_MS, + }) + if (!response.ok) { + logger.warn( + `Jira task lookup failed with HTTP ${response.status}; scan policy is unchanged.`, + ) + return { ok: false } + } + + let body: unknown + try { + body = await response.json() + } catch { + logger.warn( + 'Jira task lookup returned invalid JSON; scan policy is unchanged.', + ) + return { ok: false } + } + const issues = + body && typeof body === 'object' + ? (body as { issues?: unknown }).issues + : undefined + if (!Array.isArray(issues)) { + logger.warn( + 'Jira task lookup returned no issue list; scan policy is unchanged.', + ) + return { ok: false } + } + const key = (issues[0] as { key?: unknown } | undefined)?.key + return { ok: true, ...(typeof key === 'string' && key ? { key } : {}) } +} + +/** Create one Jira Task per scan report; a stable label updates an existing task on reruns. */ +export async function sendJiraTaskNotification( + report: NotificationReport, +): Promise { + if (!report.findings.length) { + return + } + const config = parseConfig() + if (!config) { + logger.warn( + 'Jira notifications are enabled but SOCKET_JIRA_CONFIG_JSON is invalid or missing required settings; skipping delivery.', + ) + return + } + + const label = createLabel(config, report) + const headers = jiraHeaders(config) + const description = createDescription(report) + const summary = createSummary(report) + let lookup: Awaited> + try { + lookup = await findExistingIssue(config, label) + } catch { + logger.warn('Jira task lookup failed; scan policy is unchanged.') + return + } + if (!lookup.ok) { + return + } + const issueKey = lookup.key + const baseFields = { + summary, + description, + } + const fields = issueKey + ? baseFields + : { + project: { key: config.project }, + issuetype: { name: 'Task' }, + ...baseFields, + labels: [label], + } + const issueUrl = issueKey + ? `${config.baseUrl}/issue/${encodeURIComponent(issueKey)}` + : `${config.baseUrl}/issue` + + try { + const response = await apiFetch(issueUrl, { + method: issueKey ? 'PUT' : 'POST', + headers, + body: JSON.stringify( + issueKey + ? { fields, update: { labels: [{ add: label }] } } + : { fields }, + ), + rejectRedirects: true, + timeout: REQUEST_TIMEOUT_MS, + }) + if (!response.ok) { + logger.warn( + `Jira task ${issueKey ? 'update' : 'creation'} failed with HTTP ${response.status}; scan policy is unchanged.`, + ) + return + } + if (issueKey) { + logger.info(`Jira task updated: ${issueKey}`) + return + } + let createdKey: unknown + try { + const createdBody: unknown = await response.json() + createdKey = + createdBody && typeof createdBody === 'object' + ? (createdBody as { key?: unknown }).key + : undefined + } catch { + createdKey = undefined + } + logger.info( + typeof createdKey === 'string' + ? `Jira task created: ${createdKey}` + : 'Jira task created.', + ) + } catch { + logger.warn('Jira task delivery failed; scan policy is unchanged.') + } +} diff --git a/src/commands/scan/notifications/jira.test.mts b/src/commands/scan/notifications/jira.test.mts new file mode 100644 index 000000000..cce677c8f --- /dev/null +++ b/src/commands/scan/notifications/jira.test.mts @@ -0,0 +1,241 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { apiFetch } from '../../../utils/api.mts' +import { dispatchScanNotifications } from './dispatch.mts' +import { isJiraEnabled, sendJiraTaskNotification } from './jira.mts' + +import type { NotificationReport } from './report.mts' + +vi.mock('../../../utils/api.mts', () => ({ apiFetch: vi.fn() })) + +function jiraResponse(status: number, body?: unknown): Response { + return new Response(body === undefined ? null : JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' }, + }) +} + +function queueJiraResponses(...responses: Response[]): void { + for (const response of responses) { + vi.mocked(apiFetch).mockResolvedValueOnce(response) + } +} + +const report: NotificationReport = { + kind: 'diff', + diffScanId: 'diff-42', + scanId: 'scan-42', + repository: 'example/service', + branch: 'feature/fix', + pullRequest: 42, + commitSha: '1234567890abcdef', + scanUrl: 'https://socket.dev/dashboard/org/example/diff/base/scan-42', + decision: 'fail', + summary: '1 finding (1 blocking, 0 warning)', + findings: [ + { + packageName: 'left-pad', + ecosystem: 'npm', + version: '1.0.0', + alertType: 'cve', + severity: 'high', + action: 'error', + advisoryId: 'GHSA-1234', + purl: 'pkg:npm/left-pad@1.0.0', + url: 'https://socket.dev/npm/package/left-pad/overview/1.0.0', + introducedBy: [['direct', 'package.json']], + manifests: 'package.json', + }, + ], +} + +function configureJira(): void { + vi.stubEnv('SOCKET_JIRA_ENABLED', 'true') + vi.stubEnv( + 'SOCKET_JIRA_CONFIG_JSON', + JSON.stringify({ + url: 'https://example.atlassian.net', + email: 'bot@example.com', + api_token: 'jira-secret-token', + project: 'SEC', + }), + ) + vi.stubEnv('SOCKET_SLACK_CONFIG_JSON', '') +} + +afterEach(() => { + vi.unstubAllEnvs() + vi.unstubAllGlobals() + vi.clearAllMocks() +}) + +describe('Jira scan notifications', () => { + it('creates one authenticated Task with the Python CLI summary and ADF alert table', async () => { + configureJira() + queueJiraResponses( + jiraResponse(200, { issues: [] }), + jiraResponse(201, { key: 'SEC-42' }), + ) + + await sendJiraTaskNotification(report) + + expect(apiFetch).toHaveBeenCalledTimes(2) + const [searchUrl, searchOptions] = vi.mocked(apiFetch).mock.calls[0]! + const parsedSearchUrl = new URL(searchUrl) + expect(parsedSearchUrl.pathname).toBe('/rest/api/3/search/jql') + expect(parsedSearchUrl.searchParams.get('jql')).toContain('project = "SEC"') + expect(searchOptions.rejectRedirects).toBe(true) + expect(searchOptions.timeout).toBeGreaterThan(0) + expect( + (searchOptions.headers as Record)['authorization'], + ).toBe( + `Basic ${Buffer.from('bot@example.com:jira-secret-token').toString('base64')}`, + ) + + const [issueUrl, issueOptions] = vi.mocked(apiFetch).mock.calls[1]! + expect(new URL(issueUrl).pathname).toBe('/rest/api/3/issue') + expect(issueUrl).not.toContain('jira-secret-token') + const fields = JSON.parse(String(issueOptions.body)).fields + expect(fields).toMatchObject({ + project: { key: 'SEC' }, + issuetype: { name: 'Task' }, + summary: + 'Security Issues found in Socket Security results for PR 42 - 12345678', + labels: [expect.stringMatching(/^socket-cli-[a-f0-9]{32}$/u)], + }) + expect(fields.description.content[1].content[0]).toMatchObject({ + text: 'View Socket Security scan results', + marks: [ + { + type: 'link', + attrs: { + href: 'https://socket.dev/dashboard/org/example/diff/base/scan-42', + }, + }, + ], + }) + expect(fields.description.content[2].content).toHaveLength(2) + expect(JSON.stringify(fields.description.content[2].content[1])).toContain( + 'GHSA-1234', + ) + }) + + it('updates the existing task on a rerun instead of creating a duplicate', async () => { + configureJira() + queueJiraResponses( + jiraResponse(200, { issues: [{ key: 'SEC-42' }] }), + jiraResponse(204), + ) + + await sendJiraTaskNotification(report) + + expect(apiFetch).toHaveBeenCalledTimes(2) + const [url, options] = vi.mocked(apiFetch).mock.calls[1]! + expect(new URL(url).pathname).toBe('/rest/api/3/issue/SEC-42') + expect(options.method).toBe('PUT') + const request = JSON.parse(String(options.body)) + expect(request.fields).not.toHaveProperty('issuetype') + expect(request.fields).not.toHaveProperty('labels') + expect(request.update.labels).toEqual([ + { add: expect.stringMatching(/^socket-cli-[a-f0-9]{32}$/u) }, + ]) + }) + + it('uses a stable branch key when a commit SHA is unavailable', async () => { + configureJira() + vi.stubEnv('GITHUB_SHA', '') + vi.stubEnv('CI_COMMIT_SHA', '') + vi.stubEnv('BUILDKITE_COMMIT', '') + vi.stubEnv('BITBUCKET_COMMIT', '') + vi.stubEnv('CIRCLE_SHA1', '') + vi.stubEnv('TRAVIS_COMMIT', '') + queueJiraResponses( + jiraResponse(200, { issues: [] }), + jiraResponse(201, { key: 'SEC-42' }), + jiraResponse(200, { issues: [] }), + jiraResponse(201, { key: 'SEC-43' }), + ) + const reportWithoutSha = { ...report, commitSha: undefined } + + await sendJiraTaskNotification({ ...reportWithoutSha, scanId: 'scan-1' }) + await sendJiraTaskNotification({ ...reportWithoutSha, scanId: 'scan-2' }) + + const firstCreate = vi.mocked(apiFetch).mock.calls[1]![1] + const secondCreate = vi.mocked(apiFetch).mock.calls[3]![1] + const firstLabel = JSON.parse(String(firstCreate.body)).fields.labels[0] + const secondLabel = JSON.parse(String(secondCreate.body)).fields.labels[0] + expect(secondLabel).toBe(firstLabel) + }) + + it('omits empty ADF text nodes and newline-only paragraphs', async () => { + configureJira() + queueJiraResponses( + jiraResponse(200, { issues: [] }), + jiraResponse(201, { key: 'SEC-42' }), + ) + const emptyFinding = { + ...report.findings[0]!, + introducedBy: [], + manifests: '', + } + + await sendJiraTaskNotification({ + ...report, + scanUrl: undefined, + findings: [emptyFinding], + }) + + const requestBody = JSON.parse( + String(vi.mocked(apiFetch).mock.calls[1]![1].body), + ) + const textNodes: Array<{ text: string }> = [] + const visit = (value: unknown): void => { + if (!value || typeof value !== 'object') { + return + } + if ('type' in value && value.type === 'text' && 'text' in value) { + textNodes.push(value as { text: string }) + } + if (Array.isArray(value)) { + value.forEach(visit) + } else { + Object.values(value).forEach(visit) + } + } + visit(requestBody.fields.description) + expect(textNodes.every(node => node.text.trim().length > 0)).toBe(true) + expect(textNodes.some(node => node.text === '\n')).toBe(false) + }) + + it('skips task creation if lookup fails and keeps secrets out of warnings', async () => { + configureJira() + vi.mocked(apiFetch).mockResolvedValueOnce(jiraResponse(503)) + + await expect(sendJiraTaskNotification(report)).resolves.toBeUndefined() + + expect(apiFetch).toHaveBeenCalledOnce() + expect(String(vi.mocked(apiFetch).mock.calls[0]?.[0])).not.toContain( + 'jira-secret-token', + ) + }) + + it('does not make a Jira request when there are no findings', async () => { + configureJira() + await sendJiraTaskNotification({ ...report, findings: [] }) + + expect(apiFetch).not.toHaveBeenCalled() + }) + + it('dispatches Jira with Jira enabled even when Slack is not configured', async () => { + configureJira() + queueJiraResponses( + jiraResponse(200, { issues: [] }), + jiraResponse(201, { key: 'SEC-42' }), + ) + + expect(isJiraEnabled()).toBe(true) + await dispatchScanNotifications(report) + + expect(apiFetch).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/commands/scan/notifications/report.mts b/src/commands/scan/notifications/report.mts index 371457ffc..d5e7bf75a 100644 --- a/src/commands/scan/notifications/report.mts +++ b/src/commands/scan/notifications/report.mts @@ -31,6 +31,8 @@ export type NotificationReport = { diffScanId?: string | undefined repository?: string | undefined branch?: string | undefined + pullRequest?: number | undefined + commitSha?: string | undefined scanUrl?: string | undefined decision: 'pass' | 'fail' | 'unknown' | 'not-evaluated' reachabilityEnabled?: boolean | undefined @@ -43,6 +45,8 @@ export type NotificationReport = { export type NotificationMetadata = { repository?: string | undefined branch?: string | undefined + pullRequest?: number | undefined + commitSha?: string | undefined reachabilityEnabled?: boolean | undefined reachabilityFacts?: unknown } @@ -396,6 +400,8 @@ export function createScanNotificationReport( scanId: context.scanId, repository: context.repository, branch: context.branch, + pullRequest: context.pullRequest, + commitSha: context.commitSha, scanUrl: context.scanUrl, decision: context.decision, reachabilityEnabled: context.reachabilityEnabled ?? false, @@ -436,6 +442,8 @@ export function createDiffNotificationReport( diffScanId: result.diff_scan_id ?? undefined, repository: result.repo ?? context.repository, branch: result.branch ?? context.branch, + pullRequest: context.pullRequest, + commitSha: result.commit_sha ?? context.commitSha, scanUrl: result.diff_url ?? result.report_url ?? undefined, decision: result.decision, reachabilityEnabled: context.reachabilityEnabled ?? false, diff --git a/src/commands/scan/output-diff-scan.mts b/src/commands/scan/output-diff-scan.mts index 75f678c67..983f82733 100644 --- a/src/commands/scan/output-diff-scan.mts +++ b/src/commands/scan/output-diff-scan.mts @@ -4,13 +4,8 @@ import util from 'node:util' import colors from 'yoctocolors-cjs' import { getDiffScanBlocking } from './diff-scan-verdict.mts' +import { dispatchScanNotifications } from './notifications/dispatch.mts' import { createDiffNotificationReport } from './notifications/report.mts' -import { sendSlackBotNotifications } from './notifications/slack-bot.mts' -import { - getSlackNotificationConfig, - isSlackNotificationConfigured, - sendSlackWebhookNotifications, -} from './notifications/slack-webhook.mts' import { type PythonDiffJsonContext, availableDiffAlerts, @@ -60,25 +55,24 @@ export async function outputDiffScan( } else if (payload.decision === 'unknown') { setCiExitCode('infrastructure') } - if (result.ok && notificationContext && isSlackNotificationConfigured()) { - const report = createDiffNotificationReport( - payload.comparison_status === 'incomplete' - ? { - ...payload, - new_alerts: availableDiffAlerts( - result.data.diff_scan, - strictBlocking, - ), - } - : payload, - { - ...notificationContext, - decision: payload.decision, - }, + if (result.ok && notificationContext) { + await dispatchScanNotifications( + createDiffNotificationReport( + payload.comparison_status === 'incomplete' + ? { + ...payload, + new_alerts: availableDiffAlerts( + result.data.diff_scan, + strictBlocking, + ), + } + : payload, + { + ...notificationContext, + decision: payload.decision, + }, + ), ) - const slackConfig = getSlackNotificationConfig() ?? null - await sendSlackWebhookNotifications(report, slackConfig) - await sendSlackBotNotifications(report, slackConfig) } await handlePythonJson(payload, file) return @@ -99,29 +93,28 @@ export async function outputDiffScan( if (getDiffScanBlocking(diffScan, strictBlocking)) { setCiExitCode('blocking') } - if (notificationContext && isSlackNotificationConfigured()) { + if (notificationContext) { const payload = mapDiffScanToPythonJson(result, { ...pythonJsonContext, strictBlocking, }) - const report = createDiffNotificationReport( - payload.comparison_status === 'incomplete' - ? { - ...payload, - new_alerts: availableDiffAlerts( - result.data.diff_scan, - strictBlocking, - ), - } - : payload, - { - ...notificationContext, - decision: payload.decision, - }, + await dispatchScanNotifications( + createDiffNotificationReport( + payload.comparison_status === 'incomplete' + ? { + ...payload, + new_alerts: availableDiffAlerts( + result.data.diff_scan, + strictBlocking, + ), + } + : payload, + { + ...notificationContext, + decision: payload.decision, + }, + ), ) - const slackConfig = getSlackNotificationConfig() ?? null - await sendSlackWebhookNotifications(report, slackConfig) - await sendSlackBotNotifications(report, slackConfig) } const dashboardUrl = diffScan.html_url diff --git a/src/commands/scan/output-scan-report.mts b/src/commands/scan/output-scan-report.mts index 8d357c427..c756aae62 100644 --- a/src/commands/scan/output-scan-report.mts +++ b/src/commands/scan/output-scan-report.mts @@ -3,13 +3,8 @@ import path from 'node:path' import { generateReport } from './generate-report.mts' import { createGitLabDependencyReport } from './gitlab-dependency-report.mts' +import { dispatchScanNotifications } from './notifications/dispatch.mts' import { createScanNotificationReport } from './notifications/report.mts' -import { sendSlackBotNotifications } from './notifications/slack-bot.mts' -import { - getSlackNotificationConfig, - isSlackNotificationConfigured, - sendSlackWebhookNotifications, -} from './notifications/slack-webhook.mts' import constants, { EXT_JSON, FOLD_SETTING_NONE, @@ -203,16 +198,15 @@ export async function outputScanReport( setCiExitCode('blocking') } - if (notificationContext && isSlackNotificationConfigured()) { - const notificationReport = createScanNotificationReport(result.data.scan, { - ...notificationContext, - scanId, - scanUrl: `${constants.SOCKET_WEBSITE_URL}/dashboard/org/${encodeURIComponent(orgSlug)}/sbom/${encodeURIComponent(scanId)}`, - decision: scanReport.data.healthy ? 'pass' : 'fail', - }) - const slackConfig = getSlackNotificationConfig() ?? null - await sendSlackWebhookNotifications(notificationReport, slackConfig) - await sendSlackBotNotifications(notificationReport, slackConfig) + if (notificationContext) { + await dispatchScanNotifications( + createScanNotificationReport(result.data.scan, { + ...notificationContext, + scanId, + scanUrl: `${constants.SOCKET_WEBSITE_URL}/dashboard/org/${encodeURIComponent(orgSlug)}/sbom/${encodeURIComponent(scanId)}`, + decision: scanReport.data.healthy ? 'pass' : 'fail', + }), + ) } // I don't think we emit the default error message with banner for an unhealthy report, do we? diff --git a/src/utils/api.mts b/src/utils/api.mts index d4cdae541..1e34b01de 100644 --- a/src/utils/api.mts +++ b/src/utils/api.mts @@ -219,6 +219,21 @@ function _httpsRequestFetch( } } } + const responseInit = { + status: statusCode ?? 0, + statusText: res.statusMessage ?? '', + headers: responseHeaders, + } + if ( + statusCode === 204 || + statusCode === 205 || + statusCode === 304 || + init.method === 'HEAD' + ) { + res.resume() + resolve(new Response(null, responseInit)) + return + } // Resolve with a streaming body as soon as headers are available, // matching fetch() semantics. Callers that pipe response.body (e.g. // streamDownloadWithFetch) receive a live ReadableStream rather than @@ -244,13 +259,7 @@ function _httpsRequestFetch( res.destroy() }, }) - resolve( - new Response(body, { - status: statusCode ?? 0, - statusText: res.statusMessage ?? '', - headers: responseHeaders, - }), - ) + resolve(new Response(body, responseInit)) }, ) if (init.timeout !== undefined) { diff --git a/test/unit/src/commands/ci/handle-ci.test.mts b/test/unit/src/commands/ci/handle-ci.test.mts index 1bd909446..c05b0f60e 100644 --- a/test/unit/src/commands/ci/handle-ci.test.mts +++ b/test/unit/src/commands/ci/handle-ci.test.mts @@ -137,6 +137,7 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun vi.stubEnv('GH_TOKEN', 'synthetic') vi.stubEnv('GITHUB_BASE_REF', 'main') vi.stubEnv('GITHUB_BASE_SHA', 'base-sha') + vi.stubEnv('GITHUB_SHA', 'd'.repeat(40)) vi.stubEnv('GITHUB_SERVER_URL', 'https://github.com') vi.stubEnv('GITHUB_REF', 'refs/pull/42/merge') vi.stubEnv('GITHUB_REPOSITORY', 'example/project') @@ -198,14 +199,10 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun vi.doMock('../../../../../src/utils/path-resolve.mts', () => ({ getPackageFilesForScan: async () => ['package.json'], })) + const upload = vi.fn(async () => ({ ok: true, data: { id: 'test-scan' } })) vi.doMock( '../../../../../src/commands/scan/fetch-create-org-full-scan.mts', - () => ({ - fetchCreateOrgFullScan: async () => ({ - ok: true, - data: { id: 'test-scan' }, - }), - }), + () => ({ fetchCreateOrgFullScan: upload }), ) const { handleCi } = await import( '../../../../../src/commands/ci/handle-ci.mts' @@ -220,6 +217,12 @@ it('uses GH_TOKEN to publish the finished CI report and update comments on rerun await handleCi(false) vi.stubEnv('GITHUB_REF', 'refs/heads/main') await handleCi(false) + expect(upload).toHaveBeenLastCalledWith( + expect.anything(), + expect.anything(), + expect.objectContaining({ commitHash: 'd'.repeat(40), pullRequest: 0 }), + expect.anything(), + ) expect(fetchComments).toHaveBeenCalledTimes(3) expect(writes).toEqual(['POST', 'POST', 'PATCH', 'PATCH', 'PATCH']) expect(comments).toHaveLength(2) 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 c09e65bf3..f9bbc25d1 100644 --- a/test/unit/src/commands/scan/output-scan-report.test.mts +++ b/test/unit/src/commands/scan/output-scan-report.test.mts @@ -29,7 +29,10 @@ const reportConfig = (overrides: Record = {}) => ({ ...overrides, }) -const { postSlack } = vi.hoisted(() => ({ postSlack: vi.fn() })) +const { mockApiFetch, postSlack } = vi.hoisted(() => { + const apiFetch = vi.fn() + return { mockApiFetch: apiFetch, postSlack: apiFetch } +}) vi.mock('../../../../../src/utils/api.mts', async importOriginal => ({ ...(await importOriginal()), apiFetch: postSlack, @@ -341,7 +344,7 @@ describe('output-scan-report', () => { 'SOCKET_SLACK_CONFIG_JSON', JSON.stringify({ url: 'https://hooks.example.invalid/secret' }), ) - const post = postSlack + const post = mockApiFetch .mockReset() .mockResolvedValue({ ok: true, status: 200 }) @@ -391,6 +394,65 @@ describe('output-scan-report', () => { expect(body).toContain('GHSA-1234') }) + it('keeps an unhealthy scan failing when Jira delivery fails', async () => { + vi.stubEnv('SOCKET_JIRA_ENABLED', 'true') + vi.stubEnv('SOCKET_SLACK_CONFIG_JSON', '') + vi.stubEnv( + 'SOCKET_JIRA_CONFIG_JSON', + JSON.stringify({ + url: 'https://example.atlassian.net', + email: 'bot@example.com', + api_token: 'secret', + project: 'SEC', + }), + ) + const lookup = mockApiFetch + .mockReset() + .mockRejectedValueOnce(new Error('request failed')) + mockGenerateReport.mockReturnValue({ + ok: true, + data: getUnhealthyReport(), + }) + + await outputScanReport( + { + ok: true, + data: { + scan: [ + { + type: 'npm', + name: 'left-pad', + version: '1.0.0', + alerts: [ + { + action: 'error', + type: 'cve', + severity: 'high', + props: { ghsaId: 'GHSA-1234' }, + }, + ], + }, + ], + }, + } as any, + { + orgSlug: 'test-org', + scanId: 'test-scan', + includeLicensePolicy: false, + outputKind: 'json', + filepath: '-', + fold: 'none', + reportLevel: 'error', + short: false, + notificationContext: { repository: 'api', branch: 'feature/fix' }, + }, + ) + + expect(lookup).toHaveBeenCalledOnce() + expect(lookup.mock.calls[0]?.[0]).toContain('/rest/api/3/search/jql?') + expect(process.exitCode).toBe(1) + }) + it('lets --disable-blocking make an unhealthy report non-blocking', async () => { setCiExitCodePolicy({ disableBlocking: true }) mockGenerateReport.mockReturnValue({ diff --git a/test/unit/src/utils/api.test.mts b/test/unit/src/utils/api.test.mts index 1bdd1fd69..4a5781785 100644 --- a/test/unit/src/utils/api.test.mts +++ b/test/unit/src/utils/api.test.mts @@ -630,6 +630,22 @@ describe('apiFetch with extra CA certificates', () => { ) }) + it('accepts a 204 response to a Jira issue update', async () => { + const resume = vi.fn() + mockHttpsRequest.mockImplementationOnce((_url, _options, callback) => { + callback({ statusCode: 204, headers: {}, resume }) + return { on: vi.fn(), end: vi.fn() } + }) + const { apiFetch } = await import('../../../../src/utils/api.mts') + const response = await apiFetch( + 'https://jira.example/rest/api/3/issue/SEC-1', + { method: 'PUT' }, + ) + expect(response.status).toBe(204) + expect(response.body).toBeNull() + expect(resume).toHaveBeenCalledOnce() + }) + it('should follow redirects in https.request path', async () => { const caCerts = ['ROOT_CERT', 'EXTRA_CERT'] mockGetExtraCaCerts.mockReturnValue(caCerts)