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
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
convert::TryFrom,
ops::Deref,
sync::Arc,
time::Duration,
};
use futures_util::future::join_all;
use matrix_sdk_common::executor::spawn;
use ruma::{
api::client::keys::get_keys::v3::Response as KeysQueryResponse, serde::Raw, DeviceId,
OwnedDeviceId, OwnedUserId, UserId,
};
use tracing::{debug, info, trace, warn};
use crate::{
error::OlmResult,
identities::{
MasterPubkey, ReadOnlyDevice, ReadOnlyOwnUserIdentity, ReadOnlyUserIdentities,
ReadOnlyUserIdentity, SelfSigningPubkey, UserSigningPubkey,
},
olm::PrivateCrossSigningIdentity,
requests::KeysQueryRequest,
store::{Changes, DeviceChanges, IdentityChanges, Result as StoreResult, Store},
types::{CrossSigningKey, DeviceKeys},
LocalTrust,
};
enum DeviceChange {
New(ReadOnlyDevice),
Updated(ReadOnlyDevice),
None,
}
#[derive(Clone, Debug)]
pub(crate) struct KeysQueryListener {
inner: Arc<event_listener::Event>,
store: Store,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Elapsed(());
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum UserKeyQueryResult {
WasPending,
WasNotPending,
}
impl KeysQueryListener {
pub(crate) fn new(store: Store) -> Self {
Self { inner: event_listener::Event::new().into(), store }
}
fn notify(&self) {
self.inner.notify(usize::MAX);
}
pub async fn wait_if_user_pending(
&self,
timeout: Duration,
user: &UserId,
) -> Result<UserKeyQueryResult, Elapsed> {
let users_for_key_query = self.store.users_for_key_query();
if users_for_key_query.contains(user) {
if let Err(e) = self.wait(timeout).await {
warn!(
user_id =% user,
"The user has a pending `/key/query` request which did \
not finish yet, some devices might be missing."
);
Err(e)
} else {
Ok(UserKeyQueryResult::WasPending)
}
} else {
Ok(UserKeyQueryResult::WasNotPending)
}
}
pub async fn wait(&self, timeout: Duration) -> Result<(), Elapsed> {
let listener = self.inner.listen();
#[cfg(not(target_arch = "wasm32"))]
tokio::time::timeout(timeout, async { listener.await }).await.map_err(|_| Elapsed(()))?;
#[cfg(target_arch = "wasm32")]
listener.wait_timeout(timeout);
Ok(())
}
}
#[derive(Debug, Clone)]
pub(crate) struct IdentityManager {
user_id: Arc<UserId>,
device_id: Arc<DeviceId>,
keys_query_listener: KeysQueryListener,
store: Store,
}
impl IdentityManager {
const MAX_KEY_QUERY_USERS: usize = 250;
pub fn new(user_id: Arc<UserId>, device_id: Arc<DeviceId>, store: Store) -> Self {
let keys_query_listener = KeysQueryListener::new(store.clone());
IdentityManager { user_id, device_id, store, keys_query_listener }
}
fn user_id(&self) -> &UserId {
&self.user_id
}
pub fn listen_for_received_queries(&self) -> KeysQueryListener {
self.keys_query_listener.clone()
}
pub async fn receive_keys_query_response(
&self,
response: &KeysQueryResponse,
) -> OlmResult<(DeviceChanges, IdentityChanges)> {
debug!(
users = ?response.device_keys.keys().collect::<BTreeSet<_>>(),
failures = ?response.failures,
"Handling a keys query response"
);
let devices = self.handle_devices_from_key_query(response.device_keys.clone()).await?;
let (identities, cross_signing_identity) = self.handle_cross_singing_keys(response).await?;
let changes = Changes {
identities: identities.clone(),
devices: devices.clone(),
private_identity: cross_signing_identity,
..Default::default()
};
self.store.save_changes(changes).await?;
let updated_users: Vec<&UserId> = response.device_keys.keys().map(Deref::deref).collect();
for user_id in updated_users {
self.store.update_tracked_user(user_id, false).await?;
}
let changed_devices = devices.changed.iter().fold(BTreeMap::new(), |mut acc, d| {
acc.entry(d.user_id()).or_insert_with(BTreeSet::new).insert(d.device_id());
acc
});
let new_devices = devices.new.iter().fold(BTreeMap::new(), |mut acc, d| {
acc.entry(d.user_id()).or_insert_with(BTreeSet::new).insert(d.device_id());
acc
});
let deleted_devices = devices.deleted.iter().fold(BTreeMap::new(), |mut acc, d| {
acc.entry(d.user_id()).or_insert_with(BTreeSet::new).insert(d.device_id());
acc
});
let new_identities = identities.new.iter().map(|i| i.user_id()).collect::<BTreeSet<_>>();
let changed_identities =
identities.changed.iter().map(|i| i.user_id()).collect::<BTreeSet<_>>();
debug!(
?new_devices,
?changed_devices,
?deleted_devices,
?new_identities,
?changed_identities,
"Finished handling of the keys/query response"
);
self.keys_query_listener.notify();
Ok((devices, identities))
}
async fn update_or_create_device(
store: Store,
device_keys: DeviceKeys,
) -> StoreResult<DeviceChange> {
let old_device =
store.get_readonly_device(&device_keys.user_id, &device_keys.device_id).await?;
if let Some(mut device) = old_device {
if let Err(e) = device.update_device(&device_keys) {
warn!(
user_id = device.user_id().as_str(),
device_id = device.device_id().as_str(),
error = ?e,
"Failed to update device keys",
);
Ok(DeviceChange::None)
} else {
Ok(DeviceChange::Updated(device))
}
} else {
match ReadOnlyDevice::try_from(&device_keys) {
Ok(d) => {
if d.user_id() == store.user_id() && d.device_id() == store.device_id() {
let local_device_keys = store.account().unsigned_device_keys();
if d.keys() == &local_device_keys.keys {
d.set_trust_state(LocalTrust::Verified);
trace!(
user_id = d.user_id().as_str(),
device_id = d.device_id().as_str(),
keys = ?d.keys(),
"Adding our own device to the device store, \
marking it as locally verified",
);
Ok(DeviceChange::New(d))
} else {
Ok(DeviceChange::None)
}
} else {
trace!(
user_id = d.user_id().as_str(),
device_id = d.device_id().as_str(),
keys = ?d.keys(),
"Adding a new device to the device store",
);
Ok(DeviceChange::New(d))
}
}
Err(e) => {
warn!(
user_id = device_keys.user_id.as_str(),
device_id = device_keys.device_id.as_str(),
error = ?e,
"Failed to create a new device",
);
Ok(DeviceChange::None)
}
}
}
}
async fn update_user_devices(
store: Store,
own_user_id: Arc<UserId>,
own_device_id: Arc<DeviceId>,
user_id: OwnedUserId,
device_map: BTreeMap<OwnedDeviceId, Raw<ruma::encryption::DeviceKeys>>,
) -> StoreResult<DeviceChanges> {
let own_device_id = (*own_device_id).to_owned();
let mut changes = DeviceChanges::default();
let current_devices: HashSet<OwnedDeviceId> = device_map.keys().cloned().collect();
let tasks = device_map.into_iter().filter_map(|(device_id, device_keys)| match device_keys
.deserialize_as::<DeviceKeys>(
) {
Ok(device_keys) => {
if user_id != device_keys.user_id || device_id != device_keys.device_id {
warn!(
user_id = user_id.as_str(),
device_id = device_id.as_str(),
device_key_user = device_keys.user_id.as_str(),
device_key_device_id = device_keys.device_id.as_str(),
"Mismatch in the device keys payload",
);
None
} else {
Some(spawn(Self::update_or_create_device(store.clone(), device_keys)))
}
}
Err(e) => {
warn!(
user_id = user_id.as_str(),
device_id = device_id.as_str(),
error = ?e,
"Device keys failed to deserialize",
);
None
}
});
let results = join_all(tasks).await;
for device in results {
let device = device.expect("Creating or updating a device panicked")?;
match device {
DeviceChange::New(d) => changes.new.push(d),
DeviceChange::Updated(d) => changes.changed.push(d),
DeviceChange::None => (),
}
}
let current_devices: HashSet<&OwnedDeviceId> = current_devices.iter().collect();
let stored_devices = store.get_readonly_devices_unfiltered(&user_id).await?;
let stored_devices_set: HashSet<&OwnedDeviceId> = stored_devices.keys().collect();
let deleted_devices_set = stored_devices_set.difference(¤t_devices);
for device_id in deleted_devices_set {
if user_id == *own_user_id && *device_id == &own_device_id {
warn!(
user_id = own_user_id.as_str(),
device_id = own_device_id.as_str(),
"Our own device has been deleted"
);
} else if let Some(device) = stored_devices.get(*device_id) {
device.mark_as_deleted();
changes.deleted.push(device.clone());
}
}
Ok(changes)
}
async fn handle_devices_from_key_query(
&self,
device_keys_map: BTreeMap<
OwnedUserId,
BTreeMap<OwnedDeviceId, Raw<ruma::encryption::DeviceKeys>>,
>,
) -> StoreResult<DeviceChanges> {
let mut changes = DeviceChanges::default();
let tasks = device_keys_map.into_iter().map(|(user_id, device_keys_map)| {
spawn(Self::update_user_devices(
self.store.clone(),
self.user_id.clone(),
self.device_id.clone(),
user_id,
device_keys_map,
))
});
let results = join_all(tasks).await;
for result in results {
let change_fragment = result.expect("Panic while updating user devices")?;
changes.extend(change_fragment);
}
Ok(changes)
}
async fn handle_cross_singing_keys(
&self,
response: &KeysQueryResponse,
) -> StoreResult<(IdentityChanges, Option<PrivateCrossSigningIdentity>)> {
let mut changes = IdentityChanges::default();
let mut changed_identity = None;
for (user_id, master_key) in &response.master_keys {
match master_key.deserialize_as::<CrossSigningKey>() {
Ok(master_key) => {
let master_key = MasterPubkey::from(master_key);
let self_signing = if let Some(s) = response
.self_signing_keys
.get(user_id)
.and_then(|k| k.deserialize_as::<CrossSigningKey>().ok())
{
SelfSigningPubkey::from(s)
} else {
warn!(
user_id = user_id.as_str(),
"A user identity didn't contain a self signing pubkey \
or the key was invalid"
);
continue;
};
let result = if let Some(mut i) = self.store.get_user_identity(user_id).await? {
match &mut i {
ReadOnlyUserIdentities::Own(ref mut identity) => {
let user_signing = if let Some(s) = response
.user_signing_keys
.get(user_id)
.and_then(|k| k.deserialize_as::<CrossSigningKey>().ok())
{
UserSigningPubkey::from(s)
} else {
warn!(
user_id = user_id.as_str(),
"User identity for our own user didn't \
contain a user signing pubkey",
);
continue;
};
identity
.update(master_key, self_signing, user_signing)
.map(|_| (i, false))
}
ReadOnlyUserIdentities::Other(ref mut identity) => {
identity.update(master_key, self_signing).map(|_| (i, false))
}
}
} else if user_id == self.user_id() {
if let Some(s) = response
.user_signing_keys
.get(user_id)
.and_then(|k| k.deserialize_as::<CrossSigningKey>().ok())
{
let user_signing = UserSigningPubkey::from(s);
if master_key.user_id() != user_id
|| self_signing.user_id() != user_id
|| user_signing.user_id() != user_id
{
warn!(
user_id = user_id.as_str(),
"User ID mismatch in one of the cross signing keys",
);
continue;
}
ReadOnlyOwnUserIdentity::new(master_key, self_signing, user_signing)
.map(|i| (ReadOnlyUserIdentities::Own(i), true))
} else {
warn!(
user_id = user_id.as_str(),
"User identity for our own user didn't contain a \
user signing pubkey or the key isn't valid",
);
continue;
}
} else if master_key.user_id() != user_id || self_signing.user_id() != user_id {
warn!(
user = user_id.as_str(),
"User ID mismatch in one of the cross signing keys",
);
continue;
} else {
ReadOnlyUserIdentity::new(master_key, self_signing)
.map(|i| (ReadOnlyUserIdentities::Other(i), true))
};
match result {
Ok((i, new)) => {
if let Some(identity) = i.own() {
let private_identity = self.store.private_identity();
let private_identity = private_identity.lock().await;
let result = private_identity.clear_if_differs(identity).await;
if result.any_cleared() {
changed_identity = Some((*private_identity).clone());
info!(cleared = ?result, "Removed some or all of our private cross signing keys");
}
}
if new {
trace!(user_id = user_id.as_str(), identity = ?i, "Created new user identity");
changes.new.push(i);
} else {
trace!(user_id = user_id.as_str(), identity = ?i, "Updated a user identity");
changes.changed.push(i);
}
}
Err(e) => {
warn!(
user_id = user_id.as_str(),
error = ?e,
"Couldn't update or create new user identity"
);
continue;
}
}
}
Err(e) => {
warn!(
user_id = user_id.as_str(),
error = ?e,
"Couldn't update or create new user identity"
);
continue;
}
}
}
Ok((changes, changed_identity))
}
pub async fn users_for_key_query(&self) -> Vec<KeysQueryRequest> {
let users = self.store.users_for_key_query();
let users = if users.is_empty() && !self.store.tracked_users().contains(self.user_id()) {
self.update_tracked_users([self.user_id()]).await;
self.store.users_for_key_query()
} else {
users
};
if users.is_empty() {
Vec::new()
} else {
let users: Vec<OwnedUserId> = users.into_iter().collect();
users
.chunks(Self::MAX_KEY_QUERY_USERS)
.map(|u| u.iter().map(|u| (u.clone(), Vec::new())).collect())
.map(KeysQueryRequest::new)
.collect()
}
}
pub async fn mark_user_as_changed(&self, user_id: &UserId) -> StoreResult<bool> {
if self.store.is_user_tracked(user_id) {
self.store.update_tracked_user(user_id, true).await?;
Ok(true)
} else {
Ok(false)
}
}
pub async fn update_tracked_users(&self, users: impl IntoIterator<Item = &UserId>) {
for user in users {
if self.store.is_user_tracked(user) {
continue;
}
if let Err(e) = self.store.update_tracked_user(user, true).await {
warn!("Error storing users for tracking {}", e);
}
}
}
}
#[cfg(any(test, feature = "testing"))]
pub(crate) mod testing {
#![allow(dead_code)]
use std::sync::Arc;
use matrix_sdk_common::locks::Mutex;
use ruma::{
api::{client::keys::get_keys::v3::Response as KeyQueryResponse, IncomingResponse},
device_id, user_id, DeviceId, UserId,
};
use serde_json::json;
use crate::{
identities::IdentityManager,
machine::testing::response_from_file,
olm::{PrivateCrossSigningIdentity, ReadOnlyAccount},
store::{CryptoStore, MemoryStore, Store},
verification::VerificationMachine,
};
pub fn user_id() -> &'static UserId {
user_id!("@example:localhost")
}
pub fn other_user_id() -> &'static UserId {
user_id!("@example2:localhost")
}
pub fn device_id() -> &'static DeviceId {
device_id!("WSKKLTJZCL")
}
pub(crate) fn manager() -> IdentityManager {
let identity = Arc::new(Mutex::new(PrivateCrossSigningIdentity::empty(user_id())));
let user_id = Arc::from(user_id());
let account = ReadOnlyAccount::new(&user_id, device_id());
let store: Arc<dyn CryptoStore> = Arc::new(MemoryStore::new());
let verification = VerificationMachine::new(account, identity.clone(), store);
let store =
Store::new(user_id.clone(), identity, Arc::new(MemoryStore::new()), verification);
IdentityManager::new(user_id, device_id().into(), store)
}
pub fn other_key_query() -> KeyQueryResponse {
let data = response_from_file(&json!({
"device_keys": {
"@example2:localhost": {
"SKISMLNIMH": {
"algorithms": ["m.olm.v1.curve25519-aes-sha2", "m.megolm.v1.aes-sha2"],
"device_id": "SKISMLNIMH",
"keys": {
"curve25519:SKISMLNIMH": "qO9xFazIcW8dE0oqHGMojGgJwbBpMOhGnIfJy2pzvmI",
"ed25519:SKISMLNIMH": "y3wV3AoyIGREqrJJVH8DkQtlwHBUxoZ9ApP76kFgXQ8"
},
"signatures": {
"@example2:localhost": {
"ed25519:SKISMLNIMH": "YwbT35rbjKoYFZVU1tQP8MsL06+znVNhNzUMPt6jTEYRBFoC4GDq9hQEJBiFSq37r1jvLMteggVAWw37fs1yBA",
"ed25519:ZtFrSkJ1qB8Jph/ql9Eo/lKpIYCzwvKAKXfkaS4XZNc": "PWuuTE/aTkp1EJQkPHhRx2BxbF+wjMIDFxDRp7JAerlMkDsNFUTfRRusl6vqROPU36cl+yY8oeJTZGFkU6+pBQ"
}
},
"user_id": "@example2:localhost",
"unsigned": {
"device_display_name": "Riot Desktop (Linux)"
}
}
}
},
"failures": {},
"master_keys": {
"@example2:localhost": {
"user_id": "@example2:localhost",
"usage": ["master"],
"keys": {
"ed25519:kC/HmRYw4HNqUp/i4BkwYENrf+hd9tvdB7A1YOf5+Do": "kC/HmRYw4HNqUp/i4BkwYENrf+hd9tvdB7A1YOf5+Do"
},
"signatures": {
"@example2:localhost": {
"ed25519:SKISMLNIMH": "KdUZqzt8VScGNtufuQ8lOf25byYLWIhmUYpPENdmM8nsldexD7vj+Sxoo7PknnTX/BL9h2N7uBq0JuykjunCAw"
}
}
}
},
"self_signing_keys": {
"@example2:localhost": {
"user_id": "@example2:localhost",
"usage": ["self_signing"],
"keys": {
"ed25519:ZtFrSkJ1qB8Jph/ql9Eo/lKpIYCzwvKAKXfkaS4XZNc": "ZtFrSkJ1qB8Jph/ql9Eo/lKpIYCzwvKAKXfkaS4XZNc"
},
"signatures": {
"@example2:localhost": {
"ed25519:kC/HmRYw4HNqUp/i4BkwYENrf+hd9tvdB7A1YOf5+Do": "W/O8BnmiUETPpH02mwYaBgvvgF/atXnusmpSTJZeUSH/vHg66xiZOhveQDG4cwaW8iMa+t9N4h1DWnRoHB4mCQ"
}
}
}
},
"user_signing_keys": {}
}));
KeyQueryResponse::try_from_http_response(data)
.expect("Can't parse the keys upload response")
}
pub fn own_key_query() -> KeyQueryResponse {
let data = response_from_file(&json!({
"device_keys": {
"@example:localhost": {
"WSKKLTJZCL": {
"algorithms": [
"m.olm.v1.curve25519-aes-sha2",
"m.megolm.v1.aes-sha2"
],
"device_id": "WSKKLTJZCL",
"keys": {
"curve25519:WSKKLTJZCL": "wnip2tbJBJxrFayC88NNJpm61TeSNgYcqBH4T9yEDhU",
"ed25519:WSKKLTJZCL": "lQ+eshkhgKoo+qp9Qgnj3OX5PBoWMU5M9zbuEevwYqE"
},
"signatures": {
"@example:localhost": {
"ed25519:WSKKLTJZCL": "SKpIUnq7QK0xleav0PrIQyKjVm+TgZr7Yi8cKjLeZDtkgyToE2d4/e3Aj79dqOlLB92jFVE4d1cM/Ry04wFwCA",
"ed25519:0C8lCBxrvrv/O7BQfsKnkYogHZX3zAgw3RfJuyiq210": "9UGu1iC5YhFCdELGfB29YaV+QE0t/X5UDSsPf4QcdZyXIwyp9zBbHX2lh9vWudNQ+akZpaq7ZRaaM+4TCnw/Ag"
}
},
"user_id": "@example:localhost",
"unsigned": {
"device_display_name": "Cross signing capable"
}
},
"LVWOVGOXME": {
"algorithms": [
"m.olm.v1.curve25519-aes-sha2",
"m.megolm.v1.aes-sha2"
],
"device_id": "LVWOVGOXME",
"keys": {
"curve25519:LVWOVGOXME": "KMfWKUhnDW1D11hNzATs/Ax1FQRsJxKCWzq0NyGtIiI",
"ed25519:LVWOVGOXME": "k+NC3L7CBD6fBClcHBrKLOkqCyGNSKhWXiH5Q2STRnA"
},
"signatures": {
"@example:localhost": {
"ed25519:LVWOVGOXME": "39Ir5Bttpc5+bQwzLj7rkjm5E5/cp/JTbMJ/t0enj6J5w9MXVBFOUqqM2hpaRaRwILMMpwYbJ8IOGjl0Y/MGAw"
}
},
"user_id": "@example:localhost",
"unsigned": {
"device_display_name": "Non-cross signing"
}
}
}
},
"failures": {},
"master_keys": {
"@example:localhost": {
"user_id": "@example:localhost",
"usage": [
"master"
],
"keys": {
"ed25519:rJ2TAGkEOP6dX41Ksll6cl8K3J48l8s/59zaXyvl2p0": "rJ2TAGkEOP6dX41Ksll6cl8K3J48l8s/59zaXyvl2p0"
},
"signatures": {
"@example:localhost": {
"ed25519:WSKKLTJZCL": "ZzJp1wtmRdykXAUEItEjNiFlBrxx8L6/Vaen9am8AuGwlxxJtOkuY4m+4MPLvDPOgavKHLsrRuNLAfCeakMlCQ"
}
}
}
},
"self_signing_keys": {
"@example:localhost": {
"user_id": "@example:localhost",
"usage": [
"self_signing"
],
"keys": {
"ed25519:0C8lCBxrvrv/O7BQfsKnkYogHZX3zAgw3RfJuyiq210": "0C8lCBxrvrv/O7BQfsKnkYogHZX3zAgw3RfJuyiq210"
},
"signatures": {
"@example:localhost": {
"ed25519:rJ2TAGkEOP6dX41Ksll6cl8K3J48l8s/59zaXyvl2p0": "AC7oDUW4rUhtInwb4lAoBJ0wAuu4a5k+8e34B5+NKsDB8HXRwgVwUWN/MRWc/sJgtSbVlhzqS9THEmQQ1C51Bw"
}
}
}
},
"user_signing_keys": {
"@example:localhost": {
"user_id": "@example:localhost",
"usage": [
"user_signing"
],
"keys": {
"ed25519:DU9z4gBFKFKCk7a13sW9wjT0Iyg7Hqv5f0BPM7DEhPo": "DU9z4gBFKFKCk7a13sW9wjT0Iyg7Hqv5f0BPM7DEhPo"
},
"signatures": {
"@example:localhost": {
"ed25519:rJ2TAGkEOP6dX41Ksll6cl8K3J48l8s/59zaXyvl2p0": "C4L2sx9frGqj8w41KyynHGqwUbbwBYRZpYCB+6QWnvQFA5Oi/1PJj8w5anwzEsoO0TWmLYmf7FXuAGewanOWDg"
}
}
}
}
}));
KeyQueryResponse::try_from_http_response(data)
.expect("Can't parse the keys upload response")
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::time::Duration;
use matrix_sdk_test::async_test;
use ruma::device_id;
use super::testing::{manager, other_key_query, other_user_id};
#[async_test]
async fn test_manager_creation() {
let manager = manager();
assert!(manager.store.tracked_users().is_empty())
}
#[async_test]
async fn test_manager_key_query_response() {
let manager = manager();
let other_user = other_user_id();
let devices = manager.store.get_user_devices(other_user).await.unwrap();
assert_eq!(devices.devices().count(), 0);
let listener = manager.listen_for_received_queries();
let task = tokio::task::spawn(async move { listener.wait(Duration::from_secs(10)).await });
manager.receive_keys_query_response(&other_key_query()).await.unwrap();
assert!(task.await.unwrap().is_ok());
let devices = manager.store.get_user_devices(other_user).await.unwrap();
assert_eq!(devices.devices().count(), 1);
let device = manager
.store
.get_readonly_device(other_user, device_id!("SKISMLNIMH"))
.await
.unwrap()
.unwrap();
let identity = manager.store.get_user_identity(other_user).await.unwrap().unwrap();
let identity = identity.other().unwrap();
assert!(identity.is_device_signed(&device).is_ok())
}
#[async_test]
async fn test_manager_own_key_query_response() {
let manager = manager();
let other_user = other_user_id();
let devices = manager.store.get_user_devices(other_user).await.unwrap();
assert_eq!(devices.devices().count(), 0);
manager.receive_keys_query_response(&other_key_query()).await.unwrap();
let devices = manager.store.get_user_devices(other_user).await.unwrap();
assert_eq!(devices.devices().count(), 1);
let device = manager
.store
.get_readonly_device(other_user, device_id!("SKISMLNIMH"))
.await
.unwrap()
.unwrap();
let identity = manager.store.get_user_identity(other_user).await.unwrap().unwrap();
let identity = identity.other().unwrap();
assert!(identity.is_device_signed(&device).is_ok())
}
#[async_test]
async fn no_tracked_users_key_query_request() {
let manager = manager();
assert!(manager.store.tracked_users().is_empty(), "No users are initially tracked");
let requests = manager.users_for_key_query().await;
assert!(!requests.is_empty(), "We query the keys for our own user");
assert!(
manager.store.tracked_users().contains(manager.user_id()),
"Our own user is now tracked"
);
}
}