Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,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
Expand Down
15 changes: 15 additions & 0 deletions docs/commands/scan/report.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
154 changes: 154 additions & 0 deletions src/commands/scan/notifications/slack-bot.mts
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
}
Comment thread
jdalton marked this conversation as resolved.
Resolved
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,
})
Comment thread
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.`,
)
}
}
}
}
120 changes: 120 additions & 0 deletions src/commands/scan/notifications/slack-bot.test.mts
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()
})
})
Loading
Loading