-
Notifications
You must be signed in to change notification settings - Fork 258
/
share_strategy.rs
1573 lines (1367 loc) · 59.8 KB
/
share_strategy.rs
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
// Copyright 2024 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{
collections::{BTreeMap, BTreeSet, HashMap},
default::Default,
ops::Deref,
};
use itertools::{Either, Itertools};
use ruma::{DeviceId, OwnedDeviceId, OwnedUserId, UserId};
use serde::{Deserialize, Serialize};
use tracing::{debug, instrument, trace};
use super::OutboundGroupSession;
use crate::{
error::{OlmResult, SessionRecipientCollectionError},
store::Store,
types::events::room_key_withheld::WithheldCode,
DeviceData, EncryptionSettings, LocalTrust, OlmError, OwnUserIdentityData, UserIdentityData,
};
#[cfg(doc)]
use crate::{Device, UserIdentity};
/// Strategy to collect the devices that should receive room keys for the
/// current discussion.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
pub enum CollectStrategy {
/// Device based sharing strategy.
DeviceBasedStrategy {
/// If `true`, devices that are not trusted will be excluded from the
/// conversation. A device is trusted if any of the following is true:
/// - It was manually marked as trusted.
/// - It was marked as verified via interactive verification.
/// - It is signed by its owner identity, and this identity has been
/// trusted via interactive verification.
/// - It is the current own device of the user.
only_allow_trusted_devices: bool,
/// If `true`, and a verified user has an unsigned device, key sharing
/// will fail with a
/// [`SessionRecipientCollectionError::VerifiedUserHasUnsignedDevice`].
///
/// If `true`, and a verified user has replaced their identity, key
/// sharing will fail with a
/// [`SessionRecipientCollectionError::VerifiedUserChangedIdentity`].
///
/// Otherwise, keys are shared with unsigned devices as normal.
///
/// Once the problematic devices are blacklisted or whitelisted the
/// caller can retry to share a second time.
#[serde(default)]
error_on_verified_user_problem: bool,
},
/// Share based on identity. Only distribute to devices signed by their
/// owner. If a user has no published identity he will not receive
/// any room keys.
IdentityBasedStrategy,
}
impl CollectStrategy {
/// Creates an identity based strategy
pub const fn new_identity_based() -> Self {
CollectStrategy::IdentityBasedStrategy
}
}
impl Default for CollectStrategy {
fn default() -> Self {
CollectStrategy::DeviceBasedStrategy {
only_allow_trusted_devices: false,
error_on_verified_user_problem: false,
}
}
}
/// Returned by `collect_session_recipients`.
///
/// Information indicating whether the session needs to be rotated
/// (`should_rotate`) and the list of users/devices that should receive
/// (`devices`) or not the session, including withheld reason
/// `withheld_devices`.
#[derive(Debug)]
pub(crate) struct CollectRecipientsResult {
/// If true the outbound group session should be rotated
pub should_rotate: bool,
/// The map of user|device that should receive the session
pub devices: BTreeMap<OwnedUserId, Vec<DeviceData>>,
/// The map of user|device that won't receive the key with the withheld
/// code.
pub withheld_devices: Vec<(DeviceData, WithheldCode)>,
}
/// Given a list of user and an outbound session, return the list of users
/// and their devices that this session should be shared with.
///
/// Returns information indicating whether the session needs to be rotated
/// and the list of users/devices that should receive or not the session
/// (with withheld reason).
#[instrument(skip_all)]
pub(crate) async fn collect_session_recipients(
store: &Store,
users: impl Iterator<Item = &UserId>,
settings: &EncryptionSettings,
outbound: &OutboundGroupSession,
) -> OlmResult<CollectRecipientsResult> {
let users: BTreeSet<&UserId> = users.collect();
let mut devices: BTreeMap<OwnedUserId, Vec<DeviceData>> = Default::default();
let mut withheld_devices: Vec<(DeviceData, WithheldCode)> = Default::default();
let mut verified_users_with_new_identities: Vec<OwnedUserId> = Default::default();
trace!(?users, ?settings, "Calculating group session recipients");
let users_shared_with: BTreeSet<OwnedUserId> =
outbound.shared_with_set.read().unwrap().keys().cloned().collect();
let users_shared_with: BTreeSet<&UserId> = users_shared_with.iter().map(Deref::deref).collect();
// A user left if a user is missing from the set of users that should
// get the session but is in the set of users that received the session.
let user_left = !users_shared_with.difference(&users).collect::<BTreeSet<_>>().is_empty();
let visibility_changed = outbound.settings().history_visibility != settings.history_visibility;
let algorithm_changed = outbound.settings().algorithm != settings.algorithm;
// To protect the room history we need to rotate the session if either:
//
// 1. Any user left the room.
// 2. Any of the users' devices got deleted or blacklisted.
// 3. The history visibility changed.
// 4. The encryption algorithm changed.
//
// This is calculated in the following code and stored in this variable.
let mut should_rotate = user_left || visibility_changed || algorithm_changed;
let own_identity = store.get_user_identity(store.user_id()).await?.and_then(|i| i.into_own());
// Get the recipient and withheld devices, based on the collection strategy.
match settings.sharing_strategy {
CollectStrategy::DeviceBasedStrategy {
only_allow_trusted_devices,
error_on_verified_user_problem,
} => {
let mut unsigned_devices_of_verified_users: BTreeMap<OwnedUserId, Vec<OwnedDeviceId>> =
Default::default();
for user_id in users {
trace!("Considering recipient devices for user {}", user_id);
let user_devices = store.get_device_data_for_user_filtered(user_id).await?;
// We only need the user identity if `only_allow_trusted_devices` or
// `error_on_verified_user_problem` is set.
let device_owner_identity =
if only_allow_trusted_devices || error_on_verified_user_problem {
store.get_user_identity(user_id).await?
} else {
None
};
if error_on_verified_user_problem
&& has_identity_verification_violation(
own_identity.as_ref(),
device_owner_identity.as_ref(),
)
{
verified_users_with_new_identities.push(user_id.to_owned());
// No point considering the individual devices of this user.
continue;
}
let recipient_devices = split_devices_for_user(
user_devices,
&own_identity,
&device_owner_identity,
only_allow_trusted_devices,
error_on_verified_user_problem,
);
// If `error_on_verified_user_problem` is set, then
// `unsigned_of_verified_user` may be populated. If so, add an entry to the
// list of users with unsigned devices.
if !recipient_devices.unsigned_of_verified_user.is_empty() {
unsigned_devices_of_verified_users.insert(
user_id.to_owned(),
recipient_devices
.unsigned_of_verified_user
.into_iter()
.map(|d| d.device_id().to_owned())
.collect(),
);
}
// If we haven't already concluded that the session should be
// rotated for other reasons, we also need to check whether any
// of the devices in the session got deleted or blacklisted in the
// meantime. If so, we should also rotate the session.
if !should_rotate {
should_rotate = is_session_overshared_for_user(
outbound,
user_id,
&recipient_devices.allowed_devices,
)
}
devices
.entry(user_id.to_owned())
.or_default()
.extend(recipient_devices.allowed_devices);
withheld_devices.extend(recipient_devices.denied_devices_with_code);
}
// If `error_on_verified_user_problem` is set, then
// `unsigned_devices_of_verified_users` may be populated. If so, we need to bail
// out with an error.
if !unsigned_devices_of_verified_users.is_empty() {
return Err(OlmError::SessionRecipientCollectionError(
SessionRecipientCollectionError::VerifiedUserHasUnsignedDevice(
unsigned_devices_of_verified_users,
),
));
}
}
CollectStrategy::IdentityBasedStrategy => {
// We require our own cross-signing to be properly set up for the
// identity-based strategy, so return an error if it isn't.
match &own_identity {
None => {
return Err(OlmError::SessionRecipientCollectionError(
SessionRecipientCollectionError::CrossSigningNotSetup,
))
}
Some(identity) if !identity.is_verified() => {
return Err(OlmError::SessionRecipientCollectionError(
SessionRecipientCollectionError::SendingFromUnverifiedDevice,
))
}
Some(_) => (),
}
for user_id in users {
trace!("Considering recipient devices for user {}", user_id);
let user_devices = store.get_device_data_for_user_filtered(user_id).await?;
let device_owner_identity = store.get_user_identity(user_id).await?;
if has_identity_verification_violation(
own_identity.as_ref(),
device_owner_identity.as_ref(),
) {
verified_users_with_new_identities.push(user_id.to_owned());
// No point considering the individual devices of this user.
continue;
}
let recipient_devices = split_recipients_withhelds_for_user_based_on_identity(
user_devices,
&device_owner_identity,
);
// If we haven't already concluded that the session should be
// rotated for other reasons, we also need to check whether any
// of the devices in the session got deleted or blacklisted in the
// meantime. If so, we should also rotate the session.
if !should_rotate {
should_rotate = is_session_overshared_for_user(
outbound,
user_id,
&recipient_devices.allowed_devices,
)
}
devices
.entry(user_id.to_owned())
.or_default()
.extend(recipient_devices.allowed_devices);
withheld_devices.extend(recipient_devices.denied_devices_with_code);
}
}
}
// We may have encountered previously-verified users who have changed their
// identities. If so, we bail out with an error.
if !verified_users_with_new_identities.is_empty() {
return Err(OlmError::SessionRecipientCollectionError(
SessionRecipientCollectionError::VerifiedUserChangedIdentity(
verified_users_with_new_identities,
),
));
}
if should_rotate {
debug!(
should_rotate,
user_left,
visibility_changed,
algorithm_changed,
"Rotating room key to protect room history",
);
}
trace!(should_rotate, "Done calculating group session recipients");
Ok(CollectRecipientsResult { should_rotate, devices, withheld_devices })
}
/// Check if the session has been shared with a device belonging to the given
/// user, that is no longer in the pool of devices that should participate in
/// the discussion.
///
/// # Arguments
///
/// * `outbound_session` - the outbound group session to check for oversharing.
/// * `user_id` - the ID of the user we are checking the devices for.
/// * `recipient_devices` - the list of devices belonging to `user_id` that we
/// expect to share the session with.
///
/// # Returns
///
/// `true` if the session has been shared with any devices belonging to
/// `user_id` that are not in `recipient_devices`. Otherwise, `false`.
fn is_session_overshared_for_user(
outbound_session: &OutboundGroupSession,
user_id: &UserId,
recipient_devices: &[DeviceData],
) -> bool {
// Device IDs that should receive this session
let recipient_device_ids: BTreeSet<&DeviceId> =
recipient_devices.iter().map(|d| d.device_id()).collect();
let guard = outbound_session.shared_with_set.read().unwrap();
let Some(shared) = guard.get(user_id) else {
return false;
};
// Devices that received this session
let shared: BTreeSet<&DeviceId> = shared.keys().map(|d| d.as_ref()).collect();
// The set difference between
//
// 1. Devices that had previously received the session, and
// 2. Devices that would now receive the session
//
// Represents newly deleted or blacklisted devices. If this
// set is non-empty, we must rotate.
let newly_deleted_or_blacklisted =
shared.difference(&recipient_device_ids).collect::<BTreeSet<_>>();
let should_rotate = !newly_deleted_or_blacklisted.is_empty();
if should_rotate {
debug!(
"Rotating a room key due to these devices being deleted/blacklisted {:?}",
newly_deleted_or_blacklisted,
);
}
should_rotate
}
/// Result type for [`split_devices_for_user`].
#[derive(Default)]
struct DeviceBasedRecipientDevices {
/// Devices that should receive the room key.
allowed_devices: Vec<DeviceData>,
/// Devices that should receive a withheld code.
denied_devices_with_code: Vec<(DeviceData, WithheldCode)>,
/// Devices that should cause the transmission to fail, due to being an
/// unsigned device belonging to a verified user. Only populated by
/// [`split_devices_for_user`], when
/// `error_on_verified_user_problem` is set.
unsigned_of_verified_user: Vec<DeviceData>,
}
/// Partition the list of a user's devices according to whether they should
/// receive the key, for [`CollectStrategy::DeviceBasedStrategy`].
///
/// We split the list into three buckets:
///
/// * the devices that should receive the room key.
///
/// * the devices that should receive a withheld code.
///
/// * If `error_on_verified_user_problem` is set, the devices that should cause
/// the transmission to fail due to being unsigned. (If
/// `error_on_verified_user_problem` is unset, these devices are otherwise
/// partitioned into `allowed_devices`.)
fn split_devices_for_user(
user_devices: HashMap<OwnedDeviceId, DeviceData>,
own_identity: &Option<OwnUserIdentityData>,
device_owner_identity: &Option<UserIdentityData>,
only_allow_trusted_devices: bool,
error_on_verified_user_problem: bool,
) -> DeviceBasedRecipientDevices {
let mut recipient_devices: DeviceBasedRecipientDevices = Default::default();
for d in user_devices.into_values() {
if d.is_blacklisted() {
recipient_devices.denied_devices_with_code.push((d, WithheldCode::Blacklisted));
} else if d.local_trust_state() == LocalTrust::Ignored {
// Ignore the trust state of that device and share
recipient_devices.allowed_devices.push(d);
} else if only_allow_trusted_devices && !d.is_verified(own_identity, device_owner_identity)
{
recipient_devices.denied_devices_with_code.push((d, WithheldCode::Unverified));
} else if error_on_verified_user_problem
&& is_unsigned_device_of_verified_user(
own_identity.as_ref(),
device_owner_identity.as_ref(),
&d,
)
{
recipient_devices.unsigned_of_verified_user.push(d)
} else {
recipient_devices.allowed_devices.push(d);
}
}
recipient_devices
}
/// Result type for [`split_recipients_withhelds_for_user_based_on_identity`].
#[derive(Default)]
struct IdentityBasedRecipientDevices {
/// Devices that should receive the room key.
allowed_devices: Vec<DeviceData>,
/// Devices that should receive a withheld code.
denied_devices_with_code: Vec<(DeviceData, WithheldCode)>,
}
fn split_recipients_withhelds_for_user_based_on_identity(
user_devices: HashMap<OwnedDeviceId, DeviceData>,
device_owner_identity: &Option<UserIdentityData>,
) -> IdentityBasedRecipientDevices {
match device_owner_identity {
None => {
// withheld all the users devices, we need to have an identity for this
// distribution mode
IdentityBasedRecipientDevices {
allowed_devices: Vec::default(),
denied_devices_with_code: user_devices
.into_values()
.map(|d| (d, WithheldCode::Unverified))
.collect(),
}
}
Some(device_owner_identity) => {
// Only accept devices signed by the current identity
let (recipients, withheld_recipients): (
Vec<DeviceData>,
Vec<(DeviceData, WithheldCode)>,
) = user_devices.into_values().partition_map(|d| {
if d.is_cross_signed_by_owner(device_owner_identity) {
Either::Left(d)
} else {
Either::Right((d, WithheldCode::Unverified))
}
});
IdentityBasedRecipientDevices {
allowed_devices: recipients,
denied_devices_with_code: withheld_recipients,
}
}
}
}
fn is_unsigned_device_of_verified_user(
own_identity: Option<&OwnUserIdentityData>,
device_owner_identity: Option<&UserIdentityData>,
device_data: &DeviceData,
) -> bool {
device_owner_identity.is_some_and(|device_owner_identity| {
is_user_verified(own_identity, device_owner_identity)
&& !device_data.is_cross_signed_by_owner(device_owner_identity)
})
}
/// Check if the user was previously verified, but they have now changed their
/// identity so that they are no longer verified.
///
/// This is much the same as [`UserIdentity::has_verification_violation`], but
/// works with a low-level [`UserIdentityData`] rather than higher-level
/// [`UserIdentity`].
fn has_identity_verification_violation(
own_identity: Option<&OwnUserIdentityData>,
device_owner_identity: Option<&UserIdentityData>,
) -> bool {
device_owner_identity.is_some_and(|device_owner_identity| {
device_owner_identity.was_previously_verified()
&& !is_user_verified(own_identity, device_owner_identity)
})
}
fn is_user_verified(
own_identity: Option<&OwnUserIdentityData>,
user_identity: &UserIdentityData,
) -> bool {
match user_identity {
UserIdentityData::Own(own_identity) => own_identity.is_verified(),
UserIdentityData::Other(other_identity) => {
own_identity.is_some_and(|oi| oi.is_identity_verified(other_identity))
}
}
}
#[cfg(test)]
mod tests {
use std::{collections::BTreeMap, iter, sync::Arc};
use assert_matches::assert_matches;
use assert_matches2::assert_let;
use matrix_sdk_test::{
async_test, test_json,
test_json::keys_query_sets::{
IdentityChangeDataSet, KeyDistributionTestData, MaloIdentityChangeDataSet,
VerificationViolationTestData,
},
};
use ruma::{
device_id, events::room::history_visibility::HistoryVisibility, room_id, TransactionId,
};
use crate::{
error::SessionRecipientCollectionError,
olm::OutboundGroupSession,
session_manager::{
group_sessions::share_strategy::collect_session_recipients, CollectStrategy,
},
types::events::room_key_withheld::WithheldCode,
CrossSigningKeyExport, EncryptionSettings, LocalTrust, OlmError, OlmMachine,
};
async fn set_up_test_machine() -> OlmMachine {
let machine = OlmMachine::new(
KeyDistributionTestData::me_id(),
KeyDistributionTestData::me_device_id(),
)
.await;
let keys_query = KeyDistributionTestData::me_keys_query_response();
let txn_id = TransactionId::new();
machine.mark_request_as_sent(&txn_id, &keys_query).await.unwrap();
machine
.import_cross_signing_keys(CrossSigningKeyExport {
master_key: KeyDistributionTestData::MASTER_KEY_PRIVATE_EXPORT.to_owned().into(),
self_signing_key: KeyDistributionTestData::SELF_SIGNING_KEY_PRIVATE_EXPORT
.to_owned()
.into(),
user_signing_key: KeyDistributionTestData::USER_SIGNING_KEY_PRIVATE_EXPORT
.to_owned()
.into(),
})
.await
.unwrap();
let keys_query = KeyDistributionTestData::dan_keys_query_response();
let txn_id = TransactionId::new();
machine.mark_request_as_sent(&txn_id, &keys_query).await.unwrap();
let txn_id_dave = TransactionId::new();
let keys_query_dave = KeyDistributionTestData::dave_keys_query_response();
machine.mark_request_as_sent(&txn_id_dave, &keys_query_dave).await.unwrap();
let txn_id_good = TransactionId::new();
let keys_query_good = KeyDistributionTestData::good_keys_query_response();
machine.mark_request_as_sent(&txn_id_good, &keys_query_good).await.unwrap();
machine
}
#[async_test]
async fn test_share_with_per_device_strategy_to_all() {
let machine = set_up_test_machine().await;
let encryption_settings = EncryptionSettings {
sharing_strategy: CollectStrategy::DeviceBasedStrategy {
only_allow_trusted_devices: false,
error_on_verified_user_problem: false,
},
..Default::default()
};
let group_session = create_test_outbound_group_session(&machine, &encryption_settings);
let share_result = collect_session_recipients(
machine.store(),
vec![
KeyDistributionTestData::dan_id(),
KeyDistributionTestData::dave_id(),
KeyDistributionTestData::good_id(),
]
.into_iter(),
&encryption_settings,
&group_session,
)
.await
.unwrap();
assert!(!share_result.should_rotate);
let dan_devices_shared =
share_result.devices.get(KeyDistributionTestData::dan_id()).unwrap();
let dave_devices_shared =
share_result.devices.get(KeyDistributionTestData::dave_id()).unwrap();
let good_devices_shared =
share_result.devices.get(KeyDistributionTestData::good_id()).unwrap();
// With this strategy the room key would be distributed to all devices
assert_eq!(dan_devices_shared.len(), 2);
assert_eq!(dave_devices_shared.len(), 1);
assert_eq!(good_devices_shared.len(), 2);
}
#[async_test]
async fn test_share_with_per_device_strategy_only_trusted() {
test_share_only_trusted_helper(false).await;
}
/// Variation of [`test_share_with_per_device_strategy_only_trusted`] to
/// test the interaction between
/// [`only_allow_trusted_devices`](`CollectStrategy::DeviceBasedStrategy::only_allow_trusted_devices`) and
/// [`error_on_verified_user_problem`](`CollectStrategy::DeviceBasedStrategy::error_on_verified_user_problem`).
///
/// (Given that untrusted devices are ignored, we do not expect
/// [`collect_session_recipients`] to return an error, despite the presence
/// of unsigned devices.)
#[async_test]
async fn test_share_with_per_device_strategy_only_trusted_error_on_unsigned_of_verified() {
test_share_only_trusted_helper(true).await;
}
/// Common helper for [`test_share_with_per_device_strategy_only_trusted`]
/// and [`test_share_with_per_device_strategy_only_trusted_error_on_unsigned_of_verified`].
async fn test_share_only_trusted_helper(error_on_verified_user_problem: bool) {
let machine = set_up_test_machine().await;
let encryption_settings = EncryptionSettings {
sharing_strategy: CollectStrategy::DeviceBasedStrategy {
only_allow_trusted_devices: true,
error_on_verified_user_problem,
},
..Default::default()
};
let group_session = create_test_outbound_group_session(&machine, &encryption_settings);
let share_result = collect_session_recipients(
machine.store(),
vec![
KeyDistributionTestData::dan_id(),
KeyDistributionTestData::dave_id(),
KeyDistributionTestData::good_id(),
]
.into_iter(),
&encryption_settings,
&group_session,
)
.await
.unwrap();
assert!(!share_result.should_rotate);
let dave_devices_shared = share_result.devices.get(KeyDistributionTestData::dave_id());
let good_devices_shared = share_result.devices.get(KeyDistributionTestData::good_id());
// dave and good wouldn't receive any key
assert!(dave_devices_shared.unwrap().is_empty());
assert!(good_devices_shared.unwrap().is_empty());
// dan is verified by me and has one of his devices self signed, so should get
// the key
let dan_devices_shared =
share_result.devices.get(KeyDistributionTestData::dan_id()).unwrap();
assert_eq!(dan_devices_shared.len(), 1);
let dan_device_that_will_get_the_key = &dan_devices_shared[0];
assert_eq!(
dan_device_that_will_get_the_key.device_id().as_str(),
KeyDistributionTestData::dan_signed_device_id()
);
// Check withhelds for others
let (_, code) = share_result
.withheld_devices
.iter()
.find(|(d, _)| d.device_id() == KeyDistributionTestData::dan_unsigned_device_id())
.expect("This dan's device should receive a withheld code");
assert_eq!(code, &WithheldCode::Unverified);
let (_, code) = share_result
.withheld_devices
.iter()
.find(|(d, _)| d.device_id() == KeyDistributionTestData::dave_device_id())
.expect("This daves's device should receive a withheld code");
assert_eq!(code, &WithheldCode::Unverified);
}
/// Test that [`collect_session_recipients`] returns an error if there are
/// unsigned devices belonging to verified users, when
/// `error_on_verified_user_problem` is set.
#[async_test]
async fn test_error_on_unsigned_of_verified_users() {
use VerificationViolationTestData as DataSet;
// We start with Bob, who is verified and has one unsigned device.
let machine = unsigned_of_verified_setup().await;
// Add Carol, also verified with one unsigned device.
let carol_keys = DataSet::carol_keys_query_response_signed();
machine.mark_request_as_sent(&TransactionId::new(), &carol_keys).await.unwrap();
// Double-check the state of Carol.
let carol_identity =
machine.get_identity(DataSet::carol_id(), None).await.unwrap().unwrap();
assert!(carol_identity.other().unwrap().is_verified());
let carol_unsigned_device = machine
.get_device(DataSet::carol_id(), DataSet::carol_unsigned_device_id(), None)
.await
.unwrap()
.unwrap();
assert!(!carol_unsigned_device.is_verified());
// Sharing an OutboundGroupSession should fail.
let encryption_settings = error_on_verification_problem_encryption_settings();
let group_session = create_test_outbound_group_session(&machine, &encryption_settings);
let share_result = collect_session_recipients(
machine.store(),
vec![DataSet::bob_id(), DataSet::carol_id()].into_iter(),
&encryption_settings,
&group_session,
)
.await;
assert_let!(
Err(OlmError::SessionRecipientCollectionError(
SessionRecipientCollectionError::VerifiedUserHasUnsignedDevice(unverified_devices)
)) = share_result
);
// Check the list of devices in the error.
assert_eq!(
unverified_devices,
BTreeMap::from([
(DataSet::bob_id().to_owned(), vec![DataSet::bob_device_2_id().to_owned()]),
(
DataSet::carol_id().to_owned(),
vec![DataSet::carol_unsigned_device_id().to_owned()]
),
])
);
}
/// Test that we can resolve errors from
/// `error_on_verified_user_problem` by whitelisting the
/// device.
#[async_test]
async fn test_error_on_unsigned_of_verified_resolve_by_whitelisting() {
use VerificationViolationTestData as DataSet;
let machine = unsigned_of_verified_setup().await;
// Whitelist the unsigned device
machine
.get_device(DataSet::bob_id(), DataSet::bob_device_2_id(), None)
.await
.unwrap()
.unwrap()
.set_local_trust(LocalTrust::Ignored)
.await
.unwrap();
let encryption_settings = error_on_verification_problem_encryption_settings();
let group_session = create_test_outbound_group_session(&machine, &encryption_settings);
// We should be able to share a key, and it should include the unsigned device.
let share_result = collect_session_recipients(
machine.store(),
iter::once(DataSet::bob_id()),
&encryption_settings,
&group_session,
)
.await
.unwrap();
assert_eq!(2, share_result.devices.get(DataSet::bob_id()).unwrap().len());
assert_eq!(0, share_result.withheld_devices.len());
}
/// Test that we can resolve errors from
/// `error_on_verified_user_problem` by blacklisting the
/// device.
#[async_test]
async fn test_error_on_unsigned_of_verified_resolve_by_blacklisting() {
use VerificationViolationTestData as DataSet;
let machine = unsigned_of_verified_setup().await;
// Blacklist the unsigned device
machine
.get_device(DataSet::bob_id(), DataSet::bob_device_2_id(), None)
.await
.unwrap()
.unwrap()
.set_local_trust(LocalTrust::BlackListed)
.await
.unwrap();
let encryption_settings = error_on_verification_problem_encryption_settings();
let group_session = create_test_outbound_group_session(&machine, &encryption_settings);
// We should be able to share a key, and it should exclude the unsigned device.
let share_result = collect_session_recipients(
machine.store(),
iter::once(DataSet::bob_id()),
&encryption_settings,
&group_session,
)
.await
.unwrap();
assert_eq!(1, share_result.devices.get(DataSet::bob_id()).unwrap().len());
let withheld_list: Vec<_> = share_result
.withheld_devices
.iter()
.map(|(d, code)| (d.device_id().to_owned(), code.clone()))
.collect();
assert_eq!(
withheld_list,
vec![(DataSet::bob_device_2_id().to_owned(), WithheldCode::Blacklisted)]
);
}
/// Test that [`collect_session_recipients`] returns an error when
/// `error_on_verified_user_problem` is set, if our own identity
/// is verified and we have unsigned devices.
#[async_test]
async fn test_error_on_unsigned_of_verified_owner_is_us() {
use VerificationViolationTestData as DataSet;
let machine = unsigned_of_verified_setup().await;
// Add a couple of devices to Alice's account
let mut own_keys = DataSet::own_keys_query_response_1().clone();
own_keys.device_keys.insert(
DataSet::own_id().to_owned(),
BTreeMap::from([
DataSet::own_signed_device_keys(),
DataSet::own_unsigned_device_keys(),
]),
);
machine.mark_request_as_sent(&TransactionId::new(), &own_keys).await.unwrap();
let encryption_settings = error_on_verification_problem_encryption_settings();
let group_session = create_test_outbound_group_session(&machine, &encryption_settings);
let share_result = collect_session_recipients(
machine.store(),
iter::once(DataSet::own_id()),
&encryption_settings,
&group_session,
)
.await;
assert_let!(
Err(OlmError::SessionRecipientCollectionError(
SessionRecipientCollectionError::VerifiedUserHasUnsignedDevice(unverified_devices)
)) = share_result
);
// Check the list of devices in the error.
assert_eq!(
unverified_devices,
BTreeMap::from([(
DataSet::own_id().to_owned(),
vec![DataSet::own_unsigned_device_id()]
),])
);
}
/// Test that an unsigned device of an unverified user doesn't cause an
/// error.
#[async_test]
async fn test_should_not_error_on_unsigned_of_unverified() {
use VerificationViolationTestData as DataSet;
let machine = OlmMachine::new(DataSet::own_id(), device_id!("LOCAL")).await;
// Tell the OlmMachine about our own public keys.
let own_keys = DataSet::own_keys_query_response_1();
machine.mark_request_as_sent(&TransactionId::new(), &own_keys).await.unwrap();
// Import the secret parts of our own cross-signing keys.
machine
.import_cross_signing_keys(CrossSigningKeyExport {
master_key: DataSet::MASTER_KEY_PRIVATE_EXPORT.to_owned().into(),
self_signing_key: DataSet::SELF_SIGNING_KEY_PRIVATE_EXPORT.to_owned().into(),
user_signing_key: DataSet::USER_SIGNING_KEY_PRIVATE_EXPORT.to_owned().into(),
})
.await
.unwrap();
// This time our own identity is trusted but is not signing bob.
let bob_keys = DataSet::bob_keys_query_response_rotated();
machine.mark_request_as_sent(&TransactionId::new(), &bob_keys).await.unwrap();
// Double-check the state of Bob: he should be unverified, and should have an
// unsigned device.
let bob_identity = machine.get_identity(DataSet::bob_id(), None).await.unwrap().unwrap();
assert!(!bob_identity.other().unwrap().is_verified());
let bob_unsigned_device = machine
.get_device(DataSet::bob_id(), DataSet::bob_device_1_id(), None)
.await
.unwrap()
.unwrap();
assert!(!bob_unsigned_device.is_cross_signed_by_owner());
let encryption_settings = error_on_verification_problem_encryption_settings();
let group_session = create_test_outbound_group_session(&machine, &encryption_settings);
collect_session_recipients(
machine.store(),
iter::once(DataSet::bob_id()),
&encryption_settings,
&group_session,
)
.await
.unwrap();
}
/// Test that an unsigned device of a signed user doesn't cause an
/// error, when we have not verified our own identity.
#[async_test]
async fn test_should_not_error_on_unsigned_of_signed_but_unverified() {
use VerificationViolationTestData as DataSet;
let machine = OlmMachine::new(DataSet::own_id(), device_id!("LOCAL")).await;
// Tell the OlmMachine about our own public keys.
let keys_query = DataSet::own_keys_query_response_1();
machine.mark_request_as_sent(&TransactionId::new(), &keys_query).await.unwrap();
// ... and those of Bob.
let keys_query = DataSet::bob_keys_query_response_signed();
machine.mark_request_as_sent(&TransactionId::new(), &keys_query).await.unwrap();
// Double-check the state of Bob: his identity should be signed but unverified,
// and he should have an unsigned device.
let bob_identity =
machine.get_identity(DataSet::bob_id(), None).await.unwrap().unwrap().other().unwrap();
assert!(bob_identity
.own_identity
.as_ref()
.unwrap()
.is_identity_signed(&bob_identity.inner));
assert!(!bob_identity.is_verified());
let bob_unsigned_device = machine
.get_device(DataSet::bob_id(), DataSet::bob_device_2_id(), None)
.await
.unwrap()
.unwrap();
assert!(!bob_unsigned_device.is_cross_signed_by_owner());
// Share a session, and ensure that it doesn't error.
let encryption_settings = error_on_verification_problem_encryption_settings();
let group_session = create_test_outbound_group_session(&machine, &encryption_settings);
collect_session_recipients(
machine.store(),
iter::once(DataSet::bob_id()),
&encryption_settings,
&group_session,
)
.await
.unwrap();
}
/// Test that a verified user changing their identity causes an error in
/// `collect_session_recipients`, and that it can be resolved by
/// withdrawing verification
#[async_test]
async fn test_verified_user_changed_identity() {
use test_json::keys_query_sets::VerificationViolationTestData as DataSet;
// We start with Bob, who is verified and has one unsigned device. We have also
// verified our own identity.
let machine = unsigned_of_verified_setup().await;
// Bob then rotates his identity
let bob_keys = DataSet::bob_keys_query_response_rotated();
machine.mark_request_as_sent(&TransactionId::new(), &bob_keys).await.unwrap();