Repository navigation
feat(python-cli-parity): send scan notifications to Slack bot channels #1834
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
John-David Dalton (jdalton)
wants to merge
1
commit into
parity/2241-notification-foundation
from
parity/2243-slack-bot
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<typeof safeSlackFilter> | ||
| } | ||
|
|
||
| function botDestinations(config: Record<string, unknown>): 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<string, unknown> | ||
| 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<string, unknown> | ||
| | null | ||
| | undefined = getSlackNotificationConfig(), | ||
| ): Promise<void> { | ||
| 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, | ||
| }) | ||
|
jdalton marked this conversation as resolved.
Resolved
|
||
| 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.`, | ||
| ) | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<Parameters<typeof apiFetch>[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() | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.