Skip to content

Commit cece0b7

Browse files
committed
feat(python-cli-parity): send scan notifications to Slack bot channels
1 parent a3ea3f7 commit cece0b7

7 files changed

Lines changed: 395 additions & 70 deletions

File tree

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,8 @@
892892
!/src/commands/scan/diff-scan-verdict.test.mts
893893
!/src/commands/scan/notifications/
894894
!/src/commands/scan/notifications/report.mts
895+
!/src/commands/scan/notifications/slack-bot.mts
896+
!/src/commands/scan/notifications/slack-bot.test.mts
895897
!/src/commands/scan/notifications/slack-webhook.mts
896898
!/src/commands/scan/notifications/slack-webhook.test.mts
897899
!/src/commands/ci/publish-gitlab-mr-notes.mts

‎docs/commands/scan/report.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,18 @@ filters:
6666
`alert_types` takes precedence over `severities`, matching the Python CLI.
6767
Delivery errors are reported as warnings and do not change the scan decision.
6868
Existing report viewing commands do not send notifications.
69+
70+
Slack bot delivery is available when the job also supplies a bot token and
71+
channel configuration. Create a Slack app with the `chat:write` bot token scope,
72+
install it in the workspace, and invite it to each target channel. Keep the bot
73+
token in CI secret storage:
74+
75+
```sh
76+
export SOCKET_SLACK_BOT_TOKEN="$SLACK_BOT_TOKEN"
77+
export SOCKET_SLACK_CONFIG_JSON='{"bot_configs":[{"name":"security","channels":["C0123456789"],"repos":["api"],"alert_types":["cve"]}]}'
78+
socket scan create --report
79+
```
80+
81+
The bot posts to Slack's `chat.postMessage` API. It checks both the HTTP status
82+
and Slack's JSON `ok` response. Rate limits and API errors are reported without
83+
printing the token or changing the scan decision.
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
import {
2+
filterSlackFindings,
3+
formatSlackMessage,
4+
getAllowedSlackActions,
5+
getSlackNotificationConfig,
6+
safeSlackFilter,
7+
} from './slack-webhook.mts'
8+
import { apiFetch } from '../../../utils/api.mts'
9+
import { logger } from '../../../utils/logger.mts'
10+
11+
import type { NotificationReport } from './report.mts'
12+
13+
const SLACK_POST_MESSAGE_URL = 'https://slack.com/api/chat.postMessage'
14+
const REQUEST_TIMEOUT_MS = 10_000
15+
16+
type BotDestination = {
17+
name: string
18+
channels: string[]
19+
filter: ReturnType<typeof safeSlackFilter>
20+
}
21+
22+
function botDestinations(config: Record<string, unknown>): BotDestination[] {
23+
const input = config['bot_configs']
24+
if (!Array.isArray(input)) {
25+
if (input !== undefined) {
26+
logger.warn('Slack bot_configs must be an array; skipping bot delivery.')
27+
}
28+
return []
29+
}
30+
return input.flatMap((item, index) => {
31+
if (!item || typeof item !== 'object' || Array.isArray(item)) {
32+
logger.warn(
33+
`Slack bot configuration ${index + 1} is invalid; skipping it.`,
34+
)
35+
return []
36+
}
37+
const source = item as Record<string, unknown>
38+
const name =
39+
typeof source['name'] === 'string' ? source['name'] : `bot_${index}`
40+
const channels = source['channels']
41+
if (
42+
!Array.isArray(channels) ||
43+
channels.some(channel => typeof channel !== 'string')
44+
) {
45+
logger.warn(
46+
`Slack bot configuration "${name}" has invalid channels; skipping it.`,
47+
)
48+
return []
49+
}
50+
if (channels.length === 0) {
51+
logger.warn(
52+
`Slack bot configuration "${name}" has no channels; skipping it.`,
53+
)
54+
return []
55+
}
56+
const filter = safeSlackFilter(source)
57+
if (!filter) {
58+
logger.warn(
59+
`Slack bot configuration "${name}" has an invalid filter; skipping it.`,
60+
)
61+
return []
62+
}
63+
return [{ name, channels, filter }]
64+
})
65+
}
66+
67+
/** Post selected scan findings to channels configured for a Slack bot. */
68+
export async function sendSlackBotNotifications(
69+
report: NotificationReport,
70+
config:
71+
| Record<string, unknown>
72+
| null
73+
| undefined = getSlackNotificationConfig(),
74+
): Promise<void> {
75+
const token = process.env['SOCKET_SLACK_BOT_TOKEN']
76+
if (!token) {
77+
return
78+
}
79+
if (!token.startsWith('xoxb-')) {
80+
logger.warn(
81+
'SOCKET_SLACK_BOT_TOKEN must be a bot OAuth token beginning with xoxb-.',
82+
)
83+
return
84+
}
85+
if (!config) {
86+
if (!process.env['SOCKET_SLACK_CONFIG_JSON']) {
87+
logger.warn('Slack bot delivery requires SOCKET_SLACK_CONFIG_JSON.')
88+
}
89+
return
90+
}
91+
const destinations = botDestinations(config)
92+
if (!destinations.length) {
93+
logger.warn(
94+
'No valid Slack bot destinations are configured; skipping delivery.',
95+
)
96+
return
97+
}
98+
const allowedActions = getAllowedSlackActions()
99+
for (const destination of destinations) {
100+
const findings = filterSlackFindings(
101+
report,
102+
destination.filter ?? {},
103+
allowedActions,
104+
)
105+
if (!findings.length) {
106+
continue
107+
}
108+
const message = formatSlackMessage(report, findings)
109+
for (const channel of destination.channels) {
110+
if (!channel.trim() || channel.length > 80 || /[\r\n]/u.test(channel)) {
111+
logger.warn(
112+
`Slack bot destination "${destination.name}" contains an invalid channel; skipping it.`,
113+
)
114+
continue
115+
}
116+
try {
117+
// Slack's fixed endpoint and manual redirect policy prevent sending the bot token elsewhere.
118+
// eslint-disable-next-line no-await-in-loop
119+
const response = await apiFetch(SLACK_POST_MESSAGE_URL, {
120+
method: 'POST',
121+
headers: {
122+
authorization: `Bearer ${token}`,
123+
'content-type': 'application/json; charset=utf-8',
124+
},
125+
body: JSON.stringify({ channel, ...message }),
126+
rejectRedirects: true,
127+
timeout: REQUEST_TIMEOUT_MS,
128+
})
129+
if (!response.ok) {
130+
logger.warn(
131+
`Slack bot delivery to "${destination.name}" failed with HTTP ${response.status}; scan policy is unchanged.`,
132+
)
133+
continue
134+
}
135+
// The body is one small Slack API acknowledgement, needed to check its `ok` field.
136+
// eslint-disable-next-line no-await-in-loop
137+
const responseData: unknown = await response.json()
138+
if (
139+
!responseData ||
140+
typeof responseData !== 'object' ||
141+
(responseData as { ok?: unknown }).ok !== true
142+
) {
143+
logger.warn(
144+
`Slack bot delivery to "${destination.name}" was rejected by Slack; scan policy is unchanged.`,
145+
)
146+
}
147+
} catch {
148+
logger.warn(
149+
`Slack bot delivery to "${destination.name}" failed; scan policy is unchanged.`,
150+
)
151+
}
152+
}
153+
}
154+
}
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import { apiFetch } from '../../../utils/api.mts'
2+
3+
vi.mock('../../../utils/api.mts', () => ({ apiFetch: vi.fn() }))
4+
import { afterEach, describe, expect, it, vi } from 'vitest'
5+
6+
import { sendSlackBotNotifications } from './slack-bot.mts'
7+
8+
import type { NotificationReport } from './report.mts'
9+
10+
const report: NotificationReport = {
11+
kind: 'diff',
12+
repository: 'example',
13+
branch: 'feature',
14+
decision: 'fail',
15+
summary: '2 findings (1 blocking, 1 warning)',
16+
findings: [
17+
{
18+
packageName: 'left-pad',
19+
ecosystem: 'npm',
20+
version: '1.0.0',
21+
alertType: 'cve',
22+
severity: 'high',
23+
action: 'error',
24+
advisoryId: 'GHSA-1234',
25+
},
26+
{
27+
packageName: 'safe-lib',
28+
ecosystem: 'npm',
29+
version: '2.0.0',
30+
alertType: 'license',
31+
severity: 'low',
32+
action: 'warn',
33+
},
34+
],
35+
}
36+
37+
afterEach(() => {
38+
vi.unstubAllEnvs()
39+
vi.unstubAllGlobals()
40+
})
41+
42+
describe('Slack bot notifications', () => {
43+
it('posts filtered findings to configured channels with fixed API auth', async () => {
44+
const token = 'xoxb-fake-token'
45+
vi.stubEnv('SOCKET_SLACK_BOT_TOKEN', token)
46+
vi.stubEnv(
47+
'SOCKET_SLACK_CONFIG_JSON',
48+
JSON.stringify({
49+
bot_configs: [
50+
{ name: 'security', channels: ['C123456'], alert_types: ['cve'] },
51+
],
52+
}),
53+
)
54+
const post = vi.fn().mockResolvedValue({
55+
ok: true,
56+
status: 200,
57+
json: async () => ({ ok: true }),
58+
})
59+
vi.mocked(apiFetch).mockImplementation(post)
60+
61+
await sendSlackBotNotifications(report)
62+
63+
expect(post).toHaveBeenCalledOnce()
64+
const [url, options] = post.mock.calls[0] as [
65+
string,
66+
NonNullable<Parameters<typeof apiFetch>[1]>,
67+
]
68+
expect(url).toBe('https://slack.com/api/chat.postMessage')
69+
expect(options?.rejectRedirects).toBe(true)
70+
expect(options?.headers).toMatchObject({ authorization: `Bearer ${token}` })
71+
const payload = JSON.parse(String(options?.body))
72+
expect(payload.channel).toBe('C123456')
73+
expect(JSON.stringify(payload)).toContain('GHSA-1234')
74+
expect(JSON.stringify(payload)).not.toContain('safe-lib')
75+
expect(JSON.stringify(payload)).not.toContain(token)
76+
})
77+
78+
it('checks the Slack JSON ok flag even when HTTP status is successful', async () => {
79+
vi.stubEnv('SOCKET_SLACK_BOT_TOKEN', 'xoxb-fake-token')
80+
vi.stubEnv(
81+
'SOCKET_SLACK_CONFIG_JSON',
82+
JSON.stringify({ bot_configs: [{ channels: ['C123456'] }] }),
83+
)
84+
const post = vi.fn().mockResolvedValue({
85+
ok: true,
86+
status: 200,
87+
json: async () => ({ ok: false, error: 'channel_not_found' }),
88+
})
89+
vi.mocked(apiFetch).mockImplementation(post)
90+
91+
await expect(sendSlackBotNotifications(report)).resolves.toBeUndefined()
92+
expect(post).toHaveBeenCalledOnce()
93+
})
94+
95+
it('reports HTTP rate limits and returns without retrying or throwing', async () => {
96+
vi.stubEnv('SOCKET_SLACK_BOT_TOKEN', 'xoxb-fake-token')
97+
vi.stubEnv(
98+
'SOCKET_SLACK_CONFIG_JSON',
99+
JSON.stringify({ bot_configs: [{ channels: ['C123456'] }] }),
100+
)
101+
const post = vi.fn().mockResolvedValue({ ok: false, status: 429 })
102+
vi.mocked(apiFetch).mockImplementation(post)
103+
104+
await expect(sendSlackBotNotifications(report)).resolves.toBeUndefined()
105+
expect(post).toHaveBeenCalledOnce()
106+
})
107+
108+
it('does not send when the token has the wrong credential type', async () => {
109+
vi.stubEnv('SOCKET_SLACK_BOT_TOKEN', 'xoxp-user-token')
110+
vi.stubEnv(
111+
'SOCKET_SLACK_CONFIG_JSON',
112+
JSON.stringify({ bot_configs: [{ channels: ['C123456'] }] }),
113+
)
114+
const post = vi.fn()
115+
vi.mocked(apiFetch).mockImplementation(post)
116+
117+
await sendSlackBotNotifications(report)
118+
expect(post).not.toHaveBeenCalled()
119+
})
120+
})

0 commit comments

Comments
 (0)