Skip to main content

matrix_sdk_indexeddb/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
15use std::{
16    collections::{BTreeMap, HashMap},
17    sync::{Arc, RwLock},
18};
19
20use async_trait::async_trait;
21use gloo_utils::format::JsValueSerdeExt;
22use hkdf::Hkdf;
23use indexed_db_futures::{
24    KeyRange,
25    cursor::Cursor,
26    database::Database,
27    internals::SystemRepr,
28    object_store::ObjectStore,
29    prelude::*,
30    transaction::{Transaction, TransactionMode},
31};
32use js_sys::Array;
33use matrix_sdk_base::cross_process_lock::{
34    CrossProcessLockGeneration, FIRST_CROSS_PROCESS_LOCK_GENERATION,
35};
36use matrix_sdk_crypto::{
37    Account, DeviceData, GossipRequest, SecretInfo, TrackedUser, UserIdentityData,
38    olm::{
39        Curve25519PublicKey, InboundGroupSession, OlmMessageHash, OutboundGroupSession,
40        PickledInboundGroupSession, PrivateCrossSigningIdentity, SenderDataType, Session,
41        StaticAccountData,
42    },
43    store::{
44        CryptoStore, CryptoStoreError,
45        types::{
46            BackupKeys, Changes, DehydratedDeviceKey, PendingChanges, RoomKeyCounts,
47            RoomKeyWithheldEntry, RoomPendingKeyBundleDetails, RoomSettings,
48            StoredRoomKeyBundleData,
49        },
50    },
51    vodozemac::base64_encode,
52};
53use matrix_sdk_store_encryption::StoreCipher;
54use ruma::{
55    DeviceId, MilliSecondsSinceUnixEpoch, OwnedDeviceId, RoomId, TransactionId, UserId,
56    events::secret::request::SecretName,
57};
58use serde::{Deserialize, Serialize};
59use sha2::Sha256;
60use tokio::sync::Mutex;
61use tracing::{debug, warn};
62use wasm_bindgen::JsValue;
63
64use crate::{
65    crypto_store::migrations::open_and_upgrade_db,
66    error::GenericError,
67    serializer::{MaybeEncrypted, SafeEncodeSerializer, SafeEncodeSerializerError},
68};
69
70mod migrations;
71
72mod keys {
73    // stores
74    pub const CORE: &str = "core";
75
76    pub const SESSION: &str = "session";
77
78    pub const INBOUND_GROUP_SESSIONS_V3: &str = "inbound_group_sessions3";
79    pub const INBOUND_GROUP_SESSIONS_BACKUP_INDEX: &str = "backup";
80    pub const INBOUND_GROUP_SESSIONS_BACKED_UP_TO_INDEX: &str = "backed_up_to";
81    pub const INBOUND_GROUP_SESSIONS_SENDER_KEY_INDEX: &str =
82        "inbound_group_session_sender_key_sender_data_type_idx";
83
84    pub const OUTBOUND_GROUP_SESSIONS: &str = "outbound_group_sessions";
85
86    pub const TRACKED_USERS: &str = "tracked_users";
87    pub const OLM_HASHES: &str = "olm_hashes";
88
89    pub const DEVICES: &str = "devices";
90    pub const IDENTITIES: &str = "identities";
91
92    pub const GOSSIP_REQUESTS: &str = "gossip_requests";
93    pub const GOSSIP_REQUESTS_UNSENT_INDEX: &str = "unsent";
94    pub const GOSSIP_REQUESTS_BY_INFO_INDEX: &str = "by_info";
95
96    pub const ROOM_SETTINGS: &str = "room_settings";
97
98    pub const SECRETS_INBOX_V2: &str = "secrets_inbox2";
99
100    pub const WITHHELD_SESSIONS: &str = "withheld_sessions";
101
102    pub const RECEIVED_ROOM_KEY_BUNDLES: &str = "received_room_key_bundles";
103
104    pub const LEASE_LOCKS: &str = "lease_locks";
105
106    pub const ROOM_KEY_BACKUPS_FULLY_DOWNLOADED: &str = "room_key_backups_fully_downloaded";
107    pub const ROOMS_PENDING_KEY_BUNDLE: &str = "rooms_pending_key_bundle";
108
109    // keys
110    pub const STORE_CIPHER: &str = "store_cipher";
111    pub const ACCOUNT: &str = "account";
112    pub const NEXT_BATCH_TOKEN: &str = "next_batch_token";
113    pub const PRIVATE_IDENTITY: &str = "private_identity";
114
115    // backup v1
116    pub const BACKUP_KEYS: &str = "backup_keys";
117
118    /// Indexeddb key for the key backup version that [`RECOVERY_KEY_V1`]
119    /// corresponds to.
120    pub const BACKUP_VERSION_V1: &str = "backup_version_v1";
121
122    /// Indexeddb key for the backup decryption key.
123    ///
124    /// Known, for historical reasons, as the recovery key. Not to be confused
125    /// with the client-side recovery key, which is actually an AES key for use
126    /// with SSSS.
127    pub const RECOVERY_KEY_V1: &str = "recovery_key_v1";
128
129    /// Indexeddb key for the dehydrated device pickle key.
130    pub const DEHYDRATION_PICKLE_KEY: &str = "dehydration_pickle_key";
131}
132
133/// An implementation of [CryptoStore] that uses [IndexedDB] for persistent
134/// storage.
135///
136/// [IndexedDB]: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
137pub struct IndexeddbCryptoStore {
138    static_account: RwLock<Option<StaticAccountData>>,
139    name: String,
140    pub(crate) inner: Database,
141
142    serializer: SafeEncodeSerializer,
143    save_changes_lock: Arc<Mutex<()>>,
144}
145
146#[cfg(not(tarpaulin_include))]
147impl std::fmt::Debug for IndexeddbCryptoStore {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        f.debug_struct("IndexeddbCryptoStore").field("name", &self.name).finish()
150    }
151}
152
153#[derive(Debug, thiserror::Error)]
154pub enum IndexeddbCryptoStoreError {
155    #[error(transparent)]
156    Serialization(#[from] serde_json::Error),
157    #[error("DomException {name} ({code}): {message}")]
158    DomException {
159        /// DomException code
160        code: u16,
161        /// Specific name of the DomException
162        name: String,
163        /// Message given to the DomException
164        message: String,
165    },
166    #[error(transparent)]
167    CryptoStoreError(#[from] CryptoStoreError),
168    #[error(
169        "The schema version of the crypto store is too new. \
170         Existing version: {current_version}; max supported version: {max_supported_version}"
171    )]
172    SchemaTooNewError { max_supported_version: u32, current_version: u32 },
173}
174
175impl From<SafeEncodeSerializerError> for IndexeddbCryptoStoreError {
176    fn from(value: SafeEncodeSerializerError) -> Self {
177        match value {
178            SafeEncodeSerializerError::Serialization(error) => Self::Serialization(error),
179            SafeEncodeSerializerError::DomException { code, name, message } => {
180                Self::DomException { code, name, message }
181            }
182            SafeEncodeSerializerError::CryptoStoreError(crypto_store_error) => {
183                Self::CryptoStoreError(crypto_store_error)
184            }
185        }
186    }
187}
188
189impl From<web_sys::DomException> for IndexeddbCryptoStoreError {
190    fn from(frm: web_sys::DomException) -> IndexeddbCryptoStoreError {
191        IndexeddbCryptoStoreError::DomException {
192            name: frm.name(),
193            message: frm.message(),
194            code: frm.code(),
195        }
196    }
197}
198
199impl From<serde_wasm_bindgen::Error> for IndexeddbCryptoStoreError {
200    fn from(e: serde_wasm_bindgen::Error) -> Self {
201        IndexeddbCryptoStoreError::Serialization(serde::de::Error::custom(e.to_string()))
202    }
203}
204
205impl From<IndexeddbCryptoStoreError> for CryptoStoreError {
206    fn from(frm: IndexeddbCryptoStoreError) -> CryptoStoreError {
207        match frm {
208            IndexeddbCryptoStoreError::Serialization(e) => CryptoStoreError::Serialization(e),
209            IndexeddbCryptoStoreError::CryptoStoreError(e) => e,
210            _ => CryptoStoreError::backend(frm),
211        }
212    }
213}
214
215impl From<indexed_db_futures::error::DomException> for IndexeddbCryptoStoreError {
216    fn from(value: indexed_db_futures::error::DomException) -> Self {
217        web_sys::DomException::from(value).into()
218    }
219}
220
221impl From<indexed_db_futures::error::SerialisationError> for IndexeddbCryptoStoreError {
222    fn from(value: indexed_db_futures::error::SerialisationError) -> Self {
223        Self::Serialization(serde::de::Error::custom(value.to_string()))
224    }
225}
226
227impl From<indexed_db_futures::error::UnexpectedDataError> for IndexeddbCryptoStoreError {
228    fn from(value: indexed_db_futures::error::UnexpectedDataError) -> Self {
229        Self::CryptoStoreError(CryptoStoreError::backend(value))
230    }
231}
232
233impl From<GenericError> for IndexeddbCryptoStoreError {
234    fn from(value: GenericError) -> Self {
235        Self::CryptoStoreError(value.into())
236    }
237}
238
239impl From<indexed_db_futures::error::JSError> for IndexeddbCryptoStoreError {
240    fn from(value: indexed_db_futures::error::JSError) -> Self {
241        GenericError::from(value.to_string()).into()
242    }
243}
244
245impl From<indexed_db_futures::error::Error> for IndexeddbCryptoStoreError {
246    fn from(value: indexed_db_futures::error::Error) -> Self {
247        use indexed_db_futures::error::Error;
248        match value {
249            Error::DomException(e) => e.into(),
250            Error::Serialisation(e) => e.into(),
251            Error::MissingData(e) => e.into(),
252            Error::Unknown(e) => e.into(),
253        }
254    }
255}
256
257impl From<indexed_db_futures::error::OpenDbError> for IndexeddbCryptoStoreError {
258    fn from(value: indexed_db_futures::error::OpenDbError) -> Self {
259        use indexed_db_futures::error::OpenDbError;
260        match value {
261            OpenDbError::Base(error) => error.into(),
262            _ => GenericError::from(value.to_string()).into(),
263        }
264    }
265}
266
267type Result<A, E = IndexeddbCryptoStoreError> = std::result::Result<A, E>;
268
269/// Defines an operation to perform on the database.
270enum PendingOperation {
271    Put { key: JsValue, value: JsValue },
272    Delete(JsValue),
273    DeleteByIndex { index: &'static str, key: JsValue },
274}
275
276/// A struct that represents all the operations that need to be done to the
277/// database when calls to the store `save_changes` are made.
278/// The idea is to do all the serialization and encryption before the
279/// transaction, and then just do the actual Indexeddb operations in the
280/// transaction.
281struct PendingIndexeddbChanges {
282    /// A map of the object store names to the operations to perform on that
283    /// store.
284    store_to_key_values: BTreeMap<&'static str, Vec<PendingOperation>>,
285}
286
287/// Represents the changes on a single object store.
288struct PendingStoreChanges<'a> {
289    operations: &'a mut Vec<PendingOperation>,
290}
291
292impl PendingStoreChanges<'_> {
293    fn put(&mut self, key: JsValue, value: JsValue) {
294        self.operations.push(PendingOperation::Put { key, value });
295    }
296
297    fn delete(&mut self, key: JsValue) {
298        self.operations.push(PendingOperation::Delete(key));
299    }
300
301    fn delete_by_index(&mut self, index: &'static str, key: JsValue) {
302        self.operations.push(PendingOperation::DeleteByIndex { index, key });
303    }
304}
305
306impl PendingIndexeddbChanges {
307    fn get(&mut self, store: &'static str) -> PendingStoreChanges<'_> {
308        PendingStoreChanges { operations: self.store_to_key_values.entry(store).or_default() }
309    }
310}
311
312impl PendingIndexeddbChanges {
313    fn new() -> Self {
314        Self { store_to_key_values: BTreeMap::new() }
315    }
316
317    /// Returns the list of stores that have pending operations.
318    /// Should be used as the list of store names when starting the indexeddb
319    /// transaction (`transaction_on_multi_with_mode`).
320    fn touched_stores(&self) -> Vec<&str> {
321        self.store_to_key_values
322            .iter()
323            .filter_map(
324                |(store, pending_operations)| {
325                    if !pending_operations.is_empty() { Some(*store) } else { None }
326                },
327            )
328            .collect()
329    }
330
331    /// Applies all the pending operations to the store.
332    async fn apply(self, tx: &Transaction<'_>) -> Result<()> {
333        for (store, operations) in self.store_to_key_values {
334            if operations.is_empty() {
335                continue;
336            }
337            let object_store = tx.object_store(store)?;
338            for op in operations {
339                match op {
340                    PendingOperation::Put { key, value } => {
341                        object_store.put(&value).with_key(key).build()?;
342                    }
343                    PendingOperation::Delete(key) => {
344                        object_store.delete(&key).build()?;
345                    }
346                    PendingOperation::DeleteByIndex { index, key } => {
347                        let range = KeyRange::Only(key);
348                        let ids = object_store
349                            .index(index)?
350                            .get_all_keys::<JsValue>()
351                            .with_query::<JsValue, _>(range)
352                            .await?;
353                        for id in ids {
354                            object_store.delete(id.unwrap()).await?;
355                        }
356                    }
357                }
358            }
359        }
360        Ok(())
361    }
362}
363
364impl IndexeddbCryptoStore {
365    pub(crate) async fn open_with_store_cipher(
366        prefix: &str,
367        store_cipher: Option<Arc<StoreCipher>>,
368    ) -> Result<Self> {
369        let name = format!("{prefix:0}::matrix-sdk-crypto");
370
371        let serializer = SafeEncodeSerializer::new(store_cipher);
372        debug!("IndexedDbCryptoStore: opening main store {name}");
373        let db = open_and_upgrade_db(&name, &serializer).await?;
374
375        Ok(Self {
376            name,
377            inner: db,
378            serializer,
379            static_account: RwLock::new(None),
380            save_changes_lock: Default::default(),
381        })
382    }
383
384    /// Open a new `IndexeddbCryptoStore` with default name and no passphrase
385    pub async fn open() -> Result<Self> {
386        IndexeddbCryptoStore::open_with_store_cipher("crypto", None).await
387    }
388
389    /// Open an `IndexeddbCryptoStore` with given name and passphrase.
390    ///
391    /// If the store previously existed, the encryption cipher is initialised
392    /// using the given passphrase and the details from the meta store. If the
393    /// store did not previously exist, a new encryption cipher is derived
394    /// from the passphrase, and the details are stored to the metastore.
395    ///
396    /// The store is then opened, or a new one created, using the encryption
397    /// cipher.
398    ///
399    /// # Arguments
400    ///
401    /// * `prefix` - Common prefix for the names of the two IndexedDB stores.
402    /// * `passphrase` - Passphrase which is used to derive a key to encrypt the
403    ///   key which is used to encrypt the store. Must be the same each time the
404    ///   store is opened.
405    pub async fn open_with_passphrase(prefix: &str, passphrase: &str) -> Result<Self> {
406        let db = open_meta_db(prefix).await?;
407        let store_cipher = load_store_cipher(&db).await?;
408
409        let store_cipher = match store_cipher {
410            Some(cipher) => {
411                debug!("IndexedDbCryptoStore: decrypting store cipher");
412                StoreCipher::import(passphrase, &cipher)
413                    .map_err(|_| CryptoStoreError::UnpicklingError)?
414            }
415            None => {
416                debug!("IndexedDbCryptoStore: encrypting new store cipher");
417                let cipher = StoreCipher::new().map_err(CryptoStoreError::backend)?;
418                #[cfg(not(test))]
419                let export = cipher.export(passphrase);
420                #[cfg(test)]
421                let export = cipher._insecure_export_fast_for_testing(passphrase);
422
423                let export = export.map_err(CryptoStoreError::backend)?;
424
425                save_store_cipher(&db, &export).await?;
426                cipher
427            }
428        };
429
430        // Must release the database access manually as it's not done when
431        // dropping it.
432        db.close();
433
434        IndexeddbCryptoStore::open_with_store_cipher(prefix, Some(store_cipher.into())).await
435    }
436
437    /// Open an `IndexeddbCryptoStore` with given name and key.
438    ///
439    /// If the store previously existed, the encryption cipher is initialised
440    /// using the given key and the details from the meta store. If the store
441    /// did not previously exist, a new encryption cipher is derived from
442    /// the passphrase, and the details are stored to the metastore.
443    ///
444    /// The store is then opened, or a new one created, using the encryption
445    /// cipher.
446    ///
447    /// # Arguments
448    ///
449    /// * `prefix` - Common prefix for the names of the two IndexedDB stores.
450    /// * `key` - Key with which to encrypt the key which is used to encrypt the
451    ///   store. Must be the same each time the store is opened.
452    pub async fn open_with_key(prefix: &str, key: &[u8; 32]) -> Result<Self> {
453        // The application might also use the provided key for something else, so to
454        // avoid key reuse, we pass the provided key through an HKDF
455        let mut chacha_key = zeroize::Zeroizing::new([0u8; 32]);
456        const HKDF_INFO: &[u8] = b"CRYPTOSTORE_CIPHER";
457        let hkdf = Hkdf::<Sha256>::new(None, key);
458        hkdf.expand(HKDF_INFO, &mut *chacha_key)
459            .expect("We should be able to generate a 32-byte key");
460
461        let db = open_meta_db(prefix).await?;
462        let store_cipher = load_store_cipher(&db).await?;
463
464        let store_cipher = match store_cipher {
465            Some(cipher) => {
466                debug!("IndexedDbCryptoStore: decrypting store cipher");
467                import_store_cipher_with_key(&chacha_key, key, &cipher, &db).await?
468            }
469            None => {
470                debug!("IndexedDbCryptoStore: encrypting new store cipher");
471                let cipher = StoreCipher::new().map_err(CryptoStoreError::backend)?;
472                let export = cipher
473                    .export_with_key(chacha_key.as_slice())
474                    .map_err(CryptoStoreError::backend)?;
475                save_store_cipher(&db, &export).await?;
476                cipher
477            }
478        };
479
480        // Must release the database access manually as it's not done when
481        // dropping it.
482        db.close();
483
484        IndexeddbCryptoStore::open_with_store_cipher(prefix, Some(store_cipher.into())).await
485    }
486
487    /// Open a new `IndexeddbCryptoStore` with given name and no passphrase
488    pub async fn open_with_name(name: &str) -> Result<Self> {
489        IndexeddbCryptoStore::open_with_store_cipher(name, None).await
490    }
491
492    /// Delete the IndexedDB databases for the given name.
493    #[cfg(test)]
494    pub fn delete_stores(prefix: &str) -> Result<()> {
495        Database::delete_by_name(&format!("{prefix:0}::matrix-sdk-crypto-meta"))?;
496        Database::delete_by_name(&format!("{prefix:0}::matrix-sdk-crypto"))?;
497        Ok(())
498    }
499
500    fn get_static_account(&self) -> Option<StaticAccountData> {
501        self.static_account.read().unwrap().clone()
502    }
503
504    /// Transform an [`InboundGroupSession`] into a `JsValue` holding a
505    /// [`InboundGroupSessionIndexedDbObject`], ready for storing.
506    async fn serialize_inbound_group_session(
507        &self,
508        session: &InboundGroupSession,
509    ) -> Result<JsValue> {
510        let obj =
511            InboundGroupSessionIndexedDbObject::from_session(session, &self.serializer).await?;
512        Ok(serde_wasm_bindgen::to_value(&obj)?)
513    }
514
515    /// Transform a JsValue holding a [`InboundGroupSessionIndexedDbObject`]
516    /// back into a [`InboundGroupSession`].
517    fn deserialize_inbound_group_session(
518        &self,
519        stored_value: JsValue,
520    ) -> Result<InboundGroupSession> {
521        let idb_object: InboundGroupSessionIndexedDbObject =
522            serde_wasm_bindgen::from_value(stored_value)?;
523        let pickled_session: PickledInboundGroupSession =
524            self.serializer.maybe_decrypt_value(idb_object.pickled_session)?;
525        let session = InboundGroupSession::from_pickle(pickled_session)
526            .map_err(|e| IndexeddbCryptoStoreError::CryptoStoreError(e.into()))?;
527
528        // Although a "backed up" flag is stored inside `idb_object.pickled_session`, it
529        // is not maintained when backups are reset. Overwrite the flag with the
530        // needs_backup value from the IDB object.
531        if idb_object.needs_backup {
532            session.reset_backup_state();
533        } else {
534            session.mark_as_backed_up();
535        }
536
537        Ok(session)
538    }
539
540    /// Transform a [`GossipRequest`] into a `JsValue` holding a
541    /// [`GossipRequestIndexedDbObject`], ready for storing.
542    fn serialize_gossip_request(&self, gossip_request: &GossipRequest) -> Result<JsValue> {
543        let obj = GossipRequestIndexedDbObject {
544            // hash the info as a key so that it can be used in index lookups.
545            info: self
546                .serializer
547                .encode_key_as_string(keys::GOSSIP_REQUESTS, gossip_request.info.as_key()),
548
549            // serialize and encrypt the data about the request
550            request: self.serializer.serialize_value_as_bytes(gossip_request)?,
551
552            unsent: !gossip_request.sent_out,
553        };
554
555        Ok(serde_wasm_bindgen::to_value(&obj)?)
556    }
557
558    /// Transform a JsValue holding a [`GossipRequestIndexedDbObject`] back into
559    /// a [`GossipRequest`].
560    fn deserialize_gossip_request(&self, stored_request: JsValue) -> Result<GossipRequest> {
561        let idb_object: GossipRequestIndexedDbObject =
562            serde_wasm_bindgen::from_value(stored_request)?;
563        Ok(self.serializer.deserialize_value_from_bytes(&idb_object.request)?)
564    }
565
566    /// Process all the changes and do all encryption/serialization before the
567    /// actual transaction.
568    ///
569    /// Returns a tuple where the first item is a `PendingIndexeddbChanges`
570    /// struct, and the second item is a boolean indicating whether the session
571    /// cache should be cleared.
572    async fn prepare_for_transaction(&self, changes: &Changes) -> Result<PendingIndexeddbChanges> {
573        let mut indexeddb_changes = PendingIndexeddbChanges::new();
574
575        let private_identity_pickle =
576            if let Some(i) = &changes.private_identity { Some(i.pickle().await) } else { None };
577
578        let decryption_key_pickle = &changes.backup_decryption_key;
579        let backup_version = &changes.backup_version;
580        let dehydration_pickle_key = &changes.dehydrated_device_pickle_key;
581
582        let mut core = indexeddb_changes.get(keys::CORE);
583        if let Some(next_batch) = &changes.next_batch_token {
584            core.put(
585                JsValue::from_str(keys::NEXT_BATCH_TOKEN),
586                self.serializer.serialize_value(next_batch)?,
587            );
588        }
589
590        if let Some(i) = &private_identity_pickle {
591            core.put(
592                JsValue::from_str(keys::PRIVATE_IDENTITY),
593                self.serializer.serialize_value(i)?,
594            );
595        }
596
597        if let Some(i) = &dehydration_pickle_key {
598            core.put(
599                JsValue::from_str(keys::DEHYDRATION_PICKLE_KEY),
600                self.serializer.serialize_value(i)?,
601            );
602        }
603
604        if let Some(a) = &decryption_key_pickle {
605            indexeddb_changes.get(keys::BACKUP_KEYS).put(
606                JsValue::from_str(keys::RECOVERY_KEY_V1),
607                self.serializer.serialize_value(&a)?,
608            );
609        }
610
611        if let Some(a) = &backup_version {
612            indexeddb_changes.get(keys::BACKUP_KEYS).put(
613                JsValue::from_str(keys::BACKUP_VERSION_V1),
614                self.serializer.serialize_value(&a)?,
615            );
616        }
617
618        if !changes.sessions.is_empty() {
619            let mut sessions = indexeddb_changes.get(keys::SESSION);
620
621            for session in &changes.sessions {
622                let sender_key = session.sender_key().to_base64();
623                let session_id = session.session_id();
624
625                let pickle = session.pickle().await;
626                let key = self.serializer.encode_key(keys::SESSION, (&sender_key, session_id));
627
628                sessions.put(key, self.serializer.serialize_value(&pickle)?);
629            }
630        }
631
632        if !changes.inbound_group_sessions.is_empty() {
633            let mut sessions = indexeddb_changes.get(keys::INBOUND_GROUP_SESSIONS_V3);
634
635            for session in &changes.inbound_group_sessions {
636                let room_id = session.room_id();
637                let session_id = session.session_id();
638                let key = self
639                    .serializer
640                    .encode_key(keys::INBOUND_GROUP_SESSIONS_V3, (room_id, session_id));
641                let value = self.serialize_inbound_group_session(session).await?;
642                sessions.put(key, value);
643            }
644        }
645
646        if !changes.outbound_group_sessions.is_empty() {
647            let mut sessions = indexeddb_changes.get(keys::OUTBOUND_GROUP_SESSIONS);
648
649            for session in &changes.outbound_group_sessions {
650                let room_id = session.room_id();
651                let pickle = session.pickle().await;
652                sessions.put(
653                    self.serializer.encode_key(keys::OUTBOUND_GROUP_SESSIONS, room_id),
654                    self.serializer.serialize_value(&pickle)?,
655                );
656            }
657        }
658
659        let device_changes = &changes.devices;
660        let identity_changes = &changes.identities;
661        let olm_hashes = &changes.message_hashes;
662        let key_requests = &changes.key_requests;
663        let withheld_session_info = &changes.withheld_session_info;
664        let room_settings_changes = &changes.room_settings;
665
666        let mut device_store = indexeddb_changes.get(keys::DEVICES);
667
668        for device in device_changes.new.iter().chain(&device_changes.changed) {
669            let key =
670                self.serializer.encode_key(keys::DEVICES, (device.user_id(), device.device_id()));
671            let device = self.serializer.serialize_value(&device)?;
672
673            device_store.put(key, device);
674        }
675
676        for device in &device_changes.deleted {
677            let key =
678                self.serializer.encode_key(keys::DEVICES, (device.user_id(), device.device_id()));
679            device_store.delete(key);
680        }
681
682        if !identity_changes.changed.is_empty() || !identity_changes.new.is_empty() {
683            let mut identities = indexeddb_changes.get(keys::IDENTITIES);
684            for identity in identity_changes.changed.iter().chain(&identity_changes.new) {
685                identities.put(
686                    self.serializer.encode_key(keys::IDENTITIES, identity.user_id()),
687                    self.serializer.serialize_value(&identity)?,
688                );
689            }
690        }
691
692        if !olm_hashes.is_empty() {
693            let mut hashes = indexeddb_changes.get(keys::OLM_HASHES);
694            for hash in olm_hashes {
695                hashes.put(
696                    self.serializer.encode_key(keys::OLM_HASHES, (&hash.sender_key, &hash.hash)),
697                    JsValue::TRUE,
698                );
699            }
700        }
701
702        if !key_requests.is_empty() {
703            let mut gossip_requests = indexeddb_changes.get(keys::GOSSIP_REQUESTS);
704
705            for gossip_request in key_requests {
706                // Remove any previous requests for the same secret.
707                let key_request_info =
708                    self.serializer.encode_key(keys::GOSSIP_REQUESTS, gossip_request.info.as_key());
709                gossip_requests
710                    .delete_by_index(keys::GOSSIP_REQUESTS_BY_INFO_INDEX, key_request_info);
711
712                let key_request_id = self
713                    .serializer
714                    .encode_key(keys::GOSSIP_REQUESTS, gossip_request.request_id.as_str());
715                let key_request_value = self.serialize_gossip_request(gossip_request)?;
716                gossip_requests.put(key_request_id, key_request_value);
717            }
718        }
719
720        if !withheld_session_info.is_empty() {
721            let mut withhelds = indexeddb_changes.get(keys::WITHHELD_SESSIONS);
722
723            for (room_id, data) in withheld_session_info {
724                for (session_id, event) in data {
725                    let key =
726                        self.serializer.encode_key(keys::WITHHELD_SESSIONS, (&room_id, session_id));
727                    withhelds.put(key, self.serializer.serialize_value(&event)?);
728                }
729            }
730        }
731
732        if !room_settings_changes.is_empty() {
733            let mut settings_store = indexeddb_changes.get(keys::ROOM_SETTINGS);
734
735            for (room_id, settings) in room_settings_changes {
736                let key = self.serializer.encode_key(keys::ROOM_SETTINGS, room_id);
737                let value = self.serializer.serialize_value(&settings)?;
738                settings_store.put(key, value);
739            }
740        }
741
742        if !changes.secrets.is_empty() {
743            let mut secret_store = indexeddb_changes.get(keys::SECRETS_INBOX_V2);
744
745            for secret in &changes.secrets {
746                use std::ops::Deref;
747                // The (hashed) secret value is included in the key to allow us to receive
748                // multiple secrets of the same name (indexeddb store entries must have a unique
749                // key), and allow the client to determine which one is the
750                // current secret.
751                let key = self.serializer.encode_key(
752                    keys::SECRETS_INBOX_V2,
753                    (secret.secret_name.as_str(), secret.secret.as_str()),
754                );
755                let value = self.serializer.serialize_value(secret.secret.deref())?;
756
757                secret_store.put(key, value);
758            }
759        }
760
761        if !changes.received_room_key_bundles.is_empty() {
762            let mut bundle_store = indexeddb_changes.get(keys::RECEIVED_ROOM_KEY_BUNDLES);
763            for bundle in &changes.received_room_key_bundles {
764                let key = self.serializer.encode_key(
765                    keys::RECEIVED_ROOM_KEY_BUNDLES,
766                    (&bundle.bundle_data.room_id, &bundle.sender_user),
767                );
768                let value = self.serializer.serialize_value(&bundle)?;
769                bundle_store.put(key, value);
770            }
771        }
772
773        if !changes.room_key_backups_fully_downloaded.is_empty() {
774            let mut room_store = indexeddb_changes.get(keys::ROOM_KEY_BACKUPS_FULLY_DOWNLOADED);
775            for room_id in &changes.room_key_backups_fully_downloaded {
776                room_store.put(
777                    self.serializer.encode_key(keys::ROOM_KEY_BACKUPS_FULLY_DOWNLOADED, room_id),
778                    JsValue::TRUE,
779                );
780            }
781        }
782
783        if !changes.rooms_pending_key_bundle.is_empty() {
784            let mut room_store = indexeddb_changes.get(keys::ROOMS_PENDING_KEY_BUNDLE);
785            for (room_id, details) in &changes.rooms_pending_key_bundle {
786                let key = self.serializer.encode_key(keys::ROOMS_PENDING_KEY_BUNDLE, room_id);
787                if let Some(details) = details {
788                    let value = self.serializer.serialize_value(details)?;
789                    room_store.put(key, value);
790                } else {
791                    room_store.delete(key);
792                }
793            }
794        }
795
796        Ok(indexeddb_changes)
797    }
798}
799
800// Small hack to have the following macro invocation act as the appropriate
801// trait impl block on wasm, but still be compiled on non-wasm as a regular
802// impl block otherwise.
803//
804// The trait impl doesn't compile on non-wasm due to unfulfilled trait bounds,
805// this hack allows us to still have most of rust-analyzer's IDE functionality
806// within the impl block without having to set it up to check things against
807// the wasm target (which would disable many other parts of the codebase).
808#[cfg(target_family = "wasm")]
809macro_rules! impl_crypto_store {
810    ( $($body:tt)* ) => {
811        #[async_trait(?Send)]
812        impl CryptoStore for IndexeddbCryptoStore {
813            type Error = IndexeddbCryptoStoreError;
814
815            $($body)*
816        }
817    };
818}
819
820#[cfg(not(target_family = "wasm"))]
821macro_rules! impl_crypto_store {
822    ( $($body:tt)* ) => {
823        impl IndexeddbCryptoStore {
824            $($body)*
825        }
826    };
827}
828
829impl_crypto_store! {
830    async fn save_pending_changes(&self, changes: PendingChanges) -> Result<()> {
831        // Serialize calls to `save_pending_changes`; there are multiple await points
832        // below, and we're pickling data as we go, so we don't want to
833        // invalidate data we've previously read and overwrite it in the store.
834        // TODO: #2000 should make this lock go away, or change its shape.
835        let _guard = self.save_changes_lock.lock().await;
836
837        let stores: Vec<&str> = [(changes.account.is_some(), keys::CORE)]
838            .iter()
839            .filter_map(|(id, key)| if *id { Some(*key) } else { None })
840            .collect();
841
842        if stores.is_empty() {
843            // nothing to do, quit early
844            return Ok(());
845        }
846
847        let tx = self.inner.transaction(stores).with_mode(TransactionMode::Readwrite).build()?;
848
849        let account_pickle = if let Some(account) = changes.account {
850            *self.static_account.write().unwrap() = Some(account.static_data().clone());
851            Some(account.pickle())
852        } else {
853            None
854        };
855
856        if let Some(a) = &account_pickle {
857            tx.object_store(keys::CORE)?
858                .put(&self.serializer.serialize_value(&a)?)
859                .with_key(JsValue::from_str(keys::ACCOUNT))
860                .build()?;
861        }
862
863        tx.commit().await?;
864
865        Ok(())
866    }
867
868    async fn save_changes(&self, changes: Changes) -> Result<()> {
869        // Serialize calls to `save_changes`; there are multiple await points below, and
870        // we're pickling data as we go, so we don't want to invalidate data
871        // we've previously read and overwrite it in the store.
872        // TODO: #2000 should make this lock go away, or change its shape.
873        let _guard = self.save_changes_lock.lock().await;
874
875        let indexeddb_changes = self.prepare_for_transaction(&changes).await?;
876
877        let stores = indexeddb_changes.touched_stores();
878
879        if stores.is_empty() {
880            // nothing to do, quit early
881            return Ok(());
882        }
883
884        let tx = self.inner.transaction(stores).with_mode(TransactionMode::Readwrite).build()?;
885
886        indexeddb_changes.apply(&tx).await?;
887
888        tx.commit().await?;
889
890        Ok(())
891    }
892
893    async fn save_inbound_group_sessions(
894        &self,
895        sessions: Vec<InboundGroupSession>,
896        backed_up_to_version: Option<&str>,
897    ) -> Result<()> {
898        // Sanity-check that the data in the sessions corresponds to backed_up_version
899        sessions.iter().for_each(|s| {
900            let backed_up = s.backed_up();
901            if backed_up != backed_up_to_version.is_some() {
902                warn!(
903                    backed_up,
904                    backed_up_to_version,
905                    "Session backed-up flag does not correspond to backup version setting",
906                );
907            }
908        });
909
910        // Currently, this store doesn't save the backup version separately, so this
911        // just delegates to save_changes.
912        self.save_changes(Changes { inbound_group_sessions: sessions, ..Changes::default() }).await
913    }
914
915    async fn load_tracked_users(&self) -> Result<Vec<TrackedUser>> {
916        let tx = self
917            .inner
918            .transaction(keys::TRACKED_USERS)
919            .with_mode(TransactionMode::Readonly)
920            .build()?;
921        let os = tx.object_store(keys::TRACKED_USERS)?;
922        let user_ids = os.get_all_keys::<JsValue>().await?;
923
924        let mut users = Vec::new();
925
926        for result in user_ids {
927            let user_id = result?;
928            let dirty: bool = !matches!(
929                os.get(&user_id).await?.map(|v: JsValue| v.into_serde()),
930                Some(Ok(false))
931            );
932            let Some(Ok(user_id)) = user_id.as_string().map(UserId::parse) else { continue };
933
934            users.push(TrackedUser { user_id, dirty });
935        }
936
937        Ok(users)
938    }
939
940    async fn get_outbound_group_session(
941        &self,
942        room_id: &RoomId,
943    ) -> Result<Option<OutboundGroupSession>> {
944        let account_info = self.get_static_account().ok_or(CryptoStoreError::AccountUnset)?;
945        if let Some(value) = self
946            .inner
947            .transaction(keys::OUTBOUND_GROUP_SESSIONS)
948            .with_mode(TransactionMode::Readonly)
949            .build()?
950            .object_store(keys::OUTBOUND_GROUP_SESSIONS)?
951            .get(&self.serializer.encode_key(keys::OUTBOUND_GROUP_SESSIONS, room_id))
952            .await?
953        {
954            Ok(Some(
955                OutboundGroupSession::from_pickle(
956                    account_info.device_id,
957                    account_info.identity_keys,
958                    self.serializer.deserialize_value(value)?,
959                )
960                .map_err(CryptoStoreError::from)?,
961            ))
962        } else {
963            Ok(None)
964        }
965    }
966
967    async fn get_outgoing_secret_requests(
968        &self,
969        request_id: &TransactionId,
970    ) -> Result<Option<GossipRequest>> {
971        let jskey = self.serializer.encode_key(keys::GOSSIP_REQUESTS, request_id.as_str());
972        self.inner
973            .transaction(keys::GOSSIP_REQUESTS)
974            .with_mode(TransactionMode::Readonly)
975            .build()?
976            .object_store(keys::GOSSIP_REQUESTS)?
977            .get(jskey)
978            .await?
979            .map(|val| self.deserialize_gossip_request(val))
980            .transpose()
981    }
982
983    async fn load_account(&self) -> Result<Option<Account>> {
984        if let Some(pickle) = self
985            .inner
986            .transaction(keys::CORE)
987            .with_mode(TransactionMode::Readonly)
988            .build()?
989            .object_store(keys::CORE)?
990            .get(&JsValue::from_str(keys::ACCOUNT))
991            .await?
992        {
993            let pickle = self.serializer.deserialize_value(pickle)?;
994
995            let account = Account::from_pickle(pickle).map_err(CryptoStoreError::from)?;
996
997            *self.static_account.write().unwrap() = Some(account.static_data().clone());
998
999            Ok(Some(account))
1000        } else {
1001            Ok(None)
1002        }
1003    }
1004
1005    async fn next_batch_token(&self) -> Result<Option<String>> {
1006        if let Some(serialized) = self
1007            .inner
1008            .transaction(keys::CORE)
1009            .with_mode(TransactionMode::Readonly)
1010            .build()?
1011            .object_store(keys::CORE)?
1012            .get(&JsValue::from_str(keys::NEXT_BATCH_TOKEN))
1013            .await?
1014        {
1015            let token = self.serializer.deserialize_value(serialized)?;
1016            Ok(Some(token))
1017        } else {
1018            Ok(None)
1019        }
1020    }
1021
1022    async fn load_identity(&self) -> Result<Option<PrivateCrossSigningIdentity>> {
1023        if let Some(pickle) = self
1024            .inner
1025            .transaction(keys::CORE)
1026            .with_mode(TransactionMode::Readonly)
1027            .build()?
1028            .object_store(keys::CORE)?
1029            .get(&JsValue::from_str(keys::PRIVATE_IDENTITY))
1030            .await?
1031        {
1032            let pickle = self.serializer.deserialize_value(pickle)?;
1033
1034            Ok(Some(
1035                PrivateCrossSigningIdentity::from_pickle(pickle)
1036                    .map_err(|_| CryptoStoreError::UnpicklingError)?,
1037            ))
1038        } else {
1039            Ok(None)
1040        }
1041    }
1042
1043    async fn get_sessions(&self, sender_key: &str) -> Result<Option<Vec<Session>>> {
1044        let device_keys = self.get_own_device().await?.as_device_keys().clone();
1045
1046        let range = self.serializer.encode_to_range(keys::SESSION, sender_key);
1047        let sessions: Vec<Session> = self
1048            .inner
1049            .transaction(keys::SESSION)
1050            .with_mode(TransactionMode::Readonly)
1051            .build()?
1052            .object_store(keys::SESSION)?
1053            .get_all()
1054            .with_query(&range)
1055            .await?
1056            .filter_map(Result::ok)
1057            .filter_map(|f| {
1058                self.serializer.deserialize_value(f).ok().map(|p| {
1059                    Session::from_pickle(device_keys.clone(), p).map_err(|_| {
1060                        IndexeddbCryptoStoreError::CryptoStoreError(CryptoStoreError::AccountUnset)
1061                    })
1062                })
1063            })
1064            .collect::<Result<Vec<Session>>>()?;
1065
1066        if sessions.is_empty() {
1067            Ok(None)
1068        } else {
1069            Ok(Some(sessions))
1070        }
1071    }
1072
1073    async fn get_inbound_group_session(
1074        &self,
1075        room_id: &RoomId,
1076        session_id: &str,
1077    ) -> Result<Option<InboundGroupSession>> {
1078        let key =
1079            self.serializer.encode_key(keys::INBOUND_GROUP_SESSIONS_V3, (room_id, session_id));
1080        if let Some(value) = self
1081            .inner
1082            .transaction(keys::INBOUND_GROUP_SESSIONS_V3)
1083            .with_mode(TransactionMode::Readonly)
1084            .build()?
1085            .object_store(keys::INBOUND_GROUP_SESSIONS_V3)?
1086            .get(&key)
1087            .await?
1088        {
1089            Ok(Some(self.deserialize_inbound_group_session(value)?))
1090        } else {
1091            Ok(None)
1092        }
1093    }
1094
1095    async fn get_inbound_group_sessions(&self) -> Result<Vec<InboundGroupSession>> {
1096        const INBOUND_GROUP_SESSIONS_BATCH_SIZE: usize = 1000;
1097
1098        let transaction = self
1099            .inner
1100            .transaction(keys::INBOUND_GROUP_SESSIONS_V3)
1101            .with_mode(TransactionMode::Readonly)
1102            .build()?;
1103
1104        let object_store = transaction.object_store(keys::INBOUND_GROUP_SESSIONS_V3)?;
1105
1106        fetch_from_object_store_batched(
1107            object_store,
1108            |value| self.deserialize_inbound_group_session(value),
1109            INBOUND_GROUP_SESSIONS_BATCH_SIZE,
1110        )
1111        .await
1112    }
1113
1114    async fn get_inbound_group_sessions_by_room_id(
1115        &self,
1116        room_id: &RoomId,
1117    ) -> Result<Vec<InboundGroupSession>> {
1118        let range = self.serializer.encode_to_range(keys::INBOUND_GROUP_SESSIONS_V3, room_id);
1119        Ok(self
1120            .inner
1121            .transaction(keys::INBOUND_GROUP_SESSIONS_V3)
1122            .with_mode(TransactionMode::Readonly)
1123            .build()?
1124            .object_store(keys::INBOUND_GROUP_SESSIONS_V3)?
1125            .get_all()
1126            .with_query(&range)
1127            .await?
1128            .filter_map(Result::ok)
1129            .filter_map(|v| match self.deserialize_inbound_group_session(v) {
1130                Ok(session) => Some(session),
1131                Err(e) => {
1132                    warn!("Failed to deserialize inbound group session: {e}");
1133                    None
1134                }
1135            })
1136            .collect::<Vec<InboundGroupSession>>())
1137    }
1138
1139    async fn get_inbound_group_sessions_for_device_batch(
1140        &self,
1141        sender_key: Curve25519PublicKey,
1142        sender_data_type: SenderDataType,
1143        after_session_id: Option<String>,
1144        limit: usize,
1145    ) -> Result<Vec<InboundGroupSession>> {
1146        let sender_key =
1147            self.serializer.encode_key(keys::INBOUND_GROUP_SESSIONS_V3, sender_key.to_base64());
1148
1149        // The empty string is before all keys in Indexed DB - first batch starts there.
1150        let after_session_id = after_session_id
1151            .map(|s| self.serializer.encode_key(keys::INBOUND_GROUP_SESSIONS_V3, s))
1152            .unwrap_or("".into());
1153
1154        let lower_bound: Array =
1155            [sender_key.clone(), (sender_data_type as u8).into(), after_session_id]
1156                .iter()
1157                .collect();
1158        let upper_bound: Array =
1159            [sender_key, ((sender_data_type as u8) + 1).into()].iter().collect();
1160        let key = KeyRange::Bound(lower_bound, true, upper_bound, true);
1161
1162        let tx = self
1163            .inner
1164            .transaction(keys::INBOUND_GROUP_SESSIONS_V3)
1165            .with_mode(TransactionMode::Readonly)
1166            .build()?;
1167
1168        let store = tx.object_store(keys::INBOUND_GROUP_SESSIONS_V3)?;
1169        let idx = store.index(keys::INBOUND_GROUP_SESSIONS_SENDER_KEY_INDEX)?;
1170        let serialized_sessions =
1171            idx.get_all().with_query::<Array, _>(key).with_limit(limit as u32).await?;
1172
1173        // Deserialize and decrypt after the transaction is complete.
1174        let result = serialized_sessions
1175            .filter_map(Result::ok)
1176            .filter_map(|v| match self.deserialize_inbound_group_session(v) {
1177                Ok(session) => Some(session),
1178                Err(e) => {
1179                    warn!("Failed to deserialize inbound group session: {e}");
1180                    None
1181                }
1182            })
1183            .collect::<Vec<InboundGroupSession>>();
1184
1185        Ok(result)
1186    }
1187
1188    async fn inbound_group_session_counts(
1189        &self,
1190        _backup_version: Option<&str>,
1191    ) -> Result<RoomKeyCounts> {
1192        let tx = self
1193            .inner
1194            .transaction(keys::INBOUND_GROUP_SESSIONS_V3)
1195            .with_mode(TransactionMode::Readonly)
1196            .build()?;
1197        let store = tx.object_store(keys::INBOUND_GROUP_SESSIONS_V3)?;
1198        let all = store.count().await? as usize;
1199        let not_backed_up =
1200            store.index(keys::INBOUND_GROUP_SESSIONS_BACKUP_INDEX)?.count().await? as usize;
1201        tx.commit().await?;
1202        Ok(RoomKeyCounts { total: all, backed_up: all - not_backed_up })
1203    }
1204
1205    async fn inbound_group_sessions_for_backup(
1206        &self,
1207        _backup_version: &str,
1208        limit: usize,
1209    ) -> Result<Vec<InboundGroupSession>> {
1210        let tx = self
1211            .inner
1212            .transaction(keys::INBOUND_GROUP_SESSIONS_V3)
1213            .with_mode(TransactionMode::Readonly)
1214            .build()?;
1215
1216        let store = tx.object_store(keys::INBOUND_GROUP_SESSIONS_V3)?;
1217        let idx = store.index(keys::INBOUND_GROUP_SESSIONS_BACKUP_INDEX)?;
1218
1219        // XXX ideally we would use `get_all_with_key_and_limit`, but that doesn't
1220        // appear to be   exposed (https://github.com/Alorel/rust-indexed-db/issues/31). Instead we replicate
1221        //   the behaviour with a cursor.
1222        let Some(mut cursor) = idx.open_cursor().await? else {
1223            return Ok(vec![]);
1224        };
1225
1226        let mut serialized_sessions = Vec::with_capacity(limit);
1227        for _ in 0..limit {
1228            let Some(value) = cursor.next_record().await? else {
1229                break;
1230            };
1231            serialized_sessions.push(value)
1232        }
1233
1234        tx.commit().await?;
1235
1236        // Deserialize and decrypt after the transaction is complete.
1237        let result = serialized_sessions
1238            .into_iter()
1239            .filter_map(|v| match self.deserialize_inbound_group_session(v) {
1240                Ok(session) => Some(session),
1241                Err(e) => {
1242                    warn!("Failed to deserialize inbound group session: {e}");
1243                    None
1244                }
1245            })
1246            .collect::<Vec<InboundGroupSession>>();
1247
1248        Ok(result)
1249    }
1250
1251    async fn mark_inbound_group_sessions_as_backed_up(
1252        &self,
1253        _backup_version: &str,
1254        room_and_session_ids: &[(&RoomId, &str)],
1255    ) -> Result<()> {
1256        let tx = self
1257            .inner
1258            .transaction(keys::INBOUND_GROUP_SESSIONS_V3)
1259            .with_mode(TransactionMode::Readwrite)
1260            .build()?;
1261
1262        let object_store = tx.object_store(keys::INBOUND_GROUP_SESSIONS_V3)?;
1263
1264        for (room_id, session_id) in room_and_session_ids {
1265            let key =
1266                self.serializer.encode_key(keys::INBOUND_GROUP_SESSIONS_V3, (room_id, session_id));
1267            if let Some(idb_object_js) = object_store.get(&key).await? {
1268                let mut idb_object: InboundGroupSessionIndexedDbObject =
1269                    serde_wasm_bindgen::from_value(idb_object_js)?;
1270                idb_object.needs_backup = false;
1271                object_store
1272                    .put(&serde_wasm_bindgen::to_value(&idb_object)?)
1273                    .with_key(key)
1274                    .build()?;
1275            } else {
1276                warn!(?key, "Could not find inbound group session to mark it as backed up.");
1277            }
1278        }
1279
1280        Ok(tx.commit().await?)
1281    }
1282
1283    async fn reset_backup_state(&self) -> Result<()> {
1284        let tx = self
1285            .inner
1286            .transaction(keys::INBOUND_GROUP_SESSIONS_V3)
1287            .with_mode(TransactionMode::Readwrite)
1288            .build()?;
1289
1290        if let Some(mut cursor) =
1291            tx.object_store(keys::INBOUND_GROUP_SESSIONS_V3)?.open_cursor().await?
1292        {
1293            while let Some(value) = cursor.next_record().await? {
1294                let mut idb_object: InboundGroupSessionIndexedDbObject =
1295                    serde_wasm_bindgen::from_value(value)?;
1296                if !idb_object.needs_backup {
1297                    idb_object.needs_backup = true;
1298                    // We don't bother to update the encrypted `InboundGroupSession` object stored
1299                    // inside `idb_object.data`, since that would require decryption and encryption.
1300                    // Instead, it will be patched up by `deserialize_inbound_group_session`.
1301                    let idb_object = serde_wasm_bindgen::to_value(&idb_object)?;
1302                    cursor.update(&idb_object).await?;
1303                }
1304            }
1305        }
1306
1307        Ok(tx.commit().await?)
1308    }
1309
1310    async fn save_tracked_users(&self, users: &[(&UserId, bool)]) -> Result<()> {
1311        let tx = self
1312            .inner
1313            .transaction(keys::TRACKED_USERS)
1314            .with_mode(TransactionMode::Readwrite)
1315            .build()?;
1316        let os = tx.object_store(keys::TRACKED_USERS)?;
1317
1318        for (user, dirty) in users {
1319            os.put(&JsValue::from(*dirty)).with_key(JsValue::from_str(user.as_str())).build()?;
1320        }
1321
1322        tx.commit().await?;
1323        Ok(())
1324    }
1325
1326    async fn get_device(
1327        &self,
1328        user_id: &UserId,
1329        device_id: &DeviceId,
1330    ) -> Result<Option<DeviceData>> {
1331        let key = self.serializer.encode_key(keys::DEVICES, (user_id, device_id));
1332        self.inner
1333            .transaction(keys::DEVICES)
1334            .with_mode(TransactionMode::Readonly)
1335            .build()?
1336            .object_store(keys::DEVICES)?
1337            .get(&key)
1338            .await?
1339            .map(|i| self.serializer.deserialize_value(i).map_err(Into::into))
1340            .transpose()
1341    }
1342
1343    async fn get_user_devices(
1344        &self,
1345        user_id: &UserId,
1346    ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
1347        let range = self.serializer.encode_to_range(keys::DEVICES, user_id);
1348        Ok(self
1349            .inner
1350            .transaction(keys::DEVICES)
1351            .with_mode(TransactionMode::Readonly)
1352            .build()?
1353            .object_store(keys::DEVICES)?
1354            .get_all()
1355            .with_query(&range)
1356            .await?
1357            .filter_map(Result::ok)
1358            .filter_map(|d| {
1359                let d: DeviceData = self.serializer.deserialize_value(d).ok()?;
1360                Some((d.device_id().to_owned(), d))
1361            })
1362            .collect::<HashMap<_, _>>())
1363    }
1364
1365    async fn get_own_device(&self) -> Result<DeviceData> {
1366        let account_info = self.get_static_account().ok_or(CryptoStoreError::AccountUnset)?;
1367        Ok(self.get_device(&account_info.user_id, &account_info.device_id).await?.unwrap())
1368    }
1369
1370    async fn get_user_identity(&self, user_id: &UserId) -> Result<Option<UserIdentityData>> {
1371        self.inner
1372            .transaction(keys::IDENTITIES)
1373            .with_mode(TransactionMode::Readonly)
1374            .build()?
1375            .object_store(keys::IDENTITIES)?
1376            .get(&self.serializer.encode_key(keys::IDENTITIES, user_id))
1377            .await?
1378            .map(|i| self.serializer.deserialize_value(i).map_err(Into::into))
1379            .transpose()
1380    }
1381
1382    async fn is_message_known(&self, hash: &OlmMessageHash) -> Result<bool> {
1383        Ok(self
1384            .inner
1385            .transaction(keys::OLM_HASHES)
1386            .with_mode(TransactionMode::Readonly)
1387            .build()?
1388            .object_store(keys::OLM_HASHES)?
1389            .get::<JsValue, _, _>(
1390                &self.serializer.encode_key(keys::OLM_HASHES, (&hash.sender_key, &hash.hash)),
1391            )
1392            .await?
1393            .is_some())
1394    }
1395
1396    async fn get_secrets_from_inbox(
1397        &self,
1398        secret_name: &SecretName,
1399    ) -> Result<Vec<zeroize::Zeroizing<String>>> {
1400        let range = self.serializer.encode_to_range(keys::SECRETS_INBOX_V2, secret_name.as_str());
1401
1402        self.inner
1403            .transaction(keys::SECRETS_INBOX_V2)
1404            .with_mode(TransactionMode::Readonly)
1405            .build()?
1406            .object_store(keys::SECRETS_INBOX_V2)?
1407            .get_all()
1408            .with_query(&range)
1409            .await?
1410            .map(|result| {
1411                let d = result?;
1412                let secret: String = self.serializer.deserialize_value(d)?;
1413                Ok(secret.into())
1414            })
1415            .collect()
1416    }
1417
1418    #[allow(clippy::unused_async)] // Mandated by trait on wasm.
1419    async fn delete_secrets_from_inbox(&self, secret_name: &SecretName) -> Result<()> {
1420        let range = self.serializer.encode_to_range(keys::SECRETS_INBOX_V2, secret_name.as_str());
1421
1422        let transaction = self
1423            .inner
1424            .transaction(keys::SECRETS_INBOX_V2)
1425            .with_mode(TransactionMode::Readwrite)
1426            .build()?;
1427        transaction.object_store(keys::SECRETS_INBOX_V2)?.delete(&range).build()?;
1428        transaction.commit().await?;
1429
1430        Ok(())
1431    }
1432
1433    async fn get_secret_request_by_info(
1434        &self,
1435        key_info: &SecretInfo,
1436    ) -> Result<Option<GossipRequest>> {
1437        let key = self.serializer.encode_key(keys::GOSSIP_REQUESTS, key_info.as_key());
1438
1439        let val = self
1440            .inner
1441            .transaction(keys::GOSSIP_REQUESTS)
1442            .with_mode(TransactionMode::Readonly)
1443            .build()?
1444            .object_store(keys::GOSSIP_REQUESTS)?
1445            .index(keys::GOSSIP_REQUESTS_BY_INFO_INDEX)?
1446            .get(key)
1447            .await?;
1448
1449        if let Some(val) = val {
1450            let deser = self.deserialize_gossip_request(val)?;
1451            Ok(Some(deser))
1452        } else {
1453            Ok(None)
1454        }
1455    }
1456
1457    async fn get_unsent_secret_requests(&self) -> Result<Vec<GossipRequest>> {
1458        let results = self
1459            .inner
1460            .transaction(keys::GOSSIP_REQUESTS)
1461            .with_mode(TransactionMode::Readonly)
1462            .build()?
1463            .object_store(keys::GOSSIP_REQUESTS)?
1464            .index(keys::GOSSIP_REQUESTS_UNSENT_INDEX)?
1465            .get_all()
1466            .await?
1467            .filter_map(Result::ok)
1468            .filter_map(|val| self.deserialize_gossip_request(val).ok())
1469            .collect();
1470
1471        Ok(results)
1472    }
1473
1474    async fn delete_outgoing_secret_requests(&self, request_id: &TransactionId) -> Result<()> {
1475        let jskey = self.serializer.encode_key(keys::GOSSIP_REQUESTS, request_id);
1476        let tx = self
1477            .inner
1478            .transaction(keys::GOSSIP_REQUESTS)
1479            .with_mode(TransactionMode::Readwrite)
1480            .build()?;
1481        tx.object_store(keys::GOSSIP_REQUESTS)?.delete(jskey).build()?;
1482        tx.commit().await.map_err(|e| e.into())
1483    }
1484
1485    async fn load_backup_keys(&self) -> Result<BackupKeys> {
1486        let key = {
1487            let tx = self
1488                .inner
1489                .transaction(keys::BACKUP_KEYS)
1490                .with_mode(TransactionMode::Readonly)
1491                .build()?;
1492            let store = tx.object_store(keys::BACKUP_KEYS)?;
1493
1494            let backup_version = store
1495                .get(&JsValue::from_str(keys::BACKUP_VERSION_V1))
1496                .await?
1497                .map(|i| self.serializer.deserialize_value(i))
1498                .transpose()?;
1499
1500            let decryption_key = store
1501                .get(&JsValue::from_str(keys::RECOVERY_KEY_V1))
1502                .await?
1503                .map(|i| self.serializer.deserialize_value(i))
1504                .transpose()?;
1505
1506            BackupKeys { backup_version, decryption_key }
1507        };
1508
1509        Ok(key)
1510    }
1511
1512    async fn load_dehydrated_device_pickle_key(&self) -> Result<Option<DehydratedDeviceKey>> {
1513        if let Some(pickle) = self
1514            .inner
1515            .transaction(keys::CORE)
1516            .with_mode(TransactionMode::Readonly)
1517            .build()?
1518            .object_store(keys::CORE)?
1519            .get(&JsValue::from_str(keys::DEHYDRATION_PICKLE_KEY))
1520            .await?
1521        {
1522            let pickle: DehydratedDeviceKey = self.serializer.deserialize_value(pickle)?;
1523
1524            Ok(Some(pickle))
1525        } else {
1526            Ok(None)
1527        }
1528    }
1529
1530    async fn delete_dehydrated_device_pickle_key(&self) -> Result<()> {
1531        self.remove_custom_value(keys::DEHYDRATION_PICKLE_KEY).await?;
1532        Ok(())
1533    }
1534
1535    async fn get_withheld_info(
1536        &self,
1537        room_id: &RoomId,
1538        session_id: &str,
1539    ) -> Result<Option<RoomKeyWithheldEntry>> {
1540        let key = self.serializer.encode_key(keys::WITHHELD_SESSIONS, (room_id, session_id));
1541        if let Some(pickle) = self
1542            .inner
1543            .transaction(keys::WITHHELD_SESSIONS)
1544            .with_mode(TransactionMode::Readonly)
1545            .build()?
1546            .object_store(keys::WITHHELD_SESSIONS)?
1547            .get(&key)
1548            .await?
1549        {
1550            let info = self.serializer.deserialize_value(pickle)?;
1551            Ok(Some(info))
1552        } else {
1553            Ok(None)
1554        }
1555    }
1556
1557    async fn get_withheld_sessions_by_room_id(
1558        &self,
1559        room_id: &RoomId,
1560    ) -> Result<Vec<RoomKeyWithheldEntry>> {
1561        let range = self.serializer.encode_to_range(keys::WITHHELD_SESSIONS, room_id);
1562
1563        self
1564            .inner
1565            .transaction(keys::WITHHELD_SESSIONS)
1566            .with_mode(TransactionMode::Readonly)
1567            .build()?
1568            .object_store(keys::WITHHELD_SESSIONS)?
1569            .get_all()
1570            .with_query(&range)
1571            .await?
1572            .map(|val| self.serializer.deserialize_value(val?).map_err(Into::into))
1573            .collect()
1574    }
1575
1576    async fn get_room_settings(&self, room_id: &RoomId) -> Result<Option<RoomSettings>> {
1577        let key = self.serializer.encode_key(keys::ROOM_SETTINGS, room_id);
1578        self.inner
1579            .transaction(keys::ROOM_SETTINGS)
1580            .with_mode(TransactionMode::Readonly)
1581            .build()?
1582            .object_store(keys::ROOM_SETTINGS)?
1583            .get(&key)
1584            .await?
1585            .map(|v| self.serializer.deserialize_value(v).map_err(Into::into))
1586            .transpose()
1587    }
1588
1589    async fn get_received_room_key_bundle_data(
1590        &self,
1591        room_id: &RoomId,
1592        user_id: &UserId,
1593    ) -> Result<Option<StoredRoomKeyBundleData>> {
1594        let key = self.serializer.encode_key(keys::RECEIVED_ROOM_KEY_BUNDLES, (room_id, user_id));
1595        let result = self
1596            .inner
1597            .transaction(keys::RECEIVED_ROOM_KEY_BUNDLES)
1598            .with_mode(TransactionMode::Readonly)
1599            .build()?
1600            .object_store(keys::RECEIVED_ROOM_KEY_BUNDLES)?
1601            .get(&key)
1602            .await?
1603            .map(|v| self.serializer.deserialize_value(v))
1604            .transpose()?;
1605
1606        Ok(result)
1607    }
1608
1609    async fn has_downloaded_all_room_keys(&self, room_id: &RoomId) -> Result<bool> {
1610        let key = self.serializer.encode_key(keys::ROOM_KEY_BACKUPS_FULLY_DOWNLOADED, room_id);
1611        let result = self
1612            .inner
1613            .transaction(keys::ROOM_KEY_BACKUPS_FULLY_DOWNLOADED)
1614            .with_mode(TransactionMode::Readonly)
1615            .build()?
1616            .object_store(keys::ROOM_KEY_BACKUPS_FULLY_DOWNLOADED)?
1617            .get::<JsValue, _, _>(&key)
1618            .await?
1619            .is_some();
1620
1621        Ok(result)
1622    }
1623
1624    async fn get_pending_key_bundle_details_for_room(&self, room_id: &RoomId) -> Result<Option<RoomPendingKeyBundleDetails >> {
1625        let key = self.serializer.encode_key(keys::ROOMS_PENDING_KEY_BUNDLE, room_id);
1626        let result = self
1627            .inner
1628            .transaction(keys::ROOMS_PENDING_KEY_BUNDLE)
1629            .with_mode(TransactionMode::Readonly)
1630            .build()?
1631            .object_store(keys::ROOMS_PENDING_KEY_BUNDLE)?
1632            .get(&key)
1633            .await?
1634            .map(|v| self.serializer.deserialize_value(v))
1635            .transpose()?;
1636        Ok(result)
1637    }
1638
1639    async fn get_all_rooms_pending_key_bundles(&self) -> Result<Vec<RoomPendingKeyBundleDetails>> {
1640        let result = self
1641            .inner
1642            .transaction(keys::ROOMS_PENDING_KEY_BUNDLE)
1643            .with_mode(TransactionMode::Readonly)
1644            .build()?
1645            .object_store(keys::ROOMS_PENDING_KEY_BUNDLE)?
1646            .get_all()
1647            .await?
1648            .map(|result| {
1649                result
1650                    .map_err(Into::into)
1651                    .and_then(|v| self.serializer.deserialize_value(v).map_err(Into::into))
1652            })
1653            .collect::<Result<Vec<_>>>()?;
1654        Ok(result)
1655    }
1656
1657    async fn get_custom_value(&self, key: &str) -> Result<Option<Vec<u8>>> {
1658        self.inner
1659            .transaction(keys::CORE)
1660            .with_mode(TransactionMode::Readonly)
1661            .build()?
1662            .object_store(keys::CORE)?
1663            .get(&JsValue::from_str(key))
1664            .await?
1665            .map(|v| self.serializer.deserialize_value(v).map_err(Into::into))
1666            .transpose()
1667    }
1668
1669    #[allow(clippy::unused_async)] // Mandated by trait on wasm.
1670    async fn set_custom_value(&self, key: &str, value: Vec<u8>) -> Result<()> {
1671        let transaction =
1672            self.inner.transaction(keys::CORE).with_mode(TransactionMode::Readwrite).build()?;
1673        transaction
1674            .object_store(keys::CORE)?
1675            .put(&self.serializer.serialize_value(&value)?)
1676            .with_key(JsValue::from_str(key))
1677            .build()?;
1678        transaction.commit().await?;
1679        Ok(())
1680    }
1681
1682    #[allow(clippy::unused_async)] // Mandated by trait on wasm.
1683    async fn remove_custom_value(&self, key: &str) -> Result<()> {
1684        let transaction =
1685            self.inner.transaction(keys::CORE).with_mode(TransactionMode::Readwrite).build()?;
1686        transaction.object_store(keys::CORE)?.delete(&JsValue::from_str(key)).build()?;
1687        transaction.commit().await?;
1688        Ok(())
1689    }
1690
1691    async fn try_take_leased_lock(
1692        &self,
1693        lease_duration_ms: u32,
1694        key: &str,
1695        holder: &str,
1696    ) -> Result<Option<CrossProcessLockGeneration>> {
1697        // As of 2023-06-23, the code below hasn't been tested yet.
1698        let key = JsValue::from_str(key);
1699        let txn = self
1700            .inner
1701            .transaction(keys::LEASE_LOCKS)
1702            .with_mode(TransactionMode::Readwrite)
1703            .build()?;
1704        let object_store = txn.object_store(keys::LEASE_LOCKS)?;
1705
1706        #[derive(Deserialize, Serialize)]
1707        struct Lease {
1708            holder: String,
1709            expiration: u64,
1710            generation: CrossProcessLockGeneration,
1711        }
1712
1713        let now: u64 = MilliSecondsSinceUnixEpoch::now().get().into();
1714        let expiration = now + lease_duration_ms as u64;
1715
1716        let lease = match object_store.get(&key).await? {
1717            Some(entry) => {
1718                let mut lease: Lease = self.serializer.deserialize_value(entry)?;
1719
1720                if lease.holder == holder {
1721                    // We had the lease before, extend it.
1722                    lease.expiration = expiration;
1723
1724                    Some(lease)
1725                } else {
1726                    // We didn't have it.
1727                    if lease.expiration < now {
1728                        // Steal it!
1729                        lease.holder = holder.to_owned();
1730                        lease.expiration = expiration;
1731                        lease.generation += 1;
1732
1733                        Some(lease)
1734                    } else {
1735                        // We tried our best.
1736                        None
1737                    }
1738                }
1739            }
1740            None => {
1741                let lease = Lease {
1742                    holder: holder.to_owned(),
1743                    expiration,
1744                    generation: FIRST_CROSS_PROCESS_LOCK_GENERATION,
1745                };
1746
1747                Some(lease)
1748            }
1749        };
1750
1751        Ok(if let Some(lease) = lease {
1752            object_store.put(&self.serializer.serialize_value(&lease)?).with_key(key).build()?;
1753
1754            Some(lease.generation)
1755        } else {
1756            None
1757        })
1758    }
1759
1760    #[allow(clippy::unused_async)]
1761    async fn get_size(&self) -> Result<Option<usize>> {
1762        Ok(None)
1763    }
1764
1765    #[allow(clippy::unused_async)]
1766    async fn close(&self) -> Result<()> {
1767        Ok(())
1768    }
1769
1770    #[allow(clippy::unused_async)]
1771    async fn reopen(&self) -> Result<()> {
1772        Ok(())
1773    }
1774}
1775
1776impl Drop for IndexeddbCryptoStore {
1777    fn drop(&mut self) {
1778        // Must release the database access manually as it's not done when
1779        // dropping it.
1780        self.inner.as_sys().close();
1781    }
1782}
1783
1784/// Open the meta store.
1785///
1786/// The meta store contains details about the encryption of the main store.
1787async fn open_meta_db(prefix: &str) -> Result<Database, IndexeddbCryptoStoreError> {
1788    let name = format!("{prefix:0}::matrix-sdk-crypto-meta");
1789
1790    debug!("IndexedDbCryptoStore: Opening meta-store {name}");
1791    Database::open(&name)
1792        .with_version(1u32)
1793        .with_on_upgrade_needed(|evt, tx| {
1794            let old_version = evt.old_version() as u32;
1795            if old_version < 1 {
1796                // migrating to version 1
1797                tx.db().create_object_store("matrix-sdk-crypto").build()?;
1798            }
1799            Ok(())
1800        })
1801        .await
1802        .map_err(Into::into)
1803}
1804
1805/// Load the serialised store cipher from the meta store.
1806///
1807/// # Arguments:
1808///
1809/// * `meta_db`: Connection to the meta store, as returned by [`open_meta_db`].
1810///
1811/// # Returns:
1812///
1813/// The serialised `StoreCipher` object.
1814async fn load_store_cipher(
1815    meta_db: &Database,
1816) -> Result<Option<Vec<u8>>, IndexeddbCryptoStoreError> {
1817    let tx: Transaction<'_> =
1818        meta_db.transaction("matrix-sdk-crypto").with_mode(TransactionMode::Readonly).build()?;
1819    let ob = tx.object_store("matrix-sdk-crypto")?;
1820
1821    let store_cipher: Option<Vec<u8>> = ob
1822        .get(&JsValue::from_str(keys::STORE_CIPHER))
1823        .await?
1824        .map(|k: JsValue| k.into_serde())
1825        .transpose()?;
1826    Ok(store_cipher)
1827}
1828
1829/// Save the serialised store cipher to the meta store.
1830///
1831/// # Arguments:
1832///
1833/// * `meta_db`: Connection to the meta store, as returned by [`open_meta_db`].
1834/// * `store_cipher`: The serialised `StoreCipher` object.
1835async fn save_store_cipher(
1836    db: &Database,
1837    export: &Vec<u8>,
1838) -> Result<(), IndexeddbCryptoStoreError> {
1839    let tx: Transaction<'_> =
1840        db.transaction("matrix-sdk-crypto").with_mode(TransactionMode::Readwrite).build()?;
1841    let ob = tx.object_store("matrix-sdk-crypto")?;
1842
1843    ob.put(&JsValue::from_serde(&export)?)
1844        .with_key(JsValue::from_str(keys::STORE_CIPHER))
1845        .build()?;
1846    tx.commit().await?;
1847    Ok(())
1848}
1849
1850/// Given a serialised store cipher, try importing with the given key.
1851///
1852/// This is a helper for [`IndexeddbCryptoStore::open_with_key`].
1853///
1854/// # Arguments
1855///
1856/// * `chacha_key`: The key to use with [`StoreCipher::import_with_key`].
1857///   Derived from `original_key` via an HKDF.
1858/// * `original_key`: The key provided by the application. Used to provide a
1859///   migration path from an older key derivation system.
1860/// * `serialised_cipher`: The serialized `EncryptedStoreCipher`, retrieved from
1861///   the database.
1862/// * `db`: Connection to the database.
1863async fn import_store_cipher_with_key(
1864    chacha_key: &[u8; 32],
1865    original_key: &[u8],
1866    serialised_cipher: &[u8],
1867    db: &Database,
1868) -> Result<StoreCipher, IndexeddbCryptoStoreError> {
1869    let cipher = match StoreCipher::import_with_key(chacha_key, serialised_cipher) {
1870        Ok(cipher) => cipher,
1871        Err(matrix_sdk_store_encryption::Error::KdfMismatch) => {
1872            // Old versions of the matrix-js-sdk used to base64-encode their encryption
1873            // key, and pass it into [`IndexeddbCryptoStore::open_with_passphrase`]. For
1874            // backwards compatibility, we fall back to that if we discover we have a cipher
1875            // encrypted with a KDF when we expected it to be encrypted directly with a key.
1876            let cipher = StoreCipher::import(&base64_encode(original_key), serialised_cipher)
1877                .map_err(|_| CryptoStoreError::UnpicklingError)?;
1878
1879            // Loading the cipher with the passphrase was successful. Let's update the
1880            // stored version of the cipher so that it is encrypted with a key,
1881            // to save doing this again.
1882            debug!(
1883                "IndexedDbCryptoStore: Migrating passphrase-encrypted store cipher to key-encryption"
1884            );
1885
1886            let export = cipher.export_with_key(chacha_key).map_err(CryptoStoreError::backend)?;
1887            save_store_cipher(db, &export).await?;
1888            cipher
1889        }
1890        Err(_) => Err(CryptoStoreError::UnpicklingError)?,
1891    };
1892    Ok(cipher)
1893}
1894
1895/// Fetch items from an object store in batches, transform each item using
1896/// the supplied function, and stuff the transformed items into a single
1897/// vector to return.
1898async fn fetch_from_object_store_batched<R, F>(
1899    object_store: ObjectStore<'_>,
1900    f: F,
1901    batch_size: usize,
1902) -> Result<Vec<R>>
1903where
1904    F: Fn(JsValue) -> Result<R>,
1905{
1906    let mut result = Vec::new();
1907    let mut batch_n = 0;
1908
1909    // The empty string is before all keys in Indexed DB - first batch starts there.
1910    let mut latest_key: JsValue = "".into();
1911
1912    loop {
1913        debug!("Fetching Indexed DB records starting from {}", batch_n * batch_size);
1914
1915        // See https://github.com/Alorel/rust-indexed-db/issues/31 - we
1916        // would like to use `get_all_with_key_and_limit` if it ever exists
1917        // but for now we use a cursor and manually limit batch size.
1918
1919        // Get hold of a cursor for this batch. (This should not panic in expect()
1920        // because we always use "", or the result of cursor.key(), both of
1921        // which are valid keys.)
1922        let after_latest_key = KeyRange::LowerBound(&latest_key, true);
1923        let cursor = object_store.open_cursor().with_query(&after_latest_key).await?;
1924
1925        // Fetch batch_size records into result
1926        let next_key = fetch_batch(cursor, batch_size, &f, &mut result).await?;
1927        if let Some(next_key) = next_key {
1928            latest_key = next_key;
1929        } else {
1930            break;
1931        }
1932
1933        batch_n += 1;
1934    }
1935
1936    Ok(result)
1937}
1938
1939/// Fetch batch_size records from the supplied cursor,
1940/// and return the last key we processed, or None if
1941/// we reached the end of the cursor.
1942async fn fetch_batch<R, F, Q>(
1943    cursor: Option<Cursor<'_, Q>>,
1944    batch_size: usize,
1945    f: &F,
1946    result: &mut Vec<R>,
1947) -> Result<Option<JsValue>>
1948where
1949    F: Fn(JsValue) -> Result<R>,
1950    Q: QuerySource,
1951{
1952    let Some(mut cursor) = cursor else {
1953        // Cursor was None - there are no more records
1954        return Ok(None);
1955    };
1956
1957    let mut latest_key = None;
1958
1959    for _ in 0..batch_size {
1960        let Some(value) = cursor.next_record().await? else {
1961            return Ok(None);
1962        };
1963
1964        // Process the record
1965        let processed = f(value);
1966        if let Ok(processed) = processed {
1967            result.push(processed);
1968        }
1969        // else processing failed: don't return this record at all
1970
1971        // Remember that we have processed this record, so if we hit
1972        // the end of the batch, the next batch can start after this one
1973        if let Some(key) = cursor.key()? {
1974            latest_key = Some(key);
1975        }
1976    }
1977
1978    // We finished the batch but there are more records -
1979    // return the key of the last one we processed
1980    Ok(latest_key)
1981}
1982
1983/// The objects we store in the gossip_requests indexeddb object store
1984#[derive(Debug, Serialize, Deserialize)]
1985struct GossipRequestIndexedDbObject {
1986    /// Encrypted hash of the [`SecretInfo`] structure.
1987    info: String,
1988
1989    /// Encrypted serialised representation of the [`GossipRequest`] as a whole.
1990    request: Vec<u8>,
1991
1992    /// Whether the request has yet to be sent out.
1993    ///
1994    /// Since we only need to be able to find requests where this is `true`, we
1995    /// skip serialization in cases where it is `false`. That has the effect
1996    /// of omitting it from the indexeddb index.
1997    ///
1998    /// We also use a custom serializer because bools can't be used as keys in
1999    /// indexeddb.
2000    #[serde(
2001        default,
2002        skip_serializing_if = "std::ops::Not::not",
2003        with = "crate::serializer::foreign::bool"
2004    )]
2005    unsent: bool,
2006}
2007
2008/// The objects we store in the inbound_group_sessions3 indexeddb object store
2009#[derive(Serialize, Deserialize)]
2010struct InboundGroupSessionIndexedDbObject {
2011    /// Possibly encrypted
2012    /// [`matrix_sdk_crypto::olm::group_sessions::PickledInboundGroupSession`]
2013    pickled_session: MaybeEncrypted,
2014
2015    /// The (hashed) session ID of this session. This is somewhat redundant, but
2016    /// we have to pull it out to its own object so that we can do batched
2017    /// queries such as
2018    /// [`IndexeddbStore::get_inbound_group_sessions_for_device_batch`].
2019    ///
2020    /// Added in database schema v12, and lazily populated, so it is only
2021    /// present for sessions received or modified since DB schema v12.
2022    #[serde(default, skip_serializing_if = "Option::is_none")]
2023    session_id: Option<String>,
2024
2025    /// Whether the session data has yet to be backed up.
2026    ///
2027    /// Since we only need to be able to find entries where this is `true`, we
2028    /// skip serialization in cases where it is `false`. That has the effect
2029    /// of omitting it from the indexeddb index.
2030    ///
2031    /// We also use a custom serializer because bools can't be used as keys in
2032    /// indexeddb.
2033    #[serde(
2034        default,
2035        skip_serializing_if = "std::ops::Not::not",
2036        with = "crate::serializer::foreign::bool"
2037    )]
2038    needs_backup: bool,
2039
2040    /// Unused: for future compatibility. In future, will contain the order
2041    /// number (not the ID!) of the backup for which this key has been
2042    /// backed up. This will replace `needs_backup`, fixing the performance
2043    /// problem identified in
2044    /// https://github.com/element-hq/element-web/issues/26892
2045    /// because we won't need to update all records when we spot a new backup
2046    /// version.
2047    /// In this version of the code, this is always set to -1, meaning:
2048    /// "refer to the `needs_backup` property". See:
2049    /// https://github.com/element-hq/element-web/issues/26892#issuecomment-1906336076
2050    backed_up_to: i32,
2051
2052    /// The (hashed) curve25519 key of the device that sent us this room key,
2053    /// base64-encoded.
2054    ///
2055    /// Added in database schema v12, and lazily populated, so it is only
2056    /// present for sessions received or modified since DB schema v12.
2057    #[serde(default, skip_serializing_if = "Option::is_none")]
2058    sender_key: Option<String>,
2059
2060    /// The type of the [`SenderData`] within this session, converted to a u8
2061    /// from [`SenderDataType`].
2062    ///
2063    /// Added in database schema v12, and lazily populated, so it is only
2064    /// present for sessions received or modified since DB schema v12.
2065    #[serde(default, skip_serializing_if = "Option::is_none")]
2066    sender_data_type: Option<u8>,
2067}
2068
2069impl InboundGroupSessionIndexedDbObject {
2070    /// Build an [`InboundGroupSessionIndexedDbObject`] wrapping the given
2071    /// session.
2072    pub async fn from_session(
2073        session: &InboundGroupSession,
2074        serializer: &SafeEncodeSerializer,
2075    ) -> Result<Self, CryptoStoreError> {
2076        let session_id =
2077            serializer.encode_key_as_string(keys::INBOUND_GROUP_SESSIONS_V3, session.session_id());
2078
2079        let sender_key = serializer.encode_key_as_string(
2080            keys::INBOUND_GROUP_SESSIONS_V3,
2081            session.sender_key().to_base64(),
2082        );
2083
2084        Ok(InboundGroupSessionIndexedDbObject {
2085            pickled_session: serializer.maybe_encrypt_value(session.pickle().await)?,
2086            session_id: Some(session_id),
2087            needs_backup: !session.backed_up(),
2088            backed_up_to: -1,
2089            sender_key: Some(sender_key),
2090            sender_data_type: Some(session.sender_data_type() as u8),
2091        })
2092    }
2093}
2094
2095#[cfg(test)]
2096mod unit_tests {
2097    use matrix_sdk_crypto::{
2098        olm::{Curve25519PublicKey, InboundGroupSession, SenderData, SessionKey},
2099        types::EventEncryptionAlgorithm,
2100        vodozemac::Ed25519Keypair,
2101    };
2102    use matrix_sdk_store_encryption::EncryptedValueBase64;
2103    use matrix_sdk_test::async_test;
2104    use ruma::{device_id, room_id, user_id};
2105
2106    use super::InboundGroupSessionIndexedDbObject;
2107    use crate::serializer::{MaybeEncrypted, SafeEncodeSerializer};
2108
2109    #[test]
2110    fn needs_backup_is_serialized_as_a_u8_in_json() {
2111        let session_needs_backup = backup_test_session(true);
2112
2113        // Testing the exact JSON here is theoretically flaky in the face of
2114        // serialization changes in serde_json but it seems unlikely, and it's
2115        // simple enough to fix if we need to.
2116        assert!(
2117            serde_json::to_string(&session_needs_backup).unwrap().contains(r#""needs_backup":1"#),
2118        );
2119    }
2120
2121    #[test]
2122    fn doesnt_need_backup_is_serialized_with_missing_field_in_json() {
2123        let session_backed_up = backup_test_session(false);
2124
2125        assert!(
2126            !serde_json::to_string(&session_backed_up).unwrap().contains("needs_backup"),
2127            "The needs_backup field should be missing!"
2128        );
2129    }
2130
2131    pub fn backup_test_session(needs_backup: bool) -> InboundGroupSessionIndexedDbObject {
2132        InboundGroupSessionIndexedDbObject {
2133            pickled_session: MaybeEncrypted::Encrypted(EncryptedValueBase64::new(1, "", "")),
2134            session_id: None,
2135            needs_backup,
2136            backed_up_to: -1,
2137            sender_key: None,
2138            sender_data_type: None,
2139        }
2140    }
2141
2142    #[async_test]
2143    async fn test_sender_key_and_sender_data_type_are_serialized_in_json() {
2144        let sender_key = Curve25519PublicKey::from_bytes([0; 32]);
2145
2146        let sender_data = SenderData::sender_verified(
2147            user_id!("@test:user"),
2148            device_id!("ABC"),
2149            Ed25519Keypair::new().public_key(),
2150        );
2151
2152        let db_object = sender_data_test_session(sender_key, sender_data).await;
2153        let serialized = serde_json::to_string(&db_object).unwrap();
2154
2155        assert!(
2156            serialized.contains(r#""sender_key":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA""#)
2157        );
2158        assert!(serialized.contains(r#""sender_data_type":5"#));
2159    }
2160
2161    pub async fn sender_data_test_session(
2162        sender_key: Curve25519PublicKey,
2163        sender_data: SenderData,
2164    ) -> InboundGroupSessionIndexedDbObject {
2165        let session = InboundGroupSession::new(
2166            sender_key,
2167            Ed25519Keypair::new().public_key(),
2168            room_id!("!test:localhost"),
2169            // Arbitrary session data
2170            &SessionKey::from_base64(
2171                "AgAAAABTyn3CR8mzAxhsHH88td5DrRqfipJCnNbZeMrfzhON6O1Cyr9ewx/sDFLO6\
2172                 +NvyW92yGvMub7nuAEQb+SgnZLm7nwvuVvJgSZKpoJMVliwg8iY9TXKFT286oBtT2\
2173                 /8idy6TcpKax4foSHdMYlZXu5zOsGDdd9eYnYHpUEyDT0utuiaakZM3XBMNLEVDj9\
2174                 Ps929j1FGgne1bDeFVoty2UAOQK8s/0JJigbKSu6wQ/SzaCYpE/LD4Egk2Nxs1JE2\
2175                 33ii9J8RGPYOp7QWl0kTEc8mAlqZL7mKppo9AwgtmYweAg",
2176            )
2177            .unwrap(),
2178            sender_data,
2179            None,
2180            EventEncryptionAlgorithm::MegolmV1AesSha2,
2181            None,
2182            false,
2183        )
2184        .unwrap();
2185
2186        InboundGroupSessionIndexedDbObject::from_session(&session, &SafeEncodeSerializer::new(None))
2187            .await
2188            .unwrap()
2189    }
2190}
2191
2192#[cfg(all(test, target_family = "wasm"))]
2193mod wasm_unit_tests {
2194    use std::collections::BTreeMap;
2195
2196    use matrix_sdk_crypto::{
2197        olm::{Curve25519PublicKey, SenderData},
2198        types::{DeviceKeys, Signatures},
2199    };
2200    use matrix_sdk_test::async_test;
2201    use ruma::{owned_device_id, owned_user_id};
2202    use wasm_bindgen::JsValue;
2203
2204    use crate::crypto_store::unit_tests::sender_data_test_session;
2205
2206    fn assert_field_equals(js_value: &JsValue, field: &str, expected: u32) {
2207        assert_eq!(
2208            js_sys::Reflect::get(&js_value, &field.into()).unwrap(),
2209            JsValue::from_f64(expected.into())
2210        );
2211    }
2212
2213    #[async_test]
2214    fn test_needs_backup_is_serialized_as_a_u8_in_js() {
2215        let session_needs_backup = super::unit_tests::backup_test_session(true);
2216
2217        let js_value = serde_wasm_bindgen::to_value(&session_needs_backup).unwrap();
2218
2219        assert!(js_value.is_object());
2220        assert_field_equals(&js_value, "needs_backup", 1);
2221    }
2222
2223    #[async_test]
2224    fn test_doesnt_need_backup_is_serialized_with_missing_field_in_js() {
2225        let session_backed_up = super::unit_tests::backup_test_session(false);
2226
2227        let js_value = serde_wasm_bindgen::to_value(&session_backed_up).unwrap();
2228
2229        assert!(!js_sys::Reflect::has(&js_value, &"needs_backup".into()).unwrap());
2230    }
2231
2232    #[async_test]
2233    async fn test_sender_key_and_device_type_are_serialized_in_js() {
2234        let sender_key = Curve25519PublicKey::from_bytes([0; 32]);
2235
2236        let sender_data = SenderData::device_info(DeviceKeys::new(
2237            owned_user_id!("@test:user"),
2238            owned_device_id!("ABC"),
2239            vec![],
2240            BTreeMap::new(),
2241            Signatures::new(),
2242        ));
2243        let db_object = sender_data_test_session(sender_key, sender_data).await;
2244
2245        let js_value = serde_wasm_bindgen::to_value(&db_object).unwrap();
2246
2247        assert!(js_value.is_object());
2248        assert_field_equals(&js_value, "sender_data_type", 2);
2249        assert_eq!(
2250            js_sys::Reflect::get(&js_value, &"sender_key".into()).unwrap(),
2251            JsValue::from_str("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
2252        );
2253    }
2254}
2255
2256#[cfg(all(test, target_family = "wasm"))]
2257mod tests {
2258    use matrix_sdk_crypto::cryptostore_integration_tests;
2259
2260    use super::IndexeddbCryptoStore;
2261
2262    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
2263
2264    async fn get_store(
2265        name: &str,
2266        passphrase: Option<&str>,
2267        clear_data: bool,
2268    ) -> IndexeddbCryptoStore {
2269        if clear_data {
2270            IndexeddbCryptoStore::delete_stores(name).unwrap();
2271        }
2272        match passphrase {
2273            Some(pass) => IndexeddbCryptoStore::open_with_passphrase(name, pass)
2274                .await
2275                .expect("Can't create a passphrase protected store"),
2276            None => IndexeddbCryptoStore::open_with_name(name)
2277                .await
2278                .expect("Can't create store without passphrase"),
2279        }
2280    }
2281
2282    cryptostore_integration_tests!();
2283}
2284
2285#[cfg(all(test, target_family = "wasm"))]
2286mod encrypted_tests {
2287    use matrix_sdk_crypto::{
2288        cryptostore_integration_tests,
2289        olm::Account,
2290        store::{CryptoStore, types::PendingChanges},
2291        vodozemac::base64_encode,
2292    };
2293    use matrix_sdk_test::async_test;
2294    use ruma::{device_id, user_id};
2295
2296    use super::IndexeddbCryptoStore;
2297
2298    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
2299
2300    async fn get_store(
2301        name: &str,
2302        passphrase: Option<&str>,
2303        clear_data: bool,
2304    ) -> IndexeddbCryptoStore {
2305        if clear_data {
2306            IndexeddbCryptoStore::delete_stores(name).unwrap();
2307        }
2308
2309        let pass = passphrase.unwrap_or(name);
2310        IndexeddbCryptoStore::open_with_passphrase(&name, pass)
2311            .await
2312            .expect("Can't create a passphrase protected store")
2313    }
2314    cryptostore_integration_tests!();
2315
2316    /// Test that we can migrate a store created with a passphrase, to being
2317    /// encrypted with a key instead.
2318    #[async_test]
2319    async fn test_migrate_passphrase_to_key() {
2320        let store_name = "test_migrate_passphrase_to_key";
2321        let passdata: [u8; 32] = rand::random();
2322        let b64_passdata = base64_encode(passdata);
2323
2324        // Initialise the store with some account data
2325        IndexeddbCryptoStore::delete_stores(store_name).unwrap();
2326        let store = IndexeddbCryptoStore::open_with_passphrase(&store_name, &b64_passdata)
2327            .await
2328            .expect("Can't create a passphrase-protected store");
2329
2330        store
2331            .save_pending_changes(PendingChanges {
2332                account: Some(Account::with_device_id(
2333                    user_id!("@alice:example.org"),
2334                    device_id!("ALICEDEVICE"),
2335                )),
2336            })
2337            .await
2338            .expect("Can't save account");
2339
2340        // Now reopen the store, passing the key directly rather than as a b64 string.
2341        let store = IndexeddbCryptoStore::open_with_key(&store_name, &passdata)
2342            .await
2343            .expect("Can't create a key-protected store");
2344        let loaded_account =
2345            store.load_account().await.expect("Can't load account").expect("Account was not saved");
2346        assert_eq!(loaded_account.user_id, user_id!("@alice:example.org"));
2347    }
2348}