-
Notifications
You must be signed in to change notification settings - Fork 219
/
machine.rs
2313 lines (1989 loc) · 82.6 KB
/
machine.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, BTreeSet, HashSet},
sync::Arc,
time::Duration,
};
use dashmap::DashMap;
use matrix_sdk_common::{
deserialized_responses::{AlgorithmInfo, EncryptionInfo, RoomEvent, VerificationState},
locks::Mutex,
};
use ruma::{
api::client::{
keys::{
claim_keys::v3::{Request as KeysClaimRequest, Response as KeysClaimResponse},
get_keys::v3::Response as KeysQueryResponse,
upload_keys,
upload_signatures::v3::Request as UploadSignaturesRequest,
},
sync::sync_events::v3::{DeviceLists, ToDevice},
},
assign,
events::{
secret::request::SecretName, AnyMessageLikeEvent, AnyRoomEvent, MessageLikeEventContent,
},
serde::Raw,
DeviceId, DeviceKeyAlgorithm, OwnedDeviceKeyId, OwnedTransactionId, OwnedUserId, RoomId,
TransactionId, UInt, UserId,
};
use serde_json::{value::to_raw_value, Value};
use tracing::{debug, error, info, trace, warn};
use vodozemac::{Curve25519PublicKey, Ed25519Signature};
#[cfg(feature = "backups_v1")]
use crate::backups::BackupMachine;
use crate::{
error::{EventError, MegolmError, MegolmResult, OlmError, OlmResult},
gossiping::GossipMachine,
identities::{user::UserIdentities, Device, IdentityManager, UserDevices},
olm::{
Account, CrossSigningStatus, EncryptionSettings, ExportedRoomKey, IdentityKeys,
InboundGroupSession, OlmDecryptionInfo, PrivateCrossSigningIdentity, ReadOnlyAccount,
SessionType,
},
requests::{IncomingResponse, OutgoingRequest, UploadSigningKeysRequest},
session_manager::{GroupSessionManager, SessionManager},
store::{
Changes, CryptoStore, DeviceChanges, IdentityChanges, MemoryStore, Result as StoreResult,
SecretImportError, Store,
},
types::{
events::{
room::encrypted::{
EncryptedEvent, EncryptedToDeviceEvent, RoomEncryptedEventContent,
RoomEventEncryptionScheme, SupportedEventEncryptionSchemes,
},
room_key::{RoomKeyContent, RoomKeyEvent},
ToDeviceEvents,
},
Signatures,
},
verification::{Verification, VerificationMachine, VerificationRequest},
CrossSigningKeyExport, ReadOnlyDevice, RoomKeyImportResult, SignatureError, ToDeviceRequest,
};
/// State machine implementation of the Olm/Megolm encryption protocol used for
/// Matrix end to end encryption.
#[derive(Clone)]
pub struct OlmMachine {
/// The unique user id that owns this account.
user_id: Arc<UserId>,
/// The unique device ID of the device that holds this account.
device_id: Arc<DeviceId>,
/// Our underlying Olm Account holding our identity keys.
account: Account,
/// 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.
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.
#[cfg(feature = "backups_v1")]
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 {
/// 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 {
let store: Arc<dyn CryptoStore> = Arc::new(MemoryStore::new());
OlmMachine::with_store(user_id, device_id, store)
.await
.expect("Reading and writing to the memory store always succeeds")
}
fn new_helper(
user_id: &UserId,
device_id: &DeviceId,
store: Arc<dyn CryptoStore>,
account: ReadOnlyAccount,
user_identity: PrivateCrossSigningIdentity,
) -> Self {
let user_id: Arc<UserId> = user_id.into();
let user_identity = Arc::new(Mutex::new(user_identity));
let verification_machine =
VerificationMachine::new(account.clone(), user_identity.clone(), store.clone());
let store =
Store::new(user_id.clone(), user_identity.clone(), store, verification_machine.clone());
let device_id: Arc<DeviceId> = device_id.into();
let users_for_key_claim = Arc::new(DashMap::new());
let account = Account { inner: account, store: store.clone() };
let group_session_manager = GroupSessionManager::new(account.clone(), store.clone());
let key_request_machine = GossipMachine::new(
user_id.clone(),
device_id.clone(),
store.clone(),
group_session_manager.session_cache(),
users_for_key_claim.clone(),
);
let identity_manager =
IdentityManager::new(user_id.clone(), device_id.clone(), store.clone());
let event = identity_manager.listen_for_received_queries();
let session_manager = SessionManager::new(
account.clone(),
users_for_key_claim,
key_request_machine.clone(),
store.clone(),
event,
);
#[cfg(feature = "backups_v1")]
let backup_machine = BackupMachine::new(account.clone(), store.clone(), None);
OlmMachine {
user_id,
device_id,
account,
user_identity,
store,
session_manager,
group_session_manager,
verification_machine,
key_request_machine,
identity_manager,
#[cfg(feature = "backups_v1")]
backup_machine,
}
}
/// 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.
///
/// [`Cryptostore`]: trait.CryptoStore.html
pub async fn with_store(
user_id: &UserId,
device_id: &DeviceId,
store: Arc<dyn CryptoStore>,
) -> StoreResult<Self> {
let account = match store.load_account().await? {
Some(a) => {
debug!(
ed25519_key = a.identity_keys().ed25519.to_base64().as_str(),
"Restored an Olm account"
);
a
}
None => {
let account = ReadOnlyAccount::new(user_id, device_id);
let device = ReadOnlyDevice::from_account(&account).await;
debug!(
ed25519_key = account.identity_keys().ed25519.to_base64().as_str(),
"Created a new Olm account"
);
let changes = Changes {
account: Some(account.clone()),
devices: DeviceChanges { new: vec![device], ..Default::default() },
..Default::default()
};
store.save_changes(changes).await?;
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)
}
};
Ok(OlmMachine::new_helper(user_id, device_id, store, account, identity))
}
/// The unique user id that owns this `OlmMachine` instance.
pub fn user_id(&self) -> &UserId {
&self.user_id
}
/// The unique device ID that identifies this `OlmMachine`.
pub fn device_id(&self) -> &DeviceId {
&self.device_id
}
/// Get the public parts of our Olm identity keys.
pub fn identity_keys(&self) -> IdentityKeys {
self.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 all the tracked users we know about
pub fn tracked_users(&self) -> HashSet<OwnedUserId> {
self.store.tracked_users()
}
/// 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();
if let Some(r) = self.keys_for_upload().await.map(|r| OutgoingRequest {
request_id: TransactionId::new(),
request: Arc::new(r.into()),
}) {
self.account.save().await?;
requests.push(r);
}
for request in self.identity_manager.users_for_key_query().await.into_iter().map(|r| {
OutgoingRequest { request_id: TransactionId::new(), request: Arc::new(r.into()) }
}) {
requests.push(request);
}
requests.append(&mut self.verification_machine.outgoing_messages());
requests.append(&mut self.key_request_machine.outgoing_to_device_requests().await?);
Ok(requests)
}
/// 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<IncomingResponse<'a>>,
) -> OlmResult<()> {
match response.into() {
IncomingResponse::KeysUpload(response) => {
self.receive_keys_upload_response(response).await?;
}
IncomingResponse::KeysQuery(response) => {
self.receive_keys_query_response(response).await?;
}
IncomingResponse::KeysClaim(response) => {
self.receive_keys_claim_response(response).await?;
}
IncomingResponse::ToDevice(_) => {
self.mark_to_device_request_as_sent(request_id).await?;
}
IncomingResponse::SigningKeysUpload(_) => {
self.receive_cross_signing_upload_response().await?;
}
IncomingResponse::SignatureUpload(_) => {
self.verification_machine.mark_request_as_sent(request_id);
}
IncomingResponse::RoomMessage(_) => {
self.verification_machine.mark_request_as_sent(request_id);
}
IncomingResponse::KeysBackup(_) => {
#[cfg(feature = "backups_v1")]
self.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.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**: This will delete any existing cross signing keys that might
/// exist on the server and thus will reset the trust between all the
/// devices.
///
/// Uploading these keys will require user interactive auth.
pub async fn bootstrap_cross_signing(
&self,
reset: bool,
) -> StoreResult<(UploadSigningKeysRequest, UploadSignaturesRequest)> {
let mut identity = self.user_identity.lock().await;
if identity.is_empty().await || reset {
info!("Creating new cross signing identity");
let (id, request, signature_request) = self.account.bootstrap_cross_signing().await;
*identity = id;
let public = identity.to_public_identity().await.expect(
"Couldn't create a public version of the identity from a new private identity",
);
let changes = Changes {
identities: IdentityChanges { new: vec![public.into()], ..Default::default() },
private_identity: Some(identity.clone()),
..Default::default()
};
self.store.save_changes(changes).await?;
Ok((request, signature_request))
} else {
info!("Trying to upload the existing cross signing identity");
let request = identity.as_upload_request().await;
// TODO remove this expect.
let signature_request =
identity.sign_account(&self.account).await.expect("Can't sign device keys");
Ok((request, signature_request))
}
}
/// Get the underlying Olm account of the machine.
#[cfg(any(test, feature = "testing"))]
#[allow(dead_code)]
pub(crate) fn account(&self) -> &ReadOnlyAccount {
&self.account
}
/// Receive a successful keys upload response.
///
/// # Arguments
///
/// * `response` - The keys upload response of the request that the client
/// performed.
async fn receive_keys_upload_response(
&self,
response: &upload_keys::v3::Response,
) -> OlmResult<()> {
self.account.receive_keys_upload_response(response).await
}
/// Get the 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
pub async fn get_missing_sessions(
&self,
users: impl Iterator<Item = &UserId>,
) -> StoreResult<Option<(OwnedTransactionId, KeysClaimRequest)>> {
self.session_manager.get_missing_sessions(users).await
}
/// Receive a successful key claim response and create new Olm sessions with
/// the claimed keys.
///
/// # Arguments
///
/// * `response` - The response containing the claimed one-time keys.
async fn receive_keys_claim_response(&self, response: &KeysClaimResponse) -> OlmResult<()> {
self.session_manager.receive_keys_claim_response(response).await
}
/// Receive a successful keys query response.
///
/// Returns a list of devices newly discovered devices and devices that
/// changed.
///
/// # Arguments
///
/// * `response` - The keys query response of the request that the client
/// performed.
async fn receive_keys_query_response(
&self,
response: &KeysQueryResponse,
) -> OlmResult<(DeviceChanges, IdentityChanges)> {
self.identity_manager.receive_keys_query_response(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
/// [`OlmMachine`]: struct.OlmMachine.html
async fn keys_for_upload(&self) -> Option<upload_keys::v3::Request> {
let (device_keys, one_time_keys, fallback_keys) = self.account.keys_for_upload().await;
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!(upload_keys::v3::Request::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,
event: &EncryptedToDeviceEvent,
) -> OlmResult<OlmDecryptionInfo> {
let mut decrypted = self.account.decrypt_to_device_event(event).await?;
// Handle the decrypted event, e.g. fetch out Megolm sessions out of
// the event.
self.handle_decrypted_to_device_event(&mut decrypted).await?;
Ok(decrypted)
}
/// Create a group session from a room key and add it to our crypto store.
async fn add_room_key(
&self,
sender_key: Curve25519PublicKey,
signing_key: &str,
event: &RoomKeyEvent,
) -> OlmResult<Option<InboundGroupSession>> {
let unsupported_warning = || {
warn!(
sender = %event.sender,
sender_key = sender_key.to_base64(),
algorithm = %event.algorithm(),
"Received room key with unsupported key algorithm",
);
};
match &event.content {
RoomKeyContent::MegolmV1AesSha2(content) => {
let session = InboundGroupSession::new(
sender_key,
signing_key,
&content.room_id,
&content.session_key,
event.algorithm(),
None,
);
Ok(Some(session))
}
RoomKeyContent::Unknown(_) => {
unsupported_warning();
Ok(None)
}
}
}
#[cfg(test)]
pub(crate) async fn create_outbound_group_session_with_defaults(
&self,
room_id: &RoomId,
) -> OlmResult<()> {
let (_, session) = self
.group_session_manager
.create_outbound_group_session(room_id, EncryptionSettings::default())
.await?;
self.store.save_inbound_group_sessions(&[session]).await?;
Ok(())
}
#[cfg(test)]
#[allow(dead_code)]
pub(crate) async fn create_inbound_session(
&self,
room_id: &RoomId,
) -> OlmResult<InboundGroupSession> {
let (_, session) = self
.group_session_manager
.create_outbound_group_session(room_id, EncryptionSettings::default())
.await?;
Ok(session)
}
/// Encrypt a room message for the given room.
///
/// Beware that a room key needs to be shared before this method
/// can be called using the [`OlmMachine::share_room_key`] method.
///
/// # Arguments
///
/// * `room_id` - The id of the room for which the message should be
/// encrypted.
///
/// * `content` - The plaintext content of the message that should be
/// encrypted.
///
/// # Panics
///
/// Panics if a room key for the given room wasn't shared beforehand.
pub async fn encrypt_room_event(
&self,
room_id: &RoomId,
content: impl MessageLikeEventContent,
) -> MegolmResult<Raw<RoomEncryptedEventContent>> {
let event_type = content.event_type().to_string();
let content = serde_json::to_value(&content)?;
self.encrypt_room_event_raw(room_id, content, &event_type).await
}
/// Encrypt a json [`Value`] content for the given room.
///
/// This method is equivalent to the [`OlmMachine::encrypt_room_event()`]
/// method but operates on an arbitrary JSON value instead of strongly-typed
/// event content struct.
///
/// # Arguments
///
/// * `room_id` - The id of the room for which the message should be
/// encrypted.
///
/// * `content` - The plaintext content of the message that should be
/// encrypted as a json [`Value`].
///
/// * `event_type` - The plaintext type of the event.
///
/// # Panics
///
/// Panics if a group session for the given room wasn't shared beforehand.
pub async fn encrypt_room_event_raw(
&self,
room_id: &RoomId,
content: Value,
event_type: &str,
) -> MegolmResult<Raw<RoomEncryptedEventContent>> {
self.group_session_manager.encrypt(room_id, content, event_type).await
}
/// Invalidate the currently active outbound group session for the given
/// room.
///
/// Returns true if a session was invalidated, false if there was no session
/// to invalidate.
pub async fn invalidate_group_session(&self, room_id: &RoomId) -> StoreResult<bool> {
self.group_session_manager.invalidate_group_session(room_id).await
}
/// Get to-device requests to share a room key with users in a room.
///
/// # Arguments
///
/// `room_id` - The room id of the room where the room key will be
/// used.
///
/// `users` - The list of users that should receive the room key.
pub async fn share_room_key(
&self,
room_id: &RoomId,
users: impl Iterator<Item = &UserId>,
encryption_settings: impl Into<EncryptionSettings>,
) -> OlmResult<Vec<Arc<ToDeviceRequest>>> {
self.group_session_manager.share_room_key(room_id, users, encryption_settings).await
}
/// Receive an unencrypted verification event.
///
/// This method can be used to pass verification events that are happening
/// in unencrypted rooms to the `OlmMachine`.
///
/// **Note**: This does not need to be called for encrypted events since
/// those will get passed to the `OlmMachine` during decryption.
pub async fn receive_unencrypted_verification_event(
&self,
event: &AnyMessageLikeEvent,
) -> StoreResult<()> {
self.verification_machine.receive_any_event(event).await
}
/// Receive and properly handle a decrypted to-device event.
///
/// # Arguments
///
/// * `decrypted` - The decrypted event and some associated metadata.
async fn handle_decrypted_to_device_event(
&self,
decrypted: &mut OlmDecryptionInfo,
) -> OlmResult<()> {
let event: ToDeviceEvents = match decrypted.event.deserialize_as() {
Ok(e) => e,
Err(e) => {
warn!(
sender = decrypted.sender.as_str(),
sender_key = decrypted.sender_key.to_base64(),
error = ?e,
"Decrypted to-device event failed to be deserialized correctly"
);
return Ok(());
}
};
trace!(
sender = decrypted.sender.as_str(),
sender_key = decrypted.sender_key.to_base64(),
event_type = %event.event_type(),
"Received a decrypted to-device event"
);
match event {
ToDeviceEvents::RoomKey(e) => {
let session =
self.add_room_key(decrypted.sender_key, &decrypted.signing_key, &e).await?;
decrypted.inbound_group_session = session;
}
ToDeviceEvents::ForwardedRoomKey(e) => {
let session = self
.key_request_machine
.receive_forwarded_room_key(decrypted.sender_key, &e)
.await?;
decrypted.inbound_group_session = session;
}
ToDeviceEvents::SecretSend(mut e) => {
self.key_request_machine.receive_secret_event(decrypted.sender_key, &mut e).await?;
decrypted.event = Raw::from_json(to_raw_value(&e)?)
}
_ => {
warn!(
event_type = ?event.event_type(),
"Received an unexpected encrypted to-device event"
);
}
}
Ok(())
}
async fn handle_verification_event(&self, event: &ToDeviceEvents) {
if let Err(e) = self.verification_machine.receive_any_event(event).await {
error!("Error handling a verification event: {:?}", e);
}
}
/// Mark an outgoing to-device requests as sent.
async fn mark_to_device_request_as_sent(&self, request_id: &TransactionId) -> StoreResult<()> {
self.verification_machine.mark_request_as_sent(request_id);
self.key_request_machine.mark_outgoing_request_as_sent(request_id).await?;
self.group_session_manager.mark_request_as_sent(request_id).await?;
self.session_manager.mark_outgoing_request_as_sent(request_id);
Ok(())
}
/// Get a verification object for the given user id with the given flow id.
pub fn get_verification(&self, user_id: &UserId, flow_id: &str) -> Option<Verification> {
self.verification_machine.get_verification(user_id, flow_id)
}
/// Get a verification request object with the given flow id.
pub fn get_verification_request(
&self,
user_id: &UserId,
flow_id: impl AsRef<str>,
) -> Option<VerificationRequest> {
self.verification_machine.get_request(user_id, flow_id)
}
/// Get all the verification requests of a given user.
pub fn get_verification_requests(&self, user_id: &UserId) -> Vec<VerificationRequest> {
self.verification_machine.get_requests(user_id)
}
async fn update_key_counts(
&self,
one_time_key_count: &BTreeMap<DeviceKeyAlgorithm, UInt>,
unused_fallback_keys: Option<&[DeviceKeyAlgorithm]>,
) {
self.account.update_key_counts(one_time_key_count, unused_fallback_keys).await;
}
async fn handle_to_device_event(&self, event: &ToDeviceEvents) {
use crate::types::events::ToDeviceEvents::*;
match event {
RoomKeyRequest(e) => self.key_request_machine.receive_incoming_key_request(e),
SecretRequest(e) => self.key_request_machine.receive_incoming_secret_request(e),
KeyVerificationAccept(..)
| KeyVerificationCancel(..)
| KeyVerificationKey(..)
| KeyVerificationMac(..)
| KeyVerificationRequest(..)
| KeyVerificationReady(..)
| KeyVerificationDone(..)
| KeyVerificationStart(..) => {
self.handle_verification_event(event).await;
}
Dummy(_) | RoomKey(_) | ForwardedRoomKey(_) | RoomEncrypted(_) => {}
_ => {}
}
}
/// Handle a to-device and one-time key counts from a sync response.
///
/// This will decrypt and handle to-device events returning the decrypted
/// versions of them.
///
/// To decrypt an event from the room timeline call [`decrypt_room_event`].
///
/// # Arguments
///
/// * `to_device_events` - The to-device events of the current sync
/// response.
///
/// * `changed_devices` - The list of devices that changed in this sync
/// response.
///
/// * `one_time_keys_count` - The current one-time keys counts that the sync
/// response returned.
///
/// [`decrypt_room_event`]: #method.decrypt_room_event
pub async fn receive_sync_changes(
&self,
to_device_events: ToDevice,
changed_devices: &DeviceLists,
one_time_keys_counts: &BTreeMap<DeviceKeyAlgorithm, UInt>,
unused_fallback_keys: Option<&[DeviceKeyAlgorithm]>,
) -> OlmResult<ToDevice> {
// Remove verification objects that have expired or are done.
let mut events = self.verification_machine.garbage_collect();
// Always save the account, a new session might get created which also
// touches the account.
let mut changes =
Changes { account: Some(self.account.inner.clone()), ..Default::default() };
self.update_key_counts(one_time_keys_counts, unused_fallback_keys).await;
for user_id in &changed_devices.changed {
if let Err(e) = self.identity_manager.mark_user_as_changed(user_id).await {
error!(error = ?e, "Error marking a tracked user as changed");
}
}
for mut raw_event in to_device_events.events {
let event: ToDeviceEvents = match raw_event.deserialize_as() {
Ok(e) => e,
Err(e) => {
// Skip invalid events.
warn!(
error = ?e,
"Received an invalid to-device event"
);
events.push(raw_event);
continue;
}
};
trace!(
sender = event.sender().as_str(),
event_type = %event.event_type(),
"Received a to-device event"
);
match event {
ToDeviceEvents::RoomEncrypted(e) => {
let decrypted = match self.decrypt_to_device_event(&e).await {
Ok(e) => e,
Err(err) => {
if let OlmError::SessionWedged(sender, curve_key) = err {
if let Err(e) = self
.session_manager
.mark_device_as_wedged(&sender, &curve_key)
.await
{
error!(
sender = sender.as_str(),
error = ?e,
"Couldn't mark device from to be unwedged",
);
}
}
continue;
}
};
// New sessions modify the account so we need to save that
// one as well.
match decrypted.session {
SessionType::New(s) => {
changes.sessions.push(s);
changes.account = Some(self.account.inner.clone());
}
SessionType::Existing(s) => {
changes.sessions.push(s);
}
}
changes.message_hashes.push(decrypted.message_hash);
if let Some(group_session) = decrypted.inbound_group_session {
changes.inbound_group_sessions.push(group_session);
}
match decrypted.event.deserialize_as() {
Ok(event) => {
self.handle_to_device_event(&event).await;
raw_event = event
.serialize_zeroized()
.expect("Zeroizing and reserializing our events should always work")
.cast();
}
Err(e) => {
warn!(
error = ?e,
"Received an invalid encrypted to-device event"
);
raw_event = decrypted.event;
}
}
}
e => self.handle_to_device_event(&e).await,
}
events.push(raw_event);
}
let changed_sessions = self.key_request_machine.collect_incoming_key_requests().await?;
changes.sessions.extend(changed_sessions);
self.store.save_changes(changes).await?;
let mut to_device = ToDevice::new();
to_device.events = events;
Ok(to_device)
}
/// Request a room key from our devices.
///
/// This method will return a request cancellation and a new key request if
/// the key was already requested, otherwise it will return just the key
/// request.
///
/// The request cancellation *must* be sent out before the request is sent
/// out, otherwise devices will ignore the key request.
///
/// # Arguments
///
/// * `room_id` - The id of the room where the key is used in.
///
/// * `sender_key` - The curve25519 key of the sender that owns the key.
///
/// * `session_id` - The id that uniquely identifies the session.
pub async fn request_room_key(
&self,
event: &Raw<EncryptedEvent>,
room_id: &RoomId,
) -> MegolmResult<(Option<OutgoingRequest>, OutgoingRequest)> {
let event = event.deserialize()?;
let content: SupportedEventEncryptionSchemes<'_> = match &event.content.scheme {
RoomEventEncryptionScheme::MegolmV1AesSha2(c) => c.into(),
_ => return Err(EventError::UnsupportedAlgorithm.into()),
};
Ok(self
.key_request_machine
.request_key(
room_id,