forked from slackapi/bolt-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp-built-in-middleware.spec.ts
596 lines (515 loc) · 18.1 KB
/
App-built-in-middleware.spec.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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
import 'mocha';
import sinon, { SinonSpy } from 'sinon';
import { assert } from 'chai';
import rewiremock from 'rewiremock';
import { Override, mergeOverrides, createFakeLogger, delay } from './test-helpers';
import { ErrorCode, UnknownError, AuthorizationError, CodedError, isCodedError } from './errors';
import {
Receiver,
ReceiverEvent,
NextFn,
} from './types';
import App, { ExtendedErrorHandlerArgs } from './App';
// Utility functions
const noop = () => Promise.resolve(undefined);
const noopMiddleware = async ({ next }: { next: NextFn }) => {
await next();
};
const noopAuthorize = () => Promise.resolve({});
// Fakes
class FakeReceiver implements Receiver {
private bolt: App | undefined;
public init = (bolt: App) => {
this.bolt = bolt;
};
public start = sinon.fake((...params: any[]): Promise<unknown> => Promise.resolve([...params]));
public stop = sinon.fake((...params: any[]): Promise<unknown> => Promise.resolve([...params]));
public async sendEvent(event: ReceiverEvent): Promise<void> {
return this.bolt?.processEvent(event);
}
}
// Dummies (values that have no real behavior but pass through the system opaquely)
function createDummyReceiverEvent(type: string = 'dummy_event_type'): ReceiverEvent {
// NOTE: this is a degenerate ReceiverEvent that would successfully pass through the App. it happens to look like a
// IncomingEventType.Event
return {
body: {
event: {
type,
},
},
ack: noop,
};
}
describe('App built-in middleware and mechanism', () => {
let fakeReceiver: FakeReceiver;
let fakeErrorHandler: SinonSpy;
let dummyAuthorizationResult: { botToken: string; botId: string };
beforeEach(() => {
fakeReceiver = new FakeReceiver();
fakeErrorHandler = sinon.fake();
dummyAuthorizationResult = { botToken: '', botId: '' };
});
// TODO: verify that authorize callback is called with the correct properties and responds correctly to
// various return values
function createInvalidReceiverEvents(): ReceiverEvent[] {
// TODO: create many more invalid receiver events (fuzzing)
return [
{
body: {},
ack: sinon.fake.resolves(undefined),
},
];
}
it('should warn and skip when processing a receiver event with unknown type (never crash)', async () => {
// Arrange
const fakeLogger = createFakeLogger();
const fakeMiddleware = sinon.fake(noopMiddleware);
const invalidReceiverEvents = createInvalidReceiverEvents();
const MockApp = await importApp();
// Act
const app = new MockApp({ receiver: fakeReceiver, logger: fakeLogger, authorize: noopAuthorize });
app.use(fakeMiddleware);
await Promise.all(invalidReceiverEvents.map((event) => fakeReceiver.sendEvent(event)));
// Assert
assert(fakeErrorHandler.notCalled);
assert(fakeMiddleware.notCalled);
assert.isAtLeast(fakeLogger.warn.callCount, invalidReceiverEvents.length);
});
it('should warn, send to global error handler, and skip when a receiver event fails authorization', async () => {
// Arrange
const fakeLogger = createFakeLogger();
const fakeMiddleware = sinon.fake(noopMiddleware);
const dummyOrigError = new Error('auth failed');
const dummyAuthorizationError = new AuthorizationError('auth failed', dummyOrigError);
const dummyReceiverEvent = createDummyReceiverEvent();
const MockApp = await importApp();
// Act
const app = new MockApp({
receiver: fakeReceiver,
logger: fakeLogger,
authorize: sinon.fake.rejects(dummyAuthorizationError),
});
app.use(fakeMiddleware);
app.error(fakeErrorHandler);
await fakeReceiver.sendEvent(dummyReceiverEvent);
// Assert
assert(fakeMiddleware.notCalled);
assert(fakeLogger.warn.called);
assert.instanceOf(fakeErrorHandler.firstCall.args[0], Error);
assert.propertyVal(fakeErrorHandler.firstCall.args[0], 'code', ErrorCode.AuthorizationError);
assert.propertyVal(fakeErrorHandler.firstCall.args[0], 'original', dummyAuthorizationError.original);
});
describe('global middleware', () => {
let fakeFirstMiddleware: SinonSpy;
let fakeSecondMiddleware: SinonSpy;
let app: App;
let dummyReceiverEvent: ReceiverEvent;
beforeEach(async () => {
const fakeConversationContext = sinon.fake.returns(noopMiddleware);
const overrides = mergeOverrides(
withNoopAppMetadata(),
withNoopWebClient(),
withMemoryStore(sinon.fake()),
withConversationContext(fakeConversationContext),
);
const MockApp = await importApp(overrides);
dummyReceiverEvent = createDummyReceiverEvent();
fakeFirstMiddleware = sinon.fake(noopMiddleware);
fakeSecondMiddleware = sinon.fake(noopMiddleware);
app = new MockApp({
logger: createFakeLogger(),
receiver: fakeReceiver,
authorize: sinon.fake.resolves(dummyAuthorizationResult),
});
});
it('should error if next called multiple times', async () => {
// Arrange
app.use(fakeFirstMiddleware);
app.use(async ({ next }) => {
await next();
await next();
});
app.use(fakeSecondMiddleware);
app.error(fakeErrorHandler);
// Act
await fakeReceiver.sendEvent(dummyReceiverEvent);
// Assert
assert.instanceOf(fakeErrorHandler.firstCall.args[0], Error);
});
it('correctly waits for async listeners', async () => {
let changed = false;
app.use(async ({ next }) => {
await delay(10);
changed = true;
await next();
});
await fakeReceiver.sendEvent(dummyReceiverEvent);
assert.isTrue(changed);
assert(fakeErrorHandler.notCalled);
});
it('throws errors which can be caught by upstream async listeners', async () => {
const thrownError = new Error('Error handling the message :(');
let caughtError;
app.use(async ({ next }) => {
try {
await next();
} catch (err: any) {
caughtError = err;
}
});
app.use(async () => {
throw thrownError;
});
app.error(fakeErrorHandler);
await fakeReceiver.sendEvent(dummyReceiverEvent);
assert.equal(caughtError, thrownError);
assert(fakeErrorHandler.notCalled);
});
it('calls async middleware in declared order', async () => {
const message = ':wave:';
let middlewareCount = 0;
/**
* Middleware that, when called, asserts that it was called in the correct order
* @param orderDown The order it should be called when processing middleware down the chain
* @param orderUp The order it should be called when processing middleware up the chain
*/
const assertOrderMiddleware = (orderDown: number, orderUp: number) => async ({ next }: { next?: NextFn }) => {
await delay(10);
middlewareCount += 1;
assert.equal(middlewareCount, orderDown);
if (next !== undefined) {
await next();
}
middlewareCount += 1;
assert.equal(middlewareCount, orderUp);
};
app.use(assertOrderMiddleware(1, 8));
app.message(message, assertOrderMiddleware(3, 6), assertOrderMiddleware(4, 5));
app.use(assertOrderMiddleware(2, 7));
app.error(fakeErrorHandler);
await fakeReceiver.sendEvent({
...dummyReceiverEvent,
body: {
type: 'event_callback',
event: {
type: 'message',
text: message,
},
},
});
assert.equal(middlewareCount, 8);
assert(fakeErrorHandler.notCalled);
});
it('should, on error, call the global error handler, not extended', async () => {
const error = new Error('Everything is broke, you probably should restart, if not then good luck');
app.use(() => {
throw error;
});
app.error(async (codedError: CodedError) => {
assert.instanceOf(codedError, UnknownError);
assert.equal(codedError.message, error.message);
});
await fakeReceiver.sendEvent(dummyReceiverEvent);
});
it('should, on error, call the global error handler, extended', async () => {
const error = new Error('Everything is broke, you probably should restart, if not then good luck');
// Need to change value of private property for testing purposes
// Accessing through bracket notation because it is private
// eslint-disable-next-line @typescript-eslint/dot-notation
app['extendedErrorHandler'] = true;
app.use(() => {
throw error;
});
app.error(async (args: ExtendedErrorHandlerArgs) => {
assert.property(args, 'error');
assert.property(args, 'body');
assert.property(args, 'context');
assert.property(args, 'logger');
assert.isDefined(args.error);
assert.isDefined(args.body);
assert.isDefined(args.context);
assert.isDefined(args.logger);
assert.equal(args.error.message, error.message);
});
await fakeReceiver.sendEvent(dummyReceiverEvent);
// Need to change value of private property for testing purposes
// Accessing through bracket notation because it is private
// eslint-disable-next-line @typescript-eslint/dot-notation
app['extendedErrorHandler'] = false;
});
it('with a default global error handler, rejects App#ProcessEvent', async () => {
const error = new Error('The worst has happened, bot is beyond saving, always hug servers');
let actualError;
app.use(() => {
throw error;
});
try {
await fakeReceiver.sendEvent(dummyReceiverEvent);
} catch (err: any) {
actualError = err;
}
assert.instanceOf(actualError, UnknownError);
assert.equal(actualError.message, error.message);
});
});
describe('listener middleware', () => {
let app: App;
const eventType = 'some_event_type';
const dummyReceiverEvent = createDummyReceiverEvent(eventType);
beforeEach(async () => {
const MockAppNoOverrides = await importApp();
app = new MockAppNoOverrides({
receiver: fakeReceiver,
authorize: sinon.fake.resolves(dummyAuthorizationResult),
});
app.error(fakeErrorHandler);
});
it('should bubble up errors in listeners to the global error handler', async () => {
// Arrange
const errorToThrow = new Error('listener error');
// Act
app.event(eventType, async () => {
throw errorToThrow;
});
await fakeReceiver.sendEvent(dummyReceiverEvent);
// Assert
assert(fakeErrorHandler.calledOnce);
const error = fakeErrorHandler.firstCall.args[0];
assert.equal(error.code, ErrorCode.UnknownError);
assert.equal(error.original, errorToThrow);
});
it('should aggregate multiple errors in listeners for the same incoming event', async () => {
// Arrange
const errorsToThrow = [new Error('first listener error'), new Error('second listener error')];
function createThrowingListener(toBeThrown: Error): () => Promise<void> {
return async () => {
throw toBeThrown;
};
}
// Act
app.event(eventType, createThrowingListener(errorsToThrow[0]));
app.event(eventType, createThrowingListener(errorsToThrow[1]));
await fakeReceiver.sendEvent(dummyReceiverEvent);
// Assert
assert(fakeErrorHandler.calledOnce);
const error = fakeErrorHandler.firstCall.args[0];
assert.ok(isCodedError(error));
assert(error.code === ErrorCode.MultipleListenerError);
assert.isArray(error.originals);
if (error.originals) assert.sameMembers(error.originals, errorsToThrow);
});
it('should detect invalid event names', async () => {
app.event('app_mention', async () => {});
app.event('message', async () => {});
assert.throws(() => app.event('message.channels', async () => {}), 'Although the document mentions');
assert.throws(() => app.event(/message\..+/, async () => {}), 'Although the document mentions');
});
});
describe('middleware and listener arguments', () => {
let overrides: Override;
function buildOverrides(secondOverrides: Override[]): Override {
overrides = mergeOverrides(
withNoopAppMetadata(),
...secondOverrides,
withMemoryStore(sinon.fake()),
withConversationContext(sinon.fake.returns(noopMiddleware)),
);
return overrides;
}
describe('authorize', () => {
it('should extract valid enterprise_id in a shared channel #935', async () => {
// Arrange
const fakeAxiosPost = sinon.fake.resolves({});
overrides = buildOverrides([withNoopWebClient(), withAxiosPost(fakeAxiosPost)]);
const MockApp = await importApp(overrides);
// Act
let workedAsExpected = false;
const app = new MockApp({
receiver: fakeReceiver,
authorize: async ({ enterpriseId }) => {
if (enterpriseId !== undefined) {
throw new Error('the enterprise_id must be undefined in this scenario');
}
return dummyAuthorizationResult;
},
});
app.event('message', async () => {
workedAsExpected = true;
});
await fakeReceiver.sendEvent({
ack: noop,
body: {
team_id: 'T_connected_grid_workspace',
enterprise_id: 'E_org_id',
api_app_id: 'A111',
event: {
type: 'message',
text: ':wave: Hi, this is my first message in a Slack Connect channel!',
user: 'U111',
ts: '1622099033.001500',
team: 'T_this_non_grid_workspace',
channel: 'C111',
channel_type: 'channel',
},
type: 'event_callback',
authorizations: [
{
enterprise_id: null,
team_id: 'T_this_non_grid_workspace',
user_id: 'U_authed_user',
is_bot: true,
is_enterprise_install: false,
},
],
is_ext_shared_channel: true,
event_context: '2-message-T_connected_grid_workspace-A111-C111',
},
});
// Assert
assert.isTrue(workedAsExpected);
});
it('should be skipped for tokens_revoked events #674', async () => {
// Arrange
const fakeAxiosPost = sinon.fake.resolves({});
overrides = buildOverrides([withNoopWebClient(), withAxiosPost(fakeAxiosPost)]);
const MockApp = await importApp(overrides);
// Act
let workedAsExpected = false;
let authorizeCallCount = 0;
const app = new MockApp({
receiver: fakeReceiver,
authorize: async () => {
authorizeCallCount += 1;
return {};
},
});
app.event('tokens_revoked', async () => {
workedAsExpected = true;
});
// The authorize must be called for other events
await fakeReceiver.sendEvent({
ack: noop,
body: {
enterprise_id: 'E_org_id',
api_app_id: 'A111',
event: {
type: 'app_mention',
},
type: 'event_callback',
},
});
assert.equal(authorizeCallCount, 1);
await fakeReceiver.sendEvent({
ack: noop,
body: {
enterprise_id: 'E_org_id',
api_app_id: 'A111',
event: {
type: 'tokens_revoked',
tokens: {
oauth: ['P'],
bot: ['B'],
},
},
type: 'event_callback',
},
});
// Assert
assert.equal(authorizeCallCount, 1); // still 1
assert.isTrue(workedAsExpected);
});
it('should be skipped for app_uninstalled events #674', async () => {
// Arrange
const fakeAxiosPost = sinon.fake.resolves({});
overrides = buildOverrides([withNoopWebClient(), withAxiosPost(fakeAxiosPost)]);
const MockApp = await importApp(overrides);
// Act
let workedAsExpected = false;
let authorizeCallCount = 0;
const app = new MockApp({
receiver: fakeReceiver,
authorize: async () => {
authorizeCallCount += 1;
return {};
},
});
app.event('app_uninstalled', async () => {
workedAsExpected = true;
});
// The authorize must be called for other events
await fakeReceiver.sendEvent({
ack: noop,
body: {
enterprise_id: 'E_org_id',
api_app_id: 'A111',
event: {
type: 'app_mention',
},
type: 'event_callback',
},
});
assert.equal(authorizeCallCount, 1);
await fakeReceiver.sendEvent({
ack: noop,
body: {
enterprise_id: 'E_org_id',
api_app_id: 'A111',
event: {
type: 'app_uninstalled',
},
type: 'event_callback',
},
});
// Assert
assert.equal(authorizeCallCount, 1); // still 1
assert.isTrue(workedAsExpected);
});
});
});
});
/* Testing Harness */
// Loading the system under test using overrides
async function importApp(
overrides: Override = mergeOverrides(withNoopAppMetadata(), withNoopWebClient()),
): Promise<typeof import('./App').default> {
return (await rewiremock.module(() => import('./App'), overrides)).default;
}
// Composable overrides
function withNoopWebClient(): Override {
return {
'@slack/web-api': {
WebClient: class {},
},
};
}
function withNoopAppMetadata(): Override {
return {
'@slack/web-api': {
addAppMetadata: sinon.fake(),
},
};
}
function withMemoryStore(spy: SinonSpy): Override {
return {
'./conversation-store': {
MemoryStore: spy,
},
};
}
function withConversationContext(spy: SinonSpy): Override {
return {
'./conversation-store': {
conversationContext: spy,
},
};
}
function withAxiosPost(spy: SinonSpy): Override {
return {
axios: {
create: () => ({
post: spy,
}),
},
};
}