diff --git a/.gitignore b/.gitignore index 7dd4d1664..826c23bcd 100644 --- a/.gitignore +++ b/.gitignore @@ -889,6 +889,11 @@ !/src/commands/ci/gitlab-commit-status-context.mts !/src/commands/ci/publish-gitlab-commit-status.mts !/src/commands/scan/diff-scan-verdict.mts +!/src/commands/scan/diff-scan-verdict.test.mts +!/src/commands/scan/notifications/ +!/src/commands/scan/notifications/report.mts +!/src/commands/scan/notifications/slack-webhook.mts +!/src/commands/scan/notifications/slack-webhook.test.mts !/src/commands/ci/publish-gitlab-mr-notes.mts !/src/commands/ci/publish-pr-comments.mts !/src/commands/ci/publish-pr-comments.test.mts diff --git a/docs/commands/scan/report.md b/docs/commands/scan/report.md index bf864f4d5..f3e5904c6 100644 --- a/docs/commands/scan/report.md +++ b/docs/commands/scan/report.md @@ -32,3 +32,37 @@ socket-dependency-scan: The report uses GitLab Dependency Scanning schema version `15.0.0`. Findings are generated from the scan's package and alert data before CLI report folding or policy-level filtering is applied. + +## Slack CI notifications + +The scan creation report flow can send an opt-in Slack summary after it evaluates +the report. Store the webhook URL in your CI secret store and expose the JSON +configuration only to trusted jobs: + +```sh +export SOCKET_SLACK_CONFIG_JSON='{"url":"https://hooks.slack.com/services/..."}' +export SOCKET_SLACK_LEVELS='block,warn' +socket scan create --report +``` + +For multiple destinations, use named URLs and configure each destination's +filters: + +```json +{ + "url": [ + {"name":"security","url":"https://hooks.slack.com/services/..."} + ], + "url_configs": { + "security": { + "repos": ["api"], + "alert_types": ["cve"], + "severities": ["critical", "high"] + } + } +} +``` + +`alert_types` takes precedence over `severities`, matching the Python CLI. +Delivery errors are reported as warnings and do not change the scan decision. +Existing report viewing commands do not send notifications. diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index c440547d5..37ad36eb8 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -43,8 +43,8 @@ import { import { buildToolsFor } from '../manifest/scripts/build-tool.mts' import type { ReachabilityFallback } from './output-create-new-scan.mts' -import type { PythonDiffJsonContext } from './python-diff-json.mts' import type { ReachabilityOptions } from './perform-reachability-analysis.mts' +import type { PythonDiffJsonContext } from './python-diff-json.mts' import type { REPORT_LEVEL } from './types.mts' import type { OutputKind } from '../../types.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' @@ -604,6 +604,7 @@ async function createNewScan( outputKind, pythonJsonFormat, pythonJsonContext, + notificationContext: { repository: repoName, branch: branchName }, }) } else { await handleScanReport({ @@ -615,6 +616,7 @@ async function createNewScan( reportLevel, scanId, short: false, + notificationContext: { repository: repoName, branch: branchName }, }) } } else { diff --git a/src/commands/scan/handle-diff-scan.mts b/src/commands/scan/handle-diff-scan.mts index 9778778a6..f33cff512 100644 --- a/src/commands/scan/handle-diff-scan.mts +++ b/src/commands/scan/handle-diff-scan.mts @@ -45,6 +45,7 @@ export async function handleDiffScan({ export async function handlePrDiffScan({ id1, id2, + notificationContext, onDiffReport, orgSlug, outputKind, @@ -67,6 +68,9 @@ export async function handlePrDiffScan({ outputKind: OutputKind pythonJsonFormat?: boolean | undefined pythonJsonContext?: PythonDiffJsonContext | undefined + notificationContext?: + | { repository?: string | undefined; branch?: string | undefined } + | undefined }): Promise { const result = await fetchDiffScan({ id1, id2, orgSlug }) await outputDiffScan(result, { @@ -76,6 +80,7 @@ export async function handlePrDiffScan({ strictBlocking: false, pythonJsonFormat, pythonJsonContext, + notificationContext: result.ok ? notificationContext : undefined, }) if (result.ok) { await onDiffReport?.( diff --git a/src/commands/scan/handle-scan-report.mts b/src/commands/scan/handle-scan-report.mts index 5c4f86fb2..c76109ef5 100644 --- a/src/commands/scan/handle-scan-report.mts +++ b/src/commands/scan/handle-scan-report.mts @@ -1,11 +1,13 @@ import { fetchScanData } from './fetch-report-data.mts' import { outputScanReport } from './output-scan-report.mts' +import type { NotificationMetadata } from './notifications/report.mts' import type { FOLD_SETTING, REPORT_LEVEL } from './types.mts' import type { OutputKind } from '../../types.mts' export type HandleScanReportConfig = { orgSlug: string + notificationContext?: NotificationMetadata | undefined scanId: string includeLicensePolicy: boolean outputKind: OutputKind @@ -23,6 +25,7 @@ export async function handleScanReport({ fold, gitlabSecurityFile, includeLicensePolicy, + notificationContext, orgSlug, outputKind, reportLevel, @@ -42,6 +45,7 @@ export async function handleScanReport({ outputKind, reportLevel, short, + notificationContext, enableGitlabSecurity: enableGitlabSecurity ?? false, gitlabSecurityFile: gitlabSecurityFile ?? 'gl-dependency-scanning-report.json', diff --git a/src/commands/scan/notifications/report.mts b/src/commands/scan/notifications/report.mts new file mode 100644 index 000000000..400d94751 --- /dev/null +++ b/src/commands/scan/notifications/report.mts @@ -0,0 +1,127 @@ +import type { SocketArtifact } from '../../../utils/alert/artifact.mts' +import type { PythonDiffJson } from '../python-diff-json.mts' + +export type NotificationFinding = { + packageName: string + ecosystem: string + version: string + alertType: string + severity: string + action: string + url?: string | undefined + advisoryId?: string | undefined + purl?: string | undefined + introducedBy?: Array<[string, string]> | undefined + manifests?: string | undefined +} + +export type NotificationReport = { + kind: 'diff' | 'scan' + scanId?: string | undefined + diffScanId?: string | undefined + repository?: string | undefined + branch?: string | undefined + scanUrl?: string | undefined + decision: 'pass' | 'fail' | 'unknown' | 'not-evaluated' + summary: string + findings: NotificationFinding[] +} + +export type NotificationMetadata = { + repository?: string | undefined + branch?: string | undefined +} + +export type NotificationContext = NotificationMetadata & { + decision: NotificationReport['decision'] +} + +function advisoryId(props: Record): string | undefined { + for (const value of [props['ghsaId'], props['cveId']]) { + const ids = (Array.isArray(value) ? value : [value]).filter( + (id): id is string => typeof id === 'string' && Boolean(id.trim()), + ) + if (ids.length) { + return ids.join(', ') + } + } + return undefined +} + +function findingsFromArtifacts( + artifacts: SocketArtifact[], +): NotificationFinding[] { + const findings: NotificationFinding[] = [] + for (const artifact of artifacts) { + for (const alert of artifact.alerts ?? []) { + const props = alert.props ?? {} + findings.push({ + packageName: artifact.name ?? 'unknown', + ecosystem: artifact.type ?? 'unknown', + version: artifact.version ?? 'unknown', + alertType: alert.type ?? 'unknown', + severity: alert.severity ?? 'unknown', + action: alert.action ?? 'unknown', + url: typeof props['url'] === 'string' ? props['url'] : undefined, + advisoryId: advisoryId(props), + }) + } + } + return findings +} + +export function summarize(findings: NotificationFinding[]): string { + const blocking = findings.filter(finding => finding.action === 'error').length + const warning = findings.filter(finding => finding.action === 'warn').length + return `${findings.length} finding${findings.length === 1 ? '' : 's'} (${blocking} blocking, ${warning} warning)` +} + +export function createScanNotificationReport( + scan: SocketArtifact[], + context: NotificationContext & { + scanId?: string | undefined + scanUrl?: string | undefined + }, +): NotificationReport { + const findings = findingsFromArtifacts(scan) + return { + kind: 'scan', + scanId: context.scanId, + repository: context.repository, + branch: context.branch, + scanUrl: context.scanUrl, + decision: context.decision, + summary: summarize(findings), + findings, + } +} + +export function createDiffNotificationReport( + result: PythonDiffJson, + context: NotificationContext, +): NotificationReport { + const findings: NotificationFinding[] = result.new_alerts.map(alert => ({ + packageName: alert.pkg_name ?? 'unknown', + ecosystem: alert.pkg_type ?? 'unknown', + version: alert.pkg_version ?? 'unknown', + alertType: alert.type, + severity: alert.severity ?? 'unknown', + action: alert.action ?? 'unknown', + url: alert.url ?? undefined, + advisoryId: advisoryId(alert.props), + purl: alert.purl ?? undefined, + introducedBy: alert.introduced_by, + manifests: alert.manifests, + })) + return { + kind: 'diff', + scanId: result.head_scan_id ?? undefined, + diffScanId: result.diff_scan_id ?? undefined, + repository: result.repo ?? context.repository, + branch: result.branch ?? context.branch, + scanUrl: result.diff_url ?? result.report_url ?? undefined, + decision: result.decision, + summary: summarize(findings), + findings, + } +} diff --git a/src/commands/scan/notifications/slack-webhook.mts b/src/commands/scan/notifications/slack-webhook.mts new file mode 100644 index 000000000..6263d3bb5 --- /dev/null +++ b/src/commands/scan/notifications/slack-webhook.mts @@ -0,0 +1,297 @@ +import { summarize } from './report.mts' +import { apiFetch } from '../../../utils/api.mts' +import { logger } from '../../../utils/logger.mts' + +import type { NotificationFinding, NotificationReport } from './report.mts' + +type Destination = { name: string; url: string } +type DestinationFilter = { + repos?: string[] + alert_types?: string[] + severities?: string[] +} +type SlackBlock = + | { type: 'section'; text: { type: 'mrkdwn'; text: string } } + | { type: 'context'; elements: [{ type: 'mrkdwn'; text: string }] } + +const MAX_FINDINGS = 40 +const MAX_TEXT_LENGTH = 2800 +const REQUEST_TIMEOUT_MS = 10_000 + +function parseConfig(): Record | undefined { + const raw = process.env['SOCKET_SLACK_CONFIG_JSON'] + if (!raw) { + return undefined + } + try { + const config: unknown = JSON.parse(raw) + if (config && typeof config === 'object' && !Array.isArray(config)) { + return config as Record + } + } catch { + logger.warn( + 'Slack notification configuration is invalid JSON; skipping delivery.', + ) + } + return undefined +} + +export function isSlackWebhookConfigured(): boolean { + return Boolean(process.env['SOCKET_SLACK_CONFIG_JSON']) +} + +function destinations(input: unknown): Destination[] { + const items = Array.isArray(input) ? input : [input] + return items.flatMap((item, index) => { + if (typeof item === 'string') { + return [{ name: index ? `webhook_${index}` : 'default', url: item }] + } + if (!item || typeof item !== 'object') { + return [] + } + const candidate = item as { name?: unknown; url?: unknown } + return typeof candidate.url === 'string' + ? [ + { + name: + typeof candidate.name === 'string' + ? candidate.name + : `webhook_${index}`, + url: candidate.url, + }, + ] + : [] + }) +} + +function safeFilter(value: unknown): DestinationFilter | undefined { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return undefined + } + const source = value as Record + const result: DestinationFilter = {} + for (const key of ['repos', 'alert_types', 'severities'] as const) { + const candidate = source[key] + if (candidate === undefined) { + continue + } + if ( + !Array.isArray(candidate) || + candidate.some(item => typeof item !== 'string') + ) { + return undefined + } + result[key] = candidate as string[] + } + return result +} + +function escapeMrkdwn(value: string): string { + return value + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') +} + +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.replaceAll('|', '%7C') + : undefined + } catch { + return undefined + } +} + +function matches( + finding: NotificationFinding, + report: NotificationReport, + filter: DestinationFilter, +): boolean { + if ( + filter.repos?.length && + (!report.repository || !filter.repos.includes(report.repository)) + ) { + return false + } + if (filter.alert_types?.length) { + return filter.alert_types.includes(finding.alertType) + } + if ( + filter.severities?.length && + !filter.severities.includes(finding.severity) + ) { + return false + } + return true +} + +function slackText( + report: NotificationReport, + findings: NotificationFinding[], +): string { + const title = + report.decision === 'fail' + ? 'Socket security issues were found' + : 'Socket scan completed' + const summary = summarize(findings) + const blocks: SlackBlock[] = [ + { + type: 'section', + text: { + type: 'mrkdwn', + text: `*${title}*${report.repository ? ` in ${escapeMrkdwn(report.repository)}` : ''}${report.branch ? ` (${escapeMrkdwn(report.branch)})` : ''}`.slice( + 0, + MAX_TEXT_LENGTH, + ), + }, + }, + { + type: 'section', + text: { + type: 'mrkdwn', + text: `${escapeMrkdwn(summary).slice(0, 2000)}${safeLink(report.scanUrl) ? ` · <${safeLink(report.scanUrl)}|View scan>` : ''}`.slice( + 0, + MAX_TEXT_LENGTH, + ), + }, + }, + ] + for (const finding of findings.slice(0, MAX_FINDINGS)) { + const name = escapeMrkdwn( + `${finding.ecosystem}/${finding.packageName}@${finding.version}`, + ) + const advisory = finding.advisoryId + ? ` · ${escapeMrkdwn(finding.advisoryId)}` + : '' + const url = safeLink(finding.url) + const link = url ? `<${url}|${name}>` : name + const source = finding.introducedBy?.length + ? ` · Introduced by ${escapeMrkdwn(finding.introducedBy.map(([name, version]) => `${name}@${version}`).join(', '))}` + : '' + const manifests = finding.manifests + ? ` · Manifest ${escapeMrkdwn(finding.manifests)}` + : '' + const line = `• *${escapeMrkdwn(finding.severity)}* ${link} · ${escapeMrkdwn(finding.alertType)}${advisory} · ${escapeMrkdwn(finding.action)}${source}${manifests}` + blocks.push({ + type: 'section', + text: { type: 'mrkdwn', text: line.slice(0, MAX_TEXT_LENGTH) }, + }) + } + if (findings.length > MAX_FINDINGS) { + blocks.push({ + type: 'context', + elements: [ + { + type: 'mrkdwn', + text: `${findings.length - MAX_FINDINGS} more findings omitted`, + }, + ], + }) + } + return JSON.stringify({ + text: `${title}: ${escapeMrkdwn(summary).slice(0, 500)}`, + blocks: blocks.slice(0, 50), + }) +} + +/** Send the completed scan report to explicitly configured Slack incoming webhooks. */ +export async function sendSlackWebhookNotifications( + report: NotificationReport, +): Promise { + const config = parseConfig() + if (!config?.['url']) { + return + } + const rawUrlConfigs = config['url_configs'] + if ( + rawUrlConfigs !== undefined && + (!rawUrlConfigs || + typeof rawUrlConfigs !== 'object' || + Array.isArray(rawUrlConfigs)) + ) { + logger.warn( + 'Slack notification url_configs must be an object; skipping delivery.', + ) + return + } + const urlConfigs = (rawUrlConfigs ?? {}) as Record + const levels = (process.env['SOCKET_SLACK_LEVELS'] ?? 'block,warn') + .split(',') + .map(value => value.trim().toLowerCase()) + .filter(Boolean) + const allowedActions = new Set( + levels.flatMap(level => + level === 'block' ? ['error', 'block'] : level === 'warn' ? ['warn'] : [], + ), + ) + const configured = destinations(config['url']) + if (!configured.length) { + logger.warn( + 'Slack notification configuration does not contain a webhook URL; skipping delivery.', + ) + return + } + for (const destination of configured) { + const rawFilter = urlConfigs[destination.name] + if (rawUrlConfigs && rawFilter === undefined) { + logger.warn( + `Slack webhook destination "${destination.name}" has no url_configs entry; skipping it.`, + ) + continue + } + const filter = rawFilter === undefined ? {} : safeFilter(rawFilter) + if (!filter) { + logger.warn( + `Slack webhook destination "${destination.name}" has an invalid filter; skipping it.`, + ) + continue + } + let target: URL + try { + target = new URL(destination.url) + if (target.protocol !== 'https:' || target.username || target.password) { + throw new Error('invalid URL') + } + } catch { + logger.warn( + `Slack webhook destination "${destination.name}" is not a valid HTTPS URL; skipping it.`, + ) + continue + } + const findings = report.findings.filter( + finding => + allowedActions.has(finding.action.toLowerCase()) && + matches(finding, report, filter), + ) + if (!findings.length) { + continue + } + try { + // Deliver destinations in order so each webhook failure is reported independently. + // eslint-disable-next-line no-await-in-loop + const response = await apiFetch(target.href, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: slackText(report, findings), + rejectRedirects: true, + timeout: REQUEST_TIMEOUT_MS, + }) + if (!response.ok) { + logger.warn( + `Slack webhook delivery to "${destination.name}" failed with HTTP ${response.status}; scan policy is unchanged.`, + ) + } + } catch { + logger.warn( + `Slack webhook delivery to "${destination.name}" failed; scan policy is unchanged.`, + ) + } + } +} diff --git a/src/commands/scan/notifications/slack-webhook.test.mts b/src/commands/scan/notifications/slack-webhook.test.mts new file mode 100644 index 000000000..9e9c35908 --- /dev/null +++ b/src/commands/scan/notifications/slack-webhook.test.mts @@ -0,0 +1,127 @@ +import { apiFetch } from '../../../utils/api.mts' + +vi.mock('../../../utils/api.mts', () => ({ apiFetch: vi.fn() })) +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { + isSlackWebhookConfigured, + sendSlackWebhookNotifications, +} from './slack-webhook.mts' + +import type { NotificationReport } from './report.mts' + +const report: NotificationReport = { + kind: 'diff', + repository: 'example', + branch: 'feature', + decision: 'fail', + summary: '2 findings (1 blocking, 1 warning)', + findings: [ + { + packageName: 'left-pad', + ecosystem: 'npm', + version: '1.0.0', + alertType: 'cve', + severity: 'high', + action: 'error', + advisoryId: 'GHSA-1234', + }, + { + packageName: 'safe-lib', + ecosystem: 'npm', + version: '2.0.0', + alertType: 'license', + severity: 'low', + action: 'warn', + }, + ], +} + +afterEach(() => { + vi.unstubAllEnvs() + vi.unstubAllGlobals() +}) + +describe('Slack webhook notifications', () => { + it('is disabled without an explicit webhook configuration', async () => { + const fetch = vi.fn() + vi.mocked(apiFetch).mockImplementation(fetch) + expect(isSlackWebhookConfigured()).toBe(false) + await sendSlackWebhookNotifications(report) + expect(fetch).not.toHaveBeenCalled() + }) + + it('sends filtered findings without following redirects or leaking webhook URLs', async () => { + const secretUrl = 'https://hooks.example.invalid/secret-token' + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ + url: [{ name: 'security', url: secretUrl }], + url_configs: { security: { repos: ['example'], alert_types: ['cve'] } }, + }), + ) + const fetch = vi.fn().mockResolvedValue({ ok: false, status: 302 }) + vi.mocked(apiFetch).mockImplementation(fetch) + + await sendSlackWebhookNotifications(report) + + expect(fetch).toHaveBeenCalledOnce() + const [url, options] = fetch.mock.calls[0] as [ + string, + NonNullable[1]>, + ] + expect(url).toBe(secretUrl) + expect(options.rejectRedirects).toBe(true) + expect( + JSON.parse(String(options.body)) + .blocks.map((block: { text?: { text?: string } }) => block.text?.text) + .join('\n'), + ).toContain('GHSA-1234') + expect(JSON.stringify(options.body)).not.toContain('safe-lib') + }) + + it('does not post when severity filters exclude every finding', async () => { + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ + url: 'https://hooks.example.invalid/secret-token', + url_configs: { default: { severities: ['critical'] } }, + }), + ) + const fetch = vi.fn() + vi.mocked(apiFetch).mockImplementation(fetch) + + await sendSlackWebhookNotifications(report) + + expect(fetch).not.toHaveBeenCalled() + }) + + it('skips malformed filters instead of interrupting scan output', async () => { + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ + url: [ + { name: 'security', url: 'https://hooks.example.invalid/secret' }, + ], + url_configs: { security: { alert_types: 'cve' } }, + }), + ) + const fetch = vi.fn() + vi.mocked(apiFetch).mockImplementation(fetch) + + await expect(sendSlackWebhookNotifications(report)).resolves.toBeUndefined() + expect(fetch).not.toHaveBeenCalled() + }) + + it('handles network timeouts without changing scan policy or printing the URL', async () => { + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ url: 'https://hooks.example.invalid/secret-token' }), + ) + const fetch = vi.fn().mockRejectedValue(new Error('timed out')) + vi.mocked(apiFetch).mockImplementation(fetch) + + await expect(sendSlackWebhookNotifications(report)).resolves.toBeUndefined() + expect(fetch).toHaveBeenCalledOnce() + }) +}) diff --git a/src/commands/scan/output-diff-scan.mts b/src/commands/scan/output-diff-scan.mts index a5c0f87c2..c3d146a3a 100644 --- a/src/commands/scan/output-diff-scan.mts +++ b/src/commands/scan/output-diff-scan.mts @@ -4,8 +4,14 @@ import util from 'node:util' import colors from 'yoctocolors-cjs' import { getDiffScanBlocking } from './diff-scan-verdict.mts' +import { createDiffNotificationReport } from './notifications/report.mts' +import { + isSlackWebhookConfigured, + sendSlackWebhookNotifications, +} from './notifications/slack-webhook.mts' import { type PythonDiffJsonContext, + availableDiffAlerts, mapDiffScanToPythonJson, } from './python-diff-json.mts' import constants from '../../constants.mts' @@ -23,6 +29,7 @@ export async function outputDiffScan( { depth, file, + notificationContext, outputKind, pythonJsonContext = {}, pythonJsonFormat = false, @@ -32,6 +39,9 @@ export async function outputDiffScan( file: string outputKind: OutputKind strictBlocking: boolean + notificationContext?: + | { repository?: string | undefined; branch?: string | undefined } + | undefined pythonJsonFormat?: boolean | undefined pythonJsonContext?: PythonDiffJsonContext | undefined }, @@ -48,6 +58,25 @@ export async function outputDiffScan( } else if (payload.decision === 'unknown') { setCiExitCode('infrastructure') } + if (result.ok && notificationContext && isSlackWebhookConfigured()) { + await sendSlackWebhookNotifications( + createDiffNotificationReport( + payload.comparison_status === 'incomplete' + ? { + ...payload, + new_alerts: availableDiffAlerts( + result.data.diff_scan, + strictBlocking, + ), + } + : payload, + { + ...notificationContext, + decision: payload.decision, + }, + ), + ) + } await handlePythonJson(payload, file) return } @@ -67,6 +96,29 @@ export async function outputDiffScan( if (getDiffScanBlocking(diffScan, strictBlocking)) { setCiExitCode('blocking') } + if (notificationContext && isSlackWebhookConfigured()) { + const payload = mapDiffScanToPythonJson(result, { + ...pythonJsonContext, + strictBlocking, + }) + await sendSlackWebhookNotifications( + createDiffNotificationReport( + payload.comparison_status === 'incomplete' + ? { + ...payload, + new_alerts: availableDiffAlerts( + result.data.diff_scan, + strictBlocking, + ), + } + : payload, + { + ...notificationContext, + decision: payload.decision, + }, + ), + ) + } const dashboardUrl = diffScan.html_url const dashboardMessage = dashboardUrl diff --git a/src/commands/scan/output-scan-report.mts b/src/commands/scan/output-scan-report.mts index b5cfd3f89..d5d7dc0cf 100644 --- a/src/commands/scan/output-scan-report.mts +++ b/src/commands/scan/output-scan-report.mts @@ -3,6 +3,11 @@ import path from 'node:path' import { generateReport } from './generate-report.mts' import { createGitLabDependencyReport } from './gitlab-dependency-report.mts' +import { createScanNotificationReport } from './notifications/report.mts' +import { + isSlackWebhookConfigured, + sendSlackWebhookNotifications, +} from './notifications/slack-webhook.mts' import constants, { EXT_JSON, FOLD_SETTING_NONE, @@ -21,6 +26,7 @@ import { walkNestedMap } from '../../utils/walk-nested-map.mts' import { pluralize } from '../../utils/words.mts' import type { ReportLeafNode, ScanReport } from './generate-report.mts' +import type { NotificationMetadata } from './notifications/report.mts' import type { FOLD_SETTING, REPORT_LEVEL } from './types.mts' import type { CResult, OutputKind } from '../../types.mts' import type { SocketArtifact } from '../../utils/alert/artifact.mts' @@ -34,6 +40,7 @@ export type OutputScanReportConfig = { fold: FOLD_SETTING reportLevel: REPORT_LEVEL short: boolean + notificationContext?: NotificationMetadata | undefined enableGitlabSecurity?: boolean gitlabSecurityFile?: string } @@ -119,6 +126,7 @@ export async function outputScanReport( fold, gitlabSecurityFile, includeLicensePolicy, + notificationContext, orgSlug, outputKind, reportLevel, @@ -193,6 +201,17 @@ export async function outputScanReport( setCiExitCode('blocking') } + if (notificationContext && isSlackWebhookConfigured()) { + await sendSlackWebhookNotifications( + 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? // if (!scanReport.data.healthy) { // logger.fail(failMsgWithBadge(scanReport.message, scanReport.cause)) diff --git a/src/commands/scan/python-diff-json.mts b/src/commands/scan/python-diff-json.mts index ec0027d16..361434bce 100644 --- a/src/commands/scan/python-diff-json.mts +++ b/src/commands/scan/python-diff-json.mts @@ -1,8 +1,9 @@ -import type { DiffScanData } from './fetch-diff-scan.mts' import constants from '../../constants.mts' -import type { CResult } from '../../types.mts' import { createPurlObject } from '../../utils/purl.mts' +import type { DiffScanData } from './fetch-diff-scan.mts' +import type { CResult } from '../../types.mts' + type DiffScan = DiffScanData['diff_scan'] type DiffArtifact = DiffScan['artifacts']['added'][number] type DiffArtifactGroup = keyof DiffScan['artifacts'] @@ -374,6 +375,29 @@ function fromFailure( return createPythonDiffJsonFailure(result.message, result.cause, context) } +/** Retain available findings for notifications while the Python verdict stays incomplete. */ +export function availableDiffAlerts( + diff: DiffScan, + strictBlocking: boolean, +): PythonCompatibleAlert[] { + const alerts = (group: DiffArtifactGroup) => { + const artifacts = diff.artifacts?.[group] + if (!isArtifactArray(artifacts)) { + return [] + } + return artifacts.flatMap(artifact => + (artifact.alerts ?? []) + .filter(alert => alert.action === 'error' || alert.action === 'warn') + .map(alert => alertFromArtifact(artifact, alert, group)), + ) + } + return selectOutputAlerts( + [...alerts('added'), ...alerts('updated'), ...alerts('replaced')], + strictBlocking ? alerts('unchanged') : [], + strictBlocking, + ) +} + export function mapDiffScanToPythonJson( result: CResult, context: PythonDiffJsonContext = {}, diff --git a/test/unit/src/commands/scan/output-diff-scan.test.mts b/test/unit/src/commands/scan/output-diff-scan.test.mts index 74116649e..4162c962a 100644 --- a/test/unit/src/commands/scan/output-diff-scan.test.mts +++ b/test/unit/src/commands/scan/output-diff-scan.test.mts @@ -8,6 +8,12 @@ import { handlePrDiffScan } from '../../../../../src/commands/scan/handle-diff-s import { outputDiffScan } from '../../../../../src/commands/scan/output-diff-scan.mts' import { logger } from '../../../../../src/utils/logger.mts' +const { postSlack } = vi.hoisted(() => ({ postSlack: vi.fn() })) +vi.mock('../../../../../src/utils/api.mts', async importOriginal => ({ + ...(await importOriginal()), + apiFetch: postSlack, +})) + const fetchDiffScan = vi.hoisted(() => vi.fn()) vi.mock('../../../../../src/commands/scan/fetch-diff-scan.mts', () => ({ @@ -61,6 +67,8 @@ describe('outputDiffScan strict blocking', () => { afterEach(() => { process.exitCode = 0 vi.clearAllMocks() + vi.unstubAllEnvs() + vi.unstubAllGlobals() }) it('evaluates the server-side PR diff created from the exact scan IDs', async () => { @@ -368,4 +376,61 @@ describe('diff scan report formats', () => { expect.stringContaining('use the --json flag'), ) }) + it('sends an opted-in PR report with caller-provided repository and branch metadata', async () => { + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ url: 'https://hooks.example.invalid/secret' }), + ) + const post = postSlack + .mockReset() + .mockResolvedValue({ ok: true, status: 200 }) + + fetchDiffScan.mockResolvedValue({ + ok: true, + data: { + diff_scan: { + ...diff.diff_scan, + id: 'diff-id', + html_url: 'https://socket.dev/scan/diff', + artifacts: { + ...diff.diff_scan.artifacts, + added: [ + { + type: 'npm', + name: 'left-pad', + version: '1.0.0', + alerts: [ + { + action: 'error', + type: 'test-alert', + key: 'alert-1', + severity: 'high', + }, + ], + }, + ], + unchanged: [], + }, + }, + }, + }) + + await handlePrDiffScan({ + id1: 'before', + id2: 'after', + orgSlug: 'example', + outputKind: 'json', + notificationContext: { + repository: 'socket-cli', + branch: 'feature/security', + }, + }) + + expect(post).toHaveBeenCalledOnce() + const body = JSON.stringify(post.mock.calls[0]?.[1]?.body) + expect(body).toContain('socket-cli') + expect(body).toContain('feature/security') + expect(body).toContain('left-pad') + }) + }) 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 45b4447e9..c09e65bf3 100644 --- a/test/unit/src/commands/scan/output-scan-report.test.mts +++ b/test/unit/src/commands/scan/output-scan-report.test.mts @@ -29,6 +29,12 @@ const reportConfig = (overrides: Record = {}) => ({ ...overrides, }) +const { postSlack } = vi.hoisted(() => ({ postSlack: vi.fn() })) +vi.mock('../../../../../src/utils/api.mts', async importOriginal => ({ + ...(await importOriginal()), + apiFetch: postSlack, +})) + const { mockGenerateReport } = vi.hoisted(() => ({ mockGenerateReport: vi.fn(), })) @@ -274,6 +280,7 @@ describe('output-scan-report', () => { afterEach(() => { setCiExitCodePolicy(undefined) + vi.unstubAllEnvs() process.exitCode = originalExitCode }) @@ -329,6 +336,61 @@ describe('output-scan-report', () => { expect(process.exitCode).toBeUndefined() }) + it('sends a configured notification only when scan creation supplies report context', async () => { + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ url: 'https://hooks.example.invalid/secret' }), + ) + const post = postSlack + .mockReset() + .mockResolvedValue({ ok: true, status: 200 }) + + 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(post).toHaveBeenCalledOnce() + const body = JSON.stringify(post.mock.calls[0]?.[1]?.body) + expect(body).toContain('api') + expect(body).toContain('feature/fix') + expect(body).toContain('GHSA-1234') + }) + it('lets --disable-blocking make an unhealthy report non-blocking', async () => { setCiExitCodePolicy({ disableBlocking: true }) mockGenerateReport.mockReturnValue({