Skip to content

Commit 5adf68f

Browse files
feat(slack): native Sim app trigger mode via the preview-gated slack_v2 block (#5892)
* feat(slack): native Sim app trigger mode behind the preview-gated slack_v2 block Restore the native Sim Slack app mode for the slack_oauth trigger using a single-credential-picker design. The trigger is only reachable through the preview-gated slack_v2 block, so the mode inherits that gate — no separate env flag. - Re-add SIM_SUBSCRIBED_EVENTS / SLACK_SIM_EVENT_OPTIONS derived exports. - Merge the trigger credential picker (credentialKind: 'any') so it lists Sim OAuth accounts and reusable custom bots together, mirroring the slack_v2 block. - Event dropdown narrows to the Sim app's subscribed events when an OAuth account is selected, all events for a custom bot (resolved client-side from the warmed credential list). - Deploy branch discriminates by the RESOLVED credential, not a UI field: a bot credential routes by credential id (custom app); otherwise validate the event against SIM_SUBSCRIBED_EVENTS, resolve the credential owner's token, derive routingKey from Slack team_id (auth.test), and route on the shared Sim app. - The ingest endpoint and team_id fan-out routing already existed on staging. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018asmKsWQ5Vi7T7wD9uHofz * fix(slack): address review — set credentialId, scope OAuth path to workspace, drop event narrowing Review round 1 (Greptile 4/5 + Cursor Bugbot): - deploy.ts: the native Sim-app (OAuth) branch now sets providerConfig.credentialId (runtime token resolution in the slack provider and credential-disconnect cleanup both key slack_app rows on it — without it, file downloads / reaction text fail and disconnect leaves the webhook active). - deploy.ts: resolve the OAuth credential through resolveTriggerCredentialId (workspace- and oauth-scoped) so a pasted foreign/other-tenant credential id can't bind to the workflow; use the resolved canonical id for token owner lookup + routing. - deploy.ts: a deleted/secretless custom bot credential (getSlackBotCredential → null but a service_account row exists) now returns the "reconnect the bot" error instead of the misleading "connected Slack account" message. - oauth.ts: drop the credential-based event-option narrowing. The shared dropdown framework doesn't revalidate a stored value when its dependency changes, so switching a custom bot → Sim account left an orphaned event that failed deploy with a 400. The event picker now offers all events; the deploy path is the authoritative gate. - tests: add broken-bot and workspace-not-resolvable cases; assert credentialId is set. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018asmKsWQ5Vi7T7wD9uHofz --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent efe1de3 commit 5adf68f

4 files changed

Lines changed: 341 additions & 47 deletions

File tree

apps/sim/lib/webhooks/deploy.test.ts

Lines changed: 172 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
/**
22
* @vitest-environment node
33
*/
4-
import { credential } from '@sim/db/schema'
5-
import { resetDbChainMock } from '@sim/testing'
4+
import { account, credential } from '@sim/db/schema'
5+
import { queueTableRows, resetDbChainMock } from '@sim/testing'
66
import { eq } from 'drizzle-orm'
7-
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
7+
import { afterAll, beforeEach, describe, expect, it, type Mock, vi } from 'vitest'
88
import type { SubBlockConfig } from '@/blocks/types'
99
import type { BlockState } from '@/stores/workflows/workflow/types'
1010

@@ -25,7 +25,33 @@ vi.mock('@/lib/webhooks/pending-verification', () => ({
2525
PendingWebhookVerificationTracker: vi.fn(),
2626
}))
2727

28-
import { buildProviderConfig, resolveTriggerCredentialId } from '@/lib/webhooks/deploy'
28+
const {
29+
mockGetSlackBotCredential,
30+
mockResolveOAuthAccountId,
31+
mockRefreshAccessTokenIfNeeded,
32+
mockFetchSlackTeamId,
33+
} = vi.hoisted(() => ({
34+
mockGetSlackBotCredential: vi.fn(),
35+
mockResolveOAuthAccountId: vi.fn(),
36+
mockRefreshAccessTokenIfNeeded: vi.fn(),
37+
mockFetchSlackTeamId: vi.fn(),
38+
}))
39+
vi.mock('@/app/api/auth/oauth/utils', () => ({
40+
getSlackBotCredential: mockGetSlackBotCredential,
41+
resolveOAuthAccountId: mockResolveOAuthAccountId,
42+
refreshAccessTokenIfNeeded: mockRefreshAccessTokenIfNeeded,
43+
}))
44+
vi.mock('@/lib/webhooks/providers/slack', () => ({
45+
fetchSlackTeamId: mockFetchSlackTeamId,
46+
}))
47+
48+
import {
49+
buildProviderConfig,
50+
resolveTriggerCredentialId,
51+
resolveWebhookConfigForBlock,
52+
} from '@/lib/webhooks/deploy'
53+
import { getBlock } from '@/blocks'
54+
import { getTrigger } from '@/triggers'
2955

3056
afterAll(resetDbChainMock)
3157

@@ -191,3 +217,145 @@ describe('resolveTriggerCredentialId', () => {
191217
expect(eq).toHaveBeenCalledWith(credential.accountId, 'credential-1')
192218
})
193219
})
220+
221+
describe('resolveWebhookConfigForBlock — slack_oauth routing', () => {
222+
const slackTriggerDef = {
223+
provider: 'slack_app',
224+
name: 'Slack',
225+
subBlocks: [
226+
{ id: 'eventType', mode: 'trigger', required: true },
227+
{
228+
id: 'customBotCredential',
229+
mode: 'trigger',
230+
canonicalParamId: 'botCredential',
231+
serviceId: 'slack',
232+
required: true,
233+
},
234+
{
235+
id: 'manualBotCredential',
236+
mode: 'trigger-advanced',
237+
canonicalParamId: 'botCredential',
238+
required: true,
239+
},
240+
],
241+
}
242+
243+
function resolveSlack(
244+
values: Record<string, unknown>,
245+
workflow: Record<string, unknown> = { workspaceId: 'ws-1' }
246+
) {
247+
;(getBlock as unknown as Mock).mockReturnValue({ category: 'triggers' })
248+
;(getTrigger as unknown as Mock).mockReturnValue(slackTriggerDef)
249+
return resolveWebhookConfigForBlock({
250+
block: makeBlock('slack_oauth', values),
251+
workflow,
252+
userId: 'deployer-1',
253+
requestId: 'req-1',
254+
})
255+
}
256+
257+
it('routes a custom bot credential by credential id on the slack provider', async () => {
258+
mockGetSlackBotCredential.mockResolvedValue({ workspaceId: 'ws-1', botUserId: 'BUSER' })
259+
260+
const result = await resolveSlack({ eventType: 'message', customBotCredential: 'cred_bot_1' })
261+
262+
expect(result?.success).toBe(true)
263+
if (!result?.success) throw new Error('expected success')
264+
expect(result.config.provider).toBe('slack')
265+
expect(result.config.routingKey).toBe('cred_bot_1')
266+
expect(result.config.triggerPath).toBeNull()
267+
expect(result.config.providerConfig.bot_user_id).toBe('BUSER')
268+
})
269+
270+
it('rejects a custom bot credential from another workspace', async () => {
271+
mockGetSlackBotCredential.mockResolvedValue({ workspaceId: 'other-ws', botUserId: 'BUSER' })
272+
273+
const result = await resolveSlack({ eventType: 'message', customBotCredential: 'cred_bot_1' })
274+
275+
expect(result?.success).toBe(false)
276+
if (result?.success) throw new Error('expected failure')
277+
expect(result?.error?.status).toBe(400)
278+
expect(result?.error?.message).toContain('not available in this workspace')
279+
})
280+
281+
it('rejects a deleted or secretless custom bot credential as an invalid bot', async () => {
282+
mockGetSlackBotCredential.mockResolvedValue(null)
283+
mockResolveOAuthAccountId.mockResolvedValue({ credentialType: 'service_account' })
284+
285+
const result = await resolveSlack({ eventType: 'message', customBotCredential: 'cred_bot_x' })
286+
287+
expect(result?.success).toBe(false)
288+
if (result?.success) throw new Error('expected failure')
289+
expect(result?.error?.status).toBe(400)
290+
expect(result?.error?.message).toContain('bot credential is missing or invalid')
291+
expect(mockRefreshAccessTokenIfNeeded).not.toHaveBeenCalled()
292+
})
293+
294+
it('rejects an OAuth credential not resolvable in the workflow workspace', async () => {
295+
mockGetSlackBotCredential.mockResolvedValue(null)
296+
mockResolveOAuthAccountId.mockResolvedValue({ accountId: 'acct-1' })
297+
// No credential row queued → resolveTriggerCredentialId returns null.
298+
299+
const result = await resolveSlack({ eventType: 'message', customBotCredential: 'cred_foreign' })
300+
301+
expect(result?.success).toBe(false)
302+
if (result?.success) throw new Error('expected failure')
303+
expect(result?.error?.status).toBe(400)
304+
expect(result?.error?.message).toContain('not available in this workspace')
305+
expect(mockRefreshAccessTokenIfNeeded).not.toHaveBeenCalled()
306+
})
307+
308+
it('rejects a non-simSubscribed event on the native Sim app (OAuth account)', async () => {
309+
mockGetSlackBotCredential.mockResolvedValue(null)
310+
mockResolveOAuthAccountId.mockResolvedValue({ accountId: 'acct-1' })
311+
queueTableRows(credential, [{ id: 'cred_oauth_1' }])
312+
313+
const result = await resolveSlack({
314+
eventType: 'file_shared',
315+
customBotCredential: 'cred_oauth_1',
316+
})
317+
318+
expect(result?.success).toBe(false)
319+
if (result?.success) throw new Error('expected failure')
320+
expect(result?.error?.status).toBe(400)
321+
expect(result?.error?.message).toContain('not available on the Sim Slack app')
322+
expect(mockRefreshAccessTokenIfNeeded).not.toHaveBeenCalled()
323+
})
324+
325+
it('routes an OAuth account by team_id on the slack_app provider', async () => {
326+
mockGetSlackBotCredential.mockResolvedValue(null)
327+
mockResolveOAuthAccountId.mockResolvedValue({ accountId: 'acct-1' })
328+
queueTableRows(credential, [{ id: 'cred_oauth_1' }])
329+
queueTableRows(account, [{ userId: 'owner-1' }])
330+
mockRefreshAccessTokenIfNeeded.mockResolvedValue('xoxb-token')
331+
mockFetchSlackTeamId.mockResolvedValue({ teamId: 'T123', userId: 'UBOT' })
332+
333+
const result = await resolveSlack({ eventType: 'message', customBotCredential: 'cred_oauth_1' })
334+
335+
expect(result?.success).toBe(true)
336+
if (!result?.success) throw new Error('expected success')
337+
expect(result.config.provider).toBe('slack_app')
338+
expect(result.config.routingKey).toBe('T123')
339+
expect(result.config.triggerPath).toBeNull()
340+
expect(result.config.providerConfig.bot_user_id).toBe('UBOT')
341+
// Runtime token resolution + disconnect cleanup key slack_app rows on this.
342+
expect(result.config.providerConfig.credentialId).toBe('cred_oauth_1')
343+
// Owner's token, not the deploying actor's.
344+
expect(mockRefreshAccessTokenIfNeeded).toHaveBeenCalledWith('cred_oauth_1', 'owner-1', 'req-1')
345+
})
346+
347+
it('fails when the connected Slack account token cannot be resolved', async () => {
348+
mockGetSlackBotCredential.mockResolvedValue(null)
349+
mockResolveOAuthAccountId.mockResolvedValue({ accountId: '' })
350+
queueTableRows(credential, [{ id: 'cred_oauth_1' }])
351+
mockRefreshAccessTokenIfNeeded.mockResolvedValue(null)
352+
353+
const result = await resolveSlack({ eventType: 'message', customBotCredential: 'cred_oauth_1' })
354+
355+
expect(result?.success).toBe(false)
356+
if (result?.success) throw new Error('expected failure')
357+
expect(result?.error?.status).toBe(400)
358+
expect(result?.error?.message).toContain('Could not access the connected Slack account')
359+
expect(mockFetchSlackTeamId).not.toHaveBeenCalled()
360+
})
361+
})

0 commit comments

Comments
 (0)