1#[cfg(feature = "experimental-encrypted-state-events")]
16use std::borrow::Borrow;
17use std::{
18 collections::{BTreeMap, HashMap, HashSet},
19 sync::Arc,
20 time::Duration,
21};
22
23use itertools::Itertools;
24#[cfg(feature = "experimental-send-custom-to-device")]
25use matrix_sdk_common::deserialized_responses::WithheldCode;
26use matrix_sdk_common::{
27 BoxFuture,
28 deserialized_responses::{
29 AlgorithmInfo, DecryptedRoomEvent, DeviceLinkProblem, EncryptionInfo, ForwarderInfo,
30 ProcessedToDeviceEvent, ToDeviceUnableToDecryptInfo, ToDeviceUnableToDecryptReason,
31 UnableToDecryptInfo, UnableToDecryptReason, UnsignedDecryptionResult,
32 UnsignedEventLocation, VerificationLevel, VerificationState,
33 },
34 locks::RwLock as StdRwLock,
35 timer,
36};
37#[cfg(feature = "experimental-encrypted-state-events")]
38use ruma::events::{AnyStateEventContent, StateEventContent};
39use ruma::{
40 DeviceId, DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch, OneTimeKeyAlgorithm, OwnedDeviceId,
41 OwnedDeviceKeyId, OwnedTransactionId, OwnedUserId, RoomId, TransactionId, UInt, UserId,
42 api::client::{
43 dehydrated_device::DehydratedDeviceData,
44 keys::{
45 claim_keys::v3::Request as KeysClaimRequest,
46 get_keys::v3::Response as KeysQueryResponse,
47 upload_keys::v3::{Request as UploadKeysRequest, Response as UploadKeysResponse},
48 upload_signatures::v3::Request as UploadSignaturesRequest,
49 },
50 sync::sync_events::DeviceLists,
51 },
52 assign,
53 events::{
54 AnyMessageLikeEvent, AnyMessageLikeEventContent, AnyTimelineEvent, AnyToDeviceEvent,
55 MessageLikeEventContent, secret::request::SecretName,
56 },
57 serde::{JsonObject, Raw},
58};
59use serde::Serialize;
60use serde_json::{Value, value::to_raw_value};
61use tokio::sync::Mutex;
62use tracing::{
63 Span, debug, enabled, error,
64 field::{debug, display},
65 info, instrument, trace, warn,
66};
67use vodozemac::{Curve25519PublicKey, Ed25519Signature, megolm::DecryptionError};
68
69#[cfg(feature = "experimental-push-secrets")]
70use crate::error::SecretPushError;
71#[cfg(feature = "experimental-send-custom-to-device")]
72use crate::session_manager::split_devices_for_share_strategy;
73use crate::{
74 CollectStrategy, CryptoStoreError, DecryptionSettings, DeviceData, LocalTrust,
75 RoomEventDecryptionResult, SignatureError, TrustRequirement,
76 backups::{BackupMachine, MegolmV1BackupKey},
77 dehydrated_devices::{DehydratedDevices, DehydrationError},
78 error::{EventError, MegolmError, MegolmResult, OlmError, OlmResult, SetRoomSettingsError},
79 gossiping::GossipMachine,
80 identities::{Device, IdentityManager, UserDevices, user::UserIdentity},
81 olm::{
82 Account, CrossSigningStatus, EncryptionSettings, IdentityKeys, InboundGroupSession,
83 KnownSenderData, OlmDecryptionInfo, PrivateCrossSigningIdentity, SenderData,
84 SenderDataFinder, SessionType, StaticAccountData,
85 },
86 session_manager::{GroupSessionManager, SessionManager},
87 store::{
88 CryptoStoreWrapper, IntoCryptoStore, MemoryStore, Result as StoreResult, SecretImportError,
89 Store, StoreTransaction,
90 caches::StoreCache,
91 types::{
92 Changes, CrossSigningKeyExport, DeviceChanges, IdentityChanges, PendingChanges,
93 RoomKeyInfo, RoomSettings, StoredRoomKeyBundleData,
94 },
95 },
96 types::{
97 EventEncryptionAlgorithm, Signatures,
98 events::{
99 ToDeviceEvent, ToDeviceEvents,
100 olm_v1::{AnyDecryptedOlmEvent, DecryptedRoomKeyBundleEvent, DecryptedRoomKeyEvent},
101 room::encrypted::{
102 EncryptedEvent, EncryptedToDeviceEvent, RoomEncryptedEventContent,
103 RoomEventEncryptionScheme, SupportedEventEncryptionSchemes,
104 ToDeviceEncryptedEventContent,
105 },
106 room_key::{MegolmV1AesSha2Content, RoomKeyContent},
107 room_key_bundle::RoomKeyBundleContent,
108 room_key_withheld::{
109 MegolmV1AesSha2WithheldContent, RoomKeyWithheldContent, RoomKeyWithheldEvent,
110 },
111 },
112 requests::{
113 AnyIncomingResponse, KeysQueryRequest, OutgoingRequest, ToDeviceRequest,
114 UploadSigningKeysRequest,
115 },
116 },
117 utilities::timestamp_to_iso8601,
118 verification::{Verification, VerificationMachine, VerificationRequest},
119};
120
121#[derive(Debug, Serialize)]
122pub struct RawEncryptionResult {
124 pub content: Raw<RoomEncryptedEventContent>,
126 pub encryption_info: EncryptionInfo,
128}
129
130#[derive(Clone)]
133pub struct OlmMachine {
134 pub(crate) inner: Arc<OlmMachineInner>,
135}
136
137pub struct OlmMachineInner {
138 user_id: OwnedUserId,
140 device_id: OwnedDeviceId,
142 user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
147 store: Store,
151 session_manager: SessionManager,
153 pub(crate) group_session_manager: GroupSessionManager,
155 verification_machine: VerificationMachine,
158 pub(crate) key_request_machine: GossipMachine,
161 identity_manager: IdentityManager,
164 backup_machine: BackupMachine,
166}
167
168#[cfg(not(tarpaulin_include))]
169impl std::fmt::Debug for OlmMachine {
170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 f.debug_struct("OlmMachine")
172 .field("user_id", &self.user_id())
173 .field("device_id", &self.device_id())
174 .finish()
175 }
176}
177
178impl OlmMachine {
179 const HAS_MIGRATED_VERIFICATION_LATCH: &'static str = "HAS_MIGRATED_VERIFICATION_LATCH";
180
181 pub async fn new(user_id: &UserId, device_id: &DeviceId) -> Self {
192 OlmMachine::with_store(user_id, device_id, MemoryStore::new(), None)
193 .await
194 .expect("Reading and writing to the memory store always succeeds")
195 }
196
197 pub(crate) async fn rehydrate(
198 &self,
199 pickle_key: &[u8; 32],
200 device_id: &DeviceId,
201 device_data: Raw<DehydratedDeviceData>,
202 ) -> Result<OlmMachine, DehydrationError> {
203 let account = Account::rehydrate(pickle_key, self.user_id(), device_id, device_data)?;
204 let static_account = account.static_data().clone();
205
206 let store =
207 Arc::new(CryptoStoreWrapper::new(self.user_id(), device_id, MemoryStore::new()));
208 let device = DeviceData::from_account(&account);
209 store.save_pending_changes(PendingChanges { account: Some(account) }).await?;
210 store
211 .save_changes(Changes {
212 devices: DeviceChanges { new: vec![device], ..Default::default() },
213 ..Default::default()
214 })
215 .await?;
216
217 let (verification_machine, store, identity_manager) =
218 Self::new_helper_prelude(store, static_account, self.store().private_identity());
219
220 Ok(Self::new_helper(
221 device_id,
222 store,
223 verification_machine,
224 identity_manager,
225 self.store().private_identity(),
226 None,
227 ))
228 }
229
230 fn new_helper_prelude(
231 store_wrapper: Arc<CryptoStoreWrapper>,
232 account: StaticAccountData,
233 user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
234 ) -> (VerificationMachine, Store, IdentityManager) {
235 let verification_machine =
236 VerificationMachine::new(account.clone(), user_identity.clone(), store_wrapper.clone());
237 let store = Store::new(account, user_identity, store_wrapper, verification_machine.clone());
238
239 let identity_manager = IdentityManager::new(store.clone());
240
241 (verification_machine, store, identity_manager)
242 }
243
244 fn new_helper(
245 device_id: &DeviceId,
246 store: Store,
247 verification_machine: VerificationMachine,
248 identity_manager: IdentityManager,
249 user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
250 maybe_backup_key: Option<MegolmV1BackupKey>,
251 ) -> Self {
252 let group_session_manager = GroupSessionManager::new(store.clone());
253
254 let users_for_key_claim = Arc::new(StdRwLock::new(BTreeMap::new()));
255 let key_request_machine = GossipMachine::new(
256 store.clone(),
257 identity_manager.clone(),
258 group_session_manager.session_cache(),
259 users_for_key_claim.clone(),
260 );
261
262 let session_manager =
263 SessionManager::new(users_for_key_claim, key_request_machine.clone(), store.clone());
264
265 let backup_machine = BackupMachine::new(store.clone(), maybe_backup_key);
266
267 let inner = Arc::new(OlmMachineInner {
268 user_id: store.user_id().to_owned(),
269 device_id: device_id.to_owned(),
270 user_identity,
271 store,
272 session_manager,
273 group_session_manager,
274 verification_machine,
275 key_request_machine,
276 identity_manager,
277 backup_machine,
278 });
279
280 Self { inner }
281 }
282
283 #[instrument(skip(store, custom_account), fields(ed25519_key, curve25519_key))]
308 pub async fn with_store(
309 user_id: &UserId,
310 device_id: &DeviceId,
311 store: impl IntoCryptoStore,
312 custom_account: Option<vodozemac::olm::Account>,
313 ) -> StoreResult<Self> {
314 let store = store.into_crypto_store();
315
316 let static_account = match store.load_account().await? {
317 Some(account) => {
318 if user_id != account.user_id()
319 || device_id != account.device_id()
320 || custom_account.is_some()
321 {
322 return Err(CryptoStoreError::MismatchedAccount {
323 expected: (account.user_id().to_owned(), account.device_id().to_owned()),
324 got: (user_id.to_owned(), device_id.to_owned()),
325 });
326 }
327
328 Span::current()
329 .record("ed25519_key", display(account.identity_keys().ed25519))
330 .record("curve25519_key", display(account.identity_keys().curve25519));
331 debug!("Restored an Olm account");
332
333 account.static_data().clone()
334 }
335
336 None => {
337 let account = if let Some(account) = custom_account {
338 Account::new_helper(account, user_id, device_id)
339 } else {
340 Account::with_device_id(user_id, device_id)
341 };
342
343 let static_account = account.static_data().clone();
344
345 Span::current()
346 .record("ed25519_key", display(account.identity_keys().ed25519))
347 .record("curve25519_key", display(account.identity_keys().curve25519));
348
349 let device = DeviceData::from_account(&account);
350
351 device.set_trust_state(LocalTrust::Verified);
355
356 let changes = Changes {
357 devices: DeviceChanges { new: vec![device], ..Default::default() },
358 ..Default::default()
359 };
360 store.save_changes(changes).await?;
361 store.save_pending_changes(PendingChanges { account: Some(account) }).await?;
362
363 debug!("Created a new Olm account");
364
365 static_account
366 }
367 };
368
369 let identity = match store.load_identity().await? {
370 Some(i) => {
371 let master_key = i
372 .master_public_key()
373 .await
374 .and_then(|m| m.get_first_key().map(|m| m.to_owned()));
375 debug!(?master_key, "Restored the cross signing identity");
376 i
377 }
378 None => {
379 debug!("Creating an empty cross signing identity stub");
380 PrivateCrossSigningIdentity::empty(user_id)
381 }
382 };
383
384 let saved_keys = store.load_backup_keys().await?;
389 let maybe_backup_key = saved_keys.decryption_key.and_then(|k| {
390 if let Some(version) = saved_keys.backup_version {
391 let megolm_v1_backup_key = k.megolm_v1_public_key();
392 megolm_v1_backup_key.set_version(version);
393 Some(megolm_v1_backup_key)
394 } else {
395 None
396 }
397 });
398
399 let identity = Arc::new(Mutex::new(identity));
400 let store = Arc::new(CryptoStoreWrapper::new(user_id, device_id, store));
401
402 let (verification_machine, store, identity_manager) =
403 Self::new_helper_prelude(store, static_account, identity.clone());
404
405 Self::migration_post_verified_latch_support(&store, &identity_manager).await?;
408
409 Ok(Self::new_helper(
410 device_id,
411 store,
412 verification_machine,
413 identity_manager,
414 identity,
415 maybe_backup_key,
416 ))
417 }
418
419 pub(crate) async fn migration_post_verified_latch_support(
427 store: &Store,
428 identity_manager: &IdentityManager,
429 ) -> Result<(), CryptoStoreError> {
430 let maybe_migrate_for_identity_verified_latch =
431 store.get_custom_value(Self::HAS_MIGRATED_VERIFICATION_LATCH).await?.is_none();
432
433 if maybe_migrate_for_identity_verified_latch {
434 identity_manager.mark_all_tracked_users_as_dirty(store.cache().await?).await?;
435
436 store.set_custom_value(Self::HAS_MIGRATED_VERIFICATION_LATCH, vec![0]).await?
437 }
438 Ok(())
439 }
440
441 pub fn store(&self) -> &Store {
443 &self.inner.store
444 }
445
446 pub fn user_id(&self) -> &UserId {
448 &self.inner.user_id
449 }
450
451 pub fn device_id(&self) -> &DeviceId {
453 &self.inner.device_id
454 }
455
456 pub fn device_creation_time(&self) -> MilliSecondsSinceUnixEpoch {
463 self.inner.store.static_account().creation_local_time()
464 }
465
466 pub fn identity_keys(&self) -> IdentityKeys {
468 let account = self.inner.store.static_account();
469 account.identity_keys()
470 }
471
472 pub async fn display_name(&self) -> StoreResult<Option<String>> {
474 self.store().device_display_name().await
475 }
476
477 pub async fn tracked_users(&self) -> StoreResult<HashSet<OwnedUserId>> {
482 let cache = self.store().cache().await?;
483 Ok(self.inner.identity_manager.key_query_manager.synced(&cache).await?.tracked_users())
484 }
485
486 #[cfg(feature = "automatic-room-key-forwarding")]
495 pub fn set_room_key_requests_enabled(&self, enable: bool) {
496 self.inner.key_request_machine.set_room_key_requests_enabled(enable)
497 }
498
499 pub fn are_room_key_requests_enabled(&self) -> bool {
504 self.inner.key_request_machine.are_room_key_requests_enabled()
505 }
506
507 #[cfg(feature = "automatic-room-key-forwarding")]
516 pub fn set_room_key_forwarding_enabled(&self, enable: bool) {
517 self.inner.key_request_machine.set_room_key_forwarding_enabled(enable)
518 }
519
520 pub fn is_room_key_forwarding_enabled(&self) -> bool {
524 self.inner.key_request_machine.is_room_key_forwarding_enabled()
525 }
526
527 pub async fn outgoing_requests(&self) -> StoreResult<Vec<OutgoingRequest>> {
535 let mut requests = Vec::new();
536
537 {
538 let store_cache = self.inner.store.cache().await?;
539 let account = store_cache.account().await?;
540 if let Some(r) = self.keys_for_upload(&account).await.map(|r| OutgoingRequest {
541 request_id: TransactionId::new(),
542 request: Arc::new(r.into()),
543 }) {
544 requests.push(r);
545 }
546 }
547
548 for request in self
549 .inner
550 .identity_manager
551 .users_for_key_query()
552 .await?
553 .into_iter()
554 .map(|(request_id, r)| OutgoingRequest { request_id, request: Arc::new(r.into()) })
555 {
556 requests.push(request);
557 }
558
559 requests.append(&mut self.inner.verification_machine.outgoing_messages());
560 requests.append(&mut self.inner.key_request_machine.outgoing_to_device_requests().await?);
561
562 Ok(requests)
563 }
564
565 pub fn query_keys_for_users<'a>(
586 &self,
587 users: impl IntoIterator<Item = &'a UserId>,
588 ) -> (OwnedTransactionId, KeysQueryRequest) {
589 self.inner.identity_manager.build_key_query_for_users(users)
590 }
591
592 pub async fn mark_request_as_sent<'a>(
602 &self,
603 request_id: &TransactionId,
604 response: impl Into<AnyIncomingResponse<'a>>,
605 ) -> OlmResult<()> {
606 match response.into() {
607 AnyIncomingResponse::KeysUpload(response) => {
608 Box::pin(self.receive_keys_upload_response(response)).await?;
609 }
610 AnyIncomingResponse::KeysQuery(response) => {
611 Box::pin(self.receive_keys_query_response(request_id, response)).await?;
612 }
613 AnyIncomingResponse::KeysClaim(response) => {
614 Box::pin(
615 self.inner.session_manager.receive_keys_claim_response(request_id, response),
616 )
617 .await?;
618 }
619 AnyIncomingResponse::ToDevice(_) => {
620 Box::pin(self.mark_to_device_request_as_sent(request_id)).await?;
621 }
622 AnyIncomingResponse::SigningKeysUpload(_) => {
623 Box::pin(self.receive_cross_signing_upload_response()).await?;
624 }
625 AnyIncomingResponse::SignatureUpload(_) => {
626 self.inner.verification_machine.mark_request_as_sent(request_id);
627 }
628 AnyIncomingResponse::RoomMessage(_) => {
629 self.inner.verification_machine.mark_request_as_sent(request_id);
630 }
631 AnyIncomingResponse::KeysBackup(_) => {
632 Box::pin(self.inner.backup_machine.mark_request_as_sent(request_id)).await?;
633 }
634 }
635
636 Ok(())
637 }
638
639 async fn receive_cross_signing_upload_response(&self) -> StoreResult<()> {
641 let identity = self.inner.user_identity.lock().await;
642 identity.mark_as_shared();
643
644 let changes = Changes { private_identity: Some(identity.clone()), ..Default::default() };
645
646 self.store().save_changes(changes).await
647 }
648
649 pub async fn bootstrap_cross_signing(
668 &self,
669 reset: bool,
670 ) -> StoreResult<CrossSigningBootstrapRequests> {
671 let identity = self.inner.user_identity.lock().await.clone();
676
677 let (upload_signing_keys_req, upload_signatures_req) = if reset || identity.is_empty().await
678 {
679 info!("Creating new cross signing identity");
680
681 let (identity, upload_signing_keys_req, upload_signatures_req) = {
682 let cache = self.inner.store.cache().await?;
683 let account = cache.account().await?;
684 account.bootstrap_cross_signing().await
685 };
686
687 let public = identity.to_public_identity().await.expect(
688 "Couldn't create a public version of the identity from a new private identity",
689 );
690
691 *self.inner.user_identity.lock().await = identity.clone();
692
693 self.store()
694 .save_changes(Changes {
695 identities: IdentityChanges { new: vec![public.into()], ..Default::default() },
696 private_identity: Some(identity),
697 ..Default::default()
698 })
699 .await?;
700
701 (upload_signing_keys_req, upload_signatures_req)
702 } else {
703 info!("Trying to upload the existing cross signing identity");
704 let upload_signing_keys_req = identity.as_upload_request().await;
705
706 let upload_signatures_req = identity
708 .sign_account(self.inner.store.static_account())
709 .await
710 .expect("Can't sign device keys");
711
712 (upload_signing_keys_req, upload_signatures_req)
713 };
714
715 let upload_keys_req =
719 self.upload_device_keys().await?.map(|(_, request)| OutgoingRequest::from(request));
720
721 Ok(CrossSigningBootstrapRequests {
722 upload_signing_keys_req,
723 upload_keys_req,
724 upload_signatures_req,
725 })
726 }
727
728 pub async fn upload_device_keys(
740 &self,
741 ) -> StoreResult<Option<(OwnedTransactionId, UploadKeysRequest)>> {
742 let cache = self.store().cache().await?;
743 let account = cache.account().await?;
744
745 Ok(self.keys_for_upload(&account).await.map(|request| (TransactionId::new(), request)))
746 }
747
748 async fn receive_keys_upload_response(&self, response: &UploadKeysResponse) -> OlmResult<()> {
755 self.inner
756 .store
757 .with_transaction(async |tr| {
758 let account = tr.account().await?;
759 account.receive_keys_upload_response(response)?;
760 Ok(())
761 })
762 .await
763 }
764
765 #[instrument(skip_all)]
793 pub async fn get_missing_sessions(
794 &self,
795 users: impl Iterator<Item = &UserId>,
796 ) -> StoreResult<Option<(OwnedTransactionId, KeysClaimRequest)>> {
797 self.inner.session_manager.get_missing_sessions(users).await
798 }
799
800 async fn receive_keys_query_response(
809 &self,
810 request_id: &TransactionId,
811 response: &KeysQueryResponse,
812 ) -> OlmResult<(DeviceChanges, IdentityChanges)> {
813 self.inner.identity_manager.receive_keys_query_response(request_id, response).await
814 }
815
816 async fn keys_for_upload(&self, account: &Account) -> Option<UploadKeysRequest> {
825 let (mut device_keys, one_time_keys, fallback_keys) = account.keys_for_upload();
826
827 if let Some(device_keys) = &mut device_keys {
837 let private_identity = self.store().private_identity();
838 let guard = private_identity.lock().await;
839
840 if guard.status().await.is_complete() {
841 guard.sign_device_keys(device_keys).await.expect(
842 "We should be able to sign our device keys since we confirmed that we \
843 have a complete set of private cross-signing keys",
844 );
845 }
846 }
847
848 if device_keys.is_none() && one_time_keys.is_empty() && fallback_keys.is_empty() {
849 None
850 } else {
851 let device_keys = device_keys.map(|d| d.to_raw());
852
853 Some(assign!(UploadKeysRequest::new(), {
854 device_keys, one_time_keys, fallback_keys
855 }))
856 }
857 }
858
859 async fn decrypt_to_device_event(
882 &self,
883 transaction: &mut StoreTransaction,
884 event: &EncryptedToDeviceEvent,
885 changes: &mut Changes,
886 decryption_settings: &DecryptionSettings,
887 ) -> Result<OlmDecryptionInfo, DecryptToDeviceError> {
888 let mut decrypted = transaction
890 .account()
891 .await?
892 .decrypt_to_device_event(&self.inner.store, event, decryption_settings)
893 .await?;
894
895 self.check_to_device_event_is_not_from_dehydrated_device(&decrypted, &event.sender).await?;
897
898 self.handle_decrypted_to_device_event(transaction.cache(), &mut decrypted, changes).await?;
900
901 Ok(decrypted)
902 }
903
904 #[instrument(
905 skip_all,
906 fields(room_id = ? content.room_id, session_id, message_index, shared_history = content.shared_history)
910 )]
911 async fn handle_key(
912 &self,
913 sender_key: Curve25519PublicKey,
914 event: &DecryptedRoomKeyEvent,
915 content: &MegolmV1AesSha2Content,
916 ) -> OlmResult<Option<InboundGroupSession>> {
917 let session =
918 InboundGroupSession::from_room_key_content(sender_key, event.keys.ed25519, content);
919
920 match session {
921 Ok(mut session) => {
922 Span::current().record("session_id", session.session_id());
923 Span::current().record("message_index", session.first_known_index());
924
925 let sender_data =
926 SenderDataFinder::find_using_event(self.store(), sender_key, event, &session)
927 .await?;
928 session.sender_data = sender_data;
929
930 Ok(self.store().merge_received_group_session(session).await?)
931 }
932 Err(e) => {
933 Span::current().record("session_id", &content.session_id);
934 warn!("Received a room key event which contained an invalid session key: {e}");
935
936 Ok(None)
937 }
938 }
939 }
940
941 #[instrument(skip_all, fields(algorithm = ?event.content.algorithm()))]
943 async fn add_room_key(
944 &self,
945 sender_key: Curve25519PublicKey,
946 event: &DecryptedRoomKeyEvent,
947 ) -> OlmResult<Option<InboundGroupSession>> {
948 match &event.content {
949 RoomKeyContent::MegolmV1AesSha2(content) => {
950 self.handle_key(sender_key, event, content).await
951 }
952 #[cfg(feature = "experimental-algorithms")]
953 RoomKeyContent::MegolmV2AesSha2(content) => {
954 self.handle_key(sender_key, event, content).await
955 }
956 RoomKeyContent::Unknown(_) => {
957 warn!("Received a room key with an unsupported algorithm");
958 Ok(None)
959 }
960 }
961 }
962
963 #[instrument()]
966 async fn receive_room_key_bundle_data(
967 &self,
968 sender_key: Curve25519PublicKey,
969 event: &DecryptedRoomKeyBundleEvent,
970 changes: &mut Changes,
971 ) -> OlmResult<()> {
972 let Some(sender_device_keys) = &event.sender_device_keys else {
973 warn!("Received a room key bundle with no sender device keys: ignoring");
974 return Ok(());
975 };
976
977 let sender_device_data =
982 DeviceData::try_from(sender_device_keys).expect("failed to verify sender device keys");
983 let sender_device = self.store().wrap_device_data(sender_device_data).await?;
984
985 changes.received_room_key_bundles.push(StoredRoomKeyBundleData {
986 sender_user: event.sender.clone(),
987 sender_data: SenderData::from_device(&sender_device),
988 sender_key,
989 bundle_data: event.content.clone(),
990 });
991 Ok(())
992 }
993
994 fn add_withheld_info(&self, changes: &mut Changes, event: &RoomKeyWithheldEvent) {
995 debug!(?event.content, "Processing `m.room_key.withheld` event");
996
997 if let RoomKeyWithheldContent::MegolmV1AesSha2(
998 MegolmV1AesSha2WithheldContent::BlackListed(c)
999 | MegolmV1AesSha2WithheldContent::Unverified(c)
1000 | MegolmV1AesSha2WithheldContent::Unauthorised(c)
1001 | MegolmV1AesSha2WithheldContent::Unavailable(c),
1002 ) = &event.content
1003 {
1004 changes
1005 .withheld_session_info
1006 .entry(c.room_id.to_owned())
1007 .or_default()
1008 .insert(c.session_id.to_owned(), event.to_owned().into());
1009 }
1010 }
1011
1012 #[cfg(test)]
1013 pub(crate) async fn create_outbound_group_session_with_defaults_test_helper(
1014 &self,
1015 room_id: &RoomId,
1016 ) -> OlmResult<()> {
1017 let (_, session) = self
1018 .inner
1019 .group_session_manager
1020 .create_outbound_group_session(
1021 room_id,
1022 EncryptionSettings::default(),
1023 SenderData::unknown(),
1024 )
1025 .await?;
1026
1027 self.store().save_inbound_group_sessions(&[session]).await?;
1028
1029 Ok(())
1030 }
1031
1032 #[cfg(test)]
1033 #[allow(dead_code)]
1034 pub(crate) async fn create_inbound_session_test_helper(
1035 &self,
1036 room_id: &RoomId,
1037 ) -> OlmResult<InboundGroupSession> {
1038 let (_, session) = self
1039 .inner
1040 .group_session_manager
1041 .create_outbound_group_session(
1042 room_id,
1043 EncryptionSettings::default(),
1044 SenderData::unknown(),
1045 )
1046 .await?;
1047
1048 Ok(session)
1049 }
1050
1051 pub async fn encrypt_room_event(
1068 &self,
1069 room_id: &RoomId,
1070 content: impl MessageLikeEventContent,
1071 ) -> MegolmResult<RawEncryptionResult> {
1072 let event_type = content.event_type().to_string();
1073 let content = Raw::new(&content)?.cast_unchecked();
1074 self.encrypt_room_event_raw(room_id, &event_type, &content).await
1075 }
1076
1077 pub async fn encrypt_room_event_raw(
1097 &self,
1098 room_id: &RoomId,
1099 event_type: &str,
1100 content: &Raw<AnyMessageLikeEventContent>,
1101 ) -> MegolmResult<RawEncryptionResult> {
1102 self.inner.group_session_manager.encrypt(room_id, event_type, content).await.map(|result| {
1103 RawEncryptionResult {
1104 content: result.content,
1105 encryption_info: self
1106 .own_encryption_info(result.algorithm, result.session_id.to_string()),
1107 }
1108 })
1109 }
1110
1111 fn own_encryption_info(
1112 &self,
1113 algorithm: EventEncryptionAlgorithm,
1114 session_id: String,
1115 ) -> EncryptionInfo {
1116 let identity_keys = self.identity_keys();
1117
1118 let algorithm_info = match algorithm {
1119 EventEncryptionAlgorithm::MegolmV1AesSha2 => AlgorithmInfo::MegolmV1AesSha2 {
1120 curve25519_key: identity_keys.curve25519.to_base64(),
1121 sender_claimed_keys: BTreeMap::from([(
1122 DeviceKeyAlgorithm::Ed25519,
1123 identity_keys.ed25519.to_base64(),
1124 )]),
1125 session_id: Some(session_id),
1126 },
1127 EventEncryptionAlgorithm::OlmV1Curve25519AesSha2 => {
1128 AlgorithmInfo::OlmV1Curve25519AesSha2 {
1129 curve25519_public_key_base64: identity_keys.curve25519.to_base64(),
1130 }
1131 }
1132 _ => unreachable!(
1133 "Only MegolmV1AesSha2 and OlmV1Curve25519AesSha2 are supported on this level"
1134 ),
1135 };
1136
1137 EncryptionInfo {
1138 sender: self.inner.user_id.clone(),
1139 sender_device: Some(self.inner.device_id.clone()),
1140 forwarder: None,
1141 algorithm_info,
1142 verification_state: VerificationState::Verified,
1143 }
1144 }
1145
1146 #[cfg(feature = "experimental-encrypted-state-events")]
1158 pub async fn encrypt_state_event<C, K>(
1159 &self,
1160 room_id: &RoomId,
1161 content: C,
1162 state_key: K,
1163 ) -> MegolmResult<Raw<RoomEncryptedEventContent>>
1164 where
1165 C: StateEventContent,
1166 C::StateKey: Borrow<K>,
1167 K: AsRef<str>,
1168 {
1169 let event_type = content.event_type().to_string();
1170 let content = Raw::new(&content)?.cast_unchecked();
1171 self.encrypt_state_event_raw(room_id, &event_type, state_key.as_ref(), &content).await
1172 }
1173
1174 #[cfg(feature = "experimental-encrypted-state-events")]
1193 pub async fn encrypt_state_event_raw(
1194 &self,
1195 room_id: &RoomId,
1196 event_type: &str,
1197 state_key: &str,
1198 content: &Raw<AnyStateEventContent>,
1199 ) -> MegolmResult<Raw<RoomEncryptedEventContent>> {
1200 self.inner
1201 .group_session_manager
1202 .encrypt_state(room_id, event_type, state_key, content)
1203 .await
1204 }
1205
1206 pub async fn discard_room_key(&self, room_id: &RoomId) -> StoreResult<bool> {
1217 self.inner.group_session_manager.invalidate_group_session(room_id).await
1218 }
1219
1220 pub async fn share_room_key(
1240 &self,
1241 room_id: &RoomId,
1242 users: impl Iterator<Item = &UserId>,
1243 encryption_settings: impl Into<EncryptionSettings>,
1244 ) -> OlmResult<Vec<Arc<ToDeviceRequest>>> {
1245 self.inner.group_session_manager.share_room_key(room_id, users, encryption_settings).await
1246 }
1247
1248 #[cfg(feature = "experimental-send-custom-to-device")]
1262 pub async fn encrypt_content_for_devices(
1263 &self,
1264 devices: Vec<DeviceData>,
1265 event_type: &str,
1266 content: &Value,
1267 share_strategy: CollectStrategy,
1268 ) -> OlmResult<(Vec<ToDeviceRequest>, Vec<(DeviceData, WithheldCode)>)> {
1269 let mut changes = Changes::default();
1270
1271 let (allowed_devices, mut blocked_devices) =
1272 split_devices_for_share_strategy(&self.inner.store, devices, share_strategy).await?;
1273
1274 let result = self
1275 .inner
1276 .group_session_manager
1277 .encrypt_content_for_devices(allowed_devices, event_type, content.clone(), &mut changes)
1278 .await;
1279
1280 if !changes.is_empty() {
1282 let session_count = changes.sessions.len();
1283
1284 self.inner.store.save_changes(changes).await?;
1285
1286 trace!(
1287 session_count = session_count,
1288 "Stored the changed sessions after encrypting a custom to-device event"
1289 );
1290 }
1291
1292 result.map(|(to_device_requests, mut withheld)| {
1293 withheld.append(&mut blocked_devices);
1294 (to_device_requests, withheld)
1295 })
1296 }
1297 pub async fn share_room_key_bundle_data(
1302 &self,
1303 user_id: &UserId,
1304 collect_strategy: &CollectStrategy,
1305 bundle_data: RoomKeyBundleContent,
1306 ) -> OlmResult<Vec<ToDeviceRequest>> {
1307 self.inner
1308 .group_session_manager
1309 .share_room_key_bundle_data(user_id, collect_strategy, bundle_data)
1310 .await
1311 }
1312
1313 #[deprecated(note = "Use OlmMachine::receive_verification_event instead", since = "0.7.0")]
1321 pub async fn receive_unencrypted_verification_event(
1322 &self,
1323 event: &AnyMessageLikeEvent,
1324 ) -> StoreResult<()> {
1325 self.inner.verification_machine.receive_any_event(event).await
1326 }
1327
1328 pub async fn receive_verification_event(&self, event: &AnyMessageLikeEvent) -> StoreResult<()> {
1341 self.inner.verification_machine.receive_any_event(event).await
1342 }
1343
1344 #[instrument(
1350 skip_all,
1351 fields(
1352 sender_key = ?decrypted.result.sender_key,
1353 event_type = decrypted.result.event.event_type(),
1354 ),
1355 )]
1356 async fn handle_decrypted_to_device_event(
1357 &self,
1358 cache: &StoreCache,
1359 decrypted: &mut OlmDecryptionInfo,
1360 changes: &mut Changes,
1361 ) -> OlmResult<()> {
1362 debug!(
1363 sender_device_keys =
1364 ?decrypted.result.event.sender_device_keys().map(|k| (k.curve25519_key(), k.ed25519_key())).unwrap_or((None, None)),
1365 "Received a decrypted to-device event",
1366 );
1367
1368 match &*decrypted.result.event {
1369 AnyDecryptedOlmEvent::RoomKey(e) => {
1370 let session = self.add_room_key(decrypted.result.sender_key, e).await?;
1371 decrypted.inbound_group_session = session;
1372 }
1373 AnyDecryptedOlmEvent::ForwardedRoomKey(e) => {
1374 let session = self
1375 .inner
1376 .key_request_machine
1377 .receive_forwarded_room_key(decrypted.result.sender_key, e)
1378 .await?;
1379 decrypted.inbound_group_session = session;
1380 }
1381 AnyDecryptedOlmEvent::SecretSend(e) => {
1382 let name = self
1383 .inner
1384 .key_request_machine
1385 .receive_secret_event(cache, decrypted.result.sender_key, e, changes)
1386 .await?;
1387
1388 if let Ok(ToDeviceEvents::SecretSend(mut e)) =
1391 decrypted.result.raw_event.deserialize_as()
1392 {
1393 e.content.secret_name = name;
1394 decrypted.result.raw_event = Raw::from_json(to_raw_value(&e)?);
1395 }
1396
1397 if enabled!(tracing::Level::DEBUG) {
1398 let cross_signing_status = self.cross_signing_status().await;
1399 let backup_enabled = self.backup_machine().enabled().await;
1400 debug!(
1401 ?cross_signing_status,
1402 backup_enabled, "Status after receiving secret event"
1403 );
1404 }
1405 }
1406 AnyDecryptedOlmEvent::Dummy(_) => {
1407 debug!("Received an `m.dummy` event");
1408 }
1409 AnyDecryptedOlmEvent::RoomKeyBundle(e) => {
1410 debug!("Received a room key bundle event {:?}", e);
1411 self.receive_room_key_bundle_data(decrypted.result.sender_key, e, changes).await?;
1412 }
1413 #[cfg(feature = "experimental-push-secrets")]
1414 AnyDecryptedOlmEvent::SecretPush(e) => {
1415 self.inner
1416 .key_request_machine
1417 .receive_secret_push_event(&decrypted.result.sender_key, e, changes)
1418 .await?;
1419 }
1420 AnyDecryptedOlmEvent::Custom(_) => {
1421 warn!("Received an unexpected encrypted to-device event");
1422 }
1423 }
1424
1425 Ok(())
1426 }
1427
1428 async fn handle_verification_event(&self, event: &ToDeviceEvents) {
1429 if let Err(e) = self.inner.verification_machine.receive_any_event(event).await {
1430 error!("Error handling a verification event: {e:?}");
1431 }
1432 }
1433
1434 async fn mark_to_device_request_as_sent(&self, request_id: &TransactionId) -> StoreResult<()> {
1436 self.inner.verification_machine.mark_request_as_sent(request_id);
1437 self.inner.key_request_machine.mark_outgoing_request_as_sent(request_id).await?;
1438 self.inner.group_session_manager.mark_request_as_sent(request_id).await?;
1439 self.inner.session_manager.mark_outgoing_request_as_sent(request_id);
1440 Ok(())
1441 }
1442
1443 pub fn get_verification(&self, user_id: &UserId, flow_id: &str) -> Option<Verification> {
1445 self.inner.verification_machine.get_verification(user_id, flow_id)
1446 }
1447
1448 pub fn get_verification_request(
1450 &self,
1451 user_id: &UserId,
1452 flow_id: impl AsRef<str>,
1453 ) -> Option<VerificationRequest> {
1454 self.inner.verification_machine.get_request(user_id, flow_id)
1455 }
1456
1457 pub fn get_verification_requests(&self, user_id: &UserId) -> Vec<VerificationRequest> {
1459 self.inner.verification_machine.get_requests(user_id)
1460 }
1461
1462 async fn handle_to_device_event(&self, changes: &mut Changes, event: &ToDeviceEvents) {
1467 use crate::types::events::ToDeviceEvents::*;
1468
1469 match event {
1470 RoomKeyRequest(e) => self.inner.key_request_machine.receive_incoming_key_request(e),
1476 SecretRequest(e) => self.inner.key_request_machine.receive_incoming_secret_request(e),
1477 RoomKeyWithheld(e) => self.add_withheld_info(changes, e),
1478 KeyVerificationAccept(..)
1479 | KeyVerificationCancel(..)
1480 | KeyVerificationKey(..)
1481 | KeyVerificationMac(..)
1482 | KeyVerificationRequest(..)
1483 | KeyVerificationReady(..)
1484 | KeyVerificationDone(..)
1485 | KeyVerificationStart(..) => {
1486 self.handle_verification_event(event).await;
1487 }
1488
1489 Custom(_) | Dummy(_) => {}
1491
1492 RoomEncrypted(_) => {}
1494
1495 SecretSend(_) | RoomKey(_) | ForwardedRoomKey(_) => {}
1498 }
1499 }
1500
1501 fn record_message_id(event: &Raw<AnyToDeviceEvent>) {
1502 use serde::Deserialize;
1503
1504 #[derive(Deserialize)]
1505 struct ContentStub<'a> {
1506 #[serde(borrow, rename = "org.matrix.msgid")]
1507 message_id: Option<&'a str>,
1508 }
1509 #[derive(Deserialize)]
1510 struct ToDeviceStub<'a> {
1511 sender: &'a str,
1512 #[serde(rename = "type")]
1513 event_type: &'a str,
1514 #[serde(borrow)]
1515 content: ContentStub<'a>,
1516 }
1517
1518 if let Ok(event) = event.deserialize_as_unchecked::<ToDeviceStub<'_>>() {
1519 Span::current().record("sender", event.sender);
1520 Span::current().record("event_type", event.event_type);
1521 Span::current().record("message_id", event.content.message_id);
1522 }
1523 }
1524
1525 #[instrument(skip_all, fields(sender, event_type, message_id))]
1533 async fn receive_to_device_event(
1534 &self,
1535 transaction: &mut StoreTransaction,
1536 changes: &mut Changes,
1537 raw_event: Raw<AnyToDeviceEvent>,
1538 decryption_settings: &DecryptionSettings,
1539 ) -> Option<ProcessedToDeviceEvent> {
1540 Self::record_message_id(&raw_event);
1541
1542 let event: ToDeviceEvents = match raw_event.deserialize_as() {
1543 Ok(e) => e,
1544 Err(e) => {
1545 warn!("Received an invalid to-device event: {e}");
1547 return Some(ProcessedToDeviceEvent::Invalid(raw_event));
1548 }
1549 };
1550
1551 debug!("Received a to-device event");
1552
1553 match event {
1554 ToDeviceEvents::RoomEncrypted(e) => {
1555 self.receive_encrypted_to_device_event(
1556 transaction,
1557 changes,
1558 raw_event,
1559 e,
1560 decryption_settings,
1561 )
1562 .await
1563 }
1564 e => {
1565 self.handle_to_device_event(changes, &e).await;
1566 Some(ProcessedToDeviceEvent::PlainText(raw_event))
1567 }
1568 }
1569 }
1570
1571 async fn receive_encrypted_to_device_event(
1585 &self,
1586 transaction: &mut StoreTransaction,
1587 changes: &mut Changes,
1588 mut raw_event: Raw<AnyToDeviceEvent>,
1589 e: ToDeviceEvent<ToDeviceEncryptedEventContent>,
1590 decryption_settings: &DecryptionSettings,
1591 ) -> Option<ProcessedToDeviceEvent> {
1592 let decrypted = match self
1593 .decrypt_to_device_event(transaction, &e, changes, decryption_settings)
1594 .await
1595 {
1596 Ok(decrypted) => decrypted,
1597 Err(DecryptToDeviceError::OlmError(err)) => {
1598 let reason = if let OlmError::UnverifiedSenderDevice = &err {
1599 ToDeviceUnableToDecryptReason::UnverifiedSenderDevice
1600 } else {
1601 ToDeviceUnableToDecryptReason::DecryptionFailure
1602 };
1603
1604 if let OlmError::SessionWedged(sender, curve_key) = err
1605 && let Err(e) =
1606 self.inner.session_manager.mark_device_as_wedged(&sender, curve_key).await
1607 {
1608 error!(
1609 error = ?e,
1610 "Couldn't mark device to be unwedged",
1611 );
1612 }
1613
1614 return Some(ProcessedToDeviceEvent::UnableToDecrypt {
1615 encrypted_event: raw_event,
1616 utd_info: ToDeviceUnableToDecryptInfo { reason },
1617 });
1618 }
1619 Err(DecryptToDeviceError::FromDehydratedDevice) => return None,
1620 };
1621
1622 match decrypted.session {
1625 SessionType::New(s) | SessionType::Existing(s) => {
1626 changes.sessions.push(s);
1627 }
1628 }
1629
1630 changes.message_hashes.push(decrypted.message_hash);
1631
1632 if let Some(group_session) = decrypted.inbound_group_session {
1633 changes.inbound_group_sessions.push(group_session);
1634 }
1635
1636 match decrypted.result.raw_event.deserialize_as() {
1637 Ok(event) => {
1638 self.handle_to_device_event(changes, &event).await;
1639
1640 raw_event = event
1641 .serialize_zeroized()
1642 .expect("Zeroizing and reserializing our events should always work")
1643 .cast();
1644 }
1645 Err(e) => {
1646 warn!("Received an invalid encrypted to-device event: {e}");
1647 raw_event = decrypted.result.raw_event;
1648 }
1649 }
1650
1651 Some(ProcessedToDeviceEvent::Decrypted {
1652 raw: raw_event,
1653 encryption_info: decrypted.result.encryption_info,
1654 })
1655 }
1656
1657 async fn check_to_device_event_is_not_from_dehydrated_device(
1660 &self,
1661 decrypted: &OlmDecryptionInfo,
1662 sender_user_id: &UserId,
1663 ) -> Result<(), DecryptToDeviceError> {
1664 if self.to_device_event_is_from_dehydrated_device(decrypted, sender_user_id).await? {
1665 warn!(
1666 sender = ?sender_user_id,
1667 session = ?decrypted.session,
1668 "Received a to-device event from a dehydrated device. This is unexpected: ignoring event"
1669 );
1670 Err(DecryptToDeviceError::FromDehydratedDevice)
1671 } else {
1672 Ok(())
1673 }
1674 }
1675
1676 async fn to_device_event_is_from_dehydrated_device(
1682 &self,
1683 decrypted: &OlmDecryptionInfo,
1684 sender_user_id: &UserId,
1685 ) -> OlmResult<bool> {
1686 if let Some(device_keys) = decrypted.result.event.sender_device_keys() {
1688 if device_keys.dehydrated.unwrap_or(false) {
1694 return Ok(true);
1695 }
1696 }
1701
1702 Ok(self
1704 .store()
1705 .get_device_from_curve_key(sender_user_id, decrypted.result.sender_key)
1706 .await?
1707 .is_some_and(|d| d.is_dehydrated()))
1708 }
1709
1710 #[instrument(skip_all)]
1728 pub async fn receive_sync_changes(
1729 &self,
1730 sync_changes: EncryptionSyncChanges<'_>,
1731 decryption_settings: &DecryptionSettings,
1732 ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Vec<RoomKeyInfo>)> {
1733 let mut store_transaction = self.inner.store.transaction().await;
1734
1735 let (events, changes) = self
1736 .preprocess_sync_changes(&mut store_transaction, sync_changes, decryption_settings)
1737 .await?;
1738
1739 let room_key_updates: Vec<_> =
1742 changes.inbound_group_sessions.iter().map(RoomKeyInfo::from).collect();
1743
1744 self.store().save_changes(changes).await?;
1745 store_transaction.commit().await?;
1746
1747 Ok((events, room_key_updates))
1748 }
1749
1750 pub(crate) async fn preprocess_sync_changes(
1768 &self,
1769 transaction: &mut StoreTransaction,
1770 sync_changes: EncryptionSyncChanges<'_>,
1771 decryption_settings: &DecryptionSettings,
1772 ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Changes)> {
1773 let mut events: Vec<ProcessedToDeviceEvent> = self
1775 .inner
1776 .verification_machine
1777 .garbage_collect()
1778 .iter()
1779 .map(|e| ProcessedToDeviceEvent::PlainText(e.clone()))
1783 .collect();
1784 let mut changes = Default::default();
1787
1788 {
1789 let account = transaction.account().await?;
1790 account.update_key_counts(
1791 sync_changes.one_time_keys_counts,
1792 sync_changes.unused_fallback_keys,
1793 )
1794 }
1795
1796 if let Err(e) = self
1797 .inner
1798 .identity_manager
1799 .receive_device_changes(
1800 transaction.cache(),
1801 sync_changes.changed_devices.changed.iter().map(|u| u.as_ref()),
1802 )
1803 .await
1804 {
1805 error!(error = ?e, "Error marking a tracked user as changed");
1806 }
1807
1808 for raw_event in sync_changes.to_device_events {
1809 let processed_event = Box::pin(self.receive_to_device_event(
1810 transaction,
1811 &mut changes,
1812 raw_event,
1813 decryption_settings,
1814 ))
1815 .await;
1816
1817 if let Some(processed_event) = processed_event {
1818 events.push(processed_event);
1819 }
1820 }
1821
1822 let changed_sessions = self
1823 .inner
1824 .key_request_machine
1825 .collect_incoming_key_requests(transaction.cache())
1826 .await?;
1827
1828 changes.sessions.extend(changed_sessions);
1829 changes.next_batch_token = sync_changes.next_batch_token;
1830
1831 Ok((events, changes))
1832 }
1833
1834 pub async fn request_room_key(
1851 &self,
1852 event: &Raw<EncryptedEvent>,
1853 room_id: &RoomId,
1854 ) -> MegolmResult<(Option<OutgoingRequest>, OutgoingRequest)> {
1855 let event = event.deserialize()?;
1856 self.inner.key_request_machine.request_key(room_id, &event).await
1857 }
1858
1859 async fn get_room_event_verification_state(
1872 &self,
1873 session: &InboundGroupSession,
1874 sender: &UserId,
1875 ) -> MegolmResult<(VerificationState, Option<OwnedDeviceId>)> {
1876 let sender_data = self.get_or_update_sender_data(session, sender).await?;
1877
1878 let (verification_state, device_id) = match sender_data.user_id() {
1887 Some(i) if i != sender => {
1888 (VerificationState::Unverified(VerificationLevel::MismatchedSender), None)
1889 }
1890
1891 Some(_) | None => {
1892 sender_data_to_verification_state(sender_data, session.has_been_imported())
1893 }
1894 };
1895
1896 Ok((verification_state, device_id))
1897 }
1898
1899 async fn get_or_update_sender_data(
1914 &self,
1915 session: &InboundGroupSession,
1916 sender: &UserId,
1917 ) -> MegolmResult<SenderData> {
1918 let sender_data = if session.sender_data.should_recalculate() {
1919 let calculated_sender_data = SenderDataFinder::find_using_curve_key(
1938 self.store(),
1939 session.sender_key(),
1940 sender,
1941 session,
1942 )
1943 .await?;
1944
1945 if calculated_sender_data.compare_trust_level(&session.sender_data).is_gt() {
1947 let mut new_session = session.clone();
1949 new_session.sender_data = calculated_sender_data.clone();
1950 self.store().save_inbound_group_sessions(&[new_session]).await?;
1951
1952 calculated_sender_data
1954 } else {
1955 session.sender_data.clone()
1957 }
1958 } else {
1959 session.sender_data.clone()
1960 };
1961
1962 Ok(sender_data)
1963 }
1964
1965 pub async fn query_missing_secrets_from_other_sessions(&self) -> StoreResult<bool> {
1990 let identity = self.inner.user_identity.lock().await;
1991 let mut secrets = identity.get_missing_secrets().await;
1992
1993 if self.store().load_backup_keys().await?.decryption_key.is_none() {
1994 secrets.push(SecretName::RecoveryKey);
1995 }
1996
1997 if secrets.is_empty() {
1998 debug!("No missing requests to query");
1999 return Ok(false);
2000 }
2001
2002 let secret_requests = GossipMachine::request_missing_secrets(self.user_id(), secrets);
2003
2004 let unsent_request = self.store().get_unsent_secret_requests().await?;
2006 let not_yet_requested = secret_requests
2007 .into_iter()
2008 .filter(|request| !unsent_request.iter().any(|unsent| unsent.info == request.info))
2009 .collect_vec();
2010
2011 if not_yet_requested.is_empty() {
2012 debug!("The missing secrets have already been requested");
2013 Ok(false)
2014 } else {
2015 debug!("Requesting missing secrets");
2016
2017 let changes = Changes { key_requests: not_yet_requested, ..Default::default() };
2018
2019 self.store().save_changes(changes).await?;
2020 Ok(true)
2021 }
2022 }
2023
2024 #[cfg(feature = "experimental-push-secrets")]
2031 pub async fn push_secret_to_verified_devices(
2032 &self,
2033 secret_name: SecretName,
2034 ) -> Result<HashMap<OwnedDeviceId, OlmError>, SecretPushError> {
2035 self.inner.key_request_machine.push_secret_to_verified_devices(secret_name).await
2036 }
2037
2038 async fn get_encryption_info(
2044 &self,
2045 session: &InboundGroupSession,
2046 sender: &UserId,
2047 ) -> MegolmResult<Arc<EncryptionInfo>> {
2048 let (verification_state, device_id) =
2049 self.get_room_event_verification_state(session, sender).await?;
2050
2051 Ok(Arc::new(EncryptionInfo {
2052 sender: sender.to_owned(),
2053 sender_device: device_id,
2054 forwarder: session.forwarder_data.as_ref().and_then(|data| {
2055 data.device_id().map(|device_id| ForwarderInfo {
2059 device_id: device_id.to_owned(),
2060 user_id: data.user_id().to_owned(),
2061 })
2062 }),
2063 algorithm_info: AlgorithmInfo::MegolmV1AesSha2 {
2064 curve25519_key: session.sender_key().to_base64(),
2065 sender_claimed_keys: session
2066 .signing_keys()
2067 .iter()
2068 .map(|(k, v)| (k.to_owned(), v.to_base64()))
2069 .collect(),
2070 session_id: Some(session.session_id().to_owned()),
2071 },
2072 verification_state,
2073 }))
2074 }
2075
2076 async fn decrypt_megolm_events(
2077 &self,
2078 room_id: &RoomId,
2079 event: &EncryptedEvent,
2080 content: &SupportedEventEncryptionSchemes<'_>,
2081 decryption_settings: &DecryptionSettings,
2082 ) -> MegolmResult<(JsonObject, Arc<EncryptionInfo>)> {
2083 let session =
2084 self.get_inbound_group_session_or_error(room_id, content.session_id()).await?;
2085
2086 Span::current().record("sender_key", debug(session.sender_key()));
2092
2093 let result = session.decrypt(event).await;
2094 match result {
2095 Ok((decrypted_event, _)) => {
2096 let encryption_info = self.get_encryption_info(&session, &event.sender).await?;
2097
2098 self.check_sender_trust_requirement(
2099 &session,
2100 &encryption_info,
2101 &decryption_settings.sender_device_trust_requirement,
2102 )?;
2103
2104 Ok((decrypted_event, encryption_info))
2105 }
2106 Err(error) => Err(
2107 if let MegolmError::Decryption(DecryptionError::UnknownMessageIndex(_, _)) = error {
2108 let withheld_code = self
2109 .inner
2110 .store
2111 .get_withheld_info(room_id, content.session_id())
2112 .await?
2113 .map(|e| e.content.withheld_code());
2114
2115 if withheld_code.is_some() {
2116 MegolmError::MissingRoomKey(withheld_code)
2118 } else {
2119 error
2120 }
2121 } else {
2122 error
2123 },
2124 ),
2125 }
2126 }
2127
2128 fn check_sender_trust_requirement(
2134 &self,
2135 session: &InboundGroupSession,
2136 encryption_info: &EncryptionInfo,
2137 trust_requirement: &TrustRequirement,
2138 ) -> MegolmResult<()> {
2139 trace!(
2140 verification_state = ?encryption_info.verification_state,
2141 ?trust_requirement, "check_sender_trust_requirement",
2142 );
2143
2144 let verification_level = match &encryption_info.verification_state {
2147 VerificationState::Verified => return Ok(()),
2148 VerificationState::Unverified(verification_level) => verification_level,
2149 };
2150
2151 let ok = match trust_requirement {
2152 TrustRequirement::Untrusted => true,
2153
2154 TrustRequirement::CrossSignedOrLegacy => {
2155 let legacy_session = match session.sender_data {
2161 SenderData::DeviceInfo { legacy_session, .. } => legacy_session,
2162 SenderData::UnknownDevice { legacy_session, .. } => legacy_session,
2163 _ => false,
2164 };
2165
2166 match (verification_level, legacy_session) {
2176 (VerificationLevel::UnverifiedIdentity, _) => true,
2178
2179 (VerificationLevel::UnsignedDevice, true) => true,
2181
2182 (VerificationLevel::None(_), true) => true,
2184
2185 (VerificationLevel::VerificationViolation, _)
2187 | (VerificationLevel::MismatchedSender, _)
2188 | (VerificationLevel::UnsignedDevice, false)
2189 | (VerificationLevel::None(_), false) => false,
2190 }
2191 }
2192
2193 TrustRequirement::CrossSigned => match verification_level {
2196 VerificationLevel::UnverifiedIdentity => true,
2197
2198 VerificationLevel::VerificationViolation
2199 | VerificationLevel::MismatchedSender
2200 | VerificationLevel::UnsignedDevice
2201 | VerificationLevel::None(_) => false,
2202 },
2203 };
2204
2205 if ok {
2206 Ok(())
2207 } else {
2208 Err(MegolmError::SenderIdentityNotTrusted(verification_level.clone()))
2209 }
2210 }
2211
2212 async fn get_inbound_group_session_or_error(
2217 &self,
2218 room_id: &RoomId,
2219 session_id: &str,
2220 ) -> MegolmResult<InboundGroupSession> {
2221 match self.store().get_inbound_group_session(room_id, session_id).await? {
2222 Some(session) => Ok(session),
2223 None => {
2224 let withheld_code = self
2225 .inner
2226 .store
2227 .get_withheld_info(room_id, session_id)
2228 .await?
2229 .map(|e| e.content.withheld_code());
2230 Err(MegolmError::MissingRoomKey(withheld_code))
2231 }
2232 }
2233 }
2234
2235 pub async fn try_decrypt_room_event(
2250 &self,
2251 raw_event: &Raw<EncryptedEvent>,
2252 room_id: &RoomId,
2253 decryption_settings: &DecryptionSettings,
2254 ) -> Result<RoomEventDecryptionResult, CryptoStoreError> {
2255 match self.decrypt_room_event_inner(raw_event, room_id, true, decryption_settings).await {
2256 Ok(decrypted) => Ok(RoomEventDecryptionResult::Decrypted(decrypted)),
2257 Err(err) => Ok(RoomEventDecryptionResult::UnableToDecrypt(megolm_error_to_utd_info(
2258 raw_event, err,
2259 )?)),
2260 }
2261 }
2262
2263 pub async fn decrypt_room_event(
2271 &self,
2272 event: &Raw<EncryptedEvent>,
2273 room_id: &RoomId,
2274 decryption_settings: &DecryptionSettings,
2275 ) -> MegolmResult<DecryptedRoomEvent> {
2276 self.decrypt_room_event_inner(event, room_id, true, decryption_settings).await
2277 }
2278
2279 #[instrument(name = "decrypt_room_event", skip_all, fields(?room_id, event_id, origin_server_ts, sender, algorithm, session_id, message_index, sender_key))]
2280 async fn decrypt_room_event_inner(
2281 &self,
2282 event: &Raw<EncryptedEvent>,
2283 room_id: &RoomId,
2284 decrypt_unsigned: bool,
2285 decryption_settings: &DecryptionSettings,
2286 ) -> MegolmResult<DecryptedRoomEvent> {
2287 let _timer = timer!(tracing::Level::TRACE, "_method");
2288
2289 let event = event.deserialize()?;
2290
2291 Span::current()
2292 .record("sender", debug(&event.sender))
2293 .record("event_id", debug(&event.event_id))
2294 .record(
2295 "origin_server_ts",
2296 timestamp_to_iso8601(event.origin_server_ts)
2297 .unwrap_or_else(|| "<out of range>".to_owned()),
2298 )
2299 .record("algorithm", debug(event.content.algorithm()));
2300
2301 let content: SupportedEventEncryptionSchemes<'_> = match &event.content.scheme {
2302 RoomEventEncryptionScheme::MegolmV1AesSha2(c) => {
2303 Span::current().record("sender_key", debug(c.sender_key));
2304 c.into()
2305 }
2306 #[cfg(feature = "experimental-algorithms")]
2307 RoomEventEncryptionScheme::MegolmV2AesSha2(c) => c.into(),
2308 RoomEventEncryptionScheme::Unknown(_) => {
2309 warn!("Received an encrypted room event with an unsupported algorithm");
2310 return Err(EventError::UnsupportedAlgorithm.into());
2311 }
2312 };
2313
2314 Span::current().record("session_id", content.session_id());
2315 Span::current().record("message_index", content.message_index());
2316
2317 let result =
2318 self.decrypt_megolm_events(room_id, &event, &content, decryption_settings).await;
2319
2320 if let Err(e) = &result {
2321 #[cfg(feature = "automatic-room-key-forwarding")]
2322 match e {
2323 MegolmError::MissingRoomKey(_)
2326 | MegolmError::Decryption(DecryptionError::UnknownMessageIndex(_, _)) => {
2327 self.inner
2328 .key_request_machine
2329 .create_outgoing_key_request(room_id, &event)
2330 .await?;
2331 }
2332 _ => {}
2333 }
2334
2335 warn!("Failed to decrypt a room event: {e}");
2336 }
2337
2338 let (mut decrypted_event, encryption_info) = result?;
2339
2340 let mut unsigned_encryption_info = None;
2341 if decrypt_unsigned {
2342 unsigned_encryption_info = self
2344 .decrypt_unsigned_events(&mut decrypted_event, room_id, decryption_settings)
2345 .await;
2346 }
2347
2348 let decrypted_event =
2349 serde_json::from_value::<Raw<AnyTimelineEvent>>(decrypted_event.into())?;
2350
2351 #[cfg(feature = "experimental-encrypted-state-events")]
2352 self.verify_packed_state_key(&event, &decrypted_event)?;
2353
2354 Ok(DecryptedRoomEvent { event: decrypted_event, encryption_info, unsigned_encryption_info })
2355 }
2356
2357 #[cfg(feature = "experimental-encrypted-state-events")]
2374 fn verify_packed_state_key(
2375 &self,
2376 original: &EncryptedEvent,
2377 decrypted: &Raw<AnyTimelineEvent>,
2378 ) -> MegolmResult<()> {
2379 use serde::Deserialize;
2380
2381 #[derive(Deserialize)]
2383 struct PayloadDeserializationHelper {
2384 state_key: Option<String>,
2385 #[serde(rename = "type")]
2386 event_type: String,
2387 }
2388
2389 let PayloadDeserializationHelper {
2391 state_key: inner_state_key,
2392 event_type: inner_event_type,
2393 } = decrypted
2394 .deserialize_as_unchecked()
2395 .map_err(|_| MegolmError::StateKeyVerificationFailed)?;
2396
2397 let (raw_state_key, inner_state_key) = match (&original.state_key, &inner_state_key) {
2399 (Some(raw_state_key), Some(inner_state_key)) => (raw_state_key, inner_state_key),
2400 (None, None) => return Ok(()),
2401 _ => return Err(MegolmError::StateKeyVerificationFailed),
2402 };
2403
2404 let (outer_event_type, outer_state_key) =
2406 raw_state_key.split_once(":").ok_or(MegolmError::StateKeyVerificationFailed)?;
2407
2408 if outer_event_type != inner_event_type {
2410 return Err(MegolmError::StateKeyVerificationFailed);
2411 }
2412
2413 if outer_state_key != inner_state_key {
2415 return Err(MegolmError::StateKeyVerificationFailed);
2416 }
2417 Ok(())
2418 }
2419
2420 async fn decrypt_unsigned_events(
2430 &self,
2431 main_event: &mut JsonObject,
2432 room_id: &RoomId,
2433 decryption_settings: &DecryptionSettings,
2434 ) -> Option<BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>> {
2435 let unsigned = main_event.get_mut("unsigned")?.as_object_mut()?;
2436 let mut unsigned_encryption_info: Option<
2437 BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>,
2438 > = None;
2439
2440 let location = UnsignedEventLocation::RelationsReplace;
2442 let replace = location.find_mut(unsigned);
2443 if let Some(decryption_result) =
2444 self.decrypt_unsigned_event(replace, room_id, decryption_settings).await
2445 {
2446 unsigned_encryption_info
2447 .get_or_insert_with(Default::default)
2448 .insert(location, decryption_result);
2449 }
2450
2451 let location = UnsignedEventLocation::RelationsThreadLatestEvent;
2454 let thread_latest_event = location.find_mut(unsigned);
2455 if let Some(decryption_result) =
2456 self.decrypt_unsigned_event(thread_latest_event, room_id, decryption_settings).await
2457 {
2458 unsigned_encryption_info
2459 .get_or_insert_with(Default::default)
2460 .insert(location, decryption_result);
2461 }
2462
2463 unsigned_encryption_info
2464 }
2465
2466 fn decrypt_unsigned_event<'a>(
2474 &'a self,
2475 event: Option<&'a mut Value>,
2476 room_id: &'a RoomId,
2477 decryption_settings: &'a DecryptionSettings,
2478 ) -> BoxFuture<'a, Option<UnsignedDecryptionResult>> {
2479 Box::pin(async move {
2480 let event = event?;
2481
2482 let is_encrypted = event
2483 .get("type")
2484 .and_then(|type_| type_.as_str())
2485 .is_some_and(|s| s == "m.room.encrypted");
2486 if !is_encrypted {
2487 return None;
2488 }
2489
2490 let raw_event = serde_json::from_value(event.clone()).ok()?;
2491 match self
2492 .decrypt_room_event_inner(&raw_event, room_id, false, decryption_settings)
2493 .await
2494 {
2495 Ok(decrypted_event) => {
2496 *event = serde_json::to_value(decrypted_event.event).ok()?;
2498 Some(UnsignedDecryptionResult::Decrypted(decrypted_event.encryption_info))
2499 }
2500 Err(err) => {
2501 let utd_info = megolm_error_to_utd_info(&raw_event, err).ok()?;
2506 Some(UnsignedDecryptionResult::UnableToDecrypt(utd_info))
2507 }
2508 }
2509 })
2510 }
2511
2512 pub async fn is_room_key_available(
2519 &self,
2520 event: &Raw<EncryptedEvent>,
2521 room_id: &RoomId,
2522 ) -> Result<bool, CryptoStoreError> {
2523 let event = event.deserialize()?;
2524
2525 let (session_id, message_index) = match &event.content.scheme {
2526 RoomEventEncryptionScheme::MegolmV1AesSha2(c) => {
2527 (&c.session_id, c.ciphertext.message_index())
2528 }
2529 #[cfg(feature = "experimental-algorithms")]
2530 RoomEventEncryptionScheme::MegolmV2AesSha2(c) => {
2531 (&c.session_id, c.ciphertext.message_index())
2532 }
2533 RoomEventEncryptionScheme::Unknown(_) => {
2534 return Ok(false);
2536 }
2537 };
2538
2539 Ok(self
2542 .store()
2543 .get_inbound_group_session(room_id, session_id)
2544 .await?
2545 .filter(|s| s.first_known_index() <= message_index)
2546 .is_some())
2547 }
2548
2549 #[instrument(skip(self, event), fields(event_id, sender, session_id))]
2562 pub async fn get_room_event_encryption_info(
2563 &self,
2564 event: &Raw<EncryptedEvent>,
2565 room_id: &RoomId,
2566 ) -> MegolmResult<Arc<EncryptionInfo>> {
2567 let event = event.deserialize()?;
2568
2569 let content: SupportedEventEncryptionSchemes<'_> = match &event.content.scheme {
2570 RoomEventEncryptionScheme::MegolmV1AesSha2(c) => c.into(),
2571 #[cfg(feature = "experimental-algorithms")]
2572 RoomEventEncryptionScheme::MegolmV2AesSha2(c) => c.into(),
2573 RoomEventEncryptionScheme::Unknown(_) => {
2574 return Err(EventError::UnsupportedAlgorithm.into());
2575 }
2576 };
2577
2578 Span::current()
2579 .record("sender", debug(&event.sender))
2580 .record("event_id", debug(&event.event_id))
2581 .record("session_id", content.session_id());
2582
2583 self.get_session_encryption_info(room_id, content.session_id(), &event.sender).await
2584 }
2585
2586 pub async fn get_session_encryption_info(
2601 &self,
2602 room_id: &RoomId,
2603 session_id: &str,
2604 sender: &UserId,
2605 ) -> MegolmResult<Arc<EncryptionInfo>> {
2606 let session = self.get_inbound_group_session_or_error(room_id, session_id).await?;
2607 self.get_encryption_info(&session, sender).await
2608 }
2609
2610 pub async fn update_tracked_users(
2628 &self,
2629 users: impl IntoIterator<Item = &UserId>,
2630 ) -> StoreResult<()> {
2631 self.inner.identity_manager.update_tracked_users(users).await
2632 }
2633
2634 pub async fn mark_all_tracked_users_as_dirty(&self) -> StoreResult<()> {
2639 self.inner
2640 .identity_manager
2641 .mark_all_tracked_users_as_dirty(self.inner.store.cache().await?)
2642 .await
2643 }
2644
2645 async fn wait_if_user_pending(
2646 &self,
2647 user_id: &UserId,
2648 timeout: Option<Duration>,
2649 ) -> StoreResult<()> {
2650 if let Some(timeout) = timeout {
2651 let cache = self.store().cache().await?;
2652 self.inner
2653 .identity_manager
2654 .key_query_manager
2655 .wait_if_user_key_query_pending(cache, timeout, user_id)
2656 .await?;
2657 }
2658 Ok(())
2659 }
2660
2661 #[instrument(skip(self))]
2691 pub async fn get_device(
2692 &self,
2693 user_id: &UserId,
2694 device_id: &DeviceId,
2695 timeout: Option<Duration>,
2696 ) -> StoreResult<Option<Device>> {
2697 self.wait_if_user_pending(user_id, timeout).await?;
2698 self.store().get_device(user_id, device_id).await
2699 }
2700
2701 #[instrument(skip(self))]
2715 pub async fn get_identity(
2716 &self,
2717 user_id: &UserId,
2718 timeout: Option<Duration>,
2719 ) -> StoreResult<Option<UserIdentity>> {
2720 self.wait_if_user_pending(user_id, timeout).await?;
2721 self.store().get_identity(user_id).await
2722 }
2723
2724 #[instrument(skip(self))]
2751 pub async fn get_user_devices(
2752 &self,
2753 user_id: &UserId,
2754 timeout: Option<Duration>,
2755 ) -> StoreResult<UserDevices> {
2756 self.wait_if_user_pending(user_id, timeout).await?;
2757 self.store().get_user_devices(user_id).await
2758 }
2759
2760 pub async fn cross_signing_status(&self) -> CrossSigningStatus {
2765 self.inner.user_identity.lock().await.status().await
2766 }
2767
2768 pub async fn export_cross_signing_keys(&self) -> StoreResult<Option<CrossSigningKeyExport>> {
2776 let master_key = self.store().export_secret(&SecretName::CrossSigningMasterKey).await?;
2777 let self_signing_key =
2778 self.store().export_secret(&SecretName::CrossSigningSelfSigningKey).await?;
2779 let user_signing_key =
2780 self.store().export_secret(&SecretName::CrossSigningUserSigningKey).await?;
2781
2782 Ok(if master_key.is_none() && self_signing_key.is_none() && user_signing_key.is_none() {
2783 None
2784 } else {
2785 Some(CrossSigningKeyExport { master_key, self_signing_key, user_signing_key })
2786 })
2787 }
2788
2789 pub async fn import_cross_signing_keys(
2794 &self,
2795 export: CrossSigningKeyExport,
2796 ) -> Result<CrossSigningStatus, SecretImportError> {
2797 self.store().import_cross_signing_keys(export).await
2798 }
2799
2800 async fn sign_with_master_key(
2801 &self,
2802 message: &str,
2803 ) -> Result<(OwnedDeviceKeyId, Ed25519Signature), SignatureError> {
2804 let identity = &*self.inner.user_identity.lock().await;
2805 let key_id = identity.master_key_id().await.ok_or(SignatureError::MissingSigningKey)?;
2806
2807 let signature = identity.sign(message).await?;
2808
2809 Ok((key_id, signature))
2810 }
2811
2812 pub async fn sign(&self, message: &str) -> Result<Signatures, CryptoStoreError> {
2818 let mut signatures = Signatures::new();
2819
2820 {
2821 let cache = self.inner.store.cache().await?;
2822 let account = cache.account().await?;
2823 let key_id = account.signing_key_id();
2824 let signature = account.sign(message);
2825 signatures.add_signature(self.user_id().to_owned(), key_id, signature);
2826 }
2827
2828 match self.sign_with_master_key(message).await {
2829 Ok((key_id, signature)) => {
2830 signatures.add_signature(self.user_id().to_owned(), key_id, signature);
2831 }
2832 Err(e) => {
2833 warn!(error = ?e, "Couldn't sign the message using the cross signing master key")
2834 }
2835 }
2836
2837 Ok(signatures)
2838 }
2839
2840 pub fn backup_machine(&self) -> &BackupMachine {
2845 &self.inner.backup_machine
2846 }
2847
2848 pub fn dehydrated_devices(&self) -> DehydratedDevices {
2850 DehydratedDevices { inner: self.to_owned() }
2851 }
2852
2853 pub async fn room_settings(&self, room_id: &RoomId) -> StoreResult<Option<RoomSettings>> {
2858 self.inner.store.get_room_settings(room_id).await
2861 }
2862
2863 pub async fn set_room_settings(
2874 &self,
2875 room_id: &RoomId,
2876 new_settings: &RoomSettings,
2877 ) -> Result<(), SetRoomSettingsError> {
2878 let store = &self.inner.store;
2879
2880 let _store_transaction = store.transaction().await;
2885
2886 let old_settings = store.get_room_settings(room_id).await?;
2887
2888 if let Some(old_settings) = old_settings {
2901 if old_settings != *new_settings {
2902 return Err(SetRoomSettingsError::EncryptionDowngrade);
2903 } else {
2904 return Ok(());
2906 }
2907 }
2908
2909 match new_settings.algorithm {
2911 EventEncryptionAlgorithm::MegolmV1AesSha2 => (),
2912
2913 #[cfg(feature = "experimental-algorithms")]
2914 EventEncryptionAlgorithm::MegolmV2AesSha2 => (),
2915
2916 _ => {
2917 warn!(
2918 ?room_id,
2919 "Rejecting invalid encryption algorithm {}", new_settings.algorithm
2920 );
2921 return Err(SetRoomSettingsError::InvalidSettings);
2922 }
2923 }
2924
2925 store
2927 .save_changes(Changes {
2928 room_settings: HashMap::from([(room_id.to_owned(), new_settings.clone())]),
2929 ..Default::default()
2930 })
2931 .await?;
2932
2933 Ok(())
2934 }
2935
2936 #[cfg(any(feature = "testing", test))]
2940 pub fn same_as(&self, other: &OlmMachine) -> bool {
2941 Arc::ptr_eq(&self.inner, &other.inner)
2942 }
2943
2944 #[cfg(any(feature = "testing", test))]
2946 pub async fn uploaded_key_count(&self) -> Result<u64, CryptoStoreError> {
2947 let cache = self.inner.store.cache().await?;
2948 let account = cache.account().await?;
2949 Ok(account.uploaded_key_count())
2950 }
2951
2952 #[cfg(test)]
2954 pub(crate) fn identity_manager(&self) -> &IdentityManager {
2955 &self.inner.identity_manager
2956 }
2957
2958 #[cfg(test)]
2960 pub(crate) fn key_for_has_migrated_verification_latch() -> &'static str {
2961 Self::HAS_MIGRATED_VERIFICATION_LATCH
2962 }
2963}
2964
2965fn sender_data_to_verification_state(
2966 sender_data: SenderData,
2967 session_has_been_imported: bool,
2968) -> (VerificationState, Option<OwnedDeviceId>) {
2969 match sender_data {
2970 SenderData::UnknownDevice { owner_check_failed: false, .. } => {
2971 let device_link_problem = if session_has_been_imported {
2972 DeviceLinkProblem::InsecureSource
2973 } else {
2974 DeviceLinkProblem::MissingDevice
2975 };
2976
2977 (VerificationState::Unverified(VerificationLevel::None(device_link_problem)), None)
2978 }
2979 SenderData::UnknownDevice { owner_check_failed: true, .. } => (
2980 VerificationState::Unverified(VerificationLevel::None(
2981 DeviceLinkProblem::InsecureSource,
2982 )),
2983 None,
2984 ),
2985 SenderData::DeviceInfo { device_keys, .. } => (
2986 VerificationState::Unverified(VerificationLevel::UnsignedDevice),
2987 Some(device_keys.device_id),
2988 ),
2989 SenderData::VerificationViolation(KnownSenderData { device_id, .. }) => {
2990 (VerificationState::Unverified(VerificationLevel::VerificationViolation), device_id)
2991 }
2992 SenderData::SenderUnverified(KnownSenderData { device_id, .. }) => {
2993 (VerificationState::Unverified(VerificationLevel::UnverifiedIdentity), device_id)
2994 }
2995 SenderData::SenderVerified(KnownSenderData { device_id, .. }) => {
2996 (VerificationState::Verified, device_id)
2997 }
2998 }
2999}
3000
3001#[derive(Debug, Clone)]
3004pub struct CrossSigningBootstrapRequests {
3005 pub upload_keys_req: Option<OutgoingRequest>,
3012
3013 pub upload_signing_keys_req: UploadSigningKeysRequest,
3017
3018 pub upload_signatures_req: UploadSignaturesRequest,
3023}
3024
3025#[derive(Debug)]
3028pub struct EncryptionSyncChanges<'a> {
3029 pub to_device_events: Vec<Raw<AnyToDeviceEvent>>,
3031 pub changed_devices: &'a DeviceLists,
3034 pub one_time_keys_counts: &'a BTreeMap<OneTimeKeyAlgorithm, UInt>,
3036 pub unused_fallback_keys: Option<&'a [OneTimeKeyAlgorithm]>,
3038 pub next_batch_token: Option<String>,
3040}
3041
3042fn megolm_error_to_utd_info(
3050 raw_event: &Raw<EncryptedEvent>,
3051 error: MegolmError,
3052) -> Result<UnableToDecryptInfo, CryptoStoreError> {
3053 use MegolmError::*;
3054 let reason = match error {
3055 EventError(_) => UnableToDecryptReason::MalformedEncryptedEvent,
3056 Decode(_) => UnableToDecryptReason::MalformedEncryptedEvent,
3057 MissingRoomKey(maybe_withheld) => {
3058 UnableToDecryptReason::MissingMegolmSession { withheld_code: maybe_withheld }
3059 }
3060 Decryption(DecryptionError::UnknownMessageIndex(_, _)) => {
3061 UnableToDecryptReason::UnknownMegolmMessageIndex
3062 }
3063 Decryption(_) => UnableToDecryptReason::MegolmDecryptionFailure,
3064 JsonError(_) => UnableToDecryptReason::PayloadDeserializationFailure,
3065 MismatchedIdentityKeys(_) => UnableToDecryptReason::MismatchedIdentityKeys,
3066 SenderIdentityNotTrusted(level) => UnableToDecryptReason::SenderIdentityNotTrusted(level),
3067 #[cfg(feature = "experimental-encrypted-state-events")]
3068 StateKeyVerificationFailed => UnableToDecryptReason::StateKeyVerificationFailed,
3069
3070 Store(error) => Err(error)?,
3073 };
3074
3075 let session_id = raw_event.deserialize().ok().and_then(|ev| match ev.content.scheme {
3076 RoomEventEncryptionScheme::MegolmV1AesSha2(s) => Some(s.session_id),
3077 #[cfg(feature = "experimental-algorithms")]
3078 RoomEventEncryptionScheme::MegolmV2AesSha2(s) => Some(s.session_id),
3079 RoomEventEncryptionScheme::Unknown(_) => None,
3080 });
3081
3082 Ok(UnableToDecryptInfo { session_id, reason })
3083}
3084
3085#[derive(Debug, thiserror::Error)]
3095pub(crate) enum DecryptToDeviceError {
3096 #[error("An Olm error occurred meaning we failed to decrypt the event")]
3097 OlmError(#[from] OlmError),
3098
3099 #[error("The event was sent from a dehydrated device")]
3100 FromDehydratedDevice,
3101}
3102
3103impl From<CryptoStoreError> for DecryptToDeviceError {
3104 fn from(value: CryptoStoreError) -> Self {
3105 Self::OlmError(value.into())
3106 }
3107}
3108
3109#[cfg(test)]
3110impl From<DecryptToDeviceError> for OlmError {
3111 fn from(value: DecryptToDeviceError) -> Self {
3114 match value {
3115 DecryptToDeviceError::OlmError(olm_error) => olm_error,
3116 DecryptToDeviceError::FromDehydratedDevice => {
3117 panic!("Expected an OlmError but found FromDehydratedDevice")
3118 }
3119 }
3120 }
3121}
3122
3123#[cfg(test)]
3124pub(crate) mod test_helpers;
3125
3126#[cfg(test)]
3127pub(crate) mod tests;