-
Notifications
You must be signed in to change notification settings - Fork 9
/
machine.test.ts
1610 lines (1357 loc) · 68.1 KB
/
machine.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 {
BackupDecryptionKey,
CrossSigningStatus,
DecryptedRoomEvent,
DecryptionErrorCode,
DecryptionSettings,
DeviceId,
DeviceKeyId,
DeviceLists,
EncryptionAlgorithm,
EncryptionSettings,
EventId,
getVersions,
InboundGroupSession,
KeysBackupRequest,
KeysClaimRequest,
KeysQueryRequest,
KeysUploadRequest,
MaybeSignature,
MegolmDecryptionError,
OlmMachine,
OwnUserIdentity,
RequestType,
RoomId,
RoomKeyWithheldInfo,
RoomMessageRequest,
RoomSettings,
ShieldColor,
ShieldStateCode,
SignatureState,
SignatureUploadRequest,
StoreHandle,
ToDeviceRequest,
TrustRequirement,
UserId,
OtherUserIdentity,
VerificationRequest,
Versions,
} from "@matrix-org/matrix-sdk-crypto-wasm";
import "fake-indexeddb/auto";
import * as crypto from "node:crypto";
type AnyOutgoingRequest =
| KeysUploadRequest
| KeysQueryRequest
| KeysClaimRequest
| ToDeviceRequest
| SignatureUploadRequest
| RoomMessageRequest
| KeysBackupRequest;
afterEach(() => {
// reset fake-indexeddb after each test, to make sure we don't leak data
// cf https://github.com/dumbmatter/fakeIndexedDB#wipingresetting-the-indexeddb-for-a-fresh-state
// eslint-disable-next-line no-global-assign
indexedDB = new IDBFactory();
});
describe("Versions", () => {
test("can find out the crate versions", async () => {
const versions = getVersions();
expect(versions).toBeInstanceOf(Versions);
expect(versions.vodozemac).toBeDefined();
expect(versions.matrix_sdk_crypto).toBeDefined();
expect(versions.git_sha).toBeDefined();
expect(versions.git_description).toBeDefined();
});
});
jest.setTimeout(15000);
describe(OlmMachine.name, () => {
test("can be instantiated with the async initializer", async () => {
expect(await OlmMachine.initialize(new UserId("@foo:bar.org"), new DeviceId("baz"))).toBeInstanceOf(OlmMachine);
});
test("can be instantiated with a StoreHandle", async () => {
let storeName = "hello";
let storePassphrase = "world";
let storeHandle = await StoreHandle.open(storeName, storePassphrase);
expect(
await OlmMachine.initFromStore(new UserId("@foo:bar.org"), new DeviceId("baz"), storeHandle),
).toBeInstanceOf(OlmMachine);
storeHandle.free();
});
test("can be instantiated with passphrase", async () => {
let storeName = "hello2";
let storePassphrase = "world";
const byStoreName = (db: IDBDatabaseInfo) => db.name!.startsWith(storeName);
// No databases.
expect((await indexedDB.databases()).filter(byStoreName)).toHaveLength(0);
// Creating a new Olm machine.
expect(
await OlmMachine.initialize(new UserId("@foo:bar.org"), new DeviceId("baz"), storeName, storePassphrase),
).toBeInstanceOf(OlmMachine);
// Oh, there is 2 databases now, prefixed by `storeName`.
let databases = (await indexedDB.databases()).filter(byStoreName);
expect(databases).toHaveLength(2);
expect(databases).toStrictEqual([
{ name: `${storeName}::matrix-sdk-crypto-meta`, version: 1 },
{ name: `${storeName}::matrix-sdk-crypto`, version: 12 },
]);
// Creating a new Olm machine, with the stored state.
expect(
await OlmMachine.initialize(new UserId("@foo:bar.org"), new DeviceId("baz"), storeName, storePassphrase),
).toBeInstanceOf(OlmMachine);
// Same number of databases.
expect((await indexedDB.databases()).filter(byStoreName)).toHaveLength(2);
});
test("can be instantiated with a passphrase, and then migrated to a key", async () => {
const storeName = "hello3";
const pickleKey = new Uint8Array(32);
crypto.getRandomValues(pickleKey);
const b64Pickle = Buffer.from(pickleKey)
.toString("base64")
.replace(/={1,2}$/, "");
const storeHandle = await StoreHandle.open(storeName, b64Pickle);
const olmMachine: OlmMachine = await OlmMachine.initFromStore(
new UserId("@foo:bar.org"),
new DeviceId("baz"),
storeHandle,
);
storeHandle.free();
expect(olmMachine).toBeInstanceOf(OlmMachine);
const deviceKeys = olmMachine.identityKeys;
// re-open the store, using the key directly
const storeHandle2 = await StoreHandle.openWithKey(storeName, pickleKey);
const olmMachine2: OlmMachine = await OlmMachine.initFromStore(
new UserId("@foo:bar.org"),
new DeviceId("baz"),
storeHandle2,
);
storeHandle2.free();
expect(olmMachine2).toBeInstanceOf(OlmMachine);
// make sure that we got back the same device.
const deviceKeys2 = olmMachine2.identityKeys;
expect(deviceKeys2.ed25519.toBase64()).toEqual(deviceKeys.ed25519.toBase64());
});
describe("cannot be instantiated with a store", () => {
test("store name is missing", async () => {
let storePassphrase = "world";
let err = null;
try {
await OlmMachine.initialize(
new UserId("@foo:bar.org"),
new DeviceId("baz"),
undefined,
storePassphrase,
);
} catch (error) {
err = error;
}
expect(err).toBeDefined();
});
test("store passphrase is missing", async () => {
let storeName = "hello";
let err = null;
try {
await OlmMachine.initialize(new UserId("@foo:bar.org"), new DeviceId("baz"), storeName, undefined);
} catch (error) {
err = error;
}
expect(err).toBeDefined();
});
});
const user = new UserId("@alice:example.org");
const device = new DeviceId("foobar");
const room = new RoomId("!baz:matrix.org");
function machine(newUser?: UserId, newDevice?: DeviceId): Promise<OlmMachine> {
// Uncomment to enable debug logging for tests
// new RustSdkCryptoJs.Tracing(RustSdkCryptoJs.LoggerLevel.Trace).turnOn();
return OlmMachine.initialize(newUser || user, newDevice || device);
}
test("can drop/close", async () => {
const m = await machine();
m.close();
});
test("can drop/close with a store", async () => {
let storeName = "temporary";
let storePassphrase = "temporary";
const byStoreName = (db: IDBDatabaseInfo) => db.name?.startsWith(storeName);
// No databases.
expect((await indexedDB.databases()).filter(byStoreName)).toHaveLength(0);
// Creating a new Olm machine.
const m = await OlmMachine.initialize(
new UserId("@foo:bar.org"),
new DeviceId("baz"),
storeName,
storePassphrase,
);
expect(m).toBeInstanceOf(OlmMachine);
// Oh, there is 2 databases now, prefixed by `storeName`.
let databases = (await indexedDB.databases()).filter(byStoreName);
expect(databases).toHaveLength(2);
expect(databases).toStrictEqual([
{ name: `${storeName}::matrix-sdk-crypto-meta`, version: 1 },
{ name: `${storeName}::matrix-sdk-crypto`, version: 12 },
]);
// Let's force to close the `OlmMachine`.
m.close();
// Now we can delete the databases!
for (const databaseName of [`${storeName}::matrix-sdk-crypto`, `${storeName}::matrix-sdk-crypto-meta`]) {
const deleting = indexedDB.deleteDatabase(databaseName);
deleting.onsuccess = () => {};
deleting.onerror = () => {
throw new Error("failed to remove the database (error)");
};
deleting.onblocked = () => {
throw new Error("failed to remove the database (blocked)");
};
}
});
test("can read user ID", async () => {
expect((await machine()).userId.toString()).toStrictEqual(user.toString());
});
test("can read device ID", async () => {
expect((await machine()).deviceId.toString()).toStrictEqual(device.toString());
});
test("can read creation time", async () => {
const startTime = Date.now();
const creationTime = (await machine()).deviceCreationTimeMs;
expect(creationTime).toBeLessThanOrEqual(Date.now());
expect(creationTime).toBeGreaterThanOrEqual(startTime);
});
test("can read identity keys", async () => {
const identityKeys = (await machine()).identityKeys;
expect(identityKeys.ed25519.toBase64()).toMatch(/^[A-Za-z0-9+/]+$/);
expect(identityKeys.curve25519.toBase64()).toMatch(/^[A-Za-z0-9+/]+$/);
});
// This returns the empty object for some reason?
test.skip("can read display name", async () => {
expect((await machine()).displayName).toBeUndefined();
});
test("can toggle room key requests", async () => {
const m = await machine();
expect(m.roomKeyRequestsEnabled).toBe(true);
m.roomKeyRequestsEnabled = false;
expect(m.roomKeyRequestsEnabled).toBe(false);
});
test("can toggle room key forwarding", async () => {
const m = await machine();
expect(m.roomKeyForwardingEnabled).toBe(true);
m.roomKeyForwardingEnabled = false;
expect(m.roomKeyForwardingEnabled).toBe(false);
});
test("can read tracked users", async () => {
const m = await machine();
const trackedUsers = await m.trackedUsers();
expect(trackedUsers).toBeInstanceOf(Set);
expect(trackedUsers.size).toStrictEqual(0);
});
test("can update tracked users", async () => {
const m = await machine();
expect(await m.updateTrackedUsers([user.clone()])).toStrictEqual(undefined);
});
test("can receive sync changes", async () => {
const m = await machine();
const toDeviceEvents = JSON.stringify([]);
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = new Map();
const unusedFallbackKeys = new Set();
const receiveSyncChanges = JSON.parse(
await m.receiveSyncChanges(toDeviceEvents, changedDevices, oneTimeKeyCounts, unusedFallbackKeys),
);
expect(receiveSyncChanges).toEqual([]);
});
test("can receive sync changes with unusedFallbackKeys as undefined", async () => {
const m = await machine();
const toDeviceEvents = JSON.stringify([]);
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = new Map();
const receiveSyncChanges = JSON.parse(
await m.receiveSyncChanges(toDeviceEvents, changedDevices, oneTimeKeyCounts, undefined),
);
expect(receiveSyncChanges).toEqual([]);
});
test("can get the outgoing requests that need to be sent out", async () => {
const m = await machine();
const toDeviceEvents = JSON.stringify([]);
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = new Map();
const unusedFallbackKeys = new Set();
const receiveSyncChanges = JSON.parse(
await m.receiveSyncChanges(toDeviceEvents, changedDevices, oneTimeKeyCounts, unusedFallbackKeys),
);
expect(receiveSyncChanges).toEqual([]);
const outgoingRequests = await m.outgoingRequests();
expect(outgoingRequests).toHaveLength(2);
{
expect(outgoingRequests[0]).toBeInstanceOf(KeysUploadRequest);
expect(outgoingRequests[0].id).toBeDefined();
expect(outgoingRequests[0].type).toStrictEqual(RequestType.KeysUpload);
expect(outgoingRequests[0].body).toBeDefined();
const body = JSON.parse(outgoingRequests[0].body);
expect(body.device_keys).toBeDefined();
expect(body.one_time_keys).toBeDefined();
}
{
expect(outgoingRequests[1]).toBeInstanceOf(KeysQueryRequest);
expect(outgoingRequests[1].id).toBeDefined();
expect(outgoingRequests[1].type).toStrictEqual(RequestType.KeysQuery);
expect(outgoingRequests[1].body).toBeDefined();
const body = JSON.parse(outgoingRequests[1].body);
// default timeout in Rust is None, so timeout will be omitted
expect(body.timeout).not.toBeDefined();
expect(body.device_keys).toBeDefined();
}
});
test("Can build a key query request", async () => {
const m = await machine();
const request = m.queryKeysForUsers([new UserId("@alice:example.org")]);
expect(request).toBeInstanceOf(KeysQueryRequest);
const body = JSON.parse(request.body);
expect(Object.keys(body.device_keys)).toContain("@alice:example.org");
});
describe("setup workflow to mark requests as sent", () => {
let m: OlmMachine;
let outgoingRequests: Array<AnyOutgoingRequest>;
beforeAll(async () => {
m = await machine(new UserId("@alice:example.org"), new DeviceId("DEVICEID"));
const toDeviceEvents = JSON.stringify([]);
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = new Map();
const unusedFallbackKeys = new Set();
const receiveSyncChanges = await m.receiveSyncChanges(
toDeviceEvents,
changedDevices,
oneTimeKeyCounts,
unusedFallbackKeys,
);
outgoingRequests = await m.outgoingRequests();
expect(outgoingRequests).toHaveLength(2);
});
test("can mark requests as sent", async () => {
{
const request = outgoingRequests[0];
expect(request).toBeInstanceOf(KeysUploadRequest);
// https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3keysupload
const hypotheticalResponse = JSON.stringify({
one_time_key_counts: {
curve25519: 10,
signed_curve25519: 20,
},
});
const marked = await m.markRequestAsSent(request.id!, request.type, hypotheticalResponse);
expect(marked).toStrictEqual(true);
}
{
const request = outgoingRequests[1];
expect(request).toBeInstanceOf(KeysQueryRequest);
// https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3keysquery
const hypotheticalResponse = JSON.stringify({
device_keys: {
"@alice:example.org": {
JLAFKJWSCS: {
algorithms: ["m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"],
device_id: "JLAFKJWSCS",
keys: {
"curve25519:JLAFKJWSCS": "wjLpTLRqbqBzLs63aYaEv2Boi6cFEbbM/sSRQ2oAKk4",
"ed25519:JLAFKJWSCS": "nE6W2fCblxDcOFmeEtCHNl8/l8bXcu7GKyAswA4r3mM",
},
signatures: {
"@alice:example.org": {
"ed25519:JLAFKJWSCS":
"m53Wkbh2HXkc3vFApZvCrfXcX3AI51GsDHustMhKwlv3TuOJMj4wistcOTM8q2+e/Ro7rWFUb9ZfnNbwptSUBA",
},
},
unsigned: {
device_display_name: "Alice's mobile phone",
},
user_id: "@alice:example.org",
},
},
},
failures: {},
});
const marked = await m.markRequestAsSent(request.id!, request.type, hypotheticalResponse);
expect(marked).toStrictEqual(true);
}
});
});
describe("setup workflow to encrypt/decrypt events", () => {
let m: OlmMachine;
const user = new UserId("@alice:example.org");
const device = new DeviceId("JLAFKJWSCS");
const room = new RoomId("!test:localhost");
beforeAll(async () => {
m = await machine(user, device);
});
test("can pass keysquery and keysclaim requests directly", async () => {
{
// derived from https://github.com/matrix-org/matrix-rust-sdk/blob/7f49618d350fab66b7e1dc4eaf64ec25ceafd658/benchmarks/benches/crypto_bench/keys_query.json
const hypotheticalResponse = JSON.stringify({
device_keys: {
"@example:localhost": {
AFGUOBTZWM: {
algorithms: ["m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"],
device_id: "AFGUOBTZWM",
keys: {
"curve25519:AFGUOBTZWM": "boYjDpaC+7NkECQEeMh5dC+I1+AfriX0VXG2UV7EUQo",
"ed25519:AFGUOBTZWM": "NayrMQ33ObqMRqz6R9GosmHdT6HQ6b/RX/3QlZ2yiec",
},
signatures: {
"@example:localhost": {
"ed25519:AFGUOBTZWM":
"RoSWvru1jj6fs2arnTedWsyIyBmKHMdOu7r9gDi0BZ61h9SbCK2zLXzuJ9ZFLao2VvA0yEd7CASCmDHDLYpXCA",
},
},
user_id: "@example:localhost",
unsigned: {
device_display_name: "rust-sdk",
},
},
},
},
failures: {},
master_keys: {
"@example:localhost": {
user_id: "@example:localhost",
usage: ["master"],
keys: {
"ed25519:n2lpJGx0LiKnuNE1IucZP3QExrD4SeRP0veBHPe3XUU":
"n2lpJGx0LiKnuNE1IucZP3QExrD4SeRP0veBHPe3XUU",
},
signatures: {
"@example:localhost": {
"ed25519:TCSJXPWGVS":
"+j9G3L41I1fe0++wwusTTQvbboYW0yDtRWUEujhwZz4MAltjLSfJvY0hxhnz+wHHmuEXvQDen39XOpr1p29sAg",
},
},
},
},
self_signing_keys: {
"@example:localhost": {
user_id: "@example:localhost",
usage: ["self_signing"],
keys: {
"ed25519:kQXOuy639Yt47mvNTdrIluoC6DMvfbZLYbxAmwiDyhI":
"kQXOuy639Yt47mvNTdrIluoC6DMvfbZLYbxAmwiDyhI",
},
signatures: {
"@example:localhost": {
"ed25519:n2lpJGx0LiKnuNE1IucZP3QExrD4SeRP0veBHPe3XUU":
"q32ifix/qyRpvmegw2BEJklwoBCAJldDNkcX+fp+lBA4Rpyqtycxge6BA4hcJdxYsy3oV0IHRuugS8rJMMFyAA",
},
},
},
},
user_signing_keys: {
"@example:localhost": {
user_id: "@example:localhost",
usage: ["user_signing"],
keys: {
"ed25519:g4ED07Fnqf3GzVWNN1pZ0IFrPQVdqQf+PYoJNH4eE0s":
"g4ED07Fnqf3GzVWNN1pZ0IFrPQVdqQf+PYoJNH4eE0s",
},
signatures: {
"@example:localhost": {
"ed25519:n2lpJGx0LiKnuNE1IucZP3QExrD4SeRP0veBHPe3XUU":
"nKQu8alQKDefNbZz9luYPcNj+Z+ouQSot4fU/A23ELl1xrI06QVBku/SmDx0sIW1ytso0Cqwy1a+3PzCa1XABg",
},
},
},
},
});
const marked = await m.markRequestAsSent("foo", RequestType.KeysQuery, hypotheticalResponse);
}
{
// derived from https://github.com/matrix-org/matrix-rust-sdk/blob/7f49618d350fab66b7e1dc4eaf64ec25ceafd658/benchmarks/benches/crypto_bench/keys_claim.json
const hypotheticalResponse = JSON.stringify({
one_time_keys: {
"@example:localhost": {
AFGUOBTZWM: {
"signed_curve25519:AAAABQ": {
key: "9IGouMnkB6c6HOd4xUsNv4i3Dulb4IS96TzDordzOws",
signatures: {
"@example:localhost": {
"ed25519:AFGUOBTZWM":
"2bvUbbmJegrV0eVP/vcJKuIWC3kud+V8+C0dZtg4dVovOSJdTP/iF36tQn2bh5+rb9xLlSeztXBdhy4c+LiOAg",
},
},
},
},
},
},
failures: {},
});
const marked = await m.markRequestAsSent("bar", RequestType.KeysClaim, hypotheticalResponse);
}
});
test("can share a room key", async () => {
const other_user_id = new UserId("@example:localhost");
const requests = await m.shareRoomKey(room, [other_user_id.clone()], new EncryptionSettings());
expect(requests).toHaveLength(1);
expect(requests[0]).toBeInstanceOf(ToDeviceRequest);
expect(requests[0].event_type).toEqual("m.room.encrypted");
expect(requests[0].txn_id).toBeDefined();
expect(requests[0].id).toBeDefined();
const content = JSON.parse(requests[0].body);
expect(Object.keys(content.messages)).toEqual(["@example:localhost"]);
const messageContent = content.messages["@example:localhost"]["AFGUOBTZWM"];
expect(messageContent["org.matrix.msgid"]).toBeDefined();
await m.markRequestAsSent(requests[0].id, RequestType.ToDevice, "{}");
const requestsAfterMarkedAsSent = await m.shareRoomKey(
room,
[other_user_id.clone()],
new EncryptionSettings(),
);
expect(requestsAfterMarkedAsSent).toHaveLength(0);
});
let encrypted: Record<string, any>;
test("can encrypt an event", async () => {
encrypted = JSON.parse(
await m.encryptRoomEvent(
room,
"m.room.message",
JSON.stringify({
msgtype: "m.text",
body: "Hello, World!",
}),
),
);
expect(encrypted.algorithm).toBeDefined();
expect(encrypted.ciphertext).toBeDefined();
expect(encrypted.sender_key).toBeDefined();
expect(encrypted.device_id).toStrictEqual(device.toString());
expect(encrypted.session_id).toBeDefined();
});
test("can decrypt an event", async () => {
const stringifiedEvent = JSON.stringify({
type: "m.room.encrypted",
event_id: "$xxxxx:example.org",
origin_server_ts: Date.now(),
sender: user.toString(),
content: encrypted,
unsigned: {
age: 1234,
},
});
const decryptionSettings = new DecryptionSettings(TrustRequirement.Untrusted);
const decrypted = await m.decryptRoomEvent(stringifiedEvent, room, decryptionSettings);
expect(decrypted).toBeInstanceOf(DecryptedRoomEvent);
const event = JSON.parse(decrypted.event);
expect(event.content.msgtype).toStrictEqual("m.text");
expect(event.content.body).toStrictEqual("Hello, World!");
expect(decrypted.sender.toString()).toStrictEqual(user.toString());
expect(decrypted.senderDevice.toString()).toStrictEqual(device.toString());
expect(decrypted.senderCurve25519Key).toBeDefined();
expect(decrypted.senderClaimedEd25519Key).toBeDefined();
expect(decrypted.forwardingCurve25519KeyChain).toHaveLength(0);
expect(decrypted.shieldState(true).color).toStrictEqual(ShieldColor.Red);
expect(decrypted.shieldState(true).code).toStrictEqual(ShieldStateCode.UnverifiedIdentity);
expect(decrypted.shieldState(false).color).toStrictEqual(ShieldColor.Red);
expect(decrypted.shieldState(false).code).toStrictEqual(ShieldStateCode.UnsignedDevice);
const decryptionInfo = await m.getRoomEventEncryptionInfo(stringifiedEvent, room);
expect(decryptionInfo.sender.toString()).toStrictEqual(user.toString());
expect(decryptionInfo.senderDevice.toString()).toStrictEqual(device.toString());
expect(decryptionInfo.senderCurve25519Key).toBeDefined();
expect(decryptionInfo.senderClaimedEd25519Key).toBeDefined();
expect(decryptionInfo.shieldState(true).color).toStrictEqual(ShieldColor.Red);
expect(decryptionInfo.shieldState(true).code).toStrictEqual(ShieldStateCode.UnverifiedIdentity);
expect(decryptionInfo.shieldState(false).color).toStrictEqual(ShieldColor.Red);
expect(decryptionInfo.shieldState(false).code).toStrictEqual(ShieldStateCode.UnsignedDevice);
});
});
test("failure to decrypt returns a valid error", async () => {
const m = await machine();
const evt = {
type: "m.room.encrypted",
event_id: "$xxxxx:example.org",
origin_server_ts: Date.now(),
sender: user.toString(),
content: {
algorithm: "m.megolm.v1.aes-sha2",
ciphertext: "blah",
},
};
try {
const decryptionSettings = new DecryptionSettings(TrustRequirement.Untrusted);
await m.decryptRoomEvent(JSON.stringify(evt), room, decryptionSettings);
fail("it should not reach here");
} catch (err) {
expect(err).toBeInstanceOf(MegolmDecryptionError);
expect((err as MegolmDecryptionError).code).toStrictEqual(DecryptionErrorCode.UnableToDecrypt);
}
});
test("can read cross-signing status", async () => {
const m = await machine();
const crossSigningStatus = await m.crossSigningStatus();
expect(crossSigningStatus).toBeInstanceOf(CrossSigningStatus);
expect(crossSigningStatus.hasMaster).toStrictEqual(false);
expect(crossSigningStatus.hasSelfSigning).toStrictEqual(false);
expect(crossSigningStatus.hasUserSigning).toStrictEqual(false);
});
test("can sign a message", async () => {
const m = await machine();
const signatures = await m.sign("foo");
expect(signatures.isEmpty()).toStrictEqual(false);
expect(signatures.count).toStrictEqual(1);
let base64;
// `get`
{
const signature = signatures.get(user);
expect(signature.has("ed25519:foobar")).toStrictEqual(true);
const s = signature.get("ed25519:foobar");
expect(s).toBeInstanceOf(MaybeSignature);
expect(s.isValid()).toStrictEqual(true);
expect(s.isInvalid()).toStrictEqual(false);
expect(s.invalidSignatureSource).toBeUndefined();
base64 = s.signature.toBase64();
expect(base64).toMatch(/^[A-Za-z0-9\+/]+$/);
expect(s.signature.ed25519.toBase64()).toStrictEqual(base64);
}
// `getSignature`
{
const signature = signatures.getSignature(user, new DeviceKeyId("ed25519:foobar"));
expect(signature.toBase64()).toStrictEqual(base64);
}
// Unknown signatures.
{
expect(signatures.get(new UserId("@hello:example.org"))).toBeUndefined();
expect(signatures.getSignature(user, new DeviceKeyId("world:foobar"))).toBeUndefined();
}
});
test("can mark all tracked users as dirty", async () => {
const m = await machine();
await m.markAllTrackedUsersAsDirty();
});
test("can get own user identity", async () => {
const m = await machine();
let _ = m.bootstrapCrossSigning(true);
const identity = await m.getIdentity(user);
expect(identity.isVerified()).toStrictEqual(true);
expect(identity.wasPreviouslyVerified()).toStrictEqual(true);
expect(identity.hasVerificationViolation()).toStrictEqual(false);
expect(identity).toBeInstanceOf(OwnUserIdentity);
const masterKey = JSON.parse(identity.masterKey);
const selfSigningKey = JSON.parse(identity.selfSigningKey);
const userSigningKey = JSON.parse(identity.userSigningKey);
const masterObjKeys = Object.keys(masterKey.keys);
const keyFromMasterKey = masterKey.keys[masterObjKeys[0]];
// self signing key exists
expect(Object.keys(selfSigningKey.keys).length).toBe(1);
// self signing key is different from the master key
expect(selfSigningKey.keys[keyFromMasterKey]).not.toBeDefined();
const selfSigningObjKeys = Object.keys(selfSigningKey.keys);
const keyFromSelfSigningKey = masterKey.keys[selfSigningObjKeys[0]];
// user signing key exists
expect(Object.keys(userSigningKey.keys).length).toBe(1);
// user signing key is different from the master key
expect(userSigningKey.keys[keyFromMasterKey]).not.toBeDefined();
// user signing key is different from the self signing key
expect(userSigningKey.keys[keyFromSelfSigningKey]).not.toBeDefined();
const signatureUploadRequest = await identity.verify();
expect(signatureUploadRequest).toBeInstanceOf(SignatureUploadRequest);
const [verificationRequest, outgoingVerificationRequest] = await identity.requestVerification();
expect(verificationRequest).toBeInstanceOf(VerificationRequest);
expect(outgoingVerificationRequest).toBeInstanceOf(ToDeviceRequest);
const isTrusted = await identity.trustsOurOwnDevice();
expect(isTrusted).toStrictEqual(false);
});
test("Updating user identity should call userIdentityUpdatedCallback", async () => {
const m = await machine();
let _ = m.bootstrapCrossSigning(true);
const identity = await m.getIdentity(user);
expect(identity).toBeInstanceOf(OwnUserIdentity);
const callback = jest.fn().mockImplementation(() => Promise.resolve(undefined));
m.registerUserIdentityUpdatedCallback(callback);
await identity.verify();
expect(callback).toHaveBeenCalledTimes(1);
const [userId] = callback.mock.calls[0];
expect(userId.toString()).toEqual(user.toString());
});
test("Receiving a withheld message should call roomKeysWithheldCallback", async () => {
const m = await machine();
const callback = jest.fn().mockImplementation(() => Promise.resolve(undefined));
await m.registerRoomKeysWithheldCallback(callback);
let toDeviceEvents = [
{
sender: "@alice:example.com",
type: "m.room_key.withheld",
content: {
algorithm: "m.megolm.v1.aes-sha2",
code: "m.unverified",
reason: "Device not verified",
room_id: "!Cuyf34gef24t:localhost",
sender_key: "RF3s+E7RkTQTGF2d8Deol0FkQvgII2aJDf3/Jp5mxVU",
session_id: "X3lUlvLELLYxeTx4yOVu6UDpasGEVO0Jbu+QFnm0cKQ",
},
},
];
await m.receiveSyncChanges(
JSON.stringify(toDeviceEvents),
new DeviceLists(),
new Map<string, number>(),
undefined,
);
expect(callback).toHaveBeenCalledTimes(1);
const withheld: RoomKeyWithheldInfo[] = callback.mock.calls[0][0];
expect(withheld[0].sender.toString()).toEqual("@alice:example.com");
expect(withheld[0].roomId.toString()).toEqual("!Cuyf34gef24t:localhost");
expect(withheld[0].sessionId).toEqual("X3lUlvLELLYxeTx4yOVu6UDpasGEVO0Jbu+QFnm0cKQ");
expect(withheld[0].withheldCode).toEqual("m.unverified");
});
test("can export room keys", async () => {
let m = await machine();
await m.shareRoomKey(room, [new UserId("@bob:example.org")], new EncryptionSettings());
let exportedRoomKeys = await m.exportRoomKeys((session: InboundGroupSession) => {
expect(session).toBeInstanceOf(InboundGroupSession);
expect(session.senderKey.toBase64()).toEqual(m.identityKeys.curve25519.toBase64());
expect(session.roomId.toString()).toStrictEqual(room.toString());
expect(session.sessionId).toBeDefined();
expect(session.hasBeenImported()).toStrictEqual(false);
return true;
});
const roomKeys = JSON.parse(exportedRoomKeys);
expect(roomKeys).toHaveLength(1);
expect(roomKeys[0]).toMatchObject({
algorithm: expect.any(String),
room_id: room.toString(),
sender_key: expect.any(String),
session_id: expect.any(String),
session_key: expect.any(String),
sender_claimed_keys: {
ed25519: expect.any(String),
},
forwarding_curve25519_key_chain: [],
});
});
describe("can process exported room keys", () => {
let exportedRoomKeys: string;
beforeEach(async () => {
let m = await machine();
await m.shareRoomKey(room, [new UserId("@bob:example.org")], new EncryptionSettings());
exportedRoomKeys = await m.exportRoomKeys(() => true);
});
test("can encrypt and decrypt the exported room keys", () => {
let encryptionPassphrase = "Hello, Matrix!";
let encryptedExportedRoomKeys = OlmMachine.encryptExportedRoomKeys(
exportedRoomKeys,
encryptionPassphrase,
100000,
);
expect(encryptedExportedRoomKeys).toMatch(/^-----BEGIN MEGOLM SESSION DATA-----/);
const decryptedExportedRoomKeys = OlmMachine.decryptExportedRoomKeys(
encryptedExportedRoomKeys,
encryptionPassphrase,
);
expect(decryptedExportedRoomKeys).toStrictEqual(exportedRoomKeys);
});
test("can import room keys via importRoomKeys", async () => {
const progressListener = (progress: bigint, total: bigint) => {
expect(progress).toBeLessThan(total);
// Since it's called only once, let's be crazy.
expect(progress).toStrictEqual(0);
expect(total).toStrictEqual(1);
};
let m = await machine();
const result = JSON.parse(await m.importRoomKeys(exportedRoomKeys, progressListener));
expect(result).toMatchObject({
imported_count: expect.any(Number),
total_count: expect.any(Number),
keys: expect.any(Object),
});
});
test("can import room keys via importExportedRoomKeys", async () => {
const progressListener = (progress: bigint, total: bigint) => {
expect(progress).toStrictEqual(0);
expect(total).toStrictEqual(1);
};
let m = await machine();
const result = await m.importExportedRoomKeys(exportedRoomKeys, progressListener);
expect(result.importedCount).toStrictEqual(1);
expect(result.totalCount).toStrictEqual(1);
expect(result.keys()).toMatchObject(
new Map([[room.toString(), new Map([[expect.any(String), new Set([expect.any(String)])]])]]),
);
});
test("importing room keys calls RoomKeyUpdatedCallback", async () => {
const callback = jest.fn();
callback.mockImplementation(() => Promise.resolve(undefined));
let m = await machine();
m.registerRoomKeyUpdatedCallback(callback);
await m.importRoomKeys(exportedRoomKeys, () => undefined);
expect(callback).toHaveBeenCalledTimes(1);
let keyInfoList = callback.mock.calls[0][0];
expect(keyInfoList.length).toEqual(1);
expect(keyInfoList[0].roomId.toString()).toStrictEqual(room.toString());
});
});
describe("can do in-room verification", () => {
let m: OlmMachine;
const user = new UserId("@alice:example.org");
const device = new DeviceId("JLAFKJWSCS");
const room = new RoomId("!test:localhost");
beforeAll(async () => {
m = await machine(user, device);
});
test("can inject devices from someone else", async () => {
{
const hypotheticalResponse = JSON.stringify({
device_keys: {
"@example:morpheus.localhost": {
ATRLDCRXAC: {
algorithms: ["m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"],
device_id: "ATRLDCRXAC",
keys: {
"curve25519:ATRLDCRXAC": "cAVT5Es3Z3F5pFD+2w3HT7O9+R3PstzYVkzD51X/FWQ",
"ed25519:ATRLDCRXAC": "V2w/T/x7i7AXiCCtS6JldrpbvRliRoef3CqTUNqMRHA",
},
signatures: {
"@example:morpheus.localhost": {
"ed25519:ATRLDCRXAC":
"ro2BjO5J6089B/JOANHnFmGrogrC2TIdMlgJbJO00DjOOcGxXfvOezCFIORTwZNHvkHU617YIGl/4keTDIWvBQ",
},
},
user_id: "@example:morpheus.localhost",
unsigned: {
device_display_name: "Element Desktop: Linux",
},
},
EYYGYTCTNC: {
algorithms: ["m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"],
device_id: "EYYGYTCTNC",
keys: {
"curve25519:EYYGYTCTNC": "Pqu50fo472wgb6NjKkaUxjuqoAIEAmhln2gw/zSQ7Ek",
"ed25519:EYYGYTCTNC": "Pf/2QPvui8lDty6TCTglVPRVM+irNHYavNNkyv5yFpU",
},
signatures: {
"@example:morpheus.localhost": {
"ed25519:EYYGYTCTNC":
"pnP5BYLEUUaxDgrvdzCznkjNDbvY1/MFBr1JejdnLiXlcmxRULQpIWZUCO7QTbULsCwMsYQNGn50nfmjBQX3CQ",
},
},
user_id: "@example:morpheus.localhost",
unsigned: {
device_display_name: "WeeChat-Matrix-rs",
},
},
SUMODVLSIU: {
algorithms: ["m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"],
device_id: "SUMODVLSIU",
keys: {
"curve25519:SUMODVLSIU": "geQXWGWc++gcUHk0JcFmEVSjyzDOnk2mjVsUQwbNqQU",
"ed25519:SUMODVLSIU": "ccktaQ3g+B18E6FwVhTBYie26OlHbvDUzDEtxOQ4Qcs",
},
signatures: {
"@example:morpheus.localhost": {
"ed25519:SUMODVLSIU":
"Yn+AOxHRt1GQpY2xT2Jcqqn8jh5+Vw23ctA7NXyDiWPsLPLNTpjGWHMjZdpUqflQvpiKfhODPICoIa7Pu0iSAg",
"ed25519:rUiMNDjIu6gqsrhJPbj3phyIzuEtuQGrLOEa9mCbtTM":
"Cio6k/sq289XNTOvTCWre7Q6zg+A3euzMUe7Uy1T3gPqYFzX+kt7EAxrhbPqx1HyXAEz9zD0D/uw9VEXFCvWBQ",
},
},
user_id: "@example:morpheus.localhost",