-
Notifications
You must be signed in to change notification settings - Fork 399
/
AwsLambdaReceiver.ts
340 lines (305 loc) · 10.7 KB
/
AwsLambdaReceiver.ts
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
/* eslint-disable @typescript-eslint/no-explicit-any */
import querystring from 'querystring';
import crypto from 'crypto';
import { Logger, ConsoleLogger, LogLevel } from '@slack/logger';
import tsscmp from 'tsscmp';
import App from '../App';
import { Receiver, ReceiverEvent } from '../types/receiver';
import { ReceiverMultipleAckError } from '../errors';
import { StringIndexed } from '../types/helpers';
export interface AwsEvent {
body: string | null;
headers: any;
multiValueHeaders: any;
httpMethod: string;
isBase64Encoded: boolean;
path: string;
pathParameters: any | null;
queryStringParameters: any | null;
multiValueQueryStringParameters: any | null;
stageVariables: any | null;
requestContext: any;
resource: string;
}
export type AwsCallback = (error?: Error | string | null, result?: any) => void;
export interface ReceiverInvalidRequestSignatureHandlerArgs {
rawBody: string;
signature: string;
ts: number;
awsEvent: AwsEvent;
awsResponse: Promise<AwsResponse>;
}
export interface AwsResponse {
statusCode: number;
headers?: {
[header: string]: boolean | number | string;
};
multiValueHeaders?: {
[header: string]: Array<boolean | number | string>;
};
body: string;
isBase64Encoded?: boolean;
}
export type AwsHandler = (event: AwsEvent, context: any, callback: AwsCallback) => Promise<AwsResponse>;
export interface AwsLambdaReceiverOptions {
/**
* The Slack Signing secret to be used as an input to signature verification to ensure that requests are coming from
* Slack.
*
* If the {@link signatureVerification} flag is set to `false`, this can be set to any value as signature verification
* using this secret will not be performed.
*
* @see {@link https://api.slack.com/authentication/verifying-requests-from-slack#about} for details about signing secrets
*/
signingSecret: string;
/**
* The {@link Logger} for the receiver
*
* @default ConsoleLogger
*/
logger?: Logger;
/**
* The {@link LogLevel} to be used for the logger.
*
* @default LogLevel.INFO
*/
logLevel?: LogLevel;
/**
* Flag that determines whether Bolt should {@link https://api.slack.com/authentication/verifying-requests-from-slack|verify Slack's signature on incoming requests}.
*
* @default true
*/
signatureVerification?: boolean;
/**
* Optional `function` that can extract custom properties from an incoming receiver event
* @param request The API Gateway event {@link AwsEvent}
* @returns An object containing custom properties
*
* @default noop
*/
customPropertiesExtractor?: (request: AwsEvent) => StringIndexed;
invalidRequestSignatureHandler?: (args: ReceiverInvalidRequestSignatureHandlerArgs) => void;
}
/*
* Receiver implementation for AWS API Gateway + Lambda apps
*
* Note that this receiver does not support Slack OAuth flow.
* For OAuth flow endpoints, deploy another Lambda function built with ExpressReceiver.
*/
export default class AwsLambdaReceiver implements Receiver {
private signingSecret: string;
private app?: App;
private logger: Logger;
private signatureVerification: boolean;
private customPropertiesExtractor: (request: AwsEvent) => StringIndexed;
private invalidRequestSignatureHandler: (args: ReceiverInvalidRequestSignatureHandlerArgs) => void;
public constructor({
signingSecret,
logger = undefined,
logLevel = LogLevel.INFO,
signatureVerification = true,
customPropertiesExtractor = (_) => ({}),
invalidRequestSignatureHandler,
}: AwsLambdaReceiverOptions) {
// Initialize instance variables, substituting defaults for each value
this.signingSecret = signingSecret;
this.signatureVerification = signatureVerification;
this.logger = logger ??
(() => {
const defaultLogger = new ConsoleLogger();
defaultLogger.setLevel(logLevel);
return defaultLogger;
})();
this.customPropertiesExtractor = customPropertiesExtractor;
if (invalidRequestSignatureHandler) {
this.invalidRequestSignatureHandler = invalidRequestSignatureHandler;
} else {
this.invalidRequestSignatureHandler = this.defaultInvalidRequestSignatureHandler;
}
}
public init(app: App): void {
this.app = app;
}
public start(
..._args: any[]
): Promise<AwsHandler> {
return new Promise((resolve, reject) => {
try {
const handler = this.toHandler();
resolve(handler);
} catch (error) {
reject(error);
}
});
}
// eslint-disable-next-line class-methods-use-this
public stop(
..._args: any[]
): Promise<void> {
return new Promise((resolve, _reject) => {
resolve();
});
}
public toHandler(): AwsHandler {
return async (
awsEvent: AwsEvent,
_awsContext: any,
_awsCallback: AwsCallback,
): Promise<AwsResponse> => {
this.logger.debug(`AWS event: ${JSON.stringify(awsEvent, null, 2)}`);
const rawBody = this.getRawBody(awsEvent);
const body: any = this.parseRequestBody(
rawBody,
this.getHeaderValue(awsEvent.headers, 'Content-Type'),
this.logger,
);
// ssl_check (for Slash Commands)
if (
typeof body !== 'undefined' &&
body != null &&
typeof body.ssl_check !== 'undefined' &&
body.ssl_check != null
) {
return Promise.resolve({ statusCode: 200, body: '' });
}
if (this.signatureVerification) {
// request signature verification
const signature = this.getHeaderValue(awsEvent.headers, 'X-Slack-Signature') as string;
const ts = Number(this.getHeaderValue(awsEvent.headers, 'X-Slack-Request-Timestamp'));
if (!this.isValidRequestSignature(this.signingSecret, rawBody, signature, ts)) {
const awsResponse = Promise.resolve({ statusCode: 401, body: '' });
this.invalidRequestSignatureHandler({ rawBody, signature, ts, awsEvent, awsResponse });
return awsResponse;
}
}
// url_verification (Events API)
if (
typeof body !== 'undefined' &&
body != null &&
typeof body.type !== 'undefined' &&
body.type != null &&
body.type === 'url_verification'
) {
return Promise.resolve({
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ challenge: body.challenge }),
});
}
// Setup ack timeout warning
let isAcknowledged = false;
const noAckTimeoutId = setTimeout(() => {
if (!isAcknowledged) {
this.logger.error(
'An incoming event was not acknowledged within 3 seconds. ' +
'Ensure that the ack() argument is called in a listener.',
);
}
}, 3001);
// Structure the ReceiverEvent
let storedResponse;
const event: ReceiverEvent = {
body,
ack: async (response) => {
if (isAcknowledged) {
throw new ReceiverMultipleAckError();
}
isAcknowledged = true;
clearTimeout(noAckTimeoutId);
if (typeof response === 'undefined' || response == null) {
storedResponse = '';
} else {
storedResponse = response;
}
},
retryNum: this.getHeaderValue(awsEvent.headers, 'X-Slack-Retry-Num') as number | undefined,
retryReason: this.getHeaderValue(awsEvent.headers, 'X-Slack-Retry-Reason'),
customProperties: this.customPropertiesExtractor(awsEvent),
};
// Send the event to the app for processing
try {
await this.app?.processEvent(event);
if (storedResponse !== undefined) {
if (typeof storedResponse === 'string') {
return { statusCode: 200, body: storedResponse };
}
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(storedResponse),
};
}
} catch (err) {
this.logger.error('An unhandled error occurred while Bolt processed an event');
this.logger.debug(`Error details: ${err}, storedResponse: ${storedResponse}`);
return { statusCode: 500, body: 'Internal server error' };
}
this.logger.info(`No request handler matched the request: ${awsEvent.path}`);
return { statusCode: 404, body: '' };
};
}
// eslint-disable-next-line class-methods-use-this
private getRawBody(awsEvent: AwsEvent): string {
if (typeof awsEvent.body === 'undefined' || awsEvent.body == null) {
return '';
}
if (awsEvent.isBase64Encoded) {
return Buffer.from(awsEvent.body, 'base64').toString('ascii');
}
return awsEvent.body;
}
// eslint-disable-next-line class-methods-use-this
private parseRequestBody(stringBody: string, contentType: string | undefined, logger: Logger): any {
if (contentType === 'application/x-www-form-urlencoded') {
const parsedBody = querystring.parse(stringBody);
if (typeof parsedBody.payload === 'string') {
return JSON.parse(parsedBody.payload);
}
return parsedBody;
}
if (contentType === 'application/json') {
return JSON.parse(stringBody);
}
logger.warn(`Unexpected content-type detected: ${contentType}`);
try {
// Parse this body anyway
return JSON.parse(stringBody);
} catch (e) {
logger.error(`Failed to parse body as JSON data for content-type: ${contentType}`);
throw e;
}
}
// eslint-disable-next-line class-methods-use-this
private isValidRequestSignature(
signingSecret: string,
body: string,
signature: string,
requestTimestamp: number,
): boolean {
if (!signature || !requestTimestamp) {
return false;
}
// Divide current date to match Slack ts format
// Subtract 5 minutes from current time
const fiveMinutesAgo = Math.floor(Date.now() / 1000) - 60 * 5;
if (requestTimestamp < fiveMinutesAgo) {
return false;
}
const hmac = crypto.createHmac('sha256', signingSecret);
const [version, hash] = signature.split('=');
hmac.update(`${version}:${requestTimestamp}:${body}`);
if (!tsscmp(hash, hmac.digest('hex'))) {
return false;
}
return true;
}
// eslint-disable-next-line class-methods-use-this
private getHeaderValue(headers: Record<string, any>, key: string): string | undefined {
const caseInsensitiveKey = Object.keys(headers).find((it) => key.toLowerCase() === it.toLowerCase());
return caseInsensitiveKey !== undefined ? headers[caseInsensitiveKey] : undefined;
}
private defaultInvalidRequestSignatureHandler(args: ReceiverInvalidRequestSignatureHandlerArgs): void {
const { signature, ts } = args;
this.logger.info(`Invalid request signature detected (X-Slack-Signature: ${signature}, X-Slack-Request-Timestamp: ${ts})`);
}
}