-
Notifications
You must be signed in to change notification settings - Fork 269
/
Copy pathmod.rs
2616 lines (2350 loc) · 99.2 KB
/
mod.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 2020 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, HashMap, HashSet},
sync::Arc,
time::Duration,
};
use itertools::Itertools;
use matrix_sdk_common::{
deserialized_responses::{
AlgorithmInfo, DecryptedRoomEvent, DeviceLinkProblem, EncryptionInfo, UnableToDecryptInfo,
UnableToDecryptReason, UnsignedDecryptionResult, UnsignedEventLocation, VerificationLevel,
VerificationState,
},
locks::RwLock as StdRwLock,
BoxFuture,
};
use ruma::{
api::client::{
dehydrated_device::DehydratedDeviceData,
keys::{
claim_keys::v3::Request as KeysClaimRequest,
get_keys::v3::Response as KeysQueryResponse,
upload_keys::v3::{Request as UploadKeysRequest, Response as UploadKeysResponse},
upload_signatures::v3::Request as UploadSignaturesRequest,
},
sync::sync_events::DeviceLists,
},
assign,
events::{
secret::request::SecretName, AnyMessageLikeEvent, AnyMessageLikeEventContent,
AnyToDeviceEvent, MessageLikeEventContent,
},
serde::{JsonObject, Raw},
DeviceId, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm, OwnedDeviceId, OwnedDeviceKeyId,
OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UInt, UserId,
};
use serde_json::{value::to_raw_value, Value};
use tokio::sync::Mutex;
use tracing::{
debug, error,
field::{debug, display},
info, instrument, warn, Span,
};
use vodozemac::{
megolm::{DecryptionError, SessionOrdering},
Curve25519PublicKey, Ed25519Signature,
};
use crate::{
backups::{BackupMachine, MegolmV1BackupKey},
dehydrated_devices::{DehydratedDevices, DehydrationError},
error::{EventError, MegolmError, MegolmResult, OlmError, OlmResult, SetRoomSettingsError},
gossiping::GossipMachine,
identities::{user::UserIdentity, Device, IdentityManager, UserDevices},
olm::{
Account, CrossSigningStatus, EncryptionSettings, IdentityKeys, InboundGroupSession,
KnownSenderData, OlmDecryptionInfo, PrivateCrossSigningIdentity, SenderData,
SenderDataFinder, SessionType, StaticAccountData,
},
session_manager::{GroupSessionManager, SessionManager},
store::{
Changes, CryptoStoreWrapper, DeviceChanges, IdentityChanges, IntoCryptoStore, MemoryStore,
PendingChanges, Result as StoreResult, RoomKeyInfo, RoomSettings, SecretImportError, Store,
StoreCache, StoreTransaction,
},
types::{
events::{
olm_v1::{AnyDecryptedOlmEvent, DecryptedRoomKeyEvent},
room::encrypted::{
EncryptedEvent, EncryptedToDeviceEvent, RoomEncryptedEventContent,
RoomEventEncryptionScheme, SupportedEventEncryptionSchemes,
},
room_key::{MegolmV1AesSha2Content, RoomKeyContent},
room_key_withheld::{
MegolmV1AesSha2WithheldContent, RoomKeyWithheldContent, RoomKeyWithheldEvent,
},
ToDeviceEvents,
},
requests::{
AnyIncomingResponse, KeysQueryRequest, OutgoingRequest, ToDeviceRequest,
UploadSigningKeysRequest,
},
EventEncryptionAlgorithm, Signatures,
},
utilities::timestamp_to_iso8601,
verification::{Verification, VerificationMachine, VerificationRequest},
CrossSigningKeyExport, CryptoStoreError, DecryptionSettings, DeviceData, LocalTrust,
RoomEventDecryptionResult, SignatureError, TrustRequirement,
};
/// State machine implementation of the Olm/Megolm encryption protocol used for
/// Matrix end to end encryption.
#[derive(Clone)]
pub struct OlmMachine {
pub(crate) inner: Arc<OlmMachineInner>,
}
pub struct OlmMachineInner {
/// The unique user id that owns this account.
user_id: OwnedUserId,
/// The unique device ID of the device that holds this account.
device_id: OwnedDeviceId,
/// The private part of our cross signing identity.
/// Used to sign devices and other users, might be missing if some other
/// device bootstrapped cross signing or cross signing isn't bootstrapped at
/// all.
user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
/// Store for the encryption keys.
/// Persists all the encryption keys so a client can resume the session
/// without the need to create new keys.
store: Store,
/// A state machine that handles Olm sessions creation.
session_manager: SessionManager,
/// A state machine that keeps track of our outbound group sessions.
pub(crate) group_session_manager: GroupSessionManager,
/// A state machine that is responsible to handle and keep track of SAS
/// verification flows.
verification_machine: VerificationMachine,
/// The state machine that is responsible to handle outgoing and incoming
/// key requests.
pub(crate) key_request_machine: GossipMachine,
/// State machine handling public user identities and devices, keeping track
/// of when a key query needs to be done and handling one.
identity_manager: IdentityManager,
/// A state machine that handles creating room key backups.
backup_machine: BackupMachine,
}
#[cfg(not(tarpaulin_include))]
impl std::fmt::Debug for OlmMachine {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OlmMachine")
.field("user_id", &self.user_id())
.field("device_id", &self.device_id())
.finish()
}
}
impl OlmMachine {
const CURRENT_GENERATION_STORE_KEY: &'static str = "generation-counter";
const HAS_MIGRATED_VERIFICATION_LATCH: &'static str = "HAS_MIGRATED_VERIFICATION_LATCH";
/// Create a new memory based OlmMachine.
///
/// The created machine will keep the encryption keys only in memory and
/// once the object is dropped the keys will be lost.
///
/// # Arguments
///
/// * `user_id` - The unique id of the user that owns this machine.
///
/// * `device_id` - The unique id of the device that owns this machine.
pub async fn new(user_id: &UserId, device_id: &DeviceId) -> Self {
OlmMachine::with_store(user_id, device_id, MemoryStore::new(), None)
.await
.expect("Reading and writing to the memory store always succeeds")
}
pub(crate) async fn rehydrate(
&self,
pickle_key: &[u8; 32],
device_id: &DeviceId,
device_data: Raw<DehydratedDeviceData>,
) -> Result<OlmMachine, DehydrationError> {
let account = Account::rehydrate(pickle_key, self.user_id(), device_id, device_data)?;
let static_account = account.static_data().clone();
let store =
Arc::new(CryptoStoreWrapper::new(self.user_id(), device_id, MemoryStore::new()));
let device = DeviceData::from_account(&account);
store.save_pending_changes(PendingChanges { account: Some(account) }).await?;
store
.save_changes(Changes {
devices: DeviceChanges { new: vec![device], ..Default::default() },
..Default::default()
})
.await?;
let (verification_machine, store, identity_manager) =
Self::new_helper_prelude(store, static_account, self.store().private_identity());
Ok(Self::new_helper(
device_id,
store,
verification_machine,
identity_manager,
self.store().private_identity(),
None,
))
}
fn new_helper_prelude(
store_wrapper: Arc<CryptoStoreWrapper>,
account: StaticAccountData,
user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
) -> (VerificationMachine, Store, IdentityManager) {
let verification_machine =
VerificationMachine::new(account.clone(), user_identity.clone(), store_wrapper.clone());
let store = Store::new(account, user_identity, store_wrapper, verification_machine.clone());
let identity_manager = IdentityManager::new(store.clone());
(verification_machine, store, identity_manager)
}
fn new_helper(
device_id: &DeviceId,
store: Store,
verification_machine: VerificationMachine,
identity_manager: IdentityManager,
user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
maybe_backup_key: Option<MegolmV1BackupKey>,
) -> Self {
let group_session_manager = GroupSessionManager::new(store.clone());
let users_for_key_claim = Arc::new(StdRwLock::new(BTreeMap::new()));
let key_request_machine = GossipMachine::new(
store.clone(),
identity_manager.clone(),
group_session_manager.session_cache(),
users_for_key_claim.clone(),
);
let session_manager =
SessionManager::new(users_for_key_claim, key_request_machine.clone(), store.clone());
let backup_machine = BackupMachine::new(store.clone(), maybe_backup_key);
let inner = Arc::new(OlmMachineInner {
user_id: store.user_id().to_owned(),
device_id: device_id.to_owned(),
user_identity,
store,
session_manager,
group_session_manager,
verification_machine,
key_request_machine,
identity_manager,
backup_machine,
});
Self { inner }
}
/// Create a new OlmMachine with the given [`CryptoStore`].
///
/// The created machine will keep the encryption keys only in memory and
/// once the object is dropped the keys will be lost.
///
/// If the store already contains encryption keys for the given user/device
/// pair those will be re-used. Otherwise new ones will be created and
/// stored.
///
/// # Arguments
///
/// * `user_id` - The unique id of the user that owns this machine.
///
/// * `device_id` - The unique id of the device that owns this machine.
///
/// * `store` - A `CryptoStore` implementation that will be used to store
/// the encryption keys.
///
/// * `custom_account` - A custom [`vodozemac::olm::Account`] to be used for
/// the identity and one-time keys of this [`OlmMachine`]. If no account
/// is provided, a new default one or one from the store will be used. If
/// an account is provided and one already exists in the store for this
/// [`UserId`]/[`DeviceId`] combination, an error will be raised. This is
/// useful if one wishes to create identity keys before knowing the
/// user/device IDs, e.g., to use the identity key as the device ID.
///
/// [`CryptoStore`]: crate::store::CryptoStore
#[instrument(skip(store, custom_account), fields(ed25519_key, curve25519_key))]
pub async fn with_store(
user_id: &UserId,
device_id: &DeviceId,
store: impl IntoCryptoStore,
custom_account: Option<vodozemac::olm::Account>,
) -> StoreResult<Self> {
let store = store.into_crypto_store();
let static_account = match store.load_account().await? {
Some(account) => {
if user_id != account.user_id()
|| device_id != account.device_id()
|| custom_account.is_some()
{
return Err(CryptoStoreError::MismatchedAccount {
expected: (account.user_id().to_owned(), account.device_id().to_owned()),
got: (user_id.to_owned(), device_id.to_owned()),
});
}
Span::current()
.record("ed25519_key", display(account.identity_keys().ed25519))
.record("curve25519_key", display(account.identity_keys().curve25519));
debug!("Restored an Olm account");
account.static_data().clone()
}
None => {
let account = if let Some(account) = custom_account {
Account::new_helper(account, user_id, device_id)
} else {
Account::with_device_id(user_id, device_id)
};
let static_account = account.static_data().clone();
Span::current()
.record("ed25519_key", display(account.identity_keys().ed25519))
.record("curve25519_key", display(account.identity_keys().curve25519));
let device = DeviceData::from_account(&account);
// We just created this device from our own Olm `Account`. Since we are the
// owners of the private keys of this device we can safely mark
// the device as verified.
device.set_trust_state(LocalTrust::Verified);
let changes = Changes {
devices: DeviceChanges { new: vec![device], ..Default::default() },
..Default::default()
};
store.save_changes(changes).await?;
store.save_pending_changes(PendingChanges { account: Some(account) }).await?;
debug!("Created a new Olm account");
static_account
}
};
let identity = match store.load_identity().await? {
Some(i) => {
let master_key = i
.master_public_key()
.await
.and_then(|m| m.get_first_key().map(|m| m.to_owned()));
debug!(?master_key, "Restored the cross signing identity");
i
}
None => {
debug!("Creating an empty cross signing identity stub");
PrivateCrossSigningIdentity::empty(user_id)
}
};
// FIXME: This is a workaround for `regenerate_olm` clearing the backup
// state. Ideally, backups should not get automatically enabled since
// the `OlmMachine` doesn't get enough info from the homeserver for this
// to work reliably.
let saved_keys = store.load_backup_keys().await?;
let maybe_backup_key = saved_keys.decryption_key.and_then(|k| {
if let Some(version) = saved_keys.backup_version {
let megolm_v1_backup_key = k.megolm_v1_public_key();
megolm_v1_backup_key.set_version(version);
Some(megolm_v1_backup_key)
} else {
None
}
});
let identity = Arc::new(Mutex::new(identity));
let store = Arc::new(CryptoStoreWrapper::new(user_id, device_id, store));
let (verification_machine, store, identity_manager) =
Self::new_helper_prelude(store, static_account, identity.clone());
// FIXME: We might want in the future a more generic high-level data migration
// mechanism (at the store wrapper layer).
Self::migration_post_verified_latch_support(&store, &identity_manager).await?;
Ok(Self::new_helper(
device_id,
store,
verification_machine,
identity_manager,
identity,
maybe_backup_key,
))
}
// The sdk now support verified identity change detection.
// This introduces a new local flag (`verified_latch` on
// `OtherUserIdentityData`). In order to ensure that this flag is up-to-date and
// for the sake of simplicity we force a re-download of tracked users by marking
// them as dirty.
//
// pub(crate) visibility for testing.
pub(crate) async fn migration_post_verified_latch_support(
store: &Store,
identity_manager: &IdentityManager,
) -> Result<(), CryptoStoreError> {
let maybe_migrate_for_identity_verified_latch =
store.get_custom_value(Self::HAS_MIGRATED_VERIFICATION_LATCH).await?.is_none();
if maybe_migrate_for_identity_verified_latch {
identity_manager.mark_all_tracked_users_as_dirty(store.cache().await?).await?;
store.set_custom_value(Self::HAS_MIGRATED_VERIFICATION_LATCH, vec![0]).await?
}
Ok(())
}
/// Get the crypto store associated with this `OlmMachine` instance.
pub fn store(&self) -> &Store {
&self.inner.store
}
/// The unique user id that owns this `OlmMachine` instance.
pub fn user_id(&self) -> &UserId {
&self.inner.user_id
}
/// The unique device ID that identifies this `OlmMachine`.
pub fn device_id(&self) -> &DeviceId {
&self.inner.device_id
}
/// The time at which the `Account` backing this `OlmMachine` was created.
///
/// An [`Account`] is created when an `OlmMachine` is first instantiated
/// against a given [`Store`], at which point it creates identity keys etc.
/// This method returns the timestamp, according to the local clock, at
/// which that happened.
pub fn device_creation_time(&self) -> MilliSecondsSinceUnixEpoch {
self.inner.store.static_account().creation_local_time()
}
/// Get the public parts of our Olm identity keys.
pub fn identity_keys(&self) -> IdentityKeys {
let account = self.inner.store.static_account();
account.identity_keys()
}
/// Get the display name of our own device
pub async fn display_name(&self) -> StoreResult<Option<String>> {
self.store().device_display_name().await
}
/// Get the list of "tracked users".
///
/// See [`update_tracked_users`](#method.update_tracked_users) for more
/// information.
pub async fn tracked_users(&self) -> StoreResult<HashSet<OwnedUserId>> {
let cache = self.store().cache().await?;
Ok(self.inner.identity_manager.key_query_manager.synced(&cache).await?.tracked_users())
}
/// Enable or disable room key requests.
///
/// Room key requests allow the device to request room keys that it might
/// have missed in the original share using `m.room_key_request`
/// events.
///
/// See also [`OlmMachine::set_room_key_forwarding_enabled`] and
/// [`OlmMachine::are_room_key_requests_enabled`].
#[cfg(feature = "automatic-room-key-forwarding")]
pub fn set_room_key_requests_enabled(&self, enable: bool) {
self.inner.key_request_machine.set_room_key_requests_enabled(enable)
}
/// Query whether we should send outgoing `m.room_key_request`s on
/// decryption failure.
///
/// See also [`OlmMachine::set_room_key_requests_enabled`].
pub fn are_room_key_requests_enabled(&self) -> bool {
self.inner.key_request_machine.are_room_key_requests_enabled()
}
/// Enable or disable room key forwarding.
///
/// If room key forwarding is enabled, we will automatically reply to
/// incoming `m.room_key_request` messages from verified devices by
/// forwarding the requested key (if we have it).
///
/// See also [`OlmMachine::set_room_key_requests_enabled`] and
/// [`OlmMachine::is_room_key_forwarding_enabled`].
#[cfg(feature = "automatic-room-key-forwarding")]
pub fn set_room_key_forwarding_enabled(&self, enable: bool) {
self.inner.key_request_machine.set_room_key_forwarding_enabled(enable)
}
/// Is room key forwarding enabled?
///
/// See also [`OlmMachine::set_room_key_forwarding_enabled`].
pub fn is_room_key_forwarding_enabled(&self) -> bool {
self.inner.key_request_machine.is_room_key_forwarding_enabled()
}
/// Get the outgoing requests that need to be sent out.
///
/// This returns a list of [`OutgoingRequest`]. Those requests need to be
/// sent out to the server and the responses need to be passed back to
/// the state machine using [`mark_request_as_sent`].
///
/// [`mark_request_as_sent`]: #method.mark_request_as_sent
pub async fn outgoing_requests(&self) -> StoreResult<Vec<OutgoingRequest>> {
let mut requests = Vec::new();
{
let store_cache = self.inner.store.cache().await?;
let account = store_cache.account().await?;
if let Some(r) = self.keys_for_upload(&account).await.map(|r| OutgoingRequest {
request_id: TransactionId::new(),
request: Arc::new(r.into()),
}) {
requests.push(r);
}
}
for request in self
.inner
.identity_manager
.users_for_key_query()
.await?
.into_iter()
.map(|(request_id, r)| OutgoingRequest { request_id, request: Arc::new(r.into()) })
{
requests.push(request);
}
requests.append(&mut self.inner.verification_machine.outgoing_messages());
requests.append(&mut self.inner.key_request_machine.outgoing_to_device_requests().await?);
Ok(requests)
}
/// Generate an "out-of-band" key query request for the given set of users.
///
/// This can be useful if we need the results from [`get_identity`] or
/// [`get_user_devices`] to be as up-to-date as possible.
///
/// Note that this request won't be awaited by other calls waiting for a
/// user's or device's keys, since this is an out-of-band query.
///
/// # Arguments
///
/// * `users` - list of users whose keys should be queried
///
/// # Returns
///
/// A request to be sent out to the server. Once sent, the response should
/// be passed back to the state machine using [`mark_request_as_sent`].
///
/// [`mark_request_as_sent`]: OlmMachine::mark_request_as_sent
/// [`get_identity`]: OlmMachine::get_identity
/// [`get_user_devices`]: OlmMachine::get_user_devices
pub fn query_keys_for_users<'a>(
&self,
users: impl IntoIterator<Item = &'a UserId>,
) -> (OwnedTransactionId, KeysQueryRequest) {
self.inner.identity_manager.build_key_query_for_users(users)
}
/// Mark the request with the given request id as sent.
///
/// # Arguments
///
/// * `request_id` - The unique id of the request that was sent out. This is
/// needed to couple the response with the now sent out request.
///
/// * `response` - The response that was received from the server after the
/// outgoing request was sent out.
pub async fn mark_request_as_sent<'a>(
&self,
request_id: &TransactionId,
response: impl Into<AnyIncomingResponse<'a>>,
) -> OlmResult<()> {
match response.into() {
AnyIncomingResponse::KeysUpload(response) => {
Box::pin(self.receive_keys_upload_response(response)).await?;
}
AnyIncomingResponse::KeysQuery(response) => {
Box::pin(self.receive_keys_query_response(request_id, response)).await?;
}
AnyIncomingResponse::KeysClaim(response) => {
Box::pin(
self.inner.session_manager.receive_keys_claim_response(request_id, response),
)
.await?;
}
AnyIncomingResponse::ToDevice(_) => {
Box::pin(self.mark_to_device_request_as_sent(request_id)).await?;
}
AnyIncomingResponse::SigningKeysUpload(_) => {
Box::pin(self.receive_cross_signing_upload_response()).await?;
}
AnyIncomingResponse::SignatureUpload(_) => {
self.inner.verification_machine.mark_request_as_sent(request_id);
}
AnyIncomingResponse::RoomMessage(_) => {
self.inner.verification_machine.mark_request_as_sent(request_id);
}
AnyIncomingResponse::KeysBackup(_) => {
Box::pin(self.inner.backup_machine.mark_request_as_sent(request_id)).await?;
}
};
Ok(())
}
/// Mark the cross signing identity as shared.
async fn receive_cross_signing_upload_response(&self) -> StoreResult<()> {
let identity = self.inner.user_identity.lock().await;
identity.mark_as_shared();
let changes = Changes { private_identity: Some(identity.clone()), ..Default::default() };
self.store().save_changes(changes).await
}
/// Create a new cross signing identity and get the upload request to push
/// the new public keys to the server.
///
/// **Warning**: if called with `reset`, this will delete any existing cross
/// signing keys that might exist on the server and thus will reset the
/// trust between all the devices.
///
/// # Returns
///
/// A triple of requests which should be sent out to the server, in the
/// order they appear in the return tuple.
///
/// The first request's response, if present, should be passed back to the
/// state machine using [`mark_request_as_sent`].
///
/// These requests may require user interactive auth.
///
/// [`mark_request_as_sent`]: #method.mark_request_as_sent
pub async fn bootstrap_cross_signing(
&self,
reset: bool,
) -> StoreResult<CrossSigningBootstrapRequests> {
// Don't hold the lock, otherwise we might deadlock in
// `bootstrap_cross_signing()` on `account` if a sync task is already
// running (which locks `account`), or we will deadlock
// in `upload_device_keys()` which locks private identity again.
let identity = self.inner.user_identity.lock().await.clone();
let (upload_signing_keys_req, upload_signatures_req) = if reset || identity.is_empty().await
{
info!("Creating new cross signing identity");
let (identity, upload_signing_keys_req, upload_signatures_req) = {
let cache = self.inner.store.cache().await?;
let account = cache.account().await?;
account.bootstrap_cross_signing().await
};
let public = identity.to_public_identity().await.expect(
"Couldn't create a public version of the identity from a new private identity",
);
*self.inner.user_identity.lock().await = identity.clone();
self.store()
.save_changes(Changes {
identities: IdentityChanges { new: vec![public.into()], ..Default::default() },
private_identity: Some(identity),
..Default::default()
})
.await?;
(upload_signing_keys_req, upload_signatures_req)
} else {
info!("Trying to upload the existing cross signing identity");
let upload_signing_keys_req = identity.as_upload_request().await;
// TODO remove this expect.
let upload_signatures_req = identity
.sign_account(self.inner.store.static_account())
.await
.expect("Can't sign device keys");
(upload_signing_keys_req, upload_signatures_req)
};
// If there are any *device* keys to upload (i.e. the account isn't shared),
// upload them before we upload the signatures, since the signatures may
// reference keys to be uploaded.
let upload_keys_req =
self.upload_device_keys().await?.map(|(_, request)| OutgoingRequest::from(request));
Ok(CrossSigningBootstrapRequests {
upload_signing_keys_req,
upload_keys_req,
upload_signatures_req,
})
}
/// Upload the device keys for this [`OlmMachine`].
///
/// **Warning**: Do not use this method if
/// [`OlmMachine::outgoing_requests()`] is already in use. This method
/// is intended for explicitly uploading the device keys before starting
/// a sync and before using [`OlmMachine::outgoing_requests()`].
///
/// # Returns
///
/// A tuple containing a transaction ID and a request if the device keys
/// need to be uploaded. Otherwise, returns `None`.
pub async fn upload_device_keys(
&self,
) -> StoreResult<Option<(OwnedTransactionId, UploadKeysRequest)>> {
let cache = self.store().cache().await?;
let account = cache.account().await?;
Ok(self.keys_for_upload(&account).await.map(|request| (TransactionId::new(), request)))
}
/// Receive a successful `/keys/upload` response.
///
/// # Arguments
///
/// * `response` - The response of the `/keys/upload` request that the
/// client performed.
async fn receive_keys_upload_response(&self, response: &UploadKeysResponse) -> OlmResult<()> {
self.inner
.store
.with_transaction(|mut tr| async {
let account = tr.account().await?;
account.receive_keys_upload_response(response)?;
Ok((tr, ()))
})
.await
}
/// Get a key claiming request for the user/device pairs that we are
/// missing Olm sessions for.
///
/// Returns None if no key claiming request needs to be sent out.
///
/// Sessions need to be established between devices so group sessions for a
/// room can be shared with them.
///
/// This should be called every time a group session needs to be shared as
/// well as between sync calls. After a sync some devices may request room
/// keys without us having a valid Olm session with them, making it
/// impossible to server the room key request, thus it's necessary to check
/// for missing sessions between sync as well.
///
/// **Note**: Care should be taken that only one such request at a time is
/// in flight, e.g. using a lock.
///
/// The response of a successful key claiming requests needs to be passed to
/// the `OlmMachine` with the [`mark_request_as_sent`].
///
/// # Arguments
///
/// `users` - The list of users that we should check if we lack a session
/// with one of their devices. This can be an empty iterator when calling
/// this method between sync requests.
///
/// [`mark_request_as_sent`]: #method.mark_request_as_sent
#[instrument(skip_all)]
pub async fn get_missing_sessions(
&self,
users: impl Iterator<Item = &UserId>,
) -> StoreResult<Option<(OwnedTransactionId, KeysClaimRequest)>> {
self.inner.session_manager.get_missing_sessions(users).await
}
/// Receive a successful `/keys/query` response.
///
/// Returns a list of newly discovered devices and devices that changed.
///
/// # Arguments
///
/// * `response` - The response of the `/keys/query` request that the client
/// performed.
async fn receive_keys_query_response(
&self,
request_id: &TransactionId,
response: &KeysQueryResponse,
) -> OlmResult<(DeviceChanges, IdentityChanges)> {
self.inner.identity_manager.receive_keys_query_response(request_id, response).await
}
/// Get a request to upload E2EE keys to the server.
///
/// Returns None if no keys need to be uploaded.
///
/// The response of a successful key upload requests needs to be passed to
/// the [`OlmMachine`] with the [`receive_keys_upload_response`].
///
/// [`receive_keys_upload_response`]: #method.receive_keys_upload_response
async fn keys_for_upload(&self, account: &Account) -> Option<UploadKeysRequest> {
let (mut device_keys, one_time_keys, fallback_keys) = account.keys_for_upload();
// When uploading the device keys, if all private cross-signing keys are
// available locally, sign the device using these cross-signing keys.
// This will mark the device as verified if the user identity (i.e., the
// cross-signing keys) is also marked as verified.
//
// This approach eliminates the need to upload signatures in a separate request,
// ensuring that other users/devices will never encounter this device
// without a signature from their user identity. Consequently, they will
// never see the device as unverified.
if let Some(device_keys) = &mut device_keys {
let private_identity = self.store().private_identity();
let guard = private_identity.lock().await;
if guard.status().await.is_complete() {
guard.sign_device_keys(device_keys).await.expect(
"We should be able to sign our device keys since we confirmed that we \
have a complete set of private cross-signing keys",
);
}
}
if device_keys.is_none() && one_time_keys.is_empty() && fallback_keys.is_empty() {
None
} else {
let device_keys = device_keys.map(|d| d.to_raw());
Some(assign!(UploadKeysRequest::new(), {
device_keys, one_time_keys, fallback_keys
}))
}
}
/// Decrypt a to-device event.
///
/// Returns a decrypted `ToDeviceEvent` if the decryption was successful,
/// an error indicating why decryption failed otherwise.
///
/// # Arguments
///
/// * `event` - The to-device event that should be decrypted.
async fn decrypt_to_device_event(
&self,
transaction: &mut StoreTransaction,
event: &EncryptedToDeviceEvent,
changes: &mut Changes,
) -> OlmResult<OlmDecryptionInfo> {
let mut decrypted =
transaction.account().await?.decrypt_to_device_event(&self.inner.store, event).await?;
// Handle the decrypted event, e.g. fetch out Megolm sessions out of
// the event.
self.handle_decrypted_to_device_event(transaction.cache(), &mut decrypted, changes).await?;
Ok(decrypted)
}
#[instrument(
skip_all,
// This function is only ever called by add_room_key via
// handle_decrypted_to_device_event, so sender, sender_key, and algorithm are
// already recorded.
fields(room_id = ? content.room_id, session_id)
)]
async fn handle_key(
&self,
sender_key: Curve25519PublicKey,
event: &DecryptedRoomKeyEvent,
content: &MegolmV1AesSha2Content,
) -> OlmResult<Option<InboundGroupSession>> {
let session = InboundGroupSession::new(
sender_key,
event.keys.ed25519,
&content.room_id,
&content.session_key,
SenderData::unknown(),
event.content.algorithm(),
None,
);
match session {
Ok(mut session) => {
Span::current().record("session_id", session.session_id());
let sender_data =
SenderDataFinder::find_using_event(self.store(), sender_key, event, &session)
.await?;
session.sender_data = sender_data;
match self.store().compare_group_session(&session).await? {
SessionOrdering::Better => {
info!("Received a new megolm room key");
Ok(Some(session))
}
comparison_result => {
warn!(
?comparison_result,
"Received a megolm room key that we already have a better version \
of, discarding"
);
Ok(None)
}
}
}
Err(e) => {
Span::current().record("session_id", &content.session_id);
warn!("Received a room key event which contained an invalid session key: {e}");
Ok(None)
}
}
}
/// Create a group session from a room key and add it to our crypto store.
#[instrument(skip_all, fields(algorithm = ?event.content.algorithm()))]
async fn add_room_key(
&self,
sender_key: Curve25519PublicKey,
event: &DecryptedRoomKeyEvent,
) -> OlmResult<Option<InboundGroupSession>> {
match &event.content {
RoomKeyContent::MegolmV1AesSha2(content) => {
self.handle_key(sender_key, event, content).await
}
#[cfg(feature = "experimental-algorithms")]
RoomKeyContent::MegolmV2AesSha2(content) => {
self.handle_key(sender_key, event, content).await
}
RoomKeyContent::Unknown(_) => {
warn!("Received a room key with an unsupported algorithm");
Ok(None)
}
}
}
fn add_withheld_info(&self, changes: &mut Changes, event: &RoomKeyWithheldEvent) {
debug!(?event.content, "Processing `m.room_key.withheld` event");
if let RoomKeyWithheldContent::MegolmV1AesSha2(
MegolmV1AesSha2WithheldContent::BlackListed(c)
| MegolmV1AesSha2WithheldContent::Unverified(c),
) = &event.content
{
changes
.withheld_session_info
.entry(c.room_id.to_owned())
.or_default()
.insert(c.session_id.to_owned(), event.to_owned());
}
}
#[cfg(test)]
pub(crate) async fn create_outbound_group_session_with_defaults_test_helper(
&self,
room_id: &RoomId,
) -> OlmResult<()> {
let (_, session) = self
.inner
.group_session_manager
.create_outbound_group_session(
room_id,
EncryptionSettings::default(),
SenderData::unknown(),
)
.await?;
self.store().save_inbound_group_sessions(&[session]).await?;
Ok(())
}
#[cfg(test)]
#[allow(dead_code)]
pub(crate) async fn create_inbound_session_test_helper(
&self,
room_id: &RoomId,
) -> OlmResult<InboundGroupSession> {
let (_, session) = self
.inner
.group_session_manager
.create_outbound_group_session(
room_id,
EncryptionSettings::default(),
SenderData::unknown(),
)
.await?;
Ok(session)
}
/// Encrypt a room message for the given room.
///
/// Beware that a room key needs to be shared before this method