1use std::{
45 collections::{BTreeMap, BTreeSet, HashMap, HashSet},
46 fmt::Debug,
47 ops::Deref,
48 pin::pin,
49 sync::{Arc, atomic::Ordering},
50 time::Duration,
51};
52
53use as_variant::as_variant;
54use futures_core::Stream;
55use futures_util::StreamExt;
56use itertools::{Either, Itertools};
57use ruma::{
58 DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, RoomId, UserId,
59 encryption::KeyUsage, events::secret::request::SecretName,
60};
61use serde::{Serialize, de::DeserializeOwned};
62use thiserror::Error;
63use tokio::sync::{Mutex, Notify, OwnedRwLockWriteGuard, RwLock};
64use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
65use tracing::{info, instrument, trace, warn};
66use types::{RoomKeyBundleInfo, StoredRoomKeyBundleData};
67use vodozemac::{Curve25519PublicKey, megolm::SessionOrdering};
68
69use self::types::{
70 Changes, CrossSigningKeyExport, DeviceChanges, DeviceUpdates, IdentityChanges, IdentityUpdates,
71 PendingChanges, RoomKeyInfo, RoomKeyWithheldInfo, RoomPendingKeyBundleDetails,
72 UserKeyQueryResult,
73};
74use crate::{
75 CrossSigningStatus, OwnUserIdentityData, RoomKeyImportResult,
76 gossiping::GossippedSecret,
77 identities::{Device, DeviceData, UserDevices, UserIdentityData, user::UserIdentity},
78 olm::{
79 Account, ExportedRoomKey, ForwarderData, InboundGroupSession, PrivateCrossSigningIdentity,
80 SenderData, Session, StaticAccountData,
81 },
82 store::types::{RoomKeyWithheldEntry, SecretsInboxItem},
83 types::{
84 BackupSecrets, CrossSigningSecrets, MegolmBackupV1Curve25519AesSha2Secrets, RoomKeyExport,
85 SecretsBundle,
86 },
87 verification::VerificationMachine,
88};
89#[cfg(doc)]
90use crate::{backups::BackupMachine, identities::OwnUserIdentity};
91
92pub mod caches;
93mod crypto_store_wrapper;
94mod error;
95mod memorystore;
96mod traits;
97pub mod types;
98
99#[cfg(any(test, feature = "testing"))]
100#[macro_use]
101#[allow(missing_docs)]
102pub mod integration_tests;
103
104pub(crate) use crypto_store_wrapper::CryptoStoreWrapper;
105#[cfg(any(test, feature = "testing"))]
106pub use crypto_store_wrapper::{
107 HISTORIC_ROOM_KEY_BUNDLES_BROADCASTER_CAPACITY, IDENTITIES_BROADCASTER_CAPACITY,
108 ROOM_KEYS_RECEIVED_CAPACITY, ROOM_KEYS_WITHHELD_RECEIVED_CAPACITY,
109 SECRETS_BROADCASTER_CAPACITY,
110};
111pub use error::{CryptoStoreError, Result};
112use matrix_sdk_common::{
113 cross_process_lock::{CrossProcessLock, CrossProcessLockConfig, CrossProcessLockGeneration},
114 deserialized_responses::WithheldCode,
115 timeout::timeout,
116};
117pub use memorystore::MemoryStore;
118pub use traits::{CryptoStore, DynCryptoStore, IntoCryptoStore};
119
120use self::caches::{SequenceNumber, StoreCache, StoreCacheGuard, UsersForKeyQuery};
121use crate::types::{
122 events::room_key_withheld::RoomKeyWithheldContent, room_history::RoomKeyBundle,
123};
124#[cfg(feature = "experimental-x509-identity-verification")]
125use crate::x509::{X509Signer, X509Verifier};
126pub use crate::{
127 dehydrated_devices::DehydrationError,
128 gossiping::{GossipRequest, SecretInfo},
129};
130
131#[derive(Debug, Clone)]
138pub struct Store {
139 inner: Arc<StoreInner>,
140}
141
142#[derive(Debug, Default)]
143pub(crate) struct KeyQueryManager {
144 users_for_key_query: Mutex<UsersForKeyQuery>,
146
147 users_for_key_query_notify: Notify,
149}
150
151impl KeyQueryManager {
152 pub async fn synced<'a>(&'a self, cache: &'a StoreCache) -> Result<SyncedKeyQueryManager<'a>> {
153 self.ensure_sync_tracked_users(cache).await?;
154 Ok(SyncedKeyQueryManager { cache, manager: self })
155 }
156
157 async fn ensure_sync_tracked_users(&self, cache: &StoreCache) -> Result<()> {
164 let loaded = cache.loaded_tracked_users.read().await;
166 if *loaded {
167 return Ok(());
168 }
169
170 drop(loaded);
172 let mut loaded = cache.loaded_tracked_users.write().await;
173
174 if *loaded {
178 return Ok(());
179 }
180
181 let tracked_users = cache.store.load_tracked_users().await?;
182
183 let mut query_users_lock = self.users_for_key_query.lock().await;
184 let mut tracked_users_cache = cache.tracked_users.write();
185 for user in tracked_users {
186 tracked_users_cache.insert(user.user_id.to_owned());
187
188 if user.dirty {
189 query_users_lock.insert_user(&user.user_id);
190 }
191 }
192
193 *loaded = true;
194
195 Ok(())
196 }
197
198 pub async fn wait_if_user_key_query_pending(
208 &self,
209 cache: StoreCacheGuard,
210 timeout_duration: Duration,
211 user: &UserId,
212 ) -> Result<UserKeyQueryResult> {
213 {
214 self.ensure_sync_tracked_users(&cache).await?;
218 drop(cache);
219 }
220
221 let mut users_for_key_query = self.users_for_key_query.lock().await;
222 let Some(waiter) = users_for_key_query.maybe_register_waiting_task(user) else {
223 return Ok(UserKeyQueryResult::WasNotPending);
224 };
225
226 let wait_for_completion = async {
227 while !waiter.completed.load(Ordering::Relaxed) {
228 let mut notified = pin!(self.users_for_key_query_notify.notified());
232 notified.as_mut().enable();
233 drop(users_for_key_query);
234
235 notified.await;
237
238 users_for_key_query = self.users_for_key_query.lock().await;
242 }
243 };
244
245 match timeout(Box::pin(wait_for_completion), timeout_duration).await {
246 Err(_) => {
247 warn!(
248 user_id = ?user,
249 "The user has a pending `/keys/query` request which did \
250 not finish yet, some devices might be missing."
251 );
252
253 Ok(UserKeyQueryResult::TimeoutExpired)
254 }
255 _ => Ok(UserKeyQueryResult::WasPending),
256 }
257 }
258}
259
260pub(crate) struct SyncedKeyQueryManager<'a> {
261 cache: &'a StoreCache,
262 manager: &'a KeyQueryManager,
263}
264
265impl SyncedKeyQueryManager<'_> {
266 pub async fn update_tracked_users(&self, users: impl Iterator<Item = &UserId>) -> Result<()> {
271 let mut store_updates = Vec::new();
272 let mut key_query_lock = self.manager.users_for_key_query.lock().await;
273
274 {
275 let mut tracked_users = self.cache.tracked_users.write();
276 for user_id in users {
277 if tracked_users.insert(user_id.to_owned()) {
278 key_query_lock.insert_user(user_id);
279 store_updates.push((user_id, true))
280 }
281 }
282 }
283
284 self.cache.store.save_tracked_users(&store_updates).await
285 }
286
287 pub async fn mark_tracked_users_as_changed(
294 &self,
295 users: impl Iterator<Item = &UserId>,
296 ) -> Result<()> {
297 let mut store_updates: Vec<(&UserId, bool)> = Vec::new();
298 let mut key_query_lock = self.manager.users_for_key_query.lock().await;
299
300 {
301 let tracked_users = &self.cache.tracked_users.read();
302 for user_id in users {
303 if tracked_users.contains(user_id) {
304 key_query_lock.insert_user(user_id);
305 store_updates.push((user_id, true));
306 }
307 }
308 }
309
310 self.cache.store.save_tracked_users(&store_updates).await
311 }
312
313 pub async fn mark_tracked_users_as_up_to_date(
319 &self,
320 users: impl Iterator<Item = &UserId>,
321 sequence_number: SequenceNumber,
322 ) -> Result<()> {
323 let mut store_updates: Vec<(&UserId, bool)> = Vec::new();
324 let mut key_query_lock = self.manager.users_for_key_query.lock().await;
325
326 {
327 let tracked_users = self.cache.tracked_users.read();
328 for user_id in users {
329 if tracked_users.contains(user_id) {
330 let clean = key_query_lock.maybe_remove_user(user_id, sequence_number);
331 store_updates.push((user_id, !clean));
332 }
333 }
334 }
335
336 self.cache.store.save_tracked_users(&store_updates).await?;
337 self.manager.users_for_key_query_notify.notify_waiters();
339
340 Ok(())
341 }
342
343 pub async fn users_for_key_query(&self) -> (HashSet<OwnedUserId>, SequenceNumber) {
355 self.manager.users_for_key_query.lock().await.users_for_key_query()
356 }
357
358 pub fn tracked_users(&self) -> HashSet<OwnedUserId> {
360 self.cache.tracked_users.read().iter().cloned().collect()
361 }
362
363 pub async fn mark_user_as_changed(&self, user: &UserId) -> Result<()> {
369 self.manager.users_for_key_query.lock().await.insert_user(user);
370 self.cache.tracked_users.write().insert(user.to_owned());
371
372 self.cache.store.save_tracked_users(&[(user, true)]).await
373 }
374}
375
376fn collect_device_updates(
382 verification_machine: VerificationMachine,
383 own_identity: Option<OwnUserIdentityData>,
384 identities: IdentityChanges,
385 devices: DeviceChanges,
386 #[cfg(feature = "experimental-x509-identity-verification")] x509_verifier: Option<X509Verifier>,
387) -> DeviceUpdates {
388 let mut new: BTreeMap<_, BTreeMap<_, _>> = BTreeMap::new();
389 let mut changed: BTreeMap<_, BTreeMap<_, _>> = BTreeMap::new();
390
391 let (new_identities, changed_identities, unchanged_identities) = identities.into_maps();
392
393 let map_device = |device: DeviceData| {
394 let device_owner_identity = new_identities
395 .get(device.user_id())
396 .or_else(|| changed_identities.get(device.user_id()))
397 .or_else(|| unchanged_identities.get(device.user_id()))
398 .cloned();
399
400 Device {
401 inner: device,
402 verification_machine: verification_machine.to_owned(),
403 own_identity: own_identity.to_owned(),
404 device_owner_identity,
405 #[cfg(feature = "experimental-x509-identity-verification")]
406 x509_verifier: x509_verifier.to_owned(),
407 }
408 };
409
410 for device in devices.new {
411 let device = map_device(device);
412
413 new.entry(device.user_id().to_owned())
414 .or_default()
415 .insert(device.device_id().to_owned(), device);
416 }
417
418 for device in devices.changed {
419 let device = map_device(device);
420
421 changed
422 .entry(device.user_id().to_owned())
423 .or_default()
424 .insert(device.device_id().to_owned(), device.to_owned());
425 }
426
427 DeviceUpdates { new, changed }
428}
429
430#[allow(missing_debug_implementations)]
432pub struct StoreTransaction {
433 store: Store,
434 changes: PendingChanges,
435 cache: OwnedRwLockWriteGuard<StoreCache>,
437}
438
439impl StoreTransaction {
440 async fn new(store: Store) -> Self {
442 let cache = store.inner.cache.clone();
443
444 Self { store, changes: PendingChanges::default(), cache: cache.clone().write_owned().await }
445 }
446
447 pub(crate) fn cache(&self) -> &StoreCache {
448 &self.cache
449 }
450
451 pub fn store(&self) -> &Store {
453 &self.store
454 }
455
456 pub async fn account(&mut self) -> Result<&mut Account> {
463 if self.changes.account.is_none() {
464 let _ = self.cache.account().await?;
466 self.changes.account = self.cache.account.lock().await.take();
467 }
468 Ok(self.changes.account.as_mut().unwrap())
469 }
470
471 pub async fn commit(self) -> Result<()> {
474 if self.changes.is_empty() {
475 return Ok(());
476 }
477
478 let account = self.changes.account.as_ref().map(|acc| acc.deep_clone());
480
481 self.store.save_pending_changes(self.changes).await?;
482
483 if let Some(account) = account {
485 *self.cache.account.lock().await = Some(account);
486 }
487
488 Ok(())
489 }
490}
491
492#[derive(Debug)]
493struct StoreInner {
494 identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
495 store: Arc<CryptoStoreWrapper>,
496
497 cache: Arc<RwLock<StoreCache>>,
501
502 verification_machine: VerificationMachine,
503
504 #[cfg(feature = "experimental-x509-identity-verification")]
507 x509_verifier: Option<X509Verifier>,
508
509 #[cfg(feature = "experimental-x509-identity-verification")]
512 x509_signer: Option<X509Signer>,
513
514 static_account: StaticAccountData,
517}
518
519#[derive(Debug, Error)]
522pub enum SecretImportError {
523 #[error("Error while importing {name}: {error}")]
525 Key {
526 name: SecretName,
528 error: vodozemac::KeyError,
530 },
531 #[error(
534 "Error while importing {name}: The public key of the imported private \
535 key doesn't match the public key that was uploaded to the server"
536 )]
537 MismatchedPublicKeys {
538 name: SecretName,
540 },
541 #[error(transparent)]
543 Store(#[from] CryptoStoreError),
544}
545
546#[derive(Debug, Error)]
551pub enum SecretsBundleExportError {
552 #[error(transparent)]
554 Store(#[from] CryptoStoreError),
555 #[error("The store is missing one or multiple cross-signing keys")]
557 MissingCrossSigningKey(KeyUsage),
558 #[error("The store doesn't contain any cross-signing keys")]
560 MissingCrossSigningKeys,
561 #[error("The store contains a backup key, but no backup version")]
564 MissingBackupVersion,
565}
566
567impl Store {
568 pub(crate) fn new(
570 account: StaticAccountData,
571 identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
572 store: Arc<CryptoStoreWrapper>,
573 verification_machine: VerificationMachine,
574 ) -> Self {
575 Self::new_with_x509(
576 account,
577 identity,
578 store,
579 verification_machine,
580 #[cfg(feature = "experimental-x509-identity-verification")]
581 None,
582 #[cfg(feature = "experimental-x509-identity-verification")]
583 None,
584 )
585 }
586
587 pub(crate) fn new_with_x509(
589 account: StaticAccountData,
590 identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
591 store: Arc<CryptoStoreWrapper>,
592 verification_machine: VerificationMachine,
593 #[cfg(feature = "experimental-x509-identity-verification")] x509_verifier: Option<
594 X509Verifier,
595 >,
596 #[cfg(feature = "experimental-x509-identity-verification")] x509_signer: Option<X509Signer>,
597 ) -> Self {
598 Self {
599 inner: Arc::new(StoreInner {
600 static_account: account,
601 identity,
602 store: store.clone(),
603 verification_machine,
604 #[cfg(feature = "experimental-x509-identity-verification")]
605 x509_verifier,
606 #[cfg(feature = "experimental-x509-identity-verification")]
607 x509_signer,
608 cache: Arc::new(RwLock::new(StoreCache {
609 store,
610 tracked_users: Default::default(),
611 loaded_tracked_users: Default::default(),
612 account: Default::default(),
613 })),
614 }),
615 }
616 }
617
618 pub(crate) fn user_id(&self) -> &UserId {
620 &self.inner.static_account.user_id
621 }
622
623 pub(crate) fn device_id(&self) -> &DeviceId {
625 self.inner.verification_machine.own_device_id()
626 }
627
628 pub(crate) fn static_account(&self) -> &StaticAccountData {
630 &self.inner.static_account
631 }
632
633 #[cfg(feature = "experimental-x509-identity-verification")]
636 pub(crate) fn x509_signer(&self) -> Option<&X509Signer> {
637 self.inner.x509_signer.as_ref()
638 }
639
640 #[cfg(feature = "experimental-x509-identity-verification")]
643 pub(crate) fn x509_verifier(&self) -> Option<&X509Verifier> {
644 self.inner.x509_verifier.as_ref()
645 }
646
647 pub(crate) async fn cache(&self) -> Result<StoreCacheGuard> {
648 Ok(StoreCacheGuard { cache: self.inner.cache.clone().read_owned().await })
649 }
650
651 pub(crate) async fn transaction(&self) -> StoreTransaction {
652 StoreTransaction::new(self.clone()).await
653 }
654
655 pub(crate) async fn with_transaction<T>(
656 &self,
657 func: impl AsyncFnOnce(&mut StoreTransaction) -> Result<T, crate::OlmError>,
658 ) -> Result<T, crate::OlmError> {
659 let mut tr = self.transaction().await;
660 let res = func(&mut tr).await?;
661 tr.commit().await?;
662 Ok(res)
663 }
664
665 #[cfg(test)]
666 pub(crate) async fn reset_cross_signing_identity(&self) {
668 self.inner.identity.lock().await.reset();
669 }
670
671 pub(crate) fn private_identity(&self) -> Arc<Mutex<PrivateCrossSigningIdentity>> {
673 self.inner.identity.clone()
674 }
675
676 pub(crate) async fn save_sessions(&self, sessions: &[Session]) -> Result<()> {
678 let changes = Changes { sessions: sessions.to_vec(), ..Default::default() };
679
680 self.save_changes(changes).await
681 }
682
683 pub(crate) async fn get_sessions(
684 &self,
685 sender_key: &str,
686 ) -> Result<Option<Arc<Mutex<Vec<Session>>>>> {
687 self.inner.store.get_sessions(sender_key).await
688 }
689
690 pub(crate) async fn save_changes(&self, changes: Changes) -> Result<()> {
691 self.inner.store.save_changes(changes).await
692 }
693
694 pub(crate) async fn merge_received_group_session(
702 &self,
703 session: InboundGroupSession,
704 ) -> Result<Option<InboundGroupSession>> {
705 let old_session = self
706 .inner
707 .store
708 .get_inbound_group_session(session.room_id(), session.session_id())
709 .await?;
710
711 let Some(old_session) = old_session else {
713 info!("Received a new megolm room key");
714 return Ok(Some(session));
715 };
716
717 let index_comparison = session.compare_ratchet(&old_session).await;
718 let trust_level_comparison =
719 session.sender_data.compare_trust_level(&old_session.sender_data);
720
721 let result = match (index_comparison, trust_level_comparison) {
722 (SessionOrdering::Unconnected, _) => {
723 warn!(
728 "Received a group session with an ratchet that does not connect to the one in the store, discarding"
729 );
730 None
731 }
732
733 (SessionOrdering::Better, std::cmp::Ordering::Greater)
734 | (SessionOrdering::Better, std::cmp::Ordering::Equal)
735 | (SessionOrdering::Equal, std::cmp::Ordering::Greater) => {
736 info!(
739 ?index_comparison,
740 ?trust_level_comparison,
741 "Received a megolm room key that we have a worse version of, merging"
742 );
743 Some(session)
744 }
745
746 (SessionOrdering::Worse, std::cmp::Ordering::Less)
747 | (SessionOrdering::Worse, std::cmp::Ordering::Equal)
748 | (SessionOrdering::Equal, std::cmp::Ordering::Less) => {
749 warn!(
752 ?index_comparison,
753 ?trust_level_comparison,
754 "Received a megolm room key that we already have a better version \
755 of, discarding"
756 );
757 None
758 }
759
760 (SessionOrdering::Equal, std::cmp::Ordering::Equal) => {
761 info!("Received a megolm room key that we already have, discarding");
763 None
764 }
765
766 (SessionOrdering::Better, std::cmp::Ordering::Less) => {
767 info!("Upgrading a previously-received megolm session with new ratchet");
770 let result = old_session.with_ratchet(&session);
771 result.reset_backup_state();
773 Some(result)
774 }
775
776 (SessionOrdering::Worse, std::cmp::Ordering::Greater) => {
777 info!("Upgrading a previously-received megolm session with new sender data");
780 Some(session.with_ratchet(&old_session))
781 }
782 };
783
784 Ok(result)
785 }
786
787 #[cfg(test)]
788 pub(crate) async fn save_device_data(&self, devices: &[DeviceData]) -> Result<()> {
790 use types::DeviceChanges;
791
792 let changes = Changes {
793 devices: DeviceChanges { changed: devices.to_vec(), ..Default::default() },
794 ..Default::default()
795 };
796
797 self.save_changes(changes).await
798 }
799
800 pub(crate) async fn save_inbound_group_sessions(
802 &self,
803 sessions: &[InboundGroupSession],
804 ) -> Result<()> {
805 let changes = Changes { inbound_group_sessions: sessions.to_vec(), ..Default::default() };
806
807 self.save_changes(changes).await
808 }
809
810 pub(crate) async fn device_display_name(&self) -> Result<Option<String>, CryptoStoreError> {
812 Ok(self
813 .inner
814 .store
815 .get_device(self.user_id(), self.device_id())
816 .await?
817 .and_then(|d| d.display_name().map(|d| d.to_owned())))
818 }
819
820 pub(crate) async fn get_device_data(
825 &self,
826 user_id: &UserId,
827 device_id: &DeviceId,
828 ) -> Result<Option<DeviceData>> {
829 self.inner.store.get_device(user_id, device_id).await
830 }
831
832 pub(crate) async fn get_device_data_for_user_filtered(
840 &self,
841 user_id: &UserId,
842 ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
843 self.inner.store.get_user_devices(user_id).await.map(|mut d| {
844 if user_id == self.user_id() {
845 d.remove(self.device_id());
846 }
847 d
848 })
849 }
850
851 pub(crate) async fn get_device_data_for_user(
860 &self,
861 user_id: &UserId,
862 ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
863 self.inner.store.get_user_devices(user_id).await
864 }
865
866 pub(crate) async fn get_device_from_curve_key(
872 &self,
873 user_id: &UserId,
874 curve_key: Curve25519PublicKey,
875 ) -> Result<Option<Device>> {
876 self.get_user_devices(user_id)
877 .await
878 .map(|d| d.devices().find(|d| d.curve25519_key() == Some(curve_key)))
879 }
880
881 pub(crate) async fn get_user_devices(&self, user_id: &UserId) -> Result<UserDevices> {
891 let devices = self.get_device_data_for_user(user_id).await?;
892
893 let own_identity = self
894 .inner
895 .store
896 .get_user_identity(self.user_id())
897 .await?
898 .and_then(|i| i.own().cloned());
899 let device_owner_identity = self.inner.store.get_user_identity(user_id).await?;
900
901 Ok(UserDevices {
902 inner: devices,
903 verification_machine: self.inner.verification_machine.clone(),
904 own_identity,
905 device_owner_identity,
906 #[cfg(feature = "experimental-x509-identity-verification")]
907 x509_verifier: self.x509_verifier().cloned(),
908 })
909 }
910
911 pub(crate) async fn get_device(
921 &self,
922 user_id: &UserId,
923 device_id: &DeviceId,
924 ) -> Result<Option<Device>> {
925 if let Some(device_data) = self.inner.store.get_device(user_id, device_id).await? {
926 Ok(Some(self.wrap_device_data(device_data).await?))
927 } else {
928 Ok(None)
929 }
930 }
931
932 pub(crate) async fn wrap_device_data(&self, device_data: DeviceData) -> Result<Device> {
937 let own_identity = self
938 .inner
939 .store
940 .get_user_identity(self.user_id())
941 .await?
942 .and_then(|i| i.own().cloned());
943
944 let device_owner_identity =
945 self.inner.store.get_user_identity(device_data.user_id()).await?;
946
947 Ok(Device {
948 inner: device_data,
949 verification_machine: self.inner.verification_machine.clone(),
950 own_identity,
951 device_owner_identity,
952 #[cfg(feature = "experimental-x509-identity-verification")]
953 x509_verifier: self.x509_verifier().cloned(),
954 })
955 }
956
957 pub(crate) async fn get_identity(&self, user_id: &UserId) -> Result<Option<UserIdentity>> {
959 let own_identity = self
960 .inner
961 .store
962 .get_user_identity(self.user_id())
963 .await?
964 .and_then(as_variant!(UserIdentityData::Own));
965
966 Ok(self.inner.store.get_user_identity(user_id).await?.map(|i| {
967 UserIdentity::new(
968 self.clone(),
969 i,
970 self.inner.verification_machine.to_owned(),
971 own_identity,
972 )
973 }))
974 }
975
976 pub async fn export_secret(
985 &self,
986 secret_name: &SecretName,
987 ) -> Result<Option<String>, CryptoStoreError> {
988 Ok(match secret_name {
989 SecretName::CrossSigningMasterKey
990 | SecretName::CrossSigningUserSigningKey
991 | SecretName::CrossSigningSelfSigningKey => {
992 self.inner.identity.lock().await.export_secret(secret_name).await
993 }
994 SecretName::RecoveryKey => {
995 if let Some(key) = self.load_backup_keys().await?.decryption_key {
996 let exported = key.to_base64();
997 Some(exported)
998 } else {
999 None
1000 }
1001 }
1002 name => {
1003 warn!(secret = ?name, "Unknown secret was requested");
1004 None
1005 }
1006 })
1007 }
1008
1009 pub async fn export_cross_signing_keys(
1017 &self,
1018 ) -> Result<Option<CrossSigningKeyExport>, CryptoStoreError> {
1019 let master_key = self.export_secret(&SecretName::CrossSigningMasterKey).await?;
1020 let self_signing_key = self.export_secret(&SecretName::CrossSigningSelfSigningKey).await?;
1021 let user_signing_key = self.export_secret(&SecretName::CrossSigningUserSigningKey).await?;
1022
1023 Ok(if master_key.is_none() && self_signing_key.is_none() && user_signing_key.is_none() {
1024 None
1025 } else {
1026 Some(CrossSigningKeyExport { master_key, self_signing_key, user_signing_key })
1027 })
1028 }
1029
1030 pub async fn import_cross_signing_keys(
1035 &self,
1036 export: CrossSigningKeyExport,
1037 ) -> Result<CrossSigningStatus, SecretImportError> {
1038 if let Some(public_identity) =
1039 self.get_identity(self.user_id()).await?.and_then(|i| i.own())
1040 {
1041 let identity = self.inner.identity.lock().await;
1042
1043 identity
1044 .import_secrets(
1045 public_identity.to_owned(),
1046 export.master_key.as_deref(),
1047 export.self_signing_key.as_deref(),
1048 export.user_signing_key.as_deref(),
1049 )
1050 .await?;
1051
1052 let status = identity.status().await;
1053
1054 let diff = identity.get_public_identity_diff(&public_identity.inner).await;
1055
1056 let mut changes =
1057 Changes { private_identity: Some(identity.clone()), ..Default::default() };
1058
1059 if diff.none_differ() {
1060 public_identity.mark_as_verified();
1061 changes.identities.changed.push(UserIdentityData::Own(public_identity.inner));
1062 }
1063
1064 info!(?status, "Successfully imported the private cross-signing keys");
1065
1066 self.save_changes(changes).await?;
1067 } else {
1068 warn!(
1069 "No public identity found while importing cross-signing keys, \
1070 a /keys/query needs to be done"
1071 );
1072 }
1073
1074 Ok(self.inner.identity.lock().await.status().await)
1075 }
1076
1077 pub async fn export_secrets_bundle(&self) -> Result<SecretsBundle, SecretsBundleExportError> {
1089 let Some(cross_signing) = self.export_cross_signing_keys().await? else {
1090 return Err(SecretsBundleExportError::MissingCrossSigningKeys);
1091 };
1092
1093 let Some(master_key) = cross_signing.master_key.clone() else {
1094 return Err(SecretsBundleExportError::MissingCrossSigningKey(KeyUsage::Master));
1095 };
1096
1097 let Some(user_signing_key) = cross_signing.user_signing_key.clone() else {
1098 return Err(SecretsBundleExportError::MissingCrossSigningKey(KeyUsage::UserSigning));
1099 };
1100
1101 let Some(self_signing_key) = cross_signing.self_signing_key.clone() else {
1102 return Err(SecretsBundleExportError::MissingCrossSigningKey(KeyUsage::SelfSigning));
1103 };
1104
1105 let backup_keys = self.load_backup_keys().await?;
1106
1107 let backup = if let Some(key) = backup_keys.decryption_key {
1108 if let Some(backup_version) = backup_keys.backup_version {
1109 Some(BackupSecrets::MegolmBackupV1Curve25519AesSha2(
1110 MegolmBackupV1Curve25519AesSha2Secrets { key, backup_version },
1111 ))
1112 } else {
1113 return Err(SecretsBundleExportError::MissingBackupVersion);
1114 }
1115 } else {
1116 None
1117 };
1118
1119 Ok(SecretsBundle {
1120 cross_signing: CrossSigningSecrets { master_key, user_signing_key, self_signing_key },
1121 backup,
1122 })
1123 }
1124
1125 pub async fn import_secrets_bundle(
1138 &self,
1139 bundle: &SecretsBundle,
1140 ) -> Result<(), SecretImportError> {
1141 let mut changes = Changes::default();
1142
1143 if let Some(backup_bundle) = &bundle.backup {
1144 match backup_bundle {
1145 BackupSecrets::MegolmBackupV1Curve25519AesSha2(bundle) => {
1146 changes.backup_decryption_key = Some(bundle.key.clone());
1147 changes.backup_version = Some(bundle.backup_version.clone());
1148 }
1149 }
1150 }
1151
1152 let identity = self.inner.identity.lock().await;
1153
1154 identity
1155 .import_secrets_unchecked(
1156 Some(&bundle.cross_signing.master_key),
1157 Some(&bundle.cross_signing.self_signing_key),
1158 Some(&bundle.cross_signing.user_signing_key),
1159 )
1160 .await?;
1161
1162 let public_identity = identity.to_public_identity().await.expect(
1163 "We should be able to create a new public identity since we just imported \
1164 all the private cross-signing keys",
1165 );
1166
1167 changes.private_identity = Some(identity.clone());
1168 changes.identities.new.push(UserIdentityData::Own(public_identity));
1169
1170 Ok(self.save_changes(changes).await?)
1171 }
1172
1173 pub async fn import_secret(&self, secret: &GossippedSecret) -> Result<(), SecretImportError> {
1175 match &secret.secret_name {
1176 SecretName::CrossSigningMasterKey
1177 | SecretName::CrossSigningUserSigningKey
1178 | SecretName::CrossSigningSelfSigningKey => {
1179 if let Some(public_identity) =
1180 self.get_identity(self.user_id()).await?.and_then(|i| i.own())
1181 {
1182 let identity = self.inner.identity.lock().await;
1183
1184 identity
1185 .import_secret(
1186 public_identity,
1187 &secret.secret_name,
1188 &secret.event.content.secret,
1189 )
1190 .await?;
1191 info!(
1192 secret_name = ?secret.secret_name,
1193 "Successfully imported a private cross signing key"
1194 );
1195
1196 let changes =
1197 Changes { private_identity: Some(identity.clone()), ..Default::default() };
1198
1199 self.save_changes(changes).await?;
1200 }
1201 }
1202 SecretName::RecoveryKey => {
1203 }
1209 name => {
1210 warn!(secret = ?name, "Tried to import an unknown secret");
1211 }
1212 }
1213
1214 Ok(())
1215 }
1216
1217 pub async fn get_only_allow_trusted_devices(&self) -> Result<bool> {
1220 let value = self.get_value("only_allow_trusted_devices").await?.unwrap_or_default();
1221 Ok(value)
1222 }
1223
1224 pub async fn set_only_allow_trusted_devices(
1227 &self,
1228 block_untrusted_devices: bool,
1229 ) -> Result<()> {
1230 self.set_value("only_allow_trusted_devices", &block_untrusted_devices).await
1231 }
1232
1233 pub async fn get_value<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
1235 let Some(value) = self.get_custom_value(key).await? else {
1236 return Ok(None);
1237 };
1238 let deserialized = self.deserialize_value(&value)?;
1239 Ok(Some(deserialized))
1240 }
1241
1242 pub async fn set_value(&self, key: &str, value: &impl Serialize) -> Result<()> {
1244 let serialized = self.serialize_value(value)?;
1245 self.set_custom_value(key, serialized).await?;
1246 Ok(())
1247 }
1248
1249 fn serialize_value(&self, value: &impl Serialize) -> Result<Vec<u8>> {
1250 let serialized =
1251 rmp_serde::to_vec_named(value).map_err(|x| CryptoStoreError::Backend(x.into()))?;
1252 Ok(serialized)
1253 }
1254
1255 fn deserialize_value<T: DeserializeOwned>(&self, value: &[u8]) -> Result<T> {
1256 let deserialized =
1257 rmp_serde::from_slice(value).map_err(|e| CryptoStoreError::Backend(e.into()))?;
1258 Ok(deserialized)
1259 }
1260
1261 pub fn room_keys_received_stream(
1273 &self,
1274 ) -> impl Stream<Item = Result<Vec<RoomKeyInfo>, BroadcastStreamRecvError>> + use<> {
1275 self.inner.store.room_keys_received_stream()
1276 }
1277
1278 pub fn room_keys_withheld_received_stream(
1287 &self,
1288 ) -> impl Stream<Item = Vec<RoomKeyWithheldInfo>> + use<> {
1289 self.inner.store.room_keys_withheld_received_stream()
1290 }
1291
1292 pub fn user_identities_stream(&self) -> impl Stream<Item = IdentityUpdates> + use<> {
1324 let verification_machine = self.inner.verification_machine.to_owned();
1325
1326 let this = self.clone();
1327 self.inner.store.identities_stream().map(move |(own_identity, identities, _)| {
1328 let (new_identities, changed_identities, unchanged_identities) = identities.into_maps();
1329
1330 let map_identity = |(user_id, identity)| {
1331 (
1332 user_id,
1333 UserIdentity::new(
1334 this.clone(),
1335 identity,
1336 verification_machine.to_owned(),
1337 own_identity.to_owned(),
1338 ),
1339 )
1340 };
1341
1342 let new = new_identities.into_iter().map(map_identity).collect();
1343 let changed = changed_identities.into_iter().map(map_identity).collect();
1344 let unchanged = unchanged_identities.into_iter().map(map_identity).collect();
1345
1346 IdentityUpdates { new, changed, unchanged }
1347 })
1348 }
1349
1350 pub fn devices_stream(&self) -> impl Stream<Item = DeviceUpdates> + use<> {
1383 let verification_machine = self.inner.verification_machine.to_owned();
1384 #[cfg(feature = "experimental-x509-identity-verification")]
1385 let x509_verifier = self.x509_verifier().cloned();
1386
1387 self.inner.store.identities_stream().map(move |(own_identity, identities, devices)| {
1388 collect_device_updates(
1389 verification_machine.to_owned(),
1390 own_identity,
1391 identities,
1392 devices,
1393 #[cfg(feature = "experimental-x509-identity-verification")]
1394 x509_verifier.to_owned(),
1395 )
1396 })
1397 }
1398
1399 pub fn identities_stream_raw(
1409 &self,
1410 ) -> impl Stream<Item = (IdentityChanges, DeviceChanges)> + use<> {
1411 self.inner.store.identities_stream().map(|(_, identities, devices)| (identities, devices))
1412 }
1413
1414 pub fn create_store_lock(
1417 &self,
1418 lock_key: String,
1419 config: CrossProcessLockConfig,
1420 ) -> CrossProcessLock<LockableCryptoStore> {
1421 self.inner.store.create_store_lock(lock_key, config)
1422 }
1423
1424 pub fn secrets_stream(&self) -> impl Stream<Item = SecretsInboxItem> + use<> {
1465 self.inner.store.secrets_stream()
1466 }
1467
1468 pub fn historic_room_key_stream(&self) -> impl Stream<Item = RoomKeyBundleInfo> + use<> {
1510 self.inner.store.historic_room_key_stream()
1511 }
1512
1513 pub async fn import_room_keys(
1526 &self,
1527 exported_keys: Vec<ExportedRoomKey>,
1528 from_backup_version: Option<&str>,
1529 progress_listener: impl Fn(usize, usize),
1530 ) -> Result<RoomKeyImportResult> {
1531 let exported_keys = exported_keys.iter().filter_map(|key| {
1532 key.try_into()
1533 .map_err(|e| {
1534 warn!(
1535 sender_key = key.sender_key().to_base64(),
1536 room_id = ?key.room_id(),
1537 session_id = key.session_id(),
1538 error = ?e,
1539 "Couldn't import a room key from a file export."
1540 );
1541 })
1542 .ok()
1543 });
1544 self.import_sessions_impl(exported_keys, from_backup_version, progress_listener).await
1545 }
1546
1547 pub async fn import_exported_room_keys(
1574 &self,
1575 exported_keys: Vec<ExportedRoomKey>,
1576 progress_listener: impl Fn(usize, usize),
1577 ) -> Result<RoomKeyImportResult> {
1578 self.import_room_keys(exported_keys, None, progress_listener).await
1579 }
1580
1581 async fn import_sessions_impl(
1582 &self,
1583 sessions: impl Iterator<Item = InboundGroupSession>,
1584 from_backup_version: Option<&str>,
1585 progress_listener: impl Fn(usize, usize),
1586 ) -> Result<RoomKeyImportResult> {
1587 let sessions: Vec<_> = sessions.collect();
1588 let mut imported_sessions = Vec::new();
1589
1590 let total_count = sessions.len();
1591 let mut keys = BTreeMap::new();
1592
1593 for (i, session) in sessions.into_iter().enumerate() {
1594 if let Some(merged) = self.merge_received_group_session(session).await? {
1597 if from_backup_version.is_some() {
1598 merged.mark_as_backed_up();
1599 }
1600
1601 keys.entry(merged.room_id().to_owned())
1602 .or_insert_with(BTreeMap::new)
1603 .entry(merged.sender_key().to_base64())
1604 .or_insert_with(BTreeSet::new)
1605 .insert(merged.session_id().to_owned());
1606
1607 imported_sessions.push(merged);
1608 }
1609
1610 progress_listener(i, total_count);
1611 }
1612
1613 let imported_count = imported_sessions.len();
1614
1615 self.inner
1616 .store
1617 .save_inbound_group_sessions(imported_sessions, from_backup_version)
1618 .await?;
1619
1620 info!(total_count, imported_count, room_keys = ?keys, "Successfully imported room keys");
1621
1622 Ok(RoomKeyImportResult::new(imported_count, total_count, keys))
1623 }
1624
1625 pub(crate) fn crypto_store(&self) -> Arc<CryptoStoreWrapper> {
1626 self.inner.store.clone()
1627 }
1628
1629 pub async fn export_room_keys(
1652 &self,
1653 predicate: impl FnMut(&InboundGroupSession) -> bool,
1654 ) -> Result<Vec<ExportedRoomKey>> {
1655 let mut exported = Vec::new();
1656
1657 let mut sessions = self.get_inbound_group_sessions().await?;
1658 sessions.retain(predicate);
1659
1660 for session in sessions {
1661 let export = session.export().await;
1662 exported.push(export);
1663 }
1664
1665 Ok(exported)
1666 }
1667
1668 pub async fn export_room_keys_stream(
1703 &self,
1704 predicate: impl FnMut(&InboundGroupSession) -> bool,
1705 ) -> Result<impl Stream<Item = ExportedRoomKey>> {
1706 let sessions = self.get_inbound_group_sessions().await?;
1709 Ok(futures_util::stream::iter(sessions.into_iter().filter(predicate))
1710 .then(|session| async move { session.export().await }))
1711 }
1712
1713 pub async fn build_room_key_bundle(
1718 &self,
1719 room_id: &RoomId,
1720 ) -> std::result::Result<RoomKeyBundle, CryptoStoreError> {
1721 let sessions = self.get_inbound_group_sessions_by_room_id(room_id).await?;
1722
1723 let mut bundle = RoomKeyBundle::default();
1724 for session in sessions {
1725 if session.shared_history() {
1726 bundle.room_keys.push(session.export().await.into());
1727 } else {
1728 bundle.withheld.push(RoomKeyWithheldContent::new(
1729 session.algorithm().to_owned(),
1730 WithheldCode::HistoryNotShared,
1731 session.room_id().to_owned(),
1732 session.session_id().to_owned(),
1733 session.sender_key().to_owned(),
1734 self.device_id().to_owned(),
1735 ));
1736 }
1737 }
1738
1739 let withhelds = self.get_withheld_sessions_by_room_id(room_id).await?;
1742 for withheld in withhelds {
1743 if withheld.content.withheld_code() == WithheldCode::HistoryNotShared {
1744 bundle.withheld.push(withheld.content);
1745 }
1746 }
1747
1748 Ok(bundle)
1749 }
1750
1751 #[instrument(skip(self, bundle, progress_listener), fields(bundle_size = bundle.room_keys.len(), sender_data))]
1761 pub async fn receive_room_key_bundle(
1762 &self,
1763 bundle_info: &StoredRoomKeyBundleData,
1764 bundle: RoomKeyBundle,
1765 progress_listener: impl Fn(usize, usize),
1766 ) -> Result<(), CryptoStoreError> {
1767 let sender_data = if bundle_info.sender_data.should_recalculate() {
1768 let device = self
1769 .get_device_from_curve_key(&bundle_info.sender_user, bundle_info.sender_key)
1770 .await?;
1771
1772 device
1773 .as_ref()
1774 .map(SenderData::from_device)
1775 .unwrap_or_else(|| bundle_info.sender_data.clone())
1776 } else {
1777 bundle_info.sender_data.clone()
1778 };
1779
1780 tracing::Span::current().record("sender_data", tracing::field::debug(&sender_data));
1781
1782 let Ok(forwarder_data) = (&sender_data).try_into() else {
1786 warn!(
1787 "Not accepting a historic room key bundle due to insufficient trust in the sender"
1788 );
1789 return Ok(());
1790 };
1791
1792 self.import_room_key_bundle_sessions(
1793 bundle_info,
1794 &bundle,
1795 &forwarder_data,
1796 progress_listener,
1797 )
1798 .await?;
1799 self.import_room_key_bundle_withheld_info(bundle_info, &bundle).await?;
1800
1801 Ok(())
1802 }
1803
1804 async fn import_room_key_bundle_sessions(
1805 &self,
1806 bundle_info: &StoredRoomKeyBundleData,
1807 bundle: &RoomKeyBundle,
1808 forwarder_data: &ForwarderData,
1809 progress_listener: impl Fn(usize, usize),
1810 ) -> Result<(), CryptoStoreError> {
1811 let (good, bad): (Vec<_>, Vec<_>) = bundle.room_keys.iter().partition_map(|key| {
1812 if key.room_id != bundle_info.bundle_data.room_id {
1813 trace!("Ignoring key for incorrect room {} in bundle", key.room_id);
1814 Either::Right(key)
1815 } else {
1816 Either::Left(key)
1817 }
1818 });
1819
1820 match (bad.is_empty(), good.is_empty()) {
1821 (true, true) => {
1823 warn!("Received a completely empty room key bundle");
1824 }
1825
1826 (false, true) => {
1828 let bad_keys: Vec<_> =
1829 bad.iter().map(|&key| (&key.room_id, &key.session_id)).collect();
1830
1831 warn!(
1832 ?bad_keys,
1833 "Received a room key bundle for the wrong room, ignoring all room keys from the bundle"
1834 );
1835 }
1836
1837 (_, false) => {
1839 if !bad.is_empty() {
1842 warn!(
1843 bad_key_count = bad.len(),
1844 "The room key bundle contained some room keys \
1845 that were meant for a different room"
1846 );
1847 }
1848
1849 let keys = good.iter().filter_map(|key| {
1850 key.try_into_inbound_group_session(forwarder_data)
1851 .map_err(|e| {
1852 warn!(
1853 sender_key = ?key.sender_key().to_base64(),
1854 room_id = ?key.room_id(),
1855 session_id = key.session_id(),
1856 error = ?e,
1857 "Couldn't import a room key from a key bundle."
1858 );
1859 })
1860 .ok()
1861 });
1862
1863 self.import_sessions_impl(keys, None, progress_listener).await?;
1864 }
1865 }
1866
1867 Ok(())
1868 }
1869
1870 async fn import_room_key_bundle_withheld_info(
1871 &self,
1872 bundle_info: &StoredRoomKeyBundleData,
1873 bundle: &RoomKeyBundle,
1874 ) -> Result<(), CryptoStoreError> {
1875 let mut session_id_to_withheld_code_map = BTreeMap::new();
1876
1877 let mut changes = Changes::default();
1878 for withheld in &bundle.withheld {
1879 let (room_id, session_id) = match withheld {
1880 RoomKeyWithheldContent::MegolmV1AesSha2(c) => match (c.room_id(), c.session_id()) {
1881 (Some(room_id), Some(session_id)) => (room_id, session_id),
1882 _ => continue,
1883 },
1884 #[cfg(feature = "experimental-algorithms")]
1885 RoomKeyWithheldContent::MegolmV2AesSha2(c) => match (c.room_id(), c.session_id()) {
1886 (Some(room_id), Some(session_id)) => (room_id, session_id),
1887 _ => continue,
1888 },
1889 RoomKeyWithheldContent::Unknown(_) => continue,
1890 };
1891
1892 if room_id != bundle_info.bundle_data.room_id {
1893 trace!("Ignoring withheld info for incorrect room {} in bundle", room_id);
1894 continue;
1895 }
1896
1897 changes.withheld_session_info.entry(room_id.to_owned()).or_default().insert(
1898 session_id.to_owned(),
1899 RoomKeyWithheldEntry {
1900 sender: bundle_info.sender_user.clone(),
1901 content: withheld.to_owned(),
1902 },
1903 );
1904 session_id_to_withheld_code_map.insert(session_id, withheld.withheld_code());
1905 }
1906
1907 self.save_changes(changes).await?;
1908
1909 info!(
1910 room_id = ?bundle_info.bundle_data.room_id,
1911 ?session_id_to_withheld_code_map,
1912 "Successfully imported withheld info from room key bundle",
1913 );
1914
1915 Ok(())
1916 }
1917
1918 pub async fn store_room_pending_key_bundle(
1923 &self,
1924 room_id: &RoomId,
1925 inviter: &UserId,
1926 ) -> Result<(), CryptoStoreError> {
1927 let invite_accepted_at = MilliSecondsSinceUnixEpoch::now();
1928 self.save_changes(Changes {
1929 rooms_pending_key_bundle: HashMap::from([(
1930 room_id.to_owned(),
1931 Some(RoomPendingKeyBundleDetails {
1932 room_id: room_id.to_owned(),
1933 invite_accepted_at,
1934 inviter: inviter.to_owned(),
1935 }),
1936 )]),
1937 ..Default::default()
1938 })
1939 .await?;
1940
1941 Ok(())
1942 }
1943
1944 pub async fn clear_room_pending_key_bundle(&self, room_id: &RoomId) -> Result<()> {
1948 self.save_changes(Changes {
1949 rooms_pending_key_bundle: HashMap::from([(room_id.to_owned(), None)]),
1950 ..Default::default()
1951 })
1952 .await
1953 }
1954}
1955
1956impl Deref for Store {
1957 type Target = DynCryptoStore;
1958
1959 fn deref(&self) -> &Self::Target {
1960 self.inner.store.deref().deref()
1961 }
1962}
1963
1964#[derive(Clone, Debug)]
1966pub struct LockableCryptoStore(Arc<dyn CryptoStore<Error = CryptoStoreError>>);
1967
1968impl matrix_sdk_common::cross_process_lock::TryLock for LockableCryptoStore {
1969 type LockError = CryptoStoreError;
1970
1971 async fn try_lock(
1972 &self,
1973 lease_duration_ms: u32,
1974 key: &str,
1975 holder: &str,
1976 ) -> std::result::Result<Option<CrossProcessLockGeneration>, Self::LockError> {
1977 self.0.try_take_leased_lock(lease_duration_ms, key, holder).await
1978 }
1979}
1980
1981#[cfg(test)]
1982mod tests {
1983 use std::{assert_matches, collections::BTreeMap, pin::pin};
1984
1985 use futures_util::StreamExt;
1986 use insta::{_macro_support::Content, assert_json_snapshot, internals::ContentPath};
1987 use matrix_sdk_test::async_test;
1988 use rand::RngExt;
1989 use ruma::{
1990 RoomId, device_id,
1991 events::room::{EncryptedFile, EncryptedFileHashes, V2EncryptedFileInfo},
1992 owned_device_id, owned_mxc_uri, room_id, user_id,
1993 };
1994 use serde_json::json;
1995 use strass::assert_let;
1996 use vodozemac::{Ed25519Keypair, megolm::SessionKey};
1997
1998 use crate::{
1999 Account, OlmMachine,
2000 machine::test_helpers::get_machine_pair,
2001 olm::{InboundGroupSession, SenderData},
2002 store::types::{DehydratedDeviceKey, RoomKeyWithheldEntry, StoredRoomKeyBundleData},
2003 types::{
2004 EventEncryptionAlgorithm,
2005 events::{
2006 room_key_bundle::RoomKeyBundleContent,
2007 room_key_withheld::{MegolmV1AesSha2WithheldContent, RoomKeyWithheldContent},
2008 },
2009 },
2010 };
2011
2012 #[async_test]
2013 async fn test_merge_received_group_session() {
2014 let alice_account = Account::with_device_id(user_id!("@a:s.co"), device_id!("ABC"));
2015 let bob = OlmMachine::new(user_id!("@b:s.co"), device_id!("DEF")).await;
2016
2017 let room_id = room_id!("!test:localhost");
2018
2019 let megolm_signing_key = Ed25519Keypair::new();
2020 let inbound = make_inbound_group_session(&alice_account, &megolm_signing_key, room_id);
2021
2022 let mut inbound_at_index_5 =
2025 InboundGroupSession::from_export(&inbound.export_at_index(5).await).unwrap();
2026 inbound_at_index_5.sender_data = inbound.sender_data.clone();
2027 bob.store().save_inbound_group_sessions(&[inbound_at_index_5.clone()]).await.unwrap();
2028
2029 let disconnected = make_inbound_group_session(&alice_account, &megolm_signing_key, room_id);
2031 assert_eq!(bob.store().merge_received_group_session(disconnected).await.unwrap(), None);
2032
2033 let mut worse =
2035 InboundGroupSession::from_export(&inbound.export_at_index(10).await).unwrap();
2036 worse.sender_data = inbound.sender_data.clone();
2037 assert_eq!(bob.store().merge_received_group_session(worse).await.unwrap(), None);
2038
2039 let mut copy = InboundGroupSession::from_pickle(inbound_at_index_5.pickle().await).unwrap();
2041 copy.sender_data = inbound.sender_data.clone();
2042 assert_eq!(bob.store().merge_received_group_session(copy).await.unwrap(), None);
2043
2044 let mut better =
2047 InboundGroupSession::from_export(&inbound.export_at_index(0).await).unwrap();
2048 better.sender_data = inbound.sender_data.clone();
2049 assert_let!(Some(update) = bob.store().merge_received_group_session(better).await.unwrap());
2050 assert_eq!(update.first_known_index(), 0);
2051
2052 {
2054 let mut worse_ratchet_better_trust =
2055 InboundGroupSession::from_export(&inbound.export_at_index(10).await).unwrap();
2056 let updated_sender_data = SenderData::sender_verified(
2057 alice_account.user_id(),
2058 alice_account.device_id(),
2059 Ed25519Keypair::new().public_key(),
2060 );
2061 worse_ratchet_better_trust.sender_data = updated_sender_data.clone();
2062 assert_let!(
2063 Some(update) = bob
2064 .store()
2065 .merge_received_group_session(worse_ratchet_better_trust)
2066 .await
2067 .unwrap()
2068 );
2069 assert_eq!(update.sender_data, updated_sender_data);
2070 assert_eq!(update.first_known_index(), 5);
2071 assert_eq!(
2072 update.export_at_index(0).await.session_key.to_bytes(),
2073 inbound.export_at_index(5).await.session_key.to_bytes()
2074 );
2075 }
2076
2077 {
2079 let mut better_ratchet_worse_trust =
2080 InboundGroupSession::from_export(&inbound.export_at_index(0).await).unwrap();
2081 let updated_sender_data = SenderData::unknown();
2082 better_ratchet_worse_trust.sender_data = updated_sender_data.clone();
2083 assert_let!(
2084 Some(update) = bob
2085 .store()
2086 .merge_received_group_session(better_ratchet_worse_trust)
2087 .await
2088 .unwrap()
2089 );
2090 assert_eq!(update.sender_data, inbound.sender_data);
2091 assert_eq!(update.first_known_index(), 0);
2092 assert_eq!(
2093 update.export_at_index(0).await.session_key.to_bytes(),
2094 inbound.export_at_index(0).await.session_key.to_bytes()
2095 );
2096 }
2097 }
2098
2099 fn make_inbound_group_session(
2102 sender_account: &Account,
2103 signing_key: &Ed25519Keypair,
2104 room_id: &RoomId,
2105 ) -> InboundGroupSession {
2106 InboundGroupSession::new(
2107 sender_account.identity_keys.curve25519,
2108 sender_account.identity_keys.ed25519,
2109 room_id,
2110 &make_session_key(signing_key),
2111 SenderData::device_info(crate::types::DeviceKeys::new(
2112 sender_account.user_id().to_owned(),
2113 sender_account.device_id().to_owned(),
2114 vec![],
2115 BTreeMap::new(),
2116 crate::types::Signatures::new(),
2117 )),
2118 None,
2119 EventEncryptionAlgorithm::MegolmV1AesSha2,
2120 Some(ruma::events::room::history_visibility::HistoryVisibility::Shared),
2121 true,
2122 )
2123 .unwrap()
2124 }
2125
2126 fn make_session_key(signing_key: &Ed25519Keypair) -> SessionKey {
2129 let mut session_key_bytes = vec![0u8; 229];
2134 session_key_bytes[0] = 2;
2136 rand::rng().fill(&mut session_key_bytes[5..133]);
2138 session_key_bytes[133..165].copy_from_slice(signing_key.public_key().as_bytes());
2140 let sig = signing_key.sign(&session_key_bytes[0..165]);
2142 session_key_bytes[165..229].copy_from_slice(&sig.to_bytes());
2143
2144 SessionKey::from_bytes(&session_key_bytes).unwrap()
2145 }
2146
2147 #[async_test]
2148 async fn test_import_room_keys_notifies_stream() {
2149 use futures_util::FutureExt;
2150
2151 let (alice, bob, _) =
2152 get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2153
2154 let room1_id = room_id!("!room1:localhost");
2155 alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2156 let exported_sessions = alice.store().export_room_keys(|_| true).await.unwrap();
2157
2158 let mut room_keys_received_stream = Box::pin(bob.store().room_keys_received_stream());
2159 bob.store().import_room_keys(exported_sessions, None, |_, _| {}).await.unwrap();
2160
2161 let room_keys = room_keys_received_stream
2162 .next()
2163 .now_or_never()
2164 .flatten()
2165 .expect("We should have received an update of room key infos")
2166 .unwrap();
2167 assert_eq!(room_keys.len(), 1);
2168 assert_eq!(room_keys[0].room_id, "!room1:localhost");
2169 }
2170
2171 #[async_test]
2172 async fn test_export_room_keys_provides_selected_keys() {
2173 let (alice, _, _) = get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2175 let room1_id = room_id!("!room1:localhost");
2176 let room2_id = room_id!("!room2:localhost");
2177 let room3_id = room_id!("!room3:localhost");
2178 alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2179 alice.create_outbound_group_session_with_defaults_test_helper(room2_id).await.unwrap();
2180 alice.create_outbound_group_session_with_defaults_test_helper(room3_id).await.unwrap();
2181
2182 let keys = alice
2184 .store()
2185 .export_room_keys(|s| s.room_id() == room2_id || s.room_id() == room3_id)
2186 .await
2187 .unwrap();
2188
2189 assert_eq!(keys.len(), 2);
2191 assert_eq!(keys[0].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2192 assert_eq!(keys[1].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2193 assert_eq!(keys[0].room_id, "!room2:localhost");
2194 assert_eq!(keys[1].room_id, "!room3:localhost");
2195 assert_eq!(keys[0].session_key.to_base64().len(), 220);
2196 assert_eq!(keys[1].session_key.to_base64().len(), 220);
2197 }
2198
2199 #[async_test]
2200 async fn test_export_room_keys_stream_can_provide_all_keys() {
2201 let (alice, _, _) = get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2203 let room1_id = room_id!("!room1:localhost");
2204 let room2_id = room_id!("!room2:localhost");
2205 alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2206 alice.create_outbound_group_session_with_defaults_test_helper(room2_id).await.unwrap();
2207
2208 let mut keys = pin!(alice.store().export_room_keys_stream(|_| true).await.unwrap());
2210
2211 let mut collected = vec![];
2213 while let Some(key) = keys.next().await {
2214 collected.push(key);
2215 }
2216
2217 assert_eq!(collected.len(), 2);
2219 assert_eq!(collected[0].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2220 assert_eq!(collected[1].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2221 assert_eq!(collected[0].room_id, "!room1:localhost");
2222 assert_eq!(collected[1].room_id, "!room2:localhost");
2223 assert_eq!(collected[0].session_key.to_base64().len(), 220);
2224 assert_eq!(collected[1].session_key.to_base64().len(), 220);
2225 }
2226
2227 #[async_test]
2228 async fn test_export_room_keys_stream_can_provide_a_subset_of_keys() {
2229 let (alice, _, _) = get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2231 let room1_id = room_id!("!room1:localhost");
2232 let room2_id = room_id!("!room2:localhost");
2233 alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2234 alice.create_outbound_group_session_with_defaults_test_helper(room2_id).await.unwrap();
2235
2236 let mut keys =
2238 pin!(alice.store().export_room_keys_stream(|s| s.room_id() == room1_id).await.unwrap());
2239
2240 let mut collected = vec![];
2242 while let Some(key) = keys.next().await {
2243 collected.push(key);
2244 }
2245
2246 assert_eq!(collected.len(), 1);
2248 assert_eq!(collected[0].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2249 assert_eq!(collected[0].room_id, "!room1:localhost");
2250 assert_eq!(collected[0].session_key.to_base64().len(), 220);
2251 }
2252
2253 #[async_test]
2254 async fn test_export_secrets_bundle() {
2255 let user_id = user_id!("@alice:example.com");
2256 let (first, second, _) = get_machine_pair(user_id, user_id, false).await;
2257
2258 let _ = first
2259 .bootstrap_cross_signing(false)
2260 .await
2261 .expect("We should be able to bootstrap cross-signing");
2262
2263 let bundle = first.store().export_secrets_bundle().await.expect(
2264 "We should be able to export the secrets bundle, now that we \
2265 have the cross-signing keys",
2266 );
2267
2268 assert!(bundle.backup.is_none(), "The bundle should not contain a backup key");
2269
2270 second
2271 .store()
2272 .import_secrets_bundle(&bundle)
2273 .await
2274 .expect("We should be able to import the secrets bundle");
2275
2276 let status = second.cross_signing_status().await;
2277 let identity = second.get_identity(user_id, None).await.unwrap().unwrap().own().unwrap();
2278
2279 assert!(identity.is_verified(), "The public identity should be marked as verified.");
2280
2281 assert!(status.is_complete(), "We should have imported all the cross-signing keys");
2282 }
2283
2284 #[async_test]
2285 async fn test_create_dehydrated_device_key() {
2286 let pickle_key = DehydratedDeviceKey::new();
2287
2288 let to_vec = pickle_key.inner.to_vec();
2289 let pickle_key_from_slice = DehydratedDeviceKey::from_slice(to_vec.as_slice())
2290 .expect("Should be able to create a dehydrated device key from slice");
2291
2292 assert_eq!(pickle_key_from_slice.to_base64(), pickle_key.to_base64());
2293 }
2294
2295 #[async_test]
2296 async fn test_create_dehydrated_errors() {
2297 let too_small = [0u8; 22];
2298 let pickle_key = DehydratedDeviceKey::from_slice(&too_small);
2299
2300 assert!(pickle_key.is_err());
2301
2302 let too_big = [0u8; 40];
2303 let pickle_key = DehydratedDeviceKey::from_slice(&too_big);
2304
2305 assert!(pickle_key.is_err());
2306 }
2307
2308 #[async_test]
2309 async fn test_build_room_key_bundle() {
2310 let alice = OlmMachine::new(user_id!("@a:s.co"), device_id!("ALICE")).await;
2313 let bob = OlmMachine::new(user_id!("@b:s.co"), device_id!("BOB")).await;
2314
2315 let room1_id = room_id!("!room1:localhost");
2316 let room2_id = room_id!("!room2:localhost");
2317
2318 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 let session_key3 = "AgAAAAAM9KFsliaUUhGSXgwOzM5UemjkNH4n8NHgvC/y8hhw13zTF+ooGD4uIYEXYX630oNvQm/EvgZo+dkoc0re+vsqsx4sQeNODdSjcBsWOa0oDF+irQn9oYoLUDPI1IBtY1rX+FV99Zm/xnG7uFOX7aTVlko2GSdejy1w9mfobmfxu5aUc04A9zaKJP1pOthZvRAlhpymGYHgsDtWPrrjyc/yypMflE4kIUEEEtu1kT6mrAmcl615XYRAHYK9G2+fZsGvokwzbkl4nulGwcZMpQEoM0nD2o3GWgX81HW3nGfKBg";
2325 let session_key4 = "AgAAAAA4Kkesxq2h4v9PLD6Sm3Smxspz1PXTqytQPCMQMkkrHNmzV2bHlJ+6/Al9cu8vh1Oj69AK0WUAeJOJuaiskEeg/PI3P03+UYLeC379RzgqwSHdBgdQ41G2vD6zpgmE/8vYToe+qpCZACtPOswZxyqxHH+T/Iq0nv13JmlFGIeA6fEPfr5Y28B49viG74Fs9rxV9EH5PfjbuPM/p+Sz5obShuaBPKQBX1jT913nEXPoIJ06exNZGr0285nw/LgVvNlmWmbqNnbzO2cNZjQWA+xZYz5FSfyCxwqEBbEdUCuRCQ";
2326
2327 let sessions = [
2328 create_inbound_group_session_with_visibility(
2329 &alice,
2330 room1_id,
2331 &SessionKey::from_base64(session_key1).unwrap(),
2332 true,
2333 ),
2334 create_inbound_group_session_with_visibility(
2335 &alice,
2336 room1_id,
2337 &SessionKey::from_base64(session_key2).unwrap(),
2338 true,
2339 ),
2340 create_inbound_group_session_with_visibility(
2341 &alice,
2342 room1_id,
2343 &SessionKey::from_base64(session_key3).unwrap(),
2344 false,
2345 ),
2346 create_inbound_group_session_with_visibility(
2347 &alice,
2348 room2_id,
2349 &SessionKey::from_base64(session_key4).unwrap(),
2350 true,
2351 ),
2352 ];
2353 bob.store().save_inbound_group_sessions(&sessions).await.unwrap();
2354
2355 let mut bundle = bob.store().build_room_key_bundle(room1_id).await.unwrap();
2357
2358 bundle.room_keys.sort_by_key(|session| session.session_id.clone());
2362
2363 let algorithm = if cfg!(feature = "experimental-algorithms") {
2366 "m.megolm.v2.aes-sha2"
2367 } else {
2368 "m.megolm.v1.aes-sha2"
2369 };
2370 let map_algorithm = move |value: Content, _path: ContentPath<'_>| {
2371 assert_eq!(value.as_str().unwrap(), algorithm);
2372 "[algorithm]"
2373 };
2374
2375 let alice_curve_key = alice.identity_keys().curve25519.to_base64();
2377 let map_alice_curve_key = move |value: Content, _path: ContentPath<'_>| {
2378 assert_eq!(value.as_str().unwrap(), alice_curve_key);
2379 "[alice curve key]"
2380 };
2381 let alice_ed25519_key = alice.identity_keys().ed25519.to_base64();
2382 let map_alice_ed25519_key = move |value: Content, _path: ContentPath<'_>| {
2383 assert_eq!(value.as_str().unwrap(), alice_ed25519_key);
2384 "[alice ed25519 key]"
2385 };
2386
2387 insta::with_settings!({ sort_maps => true }, {
2388 assert_json_snapshot!(bundle, {
2389 ".withheld[].algorithm" => insta::dynamic_redaction(map_algorithm),
2390 ".room_keys[].algorithm" => insta::dynamic_redaction(map_algorithm),
2391 ".room_keys[].sender_key" => insta::dynamic_redaction(map_alice_curve_key.clone()),
2392 ".withheld[].sender_key" => insta::dynamic_redaction(map_alice_curve_key),
2393 ".room_keys[].sender_claimed_keys.ed25519" => insta::dynamic_redaction(map_alice_ed25519_key),
2394 });
2395 });
2396 }
2397
2398 #[async_test]
2399 async fn test_receive_room_key_bundle() {
2400 let alice = OlmMachine::new(user_id!("@a:s.co"), device_id!("ALICE")).await;
2401 let alice_key = alice.identity_keys().curve25519;
2402 let bob = OlmMachine::new(user_id!("@b:s.co"), device_id!("BOB")).await;
2403
2404 let room_id = room_id!("!room1:localhost");
2405
2406 let session_key1 = "AgAAAAC2XHVzsMBKs4QCRElJ92CJKyGtknCSC8HY7cQ7UYwndMKLQAejXLh5UA0l6s736mgctcUMNvELScUWrObdflrHo+vth/gWreXOaCnaSxmyjjKErQwyIYTkUfqbHy40RJfEesLwnN23on9XAkch/iy8R2+Jz7B8zfG01f2Ow2SxPQFnAndcO1ZSD2GmXgedy6n4B20MWI1jGP2wiexOWbFSya8DO/VxC9m5+/mF+WwYqdpKn9g4Y05Yw4uz7cdjTc3rXm7xK+8E7hI//5QD1nHPvuKYbjjM9u2JSL+Bzp61Cw";
2407 let session_key2 = "AgAAAAC1BXreFTUQQSBGekTEuYxhdytRKyv4JgDGcG+VOBYdPNGgs807SdibCGJky4lJ3I+7ZDGHoUzZPZP/4ogGu4kxni0PWdtWuN7+5zsuamgoFF/BkaGeUUGv6kgIkx8pyPpM5SASTUEP9bN2loDSpUPYwfiIqz74DgC4WQ4435sTBctYvKz8n+TDJwdLXpyT6zKljuqADAioud+s/iqx9LYn9HpbBfezZcvbg67GtE113pLrvde3IcPI5s6dNHK2onGO2B2eoaobcen18bbEDnlUGPeIivArLya7Da6us14jBQ";
2408
2409 let sessions = [
2410 create_inbound_group_session_with_visibility(
2411 &alice,
2412 room_id,
2413 &SessionKey::from_base64(session_key1).unwrap(),
2414 true,
2415 ),
2416 create_inbound_group_session_with_visibility(
2417 &alice,
2418 room_id,
2419 &SessionKey::from_base64(session_key2).unwrap(),
2420 false,
2421 ),
2422 ];
2423
2424 alice.store().save_inbound_group_sessions(&sessions).await.unwrap();
2425 let bundle = alice.store().build_room_key_bundle(room_id).await.unwrap();
2426
2427 bob.store()
2428 .receive_room_key_bundle(
2429 &StoredRoomKeyBundleData {
2430 sender_user: alice.user_id().to_owned(),
2431 sender_key: alice_key,
2432 sender_data: SenderData::sender_verified(
2433 alice.user_id(),
2434 device_id!("ALICE"),
2435 alice.identity_keys().ed25519,
2436 ),
2437
2438 bundle_data: RoomKeyBundleContent {
2439 room_id: room_id.to_owned(),
2440 file: EncryptedFile::new(
2443 owned_mxc_uri!("mxc://example.com/0"),
2444 V2EncryptedFileInfo::encode([0; 32], [0; 16]).into(),
2445 EncryptedFileHashes::with_sha256([0; 32]),
2446 ),
2447 },
2448 },
2449 bundle,
2450 |_, _| {},
2451 )
2452 .await
2453 .unwrap();
2454
2455 let imported_sessions =
2457 bob.store().get_inbound_group_sessions_by_room_id(room_id).await.unwrap();
2458
2459 assert_eq!(imported_sessions.len(), 1);
2460 assert_eq!(imported_sessions[0].room_id(), room_id);
2461
2462 assert_eq!(
2464 imported_sessions[0]
2465 .forwarder_data
2466 .as_ref()
2467 .expect("Session should contain forwarder data.")
2468 .user_id(),
2469 alice.user_id()
2470 );
2471
2472 assert_matches!(
2473 bob.store()
2474 .get_withheld_info(room_id, sessions[1].session_id())
2475 .await
2476 .unwrap()
2477 .expect("Withheld info should be present in the store."),
2478 RoomKeyWithheldEntry {
2479 #[cfg(not(feature = "experimental-algorithms"))]
2480 content: RoomKeyWithheldContent::MegolmV1AesSha2(
2481 MegolmV1AesSha2WithheldContent::HistoryNotShared(_)
2482 ),
2483 #[cfg(feature = "experimental-algorithms")]
2484 content: RoomKeyWithheldContent::MegolmV2AesSha2(
2485 MegolmV1AesSha2WithheldContent::HistoryNotShared(_)
2486 ),
2487 ..
2488 }
2489 );
2490 }
2491
2492 #[async_test]
2498 async fn test_deserialize_room_key_withheld_entry_from_to_device_event() {
2499 let entry: RoomKeyWithheldEntry = serde_json::from_value(json!(
2500 {
2501 "content": {
2502 "algorithm": "m.megolm.v1.aes-sha2",
2503 "code": "m.unauthorised",
2504 "from_device": "ALICE",
2505 "reason": "You are not authorised to read the message.",
2506 "room_id": "!roomid:s.co",
2507 "sender_key": "7hIcOrEroXYdzjtCBvBjUiqvT0Me7g+ymeXqoc65RS0",
2508 "session_id": "session123"
2509 },
2510 "sender": "@alice:s.co",
2511 "type": "m.room_key.withheld"
2512 }
2513 ))
2514 .unwrap();
2515
2516 assert_let!(
2517 RoomKeyWithheldEntry {
2518 sender,
2519 content: RoomKeyWithheldContent::MegolmV1AesSha2(
2520 MegolmV1AesSha2WithheldContent::Unauthorised(withheld_content)
2521 ),
2522 } = entry
2523 );
2524
2525 assert_eq!(sender, "@alice:s.co");
2526 assert_eq!(withheld_content.room_id, "!roomid:s.co");
2527 assert_eq!(withheld_content.session_id, "session123");
2528 assert_eq!(
2529 withheld_content.sender_key.to_base64(),
2530 "7hIcOrEroXYdzjtCBvBjUiqvT0Me7g+ymeXqoc65RS0"
2531 );
2532 assert_eq!(withheld_content.from_device, Some(owned_device_id!("ALICE")));
2533 }
2534
2535 fn create_inbound_group_session_with_visibility(
2546 olm_machine: &OlmMachine,
2547 room_id: &RoomId,
2548 session_key: &SessionKey,
2549 shared_history: bool,
2550 ) -> InboundGroupSession {
2551 let identity_keys = &olm_machine.store().static_account().identity_keys;
2552 InboundGroupSession::new(
2553 identity_keys.curve25519,
2554 identity_keys.ed25519,
2555 room_id,
2556 session_key,
2557 SenderData::unknown(),
2558 None,
2559 #[cfg(not(feature = "experimental-algorithms"))]
2560 EventEncryptionAlgorithm::MegolmV1AesSha2,
2561 #[cfg(feature = "experimental-algorithms")]
2562 EventEncryptionAlgorithm::MegolmV2AesSha2,
2563 None,
2564 shared_history,
2565 )
2566 .unwrap()
2567 }
2568}