From c24b576c838b78a5a131bc1524f9b2cece6e8548 Mon Sep 17 00:00:00 2001 From: jdalton Date: Fri, 4 Dec 2026 01:15:56 -0500 Subject: [PATCH] feat(python-cli-parity): send scan notifications to Slack bot channels --- .gitignore | 2 + docs/commands/scan/report.md | 15 ++ src/commands/scan/notifications/slack-bot.mts | 154 ++++++++++++++++++ .../scan/notifications/slack-bot.test.mts | 120 ++++++++++++++ .../scan/notifications/slack-webhook.mts | 77 ++++++--- src/commands/scan/output-diff-scan.mts | 74 +++++---- src/commands/scan/output-scan-report.mts | 23 +-- 7 files changed, 395 insertions(+), 70 deletions(-) create mode 100644 src/commands/scan/notifications/slack-bot.mts create mode 100644 src/commands/scan/notifications/slack-bot.test.mts diff --git a/.gitignore b/.gitignore index 826c23bcd..a513f6739 100644 --- a/.gitignore +++ b/.gitignore @@ -892,6 +892,8 @@ !/src/commands/scan/diff-scan-verdict.test.mts !/src/commands/scan/notifications/ !/src/commands/scan/notifications/report.mts +!/src/commands/scan/notifications/slack-bot.mts +!/src/commands/scan/notifications/slack-bot.test.mts !/src/commands/scan/notifications/slack-webhook.mts !/src/commands/scan/notifications/slack-webhook.test.mts !/src/commands/ci/publish-gitlab-mr-notes.mts diff --git a/docs/commands/scan/report.md b/docs/commands/scan/report.md index f3e5904c6..d26c6b32f 100644 --- a/docs/commands/scan/report.md +++ b/docs/commands/scan/report.md @@ -66,3 +66,18 @@ filters: `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. + +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 +token in CI secret storage: + +```sh +export SOCKET_SLACK_BOT_TOKEN="$SLACK_BOT_TOKEN" +export SOCKET_SLACK_CONFIG_JSON='{"bot_configs":[{"name":"security","channels":["C0123456789"],"repos":["api"],"alert_types":["cve"]}]}' +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. diff --git a/src/commands/scan/notifications/slack-bot.mts b/src/commands/scan/notifications/slack-bot.mts new file mode 100644 index 000000000..3f2b66ef9 --- /dev/null +++ b/src/commands/scan/notifications/slack-bot.mts @@ -0,0 +1,154 @@ +import { + filterSlackFindings, + formatSlackMessage, + getAllowedSlackActions, + getSlackNotificationConfig, + safeSlackFilter, +} from './slack-webhook.mts' +import { apiFetch } from '../../../utils/api.mts' +import { logger } from '../../../utils/logger.mts' + +import type { NotificationReport } from './report.mts' + +const SLACK_POST_MESSAGE_URL = 'https://slack.com/api/chat.postMessage' +const REQUEST_TIMEOUT_MS = 10_000 + +type BotDestination = { + name: string + channels: string[] + filter: ReturnType +} + +function botDestinations(config: Record): BotDestination[] { + const input = config['bot_configs'] + if (!Array.isArray(input)) { + if (input !== undefined) { + logger.warn('Slack bot_configs must be an array; skipping bot delivery.') + } + return [] + } + return input.flatMap((item, index) => { + if (!item || typeof item !== 'object' || Array.isArray(item)) { + logger.warn( + `Slack bot configuration ${index + 1} is invalid; skipping it.`, + ) + return [] + } + const source = item as Record + const name = + typeof source['name'] === 'string' ? source['name'] : `bot_${index}` + const channels = source['channels'] + if ( + !Array.isArray(channels) || + channels.some(channel => typeof channel !== 'string') + ) { + logger.warn( + `Slack bot configuration "${name}" has invalid channels; skipping it.`, + ) + return [] + } + if (channels.length === 0) { + logger.warn( + `Slack bot configuration "${name}" has no channels; skipping it.`, + ) + return [] + } + const filter = safeSlackFilter(source) + if (!filter) { + logger.warn( + `Slack bot configuration "${name}" has an invalid filter; skipping it.`, + ) + return [] + } + return [{ name, channels, filter }] + }) +} + +/** Post selected scan findings to channels configured for a Slack bot. */ +export async function sendSlackBotNotifications( + report: NotificationReport, + config: + | Record + | null + | undefined = getSlackNotificationConfig(), +): Promise { + const token = process.env['SOCKET_SLACK_BOT_TOKEN'] + if (!token) { + return + } + if (!token.startsWith('xoxb-')) { + logger.warn( + 'SOCKET_SLACK_BOT_TOKEN must be a bot OAuth token beginning with xoxb-.', + ) + return + } + if (!config) { + if (!process.env['SOCKET_SLACK_CONFIG_JSON']) { + logger.warn('Slack bot delivery requires SOCKET_SLACK_CONFIG_JSON.') + } + return + } + const destinations = botDestinations(config) + if (!destinations.length) { + logger.warn( + 'No valid Slack bot destinations are configured; skipping delivery.', + ) + return + } + const allowedActions = getAllowedSlackActions() + for (const destination of destinations) { + const findings = filterSlackFindings( + report, + destination.filter ?? {}, + allowedActions, + ) + if (!findings.length) { + continue + } + const message = formatSlackMessage(report, findings) + for (const channel of destination.channels) { + if (!channel.trim() || channel.length > 80 || /[\r\n]/u.test(channel)) { + logger.warn( + `Slack bot destination "${destination.name}" contains an invalid channel; skipping it.`, + ) + continue + } + try { + // Slack's fixed endpoint and manual redirect policy prevent sending the bot token elsewhere. + // eslint-disable-next-line no-await-in-loop + const response = await apiFetch(SLACK_POST_MESSAGE_URL, { + method: 'POST', + headers: { + authorization: `Bearer ${token}`, + 'content-type': 'application/json; charset=utf-8', + }, + body: JSON.stringify({ channel, ...message }), + rejectRedirects: true, + timeout: REQUEST_TIMEOUT_MS, + }) + if (!response.ok) { + logger.warn( + `Slack bot delivery to "${destination.name}" failed with HTTP ${response.status}; scan policy is unchanged.`, + ) + continue + } + // The body is one small Slack API acknowledgement, needed to check its `ok` field. + // eslint-disable-next-line no-await-in-loop + const responseData: unknown = await response.json() + if ( + !responseData || + typeof responseData !== 'object' || + (responseData as { ok?: unknown }).ok !== true + ) { + logger.warn( + `Slack bot delivery to "${destination.name}" was rejected by Slack; scan policy is unchanged.`, + ) + } + } catch { + logger.warn( + `Slack bot delivery to "${destination.name}" failed; scan policy is unchanged.`, + ) + } + } + } +} diff --git a/src/commands/scan/notifications/slack-bot.test.mts b/src/commands/scan/notifications/slack-bot.test.mts new file mode 100644 index 000000000..b7819914a --- /dev/null +++ b/src/commands/scan/notifications/slack-bot.test.mts @@ -0,0 +1,120 @@ +import { apiFetch } from '../../../utils/api.mts' + +vi.mock('../../../utils/api.mts', () => ({ apiFetch: vi.fn() })) +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { sendSlackBotNotifications } from './slack-bot.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 bot notifications', () => { + it('posts filtered findings to configured channels with fixed API auth', async () => { + const token = 'xoxb-fake-token' + vi.stubEnv('SOCKET_SLACK_BOT_TOKEN', token) + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ + bot_configs: [ + { name: 'security', channels: ['C123456'], alert_types: ['cve'] }, + ], + }), + ) + const post = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ ok: true }), + }) + vi.mocked(apiFetch).mockImplementation(post) + + await sendSlackBotNotifications(report) + + expect(post).toHaveBeenCalledOnce() + const [url, options] = post.mock.calls[0] as [ + string, + NonNullable[1]>, + ] + expect(url).toBe('https://slack.com/api/chat.postMessage') + expect(options?.rejectRedirects).toBe(true) + expect(options?.headers).toMatchObject({ authorization: `Bearer ${token}` }) + const payload = JSON.parse(String(options?.body)) + expect(payload.channel).toBe('C123456') + expect(JSON.stringify(payload)).toContain('GHSA-1234') + expect(JSON.stringify(payload)).not.toContain('safe-lib') + expect(JSON.stringify(payload)).not.toContain(token) + }) + + it('checks the Slack JSON ok flag even when HTTP status is successful', async () => { + vi.stubEnv('SOCKET_SLACK_BOT_TOKEN', 'xoxb-fake-token') + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ bot_configs: [{ channels: ['C123456'] }] }), + ) + const post = vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ ok: false, error: 'channel_not_found' }), + }) + vi.mocked(apiFetch).mockImplementation(post) + + await expect(sendSlackBotNotifications(report)).resolves.toBeUndefined() + expect(post).toHaveBeenCalledOnce() + }) + + it('reports HTTP rate limits and returns without retrying or throwing', async () => { + vi.stubEnv('SOCKET_SLACK_BOT_TOKEN', 'xoxb-fake-token') + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ bot_configs: [{ channels: ['C123456'] }] }), + ) + const post = vi.fn().mockResolvedValue({ ok: false, status: 429 }) + vi.mocked(apiFetch).mockImplementation(post) + + await expect(sendSlackBotNotifications(report)).resolves.toBeUndefined() + expect(post).toHaveBeenCalledOnce() + }) + + it('does not send when the token has the wrong credential type', async () => { + vi.stubEnv('SOCKET_SLACK_BOT_TOKEN', 'xoxp-user-token') + vi.stubEnv( + 'SOCKET_SLACK_CONFIG_JSON', + JSON.stringify({ bot_configs: [{ channels: ['C123456'] }] }), + ) + const post = vi.fn() + vi.mocked(apiFetch).mockImplementation(post) + + await sendSlackBotNotifications(report) + expect(post).not.toHaveBeenCalled() + }) +}) diff --git a/src/commands/scan/notifications/slack-webhook.mts b/src/commands/scan/notifications/slack-webhook.mts index 6263d3bb5..2376b77ed 100644 --- a/src/commands/scan/notifications/slack-webhook.mts +++ b/src/commands/scan/notifications/slack-webhook.mts @@ -5,12 +5,12 @@ import { logger } from '../../../utils/logger.mts' import type { NotificationFinding, NotificationReport } from './report.mts' type Destination = { name: string; url: string } -type DestinationFilter = { +export type DestinationFilter = { repos?: string[] alert_types?: string[] severities?: string[] } -type SlackBlock = +export type SlackBlock = | { type: 'section'; text: { type: 'mrkdwn'; text: string } } | { type: 'context'; elements: [{ type: 'mrkdwn'; text: string }] } @@ -18,7 +18,9 @@ const MAX_FINDINGS = 40 const MAX_TEXT_LENGTH = 2800 const REQUEST_TIMEOUT_MS = 10_000 -function parseConfig(): Record | undefined { +export function getSlackNotificationConfig(): + | Record + | undefined { const raw = process.env['SOCKET_SLACK_CONFIG_JSON'] if (!raw) { return undefined @@ -28,6 +30,9 @@ function parseConfig(): Record | undefined { if (config && typeof config === 'object' && !Array.isArray(config)) { return config as Record } + logger.warn( + 'Slack notification configuration must be a JSON object; skipping delivery.', + ) } catch { logger.warn( 'Slack notification configuration is invalid JSON; skipping delivery.', @@ -40,6 +45,13 @@ export function isSlackWebhookConfigured(): boolean { return Boolean(process.env['SOCKET_SLACK_CONFIG_JSON']) } +export function isSlackNotificationConfigured(): boolean { + return Boolean( + process.env['SOCKET_SLACK_CONFIG_JSON'] || + process.env['SOCKET_SLACK_BOT_TOKEN'], + ) +} + function destinations(input: unknown): Destination[] { const items = Array.isArray(input) ? input : [input] return items.flatMap((item, index) => { @@ -64,7 +76,7 @@ function destinations(input: unknown): Destination[] { }) } -function safeFilter(value: unknown): DestinationFilter | undefined { +export function safeSlackFilter(value: unknown): DestinationFilter | undefined { if (!value || typeof value !== 'object' || Array.isArray(value)) { return undefined } @@ -132,10 +144,34 @@ function matches( return true } -function slackText( +export function getAllowedSlackActions(): Set { + const levels = (process.env['SOCKET_SLACK_LEVELS'] ?? 'block,warn') + .split(',') + .map(value => value.trim().toLowerCase()) + .filter(Boolean) + return new Set( + levels.flatMap(level => + level === 'block' ? ['error', 'block'] : level === 'warn' ? ['warn'] : [], + ), + ) +} + +export function filterSlackFindings( + report: NotificationReport, + filter: DestinationFilter, + allowedActions = getAllowedSlackActions(), +): NotificationFinding[] { + return report.findings.filter( + finding => + allowedActions.has(finding.action.toLowerCase()) && + matches(finding, report, filter), + ) +} + +export function formatSlackMessage( report: NotificationReport, findings: NotificationFinding[], -): string { +): { text: string; blocks: SlackBlock[] } { const title = report.decision === 'fail' ? 'Socket security issues were found' @@ -195,17 +231,20 @@ function slackText( ], }) } - return JSON.stringify({ + return { 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, + config: + | Record + | null + | undefined = getSlackNotificationConfig(), ): Promise { - const config = parseConfig() if (!config?.['url']) { return } @@ -222,15 +261,7 @@ export async function sendSlackWebhookNotifications( 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 allowedActions = getAllowedSlackActions() const configured = destinations(config['url']) if (!configured.length) { logger.warn( @@ -246,7 +277,7 @@ export async function sendSlackWebhookNotifications( ) continue } - const filter = rawFilter === undefined ? {} : safeFilter(rawFilter) + const filter = rawFilter === undefined ? {} : safeSlackFilter(rawFilter) if (!filter) { logger.warn( `Slack webhook destination "${destination.name}" has an invalid filter; skipping it.`, @@ -265,11 +296,7 @@ export async function sendSlackWebhookNotifications( ) continue } - const findings = report.findings.filter( - finding => - allowedActions.has(finding.action.toLowerCase()) && - matches(finding, report, filter), - ) + const findings = filterSlackFindings(report, filter, allowedActions) if (!findings.length) { continue } @@ -279,7 +306,7 @@ export async function sendSlackWebhookNotifications( const response = await apiFetch(target.href, { method: 'POST', headers: { 'content-type': 'application/json' }, - body: slackText(report, findings), + body: JSON.stringify(formatSlackMessage(report, findings)), rejectRedirects: true, timeout: REQUEST_TIMEOUT_MS, }) diff --git a/src/commands/scan/output-diff-scan.mts b/src/commands/scan/output-diff-scan.mts index c3d146a3a..75f678c67 100644 --- a/src/commands/scan/output-diff-scan.mts +++ b/src/commands/scan/output-diff-scan.mts @@ -5,8 +5,10 @@ import colors from 'yoctocolors-cjs' import { getDiffScanBlocking } from './diff-scan-verdict.mts' import { createDiffNotificationReport } from './notifications/report.mts' +import { sendSlackBotNotifications } from './notifications/slack-bot.mts' import { - isSlackWebhookConfigured, + getSlackNotificationConfig, + isSlackNotificationConfigured, sendSlackWebhookNotifications, } from './notifications/slack-webhook.mts' import { @@ -58,24 +60,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, - }, - ), + 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, + }, ) + const slackConfig = getSlackNotificationConfig() ?? null + await sendSlackWebhookNotifications(report, slackConfig) + await sendSlackBotNotifications(report, slackConfig) } await handlePythonJson(payload, file) return @@ -96,28 +99,29 @@ export async function outputDiffScan( if (getDiffScanBlocking(diffScan, strictBlocking)) { setCiExitCode('blocking') } - if (notificationContext && isSlackWebhookConfigured()) { + if (notificationContext && isSlackNotificationConfigured()) { 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 report = 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 d5d7dc0cf..8d357c427 100644 --- a/src/commands/scan/output-scan-report.mts +++ b/src/commands/scan/output-scan-report.mts @@ -4,8 +4,10 @@ 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 { sendSlackBotNotifications } from './notifications/slack-bot.mts' import { - isSlackWebhookConfigured, + getSlackNotificationConfig, + isSlackNotificationConfigured, sendSlackWebhookNotifications, } from './notifications/slack-webhook.mts' import constants, { @@ -201,15 +203,16 @@ 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', - }), - ) + 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) } // I don't think we emit the default error message with banner for an unhealthy report, do we?