-
Notifications
You must be signed in to change notification settings - Fork 409
Expand file tree
/
Copy pathintegration_tests.rs
More file actions
1588 lines (1278 loc) · 70.4 KB
/
integration_tests.rs
File metadata and controls
1588 lines (1278 loc) · 70.4 KB
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
/// A macro which will run the CryptoStore integration test suite.
///
/// You need to provide a `async fn get_store() -> StoreResult<impl StateStore>`
/// providing a fresh store on the same level you invoke the macro.
///
/// ## Usage Example:
/// ```no_run
/// # use matrix_sdk_crypto::store::{
/// # MemoryStore as MyCryptoStore,
/// # };
///
/// #[cfg(test)]
/// mod tests {
/// use super::MyCryptoStore;
///
/// async fn get_store(
/// name: &str,
/// passphrase: Option<&str>,
/// clear_data: bool,
/// ) -> MyCryptoStore {
/// let store = MyCryptoStore::new();
/// if clear_data {
/// store.clear();
/// }
/// store
/// }
///
/// cryptostore_integration_tests!();
/// }
/// ```
#[allow(unused_macros)]
#[macro_export]
macro_rules! cryptostore_integration_tests {
() => {
mod cryptostore_integration_tests {
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::Deref;
use std::time::Duration;
use assert_matches::assert_matches;
use matrix_sdk_test::async_test;
use ruma::{
device_id, events::secret::request::SecretName, room_id, serde::Raw, owned_room_id,
to_device::DeviceIdOrAllDevices, user_id, DeviceId, RoomId, TransactionId, UserId,
};
use serde_json::value::to_raw_value;
use serde_json::json;
use matrix_sdk_common::deserialized_responses::WithheldCode;
use $crate::{
olm::{
Account, Curve25519PublicKey, InboundGroupSession, OlmMessageHash,
PrivateCrossSigningIdentity, SenderData, SenderDataType, Session
},
store::{
types::{
BackupDecryptionKey, Changes, DehydratedDeviceKey, DeviceChanges,
IdentityChanges, PendingChanges, StoredRoomKeyBundleData, RoomKeyWithheldEntry,
RoomSettings
},
CryptoStore, GossipRequest,
},
testing::{get_device, get_other_identity, get_own_identity},
types::{
events::{
dummy::DummyEventContent,
olm_v1::{DecryptedSecretSendEvent, OlmV1Keys},
room_key_request::MegolmV1AesSha2Content,
room_key_withheld::{
CommonWithheldCodeContent, MegolmV1AesSha2WithheldContent,
RoomKeyWithheldContent,
},
room_key_bundle::RoomKeyBundleContent,
secret_send::SecretSendContent,
ToDeviceEvent,
},
requests::ToDeviceRequest,
DeviceKeys,
EventEncryptionAlgorithm,
},
vodozemac::megolm::{GroupSession, SessionConfig}, DeviceData, GossippedSecret, LocalTrust, SecretInfo,
TrackedUser,
};
use super::get_store;
fn alice_id() -> &'static UserId {
user_id!("@alice:example.org")
}
fn alice_device_id() -> &'static DeviceId {
device_id!("ALICEDEVICE")
}
fn bob_id() -> &'static UserId {
user_id!("@bob:example.org")
}
fn bob_device_id() -> &'static DeviceId {
device_id!("BOBDEVICE")
}
pub async fn get_loaded_store(name: &str) -> (Account, impl CryptoStore + use<>) {
let store = get_store(name, None, true).await;
let account = get_account();
store.save_pending_changes(PendingChanges { account: Some(account.deep_clone()), }).await.expect("Can't save account");
(account, store)
}
fn get_account() -> Account {
Account::with_device_id(alice_id(), alice_device_id())
}
pub(crate) async fn get_account_and_session() -> (Account, Session) {
let alice = Account::with_device_id(alice_id(), alice_device_id());
let mut bob = Account::with_device_id(bob_id(), bob_device_id());
bob.generate_one_time_keys(1);
let one_time_key = *bob.one_time_keys().values().next().unwrap();
let sender_key = bob.identity_keys().curve25519;
let session = alice.create_outbound_session_helper(
Default::default(),
sender_key,
one_time_key,
false,
alice.device_keys(),
);
(alice, session)
}
#[async_test]
async fn test_save_account_via_generic_save() {
let store = get_store("save_account_via_generic", None, true).await;
assert!(store.get_static_account().is_none());
assert!(store.load_account().await.unwrap().is_none());
let account = get_account();
store
.save_pending_changes(PendingChanges { account: Some(account) })
.await
.expect("Can't save account");
assert!(store.get_static_account().is_some());
}
#[async_test]
async fn test_save_account() {
let store = get_store("save_account", None, true).await;
assert!(store.get_static_account().is_none());
assert!(store.load_account().await.unwrap().is_none());
let account = get_account();
store
.save_pending_changes(PendingChanges { account: Some(account) })
.await
.expect("Can't save account");
assert!(store.get_static_account().is_some());
}
#[async_test]
async fn test_load_account() {
let store = get_store("load_account", None, true).await;
let account = get_account();
store
.save_pending_changes(PendingChanges { account: Some(account.deep_clone()) })
.await
.expect("Can't save account");
let loaded_account = store.load_account().await.expect("Can't load account");
let loaded_account = loaded_account.unwrap();
assert_eq!(account, loaded_account);
}
#[async_test]
async fn test_load_account_with_passphrase() {
let passphrase = Some("secret_passphrase");
let store = get_store("load_account_with_passphrase", passphrase, true).await;
let account = get_account();
store
.save_pending_changes(PendingChanges { account: Some(account.deep_clone()) })
.await
.expect("Can't save account");
let loaded_account = store.load_account().await.expect("Can't load account");
let loaded_account = loaded_account.unwrap();
assert_eq!(account, loaded_account);
}
#[async_test]
async fn test_save_and_share_account() {
let store = get_store("save_and_share_account", None, true).await;
let mut account = get_account();
store
.save_pending_changes(PendingChanges { account: Some(account.deep_clone()) })
.await
.expect("Can't save account");
account.mark_as_shared();
account.update_uploaded_key_count(50);
store
.save_pending_changes(PendingChanges { account: Some(account.deep_clone()) })
.await
.expect("Can't save account");
let loaded_account = store.load_account().await.expect("Can't load account");
let loaded_account = loaded_account.unwrap();
assert_eq!(account, loaded_account);
assert_eq!(account.uploaded_key_count(), loaded_account.uploaded_key_count());
}
#[async_test]
async fn test_load_sessions() {
let store = get_store("load_sessions", None, true).await;
let (account, session) = get_account_and_session().await;
store
.save_pending_changes(PendingChanges { account: Some(account.deep_clone()) })
.await
.expect("Can't save account");
let changes = Changes {
sessions: vec![session.clone()],
devices: DeviceChanges { new: vec![DeviceData::from_account(&account)], ..Default::default() },
..Default::default()
};
store.save_changes(changes).await.unwrap();
let sessions = store
.get_sessions(&session.sender_key.to_base64())
.await
.expect("Can't load sessions")
.unwrap();
let loaded_session = sessions.get(0).cloned().expect("We should find the session in the store.");
assert_eq!(&session, &loaded_session, "The loaded session should be the same one we put into the store.");
}
#[async_test]
async fn test_add_and_save_session() {
let store_name = "add_and_save_session";
// Given we created a session and saved it in the store
let (session_id, account, sender_key) = {
let store = get_store(store_name, None, true).await;
let (account, session) = get_account_and_session().await;
let sender_key = session.sender_key.to_base64();
let session_id = session.session_id().to_owned();
store
.save_pending_changes(PendingChanges {
account: Some(account.deep_clone()),
})
.await
.expect("Can't save account");
store
.save_changes(Changes {
devices: DeviceChanges {
new: vec![DeviceData::from_account(&account)],
..Default::default()
},
..Default::default()
})
.await
.unwrap();
let changes = Changes { sessions: vec![session.clone()], ..Default::default() };
store.save_changes(changes).await.unwrap();
let sessions = store.get_sessions(&sender_key).await.unwrap().unwrap();
let session = &sessions[0];
assert_eq!(session_id, session.session_id());
(session_id, account, sender_key)
};
// When we reload the store
let store = get_store(store_name, None, false).await;
// Then the same account and session info was reloaded
let loaded_account = store.load_account().await.unwrap().unwrap();
assert_eq!(account, loaded_account);
let sessions = store.get_sessions(&sender_key).await.unwrap().unwrap();
let session = &sessions[0];
assert_eq!(session_id, session.session_id());
}
#[async_test]
async fn test_load_outbound_group_session() {
let dir = "load_outbound_group_session";
let room_id = room_id!("!test:localhost");
// Given we saved an outbound group session
{
let (account, store) = get_loaded_store(dir.clone()).await;
assert!(
store.get_outbound_group_session(&room_id).await.unwrap().is_none(),
"Initially there should be no outbound group session"
);
let (session, _) =
account.create_group_session_pair_with_defaults(&room_id).await;
let user_id = user_id!("@example:localhost");
let request = ToDeviceRequest::new(
user_id,
DeviceIdOrAllDevices::AllDevices,
"m.dummy",
Raw::from_json(to_raw_value(&DummyEventContent::new()).unwrap()),
);
session.add_request(TransactionId::new(), request.into(), Default::default());
let changes = Changes {
outbound_group_sessions: vec![session.clone()],
..Default::default()
};
store.save_changes(changes).await.expect("Can't save group session");
assert!(
store.get_outbound_group_session(&room_id).await.unwrap().is_some(),
"Sanity: after we've saved one, there should be an outbound_group_session"
);
}
// When we reload the account
let store = get_store(dir, None, false).await;
store.load_account().await.unwrap();
// Then the saved session is restored
assert!(
store.get_outbound_group_session(&room_id).await.unwrap().is_some(),
"The outbound_group_session should have been loaded"
);
}
/// Test that we can import an inbound group session via [`CryptoStore::save_changes`]
#[async_test]
async fn test_save_changes_save_inbound_group_session() {
let (account, store) = get_loaded_store("save_inbound_group_session").await;
let room_id = &room_id!("!test:localhost");
let (_, session) = account.create_group_session_pair_with_defaults(room_id).await;
let changes =
Changes { inbound_group_sessions: vec![session], ..Default::default() };
store.save_changes(changes).await.expect("Can't save group session");
}
/// Test that we can import a backed-up group session via
/// [`CryptoStore::save_inbound_group_sessions`]
#[async_test]
async fn test_save_inbound_group_session_from_backup() {
let (account, store) =
get_loaded_store("save_inbound_group_session_from_backup").await;
let room_id = &room_id!("!test:localhost");
let (_, session) = account.create_group_session_pair_with_defaults(room_id).await;
session.mark_as_backed_up();
store
.save_inbound_group_sessions(vec![session.clone()], Some(&"bkpver1"))
.await
.expect("could not save sessions");
let loaded_session = store
.get_inbound_group_session(&session.room_id, session.session_id())
.await
.expect("error when loading session")
.expect("session not found in store");
assert_eq!(session, loaded_session);
assert_eq!(store.get_inbound_group_sessions().await.unwrap().len(), 1);
assert_eq!(store.inbound_group_session_counts(None).await.unwrap().total, 1);
// It should *not* be returned by a request for backup for the same backup version
let to_back_up = store.inbound_group_sessions_for_backup("bkpver1", 1).await.unwrap();
assert_eq!(to_back_up.len(), 0, "backup was returned by backup query");
assert_eq!(
store.inbound_group_session_counts(Some(&"bkpver1")).await.unwrap().backed_up, 1,
"backed_up count",
);
}
/// Test that the behaviour of a key imported from an *old* backup is correct
///
/// This currently only works on the MemoryStore, so is ignored. The other stores
/// are waiting for more work on https://github.com/element-hq/element-web/issues/26892.
#[ignore]
#[async_test]
async fn test_save_inbound_group_session_from_old_backup() {
let (account, store) =
get_loaded_store("save_inbound_group_session_from_old_backup").await;
let room_id = &room_id!("!test:localhost");
let (_, session) = account.create_group_session_pair_with_defaults(room_id).await;
session.mark_as_backed_up();
store
.save_inbound_group_sessions(vec![session.clone()], Some(&"bkpver1"))
.await
.expect("could not save sessions");
// The session should be returned by a request for backup from a different backup version.
let to_back_up = store.inbound_group_sessions_for_backup("bkpver2", 1).await.unwrap();
assert_eq!(to_back_up, vec![session]);
assert_eq!(
store.inbound_group_session_counts(Some(&"bkpver2")).await.unwrap().backed_up, 0,
"backed_up count for backup version 2",
);
}
/// Test that we can import a not-backed-up group session via
/// [`CryptoStore::save_inbound_group_sessions`]
#[async_test]
async fn test_save_inbound_group_session_from_import() {
let (account, store) =
get_loaded_store("save_inbound_group_session_from_import").await;
let room_id = &room_id!("!test:localhost");
let (_, session) = account.create_group_session_pair_with_defaults(room_id).await;
store
.save_inbound_group_sessions(vec![session.clone()], None)
.await
.expect("could not save sessions");
let loaded_session = store
.get_inbound_group_session(&session.room_id, session.session_id())
.await
.expect("error when loading session")
.expect("session not found in store");
assert_eq!(session, loaded_session);
assert_eq!(store.get_inbound_group_sessions().await.unwrap().len(), 1);
assert_eq!(store.inbound_group_session_counts(None).await.unwrap().total, 1);
assert_eq!(store.inbound_group_session_counts(None).await.unwrap().backed_up, 0);
// It should be returned by a request for backup
let to_back_up = store.inbound_group_sessions_for_backup("bkpver1", 1).await.unwrap();
assert_eq!(to_back_up, vec![session]);
}
#[async_test]
async fn test_mark_inbound_group_sessions_as_backed_up() {
// Given a store exists with multiple unbacked-up sessions
let (account, store) =
get_loaded_store("mark_inbound_group_sessions_as_backed_up").await;
let room_id = &room_id!("!test:localhost");
let mut sessions: Vec<InboundGroupSession> = Vec::with_capacity(10);
for _i in 0..10 {
sessions.push(account.create_group_session_pair_with_defaults(room_id).await.1);
}
let changes = Changes { inbound_group_sessions: sessions.clone(), ..Default::default() };
store.save_changes(changes).await.expect("Can't save group session");
assert_eq!(store.inbound_group_sessions_for_backup("bkpver", 100).await.unwrap().len(), 10);
// When I mark some as backed up
store.mark_inbound_group_sessions_as_backed_up("bkpver", &[
session_info(&sessions[1]),
session_info(&sessions[3]),
session_info(&sessions[5]),
session_info(&sessions[7]),
session_info(&sessions[9]),
]).await.expect("Failed to mark sessions as backed up");
// And ask which still need backing up
let to_back_up = store.inbound_group_sessions_for_backup("bkpver", 10).await.unwrap();
let needs_backing_up = |i: usize| to_back_up.iter().any(|s| s.session_id() == sessions[i].session_id());
// Then the sessions we said were backed up no longer need backing up
assert!(!needs_backing_up(1));
assert!(!needs_backing_up(3));
assert!(!needs_backing_up(5));
assert!(!needs_backing_up(7));
assert!(!needs_backing_up(9));
// And the sessions we didn't mention still need backing up
assert!(needs_backing_up(0));
assert!(needs_backing_up(2));
assert!(needs_backing_up(4));
assert!(needs_backing_up(6));
assert!(needs_backing_up(8));
assert_eq!(to_back_up.len(), 5);
}
#[async_test]
async fn test_reset_inbound_group_session_for_backup() {
// Given a store exists where all sessions are backed up to backup_1
let (account, store) =
get_loaded_store("reset_inbound_group_session_for_backup").await;
let room_id = &room_id!("!test:localhost");
let mut sessions: Vec<InboundGroupSession> = Vec::with_capacity(10);
for _ in 0..10 {
sessions.push(account.create_group_session_pair_with_defaults(room_id).await.1);
}
let changes = Changes { inbound_group_sessions: sessions.clone(), ..Default::default() };
store.save_changes(changes).await.expect("Can't save group session");
assert_eq!(store.inbound_group_sessions_for_backup("backup_1", 100).await.unwrap().len(), 10);
store.mark_inbound_group_sessions_as_backed_up(
"backup_1",
&(0..10).map(|i| session_info(&sessions[i])).collect::<Vec<_>>(),
).await.expect("Failed to mark sessions as backed up");
// Sanity: none need backing up to the same backup
{
let to_back_up_old = store.inbound_group_sessions_for_backup("backup_1", 10).await.unwrap();
assert_eq!(to_back_up_old.len(), 0);
}
// Some stores ignore backup_version and just reset when you tell them to. Tell
// them here.
store.reset_backup_state().await.expect("reset failed");
// When we ask what needs backing up to a different backup version
let to_back_up = store.inbound_group_sessions_for_backup("backup_02", 10).await.unwrap();
// Then the answer is everything
let needs_backing_up = |i: usize| to_back_up.iter().any(|s| s.session_id() == sessions[i].session_id());
assert!(needs_backing_up(0));
assert!(needs_backing_up(1));
assert!(needs_backing_up(8));
assert!(needs_backing_up(9));
assert_eq!(to_back_up.len(), 10);
}
#[async_test]
async fn test_load_inbound_group_session() {
let dir = "load_inbound_group_session";
let (account, store) = get_loaded_store(dir).await;
assert_eq!(store.get_inbound_group_sessions().await.unwrap().len(), 0);
let room_id = &room_id!("!test:localhost");
let (_, session) = account.create_group_session_pair_with_defaults(room_id).await;
let export = session.export().await;
let session = InboundGroupSession::from_export(&export).unwrap();
let changes =
Changes { inbound_group_sessions: vec![session.clone()], ..Default::default() };
store.save_changes(changes).await.expect("Can't save group session");
drop(store);
let store = get_store(dir, None, false).await;
store.load_account().await.unwrap();
let loaded_session = store
.get_inbound_group_session(&session.room_id, session.session_id())
.await
.unwrap()
.unwrap();
assert_eq!(session, loaded_session);
loaded_session.export().await;
assert_eq!(store.get_inbound_group_sessions().await.unwrap().len(), 1);
assert_eq!(store.inbound_group_session_counts(None).await.unwrap().total, 1);
}
#[async_test]
async fn test_get_inbound_group_sessions_by_room_id_empty() {
let dir = "get_inbound_group_session_by_room_id_empty";
let (_, store) = get_loaded_store(dir).await;
assert_eq!(store.get_inbound_group_sessions().await.unwrap().len(), 0);
let room_id = &room_id!("!testing:localhost");
assert_eq!(store.get_inbound_group_sessions_by_room_id(room_id).await.unwrap().len(), 0);
}
#[async_test]
async fn test_get_inbound_group_sessions_by_room_id() {
let dir = "get_inbound_group_session_by_room_id";
let (account, store) = get_loaded_store(dir).await;
assert_eq!(store.get_inbound_group_sessions().await.unwrap().len(), 0);
let room_id = &room_id!("!testing:localhost");
let (_, session_1) = account.create_group_session_pair_with_defaults(room_id).await;
let (_, session_2) = account.create_group_session_pair_with_defaults(room_id).await;
let second_room_id = &room_id!("!other_room_testing:localhost");
let (_, session_3) = account.create_group_session_pair_with_defaults(second_room_id).await;
let mut sessions = vec![
session_1,
session_2,
session_3
];
let changes = Changes {
inbound_group_sessions: sessions.clone(),
..Default::default()
};
store.save_changes(changes).await.expect("Can't save group session");
drop(store);
// The last session is in a different room, so should not be returned by
// get_inbound_group_sessions_by_room_id. Remove it from the list.
sessions.pop();
let store = get_store(dir, None, false).await;
// Make sure all the sessions are in the store
assert_eq!(store.get_inbound_group_sessions().await.unwrap().len(), 3);
store.load_account().await.unwrap();
let loaded_sessions = store
.get_inbound_group_sessions_by_room_id(room_id)
.await
.unwrap();
assert_eq!(loaded_sessions.len(), 2);
assert_session_lists_eq(sessions, loaded_sessions, "room by id sessions");
}
#[async_test]
async fn test_fetch_inbound_group_sessions_for_device() {
// Given a store exists, containing inbound group sessions from different devices
let (account, store) =
get_loaded_store("fetch_inbound_group_sessions_for_device").await;
let dev1 = Curve25519PublicKey::from_base64(
"wjLpTLRqbqBzLs63aYaEv2Boi6cFEbbM/sSRQ2oAKk4"
).unwrap();
let dev2 = Curve25519PublicKey::from_base64(
"LTpv2DGMhggPAXO02+7f68CNEp6A40F0Yl8B094Y8gc"
).unwrap();
let dev_1_unknown_a = create_session(&account, &dev1, SenderDataType::UnknownDevice).await;
let dev_1_unknown_b = create_session(&account, &dev1, SenderDataType::UnknownDevice).await;
let dev_1_keys_a = create_session(&account, &dev1, SenderDataType::DeviceInfo).await;
let dev_1_keys_b = create_session(&account, &dev1, SenderDataType::DeviceInfo).await;
let dev_1_keys_c = create_session(&account, &dev1, SenderDataType::DeviceInfo).await;
let dev_1_keys_d = create_session(&account, &dev1, SenderDataType::DeviceInfo).await;
let dev_2_unknown = create_session(
&account, &dev2, SenderDataType::UnknownDevice).await;
let dev_2_keys = create_session(
&account, &dev2, SenderDataType::DeviceInfo).await;
let sessions = vec![
dev_1_unknown_a.clone(),
dev_1_unknown_b.clone(),
dev_1_keys_a.clone(),
dev_1_keys_b.clone(),
dev_1_keys_c.clone(),
dev_1_keys_d.clone(),
dev_2_unknown.clone(),
dev_2_keys.clone(),
];
let changes = Changes {
inbound_group_sessions: sessions,
..Default::default()
};
store.save_changes(changes).await.expect("Can't save group session");
// When we fetch the list of sessions for device 1, unknown
let sessions_1_u = store.get_inbound_group_sessions_for_device_batch(
dev1,
SenderDataType::UnknownDevice,
None,
10
).await.expect("Failed to get sessions for dev1");
// Then the expected sessions are returned
assert_session_lists_eq(sessions_1_u, [dev_1_unknown_a, dev_1_unknown_b], "device 1 sessions");
// And when we ask for the list of sessions for device 2, with device keys
let sessions_2_d = store
.get_inbound_group_sessions_for_device_batch(dev2, SenderDataType::DeviceInfo, None, 10)
.await
.expect("Failed to get sessions for dev2");
// Then the matching session is returned
assert_eq!(sessions_2_d, vec![dev_2_keys], "device 2 sessions");
// And we can fetch device 1, keys in batches.
// We call the batch function repeatedly, to ensure it terminates correctly.
let mut sessions_1_k = Vec::new();
let mut previous_last_session_id: Option<String> = None;
loop {
let mut sessions_1_k_batch = store.get_inbound_group_sessions_for_device_batch(
dev1,
SenderDataType::DeviceInfo,
previous_last_session_id,
2
).await.expect("Failed to get batch 1");
// If there are no results in the batch, we have reached the end of the results.
let Some(last_session) = sessions_1_k_batch.last() else {
break;
};
// Check that there are exactly two results in the batch
assert_eq!(sessions_1_k_batch.len(), 2);
previous_last_session_id = Some(last_session.session_id().to_owned());
// Modify one of the results, to check that that doesn't break iteration
let mut last_session = last_session.clone();
last_session.sender_data = SenderData::unknown();
store.save_inbound_group_sessions(vec![last_session], None).await.unwrap();
sessions_1_k.append(&mut sessions_1_k_batch);
}
assert_session_lists_eq(
sessions_1_k,
[dev_1_keys_a, dev_1_keys_b, dev_1_keys_c, dev_1_keys_d],
"device 1 batched results"
);
}
/// Assert that two lists of sessions are the same, modulo ordering.
///
/// There is no requirement for `get_inbound_group_sessions_for_device_batch` to
/// return the results in a specific order. This helper ensures that the two lists
/// of inbound group sessions are equivalent, without worrying about the ordering.
fn assert_session_lists_eq<I, J>(actual: I, expected: J, message: &str)
where I: IntoIterator<Item = InboundGroupSession>, J: IntoIterator<Item = InboundGroupSession>
{
let sorter = |a: &InboundGroupSession, b: &InboundGroupSession| Ord::cmp(a.session_id(), b.session_id());
let mut actual = Vec::from_iter(actual);
actual.sort_unstable_by(sorter);
let mut expected = Vec::from_iter(expected);
expected.sort_unstable_by(sorter);
assert_eq!(actual, expected, "{}", message);
}
#[async_test]
async fn test_tracked_users() {
let dir = "test_tracked_users";
let (_account, store) = get_loaded_store(dir.clone()).await;
let alice = user_id!("@alice:example.org");
let bob = user_id!("@bob:example.org");
let candy = user_id!("@candy:example.org");
let loaded = store.load_tracked_users().await.unwrap();
assert!(loaded.is_empty(), "Initially there are no tracked users");
let users = vec![(alice, true), (bob, false)];
store.save_tracked_users(&users).await.unwrap();
let check_loaded_users = |loaded: Vec<TrackedUser>| {
let loaded: HashMap<_, _> =
loaded.into_iter().map(|u| (u.user_id.to_owned(), u)).collect();
let loaded_alice =
loaded.get(alice).expect("Alice should be in the store as a tracked user");
let loaded_bob =
loaded.get(bob).expect("Bob should be in the store as as tracked user");
assert!(!loaded.contains_key(candy), "Candy shouldn't be part of the store");
assert_eq!(loaded.len(), 2, "Candy shouldn't be part of the store");
assert!(loaded_alice.dirty, "Alice should be considered to be dirty");
assert!(!loaded_bob.dirty, "Bob should not be considered to be dirty");
};
let loaded = store.load_tracked_users().await.unwrap();
check_loaded_users(loaded);
drop(store);
let name = dir.clone();let store = get_store(name, None, false).await;
let loaded = store.load_tracked_users().await.unwrap();
check_loaded_users(loaded);
}
#[async_test]
async fn test_device_saving() {
let dir = "device_saving";
let (_account, store) = get_loaded_store(dir.clone()).await;
let alice_device_1 = DeviceData::from_account(&Account::with_device_id(
"@alice:localhost".try_into().unwrap(),
"FIRSTDEVICE".into(),
));
let alice_device_2 = DeviceData::from_account(&Account::with_device_id(
"@alice:localhost".try_into().unwrap(),
"SECONDDEVICE".into(),
));
let json = json!({
"algorithms": ["m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"],
"user_id": "@bob:localhost",
"device_id": "BOBDEVICE",
"extra_property": "somevalue",
"keys": {
"curve25519:BOBDEVICE": "n0zs7qnaPLLf/OTL+dDLcI5kaPexbUeQ8jLQ2q6sO0E",
"ed25519:BOBDEVICE": "RrKiu4+5EHRBWY6Qj6OtQGC0txpmEeanOz2irEZ/IN4",
},
"signatures": {
"@bob:localhost": {
"ed25519:BOBDEVICE": "9NjPewVHfB7Ah32mJ+CBx64mVoiQ8gbh+/2pc9WfAgut/H0Kqd/bbpgJq9Pn518szaXcGqEq0DxDP6CABBX8CQ",
},
},
});
let bob_device_1_keys: DeviceKeys = serde_json::from_value(json).unwrap();
let bob_device_1 = DeviceData::new(bob_device_1_keys, LocalTrust::Unset);
let changes = Changes {
devices: DeviceChanges {
new: vec![alice_device_1.clone(), alice_device_2.clone(), bob_device_1.clone()],
..Default::default()
},
..Default::default()
};
store.save_changes(changes).await.unwrap();
drop(store);
let store = get_store(dir, None, false).await;
store.load_account().await.unwrap();
let loaded_device = store
.get_device(alice_device_1.user_id(), alice_device_1.device_id())
.await
.unwrap()
.unwrap();
assert_eq!(alice_device_1, loaded_device);
for algorithm in loaded_device.algorithms() {
assert!(alice_device_1.algorithms().contains(algorithm));
}
assert_eq!(alice_device_1.algorithms().len(), loaded_device.algorithms().len());
assert_eq!(alice_device_1.keys(), loaded_device.keys());
let user_devices = store.get_user_devices(alice_device_1.user_id()).await.unwrap();
assert_eq!(user_devices.len(), 2);
let bob_device = store
.get_device(bob_device_1.user_id(), bob_device_1.device_id())
.await
.unwrap();
let bob_device_json = serde_json::to_value(bob_device).unwrap();
assert_eq!(bob_device_json["device_keys"]["extra_property"], json!("somevalue"));
}
#[async_test]
async fn test_device_deleting() {
let dir = "device_deleting";
let (_account, store) = get_loaded_store(dir.clone()).await;
let device = get_device();
let changes = Changes {
devices: DeviceChanges { changed: vec![device.clone()], ..Default::default() },
..Default::default()
};
store.save_changes(changes).await.unwrap();
let changes = Changes {
devices: DeviceChanges { deleted: vec![device.clone()], ..Default::default() },
..Default::default()
};
store.save_changes(changes).await.unwrap();
drop(store);
let store = get_store(dir, None, false).await;
store.load_account().await.unwrap();
let loaded_device =
store.get_device(device.user_id(), device.device_id()).await.unwrap();
assert!(loaded_device.is_none());
}
#[async_test]
async fn test_user_saving() {
let dir = "user_saving";
let user_id = user_id!("@example:localhost");
let device_id: &DeviceId = "WSKKLTJZCL".into();
let store = get_store(dir, None, true).await;
let account = Account::with_device_id(&user_id, device_id);
store.save_pending_changes(PendingChanges { account: Some(account), })
.await
.expect("Can't save account");
let own_identity = get_own_identity();
let changes = Changes {
identities: IdentityChanges {
changed: vec![own_identity.clone().into()],
..Default::default()
},
..Default::default()
};
store.save_changes(changes).await.expect("Can't save identity");
drop(store);
let store = get_store(dir, None, false).await;
store.load_account().await.unwrap();
let loaded_user =
store.get_user_identity(own_identity.user_id()).await.unwrap().unwrap();
assert_eq!(loaded_user.master_key(), own_identity.master_key());
assert_eq!(loaded_user.self_signing_key(), own_identity.self_signing_key());
assert_eq!(loaded_user.own().unwrap().clone(), own_identity.clone());
let other_identity = get_other_identity();
let changes = Changes {
identities: IdentityChanges {
changed: vec![other_identity.clone().into()],
..Default::default()
},
..Default::default()
};
store.save_changes(changes).await.unwrap();
let loaded_user =
store.get_user_identity(other_identity.user_id()).await.unwrap().unwrap();
assert_eq!(loaded_user.master_key(), other_identity.master_key());
assert_eq!(loaded_user.self_signing_key(), other_identity.self_signing_key());
assert_eq!(loaded_user.user_id(), other_identity.user_id());
assert_eq!(loaded_user.other().unwrap().clone(), other_identity);
own_identity.mark_as_verified();
let changes = Changes {
identities: IdentityChanges {
changed: vec![own_identity.into()],
..Default::default()
},
..Default::default()
};
store.save_changes(changes).await.unwrap();
let loaded_user = store.get_user_identity(&user_id).await.unwrap().unwrap();
assert!(loaded_user.own().unwrap().is_verified())
}
#[async_test]
async fn test_private_identity_saving() {
let (_, store) = get_loaded_store("private_identity_saving").await;
assert!(store.load_identity().await.unwrap().is_none());
let identity = PrivateCrossSigningIdentity::new(alice_id().to_owned());
let changes =
Changes { private_identity: Some(identity.clone()), ..Default::default() };
store.save_changes(changes).await.unwrap();
let loaded_identity = store.load_identity().await.unwrap().unwrap();
assert_eq!(identity.user_id(), loaded_identity.user_id());
}
#[async_test]
async fn test_olm_hash_saving() {
let (_, store) = get_loaded_store("olm_hash_saving").await;
let hash = OlmMessageHash {
sender_key: "test_sender".to_owned(),
hash: "test_hash".to_owned(),
};
let mut changes = Changes::default();
changes.message_hashes.push(hash.clone());
assert!(!store.is_message_known(&hash).await.unwrap());
store.save_changes(changes).await.unwrap();
assert!(store.is_message_known(&hash).await.unwrap());
}
#[async_test]