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;
73#[cfg(feature = "experimental-x509-identity-verification")]
74use crate::x509::{RawX509Signer, RawX509Verifier, X509Signer, X509Verifier};
75use crate::{
76 CollectStrategy, CryptoStoreError, DecryptionSettings, DeviceData, LocalTrust,
77 OwnUserIdentityData, RoomEventDecryptionResult, SignatureError, TrustRequirement,
78 backups::{BackupMachine, MegolmV1BackupKey},
79 dehydrated_devices::{DehydratedDevices, DehydrationError},
80 error::{EventError, MegolmError, MegolmResult, OlmError, OlmResult, SetRoomSettingsError},
81 gossiping::GossipMachine,
82 identities::{Device, IdentityManager, UserDevices, user::UserIdentity},
83 olm::{
84 Account, CrossSigningStatus, EncryptionSettings, IdentityKeys, InboundGroupSession,
85 KnownSenderData, OlmDecryptionInfo, PrivateCrossSigningIdentity, SenderData,
86 SenderDataFinder, SessionType, StaticAccountData,
87 },
88 session_manager::{GroupSessionManager, SessionManager},
89 store::{
90 CryptoStoreWrapper, DynCryptoStore, IntoCryptoStore, MemoryStore, Result as StoreResult,
91 SecretImportError, Store, StoreTransaction,
92 caches::StoreCache,
93 types::{
94 Changes, CrossSigningKeyExport, DeviceChanges, IdentityChanges, PendingChanges,
95 RoomKeyInfo, RoomSettings, StoredRoomKeyBundleData,
96 },
97 },
98 types::{
99 EventEncryptionAlgorithm, Signatures,
100 events::{
101 ToDeviceEvent, ToDeviceEvents,
102 olm_v1::{AnyDecryptedOlmEvent, DecryptedRoomKeyBundleEvent, DecryptedRoomKeyEvent},
103 room::encrypted::{
104 EncryptedEvent, EncryptedToDeviceEvent, RoomEncryptedEventContent,
105 RoomEventEncryptionScheme, SupportedEventEncryptionSchemes,
106 ToDeviceEncryptedEventContent,
107 },
108 room_key::{MegolmV1AesSha2Content, RoomKeyContent},
109 room_key_bundle::RoomKeyBundleContent,
110 room_key_withheld::{
111 MegolmV1AesSha2WithheldContent, RoomKeyWithheldContent, RoomKeyWithheldEvent,
112 },
113 },
114 requests::{
115 AnyIncomingResponse, KeysQueryRequest, OutgoingRequest, ToDeviceRequest,
116 UploadSigningKeysRequest,
117 },
118 },
119 utilities::timestamp_to_iso8601,
120 verification::{Verification, VerificationMachine, VerificationRequest},
121};
122
123#[derive(Debug, Serialize)]
124pub struct RawEncryptionResult {
126 pub content: Raw<RoomEncryptedEventContent>,
128 pub encryption_info: EncryptionInfo,
130}
131
132pub struct OlmMachineBuilder {
134 user_id: OwnedUserId,
136
137 device_id: OwnedDeviceId,
139
140 store: Option<Arc<DynCryptoStore>>,
143
144 custom_account: Option<vodozemac::olm::Account>,
147
148 #[cfg(feature = "experimental-x509-identity-verification")]
150 x509_verifier: Option<X509Verifier>,
151
152 #[cfg(feature = "experimental-x509-identity-verification")]
154 x509_signer: Option<X509Signer>,
155}
156
157impl OlmMachineBuilder {
158 pub fn new(user_id: &UserId, device_id: &DeviceId) -> Self {
161 Self {
162 user_id: user_id.to_owned(),
163 device_id: device_id.to_owned(),
164 store: None,
165 custom_account: None,
166 #[cfg(feature = "experimental-x509-identity-verification")]
167 x509_verifier: None,
168 #[cfg(feature = "experimental-x509-identity-verification")]
169 x509_signer: None,
170 }
171 }
172
173 pub fn with_crypto_store(mut self, store: impl IntoCryptoStore) -> Self {
181 self.store = Some(store.into_crypto_store());
182 self
183 }
184
185 pub fn with_custom_account(mut self, custom_account: Option<vodozemac::olm::Account>) -> Self {
195 self.custom_account = custom_account;
196 self
197 }
198
199 #[cfg(feature = "experimental-x509-identity-verification")]
202 pub fn with_x509_verifier(mut self, x509_verifier: Option<Arc<dyn RawX509Verifier>>) -> Self {
203 self.x509_verifier = x509_verifier.map(X509Verifier::new);
204 self
205 }
206
207 #[cfg(feature = "experimental-x509-identity-verification")]
210 pub fn with_x509_signer(mut self, x509_signer: Option<Arc<dyn RawX509Signer>>) -> Self {
211 self.x509_signer = x509_signer.map(X509Signer::new);
212 self
213 }
214
215 pub async fn build(self) -> Result<OlmMachine, CryptoStoreError> {
222 OlmMachine::from_builder(self).await
223 }
224}
225
226impl std::fmt::Debug for OlmMachineBuilder {
227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228 f.debug_struct("OlmMachineBuilder")
229 .field("user_id", &self.user_id)
230 .field("device_id", &self.device_id)
231 .finish_non_exhaustive()
232 }
233}
234
235#[derive(Clone)]
238pub struct OlmMachine {
239 pub(crate) inner: Arc<OlmMachineInner>,
240}
241
242pub struct OlmMachineInner {
243 user_id: OwnedUserId,
245 device_id: OwnedDeviceId,
247 user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
251 store: Store,
254 session_manager: SessionManager,
256 pub(crate) group_session_manager: GroupSessionManager,
258 verification_machine: VerificationMachine,
261 pub(crate) key_request_machine: GossipMachine,
264 identity_manager: IdentityManager,
267 backup_machine: BackupMachine,
269}
270
271#[cfg(not(tarpaulin_include))]
272impl std::fmt::Debug for OlmMachine {
273 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274 f.debug_struct("OlmMachine")
275 .field("user_id", &self.user_id())
276 .field("device_id", &self.device_id())
277 .finish()
278 }
279}
280
281impl OlmMachine {
282 const CURRENT_GENERATION_STORE_KEY: &'static str = "generation-counter";
283 const HAS_MIGRATED_VERIFICATION_LATCH: &'static str = "HAS_MIGRATED_VERIFICATION_LATCH";
284
285 pub async fn new(user_id: &UserId, device_id: &DeviceId) -> Self {
295 OlmMachineBuilder::new(user_id, device_id)
296 .build()
297 .await
298 .expect("Reading and writing to the memory store always succeeds")
299 }
300
301 pub(crate) async fn rehydrate(
302 &self,
303 pickle_key: &[u8; 32],
304 device_id: &DeviceId,
305 device_data: Raw<DehydratedDeviceData>,
306 ) -> Result<OlmMachine, DehydrationError> {
307 let account = Account::rehydrate(pickle_key, self.user_id(), device_id, device_data)?;
308 let static_account = account.static_data().clone();
309
310 let store =
311 Arc::new(CryptoStoreWrapper::new(self.user_id(), device_id, MemoryStore::new()));
312 let device = DeviceData::from_account(&account);
313 store.save_pending_changes(PendingChanges { account: Some(account) }).await?;
314 store
315 .save_changes(Changes {
316 devices: DeviceChanges { new: vec![device], ..Default::default() },
317 ..Default::default()
318 })
319 .await?;
320
321 let (verification_machine, store, identity_manager) = Self::new_helper_prelude(
322 store,
323 static_account,
324 self.store().private_identity(),
325 #[cfg(feature = "experimental-x509-identity-verification")]
326 self.store().x509_verifier().cloned(),
327 #[cfg(feature = "experimental-x509-identity-verification")]
328 self.store().x509_signer().cloned(),
329 );
330
331 Ok(Self::new_helper(
332 device_id,
333 store,
334 verification_machine,
335 identity_manager,
336 self.store().private_identity(),
337 None,
338 ))
339 }
340
341 fn new_helper_prelude(
342 store_wrapper: Arc<CryptoStoreWrapper>,
343 account: StaticAccountData,
344 user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
345 #[cfg(feature = "experimental-x509-identity-verification")] x509_verifier: Option<
346 X509Verifier,
347 >,
348 #[cfg(feature = "experimental-x509-identity-verification")] x509_signer: Option<X509Signer>,
349 ) -> (VerificationMachine, Store, IdentityManager) {
350 let verification_machine =
351 VerificationMachine::new(account.clone(), user_identity.clone(), store_wrapper.clone());
352
353 let store = Store::new_with_x509(
354 account,
355 user_identity,
356 store_wrapper,
357 verification_machine.clone(),
358 #[cfg(feature = "experimental-x509-identity-verification")]
359 x509_verifier,
360 #[cfg(feature = "experimental-x509-identity-verification")]
361 x509_signer,
362 );
363
364 let identity_manager = IdentityManager::new(store.clone());
365
366 (verification_machine, store, identity_manager)
367 }
368
369 fn new_helper(
370 device_id: &DeviceId,
371 store: Store,
372 verification_machine: VerificationMachine,
373 identity_manager: IdentityManager,
374 user_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
375 maybe_backup_key: Option<MegolmV1BackupKey>,
376 ) -> Self {
377 let group_session_manager = GroupSessionManager::new(store.clone());
378
379 let users_for_key_claim = Arc::new(StdRwLock::new(BTreeMap::new()));
380 let key_request_machine = GossipMachine::new(
381 store.clone(),
382 identity_manager.clone(),
383 group_session_manager.session_cache(),
384 users_for_key_claim.clone(),
385 );
386
387 let session_manager =
388 SessionManager::new(users_for_key_claim, key_request_machine.clone(), store.clone());
389
390 let backup_machine = BackupMachine::new(store.clone(), maybe_backup_key);
391
392 let inner = Arc::new(OlmMachineInner {
393 user_id: store.user_id().to_owned(),
394 device_id: device_id.to_owned(),
395 user_identity,
396 store,
397 session_manager,
398 group_session_manager,
399 verification_machine,
400 key_request_machine,
401 identity_manager,
402 backup_machine,
403 });
404
405 Self { inner }
406 }
407
408 #[instrument(skip(builder), fields(user_id, device_id, ed25519_key, curve25519_key))]
409 pub(crate) async fn from_builder(builder: OlmMachineBuilder) -> StoreResult<Self> {
410 let OlmMachineBuilder {
411 user_id,
412 device_id,
413 store,
414 custom_account,
415 #[cfg(feature = "experimental-x509-identity-verification")]
416 x509_verifier,
417 #[cfg(feature = "experimental-x509-identity-verification")]
418 x509_signer,
419 } = builder;
420
421 Span::current()
422 .record("user_id", display(&user_id))
423 .record("device_id", display(&device_id));
424
425 let store = store.unwrap_or_else(|| MemoryStore::new().into_crypto_store());
426
427 let static_account = match store.load_account().await? {
428 Some(account) => {
429 if user_id != account.user_id()
430 || device_id != account.device_id()
431 || custom_account.is_some()
432 {
433 return Err(CryptoStoreError::MismatchedAccount {
434 expected: (account.user_id().to_owned(), account.device_id().to_owned()),
435 got: (user_id.to_owned(), device_id.to_owned()),
436 });
437 }
438
439 Span::current()
440 .record("ed25519_key", display(account.identity_keys().ed25519))
441 .record("curve25519_key", display(account.identity_keys().curve25519));
442 debug!("Restored an Olm account");
443
444 account.static_data().clone()
445 }
446
447 None => {
448 let account = if let Some(account) = custom_account {
449 Account::new_helper(account, &user_id, &device_id)
450 } else {
451 Account::with_device_id(&user_id, &device_id)
452 };
453
454 let static_account = account.static_data().clone();
455
456 Span::current()
457 .record("ed25519_key", display(account.identity_keys().ed25519))
458 .record("curve25519_key", display(account.identity_keys().curve25519));
459
460 let device = DeviceData::from_account(&account);
461
462 device.set_trust_state(LocalTrust::Verified);
466
467 let changes = Changes {
468 devices: DeviceChanges { new: vec![device], ..Default::default() },
469 ..Default::default()
470 };
471 store.save_changes(changes).await?;
472 store.save_pending_changes(PendingChanges { account: Some(account) }).await?;
473
474 debug!("Created a new Olm account");
475
476 static_account
477 }
478 };
479
480 let identity = match store.load_identity().await? {
481 Some(i) => {
482 let master_key = i
483 .master_public_key()
484 .await
485 .and_then(|m| m.get_first_key().map(|m| m.to_owned()));
486 debug!(?master_key, "Restored the cross signing identity");
487 i
488 }
489 None => {
490 debug!("Creating an empty cross signing identity stub");
491 PrivateCrossSigningIdentity::empty(&user_id)
492 }
493 };
494
495 let saved_keys = store.load_backup_keys().await?;
500 let maybe_backup_key = saved_keys.decryption_key.and_then(|k| {
501 if let Some(version) = saved_keys.backup_version {
502 let megolm_v1_backup_key = k.megolm_v1_public_key();
503 megolm_v1_backup_key.set_version(version);
504 Some(megolm_v1_backup_key)
505 } else {
506 None
507 }
508 });
509
510 let identity = Arc::new(Mutex::new(identity));
511 let store = Arc::new(CryptoStoreWrapper::new(&user_id, &device_id, store));
512
513 let (verification_machine, store, identity_manager) = Self::new_helper_prelude(
514 store,
515 static_account,
516 identity.clone(),
517 #[cfg(feature = "experimental-x509-identity-verification")]
518 x509_verifier,
519 #[cfg(feature = "experimental-x509-identity-verification")]
520 x509_signer,
521 );
522
523 Self::migration_post_verified_latch_support(&store, &identity_manager).await?;
526
527 Ok(Self::new_helper(
528 &device_id,
529 store,
530 verification_machine,
531 identity_manager,
532 identity,
533 maybe_backup_key,
534 ))
535 }
536
537 pub(crate) async fn migration_post_verified_latch_support(
544 store: &Store,
545 identity_manager: &IdentityManager,
546 ) -> Result<(), CryptoStoreError> {
547 let maybe_migrate_for_identity_verified_latch =
548 store.get_custom_value(Self::HAS_MIGRATED_VERIFICATION_LATCH).await?.is_none();
549
550 if maybe_migrate_for_identity_verified_latch {
551 identity_manager.mark_all_tracked_users_as_dirty(store.cache().await?).await?;
552
553 store.set_custom_value(Self::HAS_MIGRATED_VERIFICATION_LATCH, vec![0]).await?
554 }
555 Ok(())
556 }
557
558 pub fn store(&self) -> &Store {
560 &self.inner.store
561 }
562
563 pub fn user_id(&self) -> &UserId {
565 &self.inner.user_id
566 }
567
568 pub fn device_id(&self) -> &DeviceId {
570 &self.inner.device_id
571 }
572
573 pub fn device_creation_time(&self) -> MilliSecondsSinceUnixEpoch {
580 self.inner.store.static_account().creation_local_time()
581 }
582
583 pub fn identity_keys(&self) -> IdentityKeys {
585 let account = self.inner.store.static_account();
586 account.identity_keys()
587 }
588
589 pub async fn display_name(&self) -> StoreResult<Option<String>> {
591 self.store().device_display_name().await
592 }
593
594 pub async fn tracked_users(&self) -> StoreResult<HashSet<OwnedUserId>> {
599 let cache = self.store().cache().await?;
600 Ok(self.inner.identity_manager.key_query_manager.synced(&cache).await?.tracked_users())
601 }
602
603 #[cfg(feature = "automatic-room-key-forwarding")]
611 pub fn set_room_key_requests_enabled(&self, enable: bool) {
612 self.inner.key_request_machine.set_room_key_requests_enabled(enable)
613 }
614
615 pub fn are_room_key_requests_enabled(&self) -> bool {
620 self.inner.key_request_machine.are_room_key_requests_enabled()
621 }
622
623 #[cfg(feature = "automatic-room-key-forwarding")]
632 pub fn set_room_key_forwarding_enabled(&self, enable: bool) {
633 self.inner.key_request_machine.set_room_key_forwarding_enabled(enable)
634 }
635
636 pub fn is_room_key_forwarding_enabled(&self) -> bool {
640 self.inner.key_request_machine.is_room_key_forwarding_enabled()
641 }
642
643 pub async fn outgoing_requests(&self) -> StoreResult<Vec<OutgoingRequest>> {
651 let mut requests = Vec::new();
652
653 {
654 let store_cache = self.inner.store.cache().await?;
655 let account = store_cache.account().await?;
656 if let Some(r) = self.keys_for_upload(&account).await.map(|r| OutgoingRequest {
657 request_id: TransactionId::new(),
658 request: Arc::new(r.into()),
659 }) {
660 requests.push(r);
661 }
662 }
663
664 for request in self
665 .inner
666 .identity_manager
667 .users_for_key_query()
668 .await?
669 .into_iter()
670 .map(|(request_id, r)| OutgoingRequest { request_id, request: Arc::new(r.into()) })
671 {
672 requests.push(request);
673 }
674
675 requests.append(&mut self.inner.verification_machine.outgoing_messages());
676 requests.append(&mut self.inner.key_request_machine.outgoing_to_device_requests().await?);
677
678 #[cfg(feature = "experimental-x509-identity-verification")]
679 if let Some(signature_upload_request) =
680 self.inner.identity_manager.get_x509_signature_upload_request().await
681 {
682 requests.push(signature_upload_request);
683 }
684
685 Ok(requests)
686 }
687
688 pub fn query_keys_for_users<'a>(
709 &self,
710 users: impl IntoIterator<Item = &'a UserId>,
711 ) -> (OwnedTransactionId, KeysQueryRequest) {
712 self.inner.identity_manager.build_key_query_for_users(users)
713 }
714
715 pub async fn mark_request_as_sent<'a>(
725 &self,
726 request_id: &TransactionId,
727 response: impl Into<AnyIncomingResponse<'a>>,
728 ) -> OlmResult<()> {
729 match response.into() {
730 AnyIncomingResponse::KeysUpload(response) => {
731 Box::pin(self.receive_keys_upload_response(response)).await?;
732 }
733 AnyIncomingResponse::KeysQuery(response) => {
734 Box::pin(self.receive_keys_query_response(request_id, response)).await?;
735 }
736 AnyIncomingResponse::KeysClaim(response) => {
737 Box::pin(
738 self.inner.session_manager.receive_keys_claim_response(request_id, response),
739 )
740 .await?;
741 }
742 AnyIncomingResponse::ToDevice(_) => {
743 Box::pin(self.mark_to_device_request_as_sent(request_id)).await?;
744 }
745 AnyIncomingResponse::SigningKeysUpload(_) => {
746 Box::pin(self.receive_cross_signing_upload_response()).await?;
747 }
748 AnyIncomingResponse::SignatureUpload(_) => {
749 self.inner.verification_machine.mark_request_as_sent(request_id);
750 self.inner.key_request_machine.mark_outgoing_request_as_sent(request_id).await?;
751 #[cfg(feature = "experimental-x509-identity-verification")]
752 self.inner.identity_manager.mark_x509_signature_request_as_sent(request_id).await;
753 }
754 AnyIncomingResponse::RoomMessage(_) => {
755 self.inner.verification_machine.mark_request_as_sent(request_id);
756 }
757 AnyIncomingResponse::KeysBackup(_) => {
758 Box::pin(self.inner.backup_machine.mark_request_as_sent(request_id)).await?;
759 }
760 }
761
762 Ok(())
763 }
764
765 async fn receive_cross_signing_upload_response(&self) -> StoreResult<()> {
767 let identity = self.inner.user_identity.lock().await;
768 identity.mark_as_shared();
769
770 let changes = Changes { private_identity: Some(identity.clone()), ..Default::default() };
771
772 self.store().save_changes(changes).await
773 }
774
775 pub async fn bootstrap_cross_signing(
794 &self,
795 reset: bool,
796 ) -> Result<CrossSigningBootstrapRequests, BootstrapCrossSigningError> {
797 let identity = self.inner.user_identity.lock().await.clone();
802
803 let mut requests = if reset || identity.is_empty().await {
804 let handle = self.reset_cross_signing().await?;
805 let upload_signing_keys_req = handle.upload_signing_keys_req().clone();
806 let upload_signatures_req = handle.commit().await?;
807
808 CrossSigningBootstrapRequests {
809 upload_signing_keys_req,
810 upload_keys_req: None,
811 upload_signatures_req,
812 }
813 } else {
814 info!("Trying to upload the existing cross signing identity");
815 let upload_signing_keys_req = identity.as_upload_request().await;
816
817 let upload_signatures_req = identity
819 .sign_account(self.inner.store.static_account())
820 .await
821 .expect("Can't sign device keys");
822
823 CrossSigningBootstrapRequests {
824 upload_signing_keys_req,
825 upload_keys_req: None,
826 upload_signatures_req,
827 }
828 };
829
830 requests.upload_keys_req =
834 self.upload_device_keys().await?.map(|(_, request)| OutgoingRequest::from(request));
835
836 Ok(requests)
837 }
838
839 pub async fn reset_cross_signing(
845 &self,
846 ) -> Result<UncommittedCrossSigningReset, BootstrapCrossSigningError> {
847 info!("Creating new cross signing identity");
848
849 let (identity, upload_signing_keys_req, upload_signatures_req) = {
850 let cache = self.inner.store.cache().await?;
851 let account = cache.account().await?;
852 account
853 .bootstrap_cross_signing(
854 #[cfg(feature = "experimental-x509-identity-verification")]
855 self.inner.store.x509_signer().map(|s| s.raw()),
856 )
857 .await?
858 };
859
860 let public = identity
861 .to_public_identity()
862 .await
863 .expect("Couldn't create a public version of the identity from a new private identity");
864
865 Ok(UncommittedCrossSigningReset {
866 identity,
867 public,
868 upload_signing_keys_req,
869 upload_signatures_req,
870 olm_machine: self.clone(),
871 })
872 }
873
874 pub async fn upload_device_keys(
886 &self,
887 ) -> StoreResult<Option<(OwnedTransactionId, UploadKeysRequest)>> {
888 let cache = self.store().cache().await?;
889 let account = cache.account().await?;
890
891 Ok(self.keys_for_upload(&account).await.map(|request| (TransactionId::new(), request)))
892 }
893
894 async fn receive_keys_upload_response(&self, response: &UploadKeysResponse) -> OlmResult<()> {
901 self.inner
902 .store
903 .with_transaction(async |tr| {
904 let account = tr.account().await?;
905 account.receive_keys_upload_response(response)?;
906 Ok(())
907 })
908 .await
909 }
910
911 #[instrument(skip_all)]
939 pub async fn get_missing_sessions(
940 &self,
941 users: impl Iterator<Item = &UserId>,
942 ) -> StoreResult<Option<(OwnedTransactionId, KeysClaimRequest)>> {
943 self.inner.session_manager.get_missing_sessions(users).await
944 }
945
946 async fn receive_keys_query_response(
955 &self,
956 request_id: &TransactionId,
957 response: &KeysQueryResponse,
958 ) -> OlmResult<(DeviceChanges, IdentityChanges)> {
959 self.inner.identity_manager.receive_keys_query_response(request_id, response).await
960 }
961
962 async fn keys_for_upload(&self, account: &Account) -> Option<UploadKeysRequest> {
971 let (mut device_keys, one_time_keys, fallback_keys) = account.keys_for_upload();
972
973 if let Some(device_keys) = &mut device_keys {
983 let private_identity = self.store().private_identity();
984 let guard = private_identity.lock().await;
985
986 if guard.status().await.is_complete() {
987 guard.sign_device_keys(device_keys).await.expect(
988 "We should be able to sign our device keys since we confirmed that we \
989 have a complete set of private cross-signing keys",
990 );
991 }
992 }
993
994 if device_keys.is_none() && one_time_keys.is_empty() && fallback_keys.is_empty() {
995 None
996 } else {
997 let device_keys = device_keys.map(|d| d.to_raw());
998
999 Some(assign!(UploadKeysRequest::new(), {
1000 device_keys, one_time_keys, fallback_keys
1001 }))
1002 }
1003 }
1004
1005 async fn decrypt_to_device_event(
1028 &self,
1029 transaction: &mut StoreTransaction,
1030 event: &EncryptedToDeviceEvent,
1031 changes: &mut Changes,
1032 decryption_settings: &DecryptionSettings,
1033 ) -> Result<OlmDecryptionInfo, DecryptToDeviceError> {
1034 let mut decrypted = transaction
1036 .account()
1037 .await?
1038 .decrypt_to_device_event(&self.inner.store, event, decryption_settings)
1039 .await?;
1040
1041 self.check_to_device_event_is_not_from_dehydrated_device(&decrypted, &event.sender).await?;
1043
1044 self.handle_decrypted_to_device_event(transaction.cache(), &mut decrypted, changes).await?;
1047
1048 Ok(decrypted)
1049 }
1050
1051 #[instrument(
1052 skip_all,
1053 fields(room_id = ? content.room_id, session_id, message_index, shared_history = content.shared_history)
1057 )]
1058 async fn handle_key(
1059 &self,
1060 sender_key: Curve25519PublicKey,
1061 event: &DecryptedRoomKeyEvent,
1062 content: &MegolmV1AesSha2Content,
1063 ) -> OlmResult<Option<InboundGroupSession>> {
1064 let session =
1065 InboundGroupSession::from_room_key_content(sender_key, event.keys.ed25519, content);
1066
1067 match session {
1068 Ok(mut session) => {
1069 Span::current().record("session_id", session.session_id());
1070 Span::current().record("message_index", session.first_known_index());
1071
1072 let sender_data =
1073 SenderDataFinder::find_using_event(self.store(), sender_key, event, &session)
1074 .await?;
1075 session.sender_data = sender_data;
1076
1077 Ok(self.store().merge_received_group_session(session).await?)
1078 }
1079 Err(e) => {
1080 Span::current().record("session_id", &content.session_id);
1081 warn!("Received a room key event which contained an invalid session key: {e}");
1082
1083 Ok(None)
1084 }
1085 }
1086 }
1087
1088 #[instrument(skip_all, fields(algorithm = ?event.content.algorithm()))]
1090 async fn add_room_key(
1091 &self,
1092 sender_key: Curve25519PublicKey,
1093 event: &DecryptedRoomKeyEvent,
1094 ) -> OlmResult<Option<InboundGroupSession>> {
1095 match &event.content {
1096 RoomKeyContent::MegolmV1AesSha2(content) => {
1097 self.handle_key(sender_key, event, content).await
1098 }
1099 #[cfg(feature = "experimental-algorithms")]
1100 RoomKeyContent::MegolmV2AesSha2(content) => {
1101 self.handle_key(sender_key, event, content).await
1102 }
1103 RoomKeyContent::Unknown(_) => {
1104 warn!("Received a room key with an unsupported algorithm");
1105 Ok(None)
1106 }
1107 }
1108 }
1109
1110 #[instrument()]
1112 async fn receive_room_key_bundle_data(
1113 &self,
1114 sender_key: Curve25519PublicKey,
1115 event: &DecryptedRoomKeyBundleEvent,
1116 changes: &mut Changes,
1117 ) -> OlmResult<()> {
1118 let Some(sender_device_keys) = &event.sender_device_keys else {
1119 warn!("Received a room key bundle with no sender device keys: ignoring");
1120 return Ok(());
1121 };
1122
1123 let sender_device_data =
1128 DeviceData::try_from(sender_device_keys).expect("failed to verify sender device keys");
1129 let sender_device = self.store().wrap_device_data(sender_device_data).await?;
1130
1131 changes.received_room_key_bundles.push(StoredRoomKeyBundleData {
1132 sender_user: event.sender.clone(),
1133 sender_data: SenderData::from_device(&sender_device),
1134 sender_key,
1135 bundle_data: event.content.clone(),
1136 });
1137 Ok(())
1138 }
1139
1140 fn add_withheld_info(&self, changes: &mut Changes, event: &RoomKeyWithheldEvent) {
1141 debug!(?event.content, "Processing `m.room_key.withheld` event");
1142
1143 if let RoomKeyWithheldContent::MegolmV1AesSha2(
1144 MegolmV1AesSha2WithheldContent::BlackListed(c)
1145 | MegolmV1AesSha2WithheldContent::Unverified(c)
1146 | MegolmV1AesSha2WithheldContent::Unauthorised(c)
1147 | MegolmV1AesSha2WithheldContent::Unavailable(c),
1148 ) = &event.content
1149 {
1150 changes
1151 .withheld_session_info
1152 .entry(c.room_id.to_owned())
1153 .or_default()
1154 .insert(c.session_id.to_owned(), event.to_owned().into());
1155 }
1156 }
1157
1158 #[cfg(test)]
1159 pub(crate) async fn create_outbound_group_session_with_defaults_test_helper(
1160 &self,
1161 room_id: &RoomId,
1162 ) -> OlmResult<()> {
1163 let (_, session) = self
1164 .inner
1165 .group_session_manager
1166 .create_outbound_group_session(
1167 room_id,
1168 EncryptionSettings::default(),
1169 SenderData::unknown(),
1170 )
1171 .await?;
1172
1173 self.store().save_inbound_group_sessions(&[session]).await?;
1174
1175 Ok(())
1176 }
1177
1178 #[cfg(test)]
1179 #[allow(dead_code)]
1180 pub(crate) async fn create_inbound_session_test_helper(
1181 &self,
1182 room_id: &RoomId,
1183 ) -> OlmResult<InboundGroupSession> {
1184 let (_, session) = self
1185 .inner
1186 .group_session_manager
1187 .create_outbound_group_session(
1188 room_id,
1189 EncryptionSettings::default(),
1190 SenderData::unknown(),
1191 )
1192 .await?;
1193
1194 Ok(session)
1195 }
1196
1197 pub async fn encrypt_room_event(
1214 &self,
1215 room_id: &RoomId,
1216 content: impl MessageLikeEventContent,
1217 ) -> MegolmResult<RawEncryptionResult> {
1218 let event_type = content.event_type().to_string();
1219 let content = Raw::new(&content)?.cast_unchecked();
1220 self.encrypt_room_event_raw(room_id, &event_type, &content).await
1221 }
1222
1223 pub async fn encrypt_room_event_raw(
1243 &self,
1244 room_id: &RoomId,
1245 event_type: &str,
1246 content: &Raw<AnyMessageLikeEventContent>,
1247 ) -> MegolmResult<RawEncryptionResult> {
1248 self.inner.group_session_manager.encrypt(room_id, event_type, content).await.map(|result| {
1249 RawEncryptionResult {
1250 content: result.content,
1251 encryption_info: self
1252 .own_encryption_info(result.algorithm, result.session_id.to_string()),
1253 }
1254 })
1255 }
1256
1257 fn own_encryption_info(
1258 &self,
1259 algorithm: EventEncryptionAlgorithm,
1260 session_id: String,
1261 ) -> EncryptionInfo {
1262 let identity_keys = self.identity_keys();
1263
1264 let algorithm_info = match algorithm {
1265 EventEncryptionAlgorithm::MegolmV1AesSha2 => AlgorithmInfo::MegolmV1AesSha2 {
1266 curve25519_key: identity_keys.curve25519.to_base64(),
1267 sender_claimed_keys: BTreeMap::from([(
1268 DeviceKeyAlgorithm::Ed25519,
1269 identity_keys.ed25519.to_base64(),
1270 )]),
1271 session_id: Some(session_id),
1272 },
1273 EventEncryptionAlgorithm::OlmV1Curve25519AesSha2 => {
1274 AlgorithmInfo::OlmV1Curve25519AesSha2 {
1275 curve25519_public_key_base64: identity_keys.curve25519.to_base64(),
1276 }
1277 }
1278 _ => unreachable!(
1279 "Only MegolmV1AesSha2 and OlmV1Curve25519AesSha2 are supported on this level"
1280 ),
1281 };
1282
1283 EncryptionInfo {
1284 sender: self.inner.user_id.clone(),
1285 sender_device: Some(self.inner.device_id.clone()),
1286 forwarder: None,
1287 algorithm_info,
1288 verification_state: VerificationState::Verified,
1289 }
1290 }
1291
1292 #[cfg(feature = "experimental-encrypted-state-events")]
1304 pub async fn encrypt_state_event<C, K>(
1305 &self,
1306 room_id: &RoomId,
1307 content: C,
1308 state_key: K,
1309 ) -> MegolmResult<Raw<RoomEncryptedEventContent>>
1310 where
1311 C: StateEventContent,
1312 C::StateKey: Borrow<K>,
1313 K: AsRef<str>,
1314 {
1315 let event_type = content.event_type().to_string();
1316 let content = Raw::new(&content)?.cast_unchecked();
1317 self.encrypt_state_event_raw(room_id, &event_type, state_key.as_ref(), &content).await
1318 }
1319
1320 #[cfg(feature = "experimental-encrypted-state-events")]
1337 pub async fn encrypt_state_event_raw(
1338 &self,
1339 room_id: &RoomId,
1340 event_type: &str,
1341 state_key: &str,
1342 content: &Raw<AnyStateEventContent>,
1343 ) -> MegolmResult<Raw<RoomEncryptedEventContent>> {
1344 self.inner
1345 .group_session_manager
1346 .encrypt_state(room_id, event_type, state_key, content)
1347 .await
1348 }
1349
1350 pub async fn discard_room_key(&self, room_id: &RoomId) -> StoreResult<bool> {
1361 self.inner.group_session_manager.invalidate_group_session(room_id).await
1362 }
1363
1364 pub async fn share_room_key(
1383 &self,
1384 room_id: &RoomId,
1385 users: impl Iterator<Item = &UserId>,
1386 encryption_settings: impl Into<EncryptionSettings>,
1387 ) -> OlmResult<Vec<Arc<ToDeviceRequest>>> {
1388 self.inner.group_session_manager.share_room_key(room_id, users, encryption_settings).await
1389 }
1390
1391 #[cfg(feature = "experimental-send-custom-to-device")]
1404 pub async fn encrypt_content_for_devices(
1405 &self,
1406 devices: Vec<DeviceData>,
1407 event_type: &str,
1408 content: &Value,
1409 share_strategy: CollectStrategy,
1410 ) -> OlmResult<(Vec<ToDeviceRequest>, Vec<(DeviceData, WithheldCode)>)> {
1411 let mut changes = Changes::default();
1412
1413 let (allowed_devices, mut blocked_devices) =
1414 split_devices_for_share_strategy(&self.inner.store, devices, share_strategy).await?;
1415
1416 let result = self
1417 .inner
1418 .group_session_manager
1419 .encrypt_content_for_devices(allowed_devices, event_type, content.clone(), &mut changes)
1420 .await;
1421
1422 if !changes.is_empty() {
1424 let session_count = changes.sessions.len();
1425
1426 self.inner.store.save_changes(changes).await?;
1427
1428 trace!(
1429 session_count = session_count,
1430 "Stored the changed sessions after encrypting a custom to-device event"
1431 );
1432 }
1433
1434 result.map(|(to_device_requests, mut withheld)| {
1435 withheld.append(&mut blocked_devices);
1436 (to_device_requests, withheld)
1437 })
1438 }
1439 pub async fn share_room_key_bundle_data(
1444 &self,
1445 user_id: &UserId,
1446 collect_strategy: &CollectStrategy,
1447 bundle_data: RoomKeyBundleContent,
1448 ) -> OlmResult<Vec<ToDeviceRequest>> {
1449 self.inner
1450 .group_session_manager
1451 .share_room_key_bundle_data(user_id, collect_strategy, bundle_data)
1452 .await
1453 }
1454
1455 #[deprecated(note = "Use OlmMachine::receive_verification_event instead", since = "0.7.0")]
1463 pub async fn receive_unencrypted_verification_event(
1464 &self,
1465 event: &AnyMessageLikeEvent,
1466 ) -> StoreResult<()> {
1467 self.inner.verification_machine.receive_any_event(event).await
1468 }
1469
1470 pub async fn receive_verification_event(&self, event: &AnyMessageLikeEvent) -> StoreResult<()> {
1483 self.inner.verification_machine.receive_any_event(event).await
1484 }
1485
1486 #[instrument(
1492 skip_all,
1493 fields(
1494 sender_key = ?decrypted.result.sender_key,
1495 event_type = decrypted.result.event.event_type(),
1496 ),
1497 )]
1498 async fn handle_decrypted_to_device_event(
1499 &self,
1500 cache: &StoreCache,
1501 decrypted: &mut OlmDecryptionInfo,
1502 changes: &mut Changes,
1503 ) -> OlmResult<()> {
1504 debug!(
1505 sender_device_keys =
1506 ?decrypted.result.event.sender_device_keys().map(|k| (k.curve25519_key(), k.ed25519_key())).unwrap_or((None, None)),
1507 "Received a decrypted to-device event",
1508 );
1509
1510 match &*decrypted.result.event {
1511 AnyDecryptedOlmEvent::RoomKey(e) => {
1512 let session = self.add_room_key(decrypted.result.sender_key, e).await?;
1513 decrypted.inbound_group_session = session;
1514 }
1515 AnyDecryptedOlmEvent::ForwardedRoomKey(e) => {
1516 let session = self
1517 .inner
1518 .key_request_machine
1519 .receive_forwarded_room_key(decrypted.result.sender_key, e)
1520 .await?;
1521 decrypted.inbound_group_session = session;
1522 }
1523 AnyDecryptedOlmEvent::SecretSend(e) => {
1524 let name = self
1525 .inner
1526 .key_request_machine
1527 .receive_secret_event(cache, decrypted.result.sender_key, e, changes)
1528 .await?;
1529
1530 if let Ok(ToDeviceEvents::SecretSend(mut e)) =
1533 decrypted.result.raw_event.deserialize_as()
1534 {
1535 e.content.secret_name = name;
1536 decrypted.result.raw_event = Raw::from_json(to_raw_value(&e)?);
1537 }
1538
1539 if enabled!(tracing::Level::DEBUG) {
1540 let cross_signing_status = self.cross_signing_status().await;
1541 let backup_enabled = self.backup_machine().enabled().await;
1542 debug!(
1543 ?cross_signing_status,
1544 backup_enabled, "Status after receiving secret event"
1545 );
1546 }
1547 }
1548 AnyDecryptedOlmEvent::Dummy(_) => {
1549 debug!("Received an `m.dummy` event");
1550 }
1551 AnyDecryptedOlmEvent::RoomKeyBundle(e) => {
1552 debug!("Received a room key bundle event {:?}", e);
1553 self.receive_room_key_bundle_data(decrypted.result.sender_key, e, changes).await?;
1554 }
1555 #[cfg(feature = "experimental-push-secrets")]
1556 AnyDecryptedOlmEvent::SecretPush(e) => {
1557 self.inner
1558 .key_request_machine
1559 .receive_secret_push_event(&decrypted.result.sender_key, e, changes)
1560 .await?;
1561 }
1562 AnyDecryptedOlmEvent::Custom(_) => {
1563 warn!("Received an unexpected encrypted to-device event");
1564 }
1565 }
1566
1567 Ok(())
1568 }
1569
1570 async fn handle_verification_event(&self, event: &ToDeviceEvents) {
1571 if let Err(e) = self.inner.verification_machine.receive_any_event(event).await {
1572 error!("Error handling a verification event: {e:?}");
1573 }
1574 }
1575
1576 async fn mark_to_device_request_as_sent(&self, request_id: &TransactionId) -> StoreResult<()> {
1578 self.inner.verification_machine.mark_request_as_sent(request_id);
1579 self.inner.key_request_machine.mark_outgoing_request_as_sent(request_id).await?;
1580 self.inner.group_session_manager.mark_request_as_sent(request_id).await?;
1581 self.inner.session_manager.mark_outgoing_request_as_sent(request_id);
1582 Ok(())
1583 }
1584
1585 pub fn get_verification(&self, user_id: &UserId, flow_id: &str) -> Option<Verification> {
1587 self.inner.verification_machine.get_verification(user_id, flow_id)
1588 }
1589
1590 pub fn get_verification_request(
1592 &self,
1593 user_id: &UserId,
1594 flow_id: impl AsRef<str>,
1595 ) -> Option<VerificationRequest> {
1596 self.inner.verification_machine.get_request(user_id, flow_id)
1597 }
1598
1599 pub fn get_verification_requests(&self, user_id: &UserId) -> Vec<VerificationRequest> {
1601 self.inner.verification_machine.get_requests(user_id)
1602 }
1603
1604 async fn handle_to_device_event(&self, changes: &mut Changes, event: &ToDeviceEvents) {
1609 use crate::types::events::ToDeviceEvents::*;
1610
1611 match event {
1612 RoomKeyRequest(e) => self.inner.key_request_machine.receive_incoming_key_request(e),
1618 SecretRequest(e) => self.inner.key_request_machine.receive_incoming_secret_request(e),
1619 RoomKeyWithheld(e) => self.add_withheld_info(changes, e),
1620 KeyVerificationAccept(..)
1621 | KeyVerificationCancel(..)
1622 | KeyVerificationKey(..)
1623 | KeyVerificationMac(..)
1624 | KeyVerificationRequest(..)
1625 | KeyVerificationReady(..)
1626 | KeyVerificationDone(..)
1627 | KeyVerificationStart(..) => {
1628 self.handle_verification_event(event).await;
1629 }
1630
1631 Custom(_) | Dummy(_) => {}
1633
1634 RoomEncrypted(_) => {}
1636
1637 SecretSend(_) | RoomKey(_) | ForwardedRoomKey(_) => {}
1640 }
1641 }
1642
1643 fn record_message_id(event: &Raw<AnyToDeviceEvent>) {
1644 use serde::Deserialize;
1645
1646 #[derive(Deserialize)]
1647 struct ContentStub<'a> {
1648 #[serde(borrow, rename = "org.matrix.msgid")]
1649 message_id: Option<&'a str>,
1650 }
1651 #[derive(Deserialize)]
1652 struct ToDeviceStub<'a> {
1653 sender: &'a str,
1654 #[serde(rename = "type")]
1655 event_type: &'a str,
1656 #[serde(borrow)]
1657 content: ContentStub<'a>,
1658 }
1659
1660 if let Ok(event) = event.deserialize_as_unchecked::<ToDeviceStub<'_>>() {
1661 Span::current().record("sender", event.sender);
1662 Span::current().record("event_type", event.event_type);
1663 Span::current().record("message_id", event.content.message_id);
1664 }
1665 }
1666
1667 #[instrument(skip_all, fields(sender, event_type, message_id))]
1675 async fn receive_to_device_event(
1676 &self,
1677 transaction: &mut StoreTransaction,
1678 changes: &mut Changes,
1679 raw_event: Raw<AnyToDeviceEvent>,
1680 decryption_settings: &DecryptionSettings,
1681 ) -> Option<ProcessedToDeviceEvent> {
1682 Self::record_message_id(&raw_event);
1683
1684 let event: ToDeviceEvents = match raw_event.deserialize_as() {
1685 Ok(e) => e,
1686 Err(e) => {
1687 warn!("Received an invalid to-device event: {e}");
1689 return Some(ProcessedToDeviceEvent::Invalid(raw_event));
1690 }
1691 };
1692
1693 debug!("Received a to-device event");
1694
1695 match event {
1696 ToDeviceEvents::RoomEncrypted(e) => {
1697 self.receive_encrypted_to_device_event(
1698 transaction,
1699 changes,
1700 raw_event,
1701 e,
1702 decryption_settings,
1703 )
1704 .await
1705 }
1706 e => {
1707 self.handle_to_device_event(changes, &e).await;
1708 Some(ProcessedToDeviceEvent::PlainText(raw_event))
1709 }
1710 }
1711 }
1712
1713 async fn receive_encrypted_to_device_event(
1727 &self,
1728 transaction: &mut StoreTransaction,
1729 changes: &mut Changes,
1730 mut raw_event: Raw<AnyToDeviceEvent>,
1731 e: ToDeviceEvent<ToDeviceEncryptedEventContent>,
1732 decryption_settings: &DecryptionSettings,
1733 ) -> Option<ProcessedToDeviceEvent> {
1734 let decrypted = match self
1735 .decrypt_to_device_event(transaction, &e, changes, decryption_settings)
1736 .await
1737 {
1738 Ok(decrypted) => decrypted,
1739 Err(DecryptToDeviceError::OlmError(err)) => {
1740 let reason = if let OlmError::UnverifiedSenderDevice = &err {
1741 ToDeviceUnableToDecryptReason::UnverifiedSenderDevice
1742 } else {
1743 ToDeviceUnableToDecryptReason::DecryptionFailure
1744 };
1745
1746 if let OlmError::SessionWedged(sender, curve_key) = err
1747 && let Err(e) =
1748 self.inner.session_manager.mark_device_as_wedged(&sender, curve_key).await
1749 {
1750 error!(
1751 error = ?e,
1752 "Couldn't mark device to be unwedged",
1753 );
1754 }
1755
1756 return Some(ProcessedToDeviceEvent::UnableToDecrypt {
1757 encrypted_event: raw_event,
1758 utd_info: ToDeviceUnableToDecryptInfo { reason },
1759 });
1760 }
1761 Err(DecryptToDeviceError::FromDehydratedDevice) => return None,
1762 };
1763
1764 match decrypted.session {
1766 SessionType::New(s) | SessionType::Existing(s) => {
1767 changes.sessions.push(s);
1768 }
1769 }
1770
1771 changes.message_hashes.push(decrypted.message_hash);
1772
1773 if let Some(group_session) = decrypted.inbound_group_session {
1774 changes.inbound_group_sessions.push(group_session);
1775 }
1776
1777 match decrypted.result.raw_event.deserialize_as() {
1778 Ok(event) => {
1779 self.handle_to_device_event(changes, &event).await;
1780
1781 raw_event = event
1782 .serialize_zeroized()
1783 .expect("Zeroizing and reserializing our events should always work")
1784 .cast();
1785 }
1786 Err(e) => {
1787 warn!("Received an invalid encrypted to-device event: {e}");
1788 raw_event = decrypted.result.raw_event;
1789 }
1790 }
1791
1792 Some(ProcessedToDeviceEvent::Decrypted {
1793 raw: raw_event,
1794 encryption_info: decrypted.result.encryption_info,
1795 })
1796 }
1797
1798 async fn check_to_device_event_is_not_from_dehydrated_device(
1801 &self,
1802 decrypted: &OlmDecryptionInfo,
1803 sender_user_id: &UserId,
1804 ) -> Result<(), DecryptToDeviceError> {
1805 if self.to_device_event_is_from_dehydrated_device(decrypted, sender_user_id).await? {
1806 warn!(
1807 sender = ?sender_user_id,
1808 session = ?decrypted.session,
1809 "Received a to-device event from a dehydrated device. This is unexpected: ignoring event"
1810 );
1811 Err(DecryptToDeviceError::FromDehydratedDevice)
1812 } else {
1813 Ok(())
1814 }
1815 }
1816
1817 async fn to_device_event_is_from_dehydrated_device(
1823 &self,
1824 decrypted: &OlmDecryptionInfo,
1825 sender_user_id: &UserId,
1826 ) -> OlmResult<bool> {
1827 if let Some(device_keys) = decrypted.result.event.sender_device_keys() {
1829 if device_keys.dehydrated.unwrap_or(false) {
1835 return Ok(true);
1836 }
1837 }
1842
1843 Ok(self
1845 .store()
1846 .get_device_from_curve_key(sender_user_id, decrypted.result.sender_key)
1847 .await?
1848 .is_some_and(|d| d.is_dehydrated()))
1849 }
1850
1851 #[instrument(skip_all)]
1871 pub async fn receive_sync_changes(
1872 &self,
1873 sync_changes: EncryptionSyncChanges<'_>,
1874 decryption_settings: &DecryptionSettings,
1875 ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Vec<RoomKeyInfo>)> {
1876 self.receive_sync_changes_impl(sync_changes, decryption_settings, true).await
1877 }
1878
1879 #[instrument(skip_all)]
1899 pub async fn receive_sync_changes_msc4186(
1900 &self,
1901 sync_changes: EncryptionSyncChanges<'_>,
1902 decryption_settings: &DecryptionSettings,
1903 ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Vec<RoomKeyInfo>)> {
1904 self.receive_sync_changes_impl(sync_changes, decryption_settings, false).await
1905 }
1906
1907 async fn receive_sync_changes_impl(
1917 &self,
1918 sync_changes: EncryptionSyncChanges<'_>,
1919 decryption_settings: &DecryptionSettings,
1920 is_missing_count_zero: bool,
1921 ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Vec<RoomKeyInfo>)> {
1922 let mut store_transaction = self.inner.store.transaction().await;
1923
1924 {
1925 let account = store_transaction.account().await?;
1926 account.update_key_counts(
1927 sync_changes.one_time_keys_counts,
1928 sync_changes.unused_fallback_keys,
1929 is_missing_count_zero,
1930 )
1931 }
1932
1933 let (events, changes) = self
1934 .preprocess_sync_changes(&mut store_transaction, sync_changes, decryption_settings)
1935 .await?;
1936
1937 let room_key_updates: Vec<_> =
1940 changes.inbound_group_sessions.iter().map(RoomKeyInfo::from).collect();
1941
1942 self.store().save_changes(changes).await?;
1943 store_transaction.commit().await?;
1944
1945 Ok((events, room_key_updates))
1946 }
1947
1948 pub(crate) async fn preprocess_sync_changes(
1966 &self,
1967 transaction: &mut StoreTransaction,
1968 sync_changes: EncryptionSyncChanges<'_>,
1969 decryption_settings: &DecryptionSettings,
1970 ) -> OlmResult<(Vec<ProcessedToDeviceEvent>, Changes)> {
1971 let mut events: Vec<ProcessedToDeviceEvent> = self
1973 .inner
1974 .verification_machine
1975 .garbage_collect()
1976 .iter()
1977 .map(|e| ProcessedToDeviceEvent::PlainText(e.clone()))
1981 .collect();
1982 let mut changes = Default::default();
1985
1986 if let Err(e) = self
1987 .inner
1988 .identity_manager
1989 .receive_device_changes(
1990 transaction.cache(),
1991 sync_changes.changed_devices.changed.iter().map(|u| u.as_ref()),
1992 )
1993 .await
1994 {
1995 error!(error = ?e, "Error marking a tracked user as changed");
1996 }
1997
1998 for raw_event in sync_changes.to_device_events {
1999 let processed_event = Box::pin(self.receive_to_device_event(
2000 transaction,
2001 &mut changes,
2002 raw_event,
2003 decryption_settings,
2004 ))
2005 .await;
2006
2007 if let Some(processed_event) = processed_event {
2008 events.push(processed_event);
2009 }
2010 }
2011
2012 let changed_sessions = self
2013 .inner
2014 .key_request_machine
2015 .collect_incoming_key_requests(transaction.cache())
2016 .await?;
2017
2018 changes.sessions.extend(changed_sessions);
2019 changes.next_batch_token = sync_changes.next_batch_token;
2020
2021 Ok((events, changes))
2022 }
2023
2024 pub async fn request_room_key(
2039 &self,
2040 event: &Raw<EncryptedEvent>,
2041 room_id: &RoomId,
2042 ) -> MegolmResult<(Option<OutgoingRequest>, OutgoingRequest)> {
2043 let event = event.deserialize()?;
2044 self.inner.key_request_machine.request_key(room_id, &event).await
2045 }
2046
2047 async fn get_room_event_verification_state(
2060 &self,
2061 session: &InboundGroupSession,
2062 sender: &UserId,
2063 ) -> MegolmResult<(VerificationState, Option<OwnedDeviceId>)> {
2064 let sender_data = self.get_or_update_sender_data(session, sender).await?;
2065
2066 let (verification_state, device_id) = match sender_data.user_id() {
2075 Some(i) if i != sender => {
2076 (VerificationState::Unverified(VerificationLevel::MismatchedSender), None)
2077 }
2078
2079 Some(_) | None => {
2080 sender_data_to_verification_state(sender_data, session.has_been_imported())
2081 }
2082 };
2083
2084 Ok((verification_state, device_id))
2085 }
2086
2087 async fn get_or_update_sender_data(
2102 &self,
2103 session: &InboundGroupSession,
2104 sender: &UserId,
2105 ) -> MegolmResult<SenderData> {
2106 let sender_data = if session.sender_data.should_recalculate() {
2107 let calculated_sender_data = SenderDataFinder::find_using_curve_key(
2128 self.store(),
2129 session.sender_key(),
2130 sender,
2131 session,
2132 )
2133 .await?;
2134
2135 if calculated_sender_data.compare_trust_level(&session.sender_data).is_gt() {
2137 let mut new_session = session.clone();
2139 new_session.sender_data = calculated_sender_data.clone();
2140 self.store().save_inbound_group_sessions(&[new_session]).await?;
2141
2142 calculated_sender_data
2144 } else {
2145 session.sender_data.clone()
2147 }
2148 } else {
2149 session.sender_data.clone()
2150 };
2151
2152 Ok(sender_data)
2153 }
2154
2155 pub async fn query_missing_secrets_from_other_sessions(&self) -> StoreResult<bool> {
2180 let identity = self.inner.user_identity.lock().await;
2181 let mut secrets = identity.get_missing_secrets().await;
2182
2183 if self.store().load_backup_keys().await?.decryption_key.is_none() {
2184 secrets.push(SecretName::RecoveryKey);
2185 }
2186
2187 if secrets.is_empty() {
2188 debug!("No missing requests to query");
2189 return Ok(false);
2190 }
2191
2192 let secret_requests = GossipMachine::request_missing_secrets(self.user_id(), secrets);
2193
2194 let unsent_request = self.store().get_unsent_secret_requests().await?;
2196 let not_yet_requested = secret_requests
2197 .into_iter()
2198 .filter(|request| !unsent_request.iter().any(|unsent| unsent.info == request.info))
2199 .collect_vec();
2200
2201 if not_yet_requested.is_empty() {
2202 debug!("The missing secrets have already been requested");
2203 Ok(false)
2204 } else {
2205 debug!("Requesting missing secrets");
2206
2207 let changes = Changes { key_requests: not_yet_requested, ..Default::default() };
2208
2209 self.store().save_changes(changes).await?;
2210 Ok(true)
2211 }
2212 }
2213
2214 #[cfg(feature = "experimental-push-secrets")]
2222 pub async fn push_secret_to_verified_devices(
2223 &self,
2224 secret_name: SecretName,
2225 ) -> Result<HashMap<OwnedDeviceId, OlmError>, SecretPushError> {
2226 self.inner.key_request_machine.push_secret_to_verified_devices(secret_name).await
2227 }
2228
2229 async fn get_encryption_info(
2235 &self,
2236 session: &InboundGroupSession,
2237 sender: &UserId,
2238 ) -> MegolmResult<Arc<EncryptionInfo>> {
2239 let (verification_state, device_id) =
2240 self.get_room_event_verification_state(session, sender).await?;
2241
2242 Ok(Arc::new(EncryptionInfo {
2243 sender: sender.to_owned(),
2244 sender_device: device_id,
2245 forwarder: session.forwarder_data.as_ref().and_then(|data| {
2246 data.device_id().map(|device_id| ForwarderInfo {
2251 device_id: device_id.to_owned(),
2252 user_id: data.user_id().to_owned(),
2253 })
2254 }),
2255 algorithm_info: AlgorithmInfo::MegolmV1AesSha2 {
2256 curve25519_key: session.sender_key().to_base64(),
2257 sender_claimed_keys: session
2258 .signing_keys()
2259 .iter()
2260 .map(|(k, v)| (k.to_owned(), v.to_base64()))
2261 .collect(),
2262 session_id: Some(session.session_id().to_owned()),
2263 },
2264 verification_state,
2265 }))
2266 }
2267
2268 async fn decrypt_megolm_events(
2269 &self,
2270 room_id: &RoomId,
2271 event: &EncryptedEvent,
2272 content: &SupportedEventEncryptionSchemes<'_>,
2273 decryption_settings: &DecryptionSettings,
2274 ) -> MegolmResult<(JsonObject, Arc<EncryptionInfo>)> {
2275 let session =
2276 self.get_inbound_group_session_or_error(room_id, content.session_id()).await?;
2277
2278 Span::current().record("sender_key", debug(session.sender_key()));
2284
2285 let result = session.decrypt(event).await;
2286 match result {
2287 Ok((decrypted_event, _)) => {
2288 let encryption_info = self.get_encryption_info(&session, &event.sender).await?;
2289
2290 self.check_sender_trust_requirement(
2291 &session,
2292 &encryption_info,
2293 &decryption_settings.sender_device_trust_requirement,
2294 )?;
2295
2296 Ok((decrypted_event, encryption_info))
2297 }
2298 Err(error) => Err(
2299 if let MegolmError::Decryption(DecryptionError::UnknownMessageIndex(_, _)) = error {
2300 let withheld_code = self
2301 .inner
2302 .store
2303 .get_withheld_info(room_id, content.session_id())
2304 .await?
2305 .map(|e| e.content.withheld_code());
2306
2307 if withheld_code.is_some() {
2308 MegolmError::MissingRoomKey(withheld_code)
2311 } else {
2312 error
2313 }
2314 } else {
2315 error
2316 },
2317 ),
2318 }
2319 }
2320
2321 fn check_sender_trust_requirement(
2327 &self,
2328 session: &InboundGroupSession,
2329 encryption_info: &EncryptionInfo,
2330 trust_requirement: &TrustRequirement,
2331 ) -> MegolmResult<()> {
2332 trace!(
2333 verification_state = ?encryption_info.verification_state,
2334 ?trust_requirement, "check_sender_trust_requirement",
2335 );
2336
2337 let verification_level = match &encryption_info.verification_state {
2340 VerificationState::Verified => return Ok(()),
2341 VerificationState::Unverified(verification_level) => verification_level,
2342 };
2343
2344 let ok = match trust_requirement {
2345 TrustRequirement::Untrusted => true,
2346
2347 TrustRequirement::CrossSignedOrLegacy => {
2348 let legacy_session = match session.sender_data {
2355 SenderData::DeviceInfo { legacy_session, .. } => legacy_session,
2356 SenderData::UnknownDevice { legacy_session, .. } => legacy_session,
2357 _ => false,
2358 };
2359
2360 match (verification_level, legacy_session) {
2370 (VerificationLevel::UnverifiedIdentity, _) => true,
2372
2373 (VerificationLevel::UnsignedDevice, true) => true,
2375
2376 (VerificationLevel::None(_), true) => true,
2378
2379 (VerificationLevel::VerificationViolation, _)
2381 | (VerificationLevel::MismatchedSender, _)
2382 | (VerificationLevel::UnsignedDevice, false)
2383 | (VerificationLevel::None(_), false) => false,
2384 }
2385 }
2386
2387 TrustRequirement::CrossSigned => match verification_level {
2391 VerificationLevel::UnverifiedIdentity => true,
2392
2393 VerificationLevel::VerificationViolation
2394 | VerificationLevel::MismatchedSender
2395 | VerificationLevel::UnsignedDevice
2396 | VerificationLevel::None(_) => false,
2397 },
2398 };
2399
2400 if ok {
2401 Ok(())
2402 } else {
2403 Err(MegolmError::SenderIdentityNotTrusted(verification_level.clone()))
2404 }
2405 }
2406
2407 async fn get_inbound_group_session_or_error(
2412 &self,
2413 room_id: &RoomId,
2414 session_id: &str,
2415 ) -> MegolmResult<InboundGroupSession> {
2416 match self.store().get_inbound_group_session(room_id, session_id).await? {
2417 Some(session) => Ok(session),
2418 None => {
2419 let withheld_code = self
2420 .inner
2421 .store
2422 .get_withheld_info(room_id, session_id)
2423 .await?
2424 .map(|e| e.content.withheld_code());
2425 Err(MegolmError::MissingRoomKey(withheld_code))
2426 }
2427 }
2428 }
2429
2430 pub async fn try_decrypt_room_event(
2444 &self,
2445 raw_event: &Raw<EncryptedEvent>,
2446 room_id: &RoomId,
2447 decryption_settings: &DecryptionSettings,
2448 ) -> Result<RoomEventDecryptionResult, CryptoStoreError> {
2449 match self.decrypt_room_event_inner(raw_event, room_id, true, decryption_settings).await {
2450 Ok(decrypted) => Ok(RoomEventDecryptionResult::Decrypted(decrypted)),
2451 Err(err) => Ok(RoomEventDecryptionResult::UnableToDecrypt(megolm_error_to_utd_info(
2452 raw_event, err,
2453 )?)),
2454 }
2455 }
2456
2457 pub async fn decrypt_room_event(
2465 &self,
2466 event: &Raw<EncryptedEvent>,
2467 room_id: &RoomId,
2468 decryption_settings: &DecryptionSettings,
2469 ) -> MegolmResult<DecryptedRoomEvent> {
2470 self.decrypt_room_event_inner(event, room_id, true, decryption_settings).await
2471 }
2472
2473 #[instrument(name = "decrypt_room_event", skip_all, fields(?room_id, event_id, origin_server_ts, sender, algorithm, session_id, message_index, sender_key))]
2474 async fn decrypt_room_event_inner(
2475 &self,
2476 event: &Raw<EncryptedEvent>,
2477 room_id: &RoomId,
2478 decrypt_unsigned: bool,
2479 decryption_settings: &DecryptionSettings,
2480 ) -> MegolmResult<DecryptedRoomEvent> {
2481 let _timer = timer!(tracing::Level::TRACE, "_method");
2482
2483 let event = event.deserialize()?;
2484
2485 Span::current()
2486 .record("sender", debug(&event.sender))
2487 .record("event_id", debug(&event.event_id))
2488 .record(
2489 "origin_server_ts",
2490 timestamp_to_iso8601(event.origin_server_ts)
2491 .unwrap_or_else(|| "<out of range>".to_owned()),
2492 )
2493 .record("algorithm", debug(event.content.algorithm()));
2494
2495 let content: SupportedEventEncryptionSchemes<'_> = match &event.content.scheme {
2496 RoomEventEncryptionScheme::MegolmV1AesSha2(c) => {
2497 Span::current().record("sender_key", debug(c.sender_key));
2498 c.into()
2499 }
2500 #[cfg(feature = "experimental-algorithms")]
2501 RoomEventEncryptionScheme::MegolmV2AesSha2(c) => c.into(),
2502 RoomEventEncryptionScheme::Unknown(_) => {
2503 warn!("Received an encrypted room event with an unsupported algorithm");
2504 return Err(EventError::UnsupportedAlgorithm.into());
2505 }
2506 };
2507
2508 Span::current().record("session_id", content.session_id());
2509 Span::current().record("message_index", content.message_index());
2510
2511 let result =
2512 self.decrypt_megolm_events(room_id, &event, &content, decryption_settings).await;
2513
2514 if let Err(e) = &result {
2515 #[cfg(feature = "automatic-room-key-forwarding")]
2516 match e {
2517 MegolmError::MissingRoomKey(_)
2520 | MegolmError::Decryption(DecryptionError::UnknownMessageIndex(_, _)) => {
2521 self.inner
2522 .key_request_machine
2523 .create_outgoing_key_request(room_id, &event)
2524 .await?;
2525 }
2526 _ => {}
2527 }
2528
2529 warn!("Failed to decrypt a room event: {e}");
2530 }
2531
2532 let (mut decrypted_event, encryption_info) = result?;
2533
2534 let mut unsigned_encryption_info = None;
2535 if decrypt_unsigned {
2536 unsigned_encryption_info = self
2538 .decrypt_unsigned_events(&mut decrypted_event, room_id, decryption_settings)
2539 .await;
2540 }
2541
2542 let decrypted_event =
2543 serde_json::from_value::<Raw<AnyTimelineEvent>>(decrypted_event.into())?;
2544
2545 #[cfg(feature = "experimental-encrypted-state-events")]
2546 self.verify_packed_state_key(&event, &decrypted_event)?;
2547
2548 Ok(DecryptedRoomEvent { event: decrypted_event, encryption_info, unsigned_encryption_info })
2549 }
2550
2551 #[cfg(feature = "experimental-encrypted-state-events")]
2568 fn verify_packed_state_key(
2569 &self,
2570 original: &EncryptedEvent,
2571 decrypted: &Raw<AnyTimelineEvent>,
2572 ) -> MegolmResult<()> {
2573 use serde::Deserialize;
2574
2575 #[derive(Deserialize)]
2577 struct PayloadDeserializationHelper {
2578 state_key: Option<String>,
2579 #[serde(rename = "type")]
2580 event_type: String,
2581 }
2582
2583 let PayloadDeserializationHelper {
2585 state_key: inner_state_key,
2586 event_type: inner_event_type,
2587 } = decrypted
2588 .deserialize_as_unchecked()
2589 .map_err(|_| MegolmError::StateKeyVerificationFailed)?;
2590
2591 let (raw_state_key, inner_state_key) = match (&original.state_key, &inner_state_key) {
2594 (Some(raw_state_key), Some(inner_state_key)) => (raw_state_key, inner_state_key),
2595 (None, None) => return Ok(()),
2596 _ => return Err(MegolmError::StateKeyVerificationFailed),
2597 };
2598
2599 let (outer_event_type, outer_state_key) =
2601 raw_state_key.split_once(":").ok_or(MegolmError::StateKeyVerificationFailed)?;
2602
2603 if outer_event_type != inner_event_type {
2605 return Err(MegolmError::StateKeyVerificationFailed);
2606 }
2607
2608 if outer_state_key != inner_state_key {
2610 return Err(MegolmError::StateKeyVerificationFailed);
2611 }
2612 Ok(())
2613 }
2614
2615 async fn decrypt_unsigned_events(
2625 &self,
2626 main_event: &mut JsonObject,
2627 room_id: &RoomId,
2628 decryption_settings: &DecryptionSettings,
2629 ) -> Option<BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>> {
2630 let unsigned = main_event.get_mut("unsigned")?.as_object_mut()?;
2631 let mut unsigned_encryption_info: Option<
2632 BTreeMap<UnsignedEventLocation, UnsignedDecryptionResult>,
2633 > = None;
2634
2635 let location = UnsignedEventLocation::RelationsReplace;
2637 let replace = location.find_mut(unsigned);
2638 if let Some(decryption_result) =
2639 self.decrypt_unsigned_event(replace, room_id, decryption_settings).await
2640 {
2641 unsigned_encryption_info
2642 .get_or_insert_with(Default::default)
2643 .insert(location, decryption_result);
2644 }
2645
2646 let location = UnsignedEventLocation::RelationsThreadLatestEvent;
2649 let thread_latest_event = location.find_mut(unsigned);
2650 if let Some(decryption_result) =
2651 self.decrypt_unsigned_event(thread_latest_event, room_id, decryption_settings).await
2652 {
2653 unsigned_encryption_info
2654 .get_or_insert_with(Default::default)
2655 .insert(location, decryption_result);
2656 }
2657
2658 unsigned_encryption_info
2659 }
2660
2661 fn decrypt_unsigned_event<'a>(
2669 &'a self,
2670 event: Option<&'a mut Value>,
2671 room_id: &'a RoomId,
2672 decryption_settings: &'a DecryptionSettings,
2673 ) -> BoxFuture<'a, Option<UnsignedDecryptionResult>> {
2674 Box::pin(async move {
2675 let event = event?;
2676
2677 let is_encrypted = event
2678 .get("type")
2679 .and_then(|type_| type_.as_str())
2680 .is_some_and(|s| s == "m.room.encrypted");
2681 if !is_encrypted {
2682 return None;
2683 }
2684
2685 let raw_event = serde_json::from_value(event.clone()).ok()?;
2686 match self
2687 .decrypt_room_event_inner(&raw_event, room_id, false, decryption_settings)
2688 .await
2689 {
2690 Ok(decrypted_event) => {
2691 *event = serde_json::to_value(decrypted_event.event).ok()?;
2693 Some(UnsignedDecryptionResult::Decrypted(decrypted_event.encryption_info))
2694 }
2695 Err(err) => {
2696 let utd_info = megolm_error_to_utd_info(&raw_event, err).ok()?;
2702 Some(UnsignedDecryptionResult::UnableToDecrypt(utd_info))
2703 }
2704 }
2705 })
2706 }
2707
2708 pub async fn is_room_key_available(
2715 &self,
2716 event: &Raw<EncryptedEvent>,
2717 room_id: &RoomId,
2718 ) -> Result<bool, CryptoStoreError> {
2719 let event = event.deserialize()?;
2720
2721 let (session_id, message_index) = match &event.content.scheme {
2722 RoomEventEncryptionScheme::MegolmV1AesSha2(c) => {
2723 (&c.session_id, c.ciphertext.message_index())
2724 }
2725 #[cfg(feature = "experimental-algorithms")]
2726 RoomEventEncryptionScheme::MegolmV2AesSha2(c) => {
2727 (&c.session_id, c.ciphertext.message_index())
2728 }
2729 RoomEventEncryptionScheme::Unknown(_) => {
2730 return Ok(false);
2733 }
2734 };
2735
2736 Ok(self
2739 .store()
2740 .get_inbound_group_session(room_id, session_id)
2741 .await?
2742 .filter(|s| s.first_known_index() <= message_index)
2743 .is_some())
2744 }
2745
2746 #[instrument(skip(self, event), fields(event_id, sender, session_id))]
2759 pub async fn get_room_event_encryption_info(
2760 &self,
2761 event: &Raw<EncryptedEvent>,
2762 room_id: &RoomId,
2763 ) -> MegolmResult<Arc<EncryptionInfo>> {
2764 let event = event.deserialize()?;
2765
2766 let content: SupportedEventEncryptionSchemes<'_> = match &event.content.scheme {
2767 RoomEventEncryptionScheme::MegolmV1AesSha2(c) => c.into(),
2768 #[cfg(feature = "experimental-algorithms")]
2769 RoomEventEncryptionScheme::MegolmV2AesSha2(c) => c.into(),
2770 RoomEventEncryptionScheme::Unknown(_) => {
2771 return Err(EventError::UnsupportedAlgorithm.into());
2772 }
2773 };
2774
2775 Span::current()
2776 .record("sender", debug(&event.sender))
2777 .record("event_id", debug(&event.event_id))
2778 .record("session_id", content.session_id());
2779
2780 self.get_session_encryption_info(room_id, content.session_id(), &event.sender).await
2781 }
2782
2783 pub async fn get_session_encryption_info(
2798 &self,
2799 room_id: &RoomId,
2800 session_id: &str,
2801 sender: &UserId,
2802 ) -> MegolmResult<Arc<EncryptionInfo>> {
2803 let session = self.get_inbound_group_session_or_error(room_id, session_id).await?;
2804 self.get_encryption_info(&session, sender).await
2805 }
2806
2807 pub async fn update_tracked_users(
2825 &self,
2826 users: impl IntoIterator<Item = &UserId>,
2827 ) -> StoreResult<()> {
2828 self.inner.identity_manager.update_tracked_users(users).await
2829 }
2830
2831 pub async fn mark_all_tracked_users_as_dirty(&self) -> StoreResult<()> {
2836 self.inner
2837 .identity_manager
2838 .mark_all_tracked_users_as_dirty(self.inner.store.cache().await?)
2839 .await
2840 }
2841
2842 async fn wait_if_user_pending(
2843 &self,
2844 user_id: &UserId,
2845 timeout: Option<Duration>,
2846 ) -> StoreResult<()> {
2847 if let Some(timeout) = timeout {
2848 let cache = self.store().cache().await?;
2849 self.inner
2850 .identity_manager
2851 .key_query_manager
2852 .wait_if_user_key_query_pending(cache, timeout, user_id)
2853 .await?;
2854 }
2855 Ok(())
2856 }
2857
2858 #[instrument(skip(self))]
2886 pub async fn get_device(
2887 &self,
2888 user_id: &UserId,
2889 device_id: &DeviceId,
2890 timeout: Option<Duration>,
2891 ) -> StoreResult<Option<Device>> {
2892 self.wait_if_user_pending(user_id, timeout).await?;
2893 self.store().get_device(user_id, device_id).await
2894 }
2895
2896 #[instrument(skip(self))]
2909 pub async fn get_identity(
2910 &self,
2911 user_id: &UserId,
2912 timeout: Option<Duration>,
2913 ) -> StoreResult<Option<UserIdentity>> {
2914 self.wait_if_user_pending(user_id, timeout).await?;
2915 self.store().get_identity(user_id).await
2916 }
2917
2918 #[instrument(skip(self))]
2944 pub async fn get_user_devices(
2945 &self,
2946 user_id: &UserId,
2947 timeout: Option<Duration>,
2948 ) -> StoreResult<UserDevices> {
2949 self.wait_if_user_pending(user_id, timeout).await?;
2950 self.store().get_user_devices(user_id).await
2951 }
2952
2953 pub async fn cross_signing_status(&self) -> CrossSigningStatus {
2958 self.inner.user_identity.lock().await.status().await
2959 }
2960
2961 pub async fn export_cross_signing_keys(&self) -> StoreResult<Option<CrossSigningKeyExport>> {
2969 let master_key = self.store().export_secret(&SecretName::CrossSigningMasterKey).await?;
2970 let self_signing_key =
2971 self.store().export_secret(&SecretName::CrossSigningSelfSigningKey).await?;
2972 let user_signing_key =
2973 self.store().export_secret(&SecretName::CrossSigningUserSigningKey).await?;
2974
2975 Ok(if master_key.is_none() && self_signing_key.is_none() && user_signing_key.is_none() {
2976 None
2977 } else {
2978 Some(CrossSigningKeyExport { master_key, self_signing_key, user_signing_key })
2979 })
2980 }
2981
2982 pub async fn import_cross_signing_keys(
2987 &self,
2988 export: CrossSigningKeyExport,
2989 ) -> Result<CrossSigningStatus, SecretImportError> {
2990 self.store().import_cross_signing_keys(export).await
2991 }
2992
2993 async fn sign_with_master_key(
2994 &self,
2995 message: &str,
2996 ) -> Result<(OwnedDeviceKeyId, Ed25519Signature), SignatureError> {
2997 let identity = &*self.inner.user_identity.lock().await;
2998 let key_id = identity.master_key_id().await.ok_or(SignatureError::MissingSigningKey)?;
2999
3000 let signature = identity.sign(message).await?;
3001
3002 Ok((key_id, signature))
3003 }
3004
3005 pub async fn sign(&self, message: &str) -> Result<Signatures, CryptoStoreError> {
3011 let mut signatures = Signatures::new();
3012
3013 {
3014 let cache = self.inner.store.cache().await?;
3015 let account = cache.account().await?;
3016 let key_id = account.signing_key_id();
3017 let signature = account.sign(message);
3018 signatures.add_signature(self.user_id().to_owned(), key_id, signature);
3019 }
3020
3021 match self.sign_with_master_key(message).await {
3022 Ok((key_id, signature)) => {
3023 signatures.add_signature(self.user_id().to_owned(), key_id, signature);
3024 }
3025 Err(e) => {
3026 warn!(error = ?e, "Couldn't sign the message using the cross signing master key")
3027 }
3028 }
3029
3030 Ok(signatures)
3031 }
3032
3033 pub fn backup_machine(&self) -> &BackupMachine {
3038 &self.inner.backup_machine
3039 }
3040
3041 pub async fn initialize_crypto_store_generation(
3045 &self,
3046 generation: &Mutex<Option<u64>>,
3047 ) -> StoreResult<()> {
3048 let mut gen_guard = generation.lock().await;
3051
3052 let prev_generation =
3053 self.inner.store.get_custom_value(Self::CURRENT_GENERATION_STORE_KEY).await?;
3054
3055 let generation = match prev_generation {
3056 Some(val) => {
3057 u64::from_le_bytes(val.try_into().map_err(|_| {
3061 CryptoStoreError::InvalidLockGeneration("invalid format".to_owned())
3062 })?)
3063 .wrapping_add(1)
3064 }
3065 None => 0,
3066 };
3067
3068 tracing::debug!("Initialising crypto store generation at {generation}");
3069
3070 self.inner
3071 .store
3072 .set_custom_value(Self::CURRENT_GENERATION_STORE_KEY, generation.to_le_bytes().to_vec())
3073 .await?;
3074
3075 *gen_guard = Some(generation);
3076
3077 Ok(())
3078 }
3079
3080 pub async fn maintain_crypto_store_generation(
3105 &'_ self,
3106 generation: &Mutex<Option<u64>>,
3107 ) -> StoreResult<(bool, u64)> {
3108 let mut gen_guard = generation.lock().await;
3109
3110 let actual_gen = self
3118 .inner
3119 .store
3120 .get_custom_value(Self::CURRENT_GENERATION_STORE_KEY)
3121 .await?
3122 .ok_or_else(|| {
3123 CryptoStoreError::InvalidLockGeneration("counter missing in store".to_owned())
3124 })?;
3125
3126 let actual_gen =
3127 u64::from_le_bytes(actual_gen.try_into().map_err(|_| {
3128 CryptoStoreError::InvalidLockGeneration("invalid format".to_owned())
3129 })?);
3130
3131 let new_gen = match gen_guard.as_ref() {
3132 Some(expected_gen) => {
3133 if actual_gen == *expected_gen {
3134 return Ok((false, actual_gen));
3135 }
3136 actual_gen.max(*expected_gen).wrapping_add(1)
3138 }
3139 None => {
3140 actual_gen.wrapping_add(1)
3144 }
3145 };
3146
3147 tracing::debug!(
3148 "Crypto store generation mismatch: previously known was {:?}, actual is {:?}, next is {}",
3149 *gen_guard,
3150 actual_gen,
3151 new_gen
3152 );
3153
3154 *gen_guard = Some(new_gen);
3156
3157 self.inner
3159 .store
3160 .set_custom_value(Self::CURRENT_GENERATION_STORE_KEY, new_gen.to_le_bytes().to_vec())
3161 .await?;
3162
3163 Ok((true, new_gen))
3164 }
3165
3166 pub fn dehydrated_devices(&self) -> DehydratedDevices {
3168 DehydratedDevices { inner: self.to_owned() }
3169 }
3170
3171 pub async fn room_settings(&self, room_id: &RoomId) -> StoreResult<Option<RoomSettings>> {
3176 self.inner.store.get_room_settings(room_id).await
3179 }
3180
3181 pub async fn set_room_settings(
3192 &self,
3193 room_id: &RoomId,
3194 new_settings: &RoomSettings,
3195 ) -> Result<(), SetRoomSettingsError> {
3196 let store = &self.inner.store;
3197
3198 let _store_transaction = store.transaction().await;
3203
3204 let old_settings = store.get_room_settings(room_id).await?;
3205
3206 if let Some(old_settings) = old_settings {
3221 if old_settings != *new_settings {
3222 return Err(SetRoomSettingsError::EncryptionDowngrade);
3223 } else {
3224 return Ok(());
3226 }
3227 }
3228
3229 match new_settings.algorithm {
3231 EventEncryptionAlgorithm::MegolmV1AesSha2 => (),
3232
3233 #[cfg(feature = "experimental-algorithms")]
3234 EventEncryptionAlgorithm::MegolmV2AesSha2 => (),
3235
3236 _ => {
3237 warn!(
3238 ?room_id,
3239 "Rejecting invalid encryption algorithm {}", new_settings.algorithm
3240 );
3241 return Err(SetRoomSettingsError::InvalidSettings);
3242 }
3243 }
3244
3245 store
3247 .save_changes(Changes {
3248 room_settings: HashMap::from([(room_id.to_owned(), new_settings.clone())]),
3249 ..Default::default()
3250 })
3251 .await?;
3252
3253 Ok(())
3254 }
3255
3256 #[cfg(any(feature = "testing", test))]
3260 pub fn same_as(&self, other: &OlmMachine) -> bool {
3261 Arc::ptr_eq(&self.inner, &other.inner)
3262 }
3263
3264 #[cfg(any(feature = "testing", test))]
3266 pub async fn uploaded_key_count(&self) -> Result<u64, CryptoStoreError> {
3267 let cache = self.inner.store.cache().await?;
3268 let account = cache.account().await?;
3269 Ok(account.uploaded_key_count())
3270 }
3271
3272 #[cfg(test)]
3274 pub(crate) fn identity_manager(&self) -> &IdentityManager {
3275 &self.inner.identity_manager
3276 }
3277
3278 #[cfg(test)]
3280 pub(crate) fn key_for_has_migrated_verification_latch() -> &'static str {
3281 Self::HAS_MIGRATED_VERIFICATION_LATCH
3282 }
3283}
3284
3285fn sender_data_to_verification_state(
3286 sender_data: SenderData,
3287 session_has_been_imported: bool,
3288) -> (VerificationState, Option<OwnedDeviceId>) {
3289 match sender_data {
3290 SenderData::UnknownDevice { owner_check_failed: false, .. } => {
3291 let device_link_problem = if session_has_been_imported {
3292 DeviceLinkProblem::InsecureSource
3293 } else {
3294 DeviceLinkProblem::MissingDevice
3295 };
3296
3297 (VerificationState::Unverified(VerificationLevel::None(device_link_problem)), None)
3298 }
3299 SenderData::UnknownDevice { owner_check_failed: true, .. } => (
3300 VerificationState::Unverified(VerificationLevel::None(
3301 DeviceLinkProblem::InsecureSource,
3302 )),
3303 None,
3304 ),
3305 SenderData::DeviceInfo { device_keys, .. } => (
3306 VerificationState::Unverified(VerificationLevel::UnsignedDevice),
3307 Some(device_keys.device_id),
3308 ),
3309 SenderData::VerificationViolation(KnownSenderData { device_id, .. }) => {
3310 (VerificationState::Unverified(VerificationLevel::VerificationViolation), device_id)
3311 }
3312 SenderData::SenderUnverified(KnownSenderData { device_id, .. }) => {
3313 (VerificationState::Unverified(VerificationLevel::UnverifiedIdentity), device_id)
3314 }
3315 SenderData::SenderVerified(KnownSenderData { device_id, .. }) => {
3316 (VerificationState::Verified, device_id)
3317 }
3318 }
3319}
3320
3321#[derive(Debug, Clone)]
3324pub struct CrossSigningBootstrapRequests {
3325 pub upload_keys_req: Option<OutgoingRequest>,
3332
3333 pub upload_signing_keys_req: UploadSigningKeysRequest,
3337
3338 pub upload_signatures_req: UploadSignaturesRequest,
3343}
3344
3345#[derive(Debug)]
3347pub struct UncommittedCrossSigningReset {
3348 olm_machine: OlmMachine,
3350 identity: PrivateCrossSigningIdentity,
3352 public: OwnUserIdentityData,
3354 upload_signing_keys_req: UploadSigningKeysRequest,
3359 upload_signatures_req: UploadSignaturesRequest,
3364}
3365
3366impl UncommittedCrossSigningReset {
3367 pub fn upload_signing_keys_req(&self) -> &UploadSigningKeysRequest {
3369 &self.upload_signing_keys_req
3370 }
3371
3372 pub async fn commit(self) -> Result<UploadSignaturesRequest, CryptoStoreError> {
3382 let Self { olm_machine, identity, public, upload_signatures_req, .. } = self;
3383
3384 *olm_machine.inner.user_identity.lock().await = identity.clone();
3385
3386 olm_machine
3387 .store()
3388 .save_changes(Changes {
3389 identities: IdentityChanges {
3390 new: vec![public.clone().into()],
3391 ..Default::default()
3392 },
3393 private_identity: Some(identity.clone()),
3394 ..Default::default()
3395 })
3396 .await?;
3397
3398 Ok(upload_signatures_req.clone())
3399 }
3400}
3401
3402#[derive(Debug, thiserror::Error)]
3408pub enum BootstrapCrossSigningError {
3409 #[error(transparent)]
3411 CryptoStore(#[from] CryptoStoreError),
3412
3413 #[error(transparent)]
3415 Signature(#[from] SignatureError),
3416}
3417
3418#[derive(Debug)]
3421pub struct EncryptionSyncChanges<'a> {
3422 pub to_device_events: Vec<Raw<AnyToDeviceEvent>>,
3424 pub changed_devices: &'a DeviceLists,
3427 pub one_time_keys_counts: &'a BTreeMap<OneTimeKeyAlgorithm, UInt>,
3429 pub unused_fallback_keys: Option<&'a [OneTimeKeyAlgorithm]>,
3431 pub next_batch_token: Option<String>,
3433}
3434
3435fn megolm_error_to_utd_info(
3443 raw_event: &Raw<EncryptedEvent>,
3444 error: MegolmError,
3445) -> Result<UnableToDecryptInfo, CryptoStoreError> {
3446 use MegolmError::*;
3447 let reason = match error {
3448 EventError(_) => UnableToDecryptReason::MalformedEncryptedEvent,
3449 Decode(_) => UnableToDecryptReason::MalformedEncryptedEvent,
3450 MissingRoomKey(maybe_withheld) => {
3451 UnableToDecryptReason::MissingMegolmSession { withheld_code: maybe_withheld }
3452 }
3453 Decryption(DecryptionError::UnknownMessageIndex(_, _)) => {
3454 UnableToDecryptReason::UnknownMegolmMessageIndex
3455 }
3456 Decryption(_) => UnableToDecryptReason::MegolmDecryptionFailure,
3457 JsonError(_) => UnableToDecryptReason::PayloadDeserializationFailure,
3458 MismatchedIdentityKeys(_) => UnableToDecryptReason::MismatchedIdentityKeys,
3459 SenderIdentityNotTrusted(level) => UnableToDecryptReason::SenderIdentityNotTrusted(level),
3460 #[cfg(feature = "experimental-encrypted-state-events")]
3461 StateKeyVerificationFailed => UnableToDecryptReason::StateKeyVerificationFailed,
3462
3463 Store(error) => Err(error)?,
3466 };
3467
3468 let session_id = raw_event.deserialize().ok().and_then(|ev| match ev.content.scheme {
3469 RoomEventEncryptionScheme::MegolmV1AesSha2(s) => Some(s.session_id),
3470 #[cfg(feature = "experimental-algorithms")]
3471 RoomEventEncryptionScheme::MegolmV2AesSha2(s) => Some(s.session_id),
3472 RoomEventEncryptionScheme::Unknown(_) => None,
3473 });
3474
3475 Ok(UnableToDecryptInfo { session_id, reason })
3476}
3477
3478#[derive(Debug, thiserror::Error)]
3487pub(crate) enum DecryptToDeviceError {
3488 #[error("An Olm error occurred meaning we failed to decrypt the event")]
3489 OlmError(#[from] OlmError),
3490
3491 #[error("The event was sent from a dehydrated device")]
3492 FromDehydratedDevice,
3493}
3494
3495impl From<CryptoStoreError> for DecryptToDeviceError {
3496 fn from(value: CryptoStoreError) -> Self {
3497 Self::OlmError(value.into())
3498 }
3499}
3500
3501#[cfg(test)]
3502impl From<DecryptToDeviceError> for OlmError {
3503 fn from(value: DecryptToDeviceError) -> Self {
3506 match value {
3507 DecryptToDeviceError::OlmError(olm_error) => olm_error,
3508 DecryptToDeviceError::FromDehydratedDevice => {
3509 panic!("Expected an OlmError but found FromDehydratedDevice")
3510 }
3511 }
3512 }
3513}
3514
3515#[cfg(test)]
3516pub(crate) mod test_helpers;
3517
3518#[cfg(test)]
3519pub(crate) mod tests;