Skip to main content

matrix_sdk_crypto/store/
mod.rs

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