diff --git a/.gitignore b/.gitignore index a513f6739..12c44dace 100644 --- a/.gitignore +++ b/.gitignore @@ -892,6 +892,7 @@ !/src/commands/scan/diff-scan-verdict.test.mts !/src/commands/scan/notifications/ !/src/commands/scan/notifications/report.mts +!/src/commands/scan/notifications/report.test.mts !/src/commands/scan/notifications/slack-bot.mts !/src/commands/scan/notifications/slack-bot.test.mts !/src/commands/scan/notifications/slack-webhook.mts diff --git a/docs/commands/scan/report.md b/docs/commands/scan/report.md index d26c6b32f..fdc65b17f 100644 --- a/docs/commands/scan/report.md +++ b/docs/commands/scan/report.md @@ -67,6 +67,12 @@ filters: Delivery errors are reported as warnings and do not change the scan decision. Existing report viewing commands do not send notifications. +When the scan creation flow runs with `--reach`, Slack findings include the +matching reachability state and a bounded call trace for confirmed reachable +findings. Unknown or malformed facts are marked unclassified. Set +`reachability_alerts_only: true` on a destination to send only findings whose +facts confirm they are reachable. + Slack bot delivery is available when the job also supplies a bot token and channel configuration. Create a Slack app with the `chat:write` bot token scope, install it in the workspace, and invite it to each target channel. Keep the bot diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index 37ad36eb8..742ace902 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -9,6 +9,7 @@ import { fetchSupportedScanFileNames } from './fetch-supported-scan-file-names.m import { finalizeTier1Scan } from './finalize-tier1-scan.mts' import { handlePrDiffScan } from './handle-diff-scan.mts' import { handleScanReport } from './handle-scan-report.mts' +import { isSlackNotificationConfigured } from './notifications/slack-webhook.mts' import { outputCreateNewScan } from './output-create-new-scan.mts' import { performReachabilityAnalysis } from './perform-reachability-analysis.mts' import { @@ -576,6 +577,27 @@ async function createNewScan( // A scan without --reach would upload a leftover report as an SBOM with // stale reachability results; a failed scan keeps it for debugging. + const reachabilityEnabled = + reach.runReachabilityAnalysis && !reachabilityFallback + let notificationReachabilityFacts: unknown + if ( + report && + fullScanCResult.ok && + reachabilityEnabled && + reachabilityReport && + isSlackNotificationConfigured() + ) { + try { + notificationReachabilityFacts = JSON.parse( + await fs.readFile(path.resolve(cwd, reachabilityReport), 'utf8'), + ) as unknown + } catch { + logger.warn( + 'Reachability facts could not be read for Slack notifications; findings will be marked unclassified.', + ) + } + } + if ( fullScanCResult.ok && scanId && @@ -604,7 +626,12 @@ async function createNewScan( outputKind, pythonJsonFormat, pythonJsonContext, - notificationContext: { repository: repoName, branch: branchName }, + notificationContext: { + repository: repoName, + branch: branchName, + reachabilityEnabled, + reachabilityFacts: notificationReachabilityFacts, + }, }) } else { await handleScanReport({ @@ -616,7 +643,12 @@ async function createNewScan( reportLevel, scanId, short: false, - notificationContext: { repository: repoName, branch: branchName }, + notificationContext: { + repository: repoName, + branch: branchName, + reachabilityEnabled, + reachabilityFacts: notificationReachabilityFacts, + }, }) } } else { diff --git a/src/commands/scan/handle-diff-scan.mts b/src/commands/scan/handle-diff-scan.mts index f33cff512..049480303 100644 --- a/src/commands/scan/handle-diff-scan.mts +++ b/src/commands/scan/handle-diff-scan.mts @@ -2,6 +2,7 @@ import { getDiffScanVerdict } from './diff-scan-verdict.mts' import { fetchDiffScan } from './fetch-diff-scan.mts' import { outputDiffScan } from './output-diff-scan.mts' +import type { NotificationMetadata } from './notifications/report.mts' import type { PythonDiffJsonContext } from './python-diff-json.mts' import type { OutputKind } from '../../types.mts' @@ -68,9 +69,7 @@ export async function handlePrDiffScan({ outputKind: OutputKind pythonJsonFormat?: boolean | undefined pythonJsonContext?: PythonDiffJsonContext | undefined - notificationContext?: - | { repository?: string | undefined; branch?: string | undefined } - | undefined + notificationContext?: NotificationMetadata | undefined }): Promise { const result = await fetchDiffScan({ id1, id2, orgSlug }) await outputDiffScan(result, { diff --git a/src/commands/scan/notifications/report.mts b/src/commands/scan/notifications/report.mts index 400d94751..371457ffc 100644 --- a/src/commands/scan/notifications/report.mts +++ b/src/commands/scan/notifications/report.mts @@ -1,3 +1,5 @@ +import { createPurlObject } from '../../../utils/purl.mts' + import type { SocketArtifact } from '../../../utils/alert/artifact.mts' import type { PythonDiffJson } from '../python-diff-json.mts' @@ -13,6 +15,14 @@ export type NotificationFinding = { purl?: string | undefined introducedBy?: Array<[string, string]> | undefined manifests?: string | undefined + reachability?: + | 'reachable' + | 'potentially reachable' + | 'unreachable' + | 'unclassified' + | undefined + reachabilityTrace?: string | undefined + originalSeverity?: string | undefined } export type NotificationReport = { @@ -23,13 +33,18 @@ export type NotificationReport = { branch?: string | undefined scanUrl?: string | undefined decision: 'pass' | 'fail' | 'unknown' | 'not-evaluated' + reachabilityEnabled?: boolean | undefined summary: string + reachabilitySummary?: string | undefined findings: NotificationFinding[] + reachabilityFindings?: NotificationFinding[] | undefined } export type NotificationMetadata = { repository?: string | undefined branch?: string | undefined + reachabilityEnabled?: boolean | undefined + reachabilityFacts?: unknown } export type NotificationContext = NotificationMetadata & { @@ -55,6 +70,13 @@ function findingsFromArtifacts( for (const artifact of artifacts) { for (const alert of artifact.alerts ?? []) { const props = alert.props ?? {} + const packagePurl = createPurlObject({ + type: artifact.type, + namespace: artifact.namespace, + name: artifact.name, + version: artifact.version, + throws: false, + })?.toString() findings.push({ packageName: artifact.name ?? 'unknown', ecosystem: artifact.type ?? 'unknown', @@ -62,6 +84,7 @@ function findingsFromArtifacts( alertType: alert.type ?? 'unknown', severity: alert.severity ?? 'unknown', action: alert.action ?? 'unknown', + purl: typeof props['purl'] === 'string' ? props['purl'] : packagePurl, url: typeof props['url'] === 'string' ? props['url'] : undefined, advisoryId: advisoryId(props), }) @@ -70,6 +93,286 @@ function findingsFromArtifacts( return findings } +function asRecord(value: unknown): Record | undefined { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : undefined +} + +function normalizePurl(value: string): string { + return value.trim().toLowerCase().replace(/^pkg:/, '').replaceAll('%40', '@') +} + +function normalizedAdvisory(value: unknown): string | undefined { + return typeof value === 'string' && value.trim() + ? value.trim().toUpperCase() + : undefined +} + +function componentPurl(component: Record): string | undefined { + const type = + typeof component['type'] === 'string' ? component['type'] : undefined + const name = + typeof component['name'] === 'string' + ? component['name'] + : typeof component['id'] === 'string' + ? component['id'] + : undefined + if (!type || !name) { + return undefined + } + const namespace = + typeof component['namespace'] === 'string' + ? component['namespace'].replaceAll('@', '%40') + : '' + const version = + typeof component['version'] === 'string' ? component['version'] : '' + return `pkg:${type}/${namespace ? `${namespace}/` : ''}${name}${version ? `@${version}` : ''}` +} + +function reachabilityState( + value: unknown, + undeterminable: boolean, +): NonNullable { + if (undeterminable) { + return 'potentially reachable' + } + if (typeof value !== 'string') { + return 'unclassified' + } + switch ( + value.trim().toLowerCase().replaceAll('-', '_').replaceAll(' ', '_') + ) { + case 'reachable': + return 'reachable' + case 'unreachable': + return 'unreachable' + case 'unknown': + case 'error': + case 'maybe_reachable': + case 'potentially_reachable': + return 'potentially reachable' + default: + return 'unclassified' + } +} + +function factsSeverity( + value: unknown, + state: NotificationFinding['reachability'], +): string { + if (state === 'reachable') { + return 'critical' + } + if (state === 'potentially reachable') { + return 'high' + } + if (state === 'unreachable') { + return 'low' + } + if (typeof value === 'number' && Number.isFinite(value)) { + if (value >= 9) { + return 'critical' + } + if (value >= 7) { + return 'high' + } + if (value >= 4) { + return 'medium' + } + return 'low' + } + if (typeof value === 'string') { + const severity = value.trim().toLowerCase() + if (severity === 'middle') { + return 'medium' + } + return ['critical', 'high', 'medium', 'low'].includes(severity) + ? severity + : 'unknown' + } + return 'unknown' +} + +function reachabilityTrace(value: unknown): string | undefined { + if (typeof value === 'string') { + return value.slice(0, 500) || undefined + } + if (!Array.isArray(value)) { + return undefined + } + const lines: string[] = [] + for (const group of value) { + if (!Array.isArray(group)) { + continue + } + for (const [index, rawFrame] of group.entries()) { + const frame = asRecord(rawFrame) + if (!frame) { + continue + } + const source = asRecord(frame['sourceLocation']) + const start = asRecord(source?.['start']) + const file = + typeof source?.['filename'] === 'string' ? source['filename'] : '' + const pkg = typeof frame['package'] === 'string' ? frame['package'] : '' + const line = + typeof start?.['line'] === 'number' ? start['line'] : undefined + const label = index === 0 ? file : pkg || file + if (label) { + lines.push(`${index ? '→ ' : ''}${label}${line ? `:${line}` : ''}`) + } + if (lines.join('\n').length >= 500) { + return `${lines.join('\n').slice(0, 497)}...` + } + } + } + return lines.length ? lines.join('\n') : undefined +} + +function applyReachabilityFacts( + findings: NotificationFinding[], + facts: unknown, + enabled: boolean | undefined, +): { + findings: NotificationFinding[] + reachabilityFindings: NotificationFinding[] +} { + if (!enabled) { + return { findings, reachabilityFindings: [] } + } + const output: NotificationFinding[] = findings.map(finding => ({ + ...finding, + reachability: 'unclassified' as const, + })) + const root = asRecord(facts) + const components = root?.['components'] + if (!Array.isArray(components)) { + return { findings: output, reachabilityFindings: [] } + } + const byIdentity = new Map< + string, + { + state: NonNullable + trace?: string | undefined + } + >() + const factsOnly = new Map() + for (const rawComponent of components) { + const component = asRecord(rawComponent) + const purl = component && componentPurl(component) + const vulnerabilities = component?.['vulnerabilities'] + if (!purl || !Array.isArray(vulnerabilities)) { + continue + } + const normalizedPackage = normalizePurl(purl) + const reachEntries = Array.isArray(component['reachability']) + ? component['reachability'] + : [] + for (const rawVulnerability of vulnerabilities) { + const vulnerability = asRecord(rawVulnerability) + if (!vulnerability) { + continue + } + const advisory = + normalizedAdvisory(vulnerability['ghsaId']) ?? + normalizedAdvisory(vulnerability['cveId']) + if (!advisory) { + continue + } + const entry = reachEntries + .map(asRecord) + .find( + item => + normalizedAdvisory(item?.['ghsa_id']) === advisory || + normalizedAdvisory(item?.['cve_id']) === advisory, + ) + const reachItems = Array.isArray(entry?.['reachability']) + ? entry['reachability'] + : [] + const applicable = reachItems + .map(asRecord) + .filter(item => item?.['type'] !== 'not_applicable') + if (reachItems.length && !applicable.length) { + continue + } + const reachData = asRecord(vulnerability['reachabilityData']) + const states = applicable.map(item => ({ + state: reachabilityState(item?.['type'], false), + trace: reachabilityTrace(item?.['matches']), + })) + const reachable = states.find(item => item.state === 'reachable') + const state = + reachable?.state ?? + (reachData?.['undeterminableReachability'] === true || + states.some(item => item.state === 'potentially reachable') + ? 'potentially reachable' + : states.length && states.every(item => item.state === 'unreachable') + ? 'unreachable' + : 'unclassified') + const trace = reachable?.trace + const identity = `${normalizedPackage}\0${advisory}` + byIdentity.set(identity, { state, trace }) + const originalSeverity = factsSeverity( + vulnerability['severity'], + 'unclassified', + ) + factsOnly.set(identity, { + packageName: + typeof component['name'] === 'string' + ? component['name'] + : String(component['id'] ?? 'unknown'), + ecosystem: String(component['type']), + version: + typeof component['version'] === 'string' + ? component['version'] + : 'unknown', + alertType: 'vulnerability', + severity: factsSeverity(vulnerability['severity'], state), + originalSeverity, + action: 'reachability', + advisoryId: advisory, + purl, + reachability: state, + reachabilityTrace: trace, + url: + typeof vulnerability['url'] === 'string' + ? vulnerability['url'] + : undefined, + }) + } + } + for (const finding of output) { + const packagePurl = finding.purl ? normalizePurl(finding.purl) : undefined + if (!packagePurl) { + continue + } + for (const id of finding.advisoryId?.split(',') ?? []) { + const identity = `${packagePurl}\0${normalizedAdvisory(id)}` + const matched = byIdentity.get(identity) + if (matched) { + finding.reachability = matched.state + finding.reachabilityTrace = matched.trace + factsOnly.delete(identity) + break + } + } + } + const reachabilityFindings = Array.from(factsOnly.values()) + return { findings: output, reachabilityFindings } +} + +export function summarizeReachability( + findings: NotificationFinding[], +): string | undefined { + if (!findings.length) { + return undefined + } + const count = (state: NotificationFinding['reachability']) => + findings.filter(finding => finding.reachability === state).length + return `${findings.length} reachability findings (${count('reachable')} reachable, ${count('potentially reachable')} potentially reachable, ${count('unreachable')} unreachable, ${count('unclassified')} unclassified)` +} + export function summarize(findings: NotificationFinding[]): string { const blocking = findings.filter(finding => finding.action === 'error').length const warning = findings.filter(finding => finding.action === 'warn').length @@ -83,7 +386,11 @@ export function createScanNotificationReport( scanUrl?: string | undefined }, ): NotificationReport { - const findings = findingsFromArtifacts(scan) + const reachability = applyReachabilityFacts( + findingsFromArtifacts(scan), + context.reachabilityFacts, + context.reachabilityEnabled, + ) return { kind: 'scan', scanId: context.scanId, @@ -91,8 +398,13 @@ export function createScanNotificationReport( branch: context.branch, scanUrl: context.scanUrl, decision: context.decision, - summary: summarize(findings), - findings, + reachabilityEnabled: context.reachabilityEnabled ?? false, + summary: summarize(reachability.findings), + reachabilitySummary: summarizeReachability( + reachability.reachabilityFindings, + ), + findings: reachability.findings, + reachabilityFindings: reachability.reachabilityFindings, } } @@ -113,6 +425,11 @@ export function createDiffNotificationReport( introducedBy: alert.introduced_by, manifests: alert.manifests, })) + const reachability = applyReachabilityFacts( + findings, + context.reachabilityFacts, + context.reachabilityEnabled, + ) return { kind: 'diff', scanId: result.head_scan_id ?? undefined, @@ -121,7 +438,12 @@ export function createDiffNotificationReport( branch: result.branch ?? context.branch, scanUrl: result.diff_url ?? result.report_url ?? undefined, decision: result.decision, - summary: summarize(findings), - findings, + reachabilityEnabled: context.reachabilityEnabled ?? false, + summary: summarize(reachability.findings), + reachabilitySummary: summarizeReachability( + reachability.reachabilityFindings, + ), + findings: reachability.findings, + reachabilityFindings: reachability.reachabilityFindings, } } diff --git a/src/commands/scan/notifications/report.test.mts b/src/commands/scan/notifications/report.test.mts new file mode 100644 index 000000000..1ec61da8d --- /dev/null +++ b/src/commands/scan/notifications/report.test.mts @@ -0,0 +1,194 @@ +import { describe, expect, it } from 'vitest' + +import { createDiffNotificationReport } from './report.mts' + +describe('notification reachability', () => { + it('attaches reachable, potentially reachable, and unreachable states by package and advisory', () => { + const report = createDiffNotificationReport( + { + new_alerts: [ + ['left-pad', 'GHSA-AAAA', 'npm/left-pad@1.0.0'], + ['maybe-lib', 'GHSA-BBBB', 'pkg:npm/maybe-lib@2.0.0'], + ['old-lib', 'CVE-2024-0001', 'pkg:npm/old-lib@3.0.0'], + ].map(([pkg, advisoryId, purl]) => ({ + pkg_name: pkg, + pkg_type: 'npm', + pkg_version: '1.0.0', + type: 'cve', + severity: 'high', + action: 'error', + purl, + props: { ghsaId: advisoryId }, + introduced_by: [], + manifests: 'package-lock.json', + url: null, + })), + decision: 'fail', + head_scan_id: 'head', + diff_scan_id: 'diff', + diff_url: 'https://socket.dev/report', + repo: 'api', + branch: 'feature', + } as never, + { + repository: 'api', + branch: 'feature', + decision: 'fail', + reachabilityEnabled: true, + reachabilityFacts: { + components: [ + { + type: 'npm', + name: 'left-pad', + version: '1.0.0', + vulnerabilities: [{ ghsaId: 'GHSA-AAAA' }], + reachability: [ + { + ghsa_id: 'GHSA-AAAA', + reachability: [ + { + type: 'not_applicable', + }, + { type: 'unreachable' }, + { + type: 'reachable', + matches: [ + [ + { + package: 'app', + sourceLocation: { + filename: 'src/index.js', + start: { line: 7 }, + }, + }, + { package: 'left-pad' }, + ], + ], + }, + ], + }, + ], + }, + { + type: 'npm', + name: 'maybe-lib', + version: '2.0.0', + vulnerabilities: [ + { + ghsaId: 'GHSA-BBBB', + reachabilityData: { undeterminableReachability: true }, + }, + ], + reachability: [], + }, + { + type: 'npm', + name: 'old-lib', + version: '3.0.0', + vulnerabilities: [{ cveId: 'CVE-2024-0001' }], + reachability: [ + { + cve_id: 'CVE-2024-0001', + reachability: [{ type: 'unreachable' }], + }, + ], + }, + ], + }, + }, + ) + + expect(report.findings.map(finding => finding.reachability)).toEqual([ + 'reachable', + 'potentially reachable', + 'unreachable', + ]) + expect(report.findings[0]?.reachabilityTrace).toContain('src/index.js:7') + expect(report.reachabilityFindings).toEqual([]) + expect(report.scanUrl).toBe('https://socket.dev/report') + }) + + it('keeps missing or malformed facts unclassified instead of confirming reachability', () => { + const report = createDiffNotificationReport( + { + new_alerts: [ + { + pkg_name: 'left-pad', + pkg_type: 'npm', + pkg_version: '1.0.0', + type: 'cve', + severity: 'high', + action: 'error', + purl: 'pkg:npm/left-pad@1.0.0', + props: { ghsaId: 'GHSA-AAAA' }, + introduced_by: [], + manifests: '', + url: null, + }, + ], + decision: 'fail', + head_scan_id: 'head', + diff_scan_id: 'diff', + } as never, + { + decision: 'fail', + reachabilityEnabled: true, + reachabilityFacts: { components: 'invalid' }, + }, + ) + + expect(report.findings[0]?.reachability).toBe('unclassified') + }) + + it('creates facts-only findings when no matching diff alert exists and keeps CVEs distinct', () => { + const report = createDiffNotificationReport( + { + new_alerts: [], + decision: 'pass', + head_scan_id: 'head', + diff_scan_id: 'diff', + diff_url: 'https://socket.dev/report', + } as never, + { + decision: 'pass', + reachabilityEnabled: true, + reachabilityFacts: { + components: [ + { + type: 'npm', + name: 'shared-package', + version: '1.0.0', + vulnerabilities: [ + { ghsaId: 'GHSA-REACH', severity: 'medium' }, + { cveId: 'CVE-2025-0001', severity: 'high' }, + ], + reachability: [ + { + ghsa_id: 'GHSA-REACH', + reachability: [{ type: 'reachable' }], + }, + { + cve_id: 'CVE-2025-0001', + reachability: [{ type: 'unreachable' }], + }, + ], + }, + ], + }, + }, + ) + + expect(report.findings).toEqual([]) + expect( + report.reachabilityFindings?.map(finding => [ + finding.advisoryId, + finding.reachability, + finding.severity, + ]), + ).toEqual([ + ['GHSA-REACH', 'reachable', 'critical'], + ['CVE-2025-0001', 'unreachable', 'low'], + ]) + expect(report.reachabilitySummary).toContain('2 reachability findings') + }) +}) diff --git a/src/commands/scan/notifications/slack-bot.mts b/src/commands/scan/notifications/slack-bot.mts index 3f2b66ef9..6b85b58a9 100644 --- a/src/commands/scan/notifications/slack-bot.mts +++ b/src/commands/scan/notifications/slack-bot.mts @@ -1,5 +1,6 @@ import { filterSlackFindings, + filterSlackReachabilityFindings, formatSlackMessage, getAllowedSlackActions, getSlackNotificationConfig, @@ -97,11 +98,10 @@ export async function sendSlackBotNotifications( } const allowedActions = getAllowedSlackActions() for (const destination of destinations) { - const findings = filterSlackFindings( - report, - destination.filter ?? {}, - allowedActions, - ) + const findings = [ + ...filterSlackFindings(report, destination.filter ?? {}, allowedActions), + ...filterSlackReachabilityFindings(report, destination.filter ?? {}), + ] if (!findings.length) { continue } diff --git a/src/commands/scan/notifications/slack-bot.test.mts b/src/commands/scan/notifications/slack-bot.test.mts index b7819914a..b5f9f0d0d 100644 --- a/src/commands/scan/notifications/slack-bot.test.mts +++ b/src/commands/scan/notifications/slack-bot.test.mts @@ -11,6 +11,7 @@ const report: NotificationReport = { kind: 'diff', repository: 'example', branch: 'feature', + reachabilityEnabled: true, decision: 'fail', summary: '2 findings (1 blocking, 1 warning)', findings: [ @@ -22,6 +23,8 @@ const report: NotificationReport = { severity: 'high', action: 'error', advisoryId: 'GHSA-1234', + reachability: 'reachable', + reachabilityTrace: 'src/index.js:7', }, { packageName: 'safe-lib', @@ -30,6 +33,7 @@ const report: NotificationReport = { alertType: 'license', severity: 'low', action: 'warn', + reachability: 'unreachable', }, ], } @@ -47,7 +51,12 @@ describe('Slack bot notifications', () => { 'SOCKET_SLACK_CONFIG_JSON', JSON.stringify({ bot_configs: [ - { name: 'security', channels: ['C123456'], alert_types: ['cve'] }, + { + name: 'security', + channels: ['C123456'], + alert_types: ['cve'], + reachability_alerts_only: true, + }, ], }), ) @@ -73,6 +82,8 @@ describe('Slack bot notifications', () => { expect(JSON.stringify(payload)).toContain('GHSA-1234') expect(JSON.stringify(payload)).not.toContain('safe-lib') expect(JSON.stringify(payload)).not.toContain(token) + expect(JSON.stringify(payload)).toContain('Reachability: reachable') + expect(JSON.stringify(payload)).toContain('src/index.js:7') }) it('checks the Slack JSON ok flag even when HTTP status is successful', async () => { @@ -92,6 +103,59 @@ describe('Slack bot notifications', () => { expect(post).toHaveBeenCalledOnce() }) + it('sends reachability facts even when there are no matching diff alerts', async () => { + vi.stubEnv('SOCKET_SLACK_BOT_TOKEN', 'xoxb-fake-token') + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ + bot_configs: [{ channels: ['C123456'], severities: ['critical'] }], + }), + ) + const post = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ ok: true }), + }) + vi.mocked(apiFetch).mockImplementation(post) + const factsOnlyReport: NotificationReport = { + ...report, + findings: [], + summary: '0 findings (0 blocking, 0 warning)', + reachabilitySummary: + '2 reachability findings (1 reachable, 0 potentially reachable, 1 unreachable, 0 unclassified)', + reachabilityFindings: [ + { + packageName: 'shared-package', + ecosystem: 'npm', + version: '1.0.0', + alertType: 'vulnerability', + severity: 'critical', + action: 'reachability', + advisoryId: 'GHSA-REACH', + reachability: 'reachable', + }, + { + packageName: 'shared-package', + ecosystem: 'npm', + version: '1.0.0', + alertType: 'vulnerability', + severity: 'low', + action: 'reachability', + advisoryId: 'CVE-2025-0001', + reachability: 'unreachable', + }, + ], + } + + await sendSlackBotNotifications(factsOnlyReport) + + expect(post).toHaveBeenCalledOnce() + const body = JSON.parse(String(post.mock.calls[0]?.[1]?.body)) + expect(JSON.stringify(body)).toContain('GHSA-REACH') + expect(JSON.stringify(body)).not.toContain('CVE-2025-0001') + expect(JSON.stringify(body)).toContain('1 reachable') + }) + it('reports HTTP rate limits and returns without retrying or throwing', async () => { vi.stubEnv('SOCKET_SLACK_BOT_TOKEN', 'xoxb-fake-token') vi.stubEnv( diff --git a/src/commands/scan/notifications/slack-webhook.mts b/src/commands/scan/notifications/slack-webhook.mts index 2376b77ed..7aca92d91 100644 --- a/src/commands/scan/notifications/slack-webhook.mts +++ b/src/commands/scan/notifications/slack-webhook.mts @@ -1,4 +1,4 @@ -import { summarize } from './report.mts' +import { summarize, summarizeReachability } from './report.mts' import { apiFetch } from '../../../utils/api.mts' import { logger } from '../../../utils/logger.mts' @@ -9,6 +9,7 @@ export type DestinationFilter = { repos?: string[] alert_types?: string[] severities?: string[] + reachability_alerts_only?: boolean } export type SlackBlock = | { type: 'section'; text: { type: 'mrkdwn'; text: string } } @@ -95,6 +96,12 @@ export function safeSlackFilter(value: unknown): DestinationFilter | undefined { } result[key] = candidate as string[] } + if (source['reachability_alerts_only'] !== undefined) { + if (typeof source['reachability_alerts_only'] !== 'boolean') { + return undefined + } + result.reachability_alerts_only = source['reachability_alerts_only'] + } return result } @@ -132,6 +139,13 @@ function matches( ) { return false } + if ( + filter.reachability_alerts_only && + report.reachabilityEnabled && + finding.reachability !== 'reachable' + ) { + return false + } if (filter.alert_types?.length) { return filter.alert_types.includes(finding.alertType) } @@ -168,6 +182,15 @@ export function filterSlackFindings( ) } +export function filterSlackReachabilityFindings( + report: NotificationReport, + filter: DestinationFilter, +): NotificationFinding[] { + return (report.reachabilityFindings ?? []).filter(finding => + matches(finding, report, filter), + ) +} + export function formatSlackMessage( report: NotificationReport, findings: NotificationFinding[], @@ -176,7 +199,13 @@ export function formatSlackMessage( report.decision === 'fail' ? 'Socket security issues were found' : 'Socket scan completed' - const summary = summarize(findings) + const factsOnly = new Set(report.reachabilityFindings) + const summary = [ + summarize(findings.filter(item => !factsOnly.has(item))), + summarizeReachability(findings.filter(item => factsOnly.has(item))), + ] + .filter(Boolean) + .join(' · ') const blocks: SlackBlock[] = [ { type: 'section', @@ -214,7 +243,14 @@ export function formatSlackMessage( const manifests = finding.manifests ? ` · Manifest ${escapeMrkdwn(finding.manifests)}` : '' - const line = `• *${escapeMrkdwn(finding.severity)}* ${link} · ${escapeMrkdwn(finding.alertType)}${advisory} · ${escapeMrkdwn(finding.action)}${source}${manifests}` + const reachability = finding.reachability + ? ` · Reachability: ${escapeMrkdwn(finding.reachability)}` + : '' + const trace = + finding.reachability === 'reachable' && finding.reachabilityTrace + ? `\n\`${escapeMrkdwn(finding.reachabilityTrace).slice(0, 500)}\`` + : '' + const line = `• *${escapeMrkdwn(finding.severity)}* ${link} · ${escapeMrkdwn(finding.alertType)}${advisory} · ${escapeMrkdwn(finding.action)}${reachability}${source}${manifests}${trace}` blocks.push({ type: 'section', text: { type: 'mrkdwn', text: line.slice(0, MAX_TEXT_LENGTH) }, @@ -296,7 +332,10 @@ export async function sendSlackWebhookNotifications( ) continue } - const findings = filterSlackFindings(report, filter, allowedActions) + const findings = [ + ...filterSlackFindings(report, filter, allowedActions), + ...filterSlackReachabilityFindings(report, filter), + ] if (!findings.length) { continue } diff --git a/src/commands/scan/notifications/slack-webhook.test.mts b/src/commands/scan/notifications/slack-webhook.test.mts index 9e9c35908..52057d680 100644 --- a/src/commands/scan/notifications/slack-webhook.test.mts +++ b/src/commands/scan/notifications/slack-webhook.test.mts @@ -14,6 +14,7 @@ const report: NotificationReport = { kind: 'diff', repository: 'example', branch: 'feature', + reachabilityEnabled: true, decision: 'fail', summary: '2 findings (1 blocking, 1 warning)', findings: [ @@ -25,6 +26,8 @@ const report: NotificationReport = { severity: 'high', action: 'error', advisoryId: 'GHSA-1234', + reachability: 'reachable', + reachabilityTrace: 'src/index.js:7', }, { packageName: 'safe-lib', @@ -33,6 +36,7 @@ const report: NotificationReport = { alertType: 'license', severity: 'low', action: 'warn', + reachability: 'unreachable', }, ], } @@ -57,7 +61,13 @@ describe('Slack webhook notifications', () => { 'SOCKET_SLACK_CONFIG_JSON', JSON.stringify({ url: [{ name: 'security', url: secretUrl }], - url_configs: { security: { repos: ['example'], alert_types: ['cve'] } }, + url_configs: { + security: { + repos: ['example'], + alert_types: ['cve'], + reachability_alerts_only: true, + }, + }, }), ) const fetch = vi.fn().mockResolvedValue({ ok: false, status: 302 }) @@ -78,6 +88,8 @@ describe('Slack webhook notifications', () => { .join('\n'), ).toContain('GHSA-1234') expect(JSON.stringify(options.body)).not.toContain('safe-lib') + expect(JSON.stringify(options.body)).toContain('Reachability: reachable') + expect(JSON.stringify(options.body)).toContain('src/index.js:7') }) it('does not post when severity filters exclude every finding', async () => { @@ -96,6 +108,55 @@ describe('Slack webhook notifications', () => { expect(fetch).not.toHaveBeenCalled() }) + it('sends reachability facts when there are no matching diff alerts', 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().mockResolvedValue({ ok: true, status: 200 }) + vi.mocked(apiFetch).mockImplementation(fetch) + const factsOnlyReport: NotificationReport = { + ...report, + findings: [], + summary: '0 findings (0 blocking, 0 warning)', + reachabilitySummary: + '2 reachability findings (1 reachable, 0 potentially reachable, 1 unreachable, 0 unclassified)', + reachabilityFindings: [ + { + packageName: 'shared-package', + ecosystem: 'npm', + version: '1.0.0', + alertType: 'vulnerability', + severity: 'critical', + action: 'reachability', + advisoryId: 'GHSA-REACH', + reachability: 'reachable', + }, + { + packageName: 'shared-package', + ecosystem: 'npm', + version: '1.0.0', + alertType: 'vulnerability', + severity: 'low', + action: 'reachability', + advisoryId: 'CVE-2025-0001', + reachability: 'unreachable', + }, + ], + } + + await sendSlackWebhookNotifications(factsOnlyReport) + + expect(fetch).toHaveBeenCalledOnce() + const body = JSON.stringify(fetch.mock.calls[0]?.[1]?.body) + expect(body).toContain('GHSA-REACH') + expect(body).not.toContain('CVE-2025-0001') + expect(body).toContain('1 reachable') + }) + it('skips malformed filters instead of interrupting scan output', async () => { vi.stubEnv( 'SOCKET_SLACK_CONFIG_JSON',