-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslack-integration.ts
More file actions
431 lines (383 loc) · 18.2 KB
/
slack-integration.ts
File metadata and controls
431 lines (383 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/**
* MIT No Attribution
*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import * as path from 'path';
import { ArnFormat, Duration, RemovalPolicy, Stack } from 'aws-cdk-lib';
import * as apigw from 'aws-cdk-lib/aws-apigateway';
import * as cognito from 'aws-cdk-lib/aws-cognito';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as iam from 'aws-cdk-lib/aws-iam';
import { Runtime, Architecture } from 'aws-cdk-lib/aws-lambda';
import * as lambda from 'aws-cdk-lib/aws-lambda-nodejs';
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
import { NagSuppressions } from 'cdk-nag';
import { Construct } from 'constructs';
import { SlackInstallationTable } from './slack-installation-table';
import { SlackUserMappingTable } from './slack-user-mapping-table';
/**
* Properties for SlackIntegration construct.
*/
export interface SlackIntegrationProps {
/** The existing REST API to add Slack routes to. */
readonly api: apigw.RestApi;
/** Cognito user pool for the /slack/link endpoint (Cognito-authenticated). */
readonly userPool: cognito.IUserPool;
/** The DynamoDB task table. */
readonly taskTable: dynamodb.ITable;
/** The DynamoDB task events table (must have DynamoDB Streams enabled). */
readonly taskEventsTable: dynamodb.ITable;
/** The DynamoDB repo config table (optional — for repo onboarding checks). */
readonly repoTable?: dynamodb.ITable;
/** Orchestrator Lambda function ARN for async task invocation. */
readonly orchestratorFunctionArn?: string;
/** Bedrock Guardrail ID for input screening. */
readonly guardrailId?: string;
/** Bedrock Guardrail version for input screening. */
readonly guardrailVersion?: string;
/** Task retention in days for TTL computation. */
readonly taskRetentionDays?: number;
/** Removal policy for Slack DynamoDB tables. */
readonly removalPolicy?: RemovalPolicy;
}
/**
* CDK construct that adds Slack integration to the ABCA platform.
*
* Creates:
* - SlackInstallationTable (per-workspace installation records)
* - SlackUserMappingTable (Slack user → platform user mappings)
* - Lambda handlers for OAuth, slash commands, events, and account linking
* - API Gateway routes under /slack/*
*
* Outbound Slack delivery (task lifecycle notifications) runs through
* ``FanOutConsumer`` as a per-channel dispatcher. Before issue #64 this
* construct also owned a ``SlackNotifyFn`` DynamoDB Streams consumer on
* ``TaskEventsTable``; that consumer was removed to keep the stream at
* the DynamoDB-documented one-reader-per-shard limit.
*/
export class SlackIntegration extends Construct {
/** The Slack installation table. */
public readonly installationTable: dynamodb.Table;
/** The Slack user mapping table. */
public readonly userMappingTable: dynamodb.Table;
/** The Slack signing secret (placeholder — user populates after creating the Slack App). */
public readonly signingSecret: secretsmanager.Secret;
/** The Slack client secret (placeholder — user populates after creating the Slack App). */
public readonly clientSecret: secretsmanager.Secret;
/** The Slack client ID secret (placeholder — user populates after creating the Slack App). */
public readonly clientIdSecret: secretsmanager.Secret;
constructor(scope: Construct, id: string, props: SlackIntegrationProps) {
super(scope, id);
const removalPolicy = props.removalPolicy ?? RemovalPolicy.DESTROY;
// --- DynamoDB Tables ---
const installationTable = new SlackInstallationTable(this, 'InstallationTable', { removalPolicy });
const userMappingTable = new SlackUserMappingTable(this, 'UserMappingTable', { removalPolicy });
this.installationTable = installationTable.table;
this.userMappingTable = userMappingTable.table;
// --- Slack App Secrets (CDK-created placeholders) ---
// Users populate these after creating the Slack App via the SlackAppCreateUrl output.
this.signingSecret = new secretsmanager.Secret(this, 'SigningSecret', {
description: 'Slack App signing secret — populate after creating the Slack App',
removalPolicy,
});
this.clientSecret = new secretsmanager.Secret(this, 'ClientSecret', {
description: 'Slack App client secret (OAuth) — populate after creating the Slack App',
removalPolicy,
});
this.clientIdSecret = new secretsmanager.Secret(this, 'ClientIdSecret', {
description: 'Slack App client ID — populate after creating the Slack App',
removalPolicy,
});
// --- Shared Lambda configuration ---
const handlersDir = path.join(__dirname, '..', 'handlers');
const commonBundling: lambda.BundlingOptions = {
externalModules: ['@aws-sdk/*'],
};
// Secrets Manager ARN prefix for Slack secrets (bgagent/slack/*)
const slackSecretArnPrefix = Stack.of(this).formatArn({
service: 'secretsmanager',
resource: 'secret',
resourceName: 'bgagent/slack/*',
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
});
// IAM policy for reading Slack secrets from Secrets Manager
const readSlackSecretsPolicy = new iam.PolicyStatement({
actions: ['secretsmanager:GetSecretValue'],
resources: [slackSecretArnPrefix],
});
// --- Cognito Authorizer (for /slack/link endpoint) ---
const cognitoAuthorizer = new apigw.CognitoUserPoolsAuthorizer(this, 'SlackCognitoAuthorizer', {
cognitoUserPools: [props.userPool],
});
const cognitoAuthOptions: apigw.MethodOptions = {
authorizer: cognitoAuthorizer,
authorizationType: apigw.AuthorizationType.COGNITO,
};
const noneAuthOptions: apigw.MethodOptions = {
authorizationType: apigw.AuthorizationType.NONE,
};
// --- Task creation environment (matches TaskApi createTaskEnv pattern) ---
const createTaskEnv: Record<string, string> = {
TASK_TABLE_NAME: props.taskTable.tableName,
TASK_EVENTS_TABLE_NAME: props.taskEventsTable.tableName,
TASK_RETENTION_DAYS: String(props.taskRetentionDays ?? 90),
};
if (props.repoTable) {
createTaskEnv.REPO_TABLE_NAME = props.repoTable.tableName;
}
if (props.orchestratorFunctionArn) {
createTaskEnv.ORCHESTRATOR_FUNCTION_ARN = props.orchestratorFunctionArn;
}
if (props.guardrailId && props.guardrailVersion) {
createTaskEnv.GUARDRAIL_ID = props.guardrailId;
createTaskEnv.GUARDRAIL_VERSION = props.guardrailVersion;
}
// ═══════════════════════════════════════════════════════════════════════════
// Lambda Handlers
// ═══════════════════════════════════════════════════════════════════════════
// --- OAuth Callback ---
const oauthCallbackFn = new lambda.NodejsFunction(this, 'OAuthCallbackFn', {
entry: path.join(handlersDir, 'slack-oauth-callback.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
timeout: Duration.seconds(15),
environment: {
SLACK_INSTALLATION_TABLE_NAME: this.installationTable.tableName,
SLACK_CLIENT_ID_SECRET_ARN: this.clientIdSecret.secretArn,
SLACK_CLIENT_SECRET_ARN: this.clientSecret.secretArn,
},
bundling: commonBundling,
});
this.installationTable.grantWriteData(oauthCallbackFn);
this.clientIdSecret.grantRead(oauthCallbackFn);
this.clientSecret.grantRead(oauthCallbackFn);
oauthCallbackFn.addToRolePolicy(readSlackSecretsPolicy);
// CreateSecret + UpdateSecret for bot tokens
oauthCallbackFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['secretsmanager:CreateSecret'],
resources: ['*'],
conditions: {
StringLike: { 'secretsmanager:Name': 'bgagent/slack/*' },
},
}));
oauthCallbackFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['secretsmanager:UpdateSecret', 'secretsmanager:TagResource', 'secretsmanager:RestoreSecret'],
resources: [slackSecretArnPrefix],
}));
// --- Slack Events ---
// Note: SLACK_COMMAND_PROCESSOR_FUNCTION_NAME is set below after commandProcessorFn is created.
const slackEventsFn = new lambda.NodejsFunction(this, 'SlackEventsFn', {
entry: path.join(handlersDir, 'slack-events.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
timeout: Duration.seconds(10),
environment: {
SLACK_INSTALLATION_TABLE_NAME: this.installationTable.tableName,
SLACK_SIGNING_SECRET_ARN: this.signingSecret.secretArn,
},
bundling: commonBundling,
});
// Keep one instance warm — Slack's URL verification during app creation
// times out on cold starts, and the retry UX is poor.
const slackEventsAlias = slackEventsFn.addAlias('live', {
provisionedConcurrentExecutions: 1,
});
this.installationTable.grantReadWriteData(slackEventsFn);
this.signingSecret.grantRead(slackEventsFn);
slackEventsFn.addToRolePolicy(readSlackSecretsPolicy);
slackEventsFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['secretsmanager:DeleteSecret'],
resources: [slackSecretArnPrefix],
}));
// --- Slash Command Processor (async worker) ---
const commandProcessorFn = new lambda.NodejsFunction(this, 'CommandProcessorFn', {
entry: path.join(handlersDir, 'slack-command-processor.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
timeout: Duration.seconds(30),
environment: {
...createTaskEnv,
SLACK_USER_MAPPING_TABLE_NAME: this.userMappingTable.tableName,
SLACK_INSTALLATION_TABLE_NAME: this.installationTable.tableName,
},
bundling: commonBundling,
});
this.userMappingTable.grantReadWriteData(commandProcessorFn);
this.installationTable.grantReadData(commandProcessorFn);
commandProcessorFn.addToRolePolicy(readSlackSecretsPolicy);
props.taskTable.grantReadWriteData(commandProcessorFn);
props.taskEventsTable.grantReadWriteData(commandProcessorFn);
if (props.repoTable) {
props.repoTable.grantReadData(commandProcessorFn);
}
if (props.orchestratorFunctionArn) {
commandProcessorFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['lambda:InvokeFunction'],
resources: [props.orchestratorFunctionArn],
}));
}
if (props.guardrailId) {
commandProcessorFn.addToRolePolicy(new iam.PolicyStatement({
actions: ['bedrock:ApplyGuardrail'],
resources: [
Stack.of(this).formatArn({
service: 'bedrock',
resource: 'guardrail',
resourceName: props.guardrailId,
}),
],
}));
}
// Wire events handler to command processor for @mention forwarding.
slackEventsFn.addEnvironment('SLACK_COMMAND_PROCESSOR_FUNCTION_NAME', commandProcessorFn.functionName);
commandProcessorFn.grantInvoke(slackEventsFn);
// --- Slack Interactions (Block Kit button actions) ---
const slackInteractionsFn = new lambda.NodejsFunction(this, 'SlackInteractionsFn', {
entry: path.join(handlersDir, 'slack-interactions.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
timeout: Duration.seconds(10),
environment: {
SLACK_SIGNING_SECRET_ARN: this.signingSecret.secretArn,
TASK_TABLE_NAME: props.taskTable.tableName,
SLACK_USER_MAPPING_TABLE_NAME: this.userMappingTable.tableName,
},
bundling: commonBundling,
});
this.signingSecret.grantRead(slackInteractionsFn);
slackInteractionsFn.addToRolePolicy(readSlackSecretsPolicy);
props.taskTable.grantReadWriteData(slackInteractionsFn);
this.userMappingTable.grantReadData(slackInteractionsFn);
// --- Slash Command Acknowledger ---
const slackCommandsFn = new lambda.NodejsFunction(this, 'SlackCommandsFn', {
entry: path.join(handlersDir, 'slack-commands.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
timeout: Duration.seconds(3),
environment: {
SLACK_SIGNING_SECRET_ARN: this.signingSecret.secretArn,
SLACK_COMMAND_PROCESSOR_FUNCTION_NAME: commandProcessorFn.functionName,
},
bundling: commonBundling,
});
// slackCommandsFn verifies the Slack signing secret (granted above) and
// async-invokes the processor Lambda — it never reads bot tokens, so the
// bgagent/slack/* wildcard grant is intentionally omitted here.
this.signingSecret.grantRead(slackCommandsFn);
commandProcessorFn.grantInvoke(slackCommandsFn);
// --- Account Linking (Cognito-authenticated) ---
const slackLinkFn = new lambda.NodejsFunction(this, 'SlackLinkFn', {
entry: path.join(handlersDir, 'slack-link.ts'),
handler: 'handler',
runtime: Runtime.NODEJS_24_X,
architecture: Architecture.ARM_64,
timeout: Duration.seconds(10),
environment: {
SLACK_USER_MAPPING_TABLE_NAME: this.userMappingTable.tableName,
},
bundling: commonBundling,
});
this.userMappingTable.grantReadWriteData(slackLinkFn);
// Outbound Slack delivery runs through FanOutConsumer — see the
// construct doc above for the reader-count rationale (issue #64).
// ═══════════════════════════════════════════════════════════════════════════
// API Gateway Routes
// ═══════════════════════════════════════════════════════════════════════════
const slack = props.api.root.addResource('slack');
// OAuth callback: GET /v1/slack/oauth/callback
const oauthResource = slack.addResource('oauth');
const oauthCallbackResource = oauthResource.addResource('callback');
const oauthCallbackMethod = oauthCallbackResource.addMethod(
'GET',
new apigw.LambdaIntegration(oauthCallbackFn),
noneAuthOptions,
);
// Slack events: POST /v1/slack/events
const eventsResource = slack.addResource('events');
const eventsMethod = eventsResource.addMethod(
'POST',
new apigw.LambdaIntegration(slackEventsAlias),
noneAuthOptions,
);
// Slash commands: POST /v1/slack/commands
const commandsResource = slack.addResource('commands');
const commandsMethod = commandsResource.addMethod(
'POST',
new apigw.LambdaIntegration(slackCommandsFn),
noneAuthOptions,
);
// Block Kit interactions: POST /v1/slack/interactions
const interactionsResource = slack.addResource('interactions');
const interactionsMethod = interactionsResource.addMethod(
'POST',
new apigw.LambdaIntegration(slackInteractionsFn),
noneAuthOptions,
);
// Account linking: POST /v1/slack/link (Cognito-authenticated)
const linkResource = slack.addResource('link');
linkResource.addMethod(
'POST',
new apigw.LambdaIntegration(slackLinkFn),
cognitoAuthOptions,
);
// ═══════════════════════════════════════════════════════════════════════════
// cdk-nag suppressions
// ═══════════════════════════════════════════════════════════════════════════
// Suppress APIG4 and COG4 on routes that use Slack signing secret instead of Cognito
const slackVerifiedMethods = [oauthCallbackMethod, eventsMethod, commandsMethod, interactionsMethod];
for (const method of slackVerifiedMethods) {
NagSuppressions.addResourceSuppressions(method, [
{
id: 'AwsSolutions-APIG4',
reason: 'Slack endpoint uses Slack signing secret verification instead of Cognito — by design for Slack API integration',
},
{
id: 'AwsSolutions-COG4',
reason: 'Slack endpoint uses Slack signing secret verification instead of Cognito — by design for Slack API integration',
},
]);
}
// Slack secrets are managed externally (populated by the user after creating the Slack App)
for (const secret of [this.signingSecret, this.clientSecret, this.clientIdSecret]) {
NagSuppressions.addResourceSuppressions(secret, [
{
id: 'AwsSolutions-SMG4',
reason: 'Slack App credentials are managed externally — automatic rotation is not applicable',
},
]);
}
// Standard Lambda suppressions
const allFunctions = [oauthCallbackFn, slackEventsFn, slackCommandsFn, commandProcessorFn, slackLinkFn, slackInteractionsFn];
for (const fn of allFunctions) {
NagSuppressions.addResourceSuppressions(fn, [
{
id: 'AwsSolutions-IAM4',
reason: 'AWSLambdaBasicExecutionRole is the AWS-recommended managed policy for Lambda functions',
},
{
id: 'AwsSolutions-IAM5',
reason: 'Wildcard permissions are scoped by condition (secretsmanager:Name prefix) or by DynamoDB index ARN patterns',
},
], true);
}
}
}