1use std::{
42 collections::{BTreeMap, BTreeSet, HashMap, HashSet},
43 fmt::Debug,
44 ops::Deref,
45 pin::pin,
46 sync::{Arc, atomic::Ordering},
47 time::Duration,
48};
49
50use as_variant::as_variant;
51use futures_core::Stream;
52use futures_util::StreamExt;
53use itertools::{Either, Itertools};
54use ruma::{
55 DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, RoomId, UserId,
56 encryption::KeyUsage, events::secret::request::SecretName,
57};
58use serde::{Serialize, de::DeserializeOwned};
59use thiserror::Error;
60use tokio::sync::{Mutex, Notify, OwnedRwLockWriteGuard, RwLock};
61use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
62use tracing::{info, instrument, trace, warn};
63use types::{RoomKeyBundleInfo, StoredRoomKeyBundleData};
64use vodozemac::{Curve25519PublicKey, megolm::SessionOrdering};
65
66use self::types::{
67 Changes, CrossSigningKeyExport, DeviceChanges, DeviceUpdates, IdentityChanges, IdentityUpdates,
68 PendingChanges, RoomKeyInfo, RoomKeyWithheldInfo, RoomPendingKeyBundleDetails,
69 UserKeyQueryResult,
70};
71use crate::{
72 CrossSigningStatus, OwnUserIdentityData, RoomKeyImportResult,
73 gossiping::GossippedSecret,
74 identities::{Device, DeviceData, UserDevices, UserIdentityData, user::UserIdentity},
75 olm::{
76 Account, ExportedRoomKey, ForwarderData, InboundGroupSession, PrivateCrossSigningIdentity,
77 SenderData, Session, StaticAccountData,
78 },
79 store::types::{RoomKeyWithheldEntry, SecretsInboxItem},
80 types::{
81 BackupSecrets, CrossSigningSecrets, MegolmBackupV1Curve25519AesSha2Secrets, RoomKeyExport,
82 SecretsBundle,
83 },
84 verification::VerificationMachine,
85};
86#[cfg(doc)]
87use crate::{backups::BackupMachine, identities::OwnUserIdentity};
88
89pub mod caches;
90mod crypto_store_wrapper;
91mod error;
92mod memorystore;
93mod traits;
94pub mod types;
95
96#[cfg(any(test, feature = "testing"))]
97#[macro_use]
98#[allow(missing_docs)]
99pub mod integration_tests;
100
101pub(crate) use crypto_store_wrapper::CryptoStoreWrapper;
102pub use error::{CryptoStoreError, Result};
103use matrix_sdk_common::{
104 cross_process_lock::{CrossProcessLock, CrossProcessLockConfig, CrossProcessLockGeneration},
105 deserialized_responses::WithheldCode,
106 timeout::timeout,
107};
108pub use memorystore::MemoryStore;
109pub use traits::{CryptoStore, DynCryptoStore, IntoCryptoStore};
110
111use self::caches::{SequenceNumber, StoreCache, StoreCacheGuard, UsersForKeyQuery};
112use crate::types::{
113 events::room_key_withheld::RoomKeyWithheldContent, room_history::RoomKeyBundle,
114};
115pub use crate::{
116 dehydrated_devices::DehydrationError,
117 gossiping::{GossipRequest, SecretInfo},
118};
119
120#[derive(Debug, Clone)]
127pub struct Store {
128 inner: Arc<StoreInner>,
129}
130
131#[derive(Debug, Default)]
132pub(crate) struct KeyQueryManager {
133 users_for_key_query: Mutex<UsersForKeyQuery>,
135
136 users_for_key_query_notify: Notify,
138}
139
140impl KeyQueryManager {
141 pub async fn synced<'a>(&'a self, cache: &'a StoreCache) -> Result<SyncedKeyQueryManager<'a>> {
142 self.ensure_sync_tracked_users(cache).await?;
143 Ok(SyncedKeyQueryManager { cache, manager: self })
144 }
145
146 async fn ensure_sync_tracked_users(&self, cache: &StoreCache) -> Result<()> {
153 let loaded = cache.loaded_tracked_users.read().await;
155 if *loaded {
156 return Ok(());
157 }
158
159 drop(loaded);
161 let mut loaded = cache.loaded_tracked_users.write().await;
162
163 if *loaded {
167 return Ok(());
168 }
169
170 let tracked_users = cache.store.load_tracked_users().await?;
171
172 let mut query_users_lock = self.users_for_key_query.lock().await;
173 let mut tracked_users_cache = cache.tracked_users.write();
174 for user in tracked_users {
175 tracked_users_cache.insert(user.user_id.to_owned());
176
177 if user.dirty {
178 query_users_lock.insert_user(&user.user_id);
179 }
180 }
181
182 *loaded = true;
183
184 Ok(())
185 }
186
187 pub async fn wait_if_user_key_query_pending(
197 &self,
198 cache: StoreCacheGuard,
199 timeout_duration: Duration,
200 user: &UserId,
201 ) -> Result<UserKeyQueryResult> {
202 {
203 self.ensure_sync_tracked_users(&cache).await?;
206 drop(cache);
207 }
208
209 let mut users_for_key_query = self.users_for_key_query.lock().await;
210 let Some(waiter) = users_for_key_query.maybe_register_waiting_task(user) else {
211 return Ok(UserKeyQueryResult::WasNotPending);
212 };
213
214 let wait_for_completion = async {
215 while !waiter.completed.load(Ordering::Relaxed) {
216 let mut notified = pin!(self.users_for_key_query_notify.notified());
220 notified.as_mut().enable();
221 drop(users_for_key_query);
222
223 notified.await;
225
226 users_for_key_query = self.users_for_key_query.lock().await;
230 }
231 };
232
233 match timeout(Box::pin(wait_for_completion), timeout_duration).await {
234 Err(_) => {
235 warn!(
236 user_id = ?user,
237 "The user has a pending `/keys/query` request which did \
238 not finish yet, some devices might be missing."
239 );
240
241 Ok(UserKeyQueryResult::TimeoutExpired)
242 }
243 _ => Ok(UserKeyQueryResult::WasPending),
244 }
245 }
246}
247
248pub(crate) struct SyncedKeyQueryManager<'a> {
249 cache: &'a StoreCache,
250 manager: &'a KeyQueryManager,
251}
252
253impl SyncedKeyQueryManager<'_> {
254 pub async fn update_tracked_users(&self, users: impl Iterator<Item = &UserId>) -> Result<()> {
259 let mut store_updates = Vec::new();
260 let mut key_query_lock = self.manager.users_for_key_query.lock().await;
261
262 {
263 let mut tracked_users = self.cache.tracked_users.write();
264 for user_id in users {
265 if tracked_users.insert(user_id.to_owned()) {
266 key_query_lock.insert_user(user_id);
267 store_updates.push((user_id, true))
268 }
269 }
270 }
271
272 self.cache.store.save_tracked_users(&store_updates).await
273 }
274
275 pub async fn mark_tracked_users_as_changed(
282 &self,
283 users: impl Iterator<Item = &UserId>,
284 ) -> Result<()> {
285 let mut store_updates: Vec<(&UserId, bool)> = Vec::new();
286 let mut key_query_lock = self.manager.users_for_key_query.lock().await;
287
288 {
289 let tracked_users = &self.cache.tracked_users.read();
290 for user_id in users {
291 if tracked_users.contains(user_id) {
292 key_query_lock.insert_user(user_id);
293 store_updates.push((user_id, true));
294 }
295 }
296 }
297
298 self.cache.store.save_tracked_users(&store_updates).await
299 }
300
301 pub async fn mark_tracked_users_as_up_to_date(
307 &self,
308 users: impl Iterator<Item = &UserId>,
309 sequence_number: SequenceNumber,
310 ) -> Result<()> {
311 let mut store_updates: Vec<(&UserId, bool)> = Vec::new();
312 let mut key_query_lock = self.manager.users_for_key_query.lock().await;
313
314 {
315 let tracked_users = self.cache.tracked_users.read();
316 for user_id in users {
317 if tracked_users.contains(user_id) {
318 let clean = key_query_lock.maybe_remove_user(user_id, sequence_number);
319 store_updates.push((user_id, !clean));
320 }
321 }
322 }
323
324 self.cache.store.save_tracked_users(&store_updates).await?;
325 self.manager.users_for_key_query_notify.notify_waiters();
327
328 Ok(())
329 }
330
331 pub async fn users_for_key_query(&self) -> (HashSet<OwnedUserId>, SequenceNumber) {
343 self.manager.users_for_key_query.lock().await.users_for_key_query()
344 }
345
346 pub fn tracked_users(&self) -> HashSet<OwnedUserId> {
348 self.cache.tracked_users.read().iter().cloned().collect()
349 }
350
351 pub async fn mark_user_as_changed(&self, user: &UserId) -> Result<()> {
357 self.manager.users_for_key_query.lock().await.insert_user(user);
358 self.cache.tracked_users.write().insert(user.to_owned());
359
360 self.cache.store.save_tracked_users(&[(user, true)]).await
361 }
362}
363
364fn collect_device_updates(
370 verification_machine: VerificationMachine,
371 own_identity: Option<OwnUserIdentityData>,
372 identities: IdentityChanges,
373 devices: DeviceChanges,
374) -> DeviceUpdates {
375 let mut new: BTreeMap<_, BTreeMap<_, _>> = BTreeMap::new();
376 let mut changed: BTreeMap<_, BTreeMap<_, _>> = BTreeMap::new();
377
378 let (new_identities, changed_identities, unchanged_identities) = identities.into_maps();
379
380 let map_device = |device: DeviceData| {
381 let device_owner_identity = new_identities
382 .get(device.user_id())
383 .or_else(|| changed_identities.get(device.user_id()))
384 .or_else(|| unchanged_identities.get(device.user_id()))
385 .cloned();
386
387 Device {
388 inner: device,
389 verification_machine: verification_machine.to_owned(),
390 own_identity: own_identity.to_owned(),
391 device_owner_identity,
392 }
393 };
394
395 for device in devices.new {
396 let device = map_device(device);
397
398 new.entry(device.user_id().to_owned())
399 .or_default()
400 .insert(device.device_id().to_owned(), device);
401 }
402
403 for device in devices.changed {
404 let device = map_device(device);
405
406 changed
407 .entry(device.user_id().to_owned())
408 .or_default()
409 .insert(device.device_id().to_owned(), device.to_owned());
410 }
411
412 DeviceUpdates { new, changed }
413}
414
415#[allow(missing_debug_implementations)]
417pub struct StoreTransaction {
418 store: Store,
419 changes: PendingChanges,
420 cache: OwnedRwLockWriteGuard<StoreCache>,
422}
423
424impl StoreTransaction {
425 async fn new(store: Store) -> Self {
427 let cache = store.inner.cache.clone();
428
429 Self { store, changes: PendingChanges::default(), cache: cache.clone().write_owned().await }
430 }
431
432 pub(crate) fn cache(&self) -> &StoreCache {
433 &self.cache
434 }
435
436 pub fn store(&self) -> &Store {
438 &self.store
439 }
440
441 pub async fn account(&mut self) -> Result<&mut Account> {
448 if self.changes.account.is_none() {
449 let _ = self.cache.account().await?;
451 self.changes.account = self.cache.account.lock().await.take();
452 }
453 Ok(self.changes.account.as_mut().unwrap())
454 }
455
456 pub async fn commit(self) -> Result<()> {
459 if self.changes.is_empty() {
460 return Ok(());
461 }
462
463 let account = self.changes.account.as_ref().map(|acc| acc.deep_clone());
465
466 self.store.save_pending_changes(self.changes).await?;
467
468 if let Some(account) = account {
470 *self.cache.account.lock().await = Some(account);
471 }
472
473 Ok(())
474 }
475}
476
477#[derive(Debug)]
478struct StoreInner {
479 identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
480 store: Arc<CryptoStoreWrapper>,
481
482 cache: Arc<RwLock<StoreCache>>,
486
487 verification_machine: VerificationMachine,
488
489 static_account: StaticAccountData,
492}
493
494#[derive(Debug, Error)]
497pub enum SecretImportError {
498 #[error("Error while importing {name}: {error}")]
500 Key {
501 name: SecretName,
503 error: vodozemac::KeyError,
505 },
506 #[error(
509 "Error while importing {name}: The public key of the imported private \
510 key doesn't match the public key that was uploaded to the server"
511 )]
512 MismatchedPublicKeys {
513 name: SecretName,
515 },
516 #[error(transparent)]
518 Store(#[from] CryptoStoreError),
519}
520
521#[derive(Debug, Error)]
526pub enum SecretsBundleExportError {
527 #[error(transparent)]
529 Store(#[from] CryptoStoreError),
530 #[error("The store is missing one or multiple cross-signing keys")]
532 MissingCrossSigningKey(KeyUsage),
533 #[error("The store doesn't contain any cross-signing keys")]
535 MissingCrossSigningKeys,
536 #[error("The store contains a backup key, but no backup version")]
539 MissingBackupVersion,
540}
541
542impl Store {
543 pub(crate) fn new(
545 account: StaticAccountData,
546 identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
547 store: Arc<CryptoStoreWrapper>,
548 verification_machine: VerificationMachine,
549 ) -> Self {
550 Self {
551 inner: Arc::new(StoreInner {
552 static_account: account,
553 identity,
554 store: store.clone(),
555 verification_machine,
556 cache: Arc::new(RwLock::new(StoreCache {
557 store,
558 tracked_users: Default::default(),
559 loaded_tracked_users: Default::default(),
560 account: Default::default(),
561 })),
562 }),
563 }
564 }
565
566 pub(crate) fn user_id(&self) -> &UserId {
568 &self.inner.static_account.user_id
569 }
570
571 pub(crate) fn device_id(&self) -> &DeviceId {
573 self.inner.verification_machine.own_device_id()
574 }
575
576 pub(crate) fn static_account(&self) -> &StaticAccountData {
578 &self.inner.static_account
579 }
580
581 pub(crate) async fn cache(&self) -> Result<StoreCacheGuard> {
582 Ok(StoreCacheGuard { cache: self.inner.cache.clone().read_owned().await })
583 }
584
585 pub(crate) async fn transaction(&self) -> StoreTransaction {
586 StoreTransaction::new(self.clone()).await
587 }
588
589 pub(crate) async fn with_transaction<T>(
590 &self,
591 func: impl AsyncFnOnce(&mut StoreTransaction) -> Result<T, crate::OlmError>,
592 ) -> Result<T, crate::OlmError> {
593 let mut tr = self.transaction().await;
594 let res = func(&mut tr).await?;
595 tr.commit().await?;
596 Ok(res)
597 }
598
599 #[cfg(test)]
600 pub(crate) async fn reset_cross_signing_identity(&self) {
602 self.inner.identity.lock().await.reset();
603 }
604
605 pub(crate) fn private_identity(&self) -> Arc<Mutex<PrivateCrossSigningIdentity>> {
607 self.inner.identity.clone()
608 }
609
610 pub(crate) async fn save_sessions(&self, sessions: &[Session]) -> Result<()> {
612 let changes = Changes { sessions: sessions.to_vec(), ..Default::default() };
613
614 self.save_changes(changes).await
615 }
616
617 pub(crate) async fn get_sessions(
618 &self,
619 sender_key: &str,
620 ) -> Result<Option<Arc<Mutex<Vec<Session>>>>> {
621 self.inner.store.get_sessions(sender_key).await
622 }
623
624 pub(crate) async fn save_changes(&self, changes: Changes) -> Result<()> {
625 self.inner.store.save_changes(changes).await
626 }
627
628 pub(crate) async fn merge_received_group_session(
636 &self,
637 session: InboundGroupSession,
638 ) -> Result<Option<InboundGroupSession>> {
639 let old_session = self
640 .inner
641 .store
642 .get_inbound_group_session(session.room_id(), session.session_id())
643 .await?;
644
645 let Some(old_session) = old_session else {
647 info!("Received a new megolm room key");
648 return Ok(Some(session));
649 };
650
651 let index_comparison = session.compare_ratchet(&old_session).await;
652 let trust_level_comparison =
653 session.sender_data.compare_trust_level(&old_session.sender_data);
654
655 let result = match (index_comparison, trust_level_comparison) {
656 (SessionOrdering::Unconnected, _) => {
657 warn!(
661 "Received a group session with an ratchet that does not connect to the one in the store, discarding"
662 );
663 None
664 }
665
666 (SessionOrdering::Better, std::cmp::Ordering::Greater)
667 | (SessionOrdering::Better, std::cmp::Ordering::Equal)
668 | (SessionOrdering::Equal, std::cmp::Ordering::Greater) => {
669 info!(
671 ?index_comparison,
672 ?trust_level_comparison,
673 "Received a megolm room key that we have a worse version of, merging"
674 );
675 Some(session)
676 }
677
678 (SessionOrdering::Worse, std::cmp::Ordering::Less)
679 | (SessionOrdering::Worse, std::cmp::Ordering::Equal)
680 | (SessionOrdering::Equal, std::cmp::Ordering::Less) => {
681 warn!(
683 ?index_comparison,
684 ?trust_level_comparison,
685 "Received a megolm room key that we already have a better version \
686 of, discarding"
687 );
688 None
689 }
690
691 (SessionOrdering::Equal, std::cmp::Ordering::Equal) => {
692 info!("Received a megolm room key that we already have, discarding");
694 None
695 }
696
697 (SessionOrdering::Better, std::cmp::Ordering::Less) => {
698 info!("Upgrading a previously-received megolm session with new ratchet");
701 let result = old_session.with_ratchet(&session);
702 result.reset_backup_state();
704 Some(result)
705 }
706
707 (SessionOrdering::Worse, std::cmp::Ordering::Greater) => {
708 info!("Upgrading a previously-received megolm session with new sender data");
711 Some(session.with_ratchet(&old_session))
712 }
713 };
714
715 Ok(result)
716 }
717
718 #[cfg(test)]
719 pub(crate) async fn save_device_data(&self, devices: &[DeviceData]) -> Result<()> {
721 use types::DeviceChanges;
722
723 let changes = Changes {
724 devices: DeviceChanges { changed: devices.to_vec(), ..Default::default() },
725 ..Default::default()
726 };
727
728 self.save_changes(changes).await
729 }
730
731 pub(crate) async fn save_inbound_group_sessions(
733 &self,
734 sessions: &[InboundGroupSession],
735 ) -> Result<()> {
736 let changes = Changes { inbound_group_sessions: sessions.to_vec(), ..Default::default() };
737
738 self.save_changes(changes).await
739 }
740
741 pub(crate) async fn device_display_name(&self) -> Result<Option<String>, CryptoStoreError> {
743 Ok(self
744 .inner
745 .store
746 .get_device(self.user_id(), self.device_id())
747 .await?
748 .and_then(|d| d.display_name().map(|d| d.to_owned())))
749 }
750
751 pub(crate) async fn get_device_data(
756 &self,
757 user_id: &UserId,
758 device_id: &DeviceId,
759 ) -> Result<Option<DeviceData>> {
760 self.inner.store.get_device(user_id, device_id).await
761 }
762
763 pub(crate) async fn get_device_data_for_user_filtered(
771 &self,
772 user_id: &UserId,
773 ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
774 self.inner.store.get_user_devices(user_id).await.map(|mut d| {
775 if user_id == self.user_id() {
776 d.remove(self.device_id());
777 }
778 d
779 })
780 }
781
782 pub(crate) async fn get_device_data_for_user(
791 &self,
792 user_id: &UserId,
793 ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
794 self.inner.store.get_user_devices(user_id).await
795 }
796
797 pub(crate) async fn get_device_from_curve_key(
803 &self,
804 user_id: &UserId,
805 curve_key: Curve25519PublicKey,
806 ) -> Result<Option<Device>> {
807 self.get_user_devices(user_id)
808 .await
809 .map(|d| d.devices().find(|d| d.curve25519_key() == Some(curve_key)))
810 }
811
812 pub(crate) async fn get_user_devices(&self, user_id: &UserId) -> Result<UserDevices> {
822 let devices = self.get_device_data_for_user(user_id).await?;
823
824 let own_identity = self
825 .inner
826 .store
827 .get_user_identity(self.user_id())
828 .await?
829 .and_then(|i| i.own().cloned());
830 let device_owner_identity = self.inner.store.get_user_identity(user_id).await?;
831
832 Ok(UserDevices {
833 inner: devices,
834 verification_machine: self.inner.verification_machine.clone(),
835 own_identity,
836 device_owner_identity,
837 })
838 }
839
840 pub(crate) async fn get_device(
850 &self,
851 user_id: &UserId,
852 device_id: &DeviceId,
853 ) -> Result<Option<Device>> {
854 if let Some(device_data) = self.inner.store.get_device(user_id, device_id).await? {
855 Ok(Some(self.wrap_device_data(device_data).await?))
856 } else {
857 Ok(None)
858 }
859 }
860
861 pub(crate) async fn wrap_device_data(&self, device_data: DeviceData) -> Result<Device> {
866 let own_identity = self
867 .inner
868 .store
869 .get_user_identity(self.user_id())
870 .await?
871 .and_then(|i| i.own().cloned());
872
873 let device_owner_identity =
874 self.inner.store.get_user_identity(device_data.user_id()).await?;
875
876 Ok(Device {
877 inner: device_data,
878 verification_machine: self.inner.verification_machine.clone(),
879 own_identity,
880 device_owner_identity,
881 })
882 }
883
884 pub(crate) async fn get_identity(&self, user_id: &UserId) -> Result<Option<UserIdentity>> {
886 let own_identity = self
887 .inner
888 .store
889 .get_user_identity(self.user_id())
890 .await?
891 .and_then(as_variant!(UserIdentityData::Own));
892
893 Ok(self.inner.store.get_user_identity(user_id).await?.map(|i| {
894 UserIdentity::new(
895 self.clone(),
896 i,
897 self.inner.verification_machine.to_owned(),
898 own_identity,
899 )
900 }))
901 }
902
903 pub async fn export_secret(
912 &self,
913 secret_name: &SecretName,
914 ) -> Result<Option<String>, CryptoStoreError> {
915 Ok(match secret_name {
916 SecretName::CrossSigningMasterKey
917 | SecretName::CrossSigningUserSigningKey
918 | SecretName::CrossSigningSelfSigningKey => {
919 self.inner.identity.lock().await.export_secret(secret_name).await
920 }
921 SecretName::RecoveryKey => {
922 if let Some(key) = self.load_backup_keys().await?.decryption_key {
923 let exported = key.to_base64();
924 Some(exported)
925 } else {
926 None
927 }
928 }
929 name => {
930 warn!(secret = ?name, "Unknown secret was requested");
931 None
932 }
933 })
934 }
935
936 pub async fn export_cross_signing_keys(
944 &self,
945 ) -> Result<Option<CrossSigningKeyExport>, CryptoStoreError> {
946 let master_key = self.export_secret(&SecretName::CrossSigningMasterKey).await?;
947 let self_signing_key = self.export_secret(&SecretName::CrossSigningSelfSigningKey).await?;
948 let user_signing_key = self.export_secret(&SecretName::CrossSigningUserSigningKey).await?;
949
950 Ok(if master_key.is_none() && self_signing_key.is_none() && user_signing_key.is_none() {
951 None
952 } else {
953 Some(CrossSigningKeyExport { master_key, self_signing_key, user_signing_key })
954 })
955 }
956
957 pub async fn import_cross_signing_keys(
962 &self,
963 export: CrossSigningKeyExport,
964 ) -> Result<CrossSigningStatus, SecretImportError> {
965 if let Some(public_identity) =
966 self.get_identity(self.user_id()).await?.and_then(|i| i.own())
967 {
968 let identity = self.inner.identity.lock().await;
969
970 identity
971 .import_secrets(
972 public_identity.to_owned(),
973 export.master_key.as_deref(),
974 export.self_signing_key.as_deref(),
975 export.user_signing_key.as_deref(),
976 )
977 .await?;
978
979 let status = identity.status().await;
980
981 let diff = identity.get_public_identity_diff(&public_identity.inner).await;
982
983 let mut changes =
984 Changes { private_identity: Some(identity.clone()), ..Default::default() };
985
986 if diff.none_differ() {
987 public_identity.mark_as_verified();
988 changes.identities.changed.push(UserIdentityData::Own(public_identity.inner));
989 }
990
991 info!(?status, "Successfully imported the private cross-signing keys");
992
993 self.save_changes(changes).await?;
994 } else {
995 warn!(
996 "No public identity found while importing cross-signing keys, \
997 a /keys/query needs to be done"
998 );
999 }
1000
1001 Ok(self.inner.identity.lock().await.status().await)
1002 }
1003
1004 pub async fn export_secrets_bundle(&self) -> Result<SecretsBundle, SecretsBundleExportError> {
1016 let Some(cross_signing) = self.export_cross_signing_keys().await? else {
1017 return Err(SecretsBundleExportError::MissingCrossSigningKeys);
1018 };
1019
1020 let Some(master_key) = cross_signing.master_key.clone() else {
1021 return Err(SecretsBundleExportError::MissingCrossSigningKey(KeyUsage::Master));
1022 };
1023
1024 let Some(user_signing_key) = cross_signing.user_signing_key.clone() else {
1025 return Err(SecretsBundleExportError::MissingCrossSigningKey(KeyUsage::UserSigning));
1026 };
1027
1028 let Some(self_signing_key) = cross_signing.self_signing_key.clone() else {
1029 return Err(SecretsBundleExportError::MissingCrossSigningKey(KeyUsage::SelfSigning));
1030 };
1031
1032 let backup_keys = self.load_backup_keys().await?;
1033
1034 let backup = if let Some(key) = backup_keys.decryption_key {
1035 if let Some(backup_version) = backup_keys.backup_version {
1036 Some(BackupSecrets::MegolmBackupV1Curve25519AesSha2(
1037 MegolmBackupV1Curve25519AesSha2Secrets { key, backup_version },
1038 ))
1039 } else {
1040 return Err(SecretsBundleExportError::MissingBackupVersion);
1041 }
1042 } else {
1043 None
1044 };
1045
1046 Ok(SecretsBundle {
1047 cross_signing: CrossSigningSecrets { master_key, user_signing_key, self_signing_key },
1048 backup,
1049 })
1050 }
1051
1052 pub async fn import_secrets_bundle(
1065 &self,
1066 bundle: &SecretsBundle,
1067 ) -> Result<(), SecretImportError> {
1068 let mut changes = Changes::default();
1069
1070 if let Some(backup_bundle) = &bundle.backup {
1071 match backup_bundle {
1072 BackupSecrets::MegolmBackupV1Curve25519AesSha2(bundle) => {
1073 changes.backup_decryption_key = Some(bundle.key.clone());
1074 changes.backup_version = Some(bundle.backup_version.clone());
1075 }
1076 }
1077 }
1078
1079 let identity = self.inner.identity.lock().await;
1080
1081 identity
1082 .import_secrets_unchecked(
1083 Some(&bundle.cross_signing.master_key),
1084 Some(&bundle.cross_signing.self_signing_key),
1085 Some(&bundle.cross_signing.user_signing_key),
1086 )
1087 .await?;
1088
1089 let public_identity = identity.to_public_identity().await.expect(
1090 "We should be able to create a new public identity since we just imported \
1091 all the private cross-signing keys",
1092 );
1093
1094 changes.private_identity = Some(identity.clone());
1095 changes.identities.new.push(UserIdentityData::Own(public_identity));
1096
1097 Ok(self.save_changes(changes).await?)
1098 }
1099
1100 pub async fn import_secret(&self, secret: &GossippedSecret) -> Result<(), SecretImportError> {
1102 match &secret.secret_name {
1103 SecretName::CrossSigningMasterKey
1104 | SecretName::CrossSigningUserSigningKey
1105 | SecretName::CrossSigningSelfSigningKey => {
1106 if let Some(public_identity) =
1107 self.get_identity(self.user_id()).await?.and_then(|i| i.own())
1108 {
1109 let identity = self.inner.identity.lock().await;
1110
1111 identity
1112 .import_secret(
1113 public_identity,
1114 &secret.secret_name,
1115 &secret.event.content.secret,
1116 )
1117 .await?;
1118 info!(
1119 secret_name = ?secret.secret_name,
1120 "Successfully imported a private cross signing key"
1121 );
1122
1123 let changes =
1124 Changes { private_identity: Some(identity.clone()), ..Default::default() };
1125
1126 self.save_changes(changes).await?;
1127 }
1128 }
1129 SecretName::RecoveryKey => {
1130 }
1136 name => {
1137 warn!(secret = ?name, "Tried to import an unknown secret");
1138 }
1139 }
1140
1141 Ok(())
1142 }
1143
1144 pub async fn get_only_allow_trusted_devices(&self) -> Result<bool> {
1147 let value = self.get_value("only_allow_trusted_devices").await?.unwrap_or_default();
1148 Ok(value)
1149 }
1150
1151 pub async fn set_only_allow_trusted_devices(
1154 &self,
1155 block_untrusted_devices: bool,
1156 ) -> Result<()> {
1157 self.set_value("only_allow_trusted_devices", &block_untrusted_devices).await
1158 }
1159
1160 pub async fn get_value<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
1162 let Some(value) = self.get_custom_value(key).await? else {
1163 return Ok(None);
1164 };
1165 let deserialized = self.deserialize_value(&value)?;
1166 Ok(Some(deserialized))
1167 }
1168
1169 pub async fn set_value(&self, key: &str, value: &impl Serialize) -> Result<()> {
1171 let serialized = self.serialize_value(value)?;
1172 self.set_custom_value(key, serialized).await?;
1173 Ok(())
1174 }
1175
1176 fn serialize_value(&self, value: &impl Serialize) -> Result<Vec<u8>> {
1177 let serialized =
1178 rmp_serde::to_vec_named(value).map_err(|x| CryptoStoreError::Backend(x.into()))?;
1179 Ok(serialized)
1180 }
1181
1182 fn deserialize_value<T: DeserializeOwned>(&self, value: &[u8]) -> Result<T> {
1183 let deserialized =
1184 rmp_serde::from_slice(value).map_err(|e| CryptoStoreError::Backend(e.into()))?;
1185 Ok(deserialized)
1186 }
1187
1188 pub fn room_keys_received_stream(
1200 &self,
1201 ) -> impl Stream<Item = Result<Vec<RoomKeyInfo>, BroadcastStreamRecvError>> + use<> {
1202 self.inner.store.room_keys_received_stream()
1203 }
1204
1205 pub fn room_keys_withheld_received_stream(
1214 &self,
1215 ) -> impl Stream<Item = Vec<RoomKeyWithheldInfo>> + use<> {
1216 self.inner.store.room_keys_withheld_received_stream()
1217 }
1218
1219 pub fn user_identities_stream(&self) -> impl Stream<Item = IdentityUpdates> + use<> {
1250 let verification_machine = self.inner.verification_machine.to_owned();
1251
1252 let this = self.clone();
1253 self.inner.store.identities_stream().map(move |(own_identity, identities, _)| {
1254 let (new_identities, changed_identities, unchanged_identities) = identities.into_maps();
1255
1256 let map_identity = |(user_id, identity)| {
1257 (
1258 user_id,
1259 UserIdentity::new(
1260 this.clone(),
1261 identity,
1262 verification_machine.to_owned(),
1263 own_identity.to_owned(),
1264 ),
1265 )
1266 };
1267
1268 let new = new_identities.into_iter().map(map_identity).collect();
1269 let changed = changed_identities.into_iter().map(map_identity).collect();
1270 let unchanged = unchanged_identities.into_iter().map(map_identity).collect();
1271
1272 IdentityUpdates { new, changed, unchanged }
1273 })
1274 }
1275
1276 pub fn devices_stream(&self) -> impl Stream<Item = DeviceUpdates> + use<> {
1308 let verification_machine = self.inner.verification_machine.to_owned();
1309
1310 self.inner.store.identities_stream().map(move |(own_identity, identities, devices)| {
1311 collect_device_updates(
1312 verification_machine.to_owned(),
1313 own_identity,
1314 identities,
1315 devices,
1316 )
1317 })
1318 }
1319
1320 pub fn identities_stream_raw(
1330 &self,
1331 ) -> impl Stream<Item = (IdentityChanges, DeviceChanges)> + use<> {
1332 self.inner.store.identities_stream().map(|(_, identities, devices)| (identities, devices))
1333 }
1334
1335 pub fn create_store_lock(
1338 &self,
1339 lock_key: String,
1340 config: CrossProcessLockConfig,
1341 ) -> CrossProcessLock<LockableCryptoStore> {
1342 self.inner.store.create_store_lock(lock_key, config)
1343 }
1344
1345 pub fn secrets_stream(&self) -> impl Stream<Item = SecretsInboxItem> + use<> {
1385 self.inner.store.secrets_stream()
1386 }
1387
1388 pub fn historic_room_key_stream(&self) -> impl Stream<Item = RoomKeyBundleInfo> + use<> {
1428 self.inner.store.historic_room_key_stream()
1429 }
1430
1431 pub async fn import_room_keys(
1444 &self,
1445 exported_keys: Vec<ExportedRoomKey>,
1446 from_backup_version: Option<&str>,
1447 progress_listener: impl Fn(usize, usize),
1448 ) -> Result<RoomKeyImportResult> {
1449 let exported_keys = exported_keys.iter().filter_map(|key| {
1450 key.try_into()
1451 .map_err(|e| {
1452 warn!(
1453 sender_key = key.sender_key().to_base64(),
1454 room_id = ?key.room_id(),
1455 session_id = key.session_id(),
1456 error = ?e,
1457 "Couldn't import a room key from a file export."
1458 );
1459 })
1460 .ok()
1461 });
1462 self.import_sessions_impl(exported_keys, from_backup_version, progress_listener).await
1463 }
1464
1465 pub async fn import_exported_room_keys(
1492 &self,
1493 exported_keys: Vec<ExportedRoomKey>,
1494 progress_listener: impl Fn(usize, usize),
1495 ) -> Result<RoomKeyImportResult> {
1496 self.import_room_keys(exported_keys, None, progress_listener).await
1497 }
1498
1499 async fn import_sessions_impl(
1500 &self,
1501 sessions: impl Iterator<Item = InboundGroupSession>,
1502 from_backup_version: Option<&str>,
1503 progress_listener: impl Fn(usize, usize),
1504 ) -> Result<RoomKeyImportResult> {
1505 let sessions: Vec<_> = sessions.collect();
1506 let mut imported_sessions = Vec::new();
1507
1508 let total_count = sessions.len();
1509 let mut keys = BTreeMap::new();
1510
1511 for (i, session) in sessions.into_iter().enumerate() {
1512 if let Some(merged) = self.merge_received_group_session(session).await? {
1515 if from_backup_version.is_some() {
1516 merged.mark_as_backed_up();
1517 }
1518
1519 keys.entry(merged.room_id().to_owned())
1520 .or_insert_with(BTreeMap::new)
1521 .entry(merged.sender_key().to_base64())
1522 .or_insert_with(BTreeSet::new)
1523 .insert(merged.session_id().to_owned());
1524
1525 imported_sessions.push(merged);
1526 }
1527
1528 progress_listener(i, total_count);
1529 }
1530
1531 let imported_count = imported_sessions.len();
1532
1533 self.inner
1534 .store
1535 .save_inbound_group_sessions(imported_sessions, from_backup_version)
1536 .await?;
1537
1538 info!(total_count, imported_count, room_keys = ?keys, "Successfully imported room keys");
1539
1540 Ok(RoomKeyImportResult::new(imported_count, total_count, keys))
1541 }
1542
1543 pub(crate) fn crypto_store(&self) -> Arc<CryptoStoreWrapper> {
1544 self.inner.store.clone()
1545 }
1546
1547 pub async fn export_room_keys(
1570 &self,
1571 predicate: impl FnMut(&InboundGroupSession) -> bool,
1572 ) -> Result<Vec<ExportedRoomKey>> {
1573 let mut exported = Vec::new();
1574
1575 let mut sessions = self.get_inbound_group_sessions().await?;
1576 sessions.retain(predicate);
1577
1578 for session in sessions {
1579 let export = session.export().await;
1580 exported.push(export);
1581 }
1582
1583 Ok(exported)
1584 }
1585
1586 pub async fn export_room_keys_stream(
1621 &self,
1622 predicate: impl FnMut(&InboundGroupSession) -> bool,
1623 ) -> Result<impl Stream<Item = ExportedRoomKey>> {
1624 let sessions = self.get_inbound_group_sessions().await?;
1626 Ok(futures_util::stream::iter(sessions.into_iter().filter(predicate))
1627 .then(|session| async move { session.export().await }))
1628 }
1629
1630 pub async fn build_room_key_bundle(
1635 &self,
1636 room_id: &RoomId,
1637 ) -> std::result::Result<RoomKeyBundle, CryptoStoreError> {
1638 let sessions = self.get_inbound_group_sessions_by_room_id(room_id).await?;
1639
1640 let mut bundle = RoomKeyBundle::default();
1641 for session in sessions {
1642 if session.shared_history() {
1643 bundle.room_keys.push(session.export().await.into());
1644 } else {
1645 bundle.withheld.push(RoomKeyWithheldContent::new(
1646 session.algorithm().to_owned(),
1647 WithheldCode::HistoryNotShared,
1648 session.room_id().to_owned(),
1649 session.session_id().to_owned(),
1650 session.sender_key().to_owned(),
1651 self.device_id().to_owned(),
1652 ));
1653 }
1654 }
1655
1656 let withhelds = self.get_withheld_sessions_by_room_id(room_id).await?;
1659 for withheld in withhelds {
1660 if withheld.content.withheld_code() == WithheldCode::HistoryNotShared {
1661 bundle.withheld.push(withheld.content);
1662 }
1663 }
1664
1665 Ok(bundle)
1666 }
1667
1668 #[instrument(skip(self, bundle, progress_listener), fields(bundle_size = bundle.room_keys.len(), sender_data))]
1678 pub async fn receive_room_key_bundle(
1679 &self,
1680 bundle_info: &StoredRoomKeyBundleData,
1681 bundle: RoomKeyBundle,
1682 progress_listener: impl Fn(usize, usize),
1683 ) -> Result<(), CryptoStoreError> {
1684 let sender_data = if bundle_info.sender_data.should_recalculate() {
1685 let device = self
1686 .get_device_from_curve_key(&bundle_info.sender_user, bundle_info.sender_key)
1687 .await?;
1688
1689 device
1690 .as_ref()
1691 .map(SenderData::from_device)
1692 .unwrap_or_else(|| bundle_info.sender_data.clone())
1693 } else {
1694 bundle_info.sender_data.clone()
1695 };
1696
1697 tracing::Span::current().record("sender_data", tracing::field::debug(&sender_data));
1698
1699 let Ok(forwarder_data) = (&sender_data).try_into() else {
1703 warn!(
1704 "Not accepting a historic room key bundle due to insufficient trust in the sender"
1705 );
1706 return Ok(());
1707 };
1708
1709 self.import_room_key_bundle_sessions(
1710 bundle_info,
1711 &bundle,
1712 &forwarder_data,
1713 progress_listener,
1714 )
1715 .await?;
1716 self.import_room_key_bundle_withheld_info(bundle_info, &bundle).await?;
1717
1718 Ok(())
1719 }
1720
1721 async fn import_room_key_bundle_sessions(
1722 &self,
1723 bundle_info: &StoredRoomKeyBundleData,
1724 bundle: &RoomKeyBundle,
1725 forwarder_data: &ForwarderData,
1726 progress_listener: impl Fn(usize, usize),
1727 ) -> Result<(), CryptoStoreError> {
1728 let (good, bad): (Vec<_>, Vec<_>) = bundle.room_keys.iter().partition_map(|key| {
1729 if key.room_id != bundle_info.bundle_data.room_id {
1730 trace!("Ignoring key for incorrect room {} in bundle", key.room_id);
1731 Either::Right(key)
1732 } else {
1733 Either::Left(key)
1734 }
1735 });
1736
1737 match (bad.is_empty(), good.is_empty()) {
1738 (true, true) => {
1740 warn!("Received a completely empty room key bundle");
1741 }
1742
1743 (false, true) => {
1745 let bad_keys: Vec<_> =
1746 bad.iter().map(|&key| (&key.room_id, &key.session_id)).collect();
1747
1748 warn!(
1749 ?bad_keys,
1750 "Received a room key bundle for the wrong room, ignoring all room keys from the bundle"
1751 );
1752 }
1753
1754 (_, false) => {
1756 if !bad.is_empty() {
1759 warn!(
1760 bad_key_count = bad.len(),
1761 "The room key bundle contained some room keys \
1762 that were meant for a different room"
1763 );
1764 }
1765
1766 let keys = good.iter().filter_map(|key| {
1767 key.try_into_inbound_group_session(forwarder_data)
1768 .map_err(|e| {
1769 warn!(
1770 sender_key = ?key.sender_key().to_base64(),
1771 room_id = ?key.room_id(),
1772 session_id = key.session_id(),
1773 error = ?e,
1774 "Couldn't import a room key from a key bundle."
1775 );
1776 })
1777 .ok()
1778 });
1779
1780 self.import_sessions_impl(keys, None, progress_listener).await?;
1781 }
1782 }
1783
1784 Ok(())
1785 }
1786
1787 async fn import_room_key_bundle_withheld_info(
1788 &self,
1789 bundle_info: &StoredRoomKeyBundleData,
1790 bundle: &RoomKeyBundle,
1791 ) -> Result<(), CryptoStoreError> {
1792 let mut session_id_to_withheld_code_map = BTreeMap::new();
1793
1794 let mut changes = Changes::default();
1795 for withheld in &bundle.withheld {
1796 let (room_id, session_id) = match withheld {
1797 RoomKeyWithheldContent::MegolmV1AesSha2(c) => match (c.room_id(), c.session_id()) {
1798 (Some(room_id), Some(session_id)) => (room_id, session_id),
1799 _ => continue,
1800 },
1801 #[cfg(feature = "experimental-algorithms")]
1802 RoomKeyWithheldContent::MegolmV2AesSha2(c) => match (c.room_id(), c.session_id()) {
1803 (Some(room_id), Some(session_id)) => (room_id, session_id),
1804 _ => continue,
1805 },
1806 RoomKeyWithheldContent::Unknown(_) => continue,
1807 };
1808
1809 if room_id != bundle_info.bundle_data.room_id {
1810 trace!("Ignoring withheld info for incorrect room {} in bundle", room_id);
1811 continue;
1812 }
1813
1814 changes.withheld_session_info.entry(room_id.to_owned()).or_default().insert(
1815 session_id.to_owned(),
1816 RoomKeyWithheldEntry {
1817 sender: bundle_info.sender_user.clone(),
1818 content: withheld.to_owned(),
1819 },
1820 );
1821 session_id_to_withheld_code_map.insert(session_id, withheld.withheld_code());
1822 }
1823
1824 self.save_changes(changes).await?;
1825
1826 info!(
1827 room_id = ?bundle_info.bundle_data.room_id,
1828 ?session_id_to_withheld_code_map,
1829 "Successfully imported withheld info from room key bundle",
1830 );
1831
1832 Ok(())
1833 }
1834
1835 pub async fn store_room_pending_key_bundle(
1841 &self,
1842 room_id: &RoomId,
1843 inviter: &UserId,
1844 ) -> Result<(), CryptoStoreError> {
1845 let invite_accepted_at = MilliSecondsSinceUnixEpoch::now();
1846 self.save_changes(Changes {
1847 rooms_pending_key_bundle: HashMap::from([(
1848 room_id.to_owned(),
1849 Some(RoomPendingKeyBundleDetails {
1850 room_id: room_id.to_owned(),
1851 invite_accepted_at,
1852 inviter: inviter.to_owned(),
1853 }),
1854 )]),
1855 ..Default::default()
1856 })
1857 .await?;
1858
1859 Ok(())
1860 }
1861
1862 pub async fn clear_room_pending_key_bundle(&self, room_id: &RoomId) -> Result<()> {
1866 self.save_changes(Changes {
1867 rooms_pending_key_bundle: HashMap::from([(room_id.to_owned(), None)]),
1868 ..Default::default()
1869 })
1870 .await
1871 }
1872}
1873
1874impl Deref for Store {
1875 type Target = DynCryptoStore;
1876
1877 fn deref(&self) -> &Self::Target {
1878 self.inner.store.deref().deref()
1879 }
1880}
1881
1882#[derive(Clone, Debug)]
1884pub struct LockableCryptoStore(Arc<dyn CryptoStore<Error = CryptoStoreError>>);
1885
1886impl matrix_sdk_common::cross_process_lock::TryLock for LockableCryptoStore {
1887 type LockError = CryptoStoreError;
1888
1889 async fn try_lock(
1890 &self,
1891 lease_duration_ms: u32,
1892 key: &str,
1893 holder: &str,
1894 ) -> std::result::Result<Option<CrossProcessLockGeneration>, Self::LockError> {
1895 self.0.try_take_leased_lock(lease_duration_ms, key, holder).await
1896 }
1897}
1898
1899#[cfg(test)]
1900mod tests {
1901 use std::{collections::BTreeMap, pin::pin};
1902
1903 use assert_matches2::{assert_let, assert_matches};
1904 use futures_util::StreamExt;
1905 use insta::{_macro_support::Content, assert_json_snapshot, internals::ContentPath};
1906 use matrix_sdk_test::async_test;
1907 use rand::RngExt;
1908 use ruma::{
1909 RoomId, device_id,
1910 events::room::{EncryptedFile, EncryptedFileHashes, V2EncryptedFileInfo},
1911 owned_device_id, owned_mxc_uri, room_id, user_id,
1912 };
1913 use serde_json::json;
1914 use vodozemac::{Ed25519Keypair, megolm::SessionKey};
1915
1916 use crate::{
1917 Account, OlmMachine,
1918 machine::test_helpers::get_machine_pair,
1919 olm::{InboundGroupSession, SenderData},
1920 store::types::{DehydratedDeviceKey, RoomKeyWithheldEntry, StoredRoomKeyBundleData},
1921 types::{
1922 EventEncryptionAlgorithm,
1923 events::{
1924 room_key_bundle::RoomKeyBundleContent,
1925 room_key_withheld::{MegolmV1AesSha2WithheldContent, RoomKeyWithheldContent},
1926 },
1927 },
1928 };
1929
1930 #[async_test]
1931 async fn test_merge_received_group_session() {
1932 let alice_account = Account::with_device_id(user_id!("@a:s.co"), device_id!("ABC"));
1933 let bob = OlmMachine::new(user_id!("@b:s.co"), device_id!("DEF")).await;
1934
1935 let room_id = room_id!("!test:localhost");
1936
1937 let megolm_signing_key = Ed25519Keypair::new();
1938 let inbound = make_inbound_group_session(&alice_account, &megolm_signing_key, room_id);
1939
1940 let mut inbound_at_index_5 =
1942 InboundGroupSession::from_export(&inbound.export_at_index(5).await).unwrap();
1943 inbound_at_index_5.sender_data = inbound.sender_data.clone();
1944 bob.store().save_inbound_group_sessions(&[inbound_at_index_5.clone()]).await.unwrap();
1945
1946 let disconnected = make_inbound_group_session(&alice_account, &megolm_signing_key, room_id);
1948 assert_eq!(bob.store().merge_received_group_session(disconnected).await.unwrap(), None);
1949
1950 let mut worse =
1952 InboundGroupSession::from_export(&inbound.export_at_index(10).await).unwrap();
1953 worse.sender_data = inbound.sender_data.clone();
1954 assert_eq!(bob.store().merge_received_group_session(worse).await.unwrap(), None);
1955
1956 let mut copy = InboundGroupSession::from_pickle(inbound_at_index_5.pickle().await).unwrap();
1958 copy.sender_data = inbound.sender_data.clone();
1959 assert_eq!(bob.store().merge_received_group_session(copy).await.unwrap(), None);
1960
1961 let mut better =
1963 InboundGroupSession::from_export(&inbound.export_at_index(0).await).unwrap();
1964 better.sender_data = inbound.sender_data.clone();
1965 assert_let!(Some(update) = bob.store().merge_received_group_session(better).await.unwrap());
1966 assert_eq!(update.first_known_index(), 0);
1967
1968 {
1970 let mut worse_ratchet_better_trust =
1971 InboundGroupSession::from_export(&inbound.export_at_index(10).await).unwrap();
1972 let updated_sender_data = SenderData::sender_verified(
1973 alice_account.user_id(),
1974 alice_account.device_id(),
1975 Ed25519Keypair::new().public_key(),
1976 );
1977 worse_ratchet_better_trust.sender_data = updated_sender_data.clone();
1978 assert_let!(
1979 Some(update) = bob
1980 .store()
1981 .merge_received_group_session(worse_ratchet_better_trust)
1982 .await
1983 .unwrap()
1984 );
1985 assert_eq!(update.sender_data, updated_sender_data);
1986 assert_eq!(update.first_known_index(), 5);
1987 assert_eq!(
1988 update.export_at_index(0).await.session_key.to_bytes(),
1989 inbound.export_at_index(5).await.session_key.to_bytes()
1990 );
1991 }
1992
1993 {
1995 let mut better_ratchet_worse_trust =
1996 InboundGroupSession::from_export(&inbound.export_at_index(0).await).unwrap();
1997 let updated_sender_data = SenderData::unknown();
1998 better_ratchet_worse_trust.sender_data = updated_sender_data.clone();
1999 assert_let!(
2000 Some(update) = bob
2001 .store()
2002 .merge_received_group_session(better_ratchet_worse_trust)
2003 .await
2004 .unwrap()
2005 );
2006 assert_eq!(update.sender_data, inbound.sender_data);
2007 assert_eq!(update.first_known_index(), 0);
2008 assert_eq!(
2009 update.export_at_index(0).await.session_key.to_bytes(),
2010 inbound.export_at_index(0).await.session_key.to_bytes()
2011 );
2012 }
2013 }
2014
2015 fn make_inbound_group_session(
2018 sender_account: &Account,
2019 signing_key: &Ed25519Keypair,
2020 room_id: &RoomId,
2021 ) -> InboundGroupSession {
2022 InboundGroupSession::new(
2023 sender_account.identity_keys.curve25519,
2024 sender_account.identity_keys.ed25519,
2025 room_id,
2026 &make_session_key(signing_key),
2027 SenderData::device_info(crate::types::DeviceKeys::new(
2028 sender_account.user_id().to_owned(),
2029 sender_account.device_id().to_owned(),
2030 vec![],
2031 BTreeMap::new(),
2032 crate::types::Signatures::new(),
2033 )),
2034 None,
2035 EventEncryptionAlgorithm::MegolmV1AesSha2,
2036 Some(ruma::events::room::history_visibility::HistoryVisibility::Shared),
2037 true,
2038 )
2039 .unwrap()
2040 }
2041
2042 fn make_session_key(signing_key: &Ed25519Keypair) -> SessionKey {
2045 let mut session_key_bytes = vec![0u8; 229];
2050 session_key_bytes[0] = 2;
2052 rand::rng().fill(&mut session_key_bytes[5..133]);
2055 session_key_bytes[133..165].copy_from_slice(signing_key.public_key().as_bytes());
2057 let sig = signing_key.sign(&session_key_bytes[0..165]);
2059 session_key_bytes[165..229].copy_from_slice(&sig.to_bytes());
2060
2061 SessionKey::from_bytes(&session_key_bytes).unwrap()
2062 }
2063
2064 #[async_test]
2065 async fn test_import_room_keys_notifies_stream() {
2066 use futures_util::FutureExt;
2067
2068 let (alice, bob, _) =
2069 get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2070
2071 let room1_id = room_id!("!room1:localhost");
2072 alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2073 let exported_sessions = alice.store().export_room_keys(|_| true).await.unwrap();
2074
2075 let mut room_keys_received_stream = Box::pin(bob.store().room_keys_received_stream());
2076 bob.store().import_room_keys(exported_sessions, None, |_, _| {}).await.unwrap();
2077
2078 let room_keys = room_keys_received_stream
2079 .next()
2080 .now_or_never()
2081 .flatten()
2082 .expect("We should have received an update of room key infos")
2083 .unwrap();
2084 assert_eq!(room_keys.len(), 1);
2085 assert_eq!(room_keys[0].room_id, "!room1:localhost");
2086 }
2087
2088 #[async_test]
2089 async fn test_export_room_keys_provides_selected_keys() {
2090 let (alice, _, _) = get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2092 let room1_id = room_id!("!room1:localhost");
2093 let room2_id = room_id!("!room2:localhost");
2094 let room3_id = room_id!("!room3:localhost");
2095 alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2096 alice.create_outbound_group_session_with_defaults_test_helper(room2_id).await.unwrap();
2097 alice.create_outbound_group_session_with_defaults_test_helper(room3_id).await.unwrap();
2098
2099 let keys = alice
2101 .store()
2102 .export_room_keys(|s| s.room_id() == room2_id || s.room_id() == room3_id)
2103 .await
2104 .unwrap();
2105
2106 assert_eq!(keys.len(), 2);
2108 assert_eq!(keys[0].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2109 assert_eq!(keys[1].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2110 assert_eq!(keys[0].room_id, "!room2:localhost");
2111 assert_eq!(keys[1].room_id, "!room3:localhost");
2112 assert_eq!(keys[0].session_key.to_base64().len(), 220);
2113 assert_eq!(keys[1].session_key.to_base64().len(), 220);
2114 }
2115
2116 #[async_test]
2117 async fn test_export_room_keys_stream_can_provide_all_keys() {
2118 let (alice, _, _) = get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2120 let room1_id = room_id!("!room1:localhost");
2121 let room2_id = room_id!("!room2:localhost");
2122 alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2123 alice.create_outbound_group_session_with_defaults_test_helper(room2_id).await.unwrap();
2124
2125 let mut keys = pin!(alice.store().export_room_keys_stream(|_| true).await.unwrap());
2127
2128 let mut collected = vec![];
2130 while let Some(key) = keys.next().await {
2131 collected.push(key);
2132 }
2133
2134 assert_eq!(collected.len(), 2);
2136 assert_eq!(collected[0].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2137 assert_eq!(collected[1].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2138 assert_eq!(collected[0].room_id, "!room1:localhost");
2139 assert_eq!(collected[1].room_id, "!room2:localhost");
2140 assert_eq!(collected[0].session_key.to_base64().len(), 220);
2141 assert_eq!(collected[1].session_key.to_base64().len(), 220);
2142 }
2143
2144 #[async_test]
2145 async fn test_export_room_keys_stream_can_provide_a_subset_of_keys() {
2146 let (alice, _, _) = get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2148 let room1_id = room_id!("!room1:localhost");
2149 let room2_id = room_id!("!room2:localhost");
2150 alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2151 alice.create_outbound_group_session_with_defaults_test_helper(room2_id).await.unwrap();
2152
2153 let mut keys =
2155 pin!(alice.store().export_room_keys_stream(|s| s.room_id() == room1_id).await.unwrap());
2156
2157 let mut collected = vec![];
2159 while let Some(key) = keys.next().await {
2160 collected.push(key);
2161 }
2162
2163 assert_eq!(collected.len(), 1);
2165 assert_eq!(collected[0].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2166 assert_eq!(collected[0].room_id, "!room1:localhost");
2167 assert_eq!(collected[0].session_key.to_base64().len(), 220);
2168 }
2169
2170 #[async_test]
2171 async fn test_export_secrets_bundle() {
2172 let user_id = user_id!("@alice:example.com");
2173 let (first, second, _) = get_machine_pair(user_id, user_id, false).await;
2174
2175 let _ = first
2176 .bootstrap_cross_signing(false)
2177 .await
2178 .expect("We should be able to bootstrap cross-signing");
2179
2180 let bundle = first.store().export_secrets_bundle().await.expect(
2181 "We should be able to export the secrets bundle, now that we \
2182 have the cross-signing keys",
2183 );
2184
2185 assert!(bundle.backup.is_none(), "The bundle should not contain a backup key");
2186
2187 second
2188 .store()
2189 .import_secrets_bundle(&bundle)
2190 .await
2191 .expect("We should be able to import the secrets bundle");
2192
2193 let status = second.cross_signing_status().await;
2194 let identity = second.get_identity(user_id, None).await.unwrap().unwrap().own().unwrap();
2195
2196 assert!(identity.is_verified(), "The public identity should be marked as verified.");
2197
2198 assert!(status.is_complete(), "We should have imported all the cross-signing keys");
2199 }
2200
2201 #[async_test]
2202 async fn test_create_dehydrated_device_key() {
2203 let pickle_key = DehydratedDeviceKey::new();
2204
2205 let to_vec = pickle_key.inner.to_vec();
2206 let pickle_key_from_slice = DehydratedDeviceKey::from_slice(to_vec.as_slice())
2207 .expect("Should be able to create a dehydrated device key from slice");
2208
2209 assert_eq!(pickle_key_from_slice.to_base64(), pickle_key.to_base64());
2210 }
2211
2212 #[async_test]
2213 async fn test_create_dehydrated_errors() {
2214 let too_small = [0u8; 22];
2215 let pickle_key = DehydratedDeviceKey::from_slice(&too_small);
2216
2217 assert!(pickle_key.is_err());
2218
2219 let too_big = [0u8; 40];
2220 let pickle_key = DehydratedDeviceKey::from_slice(&too_big);
2221
2222 assert!(pickle_key.is_err());
2223 }
2224
2225 #[async_test]
2226 async fn test_build_room_key_bundle() {
2227 let alice = OlmMachine::new(user_id!("@a:s.co"), device_id!("ALICE")).await;
2230 let bob = OlmMachine::new(user_id!("@b:s.co"), device_id!("BOB")).await;
2231
2232 let room1_id = room_id!("!room1:localhost");
2233 let room2_id = room_id!("!room2:localhost");
2234
2235 let session_key1 = "AgAAAAC2XHVzsMBKs4QCRElJ92CJKyGtknCSC8HY7cQ7UYwndMKLQAejXLh5UA0l6s736mgctcUMNvELScUWrObdflrHo+vth/gWreXOaCnaSxmyjjKErQwyIYTkUfqbHy40RJfEesLwnN23on9XAkch/iy8R2+Jz7B8zfG01f2Ow2SxPQFnAndcO1ZSD2GmXgedy6n4B20MWI1jGP2wiexOWbFSya8DO/VxC9m5+/mF+WwYqdpKn9g4Y05Yw4uz7cdjTc3rXm7xK+8E7hI//5QD1nHPvuKYbjjM9u2JSL+Bzp61Cw";
2240 let session_key2 = "AgAAAAC1BXreFTUQQSBGekTEuYxhdytRKyv4JgDGcG+VOBYdPNGgs807SdibCGJky4lJ3I+7ZDGHoUzZPZP/4ogGu4kxni0PWdtWuN7+5zsuamgoFF/BkaGeUUGv6kgIkx8pyPpM5SASTUEP9bN2loDSpUPYwfiIqz74DgC4WQ4435sTBctYvKz8n+TDJwdLXpyT6zKljuqADAioud+s/iqx9LYn9HpbBfezZcvbg67GtE113pLrvde3IcPI5s6dNHK2onGO2B2eoaobcen18bbEDnlUGPeIivArLya7Da6us14jBQ";
2241 let session_key3 = "AgAAAAAM9KFsliaUUhGSXgwOzM5UemjkNH4n8NHgvC/y8hhw13zTF+ooGD4uIYEXYX630oNvQm/EvgZo+dkoc0re+vsqsx4sQeNODdSjcBsWOa0oDF+irQn9oYoLUDPI1IBtY1rX+FV99Zm/xnG7uFOX7aTVlko2GSdejy1w9mfobmfxu5aUc04A9zaKJP1pOthZvRAlhpymGYHgsDtWPrrjyc/yypMflE4kIUEEEtu1kT6mrAmcl615XYRAHYK9G2+fZsGvokwzbkl4nulGwcZMpQEoM0nD2o3GWgX81HW3nGfKBg";
2242 let session_key4 = "AgAAAAA4Kkesxq2h4v9PLD6Sm3Smxspz1PXTqytQPCMQMkkrHNmzV2bHlJ+6/Al9cu8vh1Oj69AK0WUAeJOJuaiskEeg/PI3P03+UYLeC379RzgqwSHdBgdQ41G2vD6zpgmE/8vYToe+qpCZACtPOswZxyqxHH+T/Iq0nv13JmlFGIeA6fEPfr5Y28B49viG74Fs9rxV9EH5PfjbuPM/p+Sz5obShuaBPKQBX1jT913nEXPoIJ06exNZGr0285nw/LgVvNlmWmbqNnbzO2cNZjQWA+xZYz5FSfyCxwqEBbEdUCuRCQ";
2243
2244 let sessions = [
2245 create_inbound_group_session_with_visibility(
2246 &alice,
2247 room1_id,
2248 &SessionKey::from_base64(session_key1).unwrap(),
2249 true,
2250 ),
2251 create_inbound_group_session_with_visibility(
2252 &alice,
2253 room1_id,
2254 &SessionKey::from_base64(session_key2).unwrap(),
2255 true,
2256 ),
2257 create_inbound_group_session_with_visibility(
2258 &alice,
2259 room1_id,
2260 &SessionKey::from_base64(session_key3).unwrap(),
2261 false,
2262 ),
2263 create_inbound_group_session_with_visibility(
2264 &alice,
2265 room2_id,
2266 &SessionKey::from_base64(session_key4).unwrap(),
2267 true,
2268 ),
2269 ];
2270 bob.store().save_inbound_group_sessions(&sessions).await.unwrap();
2271
2272 let mut bundle = bob.store().build_room_key_bundle(room1_id).await.unwrap();
2274
2275 bundle.room_keys.sort_by_key(|session| session.session_id.clone());
2279
2280 let algorithm = if cfg!(feature = "experimental-algorithms") {
2282 "m.megolm.v2.aes-sha2"
2283 } else {
2284 "m.megolm.v1.aes-sha2"
2285 };
2286 let map_algorithm = move |value: Content, _path: ContentPath<'_>| {
2287 assert_eq!(value.as_str().unwrap(), algorithm);
2288 "[algorithm]"
2289 };
2290
2291 let alice_curve_key = alice.identity_keys().curve25519.to_base64();
2293 let map_alice_curve_key = move |value: Content, _path: ContentPath<'_>| {
2294 assert_eq!(value.as_str().unwrap(), alice_curve_key);
2295 "[alice curve key]"
2296 };
2297 let alice_ed25519_key = alice.identity_keys().ed25519.to_base64();
2298 let map_alice_ed25519_key = move |value: Content, _path: ContentPath<'_>| {
2299 assert_eq!(value.as_str().unwrap(), alice_ed25519_key);
2300 "[alice ed25519 key]"
2301 };
2302
2303 insta::with_settings!({ sort_maps => true }, {
2304 assert_json_snapshot!(bundle, {
2305 ".withheld[].algorithm" => insta::dynamic_redaction(map_algorithm),
2306 ".room_keys[].algorithm" => insta::dynamic_redaction(map_algorithm),
2307 ".room_keys[].sender_key" => insta::dynamic_redaction(map_alice_curve_key.clone()),
2308 ".withheld[].sender_key" => insta::dynamic_redaction(map_alice_curve_key),
2309 ".room_keys[].sender_claimed_keys.ed25519" => insta::dynamic_redaction(map_alice_ed25519_key),
2310 });
2311 });
2312 }
2313
2314 #[async_test]
2315 async fn test_receive_room_key_bundle() {
2316 let alice = OlmMachine::new(user_id!("@a:s.co"), device_id!("ALICE")).await;
2317 let alice_key = alice.identity_keys().curve25519;
2318 let bob = OlmMachine::new(user_id!("@b:s.co"), device_id!("BOB")).await;
2319
2320 let room_id = room_id!("!room1:localhost");
2321
2322 let session_key1 = "AgAAAAC2XHVzsMBKs4QCRElJ92CJKyGtknCSC8HY7cQ7UYwndMKLQAejXLh5UA0l6s736mgctcUMNvELScUWrObdflrHo+vth/gWreXOaCnaSxmyjjKErQwyIYTkUfqbHy40RJfEesLwnN23on9XAkch/iy8R2+Jz7B8zfG01f2Ow2SxPQFnAndcO1ZSD2GmXgedy6n4B20MWI1jGP2wiexOWbFSya8DO/VxC9m5+/mF+WwYqdpKn9g4Y05Yw4uz7cdjTc3rXm7xK+8E7hI//5QD1nHPvuKYbjjM9u2JSL+Bzp61Cw";
2323 let session_key2 = "AgAAAAC1BXreFTUQQSBGekTEuYxhdytRKyv4JgDGcG+VOBYdPNGgs807SdibCGJky4lJ3I+7ZDGHoUzZPZP/4ogGu4kxni0PWdtWuN7+5zsuamgoFF/BkaGeUUGv6kgIkx8pyPpM5SASTUEP9bN2loDSpUPYwfiIqz74DgC4WQ4435sTBctYvKz8n+TDJwdLXpyT6zKljuqADAioud+s/iqx9LYn9HpbBfezZcvbg67GtE113pLrvde3IcPI5s6dNHK2onGO2B2eoaobcen18bbEDnlUGPeIivArLya7Da6us14jBQ";
2324
2325 let sessions = [
2326 create_inbound_group_session_with_visibility(
2327 &alice,
2328 room_id,
2329 &SessionKey::from_base64(session_key1).unwrap(),
2330 true,
2331 ),
2332 create_inbound_group_session_with_visibility(
2333 &alice,
2334 room_id,
2335 &SessionKey::from_base64(session_key2).unwrap(),
2336 false,
2337 ),
2338 ];
2339
2340 alice.store().save_inbound_group_sessions(&sessions).await.unwrap();
2341 let bundle = alice.store().build_room_key_bundle(room_id).await.unwrap();
2342
2343 bob.store()
2344 .receive_room_key_bundle(
2345 &StoredRoomKeyBundleData {
2346 sender_user: alice.user_id().to_owned(),
2347 sender_key: alice_key,
2348 sender_data: SenderData::sender_verified(
2349 alice.user_id(),
2350 device_id!("ALICE"),
2351 alice.identity_keys().ed25519,
2352 ),
2353
2354 bundle_data: RoomKeyBundleContent {
2355 room_id: room_id.to_owned(),
2356 file: EncryptedFile::new(
2359 owned_mxc_uri!("mxc://example.com/0"),
2360 V2EncryptedFileInfo::encode([0; 32], [0; 16]).into(),
2361 EncryptedFileHashes::with_sha256([0; 32]),
2362 ),
2363 },
2364 },
2365 bundle,
2366 |_, _| {},
2367 )
2368 .await
2369 .unwrap();
2370
2371 let imported_sessions =
2373 bob.store().get_inbound_group_sessions_by_room_id(room_id).await.unwrap();
2374
2375 assert_eq!(imported_sessions.len(), 1);
2376 assert_eq!(imported_sessions[0].room_id(), room_id);
2377
2378 assert_eq!(
2380 imported_sessions[0]
2381 .forwarder_data
2382 .as_ref()
2383 .expect("Session should contain forwarder data.")
2384 .user_id(),
2385 alice.user_id()
2386 );
2387
2388 assert_matches!(
2389 bob.store()
2390 .get_withheld_info(room_id, sessions[1].session_id())
2391 .await
2392 .unwrap()
2393 .expect("Withheld info should be present in the store."),
2394 RoomKeyWithheldEntry {
2395 #[cfg(not(feature = "experimental-algorithms"))]
2396 content: RoomKeyWithheldContent::MegolmV1AesSha2(
2397 MegolmV1AesSha2WithheldContent::HistoryNotShared(_)
2398 ),
2399 #[cfg(feature = "experimental-algorithms")]
2400 content: RoomKeyWithheldContent::MegolmV2AesSha2(
2401 MegolmV1AesSha2WithheldContent::HistoryNotShared(_)
2402 ),
2403 ..
2404 }
2405 );
2406 }
2407
2408 #[async_test]
2414 async fn test_deserialize_room_key_withheld_entry_from_to_device_event() {
2415 let entry: RoomKeyWithheldEntry = serde_json::from_value(json!(
2416 {
2417 "content": {
2418 "algorithm": "m.megolm.v1.aes-sha2",
2419 "code": "m.unauthorised",
2420 "from_device": "ALICE",
2421 "reason": "You are not authorised to read the message.",
2422 "room_id": "!roomid:s.co",
2423 "sender_key": "7hIcOrEroXYdzjtCBvBjUiqvT0Me7g+ymeXqoc65RS0",
2424 "session_id": "session123"
2425 },
2426 "sender": "@alice:s.co",
2427 "type": "m.room_key.withheld"
2428 }
2429 ))
2430 .unwrap();
2431
2432 assert_matches!(
2433 entry,
2434 RoomKeyWithheldEntry {
2435 sender,
2436 content: RoomKeyWithheldContent::MegolmV1AesSha2(
2437 MegolmV1AesSha2WithheldContent::Unauthorised(withheld_content,)
2438 ),
2439 }
2440 );
2441
2442 assert_eq!(sender, "@alice:s.co");
2443 assert_eq!(withheld_content.room_id, "!roomid:s.co");
2444 assert_eq!(withheld_content.session_id, "session123");
2445 assert_eq!(
2446 withheld_content.sender_key.to_base64(),
2447 "7hIcOrEroXYdzjtCBvBjUiqvT0Me7g+ymeXqoc65RS0"
2448 );
2449 assert_eq!(withheld_content.from_device, Some(owned_device_id!("ALICE")));
2450 }
2451
2452 fn create_inbound_group_session_with_visibility(
2463 olm_machine: &OlmMachine,
2464 room_id: &RoomId,
2465 session_key: &SessionKey,
2466 shared_history: bool,
2467 ) -> InboundGroupSession {
2468 let identity_keys = &olm_machine.store().static_account().identity_keys;
2469 InboundGroupSession::new(
2470 identity_keys.curve25519,
2471 identity_keys.ed25519,
2472 room_id,
2473 session_key,
2474 SenderData::unknown(),
2475 None,
2476 #[cfg(not(feature = "experimental-algorithms"))]
2477 EventEncryptionAlgorithm::MegolmV1AesSha2,
2478 #[cfg(feature = "experimental-algorithms")]
2479 EventEncryptionAlgorithm::MegolmV2AesSha2,
2480 None,
2481 shared_history,
2482 )
2483 .unwrap()
2484 }
2485}