-
Notifications
You must be signed in to change notification settings - Fork 282
/
Copy pathbotFrameworkAdapter.test.js
2108 lines (1753 loc) · 85.8 KB
/
botFrameworkAdapter.test.js
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const assert = require('assert');
const nock = require('nock');
const os = require('os');
const pjson = require('../package.json');
const sinon = require('sinon');
const { BotFrameworkAdapter } = require('../');
const { Conversations } = require('botframework-connector/lib/connectorApi/operations');
const { UserToken, BotSignIn } = require('botframework-connector/lib/tokenApi/operations');
const { userAgentPolicy, HttpHeaders } = require('@azure/core-http');
const {
ActivityTypes,
CallerIdConstants,
Channels,
DeliveryModes,
StatusCodes,
TurnContext,
} = require('botbuilder-core');
const connector = require('botframework-connector');
const {
AuthenticationConstants,
CertificateAppCredentials,
ClaimsIdentity,
ConnectorClient,
GovernmentConstants,
JwtTokenValidation,
MicrosoftAppCredentials,
ChannelValidation,
GovernmentChannelValidation,
} = require('botframework-connector');
const reference = {
activityId: '1234',
channelId: 'test',
serviceUrl: 'https://example.org/channel',
user: { id: 'user', name: 'User Name' },
bot: { id: 'bot', name: 'Bot Name' },
conversation: {
id: 'convo1',
properties: {
foo: 'bar',
},
},
};
const incomingMessage = TurnContext.applyConversationReference({ text: 'test', type: 'message' }, reference, true);
const outgoingMessage = TurnContext.applyConversationReference({ text: 'test', type: 'message' }, reference);
const incomingInvoke = TurnContext.applyConversationReference({ type: 'invoke' }, reference, true);
const testTraceMessage = {
type: 'trace',
name: 'TestTrace',
valueType: 'https://example.org/test/trace',
label: 'Test Trace',
};
class AdapterUnderTest extends BotFrameworkAdapter {
constructor(settings, { failAuth = false, failOperation = false, expectAuthHeader = '', newServiceUrl } = {}) {
super(settings);
this.failAuth = failAuth;
this.failOperation = failOperation;
this.expectAuthHeader = expectAuthHeader;
this.newServiceUrl = newServiceUrl;
}
getOAuthScope() {
return this.credentials.oAuthScope;
}
async testAuthenticateRequest(request, authHeader) {
const claims = await super.authenticateRequestInternal(request, authHeader);
if (!claims.isAuthenticated) {
throw new Error('Unauthorized Access. Request is not authorized');
}
}
testCreateConnectorClient(serviceUrl) {
return super.createConnectorClient(serviceUrl);
}
authenticateRequest(request, authHeader) {
return this.authenticateRequestInternal.bind(this)(request, authHeader);
}
authenticateRequestInternal(request, authHeader) {
assert(request, 'authenticateRequestInternal() not passed request.');
assert.strictEqual(
authHeader,
this.expectAuthHeader,
'authenticateRequestInternal() not passed expected authHeader.',
);
return this.failAuth ? Promise.reject(new Error('failed auth')) : Promise.resolve({ claims: [] });
}
createConnectorClient(serviceUrl) {
assert(serviceUrl, 'createConnectorClient() not passed serviceUrl.');
return this.mockConnectorClient.bind(this)();
}
createConnectorClientWithIdentity(serviceUrl, identity) {
assert(serviceUrl, 'createConnectorClientWithIdentity() not passed serviceUrl.');
assert(identity, 'createConnectorClientWithIdentity() not passed identity.');
return this.mockConnectorClient.bind(this)();
}
createConnectorClientInternal(serviceUrl, credentials) {
assert(serviceUrl, 'createConnectorClientInternal() not passed serviceUrl.');
assert(credentials, 'createConnectorClientInternal() not passed credentials.');
return this.mockConnectorClient.bind(this)();
}
getOrCreateConnectorClient(context, serviceUrl, credentials) {
assert(context, 'createConnectorClient() not passed context.');
assert(serviceUrl, 'createConnectorClient() not passed serviceUrl.');
assert(credentials, 'createConnectorClient() not passed credentials.');
return this.mockConnectorClient.bind(this)();
}
mockConnectorClient() {
return {
conversations: {
replyToActivity: (conversationId, activityId, activity) => {
assert(conversationId, 'replyToActivity() not passed conversationId.');
assert(activityId, 'replyToActivity() not passed activityId.');
assert(activity, 'replyToActivity() not passed activity.');
return this.failOperation ? Promise.reject(new Error('failed')) : Promise.resolve({ id: '5678' });
},
sendToConversation: (conversationId, activity) => {
assert(conversationId, 'sendToConversation() not passed conversationId.');
assert(activity, 'sendToConversation() not passed activity.');
return this.failOperation ? Promise.reject(new Error('failed')) : Promise.resolve({ id: '5678' });
},
updateActivity: (conversationId, activityId, activity) => {
assert(conversationId, 'updateActivity() not passed conversationId.');
assert(activityId, 'updateActivity() not passed activityId.');
assert(activity, 'updateActivity() not passed activity.');
return this.failOperation ? Promise.reject(new Error('failed')) : Promise.resolve({ id: '5678' });
},
deleteActivity: (conversationId, activityId) => {
assert(conversationId, 'deleteActivity() not passed conversationId.');
assert(activityId, 'deleteActivity() not passed activityId.');
return this.failOperation ? Promise.reject(new Error('failed')) : Promise.resolve();
},
createConversation: (parameters) => {
assert(parameters, 'createConversation() not passed parameters.');
return this.failOperation
? Promise.reject(new Error('failed'))
: Promise.resolve({ id: 'convo2', serviceUrl: this.newServiceUrl });
},
},
};
}
}
class MockRequest {
constructor(body, headers) {
this.data = JSON.stringify(body);
this.headers = headers || {};
}
on(event, handler) {
switch (event) {
case 'data':
handler(this.data);
break;
case 'end':
handler();
break;
}
}
}
class MockBodyRequest {
constructor(body, headers) {
this.body = body;
this.headers = headers || {};
}
on() {
assert.fail('unexpected call to request.on()');
}
}
class MockResponse {
constructor() {
this.ended = false;
this.statusCode = undefined;
this.body = undefined;
}
status(status) {
this.statusCode = status;
}
send(body) {
assert(!this.ended, 'response.send() called after response.end().');
this.body = body;
}
end() {
assert(!this.ended, 'response.end() called twice.');
assert.notStrictEqual(this.statusCode, undefined, 'response.end() called before response.send().');
this.ended = true;
}
}
class MockConnector extends ConnectorClient {
constructor(conversations) {
super(new MicrosoftAppCredentials('', ''));
this.conversations = conversations;
}
}
function assertResponse(res, statusCode, hasBody) {
assert(res.ended, 'response not ended.');
assert.strictEqual(res.statusCode, statusCode);
if (hasBody) {
assert(res.body, 'response missing body.');
} else {
assert.strictEqual(res.body, undefined);
}
}
function createActivity() {
const account1 = {
id: 'ChannelAccount_Id_1',
name: 'ChannelAccount_Name_1',
role: 'ChannelAccount_Role_1',
};
const account2 = {
id: 'ChannelAccount_Id_2',
name: 'ChannelAccount_Name_2',
role: 'ChannelAccount_Role_2',
};
const conversationAccount = {
conversationType: 'a',
id: '123',
isGroup: true,
name: 'Name',
role: 'ConversationAccount_Role',
};
return {
id: '123',
from: account1,
recipient: account2,
conversation: conversationAccount,
channelId: 'ChannelId123',
locale: 'en-uS', // Intentionally oddly-cased to check that it isn't defaulted somewhere, but tests stay in English
serviceUrl: 'ServiceUrl123',
};
}
describe('BotFrameworkAdapter', function () {
let sandbox;
beforeEach(function () {
sandbox = sinon.createSandbox();
});
afterEach(function () {
sandbox.restore();
});
const mockReturns = (obj, method, returns) => sandbox.mock(obj).expects(method).returns(returns).once();
const mockResponse = (obj, method, status = 200, parsedBody) =>
mockReturns(obj, method, { _response: { status, parsedBody } });
const processActivity = async (logic, { activity = incomingMessage, adapterArgs, testAdapterArgs } = {}) => {
const request = new MockRequest(activity);
const response = new MockResponse();
const adapter = new AdapterUnderTest(adapterArgs, testAdapterArgs);
const fake = sandbox.fake(logic);
try {
await adapter.processActivity(request, response, fake);
return { fake, response, verify: () => assert(fake.called, 'bot logic not called') };
} catch (err) {
err.fake = fake;
err.response = response;
throw err;
}
};
describe('constructor()', function () {
it('should use CertificateAppCredentials when certificateThumbprint and certificatePrivateKey are provided', function () {
const certificatePrivateKey = 'key';
const certificateThumbprint = 'thumbprint';
const appId = '11111111-7777-8888-9999-333333333333';
const adapter = new BotFrameworkAdapter({ appId, certificatePrivateKey, certificateThumbprint });
assert(adapter.credentials instanceof CertificateAppCredentials);
assert.strictEqual(adapter.credentials.appId, appId);
assert.strictEqual(adapter.credentials.certificatePrivateKey, certificatePrivateKey);
assert.strictEqual(adapter.credentials.certificateThumbprint, certificateThumbprint);
assert.strictEqual(adapter.settings.appId, appId);
assert.strictEqual(adapter.settings.appPassword, '');
});
it('should use CertificateAppCredentials over MicrosoftAppCredentials when certificateThumbprint and certificatePrivateKey are provided', function () {
const certificatePrivateKey = 'key';
const certificateThumbprint = 'thumbprint';
const appId = '11111111-7777-8888-9999-333333333333';
const appPassword = 'password';
const adapter = new BotFrameworkAdapter({
appId,
certificatePrivateKey,
certificateThumbprint,
appPassword,
});
assert(adapter.credentials instanceof CertificateAppCredentials);
assert.strictEqual(adapter.credentials.appId, appId);
assert.strictEqual(adapter.credentials.certificatePrivateKey, certificatePrivateKey);
assert.strictEqual(adapter.credentials.certificateThumbprint, certificateThumbprint);
// adapter.credentialsProvider should have an empty string for a password.
assert.strictEqual(adapter.credentialsProvider.appPassword, '');
// appPassword should still be stored in BotFrameworkAdapter.settings through the spread syntax.
assert.strictEqual(adapter.settings.appPassword, appPassword);
});
it('should read ChannelService and BotOpenIdMetadata env var if they exist', function () {
process.env.ChannelService = 'https://botframework.azure.us';
process.env.BotOpenIdMetadata = 'https://someEndpoint.com';
const adapter = new AdapterUnderTest();
assert.strictEqual(adapter.settings.channelService, 'https://botframework.azure.us');
assert.strictEqual(adapter.settings.openIdMetadata, 'https://someEndpoint.com');
delete process.env.ChannelService;
delete process.env.BotOpenIdMetadata;
});
it('should read webSocketFactory from the settings if it exists', function () {
const adapter = new AdapterUnderTest({ webSocketFactory: 'test-web-socket' });
assert.strictEqual(
adapter.webSocketFactory,
'test-web-socket',
'Adapter should have read settings.webSocketFactory',
);
});
});
describe('authenticateRequest()', function () {
it('should work if no appId or appPassword.', async function () {
mockReturns(JwtTokenValidation, 'authenticateRequest', new ClaimsIdentity([], true));
const req = new MockRequest(incomingMessage);
const adapter = new AdapterUnderTest();
await adapter.testAuthenticateRequest(req, '');
sandbox.verify();
});
it('should work if no appId or appPassword and discard callerId', async function () {
mockReturns(JwtTokenValidation, 'authenticateRequest', new ClaimsIdentity([], true));
// Create activity with callerId
const incoming = TurnContext.applyConversationReference(
{ type: 'message', text: 'foo', callerId: 'foo' },
reference,
true,
);
incoming.channelId = 'msteams';
// Create Adapter, stub and spy for indirectly called methods
const adapter = new BotFrameworkAdapter();
await adapter.authenticateRequest(incoming, 'authHeader');
assert.strictEqual(incoming.callerId, undefined);
sandbox.verify();
});
it('should stamp over received callerId', async function () {
mockReturns(JwtTokenValidation, 'authenticateRequest', new ClaimsIdentity([], true));
// Create activity with callerId
const incoming = TurnContext.applyConversationReference(
{ type: 'message', text: 'foo', callerId: 'foo' },
reference,
true,
);
incoming.channelId = 'msteams';
// Create Adapter, stub and spy for indirectly called methods
const adapter = new BotFrameworkAdapter();
mockReturns(adapter.credentialsProvider, 'isAuthenticationDisabled', Promise.resolve(false));
await adapter.authenticateRequest(incoming, 'authHeader');
assert.strictEqual(incoming.callerId, CallerIdConstants.PublicAzureChannel);
sandbox.verify();
});
it('should fail if appId+appPassword and no headers.', async function () {
const req = new MockRequest(incomingMessage);
const adapter = new AdapterUnderTest({ appId: 'bogusApp', appPassword: 'bogusPassword' });
await assert.rejects(
adapter.testAuthenticateRequest(req, ''),
new Error('Unauthorized Access. Request is not authorized'),
);
});
});
describe('buildCredentials()', function () {
it('should return credentials with correct parameters', async function () {
const adapter = new BotFrameworkAdapter({ appId: 'appId', appPassword: 'appPassword' });
const creds = await adapter.buildCredentials('appId', 'scope');
assert.strictEqual(creds.appId, 'appId');
assert.strictEqual(creds.appPassword, 'appPassword');
assert.strictEqual(creds.oAuthScope, 'scope');
});
it('should return credentials with default public Azure values', async function () {
const adapter = new BotFrameworkAdapter({ appId: 'appId', appPassword: 'appPassword' });
const creds = await adapter.buildCredentials('appId');
assert.strictEqual(creds.appId, 'appId');
assert.strictEqual(creds.appPassword, 'appPassword');
assert.strictEqual(creds.oAuthScope, AuthenticationConstants.ToBotFromChannelTokenIssuer);
const oAuthEndpoint =
AuthenticationConstants.ToChannelFromBotLoginUrlPrefix +
AuthenticationConstants.DefaultChannelAuthTenant;
assert.strictEqual(creds.oAuthEndpoint, oAuthEndpoint);
});
});
describe('get/create ConnectorClient methods', function () {
it('should createConnectorClient().', function () {
const adapter = new AdapterUnderTest();
const client = adapter.testCreateConnectorClient(reference.serviceUrl);
assert(client, 'client not returned.');
assert(client.conversations, 'invalid client returned.');
});
it('getOrCreateConnectorClient should create a new client if the cached serviceUrl does not match the provided one', function () {
const adapter = new BotFrameworkAdapter();
const context = new TurnContext(adapter, {
type: ActivityTypes.Message,
text: 'hello',
serviceUrl: 'http://bing.com',
});
const cc = new ConnectorClient(new MicrosoftAppCredentials('', ''), { baseUri: 'http://bing.com' });
context.turnState.set(adapter.ConnectorClientKey, cc);
const client = adapter.getOrCreateConnectorClient(context, 'https://botframework.com', adapter.credentials);
assert.notStrictEqual(client.baseUri, cc.baseUri);
});
it('ConnectorClient should add userAgent header from clientOptions', async function () {
const userAgent = 'test user agent';
nock(reference.serviceUrl)
.matchHeader('user-agent', ([val]) => val.endsWith(userAgent))
.post('/v3/conversations/convo1/activities/1234')
.reply(200, { id: 'abc123id' });
const adapter = new BotFrameworkAdapter({ clientOptions: { userAgent } });
await adapter.continueConversation(reference, async (turnContext) => {
await turnContext.sendActivity(outgoingMessage);
});
});
it('ConnectorClient should use httpClient from clientOptions', async function () {
const outgoingMessageLocale = JSON.parse(JSON.stringify(outgoingMessage));
outgoingMessageLocale.locale = 'en-uS'; // Intentionally oddly-cased to check that it isn't defaulted somewhere, but tests stay in English
const sendRequest = sandbox.fake((request) =>
Promise.resolve({
request,
status: 200,
headers: new HttpHeaders(),
readableStreamBody: undefined,
bodyAsText: '',
}),
);
const adapter = new BotFrameworkAdapter({ clientOptions: { httpClient: { sendRequest } } });
const referenceWithLocale = JSON.parse(JSON.stringify(reference));
referenceWithLocale.locale = 'en-uS'; // Intentionally oddly-cased to check that it isn't defaulted somewhere, but tests stay in English
await adapter.continueConversation(referenceWithLocale, async (turnContext) => {
await turnContext.sendActivity(outgoingMessage);
});
assert(
sendRequest.called,
'sendRequest on HttpClient provided to BotFrameworkAdapter.clientOptions was not called when sending an activity',
);
const [request] = sendRequest.args[0];
assert.deepStrictEqual(
JSON.parse(request.body),
outgoingMessageLocale,
'sentActivity should flow through custom httpClient.sendRequest',
);
});
it('ConnectorClient should use requestPolicyFactories from clientOptions', async function () {
const setUserAgent = userAgentPolicy({ value: 'test' });
const factories = [setUserAgent];
const adapter = new BotFrameworkAdapter({ clientOptions: { requestPolicyFactories: factories } });
await adapter.continueConversation(reference, async (turnContext) => {
const connectorClient = turnContext.turnState.get(turnContext.adapter.ConnectorClientKey);
assert(
connectorClient._requestPolicyFactories.find((policy) => policy === setUserAgent),
'requestPolicyFactories from clientOptions parameter is not used.',
);
});
});
it('ConnectorClient should add requestPolicyFactory for accept header', async function () {
let hasAcceptHeader = false;
const mockNextPolicy = {
create: () => ({}),
sendRequest: () => {
return {};
},
};
const client = new BotFrameworkAdapter().createConnectorClient('https://localhost');
const length = client._requestPolicyFactories.length;
for (let i = 0; i < length; i++) {
const mockHttp = {
headers: new HttpHeaders(),
};
const result = client._requestPolicyFactories[i].create(mockNextPolicy);
result.sendRequest(mockHttp);
if (mockHttp.headers.get('accept') == '*/*') {
hasAcceptHeader = true;
break;
}
}
assert(hasAcceptHeader, 'accept header from connector client should be */*');
});
it('createConnectorClientWithIdentity should throw without identity', async function () {
const adapter = new BotFrameworkAdapter();
await assert.rejects(
adapter.createConnectorClientWithIdentity('https://serviceurl.com'),
new Error('BotFrameworkAdapter.createConnectorClientWithIdentity(): invalid identity parameter.'),
);
});
it('createConnectorClientWithIdentity should use valid passed-in audience', async function () {
const adapter = new BotFrameworkAdapter();
const appId = '00000000-0000-0000-0000-000000000001';
const serviceUrl = 'https://serviceurl.com';
const audience = 'not-a-bot-or-channel';
const identity = new ClaimsIdentity([
{ type: AuthenticationConstants.AudienceClaim, value: appId },
{ type: AuthenticationConstants.VersionClaim, value: '2.0' },
]);
sandbox.mock(adapter).expects('getOAuthScope').never();
sandbox
.mock(adapter)
.expects('buildCredentials')
.callsFake((appId, oAuthScope) =>
Promise.resolve(new MicrosoftAppCredentials(appId, '', undefined, oAuthScope)),
)
.once();
const client = await adapter.createConnectorClientWithIdentity(serviceUrl, identity, audience);
sandbox.verify();
assert.strictEqual(client.credentials.appId, appId);
assert.strictEqual(client.credentials.oAuthScope, audience);
});
it('createConnectorClientWithIdentity should use claims with invalid audience', async function () {
const adapter = new BotFrameworkAdapter();
const appId = '00000000-0000-0000-0000-000000000001';
const skillAppId = '00000000-0000-0000-0000-000000000002';
const serviceUrl = 'https://serviceurl.com';
const audience = ' ';
const identity = new ClaimsIdentity([
{ type: AuthenticationConstants.AudienceClaim, value: appId },
{ type: AuthenticationConstants.VersionClaim, value: '2.0' },
{ type: AuthenticationConstants.AuthorizedParty, value: skillAppId },
]);
sandbox.mock(adapter).expects('getOAuthScope').withArgs(appId, identity.claims).once().callThrough();
sandbox
.mock(adapter)
.expects('buildCredentials')
.callsFake((appId, oAuthScope) =>
Promise.resolve(new MicrosoftAppCredentials(appId, '', undefined, oAuthScope)),
)
.once();
const client = await adapter.createConnectorClientWithIdentity(serviceUrl, identity, audience);
sandbox.verify();
assert.strictEqual(client.credentials.appId, appId);
assert.strictEqual(client.credentials.oAuthScope, skillAppId);
});
it('createConnectorClientWithIdentity should use credentials.oAuthScope with bad invalid audience and non-skill claims', async function () {
const adapter = new BotFrameworkAdapter();
const appId = '00000000-0000-0000-0000-000000000001';
const serviceUrl = 'https://serviceurl.com';
const audience = ' ';
const identity = new ClaimsIdentity([
{ type: AuthenticationConstants.AudienceClaim, value: appId },
{ type: AuthenticationConstants.VersionClaim, value: '2.0' },
]);
sandbox.mock(adapter).expects('getOAuthScope').once().callThrough();
sandbox
.mock(adapter)
.expects('buildCredentials')
.callsFake((appId, oAuthScope) =>
Promise.resolve(new MicrosoftAppCredentials(appId, '', undefined, oAuthScope)),
)
.once();
const client = await adapter.createConnectorClientWithIdentity(serviceUrl, identity, audience);
sandbox.verify();
assert.strictEqual(client.credentials.appId, appId);
assert.strictEqual(client.credentials.oAuthScope, AuthenticationConstants.ToChannelFromBotOAuthScope);
});
it('createConnectorClientWithIdentity should create a ConnectorClient with CertificateAppCredentials when certificateThumbprint and certificatePrivatekey are provided', async function () {
const appId = '01234567-4242-aaaa-bbbb-cccccccccccc';
const certificatePrivateKey = 'key';
const certificateThumbprint = 'thumbprint';
const adapter = new BotFrameworkAdapter({ appId, certificatePrivateKey, certificateThumbprint });
const connector = await adapter.createConnectorClientWithIdentity(
'https://serviceurl.com',
new ClaimsIdentity([{ type: AuthenticationConstants.AppIdClaim, value: appId }]),
);
const credentials = connector.credentials;
assert(credentials instanceof CertificateAppCredentials);
assert.strictEqual(credentials.appId, appId);
assert.strictEqual(credentials.certificatePrivateKey, certificatePrivateKey);
assert.strictEqual(credentials.certificateThumbprint, certificateThumbprint);
});
it('createConnectorClientWithIdentity should create a ConnectorClient with MicrosoftAppCredentials when certificateThumbprint and certificatePrivatekey are absent and ClaimsIdenity has AppIdClaim', async function () {
const appId = '01234567-4242-aaaa-bbbb-cccccccccccc';
// [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="This is a fake password.")]
const appPassword = 'password123';
const adapter = new BotFrameworkAdapter({ appId, appPassword });
const connector = await adapter.createConnectorClientWithIdentity(
'https://serviceurl.com',
new ClaimsIdentity([{ type: AuthenticationConstants.AppIdClaim, value: appId }]),
);
const credentials = connector.credentials;
assert(credentials instanceof MicrosoftAppCredentials);
assert.strictEqual(credentials.appId, appId);
assert.strictEqual(credentials.certificatePrivateKey, undefined);
assert.strictEqual(credentials.certificateThumbprint, undefined);
});
it('createConnectorClientWithIdentity should create a ConnectorClient with MicrosoftAppCredentials when certificateThumbprint and certificatePrivatekey are absent and ClaimsIdenity has AudienceClaim', async function () {
const appId = '01234567-4242-aaaa-bbbb-cccccccccccc';
// [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="This is a fake password.")]
const appPassword = 'password123';
const adapter = new BotFrameworkAdapter({ appId, appPassword });
const connector = await adapter.createConnectorClientWithIdentity(
'https://serviceurl.com',
new ClaimsIdentity([{ type: AuthenticationConstants.AudienceClaim, value: appId }]),
);
const credentials = connector.credentials;
assert(credentials instanceof MicrosoftAppCredentials);
assert.strictEqual(credentials.appId, appId);
assert.strictEqual(credentials.certificatePrivateKey, undefined);
assert.strictEqual(credentials.certificateThumbprint, undefined);
});
});
it("processActivity() should respect expectReplies if it's set via logic", async function () {
const { response, verify } = await processActivity(async (context) => {
context.activity.deliveryMode = 'expectReplies';
await context.sendActivity({ type: 'message', text: 'Hello Buffered World!' });
});
assertResponse(response, StatusCodes.OK, true);
verify();
});
it('processActivity() should send only bufferedActivities when both expectReplies and invoke are set', async function () {
const activity = {
...JSON.parse(JSON.stringify(incomingMessage)),
type: ActivityTypes.Invoke,
deliveryMode: DeliveryModes.ExpectReplies,
};
const { response, verify } = await processActivity(
async (context) => {
await context.sendActivity({ type: 'invokeResponse', text: '1st message' });
await context.sendActivity({ type: 'invokeResponse', text: '2nd message' });
},
{ activity },
);
assertResponse(response, StatusCodes.OK, true);
verify();
assert.deepStrictEqual(
response.body.activities.map(({ text, type }) => ({ text, type })),
[
{
text: '1st message',
type: 'invokeResponse',
},
{
text: '2nd message',
type: 'invokeResponse',
},
],
);
});
it('should remove trace activities from bufferedReplyActivities if request.channelId !== Channels.Emulator', async function () {
const activity = {
...JSON.parse(JSON.stringify(incomingMessage)),
type: ActivityTypes.Invoke,
deliveryMode: DeliveryModes.ExpectReplies,
channelId: Channels.Msteams,
};
const { response, verify } = await processActivity(
async (context) => {
await context.sendActivity({ type: 'invokeResponse', text: 'message' });
await context.sendActivity(testTraceMessage);
},
{ activity },
);
assertResponse(response, StatusCodes.OK, true);
verify();
assert.deepStrictEqual(
response.body.activities.map(({ text, type }) => ({ text, type })),
[
{
text: 'message',
type: 'invokeResponse',
},
],
);
});
it('should keep trace activities from bufferedReplyActivities if request.channelId === Channels.Emulator', async function () {
const activity = {
...JSON.parse(JSON.stringify(incomingMessage)),
type: ActivityTypes.Invoke,
deliveryMode: DeliveryModes.ExpectReplies,
channelId: Channels.Emulator,
};
const { response, verify } = await processActivity(
async (context) => {
await context.sendActivity({ type: 'invokeResponse', text: 'message' });
await context.sendActivity(testTraceMessage);
},
{ activity },
);
assertResponse(response, StatusCodes.OK, true);
verify();
assert.deepStrictEqual(
response.body.activities.map(({ type }) => type),
['invokeResponse', 'trace'],
);
});
it('processActivity() should not respect invokeResponses if the incoming request wasn\'t of type "invoke"', async function () {
const { response, verify } = await processActivity(async (context) => {
await context.sendActivity({ type: 'invokeResponse', text: 'InvokeResponse Test' });
});
assertResponse(response, StatusCodes.OK, false);
verify();
});
it('should processActivity().', async function () {
const { response, verify } = await processActivity((context) => {
assert(context, 'context not passed.');
});
assertResponse(response, StatusCodes.OK);
verify();
});
it('should processActivity() sent as body.', async function () {
const { response, verify } = await processActivity((context) => {
assert(context, 'context not passed.');
});
assertResponse(response, StatusCodes.OK);
verify();
});
it('should check timestamp in processActivity() sent as body.', async function () {
const activity = {
...incomingMessage,
timestamp: '2018-10-01T14:14:54.790Z',
localTimestamp: '2018-10-01T14:14:54.790Z',
};
const { response, verify } = await processActivity(
(context) => {
assert(context, 'context not passed.');
assert.strictEqual(
typeof context.activity.timestamp,
'object',
"'context.activity.timestamp' is not a date",
);
assert(context.activity.timestamp instanceof Date, "'context.activity.timestamp' is not a date");
assert.strictEqual(
typeof context.activity.localTimestamp,
'object',
"'context.activity.localTimestamp' is not a date",
);
assert(
context.activity.localTimestamp instanceof Date,
"'context.activity.localTimestamp' is not a date",
);
},
{ activity },
);
assertResponse(response, StatusCodes.OK);
verify();
});
it('should reject a bogus request sent to processActivity().', async function () {
await assert.rejects(
processActivity(() => null, { activity: 'bogus' }),
(err) => {
const { fake, response } = err;
assert(!fake.called);
assertResponse(response, 400, true);
return true;
},
);
});
it('should reject a request without activity type sent to processActivity().', async function () {
await assert.rejects(
processActivity(() => null, { activity: { text: 'foo' } }),
(err) => {
const { fake, response } = err;
assert(!fake.called);
assertResponse(response, 400, true);
return true;
},
);
});
it('should migrate location of tenantId for MS Teams processActivity().', async function () {
const activity = TurnContext.applyConversationReference(
{ type: 'message', text: 'foo', channelData: { tenant: { id: '1234' } } },
reference,
true,
);
activity.channelId = 'msteams';
const { response, verify } = await processActivity(
(context) => {
assert.strictEqual(
context.activity.conversation.tenantId,
'1234',
'should have copied tenant id from channelData to conversation address',
);
},
{ activity },
);
assertResponse(response, StatusCodes.OK);
verify();
});
it('receive a semanticAction with a state property on the activity in processActivity().', async function () {
const activity = TurnContext.applyConversationReference(
{ type: 'message', text: 'foo', semanticAction: { state: 'start' } },
reference,
true,
);
activity.channelId = 'msteams';
const { response, verify } = await processActivity(
(context) => {
assert(context.activity.semanticAction.state === 'start');
},
{ activity },
);
assertResponse(response, StatusCodes.OK);
verify();
});
describe('callerId generation', function () {
const processIncoming = async (
incoming,
handler,
{ adapterArgs = {}, authDisabled = false, claims = [] } = {},
) => {
// Sets up expectation for JWT validation to pass back claims
mockReturns(JwtTokenValidation, 'authenticateRequest', new ClaimsIdentity(claims, true));
const adapter = new BotFrameworkAdapter(adapterArgs);
// Sets up expectation for whether auth is enabled or disabled
mockReturns(adapter.credentialsProvider, 'isAuthenticationDisabled', Promise.resolve(authDisabled));
// Ensures that generateCalledId is invoked
sandbox.mock(adapter).expects('generateCallerId').once().callThrough();
// Construct the things, invoke processActivity
const fake = sandbox.fake(handler);
const req = new MockBodyRequest(incoming);
const res = new MockResponse();
await adapter.processActivity(req, res, fake);
// Ensure expectations were met and handler was called
sandbox.verify();
assertResponse(res, StatusCodes.OK);
assert(fake.called, 'bot handler was not called');
};
it('should ignore received and generate callerId on parsed activity in processActivity()', async function () {
const incoming = TurnContext.applyConversationReference(
{ type: 'message', text: 'foo', callerId: 'foo' },
reference,
true,
);
incoming.channelId = 'msteams';
await processIncoming(incoming, (context) => {
assert.strictEqual(context.activity.callerId, CallerIdConstants.PublicAzureChannel);
});
});
it('should generate a skill callerId property on the activity in processActivity()', async function () {
const skillAppId = '00000000-0000-0000-0000-000000000000';
const skillConsumerAppId = '00000000-0000-0000-0000-000000000001';
const incoming = TurnContext.applyConversationReference({ type: 'message', text: 'foo' }, reference, true);
incoming.channelId = 'msteams';
await processIncoming(
incoming,
(context) => {
assert.strictEqual(
context.activity.callerId,
`${CallerIdConstants.BotToBotPrefix}${skillConsumerAppId}`,
);
},
{
claims: [
{ type: AuthenticationConstants.AudienceClaim, value: skillAppId },
{ type: AuthenticationConstants.AppIdClaim, value: skillConsumerAppId },
{ type: AuthenticationConstants.VersionClaim, value: '1.0' },
],
},
);