-
Notifications
You must be signed in to change notification settings - Fork 182
/
ConnectionService.test.ts
1059 lines (875 loc) · 40.3 KB
/
ConnectionService.test.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
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
import type { AgentContext } from '../../../agent'
import type { Wallet } from '../../../wallet/Wallet'
import type { DidDocument } from '../../dids'
import type { Routing } from '../services/ConnectionService'
import { Subject } from 'rxjs'
import { IndySdkWallet } from '../../../../../indy-sdk/src'
import { indySdk } from '../../../../../indy-sdk/tests/setupIndySdkModule'
import {
getAgentConfig,
getAgentContext,
getMockConnection,
getMockOutOfBand,
mockFunction,
} from '../../../../tests/helpers'
import { AgentMessage } from '../../../agent/AgentMessage'
import { EventEmitter } from '../../../agent/EventEmitter'
import { InboundMessageContext } from '../../../agent/models/InboundMessageContext'
import { Key, KeyType } from '../../../crypto'
import { SigningProviderRegistry } from '../../../crypto/signing-provider'
import { signData, unpackAndVerifySignatureDecorator } from '../../../decorators/signature/SignatureDecoratorUtils'
import { JsonTransformer } from '../../../utils/JsonTransformer'
import { indyDidFromPublicKeyBase58 } from '../../../utils/did'
import { uuid } from '../../../utils/uuid'
import { AckMessage, AckStatus } from '../../common'
import { DidKey, IndyAgentService } from '../../dids'
import { DidDocumentRole } from '../../dids/domain/DidDocumentRole'
import { DidCommV1Service } from '../../dids/domain/service/DidCommV1Service'
import { didDocumentJsonToNumAlgo1Did } from '../../dids/methods/peer/peerDidNumAlgo1'
import { DidRecord, DidRepository } from '../../dids/repository'
import { DidRegistrarService } from '../../dids/services/DidRegistrarService'
import { OutOfBandService } from '../../oob/OutOfBandService'
import { OutOfBandRole } from '../../oob/domain/OutOfBandRole'
import { OutOfBandState } from '../../oob/domain/OutOfBandState'
import { OutOfBandRepository } from '../../oob/repository/OutOfBandRepository'
import { ConnectionRequestMessage, ConnectionResponseMessage, TrustPingMessage } from '../messages'
import {
Connection,
DidDoc,
EmbeddedAuthentication,
Ed25119Sig2018,
DidExchangeRole,
DidExchangeState,
ReferencedAuthentication,
authenticationTypes,
} from '../models'
import { ConnectionRepository } from '../repository/ConnectionRepository'
import { ConnectionService } from '../services/ConnectionService'
import { convertToNewDidDocument } from '../services/helpers'
jest.mock('../repository/ConnectionRepository')
jest.mock('../../oob/repository/OutOfBandRepository')
jest.mock('../../oob/OutOfBandService')
jest.mock('../../dids/services/DidRegistrarService')
jest.mock('../../dids/repository/DidRepository')
const ConnectionRepositoryMock = ConnectionRepository as jest.Mock<ConnectionRepository>
const OutOfBandRepositoryMock = OutOfBandRepository as jest.Mock<OutOfBandRepository>
const OutOfBandServiceMock = OutOfBandService as jest.Mock<OutOfBandService>
const DidRepositoryMock = DidRepository as jest.Mock<DidRepository>
const DidRegistrarServiceMock = DidRegistrarService as jest.Mock<DidRegistrarService>
const didRegistrarService = new DidRegistrarServiceMock()
mockFunction(didRegistrarService.create).mockResolvedValue({
didDocumentMetadata: {},
didRegistrationMetadata: {},
didState: {
state: 'finished',
did: 'did:peer:123',
didDocument: {} as DidDocument,
},
})
const connectionImageUrl = 'https://example.com/image.png'
const agentConfig = getAgentConfig('ConnectionServiceTest', {
endpoints: ['http://agent.com:8080'],
connectionImageUrl,
})
const outOfBandRepository = new OutOfBandRepositoryMock()
const outOfBandService = new OutOfBandServiceMock()
describe('ConnectionService', () => {
let wallet: Wallet
let connectionRepository: ConnectionRepository
let didRepository: DidRepository
let connectionService: ConnectionService
let eventEmitter: EventEmitter
let myRouting: Routing
let agentContext: AgentContext
beforeAll(async () => {
wallet = new IndySdkWallet(indySdk, agentConfig.logger, new SigningProviderRegistry([]))
agentContext = getAgentContext({
wallet,
agentConfig,
registerInstances: [
[OutOfBandRepository, outOfBandRepository],
[OutOfBandService, outOfBandService],
],
})
await wallet.createAndOpen(agentConfig.walletConfig)
})
afterAll(async () => {
await wallet.delete()
})
beforeEach(async () => {
eventEmitter = new EventEmitter(agentConfig.agentDependencies, new Subject())
connectionRepository = new ConnectionRepositoryMock()
didRepository = new DidRepositoryMock()
connectionService = new ConnectionService(agentConfig.logger, connectionRepository, didRepository, eventEmitter)
myRouting = {
recipientKey: Key.fromFingerprint('z6MkwFkSP4uv5PhhKJCGehtjuZedkotC7VF64xtMsxuM8R3W'),
endpoints: agentConfig.endpoints ?? [],
routingKeys: [],
mediatorId: 'fakeMediatorId',
}
mockFunction(didRepository.getById).mockResolvedValue(
new DidRecord({
did: 'did:peer:123',
role: DidDocumentRole.Created,
})
)
})
describe('createRequest', () => {
it('returns a connection request message containing the information from the connection record', async () => {
expect.assertions(5)
const outOfBand = getMockOutOfBand({ state: OutOfBandState.PrepareResponse })
const config = { routing: myRouting }
const { connectionRecord, message } = await connectionService.createRequest(agentContext, outOfBand, config)
expect(connectionRecord.state).toBe(DidExchangeState.RequestSent)
expect(message.label).toBe(agentConfig.label)
expect(message.connection.did).toBe('XpwgBjsC2wh3eHcMW6ZRJT')
const publicKey = new Ed25119Sig2018({
id: `XpwgBjsC2wh3eHcMW6ZRJT#1`,
controller: 'XpwgBjsC2wh3eHcMW6ZRJT',
publicKeyBase58: 'HoVPnpfUjrDECoMZy8vu4U6dwEcLhbzjNwyS3gwLDCG8',
})
expect(message.connection.didDoc).toEqual(
new DidDoc({
id: 'XpwgBjsC2wh3eHcMW6ZRJT',
publicKey: [publicKey],
authentication: [new ReferencedAuthentication(publicKey, authenticationTypes.Ed25519VerificationKey2018)],
service: [
new IndyAgentService({
id: `XpwgBjsC2wh3eHcMW6ZRJT#IndyAgentService-1`,
serviceEndpoint: agentConfig.endpoints[0],
recipientKeys: ['HoVPnpfUjrDECoMZy8vu4U6dwEcLhbzjNwyS3gwLDCG8'],
routingKeys: [],
}),
],
})
)
expect(message.imageUrl).toBe(connectionImageUrl)
})
it('returns a connection request message containing a custom label', async () => {
expect.assertions(1)
const outOfBand = getMockOutOfBand({ state: OutOfBandState.PrepareResponse })
const config = { label: 'Custom label', routing: myRouting }
const { message } = await connectionService.createRequest(agentContext, outOfBand, config)
expect(message.label).toBe('Custom label')
})
it('returns a connection record containing image url', async () => {
expect.assertions(1)
const outOfBand = getMockOutOfBand({ state: OutOfBandState.PrepareResponse, imageUrl: connectionImageUrl })
const config = { label: 'Custom label', routing: myRouting }
const { connectionRecord } = await connectionService.createRequest(agentContext, outOfBand, config)
expect(connectionRecord.imageUrl).toBe(connectionImageUrl)
})
it('returns a connection request message containing a custom image url', async () => {
expect.assertions(1)
const outOfBand = getMockOutOfBand({ state: OutOfBandState.PrepareResponse })
const config = { imageUrl: 'custom-image-url', routing: myRouting }
const { message } = await connectionService.createRequest(agentContext, outOfBand, config)
expect(message.imageUrl).toBe('custom-image-url')
})
it(`throws an error when out-of-band role is not ${OutOfBandRole.Receiver}`, async () => {
expect.assertions(1)
const outOfBand = getMockOutOfBand({ role: OutOfBandRole.Sender, state: OutOfBandState.PrepareResponse })
const config = { routing: myRouting }
return expect(connectionService.createRequest(agentContext, outOfBand, config)).rejects.toThrowError(
`Invalid out-of-band record role ${OutOfBandRole.Sender}, expected is ${OutOfBandRole.Receiver}.`
)
})
const invalidConnectionStates = [OutOfBandState.Initial, OutOfBandState.AwaitResponse, OutOfBandState.Done]
test.each(invalidConnectionStates)(
`throws an error when out-of-band state is %s and not ${OutOfBandState.PrepareResponse}`,
(state) => {
expect.assertions(1)
const outOfBand = getMockOutOfBand({ state })
const config = { routing: myRouting }
return expect(connectionService.createRequest(agentContext, outOfBand, config)).rejects.toThrowError(
`Invalid out-of-band record state ${state}, valid states are: ${OutOfBandState.PrepareResponse}.`
)
}
)
})
describe('processRequest', () => {
it('returns a connection record containing the information from the connection request', async () => {
expect.assertions(5)
const theirDid = 'their-did'
const theirKey = Key.fromPublicKeyBase58('79CXkde3j8TNuMXxPdV7nLUrT2g7JAEjH5TreyVY7GEZ', KeyType.Ed25519)
const theirDidDoc = new DidDoc({
id: theirDid,
publicKey: [],
authentication: [
new EmbeddedAuthentication(
new Ed25119Sig2018({
id: `${theirDid}#key-id`,
controller: theirDid,
publicKeyBase58: theirKey.publicKeyBase58,
})
),
],
service: [
new DidCommV1Service({
id: `${theirDid};indy`,
serviceEndpoint: 'https://endpoint.com',
recipientKeys: [`${theirDid}#key-id`],
}),
],
})
const connectionRequest = new ConnectionRequestMessage({
did: theirDid,
didDoc: theirDidDoc,
label: 'test-label',
imageUrl: connectionImageUrl,
})
const messageContext = new InboundMessageContext(connectionRequest, {
agentContext,
senderKey: theirKey,
recipientKey: Key.fromPublicKeyBase58('8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K', KeyType.Ed25519),
})
const outOfBand = getMockOutOfBand({
mediatorId: 'fakeMediatorId',
role: OutOfBandRole.Sender,
state: OutOfBandState.AwaitResponse,
})
const processedConnection = await connectionService.processRequest(messageContext, outOfBand)
expect(processedConnection.state).toBe(DidExchangeState.RequestReceived)
expect(processedConnection.theirDid).toBe('did:peer:1zQmW2esSyEVGzrh3CFt1eQZUHEAb3Li1hyPudPhSoFevrFY')
expect(processedConnection.theirLabel).toBe('test-label')
expect(processedConnection.threadId).toBe(connectionRequest.id)
expect(processedConnection.imageUrl).toBe(connectionImageUrl)
})
it('returns a new connection record containing the information from the connection request when multiUseInvitation is enabled on the connection', async () => {
expect.assertions(8)
const connectionRecord = getMockConnection({
id: 'test',
state: DidExchangeState.InvitationSent,
role: DidExchangeRole.Responder,
})
const theirDid = 'their-did'
const theirKey = Key.fromPublicKeyBase58('79CXkde3j8TNuMXxPdV7nLUrT2g7JAEjH5TreyVY7GEZ', KeyType.Ed25519)
const theirDidDoc = new DidDoc({
id: theirDid,
publicKey: [],
authentication: [
new EmbeddedAuthentication(
new Ed25119Sig2018({
id: `${theirDid}#key-id`,
controller: theirDid,
publicKeyBase58: theirKey.publicKeyBase58,
})
),
],
service: [
new DidCommV1Service({
id: `${theirDid};indy`,
serviceEndpoint: 'https://endpoint.com',
recipientKeys: [`${theirDid}#key-id`],
}),
],
})
const connectionRequest = new ConnectionRequestMessage({
did: theirDid,
didDoc: theirDidDoc,
label: 'test-label',
})
const messageContext = new InboundMessageContext(connectionRequest, {
agentContext,
connection: connectionRecord,
senderKey: theirKey,
recipientKey: Key.fromPublicKeyBase58('8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K', KeyType.Ed25519),
})
const outOfBand = getMockOutOfBand({
mediatorId: 'fakeMediatorId',
role: OutOfBandRole.Sender,
state: OutOfBandState.AwaitResponse,
})
const processedConnection = await connectionService.processRequest(messageContext, outOfBand)
expect(processedConnection.state).toBe(DidExchangeState.RequestReceived)
expect(processedConnection.theirDid).toBe('did:peer:1zQmW2esSyEVGzrh3CFt1eQZUHEAb3Li1hyPudPhSoFevrFY')
expect(processedConnection.theirLabel).toBe('test-label')
expect(processedConnection.threadId).toBe(connectionRequest.id)
expect(connectionRepository.save).toHaveBeenCalledTimes(1)
expect(processedConnection.id).not.toBe(connectionRecord.id)
expect(connectionRecord.id).toBe('test')
expect(connectionRecord.state).toBe(DidExchangeState.InvitationSent)
})
it('throws an error when the message does not contain a did doc', async () => {
expect.assertions(1)
const connectionRequest = new ConnectionRequestMessage({
did: 'did',
label: 'test-label',
})
const messageContext = new InboundMessageContext(connectionRequest, {
agentContext,
recipientKey: Key.fromPublicKeyBase58('8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K', KeyType.Ed25519),
senderKey: Key.fromPublicKeyBase58('79CXkde3j8TNuMXxPdV7nLUrT2g7JAEjH5TreyVY7GEZ', KeyType.Ed25519),
})
const outOfBand = getMockOutOfBand({ role: OutOfBandRole.Sender, state: OutOfBandState.AwaitResponse })
return expect(connectionService.processRequest(messageContext, outOfBand)).rejects.toThrowError(
`Public DIDs are not supported yet`
)
})
it(`throws an error when out-of-band role is not ${OutOfBandRole.Sender}`, async () => {
expect.assertions(1)
const inboundMessage = new InboundMessageContext(jest.fn()(), {
agentContext,
recipientKey: Key.fromPublicKeyBase58('8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K', KeyType.Ed25519),
senderKey: Key.fromPublicKeyBase58('79CXkde3j8TNuMXxPdV7nLUrT2g7JAEjH5TreyVY7GEZ', KeyType.Ed25519),
})
const outOfBand = getMockOutOfBand({ role: OutOfBandRole.Receiver, state: OutOfBandState.AwaitResponse })
return expect(connectionService.processRequest(inboundMessage, outOfBand)).rejects.toThrowError(
`Invalid out-of-band record role ${OutOfBandRole.Receiver}, expected is ${OutOfBandRole.Sender}.`
)
})
const invalidOutOfBandStates = [OutOfBandState.Initial, OutOfBandState.PrepareResponse, OutOfBandState.Done]
test.each(invalidOutOfBandStates)(
`throws an error when out-of-band state is %s and not ${OutOfBandState.AwaitResponse}`,
(state) => {
expect.assertions(1)
const inboundMessage = new InboundMessageContext(jest.fn()(), { agentContext })
const outOfBand = getMockOutOfBand({ role: OutOfBandRole.Sender, state })
return expect(connectionService.processRequest(inboundMessage, outOfBand)).rejects.toThrowError(
`Invalid out-of-band record state ${state}, valid states are: ${OutOfBandState.AwaitResponse}.`
)
}
)
})
describe('createResponse', () => {
it('returns a connection response message containing the information from the connection record', async () => {
expect.assertions(2)
const key = await wallet.createKey({ keyType: KeyType.Ed25519 })
const did = indyDidFromPublicKeyBase58(key.publicKeyBase58)
// Needed for signing connection~sig
const mockConnection = getMockConnection({
state: DidExchangeState.RequestReceived,
role: DidExchangeRole.Responder,
tags: {
threadId: 'test',
},
})
const recipientKeys = [new DidKey(key)]
const outOfBand = getMockOutOfBand({ recipientKeys: recipientKeys.map((did) => did.did) })
const publicKey = new Ed25119Sig2018({
id: `${did}#1`,
controller: did,
publicKeyBase58: key.publicKeyBase58,
})
const mockDidDoc = new DidDoc({
id: did,
publicKey: [publicKey],
authentication: [new ReferencedAuthentication(publicKey, authenticationTypes.Ed25519VerificationKey2018)],
service: [
new IndyAgentService({
id: `${did}#IndyAgentService-1`,
serviceEndpoint: 'http://example.com',
recipientKeys: recipientKeys.map((did) => did.key.publicKeyBase58),
routingKeys: [],
}),
],
})
const { message, connectionRecord: connectionRecord } = await connectionService.createResponse(
agentContext,
mockConnection,
outOfBand
)
const connection = new Connection({
did,
didDoc: mockDidDoc,
})
const plainConnection = JsonTransformer.toJSON(connection)
expect(connectionRecord.state).toBe(DidExchangeState.ResponseSent)
expect(await unpackAndVerifySignatureDecorator(message.connectionSig, wallet)).toEqual(plainConnection)
})
it(`throws an error when connection role is ${DidExchangeRole.Requester} and not ${DidExchangeRole.Responder}`, async () => {
expect.assertions(1)
const connection = getMockConnection({
role: DidExchangeRole.Requester,
state: DidExchangeState.RequestReceived,
})
const outOfBand = getMockOutOfBand()
return expect(connectionService.createResponse(agentContext, connection, outOfBand)).rejects.toThrowError(
`Connection record has invalid role ${DidExchangeRole.Requester}. Expected role ${DidExchangeRole.Responder}.`
)
})
const invalidOutOfBandStates = [
DidExchangeState.InvitationSent,
DidExchangeState.InvitationReceived,
DidExchangeState.RequestSent,
DidExchangeState.ResponseSent,
DidExchangeState.ResponseReceived,
DidExchangeState.Completed,
DidExchangeState.Abandoned,
DidExchangeState.Start,
]
test.each(invalidOutOfBandStates)(
`throws an error when connection state is %s and not ${DidExchangeState.RequestReceived}`,
async (state) => {
expect.assertions(1)
const connection = getMockConnection({ state })
const outOfBand = getMockOutOfBand()
return expect(connectionService.createResponse(agentContext, connection, outOfBand)).rejects.toThrowError(
`Connection record is in invalid state ${state}. Valid states are: ${DidExchangeState.RequestReceived}.`
)
}
)
})
describe('processResponse', () => {
it('returns a connection record containing the information from the connection response', async () => {
expect.assertions(2)
const key = await wallet.createKey({ keyType: KeyType.Ed25519 })
const did = indyDidFromPublicKeyBase58(key.publicKeyBase58)
const theirKey = await wallet.createKey({ keyType: KeyType.Ed25519 })
const theirDid = indyDidFromPublicKeyBase58(key.publicKeyBase58)
const connectionRecord = getMockConnection({
did,
state: DidExchangeState.RequestSent,
role: DidExchangeRole.Requester,
})
const otherPartyConnection = new Connection({
did: theirDid,
didDoc: new DidDoc({
id: theirDid,
publicKey: [],
authentication: [
new EmbeddedAuthentication(
new Ed25119Sig2018({
id: `${theirDid}#key-id`,
controller: theirDid,
publicKeyBase58: theirKey.publicKeyBase58,
})
),
],
service: [
new DidCommV1Service({
id: `${did};indy`,
serviceEndpoint: 'https://endpoint.com',
recipientKeys: [`${theirDid}#key-id`],
}),
],
}),
})
const plainConnection = JsonTransformer.toJSON(otherPartyConnection)
const connectionSig = await signData(plainConnection, wallet, theirKey.publicKeyBase58)
const connectionResponse = new ConnectionResponseMessage({
threadId: uuid(),
connectionSig,
})
const outOfBandRecord = getMockOutOfBand({
recipientKeys: [new DidKey(theirKey).did],
})
const messageContext = new InboundMessageContext(connectionResponse, {
agentContext,
connection: connectionRecord,
senderKey: theirKey,
recipientKey: key,
})
const processedConnection = await connectionService.processResponse(messageContext, outOfBandRecord)
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const peerDid = didDocumentJsonToNumAlgo1Did(convertToNewDidDocument(otherPartyConnection.didDoc!).toJSON())
expect(processedConnection.state).toBe(DidExchangeState.ResponseReceived)
expect(processedConnection.theirDid).toBe(peerDid)
})
it(`throws an error when connection role is ${DidExchangeRole.Responder} and not ${DidExchangeRole.Requester}`, async () => {
expect.assertions(1)
const outOfBandRecord = getMockOutOfBand()
const connectionRecord = getMockConnection({
role: DidExchangeRole.Responder,
state: DidExchangeState.RequestSent,
})
const messageContext = new InboundMessageContext(jest.fn()(), {
agentContext,
connection: connectionRecord,
recipientKey: Key.fromPublicKeyBase58('8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K', KeyType.Ed25519),
senderKey: Key.fromPublicKeyBase58('79CXkde3j8TNuMXxPdV7nLUrT2g7JAEjH5TreyVY7GEZ', KeyType.Ed25519),
})
return expect(connectionService.processResponse(messageContext, outOfBandRecord)).rejects.toThrowError(
`Connection record has invalid role ${DidExchangeRole.Responder}. Expected role ${DidExchangeRole.Requester}.`
)
})
it('throws an error when the connection sig is not signed with the same key as the recipient key from the invitation', async () => {
expect.assertions(1)
const key = await wallet.createKey({ keyType: KeyType.Ed25519 })
const did = indyDidFromPublicKeyBase58(key.publicKeyBase58)
const theirKey = await wallet.createKey({ keyType: KeyType.Ed25519 })
const theirDid = indyDidFromPublicKeyBase58(key.publicKeyBase58)
const connectionRecord = getMockConnection({
did,
role: DidExchangeRole.Requester,
state: DidExchangeState.RequestSent,
})
const otherPartyConnection = new Connection({
did: theirDid,
didDoc: new DidDoc({
id: theirDid,
publicKey: [],
authentication: [
new EmbeddedAuthentication(
new Ed25119Sig2018({
id: `${theirDid}#key-id`,
controller: theirDid,
publicKeyBase58: theirKey.publicKeyBase58,
})
),
],
service: [
new DidCommV1Service({
id: `${did};indy`,
serviceEndpoint: 'https://endpoint.com',
recipientKeys: [`${theirDid}#key-id`],
}),
],
}),
})
const plainConnection = JsonTransformer.toJSON(otherPartyConnection)
const connectionSig = await signData(plainConnection, wallet, theirKey.publicKeyBase58)
const connectionResponse = new ConnectionResponseMessage({
threadId: uuid(),
connectionSig,
})
// Recipient key `verkey` is not the same as theirVerkey which was used to sign message,
// therefore it should cause a failure.
const outOfBandRecord = getMockOutOfBand({
recipientKeys: [new DidKey(key).did],
})
const messageContext = new InboundMessageContext(connectionResponse, {
agentContext,
connection: connectionRecord,
senderKey: theirKey,
recipientKey: key,
})
return expect(connectionService.processResponse(messageContext, outOfBandRecord)).rejects.toThrowError(
new RegExp(
'Connection object in connection response message is not signed with same key as recipient key in invitation'
)
)
})
it('throws an error when the message does not contain a DID Document', async () => {
expect.assertions(1)
const key = await wallet.createKey({ keyType: KeyType.Ed25519 })
const did = indyDidFromPublicKeyBase58(key.publicKeyBase58)
const theirKey = await wallet.createKey({ keyType: KeyType.Ed25519 })
const theirDid = indyDidFromPublicKeyBase58(key.publicKeyBase58)
const connectionRecord = getMockConnection({
did,
state: DidExchangeState.RequestSent,
theirDid: undefined,
})
const otherPartyConnection = new Connection({ did: theirDid })
const plainConnection = JsonTransformer.toJSON(otherPartyConnection)
const connectionSig = await signData(plainConnection, wallet, theirKey.publicKeyBase58)
const connectionResponse = new ConnectionResponseMessage({ threadId: uuid(), connectionSig })
const outOfBandRecord = getMockOutOfBand({ recipientKeys: [new DidKey(theirKey).did] })
const messageContext = new InboundMessageContext(connectionResponse, {
agentContext,
connection: connectionRecord,
recipientKey: Key.fromPublicKeyBase58('8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K', KeyType.Ed25519),
senderKey: Key.fromPublicKeyBase58('79CXkde3j8TNuMXxPdV7nLUrT2g7JAEjH5TreyVY7GEZ', KeyType.Ed25519),
})
return expect(connectionService.processResponse(messageContext, outOfBandRecord)).rejects.toThrowError(
`DID Document is missing.`
)
})
})
describe('createTrustPing', () => {
it('returns a trust ping message', async () => {
expect.assertions(2)
const mockConnection = getMockConnection({ state: DidExchangeState.ResponseReceived })
const { message, connectionRecord: connectionRecord } = await connectionService.createTrustPing(
agentContext,
mockConnection
)
expect(connectionRecord.state).toBe(DidExchangeState.Completed)
expect(message).toEqual(expect.any(TrustPingMessage))
})
const invalidConnectionStates = [
DidExchangeState.InvitationSent,
DidExchangeState.InvitationReceived,
DidExchangeState.RequestSent,
DidExchangeState.RequestReceived,
DidExchangeState.ResponseSent,
DidExchangeState.Abandoned,
DidExchangeState.Start,
]
test.each(invalidConnectionStates)(
`throws an error when connection state is %s and not ${DidExchangeState.ResponseReceived} or ${DidExchangeState.Completed}`,
(state) => {
expect.assertions(1)
const connection = getMockConnection({ state })
return expect(connectionService.createTrustPing(agentContext, connection)).rejects.toThrowError(
`Connection record is in invalid state ${state}. Valid states are: ${DidExchangeState.ResponseReceived}, ${DidExchangeState.Completed}.`
)
}
)
})
describe('processAck', () => {
it('throws an error when the message context does not have a connection', async () => {
expect.assertions(1)
const ack = new AckMessage({
status: AckStatus.OK,
threadId: 'thread-id',
})
const messageContext = new InboundMessageContext(ack, { agentContext })
return expect(connectionService.processAck(messageContext)).rejects.toThrowError(
'Unable to process connection ack: connection for recipient key undefined not found'
)
})
it('updates the state to Completed when the state is ResponseSent and role is Responder', async () => {
expect.assertions(1)
const connection = getMockConnection({
state: DidExchangeState.ResponseSent,
role: DidExchangeRole.Responder,
})
const ack = new AckMessage({
status: AckStatus.OK,
threadId: 'thread-id',
})
const messageContext = new InboundMessageContext(ack, { agentContext, connection })
const updatedConnection = await connectionService.processAck(messageContext)
expect(updatedConnection.state).toBe(DidExchangeState.Completed)
})
it('does not update the state when the state is not ResponseSent or the role is not Responder', async () => {
expect.assertions(1)
const connection = getMockConnection({
state: DidExchangeState.ResponseReceived,
role: DidExchangeRole.Requester,
})
const ack = new AckMessage({
status: AckStatus.OK,
threadId: 'thread-id',
})
const messageContext = new InboundMessageContext(ack, { agentContext, connection })
const updatedConnection = await connectionService.processAck(messageContext)
expect(updatedConnection.state).toBe(DidExchangeState.ResponseReceived)
})
})
describe('assertConnectionOrOutOfBandExchange', () => {
it('should not throw an error when a connection record with state complete is present in the messageContext', async () => {
expect.assertions(1)
const messageContext = new InboundMessageContext(new AgentMessage(), {
agentContext,
connection: getMockConnection({ state: DidExchangeState.Completed }),
})
await expect(connectionService.assertConnectionOrOutOfBandExchange(messageContext)).resolves.not.toThrow()
})
it('should throw an error when a connection record is present and state not complete in the messageContext', async () => {
expect.assertions(1)
const messageContext = new InboundMessageContext(new AgentMessage(), {
agentContext,
connection: getMockConnection({ state: DidExchangeState.InvitationReceived }),
})
await expect(connectionService.assertConnectionOrOutOfBandExchange(messageContext)).rejects.toThrowError(
'Connection record is not ready to be used'
)
})
it('should not throw an error when no connection record is present in the messageContext and no additional data, but the message has a ~service decorator', async () => {
expect.assertions(1)
mockFunction(outOfBandRepository.findSingleByQuery).mockResolvedValue(null)
const message = new AgentMessage()
message.setService({
recipientKeys: [],
serviceEndpoint: '',
routingKeys: [],
})
const messageContext = new InboundMessageContext(message, { agentContext })
await expect(connectionService.assertConnectionOrOutOfBandExchange(messageContext)).resolves.not.toThrow()
})
it('should not throw when a fully valid connection-less input is passed', async () => {
expect.assertions(1)
const recipientKey = Key.fromPublicKeyBase58('8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K', KeyType.Ed25519)
const senderKey = Key.fromPublicKeyBase58('79CXkde3j8TNuMXxPdV7nLUrT2g7JAEjH5TreyVY7GEZ', KeyType.Ed25519)
const lastSentMessage = new AgentMessage()
lastSentMessage.setService({
recipientKeys: [recipientKey.publicKeyBase58],
serviceEndpoint: '',
routingKeys: [],
})
const lastReceivedMessage = new AgentMessage()
lastReceivedMessage.setService({
recipientKeys: [senderKey.publicKeyBase58],
serviceEndpoint: '',
routingKeys: [],
})
const message = new AgentMessage()
message.setService({
recipientKeys: [senderKey.publicKeyBase58],
serviceEndpoint: '',
routingKeys: [],
})
const messageContext = new InboundMessageContext(message, { agentContext, recipientKey, senderKey })
await expect(
connectionService.assertConnectionOrOutOfBandExchange(messageContext, {
lastReceivedMessage,
lastSentMessage,
})
).resolves.not.toThrow()
})
it('should throw an error when lastSentMessage is present, but recipientVerkey is not ', async () => {
expect.assertions(1)
const lastSentMessage = new AgentMessage()
lastSentMessage.setService({
recipientKeys: [],
serviceEndpoint: '',
routingKeys: [],
})
const message = new AgentMessage()
message.setService({
recipientKeys: [],
serviceEndpoint: '',
routingKeys: [],
})
const messageContext = new InboundMessageContext(message, { agentContext })
await expect(
connectionService.assertConnectionOrOutOfBandExchange(messageContext, {
lastSentMessage,
})
).rejects.toThrowError(
'Incoming message must have recipientKey and senderKey (so cannot be AuthCrypt or unpacked) if there are lastSentMessage or lastReceivedMessage.'
)
})
it('should throw an error when lastSentMessage and recipientKey are present, but recipient key is not present in recipientKeys of previously sent message ~service decorator', async () => {
expect.assertions(1)
const recipientKey = Key.fromPublicKeyBase58('8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K', KeyType.Ed25519)
const senderKey = Key.fromPublicKeyBase58('8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K', KeyType.Ed25519)
const lastSentMessage = new AgentMessage()
lastSentMessage.setService({
recipientKeys: ['anotherKey'],
serviceEndpoint: '',
routingKeys: [],
})
const message = new AgentMessage()
message.setService({
recipientKeys: [],
serviceEndpoint: '',
routingKeys: [],
})
const messageContext = new InboundMessageContext(message, { agentContext, recipientKey, senderKey })
await expect(
connectionService.assertConnectionOrOutOfBandExchange(messageContext, {
lastSentMessage,
})
).rejects.toThrowError('Recipient key 8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K not found in our service')
})
it('should throw an error when lastReceivedMessage is present, but senderVerkey is not ', async () => {
expect.assertions(1)
const lastReceivedMessage = new AgentMessage()
lastReceivedMessage.setService({
recipientKeys: [],
serviceEndpoint: '',
routingKeys: [],
})
const message = new AgentMessage()
const messageContext = new InboundMessageContext(message, { agentContext })
await expect(
connectionService.assertConnectionOrOutOfBandExchange(messageContext, {
lastReceivedMessage,
})
).rejects.toThrowError(
'No keys on our side to use for encrypting messages, and previous messages found (in which case our keys MUST also be present).'
)
})
it('should throw an error when lastReceivedMessage and senderKey are present, but sender key is not present in recipientKeys of previously received message ~service decorator', async () => {
expect.assertions(1)
const senderKey = 'senderKey'
const lastReceivedMessage = new AgentMessage()
lastReceivedMessage.setService({
recipientKeys: ['anotherKey'],
serviceEndpoint: '',
routingKeys: [],
})
const lastSentMessage = new AgentMessage()
lastSentMessage.setService({
recipientKeys: [senderKey],
serviceEndpoint: '',
routingKeys: [],
})
const message = new AgentMessage()
const messageContext = new InboundMessageContext(message, {
agentContext,
senderKey: Key.fromPublicKeyBase58('randomKey', KeyType.Ed25519),
recipientKey: Key.fromPublicKeyBase58(senderKey, KeyType.Ed25519),
})
await expect(
connectionService.assertConnectionOrOutOfBandExchange(messageContext, {
lastReceivedMessage,
lastSentMessage,
})
).rejects.toThrowError('Sender key randomKey not found in their service')
})
})
describe('repository methods', () => {
it('getById should return value from connectionRepository.getById', async () => {
const expected = getMockConnection()
mockFunction(connectionRepository.getById).mockReturnValue(Promise.resolve(expected))
const result = await connectionService.getById(agentContext, expected.id)
expect(connectionRepository.getById).toBeCalledWith(agentContext, expected.id)
expect(result).toBe(expected)
})
it('getByThreadId should return value from connectionRepository.getSingleByQuery', async () => {
const expected = getMockConnection()
mockFunction(connectionRepository.getByThreadId).mockReturnValue(Promise.resolve(expected))
const result = await connectionService.getByThreadId(agentContext, 'threadId')
expect(connectionRepository.getByThreadId).toBeCalledWith(agentContext, 'threadId')
expect(result).toBe(expected)
})
it('findById should return value from connectionRepository.findById', async () => {
const expected = getMockConnection()
mockFunction(connectionRepository.findById).mockReturnValue(Promise.resolve(expected))
const result = await connectionService.findById(agentContext, expected.id)
expect(connectionRepository.findById).toBeCalledWith(agentContext, expected.id)
expect(result).toBe(expected)
})
it('getAll should return value from connectionRepository.getAll', async () => {
const expected = [getMockConnection(), getMockConnection()]
mockFunction(connectionRepository.getAll).mockReturnValue(Promise.resolve(expected))
const result = await connectionService.getAll(agentContext)
expect(connectionRepository.getAll).toBeCalledWith(agentContext)
expect(result).toEqual(expect.arrayContaining(expected))
})
it('findAllByQuery should return value from connectionRepository.findByQuery', async () => {
const expected = [getMockConnection(), getMockConnection()]
mockFunction(connectionRepository.findByQuery).mockReturnValue(Promise.resolve(expected))
const result = await connectionService.findAllByQuery(agentContext, {