matrix_sdk_crypto/store/
mod.rs

1// Copyright 2020 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Types and traits to implement the storage layer for the [`OlmMachine`]
16//!
17//! The storage layer for the [`OlmMachine`] can be customized using a trait.
18//! Implementing your own [`CryptoStore`]
19//!
20//! An in-memory only store is provided as well as an SQLite-based one,
21//! depending on your needs and targets a custom store may be implemented, e.g.
22//! for `wasm-unknown-unknown` an indexeddb store would be needed
23//!
24//! ```
25//! # use std::sync::Arc;
26//! # use matrix_sdk_crypto::{
27//! #     OlmMachine,
28//! #     store::MemoryStore,
29//! # };
30//! # use ruma::{device_id, user_id};
31//! # let user_id = user_id!("@example:localhost");
32//! # let device_id = device_id!("TEST");
33//! let store = Arc::new(MemoryStore::new());
34//!
35//! let machine = OlmMachine::with_store(user_id, device_id, store, None);
36//! ```
37//!
38//! [`OlmMachine`]: /matrix_sdk_crypto/struct.OlmMachine.html
39//! [`CryptoStore`]: trait.Cryptostore.html
40
41use std::{
42    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
43    fmt::Debug,
44    ops::Deref,
45    pin::pin,
46    sync::{atomic::Ordering, Arc},
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    encryption::KeyUsage, events::secret::request::SecretName, DeviceId, OwnedDeviceId,
56    OwnedUserId, RoomId, UserId,
57};
58use serde::{de::DeserializeOwned, Serialize};
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::{megolm::SessionOrdering, Curve25519PublicKey};
65
66use self::types::{
67    Changes, CrossSigningKeyExport, DeviceChanges, DeviceUpdates, IdentityChanges, IdentityUpdates,
68    PendingChanges, RoomKeyInfo, RoomKeyWithheldInfo, UserKeyQueryResult,
69};
70#[cfg(doc)]
71use crate::{backups::BackupMachine, identities::OwnUserIdentity};
72use crate::{
73    gossiping::GossippedSecret,
74    identities::{user::UserIdentity, Device, DeviceData, UserDevices, UserIdentityData},
75    olm::{
76        Account, ExportedRoomKey, InboundGroupSession, PrivateCrossSigningIdentity, SenderData,
77        Session, StaticAccountData,
78    },
79    store::types::RoomKeyWithheldEntry,
80    types::{
81        BackupSecrets, CrossSigningSecrets, MegolmBackupV1Curve25519AesSha2Secrets, RoomKeyExport,
82        SecretsBundle,
83    },
84    verification::VerificationMachine,
85    CrossSigningStatus, OwnUserIdentityData, RoomKeyImportResult,
86};
87
88pub mod caches;
89mod crypto_store_wrapper;
90mod error;
91mod memorystore;
92mod traits;
93pub mod types;
94
95#[cfg(any(test, feature = "testing"))]
96#[macro_use]
97#[allow(missing_docs)]
98pub mod integration_tests;
99
100pub(crate) use crypto_store_wrapper::CryptoStoreWrapper;
101pub use error::{CryptoStoreError, Result};
102use matrix_sdk_common::{
103    cross_process_lock::{CrossProcessLock, CrossProcessLockGeneration},
104    deserialized_responses::WithheldCode,
105    timeout::timeout,
106};
107pub use memorystore::MemoryStore;
108pub use traits::{CryptoStore, DynCryptoStore, IntoCryptoStore};
109
110use self::caches::{SequenceNumber, StoreCache, StoreCacheGuard, UsersForKeyQuery};
111use crate::types::{
112    events::room_key_withheld::RoomKeyWithheldContent, room_history::RoomKeyBundle,
113};
114pub use crate::{
115    dehydrated_devices::DehydrationError,
116    gossiping::{GossipRequest, SecretInfo},
117};
118
119/// A wrapper for our CryptoStore trait object.
120///
121/// This is needed because we want to have a generic interface so we can
122/// store/restore objects that we can serialize. Since trait objects and
123/// generics don't mix let the CryptoStore store strings and this wrapper
124/// adds the generic interface on top.
125#[derive(Debug, Clone)]
126pub struct Store {
127    inner: Arc<StoreInner>,
128}
129
130#[derive(Debug, Default)]
131pub(crate) struct KeyQueryManager {
132    /// Record of the users that are waiting for a /keys/query.
133    users_for_key_query: Mutex<UsersForKeyQuery>,
134
135    /// Notifier that is triggered each time an update is received for a user.
136    users_for_key_query_notify: Notify,
137}
138
139impl KeyQueryManager {
140    pub async fn synced<'a>(&'a self, cache: &'a StoreCache) -> Result<SyncedKeyQueryManager<'a>> {
141        self.ensure_sync_tracked_users(cache).await?;
142        Ok(SyncedKeyQueryManager { cache, manager: self })
143    }
144
145    /// Load the list of users for whom we are tracking their device lists and
146    /// fill out our caches.
147    ///
148    /// This method ensures that we're only going to load the users from the
149    /// actual [`CryptoStore`] once, it will also make sure that any
150    /// concurrent calls to this method get deduplicated.
151    async fn ensure_sync_tracked_users(&self, cache: &StoreCache) -> Result<()> {
152        // Check if the users are loaded, and in that case do nothing.
153        let loaded = cache.loaded_tracked_users.read().await;
154        if *loaded {
155            return Ok(());
156        }
157
158        // Otherwise, we may load the users.
159        drop(loaded);
160        let mut loaded = cache.loaded_tracked_users.write().await;
161
162        // Check again if the users have been loaded, in case another call to this
163        // method loaded the tracked users between the time we tried to
164        // acquire the lock and the time we actually acquired the lock.
165        if *loaded {
166            return Ok(());
167        }
168
169        let tracked_users = cache.store.load_tracked_users().await?;
170
171        let mut query_users_lock = self.users_for_key_query.lock().await;
172        let mut tracked_users_cache = cache.tracked_users.write();
173        for user in tracked_users {
174            tracked_users_cache.insert(user.user_id.to_owned());
175
176            if user.dirty {
177                query_users_lock.insert_user(&user.user_id);
178            }
179        }
180
181        *loaded = true;
182
183        Ok(())
184    }
185
186    /// Wait for a `/keys/query` response to be received if one is expected for
187    /// the given user.
188    ///
189    /// If the given timeout elapses, the method will stop waiting and return
190    /// [`UserKeyQueryResult::TimeoutExpired`].
191    ///
192    /// Requires a [`StoreCacheGuard`] to make sure the users for which a key
193    /// query is pending are up to date, but doesn't hold on to it
194    /// thereafter: the lock is short-lived in this case.
195    pub async fn wait_if_user_key_query_pending(
196        &self,
197        cache: StoreCacheGuard,
198        timeout_duration: Duration,
199        user: &UserId,
200    ) -> Result<UserKeyQueryResult> {
201        {
202            // Drop the cache early, so we don't keep it while waiting (since writing the
203            // results requires to write in the cache, thus take another lock).
204            self.ensure_sync_tracked_users(&cache).await?;
205            drop(cache);
206        }
207
208        let mut users_for_key_query = self.users_for_key_query.lock().await;
209        let Some(waiter) = users_for_key_query.maybe_register_waiting_task(user) else {
210            return Ok(UserKeyQueryResult::WasNotPending);
211        };
212
213        let wait_for_completion = async {
214            while !waiter.completed.load(Ordering::Relaxed) {
215                // Register for being notified before releasing the mutex, so
216                // it's impossible to miss a wakeup between the last check for
217                // whether we should wait, and starting to wait.
218                let mut notified = pin!(self.users_for_key_query_notify.notified());
219                notified.as_mut().enable();
220                drop(users_for_key_query);
221
222                // Wait for a notification
223                notified.await;
224
225                // Reclaim the lock before checking the flag to avoid races
226                // when two notifications happen right after each other and the
227                // second one sets the flag we want to wait for.
228                users_for_key_query = self.users_for_key_query.lock().await;
229            }
230        };
231
232        match timeout(Box::pin(wait_for_completion), timeout_duration).await {
233            Err(_) => {
234                warn!(
235                    user_id = ?user,
236                    "The user has a pending `/keys/query` request which did \
237                    not finish yet, some devices might be missing."
238                );
239
240                Ok(UserKeyQueryResult::TimeoutExpired)
241            }
242            _ => Ok(UserKeyQueryResult::WasPending),
243        }
244    }
245}
246
247pub(crate) struct SyncedKeyQueryManager<'a> {
248    cache: &'a StoreCache,
249    manager: &'a KeyQueryManager,
250}
251
252impl SyncedKeyQueryManager<'_> {
253    /// Add entries to the list of users being tracked for device changes
254    ///
255    /// Any users not already on the list are flagged as awaiting a key query.
256    /// Users that were already in the list are unaffected.
257    pub async fn update_tracked_users(&self, users: impl Iterator<Item = &UserId>) -> Result<()> {
258        let mut store_updates = Vec::new();
259        let mut key_query_lock = self.manager.users_for_key_query.lock().await;
260
261        {
262            let mut tracked_users = self.cache.tracked_users.write();
263            for user_id in users {
264                if tracked_users.insert(user_id.to_owned()) {
265                    key_query_lock.insert_user(user_id);
266                    store_updates.push((user_id, true))
267                }
268            }
269        }
270
271        self.cache.store.save_tracked_users(&store_updates).await
272    }
273
274    /// Process notifications that users have changed devices.
275    ///
276    /// This is used to handle the list of device-list updates that is received
277    /// from the `/sync` response. Any users *whose device lists we are
278    /// tracking* are flagged as needing a key query. Users whose devices we
279    /// are not tracking are ignored.
280    pub async fn mark_tracked_users_as_changed(
281        &self,
282        users: impl Iterator<Item = &UserId>,
283    ) -> Result<()> {
284        let mut store_updates: Vec<(&UserId, bool)> = Vec::new();
285        let mut key_query_lock = self.manager.users_for_key_query.lock().await;
286
287        {
288            let tracked_users = &self.cache.tracked_users.read();
289            for user_id in users {
290                if tracked_users.contains(user_id) {
291                    key_query_lock.insert_user(user_id);
292                    store_updates.push((user_id, true));
293                }
294            }
295        }
296
297        self.cache.store.save_tracked_users(&store_updates).await
298    }
299
300    /// Flag that the given users devices are now up-to-date.
301    ///
302    /// This is called after processing the response to a /keys/query request.
303    /// Any users whose device lists we are tracking are removed from the
304    /// list of those pending a /keys/query.
305    pub async fn mark_tracked_users_as_up_to_date(
306        &self,
307        users: impl Iterator<Item = &UserId>,
308        sequence_number: SequenceNumber,
309    ) -> Result<()> {
310        let mut store_updates: Vec<(&UserId, bool)> = Vec::new();
311        let mut key_query_lock = self.manager.users_for_key_query.lock().await;
312
313        {
314            let tracked_users = self.cache.tracked_users.read();
315            for user_id in users {
316                if tracked_users.contains(user_id) {
317                    let clean = key_query_lock.maybe_remove_user(user_id, sequence_number);
318                    store_updates.push((user_id, !clean));
319                }
320            }
321        }
322
323        self.cache.store.save_tracked_users(&store_updates).await?;
324        // wake up any tasks that may have been waiting for updates
325        self.manager.users_for_key_query_notify.notify_waiters();
326
327        Ok(())
328    }
329
330    /// Get the set of users that has the outdate/dirty flag set for their list
331    /// of devices.
332    ///
333    /// This set should be included in a `/keys/query` request which will update
334    /// the device list.
335    ///
336    /// # Returns
337    ///
338    /// A pair `(users, sequence_number)`, where `users` is the list of users to
339    /// be queried, and `sequence_number` is the current sequence number,
340    /// which should be returned in `mark_tracked_users_as_up_to_date`.
341    pub async fn users_for_key_query(&self) -> (HashSet<OwnedUserId>, SequenceNumber) {
342        self.manager.users_for_key_query.lock().await.users_for_key_query()
343    }
344
345    /// See the docs for [`crate::OlmMachine::tracked_users()`].
346    pub fn tracked_users(&self) -> HashSet<OwnedUserId> {
347        self.cache.tracked_users.read().iter().cloned().collect()
348    }
349
350    /// Mark the given user as being tracked for device lists, and mark that it
351    /// has an outdated device list.
352    ///
353    /// This means that the user will be considered for a `/keys/query` request
354    /// next time [`Store::users_for_key_query()`] is called.
355    pub async fn mark_user_as_changed(&self, user: &UserId) -> Result<()> {
356        self.manager.users_for_key_query.lock().await.insert_user(user);
357        self.cache.tracked_users.write().insert(user.to_owned());
358
359        self.cache.store.save_tracked_users(&[(user, true)]).await
360    }
361}
362
363/// Convert the devices and vectors contained in the [`DeviceChanges`] into
364/// a [`DeviceUpdates`] struct.
365///
366/// The [`DeviceChanges`] will contain vectors of [`DeviceData`]s which
367/// we want to convert to a [`Device`].
368fn collect_device_updates(
369    verification_machine: VerificationMachine,
370    own_identity: Option<OwnUserIdentityData>,
371    identities: IdentityChanges,
372    devices: DeviceChanges,
373) -> DeviceUpdates {
374    let mut new: BTreeMap<_, BTreeMap<_, _>> = BTreeMap::new();
375    let mut changed: BTreeMap<_, BTreeMap<_, _>> = BTreeMap::new();
376
377    let (new_identities, changed_identities, unchanged_identities) = identities.into_maps();
378
379    let map_device = |device: DeviceData| {
380        let device_owner_identity = new_identities
381            .get(device.user_id())
382            .or_else(|| changed_identities.get(device.user_id()))
383            .or_else(|| unchanged_identities.get(device.user_id()))
384            .cloned();
385
386        Device {
387            inner: device,
388            verification_machine: verification_machine.to_owned(),
389            own_identity: own_identity.to_owned(),
390            device_owner_identity,
391        }
392    };
393
394    for device in devices.new {
395        let device = map_device(device);
396
397        new.entry(device.user_id().to_owned())
398            .or_default()
399            .insert(device.device_id().to_owned(), device);
400    }
401
402    for device in devices.changed {
403        let device = map_device(device);
404
405        changed
406            .entry(device.user_id().to_owned())
407            .or_default()
408            .insert(device.device_id().to_owned(), device.to_owned());
409    }
410
411    DeviceUpdates { new, changed }
412}
413
414/// A temporary transaction (that implies a write) to the underlying store.
415#[allow(missing_debug_implementations)]
416pub struct StoreTransaction {
417    store: Store,
418    changes: PendingChanges,
419    // TODO hold onto the cross-process crypto store lock + cache.
420    cache: OwnedRwLockWriteGuard<StoreCache>,
421}
422
423impl StoreTransaction {
424    /// Starts a new `StoreTransaction`.
425    async fn new(store: Store) -> Self {
426        let cache = store.inner.cache.clone();
427
428        Self { store, changes: PendingChanges::default(), cache: cache.clone().write_owned().await }
429    }
430
431    pub(crate) fn cache(&self) -> &StoreCache {
432        &self.cache
433    }
434
435    /// Returns a reference to the current `Store`.
436    pub fn store(&self) -> &Store {
437        &self.store
438    }
439
440    /// Gets a `Account` for update.
441    ///
442    /// Note: since it's guaranteed that one can't have both a
443    /// `StoreTransaction` and a `StoreCacheGuard` at runtime (since the
444    /// underlying `StoreCache` is guarded by a `RwLock` mutex), this ensures
445    /// that we can't have two copies of an `Account` alive at the same time.
446    pub async fn account(&mut self) -> Result<&mut Account> {
447        if self.changes.account.is_none() {
448            // Make sure the cache loaded the account.
449            let _ = self.cache.account().await?;
450            self.changes.account = self.cache.account.lock().await.take();
451        }
452        Ok(self.changes.account.as_mut().unwrap())
453    }
454
455    /// Commits all dirty fields to the store, and maintains the cache so it
456    /// reflects the current state of the database.
457    pub async fn commit(self) -> Result<()> {
458        if self.changes.is_empty() {
459            return Ok(());
460        }
461
462        // Save changes in the database.
463        let account = self.changes.account.as_ref().map(|acc| acc.deep_clone());
464
465        self.store.save_pending_changes(self.changes).await?;
466
467        // Make the cache coherent with the database.
468        if let Some(account) = account {
469            *self.cache.account.lock().await = Some(account);
470        }
471
472        Ok(())
473    }
474}
475
476#[derive(Debug)]
477struct StoreInner {
478    identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
479    store: Arc<CryptoStoreWrapper>,
480
481    /// In-memory cache for the current crypto store.
482    ///
483    /// ⚠ Must remain private.
484    cache: Arc<RwLock<StoreCache>>,
485
486    verification_machine: VerificationMachine,
487
488    /// Static account data that never changes (and thus can be loaded once and
489    /// for all when creating the store).
490    static_account: StaticAccountData,
491}
492
493/// Error describing what went wrong when importing private cross signing keys
494/// or the key backup key.
495#[derive(Debug, Error)]
496pub enum SecretImportError {
497    /// The key that we tried to import was invalid.
498    #[error("Error while importing {name}: {error}")]
499    Key {
500        /// The name of the secret that was being imported.
501        name: SecretName,
502        /// The key error that occurred.
503        error: vodozemac::KeyError,
504    },
505    /// The public key of the imported private key doesn't match the public
506    /// key that was uploaded to the server.
507    #[error(
508        "Error while importing {name}: The public key of the imported private \
509            key doesn't match the public key that was uploaded to the server"
510    )]
511    MismatchedPublicKeys {
512        /// The name of the secret that was being imported.
513        name: SecretName,
514    },
515    /// The new version of the identity couldn't be stored.
516    #[error(transparent)]
517    Store(#[from] CryptoStoreError),
518}
519
520/// Error describing what went wrong when exporting a [`SecretsBundle`].
521///
522/// The [`SecretsBundle`] can only be exported if we have all cross-signing
523/// private keys in the store.
524#[derive(Debug, Error)]
525pub enum SecretsBundleExportError {
526    /// The store itself had an error.
527    #[error(transparent)]
528    Store(#[from] CryptoStoreError),
529    /// We're missing one or multiple cross-signing keys.
530    #[error("The store is missing one or multiple cross-signing keys")]
531    MissingCrossSigningKey(KeyUsage),
532    /// We're missing all cross-signing keys.
533    #[error("The store doesn't contain any cross-signing keys")]
534    MissingCrossSigningKeys,
535    /// We have a backup key stored, but we don't know the version of the
536    /// backup.
537    #[error("The store contains a backup key, but no backup version")]
538    MissingBackupVersion,
539}
540
541impl Store {
542    /// Create a new Store.
543    pub(crate) fn new(
544        account: StaticAccountData,
545        identity: Arc<Mutex<PrivateCrossSigningIdentity>>,
546        store: Arc<CryptoStoreWrapper>,
547        verification_machine: VerificationMachine,
548    ) -> Self {
549        Self {
550            inner: Arc::new(StoreInner {
551                static_account: account,
552                identity,
553                store: store.clone(),
554                verification_machine,
555                cache: Arc::new(RwLock::new(StoreCache {
556                    store,
557                    tracked_users: Default::default(),
558                    loaded_tracked_users: Default::default(),
559                    account: Default::default(),
560                })),
561            }),
562        }
563    }
564
565    /// UserId associated with this store
566    pub(crate) fn user_id(&self) -> &UserId {
567        &self.inner.static_account.user_id
568    }
569
570    /// DeviceId associated with this store
571    pub(crate) fn device_id(&self) -> &DeviceId {
572        self.inner.verification_machine.own_device_id()
573    }
574
575    /// The static data for the account associated with this store.
576    pub(crate) fn static_account(&self) -> &StaticAccountData {
577        &self.inner.static_account
578    }
579
580    pub(crate) async fn cache(&self) -> Result<StoreCacheGuard> {
581        // TODO: (bnjbvr, #2624) If configured with a cross-process lock:
582        // - try to take the lock,
583        // - if acquired, look if another process touched the underlying storage,
584        // - if yes, reload everything; if no, return current cache
585        Ok(StoreCacheGuard { cache: self.inner.cache.clone().read_owned().await })
586    }
587
588    pub(crate) async fn transaction(&self) -> StoreTransaction {
589        StoreTransaction::new(self.clone()).await
590    }
591
592    // Note: bnjbvr lost against borrowck here. Ideally, the `F` parameter would
593    // take a `&StoreTransaction`, but callers didn't quite like that.
594    pub(crate) async fn with_transaction<
595        T,
596        Fut: futures_core::Future<Output = Result<(StoreTransaction, T), crate::OlmError>>,
597        F: FnOnce(StoreTransaction) -> Fut,
598    >(
599        &self,
600        func: F,
601    ) -> Result<T, crate::OlmError> {
602        let tr = self.transaction().await;
603        let (tr, res) = func(tr).await?;
604        tr.commit().await?;
605        Ok(res)
606    }
607
608    #[cfg(test)]
609    /// test helper to reset the cross signing identity
610    pub(crate) async fn reset_cross_signing_identity(&self) {
611        self.inner.identity.lock().await.reset();
612    }
613
614    /// PrivateCrossSigningIdentity associated with this store
615    pub(crate) fn private_identity(&self) -> Arc<Mutex<PrivateCrossSigningIdentity>> {
616        self.inner.identity.clone()
617    }
618
619    /// Save the given Sessions to the store
620    pub(crate) async fn save_sessions(&self, sessions: &[Session]) -> Result<()> {
621        let changes = Changes { sessions: sessions.to_vec(), ..Default::default() };
622
623        self.save_changes(changes).await
624    }
625
626    pub(crate) async fn get_sessions(
627        &self,
628        sender_key: &str,
629    ) -> Result<Option<Arc<Mutex<Vec<Session>>>>> {
630        self.inner.store.get_sessions(sender_key).await
631    }
632
633    pub(crate) async fn save_changes(&self, changes: Changes) -> Result<()> {
634        self.inner.store.save_changes(changes).await
635    }
636
637    /// Given an `InboundGroupSession` which we have just received, see if we
638    /// have a matching session already in the store, and determine how to
639    /// handle it.
640    ///
641    /// If the store already has everything we can gather from the new session,
642    /// returns `None`. Otherwise, returns a merged session which should be
643    /// persisted to the store.
644    pub(crate) async fn merge_received_group_session(
645        &self,
646        session: InboundGroupSession,
647    ) -> Result<Option<InboundGroupSession>> {
648        let old_session = self
649            .inner
650            .store
651            .get_inbound_group_session(session.room_id(), session.session_id())
652            .await?;
653
654        // If there is no old session, just use the new session.
655        let Some(old_session) = old_session else {
656            info!("Received a new megolm room key");
657            return Ok(Some(session));
658        };
659
660        let index_comparison = session.compare_ratchet(&old_session).await;
661        let trust_level_comparison =
662            session.sender_data.compare_trust_level(&old_session.sender_data);
663
664        let result = match (index_comparison, trust_level_comparison) {
665            (SessionOrdering::Unconnected, _) => {
666                // If this happens, it means that we have two sessions purporting to have the
667                // same session id, but where the ratchets do not match up.
668                // In other words, someone is playing silly buggers.
669                warn!("Received a group session with an ratchet that does not connect to the one in the store, discarding");
670                None
671            }
672
673            (SessionOrdering::Better, std::cmp::Ordering::Greater)
674            | (SessionOrdering::Better, std::cmp::Ordering::Equal)
675            | (SessionOrdering::Equal, std::cmp::Ordering::Greater) => {
676                // The new session is unambiguously better than what we have in the store.
677                info!(
678                    ?index_comparison,
679                    ?trust_level_comparison,
680                    "Received a megolm room key that we have a worse version of, merging"
681                );
682                Some(session)
683            }
684
685            (SessionOrdering::Worse, std::cmp::Ordering::Less)
686            | (SessionOrdering::Worse, std::cmp::Ordering::Equal)
687            | (SessionOrdering::Equal, std::cmp::Ordering::Less) => {
688                // The new session is unambiguously worse than the one we have in the store.
689                warn!(
690                    ?index_comparison,
691                    ?trust_level_comparison,
692                    "Received a megolm room key that we already have a better version \
693                     of, discarding"
694                );
695                None
696            }
697
698            (SessionOrdering::Equal, std::cmp::Ordering::Equal) => {
699                // The new session is the same as what we have.
700                info!("Received a megolm room key that we already have, discarding");
701                None
702            }
703
704            (SessionOrdering::Better, std::cmp::Ordering::Less) => {
705                // We need to take the ratchet from the new session, and the
706                // sender data from the old session.
707                info!("Upgrading a previously-received megolm session with new ratchet");
708                let result = old_session.with_ratchet(&session);
709                // We'll need to back it up again.
710                result.reset_backup_state();
711                Some(result)
712            }
713
714            (SessionOrdering::Worse, std::cmp::Ordering::Greater) => {
715                // We need to take the ratchet from the old session, and the
716                // sender data from the new session.
717                info!("Upgrading a previously-received megolm session with new sender data");
718                Some(session.with_ratchet(&old_session))
719            }
720        };
721
722        Ok(result)
723    }
724
725    #[cfg(test)]
726    /// Testing helper to allow to save only a set of devices
727    pub(crate) async fn save_device_data(&self, devices: &[DeviceData]) -> Result<()> {
728        use types::DeviceChanges;
729
730        let changes = Changes {
731            devices: DeviceChanges { changed: devices.to_vec(), ..Default::default() },
732            ..Default::default()
733        };
734
735        self.save_changes(changes).await
736    }
737
738    /// Convenience helper to persist an array of [`InboundGroupSession`]s.
739    pub(crate) async fn save_inbound_group_sessions(
740        &self,
741        sessions: &[InboundGroupSession],
742    ) -> Result<()> {
743        let changes = Changes { inbound_group_sessions: sessions.to_vec(), ..Default::default() };
744
745        self.save_changes(changes).await
746    }
747
748    /// Get the display name of our own device.
749    pub(crate) async fn device_display_name(&self) -> Result<Option<String>, CryptoStoreError> {
750        Ok(self
751            .inner
752            .store
753            .get_device(self.user_id(), self.device_id())
754            .await?
755            .and_then(|d| d.display_name().map(|d| d.to_owned())))
756    }
757
758    /// Get the device data for the given [`UserId`] and [`DeviceId`].
759    ///
760    /// *Note*: This method will include our own device which is always present
761    /// in the store.
762    pub(crate) async fn get_device_data(
763        &self,
764        user_id: &UserId,
765        device_id: &DeviceId,
766    ) -> Result<Option<DeviceData>> {
767        self.inner.store.get_device(user_id, device_id).await
768    }
769
770    /// Get the device data for the given [`UserId`] and [`DeviceId`].
771    ///
772    /// *Note*: This method will **not** include our own device.
773    ///
774    /// Use this method if you need a list of recipients for a given user, since
775    /// we don't want to encrypt for our own device, otherwise take a look at
776    /// the [`Store::get_device_data_for_user`] method.
777    pub(crate) async fn get_device_data_for_user_filtered(
778        &self,
779        user_id: &UserId,
780    ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
781        self.inner.store.get_user_devices(user_id).await.map(|mut d| {
782            if user_id == self.user_id() {
783                d.remove(self.device_id());
784            }
785            d
786        })
787    }
788
789    /// Get the [`DeviceData`] for all the devices a user has.
790    ///
791    /// *Note*: This method will include our own device which is always present
792    /// in the store.
793    ///
794    /// Use this method if you need to operate on or update all devices of a
795    /// user, otherwise take a look at the
796    /// [`Store::get_device_data_for_user_filtered`] method.
797    pub(crate) async fn get_device_data_for_user(
798        &self,
799        user_id: &UserId,
800    ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
801        self.inner.store.get_user_devices(user_id).await
802    }
803
804    /// Get a [`Device`] for the given user with the given
805    /// [`Curve25519PublicKey`] key.
806    ///
807    /// *Note*: This method will include our own device which is always present
808    /// in the store.
809    pub(crate) async fn get_device_from_curve_key(
810        &self,
811        user_id: &UserId,
812        curve_key: Curve25519PublicKey,
813    ) -> Result<Option<Device>> {
814        self.get_user_devices(user_id)
815            .await
816            .map(|d| d.devices().find(|d| d.curve25519_key() == Some(curve_key)))
817    }
818
819    /// Get all devices associated with the given [`UserId`].
820    ///
821    /// This method is more expensive than the
822    /// [`Store::get_device_data_for_user`] method, since a [`Device`]
823    /// requires the [`OwnUserIdentityData`] and the [`UserIdentityData`] of the
824    /// device owner to be fetched from the store as well.
825    ///
826    /// *Note*: This method will include our own device which is always present
827    /// in the store.
828    pub(crate) async fn get_user_devices(&self, user_id: &UserId) -> Result<UserDevices> {
829        let devices = self.get_device_data_for_user(user_id).await?;
830
831        let own_identity = self
832            .inner
833            .store
834            .get_user_identity(self.user_id())
835            .await?
836            .and_then(|i| i.own().cloned());
837        let device_owner_identity = self.inner.store.get_user_identity(user_id).await?;
838
839        Ok(UserDevices {
840            inner: devices,
841            verification_machine: self.inner.verification_machine.clone(),
842            own_identity,
843            device_owner_identity,
844        })
845    }
846
847    /// Get a [`Device`] for the given user with the given [`DeviceId`].
848    ///
849    /// This method is more expensive than the [`Store::get_device_data`] method
850    /// since a [`Device`] requires the [`OwnUserIdentityData`] and the
851    /// [`UserIdentityData`] of the device owner to be fetched from the
852    /// store as well.
853    ///
854    /// *Note*: This method will include our own device which is always present
855    /// in the store.
856    pub(crate) async fn get_device(
857        &self,
858        user_id: &UserId,
859        device_id: &DeviceId,
860    ) -> Result<Option<Device>> {
861        if let Some(device_data) = self.inner.store.get_device(user_id, device_id).await? {
862            Ok(Some(self.wrap_device_data(device_data).await?))
863        } else {
864            Ok(None)
865        }
866    }
867
868    /// Create a new device using the supplied [`DeviceData`]. Normally we would
869    /// call [`Self::get_device`] to find an existing device inside this
870    /// store. Only call this if you have some existing DeviceData and want
871    /// to wrap it with the extra information provided by a [`Device`].
872    pub(crate) async fn wrap_device_data(&self, device_data: DeviceData) -> Result<Device> {
873        let own_identity = self
874            .inner
875            .store
876            .get_user_identity(self.user_id())
877            .await?
878            .and_then(|i| i.own().cloned());
879
880        let device_owner_identity =
881            self.inner.store.get_user_identity(device_data.user_id()).await?;
882
883        Ok(Device {
884            inner: device_data,
885            verification_machine: self.inner.verification_machine.clone(),
886            own_identity,
887            device_owner_identity,
888        })
889    }
890
891    ///  Get the Identity of `user_id`
892    pub(crate) async fn get_identity(&self, user_id: &UserId) -> Result<Option<UserIdentity>> {
893        let own_identity = self
894            .inner
895            .store
896            .get_user_identity(self.user_id())
897            .await?
898            .and_then(as_variant!(UserIdentityData::Own));
899
900        Ok(self.inner.store.get_user_identity(user_id).await?.map(|i| {
901            UserIdentity::new(
902                self.clone(),
903                i,
904                self.inner.verification_machine.to_owned(),
905                own_identity,
906            )
907        }))
908    }
909
910    /// Try to export the secret with the given secret name.
911    ///
912    /// The exported secret will be encoded as unpadded base64. Returns `Null`
913    /// if the secret can't be found.
914    ///
915    /// # Arguments
916    ///
917    /// * `secret_name` - The name of the secret that should be exported.
918    pub async fn export_secret(
919        &self,
920        secret_name: &SecretName,
921    ) -> Result<Option<String>, CryptoStoreError> {
922        Ok(match secret_name {
923            SecretName::CrossSigningMasterKey
924            | SecretName::CrossSigningUserSigningKey
925            | SecretName::CrossSigningSelfSigningKey => {
926                self.inner.identity.lock().await.export_secret(secret_name).await
927            }
928            SecretName::RecoveryKey => {
929                if let Some(key) = self.load_backup_keys().await?.decryption_key {
930                    let exported = key.to_base64();
931                    Some(exported)
932                } else {
933                    None
934                }
935            }
936            name => {
937                warn!(secret = ?name, "Unknown secret was requested");
938                None
939            }
940        })
941    }
942
943    /// Export all the private cross signing keys we have.
944    ///
945    /// The export will contain the seed for the ed25519 keys as a unpadded
946    /// base64 encoded string.
947    ///
948    /// This method returns `None` if we don't have any private cross signing
949    /// keys.
950    pub async fn export_cross_signing_keys(
951        &self,
952    ) -> Result<Option<CrossSigningKeyExport>, CryptoStoreError> {
953        let master_key = self.export_secret(&SecretName::CrossSigningMasterKey).await?;
954        let self_signing_key = self.export_secret(&SecretName::CrossSigningSelfSigningKey).await?;
955        let user_signing_key = self.export_secret(&SecretName::CrossSigningUserSigningKey).await?;
956
957        Ok(if master_key.is_none() && self_signing_key.is_none() && user_signing_key.is_none() {
958            None
959        } else {
960            Some(CrossSigningKeyExport { master_key, self_signing_key, user_signing_key })
961        })
962    }
963
964    /// Import our private cross signing keys.
965    ///
966    /// The export needs to contain the seed for the Ed25519 keys as an unpadded
967    /// base64 encoded string.
968    pub async fn import_cross_signing_keys(
969        &self,
970        export: CrossSigningKeyExport,
971    ) -> Result<CrossSigningStatus, SecretImportError> {
972        if let Some(public_identity) =
973            self.get_identity(self.user_id()).await?.and_then(|i| i.own())
974        {
975            let identity = self.inner.identity.lock().await;
976
977            identity
978                .import_secrets(
979                    public_identity.to_owned(),
980                    export.master_key.as_deref(),
981                    export.self_signing_key.as_deref(),
982                    export.user_signing_key.as_deref(),
983                )
984                .await?;
985
986            let status = identity.status().await;
987
988            let diff = identity.get_public_identity_diff(&public_identity.inner).await;
989
990            let mut changes =
991                Changes { private_identity: Some(identity.clone()), ..Default::default() };
992
993            if diff.none_differ() {
994                public_identity.mark_as_verified();
995                changes.identities.changed.push(UserIdentityData::Own(public_identity.inner));
996            }
997
998            info!(?status, "Successfully imported the private cross-signing keys");
999
1000            self.save_changes(changes).await?;
1001        } else {
1002            warn!(
1003                "No public identity found while importing cross-signing keys, \
1004                 a /keys/query needs to be done"
1005            );
1006        }
1007
1008        Ok(self.inner.identity.lock().await.status().await)
1009    }
1010
1011    /// Export all the secrets we have in the store into a [`SecretsBundle`].
1012    ///
1013    /// This method will export all the private cross-signing keys and, if
1014    /// available, the private part of a backup key and its accompanying
1015    /// version.
1016    ///
1017    /// The method will fail if we don't have all three private cross-signing
1018    /// keys available.
1019    ///
1020    /// **Warning**: Only export this and share it with a trusted recipient,
1021    /// i.e. if an existing device is sharing this with a new device.
1022    pub async fn export_secrets_bundle(&self) -> Result<SecretsBundle, SecretsBundleExportError> {
1023        let Some(cross_signing) = self.export_cross_signing_keys().await? else {
1024            return Err(SecretsBundleExportError::MissingCrossSigningKeys);
1025        };
1026
1027        let Some(master_key) = cross_signing.master_key.clone() else {
1028            return Err(SecretsBundleExportError::MissingCrossSigningKey(KeyUsage::Master));
1029        };
1030
1031        let Some(user_signing_key) = cross_signing.user_signing_key.clone() else {
1032            return Err(SecretsBundleExportError::MissingCrossSigningKey(KeyUsage::UserSigning));
1033        };
1034
1035        let Some(self_signing_key) = cross_signing.self_signing_key.clone() else {
1036            return Err(SecretsBundleExportError::MissingCrossSigningKey(KeyUsage::SelfSigning));
1037        };
1038
1039        let backup_keys = self.load_backup_keys().await?;
1040
1041        let backup = if let Some(key) = backup_keys.decryption_key {
1042            if let Some(backup_version) = backup_keys.backup_version {
1043                Some(BackupSecrets::MegolmBackupV1Curve25519AesSha2(
1044                    MegolmBackupV1Curve25519AesSha2Secrets { key, backup_version },
1045                ))
1046            } else {
1047                return Err(SecretsBundleExportError::MissingBackupVersion);
1048            }
1049        } else {
1050            None
1051        };
1052
1053        Ok(SecretsBundle {
1054            cross_signing: CrossSigningSecrets { master_key, user_signing_key, self_signing_key },
1055            backup,
1056        })
1057    }
1058
1059    /// Import and persists secrets from a [`SecretsBundle`].
1060    ///
1061    /// This method will import all the private cross-signing keys and, if
1062    /// available, the private part of a backup key and its accompanying
1063    /// version into the store.
1064    ///
1065    /// **Warning**: Only import this from a trusted source, i.e. if an existing
1066    /// device is sharing this with a new device. The imported cross-signing
1067    /// keys will create a [`OwnUserIdentity`] and mark it as verified.
1068    ///
1069    /// The backup key will be persisted in the store and can be enabled using
1070    /// the [`BackupMachine`].
1071    pub async fn import_secrets_bundle(
1072        &self,
1073        bundle: &SecretsBundle,
1074    ) -> Result<(), SecretImportError> {
1075        let mut changes = Changes::default();
1076
1077        if let Some(backup_bundle) = &bundle.backup {
1078            match backup_bundle {
1079                BackupSecrets::MegolmBackupV1Curve25519AesSha2(bundle) => {
1080                    changes.backup_decryption_key = Some(bundle.key.clone());
1081                    changes.backup_version = Some(bundle.backup_version.clone());
1082                }
1083            }
1084        }
1085
1086        let identity = self.inner.identity.lock().await;
1087
1088        identity
1089            .import_secrets_unchecked(
1090                Some(&bundle.cross_signing.master_key),
1091                Some(&bundle.cross_signing.self_signing_key),
1092                Some(&bundle.cross_signing.user_signing_key),
1093            )
1094            .await?;
1095
1096        let public_identity = identity.to_public_identity().await.expect(
1097            "We should be able to create a new public identity since we just imported \
1098             all the private cross-signing keys",
1099        );
1100
1101        changes.private_identity = Some(identity.clone());
1102        changes.identities.new.push(UserIdentityData::Own(public_identity));
1103
1104        Ok(self.save_changes(changes).await?)
1105    }
1106
1107    /// Import the given `secret` named `secret_name` into the keystore.
1108    pub async fn import_secret(&self, secret: &GossippedSecret) -> Result<(), SecretImportError> {
1109        match &secret.secret_name {
1110            SecretName::CrossSigningMasterKey
1111            | SecretName::CrossSigningUserSigningKey
1112            | SecretName::CrossSigningSelfSigningKey => {
1113                if let Some(public_identity) =
1114                    self.get_identity(self.user_id()).await?.and_then(|i| i.own())
1115                {
1116                    let identity = self.inner.identity.lock().await;
1117
1118                    identity
1119                        .import_secret(
1120                            public_identity,
1121                            &secret.secret_name,
1122                            &secret.event.content.secret,
1123                        )
1124                        .await?;
1125                    info!(
1126                        secret_name = ?secret.secret_name,
1127                        "Successfully imported a private cross signing key"
1128                    );
1129
1130                    let changes =
1131                        Changes { private_identity: Some(identity.clone()), ..Default::default() };
1132
1133                    self.save_changes(changes).await?;
1134                }
1135            }
1136            SecretName::RecoveryKey => {
1137                // We don't import the decryption key here since we'll want to
1138                // check if the public key matches to the latest version on the
1139                // server. We instead put the secret into a secret inbox where
1140                // it will stay until it either gets overwritten
1141                // or the user accepts the secret.
1142            }
1143            name => {
1144                warn!(secret = ?name, "Tried to import an unknown secret");
1145            }
1146        }
1147
1148        Ok(())
1149    }
1150
1151    /// Check whether there is a global flag to only encrypt messages for
1152    /// trusted devices or for everyone.
1153    pub async fn get_only_allow_trusted_devices(&self) -> Result<bool> {
1154        let value = self.get_value("only_allow_trusted_devices").await?.unwrap_or_default();
1155        Ok(value)
1156    }
1157
1158    /// Set global flag whether to encrypt messages for untrusted devices, or
1159    /// whether they should be excluded from the conversation.
1160    pub async fn set_only_allow_trusted_devices(
1161        &self,
1162        block_untrusted_devices: bool,
1163    ) -> Result<()> {
1164        self.set_value("only_allow_trusted_devices", &block_untrusted_devices).await
1165    }
1166
1167    /// Get custom stored value associated with a key
1168    pub async fn get_value<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
1169        let Some(value) = self.get_custom_value(key).await? else {
1170            return Ok(None);
1171        };
1172        let deserialized = self.deserialize_value(&value)?;
1173        Ok(Some(deserialized))
1174    }
1175
1176    /// Store custom value associated with a key
1177    pub async fn set_value(&self, key: &str, value: &impl Serialize) -> Result<()> {
1178        let serialized = self.serialize_value(value)?;
1179        self.set_custom_value(key, serialized).await?;
1180        Ok(())
1181    }
1182
1183    fn serialize_value(&self, value: &impl Serialize) -> Result<Vec<u8>> {
1184        let serialized =
1185            rmp_serde::to_vec_named(value).map_err(|x| CryptoStoreError::Backend(x.into()))?;
1186        Ok(serialized)
1187    }
1188
1189    fn deserialize_value<T: DeserializeOwned>(&self, value: &[u8]) -> Result<T> {
1190        let deserialized =
1191            rmp_serde::from_slice(value).map_err(|e| CryptoStoreError::Backend(e.into()))?;
1192        Ok(deserialized)
1193    }
1194
1195    /// Receive notifications of room keys being received as a [`Stream`].
1196    ///
1197    /// Each time a room key is updated in any way, an update will be sent to
1198    /// the stream. Updates that happen at the same time are batched into a
1199    /// [`Vec`].
1200    ///
1201    /// If the reader of the stream lags too far behind an error will be sent to
1202    /// the reader.
1203    ///
1204    /// The stream will terminate once all references to the underlying
1205    /// `CryptoStoreWrapper` are dropped.
1206    pub fn room_keys_received_stream(
1207        &self,
1208    ) -> impl Stream<Item = Result<Vec<RoomKeyInfo>, BroadcastStreamRecvError>> + use<> {
1209        self.inner.store.room_keys_received_stream()
1210    }
1211
1212    /// Receive notifications of received `m.room_key.withheld` messages.
1213    ///
1214    /// Each time an `m.room_key.withheld` is received and stored, an update
1215    /// will be sent to the stream. Updates that happen at the same time are
1216    /// batched into a [`Vec`].
1217    ///
1218    /// If the reader of the stream lags too far behind, a warning will be
1219    /// logged and items will be dropped.
1220    pub fn room_keys_withheld_received_stream(
1221        &self,
1222    ) -> impl Stream<Item = Vec<RoomKeyWithheldInfo>> + use<> {
1223        self.inner.store.room_keys_withheld_received_stream()
1224    }
1225
1226    /// Returns a stream of user identity updates, allowing users to listen for
1227    /// notifications about new or changed user identities.
1228    ///
1229    /// The stream produced by this method emits updates whenever a new user
1230    /// identity is discovered or when an existing identities information is
1231    /// changed. Users can subscribe to this stream and receive updates in
1232    /// real-time.
1233    ///
1234    /// Caution: the returned stream will never terminate, and it holds a
1235    /// reference to the [`CryptoStore`]. Listeners should be careful to avoid
1236    /// resource leaks.
1237    ///
1238    /// # Examples
1239    ///
1240    /// ```no_run
1241    /// # use matrix_sdk_crypto::OlmMachine;
1242    /// # use ruma::{device_id, user_id};
1243    /// # use futures_util::{pin_mut, StreamExt};
1244    /// # let machine: OlmMachine = unimplemented!();
1245    /// # futures_executor::block_on(async {
1246    /// let identities_stream = machine.store().user_identities_stream();
1247    /// pin_mut!(identities_stream);
1248    ///
1249    /// for identity_updates in identities_stream.next().await {
1250    ///     for (_, identity) in identity_updates.new {
1251    ///         println!("A new identity has been added {}", identity.user_id());
1252    ///     }
1253    /// }
1254    /// # });
1255    /// ```
1256    pub fn user_identities_stream(&self) -> impl Stream<Item = IdentityUpdates> + use<> {
1257        let verification_machine = self.inner.verification_machine.to_owned();
1258
1259        let this = self.clone();
1260        self.inner.store.identities_stream().map(move |(own_identity, identities, _)| {
1261            let (new_identities, changed_identities, unchanged_identities) = identities.into_maps();
1262
1263            let map_identity = |(user_id, identity)| {
1264                (
1265                    user_id,
1266                    UserIdentity::new(
1267                        this.clone(),
1268                        identity,
1269                        verification_machine.to_owned(),
1270                        own_identity.to_owned(),
1271                    ),
1272                )
1273            };
1274
1275            let new = new_identities.into_iter().map(map_identity).collect();
1276            let changed = changed_identities.into_iter().map(map_identity).collect();
1277            let unchanged = unchanged_identities.into_iter().map(map_identity).collect();
1278
1279            IdentityUpdates { new, changed, unchanged }
1280        })
1281    }
1282
1283    /// Returns a stream of device updates, allowing users to listen for
1284    /// notifications about new or changed devices.
1285    ///
1286    /// The stream produced by this method emits updates whenever a new device
1287    /// is discovered or when an existing device's information is changed. Users
1288    /// can subscribe to this stream and receive updates in real-time.
1289    ///
1290    /// Caution: the returned stream will never terminate, and it holds a
1291    /// reference to the [`CryptoStore`]. Listeners should be careful to avoid
1292    /// resource leaks.
1293    ///
1294    /// # Examples
1295    ///
1296    /// ```no_run
1297    /// # use matrix_sdk_crypto::OlmMachine;
1298    /// # use ruma::{device_id, user_id};
1299    /// # use futures_util::{pin_mut, StreamExt};
1300    /// # let machine: OlmMachine = unimplemented!();
1301    /// # futures_executor::block_on(async {
1302    /// let devices_stream = machine.store().devices_stream();
1303    /// pin_mut!(devices_stream);
1304    ///
1305    /// for device_updates in devices_stream.next().await {
1306    ///     if let Some(user_devices) = device_updates.new.get(machine.user_id()) {
1307    ///         for device in user_devices.values() {
1308    ///             println!("A new device has been added {}", device.device_id());
1309    ///         }
1310    ///     }
1311    /// }
1312    /// # });
1313    /// ```
1314    pub fn devices_stream(&self) -> impl Stream<Item = DeviceUpdates> + use<> {
1315        let verification_machine = self.inner.verification_machine.to_owned();
1316
1317        self.inner.store.identities_stream().map(move |(own_identity, identities, devices)| {
1318            collect_device_updates(
1319                verification_machine.to_owned(),
1320                own_identity,
1321                identities,
1322                devices,
1323            )
1324        })
1325    }
1326
1327    /// Returns a [`Stream`] of user identity and device updates
1328    ///
1329    /// The stream returned by this method returns the same data as
1330    /// [`Store::user_identities_stream`] and [`Store::devices_stream`] but does
1331    /// not include references to the `VerificationMachine`. It is therefore a
1332    /// lower-level view on that data.
1333    ///
1334    /// The stream will terminate once all references to the underlying
1335    /// `CryptoStoreWrapper` are dropped.
1336    pub fn identities_stream_raw(
1337        &self,
1338    ) -> impl Stream<Item = (IdentityChanges, DeviceChanges)> + use<> {
1339        self.inner.store.identities_stream().map(|(_, identities, devices)| (identities, devices))
1340    }
1341
1342    /// Creates a [`CrossProcessLock`] for this store, that will contain the
1343    /// given key and value when hold.
1344    pub fn create_store_lock(
1345        &self,
1346        lock_key: String,
1347        lock_value: String,
1348    ) -> CrossProcessLock<LockableCryptoStore> {
1349        self.inner.store.create_store_lock(lock_key, lock_value)
1350    }
1351
1352    /// Receive notifications of gossipped secrets being received and stored in
1353    /// the secret inbox as a [`Stream`].
1354    ///
1355    /// The gossipped secrets are received using the `m.secret.send` event type
1356    /// and are guaranteed to have been received over a 1-to-1 Olm
1357    /// [`Session`] from a verified [`Device`].
1358    ///
1359    /// The [`GossippedSecret`] can also be later found in the secret inbox and
1360    /// retrieved using the [`CryptoStore::get_secrets_from_inbox()`] method.
1361    ///
1362    /// After a suitable secret of a certain type has been found it can be
1363    /// removed from the store
1364    /// using the [`CryptoStore::delete_secrets_from_inbox()`] method.
1365    ///
1366    /// The only secret this will currently broadcast is the
1367    /// `m.megolm_backup.v1`.
1368    ///
1369    /// If the reader of the stream lags too far behind, a warning will be
1370    /// logged and items will be dropped.
1371    ///
1372    /// # Examples
1373    ///
1374    /// ```no_run
1375    /// # use matrix_sdk_crypto::OlmMachine;
1376    /// # use ruma::{device_id, user_id};
1377    /// # use futures_util::{pin_mut, StreamExt};
1378    /// # let alice = user_id!("@alice:example.org").to_owned();
1379    /// # futures_executor::block_on(async {
1380    /// # let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
1381    ///
1382    /// let secret_stream = machine.store().secrets_stream();
1383    /// pin_mut!(secret_stream);
1384    ///
1385    /// for secret in secret_stream.next().await {
1386    ///     // Accept the secret if it's valid, then delete all the secrets of this type.
1387    ///     machine.store().delete_secrets_from_inbox(&secret.secret_name);
1388    /// }
1389    /// # });
1390    /// ```
1391    pub fn secrets_stream(&self) -> impl Stream<Item = GossippedSecret> + use<> {
1392        self.inner.store.secrets_stream()
1393    }
1394
1395    /// Receive notifications of historic room key bundles as a [`Stream`].
1396    ///
1397    /// Historic room key bundles are defined in [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268).
1398    ///
1399    /// Each time a historic room key bundle was received, an update will be
1400    /// sent to the stream. This stream can be used to accept historic room key
1401    /// bundles that arrive out of order, i.e. the bundle arrives after the
1402    /// user has already accepted a room invitation.
1403    ///
1404    /// # Examples
1405    ///
1406    /// ```no_run
1407    /// # use matrix_sdk_crypto::{
1408    /// #    OlmMachine,
1409    /// #    store::types::StoredRoomKeyBundleData,
1410    /// #    types::room_history::RoomKeyBundle
1411    /// # };
1412    /// # use ruma::{device_id, user_id};
1413    /// # use futures_util::{pin_mut, StreamExt};
1414    /// # let alice = user_id!("@alice:example.org").to_owned();
1415    /// # async {
1416    /// # let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
1417    /// let bundle_stream = machine.store().historic_room_key_stream();
1418    /// pin_mut!(bundle_stream);
1419    ///
1420    /// while let Some(bundle_info) = bundle_stream.next().await {
1421    ///     // Try to find the bundle content in the store and if it's valid accept it.
1422    ///     if let Some(bundle_data) = machine.store().get_received_room_key_bundle_data(&bundle_info.room_id, &bundle_info.sender).await? {
1423    ///         // Download the bundle now and import it.
1424    ///         let bundle: RoomKeyBundle = todo!("Download the bundle");
1425    ///         machine.store().receive_room_key_bundle(
1426    ///             &bundle_data,
1427    ///             bundle,
1428    ///             |_, _| {},
1429    ///         ).await?;
1430    ///     }
1431    /// }
1432    /// # anyhow::Ok(()) };
1433    /// ```
1434    pub fn historic_room_key_stream(&self) -> impl Stream<Item = RoomKeyBundleInfo> + use<> {
1435        self.inner.store.historic_room_key_stream()
1436    }
1437
1438    /// Import the given room keys into the store.
1439    ///
1440    /// # Arguments
1441    ///
1442    /// * `exported_keys` - The keys to be imported.
1443    /// * `from_backup_version` - If the keys came from key backup, the key
1444    ///   backup version. This will cause the keys to be marked as already
1445    ///   backed up, and therefore not requiring another backup.
1446    /// * `progress_listener` - Callback which will be called after each key is
1447    ///   processed. Called with arguments `(processed, total)` where
1448    ///   `processed` is the number of keys processed so far, and `total` is the
1449    ///   total number of keys (i.e., `exported_keys.len()`).
1450    pub async fn import_room_keys(
1451        &self,
1452        exported_keys: Vec<ExportedRoomKey>,
1453        from_backup_version: Option<&str>,
1454        progress_listener: impl Fn(usize, usize),
1455    ) -> Result<RoomKeyImportResult> {
1456        let exported_keys: Vec<&ExportedRoomKey> = exported_keys.iter().collect();
1457        self.import_sessions_impl(exported_keys, from_backup_version, progress_listener).await
1458    }
1459
1460    /// Import the given room keys into our store.
1461    ///
1462    /// # Arguments
1463    ///
1464    /// * `exported_keys` - A list of previously exported keys that should be
1465    ///   imported into our store. If we already have a better version of a key
1466    ///   the key will *not* be imported.
1467    ///
1468    /// Returns a tuple of numbers that represent the number of sessions that
1469    /// were imported and the total number of sessions that were found in the
1470    /// key export.
1471    ///
1472    /// # Examples
1473    ///
1474    /// ```no_run
1475    /// # use std::io::Cursor;
1476    /// # use matrix_sdk_crypto::{OlmMachine, decrypt_room_key_export};
1477    /// # use ruma::{device_id, user_id};
1478    /// # let alice = user_id!("@alice:example.org");
1479    /// # async {
1480    /// # let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
1481    /// # let export = Cursor::new("".to_owned());
1482    /// let exported_keys = decrypt_room_key_export(export, "1234").unwrap();
1483    /// machine.store().import_exported_room_keys(exported_keys, |_, _| {}).await.unwrap();
1484    /// # };
1485    /// ```
1486    pub async fn import_exported_room_keys(
1487        &self,
1488        exported_keys: Vec<ExportedRoomKey>,
1489        progress_listener: impl Fn(usize, usize),
1490    ) -> Result<RoomKeyImportResult> {
1491        self.import_room_keys(exported_keys, None, progress_listener).await
1492    }
1493
1494    async fn import_sessions_impl<T>(
1495        &self,
1496        room_keys: Vec<T>,
1497        from_backup_version: Option<&str>,
1498        progress_listener: impl Fn(usize, usize),
1499    ) -> Result<RoomKeyImportResult>
1500    where
1501        T: TryInto<InboundGroupSession> + RoomKeyExport + Copy,
1502        T::Error: Debug,
1503    {
1504        let mut sessions = Vec::new();
1505
1506        let total_count = room_keys.len();
1507        let mut keys = BTreeMap::new();
1508
1509        for (i, key) in room_keys.into_iter().enumerate() {
1510            match key.try_into() {
1511                Ok(session) => {
1512                    // Only import the session if we didn't have this session or
1513                    // if it's a better version of the same session.
1514                    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                        sessions.push(merged);
1526                    }
1527                }
1528                Err(e) => {
1529                    warn!(
1530                        sender_key = key.sender_key().to_base64(),
1531                        room_id = ?key.room_id(),
1532                        session_id = key.session_id(),
1533                        error = ?e,
1534                        "Couldn't import a room key from a file export."
1535                    );
1536                }
1537            }
1538
1539            progress_listener(i, total_count);
1540        }
1541
1542        let imported_count = sessions.len();
1543
1544        self.inner.store.save_inbound_group_sessions(sessions, from_backup_version).await?;
1545
1546        info!(total_count, imported_count, room_keys = ?keys, "Successfully imported room keys");
1547
1548        Ok(RoomKeyImportResult::new(imported_count, total_count, keys))
1549    }
1550
1551    pub(crate) fn crypto_store(&self) -> Arc<CryptoStoreWrapper> {
1552        self.inner.store.clone()
1553    }
1554
1555    /// Export the keys that match the given predicate.
1556    ///
1557    /// # Arguments
1558    ///
1559    /// * `predicate` - A closure that will be called for every known
1560    ///   `InboundGroupSession`, which represents a room key. If the closure
1561    ///   returns `true` the `InboundGroupSession` will be included in the
1562    ///   export, if the closure returns `false` it will not be included.
1563    ///
1564    /// # Examples
1565    ///
1566    /// ```no_run
1567    /// # use matrix_sdk_crypto::{OlmMachine, encrypt_room_key_export};
1568    /// # use ruma::{device_id, user_id, room_id};
1569    /// # let alice = user_id!("@alice:example.org");
1570    /// # async {
1571    /// # let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
1572    /// let room_id = room_id!("!test:localhost");
1573    /// let exported_keys = machine.store().export_room_keys(|s| s.room_id() == room_id).await.unwrap();
1574    /// let encrypted_export = encrypt_room_key_export(&exported_keys, "1234", 1);
1575    /// # };
1576    /// ```
1577    pub async fn export_room_keys(
1578        &self,
1579        predicate: impl FnMut(&InboundGroupSession) -> bool,
1580    ) -> Result<Vec<ExportedRoomKey>> {
1581        let mut exported = Vec::new();
1582
1583        let mut sessions = self.get_inbound_group_sessions().await?;
1584        sessions.retain(predicate);
1585
1586        for session in sessions {
1587            let export = session.export().await;
1588            exported.push(export);
1589        }
1590
1591        Ok(exported)
1592    }
1593
1594    /// Export room keys matching a predicate, providing them as an async
1595    /// `Stream`.
1596    ///
1597    /// # Arguments
1598    ///
1599    /// * `predicate` - A closure that will be called for every known
1600    ///   `InboundGroupSession`, which represents a room key. If the closure
1601    ///   returns `true` the `InboundGroupSession` will be included in the
1602    ///   export, if the closure returns `false` it will not be included.
1603    ///
1604    /// # Examples
1605    ///
1606    /// ```no_run
1607    /// use std::pin::pin;
1608    ///
1609    /// use matrix_sdk_crypto::{olm::ExportedRoomKey, OlmMachine};
1610    /// use ruma::{device_id, room_id, user_id};
1611    /// use tokio_stream::StreamExt;
1612    /// # async {
1613    /// let alice = user_id!("@alice:example.org");
1614    /// let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await;
1615    /// let room_id = room_id!("!test:localhost");
1616    /// let mut keys = pin!(machine
1617    ///     .store()
1618    ///     .export_room_keys_stream(|s| s.room_id() == room_id)
1619    ///     .await
1620    ///     .unwrap());
1621    /// while let Some(key) = keys.next().await {
1622    ///     println!("{}", key.room_id);
1623    /// }
1624    /// # };
1625    /// ```
1626    pub async fn export_room_keys_stream(
1627        &self,
1628        predicate: impl FnMut(&InboundGroupSession) -> bool,
1629    ) -> Result<impl Stream<Item = ExportedRoomKey>> {
1630        // TODO: if/when there is a get_inbound_group_sessions_stream, use that here.
1631        let sessions = self.get_inbound_group_sessions().await?;
1632        Ok(futures_util::stream::iter(sessions.into_iter().filter(predicate))
1633            .then(|session| async move { session.export().await }))
1634    }
1635
1636    /// Assemble a room key bundle for sharing encrypted history, as per
1637    /// [MSC4268].
1638    ///
1639    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
1640    pub async fn build_room_key_bundle(
1641        &self,
1642        room_id: &RoomId,
1643    ) -> std::result::Result<RoomKeyBundle, CryptoStoreError> {
1644        let sessions = self.get_inbound_group_sessions_by_room_id(room_id).await?;
1645
1646        let mut bundle = RoomKeyBundle::default();
1647        for session in sessions {
1648            if session.shared_history() {
1649                bundle.room_keys.push(session.export().await.into());
1650            } else {
1651                bundle.withheld.push(RoomKeyWithheldContent::new(
1652                    session.algorithm().to_owned(),
1653                    WithheldCode::HistoryNotShared,
1654                    session.room_id().to_owned(),
1655                    session.session_id().to_owned(),
1656                    session.sender_key().to_owned(),
1657                    self.device_id().to_owned(),
1658                ));
1659            }
1660        }
1661
1662        // If we received a key bundle ourselves, in which one or more sessions was
1663        // marked as "history not shared", pass that on to the new user.
1664        let withhelds = self.get_withheld_sessions_by_room_id(room_id).await?;
1665        for withheld in withhelds {
1666            if withheld.content.withheld_code() == WithheldCode::HistoryNotShared {
1667                bundle.withheld.push(withheld.content);
1668            }
1669        }
1670
1671        Ok(bundle)
1672    }
1673
1674    /// Import the contents of a downloaded and decrypted [MSC4268] key bundle.
1675    ///
1676    /// # Arguments
1677    ///
1678    /// * `bundle_info` - The [`StoredRoomKeyBundleData`] of the bundle that is
1679    ///   being received.
1680    /// * `bundle` - The decrypted and deserialized bundle itself.
1681    ///
1682    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
1683    #[instrument(skip(self, bundle, progress_listener), fields(bundle_size = bundle.room_keys.len(), sender_data))]
1684    pub async fn receive_room_key_bundle(
1685        &self,
1686        bundle_info: &StoredRoomKeyBundleData,
1687        bundle: RoomKeyBundle,
1688        progress_listener: impl Fn(usize, usize),
1689    ) -> Result<(), CryptoStoreError> {
1690        let sender_data = if bundle_info.sender_data.should_recalculate() {
1691            let device = self
1692                .get_device_from_curve_key(&bundle_info.sender_user, bundle_info.sender_key)
1693                .await?;
1694
1695            device
1696                .as_ref()
1697                .map(SenderData::from_device)
1698                .unwrap_or_else(|| bundle_info.sender_data.clone())
1699        } else {
1700            bundle_info.sender_data.clone()
1701        };
1702
1703        tracing::Span::current().record("sender_data", tracing::field::debug(&sender_data));
1704
1705        if matches!(
1706            &sender_data,
1707            SenderData::UnknownDevice { .. }
1708                | SenderData::VerificationViolation(_)
1709                | SenderData::DeviceInfo { .. }
1710        ) {
1711            warn!(
1712                "Not accepting a historic room key bundle due to insufficient trust in the sender"
1713            );
1714            return Ok(());
1715        }
1716
1717        self.import_room_key_bundle_sessions(bundle_info, &bundle, progress_listener).await?;
1718        self.import_room_key_bundle_withheld_info(bundle_info, &bundle).await?;
1719
1720        Ok(())
1721    }
1722
1723    async fn import_room_key_bundle_sessions(
1724        &self,
1725        bundle_info: &StoredRoomKeyBundleData,
1726        bundle: &RoomKeyBundle,
1727        progress_listener: impl Fn(usize, usize),
1728    ) -> Result<(), CryptoStoreError> {
1729        let (good, bad): (Vec<_>, Vec<_>) = bundle.room_keys.iter().partition_map(|key| {
1730            if key.room_id != bundle_info.bundle_data.room_id {
1731                trace!("Ignoring key for incorrect room {} in bundle", key.room_id);
1732                Either::Right(key)
1733            } else {
1734                Either::Left(key)
1735            }
1736        });
1737
1738        match (bad.is_empty(), good.is_empty()) {
1739            // Case 1: Completely empty bundle.
1740            (true, true) => {
1741                warn!("Received a completely empty room key bundle");
1742            }
1743
1744            // Case 2: A bundle for the wrong room.
1745            (false, true) => {
1746                let bad_keys: Vec<_> =
1747                    bad.iter().map(|&key| (&key.room_id, &key.session_id)).collect();
1748
1749                warn!(
1750                    ?bad_keys,
1751                    "Received a room key bundle for the wrong room, ignoring all room keys from the bundle"
1752                );
1753            }
1754
1755            // Case 3: A bundle containing useful room keys.
1756            (_, false) => {
1757                // We have at least some good keys, if we also have some bad ones let's
1758                // mention that here.
1759                if !bad.is_empty() {
1760                    warn!(
1761                        bad_key_count = bad.len(),
1762                        "The room key bundle contained some room keys \
1763                         that were meant for a different room"
1764                    );
1765                }
1766
1767                self.import_sessions_impl(good, None, progress_listener).await?;
1768            }
1769        }
1770
1771        Ok(())
1772    }
1773
1774    async fn import_room_key_bundle_withheld_info(
1775        &self,
1776        bundle_info: &StoredRoomKeyBundleData,
1777        bundle: &RoomKeyBundle,
1778    ) -> Result<(), CryptoStoreError> {
1779        let mut session_id_to_withheld_code_map = BTreeMap::new();
1780
1781        let mut changes = Changes::default();
1782        for withheld in &bundle.withheld {
1783            let (room_id, session_id) = match withheld {
1784                RoomKeyWithheldContent::MegolmV1AesSha2(c) => match (c.room_id(), c.session_id()) {
1785                    (Some(room_id), Some(session_id)) => (room_id, session_id),
1786                    _ => continue,
1787                },
1788                #[cfg(feature = "experimental-algorithms")]
1789                RoomKeyWithheldContent::MegolmV2AesSha2(c) => match (c.room_id(), c.session_id()) {
1790                    (Some(room_id), Some(session_id)) => (room_id, session_id),
1791                    _ => continue,
1792                },
1793                RoomKeyWithheldContent::Unknown(_) => continue,
1794            };
1795
1796            if room_id != bundle_info.bundle_data.room_id {
1797                trace!("Ignoring withheld info for incorrect room {} in bundle", room_id);
1798                continue;
1799            }
1800
1801            changes.withheld_session_info.entry(room_id.to_owned()).or_default().insert(
1802                session_id.to_owned(),
1803                RoomKeyWithheldEntry {
1804                    sender: bundle_info.sender_user.clone(),
1805                    content: withheld.to_owned(),
1806                },
1807            );
1808            session_id_to_withheld_code_map.insert(session_id, withheld.withheld_code());
1809        }
1810
1811        self.save_changes(changes).await?;
1812
1813        info!(
1814            room_id = ?bundle_info.bundle_data.room_id,
1815            ?session_id_to_withheld_code_map,
1816            "Successfully imported withheld info from room key bundle",
1817        );
1818
1819        Ok(())
1820    }
1821}
1822
1823impl Deref for Store {
1824    type Target = DynCryptoStore;
1825
1826    fn deref(&self) -> &Self::Target {
1827        self.inner.store.deref().deref()
1828    }
1829}
1830
1831/// A crypto store that implements primitives for cross-process locking.
1832#[derive(Clone, Debug)]
1833pub struct LockableCryptoStore(Arc<dyn CryptoStore<Error = CryptoStoreError>>);
1834
1835impl matrix_sdk_common::cross_process_lock::TryLock for LockableCryptoStore {
1836    type LockError = CryptoStoreError;
1837
1838    async fn try_lock(
1839        &self,
1840        lease_duration_ms: u32,
1841        key: &str,
1842        holder: &str,
1843    ) -> std::result::Result<Option<CrossProcessLockGeneration>, Self::LockError> {
1844        self.0.try_take_leased_lock(lease_duration_ms, key, holder).await
1845    }
1846}
1847
1848#[cfg(test)]
1849mod tests {
1850    use std::{collections::BTreeMap, pin::pin};
1851
1852    use assert_matches2::{assert_let, assert_matches};
1853    use futures_util::StreamExt;
1854    use insta::{_macro_support::Content, assert_json_snapshot, internals::ContentPath};
1855    use matrix_sdk_test::async_test;
1856    use ruma::{
1857        device_id,
1858        events::room::{EncryptedFileInit, JsonWebKeyInit},
1859        owned_device_id, owned_mxc_uri, room_id,
1860        serde::Base64,
1861        user_id, RoomId,
1862    };
1863    use serde_json::json;
1864    use vodozemac::{megolm::SessionKey, Ed25519Keypair};
1865
1866    use crate::{
1867        machine::test_helpers::get_machine_pair,
1868        olm::{InboundGroupSession, SenderData},
1869        store::types::{DehydratedDeviceKey, RoomKeyWithheldEntry, StoredRoomKeyBundleData},
1870        types::{
1871            events::{
1872                room_key_bundle::RoomKeyBundleContent,
1873                room_key_withheld::{MegolmV1AesSha2WithheldContent, RoomKeyWithheldContent},
1874            },
1875            EventEncryptionAlgorithm,
1876        },
1877        Account, OlmMachine,
1878    };
1879
1880    #[async_test]
1881    async fn test_merge_received_group_session() {
1882        let alice_account = Account::with_device_id(user_id!("@a:s.co"), device_id!("ABC"));
1883        let bob = OlmMachine::new(user_id!("@b:s.co"), device_id!("DEF")).await;
1884
1885        let room_id = room_id!("!test:localhost");
1886
1887        let megolm_signing_key = Ed25519Keypair::new();
1888        let inbound = make_inbound_group_session(&alice_account, &megolm_signing_key, room_id);
1889
1890        // Bob already knows about the session, at index 5, with the device keys.
1891        let mut inbound_at_index_5 =
1892            InboundGroupSession::from_export(&inbound.export_at_index(5).await).unwrap();
1893        inbound_at_index_5.sender_data = inbound.sender_data.clone();
1894        bob.store().save_inbound_group_sessions(&[inbound_at_index_5.clone()]).await.unwrap();
1895
1896        // No changes if we get a disconnected session.
1897        let disconnected = make_inbound_group_session(&alice_account, &megolm_signing_key, room_id);
1898        assert_eq!(bob.store().merge_received_group_session(disconnected).await.unwrap(), None);
1899
1900        // No changes needed when we receive a worse copy of the session
1901        let mut worse =
1902            InboundGroupSession::from_export(&inbound.export_at_index(10).await).unwrap();
1903        worse.sender_data = inbound.sender_data.clone();
1904        assert_eq!(bob.store().merge_received_group_session(worse).await.unwrap(), None);
1905
1906        // Nor when we receive an exact copy of what we already have
1907        let mut copy = InboundGroupSession::from_pickle(inbound_at_index_5.pickle().await).unwrap();
1908        copy.sender_data = inbound.sender_data.clone();
1909        assert_eq!(bob.store().merge_received_group_session(copy).await.unwrap(), None);
1910
1911        // But when we receive a better copy of the session, we should get it back
1912        let mut better =
1913            InboundGroupSession::from_export(&inbound.export_at_index(0).await).unwrap();
1914        better.sender_data = inbound.sender_data.clone();
1915        assert_let!(Some(update) = bob.store().merge_received_group_session(better).await.unwrap());
1916        assert_eq!(update.first_known_index(), 0);
1917
1918        // A worse copy of the ratchet, but better trust data
1919        {
1920            let mut worse_ratchet_better_trust =
1921                InboundGroupSession::from_export(&inbound.export_at_index(10).await).unwrap();
1922            let updated_sender_data = SenderData::sender_verified(
1923                alice_account.user_id(),
1924                alice_account.device_id(),
1925                Ed25519Keypair::new().public_key(),
1926            );
1927            worse_ratchet_better_trust.sender_data = updated_sender_data.clone();
1928            assert_let!(
1929                Some(update) = bob
1930                    .store()
1931                    .merge_received_group_session(worse_ratchet_better_trust)
1932                    .await
1933                    .unwrap()
1934            );
1935            assert_eq!(update.sender_data, updated_sender_data);
1936            assert_eq!(update.first_known_index(), 5);
1937            assert_eq!(
1938                update.export_at_index(0).await.session_key.to_bytes(),
1939                inbound.export_at_index(5).await.session_key.to_bytes()
1940            );
1941        }
1942
1943        // A better copy of the ratchet, but worse trust data
1944        {
1945            let mut better_ratchet_worse_trust =
1946                InboundGroupSession::from_export(&inbound.export_at_index(0).await).unwrap();
1947            let updated_sender_data = SenderData::unknown();
1948            better_ratchet_worse_trust.sender_data = updated_sender_data.clone();
1949            assert_let!(
1950                Some(update) = bob
1951                    .store()
1952                    .merge_received_group_session(better_ratchet_worse_trust)
1953                    .await
1954                    .unwrap()
1955            );
1956            assert_eq!(update.sender_data, inbound.sender_data);
1957            assert_eq!(update.first_known_index(), 0);
1958            assert_eq!(
1959                update.export_at_index(0).await.session_key.to_bytes(),
1960                inbound.export_at_index(0).await.session_key.to_bytes()
1961            );
1962        }
1963    }
1964
1965    /// Create an [`InboundGroupSession`] for the given room, using the given
1966    /// Ed25519 key as the signing key/session ID.
1967    fn make_inbound_group_session(
1968        sender_account: &Account,
1969        signing_key: &Ed25519Keypair,
1970        room_id: &RoomId,
1971    ) -> InboundGroupSession {
1972        InboundGroupSession::new(
1973            sender_account.identity_keys.curve25519,
1974            sender_account.identity_keys.ed25519,
1975            room_id,
1976            &make_session_key(signing_key),
1977            SenderData::device_info(crate::types::DeviceKeys::new(
1978                sender_account.user_id().to_owned(),
1979                sender_account.device_id().to_owned(),
1980                vec![],
1981                BTreeMap::new(),
1982                crate::types::Signatures::new(),
1983            )),
1984            EventEncryptionAlgorithm::MegolmV1AesSha2,
1985            Some(ruma::events::room::history_visibility::HistoryVisibility::Shared),
1986            true,
1987        )
1988        .unwrap()
1989    }
1990
1991    /// Make a Megolm [`SessionKey`] using the given Ed25519 key as a signing
1992    /// key/session ID.
1993    fn make_session_key(signing_key: &Ed25519Keypair) -> SessionKey {
1994        use rand::Rng;
1995
1996        // `SessionKey::new` is not public, so the easiest way to construct a Megolm
1997        // session using a known Ed25519 key is to build a byte array in the export
1998        // format.
1999
2000        let mut session_key_bytes = vec![0u8; 229];
2001        // 0: version
2002        session_key_bytes[0] = 2;
2003        // 1..5: index
2004        // 5..133: ratchet key
2005        rand::thread_rng().fill(&mut session_key_bytes[5..133]);
2006        // 133..165: public ed25519 key
2007        session_key_bytes[133..165].copy_from_slice(signing_key.public_key().as_bytes());
2008        // 165..229: signature
2009        let sig = signing_key.sign(&session_key_bytes[0..165]);
2010        session_key_bytes[165..229].copy_from_slice(&sig.to_bytes());
2011
2012        SessionKey::from_bytes(&session_key_bytes).unwrap()
2013    }
2014
2015    #[async_test]
2016    async fn test_import_room_keys_notifies_stream() {
2017        use futures_util::FutureExt;
2018
2019        let (alice, bob, _) =
2020            get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2021
2022        let room1_id = room_id!("!room1:localhost");
2023        alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2024        let exported_sessions = alice.store().export_room_keys(|_| true).await.unwrap();
2025
2026        let mut room_keys_received_stream = Box::pin(bob.store().room_keys_received_stream());
2027        bob.store().import_room_keys(exported_sessions, None, |_, _| {}).await.unwrap();
2028
2029        let room_keys = room_keys_received_stream
2030            .next()
2031            .now_or_never()
2032            .flatten()
2033            .expect("We should have received an update of room key infos")
2034            .unwrap();
2035        assert_eq!(room_keys.len(), 1);
2036        assert_eq!(room_keys[0].room_id, "!room1:localhost");
2037    }
2038
2039    #[async_test]
2040    async fn test_export_room_keys_provides_selected_keys() {
2041        // Given an OlmMachine with room keys in it
2042        let (alice, _, _) = get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2043        let room1_id = room_id!("!room1:localhost");
2044        let room2_id = room_id!("!room2:localhost");
2045        let room3_id = room_id!("!room3:localhost");
2046        alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2047        alice.create_outbound_group_session_with_defaults_test_helper(room2_id).await.unwrap();
2048        alice.create_outbound_group_session_with_defaults_test_helper(room3_id).await.unwrap();
2049
2050        // When I export some of the keys
2051        let keys = alice
2052            .store()
2053            .export_room_keys(|s| s.room_id() == room2_id || s.room_id() == room3_id)
2054            .await
2055            .unwrap();
2056
2057        // Then the requested keys were provided
2058        assert_eq!(keys.len(), 2);
2059        assert_eq!(keys[0].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2060        assert_eq!(keys[1].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2061        assert_eq!(keys[0].room_id, "!room2:localhost");
2062        assert_eq!(keys[1].room_id, "!room3:localhost");
2063        assert_eq!(keys[0].session_key.to_base64().len(), 220);
2064        assert_eq!(keys[1].session_key.to_base64().len(), 220);
2065    }
2066
2067    #[async_test]
2068    async fn test_export_room_keys_stream_can_provide_all_keys() {
2069        // Given an OlmMachine with room keys in it
2070        let (alice, _, _) = get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2071        let room1_id = room_id!("!room1:localhost");
2072        let room2_id = room_id!("!room2:localhost");
2073        alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2074        alice.create_outbound_group_session_with_defaults_test_helper(room2_id).await.unwrap();
2075
2076        // When I export the keys as a stream
2077        let mut keys = pin!(alice.store().export_room_keys_stream(|_| true).await.unwrap());
2078
2079        // And collect them
2080        let mut collected = vec![];
2081        while let Some(key) = keys.next().await {
2082            collected.push(key);
2083        }
2084
2085        // Then all the keys were provided
2086        assert_eq!(collected.len(), 2);
2087        assert_eq!(collected[0].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2088        assert_eq!(collected[1].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2089        assert_eq!(collected[0].room_id, "!room1:localhost");
2090        assert_eq!(collected[1].room_id, "!room2:localhost");
2091        assert_eq!(collected[0].session_key.to_base64().len(), 220);
2092        assert_eq!(collected[1].session_key.to_base64().len(), 220);
2093    }
2094
2095    #[async_test]
2096    async fn test_export_room_keys_stream_can_provide_a_subset_of_keys() {
2097        // Given an OlmMachine with room keys in it
2098        let (alice, _, _) = get_machine_pair(user_id!("@a:s.co"), user_id!("@b:s.co"), false).await;
2099        let room1_id = room_id!("!room1:localhost");
2100        let room2_id = room_id!("!room2:localhost");
2101        alice.create_outbound_group_session_with_defaults_test_helper(room1_id).await.unwrap();
2102        alice.create_outbound_group_session_with_defaults_test_helper(room2_id).await.unwrap();
2103
2104        // When I export the keys as a stream
2105        let mut keys =
2106            pin!(alice.store().export_room_keys_stream(|s| s.room_id() == room1_id).await.unwrap());
2107
2108        // And collect them
2109        let mut collected = vec![];
2110        while let Some(key) = keys.next().await {
2111            collected.push(key);
2112        }
2113
2114        // Then all the keys matching our predicate were provided, and no others
2115        assert_eq!(collected.len(), 1);
2116        assert_eq!(collected[0].algorithm, EventEncryptionAlgorithm::MegolmV1AesSha2);
2117        assert_eq!(collected[0].room_id, "!room1:localhost");
2118        assert_eq!(collected[0].session_key.to_base64().len(), 220);
2119    }
2120
2121    #[async_test]
2122    async fn test_export_secrets_bundle() {
2123        let user_id = user_id!("@alice:example.com");
2124        let (first, second, _) = get_machine_pair(user_id, user_id, false).await;
2125
2126        let _ = first
2127            .bootstrap_cross_signing(false)
2128            .await
2129            .expect("We should be able to bootstrap cross-signing");
2130
2131        let bundle = first.store().export_secrets_bundle().await.expect(
2132            "We should be able to export the secrets bundle, now that we \
2133             have the cross-signing keys",
2134        );
2135
2136        assert!(bundle.backup.is_none(), "The bundle should not contain a backup key");
2137
2138        second
2139            .store()
2140            .import_secrets_bundle(&bundle)
2141            .await
2142            .expect("We should be able to import the secrets bundle");
2143
2144        let status = second.cross_signing_status().await;
2145        let identity = second.get_identity(user_id, None).await.unwrap().unwrap().own().unwrap();
2146
2147        assert!(identity.is_verified(), "The public identity should be marked as verified.");
2148
2149        assert!(status.is_complete(), "We should have imported all the cross-signing keys");
2150    }
2151
2152    #[async_test]
2153    async fn test_create_dehydrated_device_key() {
2154        let pickle_key = DehydratedDeviceKey::new()
2155            .expect("Should be able to create a random dehydrated device key");
2156
2157        let to_vec = pickle_key.inner.to_vec();
2158        let pickle_key_from_slice = DehydratedDeviceKey::from_slice(to_vec.as_slice())
2159            .expect("Should be able to create a dehydrated device key from slice");
2160
2161        assert_eq!(pickle_key_from_slice.to_base64(), pickle_key.to_base64());
2162    }
2163
2164    #[async_test]
2165    async fn test_create_dehydrated_errors() {
2166        let too_small = [0u8; 22];
2167        let pickle_key = DehydratedDeviceKey::from_slice(&too_small);
2168
2169        assert!(pickle_key.is_err());
2170
2171        let too_big = [0u8; 40];
2172        let pickle_key = DehydratedDeviceKey::from_slice(&too_big);
2173
2174        assert!(pickle_key.is_err());
2175    }
2176
2177    #[async_test]
2178    async fn test_build_room_key_bundle() {
2179        // Given: Alice has sent a number of room keys to Bob, including some in the
2180        // wrong room, and some that are not marked as shared...
2181        let alice = OlmMachine::new(user_id!("@a:s.co"), device_id!("ALICE")).await;
2182        let bob = OlmMachine::new(user_id!("@b:s.co"), device_id!("BOB")).await;
2183
2184        let room1_id = room_id!("!room1:localhost");
2185        let room2_id = room_id!("!room2:localhost");
2186
2187        /* We use hardcoded megolm session data, to get a stable output snapshot. These were all created with:
2188
2189           println!("{}", vodozemac::megolm::GroupSession::new(Default::default()).session_key().to_base64());
2190        */
2191        let session_key1 = "AgAAAAC2XHVzsMBKs4QCRElJ92CJKyGtknCSC8HY7cQ7UYwndMKLQAejXLh5UA0l6s736mgctcUMNvELScUWrObdflrHo+vth/gWreXOaCnaSxmyjjKErQwyIYTkUfqbHy40RJfEesLwnN23on9XAkch/iy8R2+Jz7B8zfG01f2Ow2SxPQFnAndcO1ZSD2GmXgedy6n4B20MWI1jGP2wiexOWbFSya8DO/VxC9m5+/mF+WwYqdpKn9g4Y05Yw4uz7cdjTc3rXm7xK+8E7hI//5QD1nHPvuKYbjjM9u2JSL+Bzp61Cw";
2192        let session_key2 = "AgAAAAC1BXreFTUQQSBGekTEuYxhdytRKyv4JgDGcG+VOBYdPNGgs807SdibCGJky4lJ3I+7ZDGHoUzZPZP/4ogGu4kxni0PWdtWuN7+5zsuamgoFF/BkaGeUUGv6kgIkx8pyPpM5SASTUEP9bN2loDSpUPYwfiIqz74DgC4WQ4435sTBctYvKz8n+TDJwdLXpyT6zKljuqADAioud+s/iqx9LYn9HpbBfezZcvbg67GtE113pLrvde3IcPI5s6dNHK2onGO2B2eoaobcen18bbEDnlUGPeIivArLya7Da6us14jBQ";
2193        let session_key3 = "AgAAAAAM9KFsliaUUhGSXgwOzM5UemjkNH4n8NHgvC/y8hhw13zTF+ooGD4uIYEXYX630oNvQm/EvgZo+dkoc0re+vsqsx4sQeNODdSjcBsWOa0oDF+irQn9oYoLUDPI1IBtY1rX+FV99Zm/xnG7uFOX7aTVlko2GSdejy1w9mfobmfxu5aUc04A9zaKJP1pOthZvRAlhpymGYHgsDtWPrrjyc/yypMflE4kIUEEEtu1kT6mrAmcl615XYRAHYK9G2+fZsGvokwzbkl4nulGwcZMpQEoM0nD2o3GWgX81HW3nGfKBg";
2194        let session_key4 = "AgAAAAA4Kkesxq2h4v9PLD6Sm3Smxspz1PXTqytQPCMQMkkrHNmzV2bHlJ+6/Al9cu8vh1Oj69AK0WUAeJOJuaiskEeg/PI3P03+UYLeC379RzgqwSHdBgdQ41G2vD6zpgmE/8vYToe+qpCZACtPOswZxyqxHH+T/Iq0nv13JmlFGIeA6fEPfr5Y28B49viG74Fs9rxV9EH5PfjbuPM/p+Sz5obShuaBPKQBX1jT913nEXPoIJ06exNZGr0285nw/LgVvNlmWmbqNnbzO2cNZjQWA+xZYz5FSfyCxwqEBbEdUCuRCQ";
2195
2196        let sessions = [
2197            create_inbound_group_session_with_visibility(
2198                &alice,
2199                room1_id,
2200                &SessionKey::from_base64(session_key1).unwrap(),
2201                true,
2202            ),
2203            create_inbound_group_session_with_visibility(
2204                &alice,
2205                room1_id,
2206                &SessionKey::from_base64(session_key2).unwrap(),
2207                true,
2208            ),
2209            create_inbound_group_session_with_visibility(
2210                &alice,
2211                room1_id,
2212                &SessionKey::from_base64(session_key3).unwrap(),
2213                false,
2214            ),
2215            create_inbound_group_session_with_visibility(
2216                &alice,
2217                room2_id,
2218                &SessionKey::from_base64(session_key4).unwrap(),
2219                true,
2220            ),
2221        ];
2222        bob.store().save_inbound_group_sessions(&sessions).await.unwrap();
2223
2224        // When I build the bundle
2225        let mut bundle = bob.store().build_room_key_bundle(room1_id).await.unwrap();
2226
2227        // Then the bundle matches the snapshot.
2228
2229        // We sort the sessions in the bundle, so that the snapshot is stable.
2230        bundle.room_keys.sort_by_key(|session| session.session_id.clone());
2231
2232        // We substitute the algorithm, since this changes based on feature flags.
2233        let algorithm = if cfg!(feature = "experimental-algorithms") {
2234            "m.megolm.v2.aes-sha2"
2235        } else {
2236            "m.megolm.v1.aes-sha2"
2237        };
2238        let map_algorithm = move |value: Content, _path: ContentPath<'_>| {
2239            assert_eq!(value.as_str().unwrap(), algorithm);
2240            "[algorithm]"
2241        };
2242
2243        // We also substitute alice's keys in the snapshot with placeholders
2244        let alice_curve_key = alice.identity_keys().curve25519.to_base64();
2245        let map_alice_curve_key = move |value: Content, _path: ContentPath<'_>| {
2246            assert_eq!(value.as_str().unwrap(), alice_curve_key);
2247            "[alice curve key]"
2248        };
2249        let alice_ed25519_key = alice.identity_keys().ed25519.to_base64();
2250        let map_alice_ed25519_key = move |value: Content, _path: ContentPath<'_>| {
2251            assert_eq!(value.as_str().unwrap(), alice_ed25519_key);
2252            "[alice ed25519 key]"
2253        };
2254
2255        insta::with_settings!({ sort_maps => true }, {
2256            assert_json_snapshot!(bundle, {
2257                ".withheld[].algorithm" => insta::dynamic_redaction(map_algorithm),
2258                ".room_keys[].algorithm" => insta::dynamic_redaction(map_algorithm),
2259                ".room_keys[].sender_key" => insta::dynamic_redaction(map_alice_curve_key.clone()),
2260                ".withheld[].sender_key" => insta::dynamic_redaction(map_alice_curve_key),
2261                ".room_keys[].sender_claimed_keys.ed25519" => insta::dynamic_redaction(map_alice_ed25519_key),
2262            });
2263        });
2264    }
2265
2266    #[async_test]
2267    async fn test_receive_room_key_bundle() {
2268        let alice = OlmMachine::new(user_id!("@a:s.co"), device_id!("ALICE")).await;
2269        let alice_key = alice.identity_keys().curve25519;
2270        let bob = OlmMachine::new(user_id!("@b:s.co"), device_id!("BOB")).await;
2271
2272        let room_id = room_id!("!room1:localhost");
2273
2274        let session_key1 = "AgAAAAC2XHVzsMBKs4QCRElJ92CJKyGtknCSC8HY7cQ7UYwndMKLQAejXLh5UA0l6s736mgctcUMNvELScUWrObdflrHo+vth/gWreXOaCnaSxmyjjKErQwyIYTkUfqbHy40RJfEesLwnN23on9XAkch/iy8R2+Jz7B8zfG01f2Ow2SxPQFnAndcO1ZSD2GmXgedy6n4B20MWI1jGP2wiexOWbFSya8DO/VxC9m5+/mF+WwYqdpKn9g4Y05Yw4uz7cdjTc3rXm7xK+8E7hI//5QD1nHPvuKYbjjM9u2JSL+Bzp61Cw";
2275        let session_key2 = "AgAAAAC1BXreFTUQQSBGekTEuYxhdytRKyv4JgDGcG+VOBYdPNGgs807SdibCGJky4lJ3I+7ZDGHoUzZPZP/4ogGu4kxni0PWdtWuN7+5zsuamgoFF/BkaGeUUGv6kgIkx8pyPpM5SASTUEP9bN2loDSpUPYwfiIqz74DgC4WQ4435sTBctYvKz8n+TDJwdLXpyT6zKljuqADAioud+s/iqx9LYn9HpbBfezZcvbg67GtE113pLrvde3IcPI5s6dNHK2onGO2B2eoaobcen18bbEDnlUGPeIivArLya7Da6us14jBQ";
2276
2277        let sessions = [
2278            create_inbound_group_session_with_visibility(
2279                &alice,
2280                room_id,
2281                &SessionKey::from_base64(session_key1).unwrap(),
2282                true,
2283            ),
2284            create_inbound_group_session_with_visibility(
2285                &alice,
2286                room_id,
2287                &SessionKey::from_base64(session_key2).unwrap(),
2288                false,
2289            ),
2290        ];
2291
2292        alice.store().save_inbound_group_sessions(&sessions).await.unwrap();
2293        let bundle = alice.store().build_room_key_bundle(room_id).await.unwrap();
2294
2295        bob.store()
2296            .receive_room_key_bundle(
2297                &StoredRoomKeyBundleData {
2298                    sender_user: alice.user_id().to_owned(),
2299                    sender_key: alice_key,
2300                    sender_data: SenderData::sender_verified(
2301                        alice.user_id(),
2302                        device_id!("ALICE"),
2303                        alice.identity_keys().ed25519,
2304                    ),
2305
2306                    bundle_data: RoomKeyBundleContent {
2307                        room_id: room_id.to_owned(),
2308                        // This isn't used at all in the method call, so we can fill it with
2309                        // garbage.
2310                        file: EncryptedFileInit {
2311                            url: owned_mxc_uri!("mxc://example.com/0"),
2312                            key: JsonWebKeyInit {
2313                                kty: "oct".to_owned(),
2314                                key_ops: vec!["encrypt".to_owned(), "decrypt".to_owned()],
2315                                alg: "A256CTR.".to_owned(),
2316                                k: Base64::new(vec![0u8; 128]),
2317                                ext: true,
2318                            }
2319                            .into(),
2320                            iv: Base64::new(vec![0u8; 128]),
2321                            hashes: vec![("sha256".to_owned(), Base64::new(vec![0u8; 128]))]
2322                                .into_iter()
2323                                .collect(),
2324                            v: "v2".to_owned(),
2325                        }
2326                        .into(),
2327                    },
2328                },
2329                bundle,
2330                |_, _| {},
2331            )
2332            .await
2333            .unwrap();
2334
2335        // The room key should be imported successfully
2336        let imported_sessions =
2337            bob.store().get_inbound_group_sessions_by_room_id(room_id).await.unwrap();
2338
2339        assert_eq!(imported_sessions.len(), 1);
2340        assert_eq!(imported_sessions[0].room_id(), room_id);
2341
2342        assert_matches!(
2343            bob.store()
2344                .get_withheld_info(room_id, sessions[1].session_id())
2345                .await
2346                .unwrap()
2347                .expect("Withheld info should be present in the store."),
2348            RoomKeyWithheldEntry {
2349                #[cfg(not(feature = "experimental-algorithms"))]
2350                content: RoomKeyWithheldContent::MegolmV1AesSha2(
2351                    MegolmV1AesSha2WithheldContent::HistoryNotShared(_)
2352                ),
2353                #[cfg(feature = "experimental-algorithms")]
2354                content: RoomKeyWithheldContent::MegolmV2AesSha2(
2355                    MegolmV1AesSha2WithheldContent::HistoryNotShared(_)
2356                ),
2357                ..
2358            }
2359        );
2360    }
2361
2362    /// Tests that the new store format introduced in [#5737][#5737] does not
2363    /// conflict with items already in the store that were serialised with the
2364    /// older format.
2365    ///
2366    /// [#5737]: https://github.com/matrix-org/matrix-rust-sdk/pull/5737
2367    #[async_test]
2368    async fn test_deserialize_room_key_withheld_entry_from_to_device_event() {
2369        let entry: RoomKeyWithheldEntry = serde_json::from_value(json!(
2370            {
2371              "content": {
2372                "algorithm": "m.megolm.v1.aes-sha2",
2373                "code": "m.unauthorised",
2374                "from_device": "ALICE",
2375                "reason": "You are not authorised to read the message.",
2376                "room_id": "!roomid:s.co",
2377                "sender_key": "7hIcOrEroXYdzjtCBvBjUiqvT0Me7g+ymeXqoc65RS0",
2378                "session_id": "session123"
2379              },
2380              "sender": "@alice:s.co",
2381              "type": "m.room_key.withheld"
2382            }
2383        ))
2384        .unwrap();
2385
2386        assert_matches!(
2387            entry,
2388            RoomKeyWithheldEntry {
2389                sender,
2390                content: RoomKeyWithheldContent::MegolmV1AesSha2(
2391                    MegolmV1AesSha2WithheldContent::Unauthorised(withheld_content,)
2392                ),
2393            }
2394        );
2395
2396        assert_eq!(sender, "@alice:s.co");
2397        assert_eq!(withheld_content.room_id, "!roomid:s.co");
2398        assert_eq!(withheld_content.session_id, "session123");
2399        assert_eq!(
2400            withheld_content.sender_key.to_base64(),
2401            "7hIcOrEroXYdzjtCBvBjUiqvT0Me7g+ymeXqoc65RS0"
2402        );
2403        assert_eq!(withheld_content.from_device, Some(owned_device_id!("ALICE")));
2404    }
2405
2406    /// Create an inbound Megolm session for the given room.
2407    ///
2408    /// `olm_machine` is used to set the `sender_key` and `signing_key`
2409    /// fields of the resultant session.
2410    ///
2411    /// The encryption algorithm used for the session depends on the
2412    /// `experimental-algorithms` feature flag:
2413    ///
2414    /// - When not set, the session uses `m.megolm.v1.aes-sha2`.
2415    /// - When set, the session uses `m.megolm.v2.aes-sha2`.
2416    fn create_inbound_group_session_with_visibility(
2417        olm_machine: &OlmMachine,
2418        room_id: &RoomId,
2419        session_key: &SessionKey,
2420        shared_history: bool,
2421    ) -> InboundGroupSession {
2422        let identity_keys = &olm_machine.store().static_account().identity_keys;
2423        InboundGroupSession::new(
2424            identity_keys.curve25519,
2425            identity_keys.ed25519,
2426            room_id,
2427            session_key,
2428            SenderData::unknown(),
2429            #[cfg(not(feature = "experimental-algorithms"))]
2430            EventEncryptionAlgorithm::MegolmV1AesSha2,
2431            #[cfg(feature = "experimental-algorithms")]
2432            EventEncryptionAlgorithm::MegolmV2AesSha2,
2433            None,
2434            shared_history,
2435        )
2436        .unwrap()
2437    }
2438}