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. The idea is to do
278/// all the serialization and encryption before the transaction, and then just
279/// do the actual Indexeddb operations in the transaction.
280struct PendingIndexeddbChanges {
281    /// A map of the object store names to the operations to perform on that
282    /// store.
283    store_to_key_values: BTreeMap<&'static str, Vec<PendingOperation>>,
284}
285
286/// Represents the changes on a single object store.
287struct PendingStoreChanges<'a> {
288    operations: &'a mut Vec<PendingOperation>,
289}
290
291impl PendingStoreChanges<'_> {
292    fn put(&mut self, key: JsValue, value: JsValue) {
293        self.operations.push(PendingOperation::Put { key, value });
294    }
295
296    fn delete(&mut self, key: JsValue) {
297        self.operations.push(PendingOperation::Delete(key));
298    }
299
300    fn delete_by_index(&mut self, index: &'static str, key: JsValue) {
301        self.operations.push(PendingOperation::DeleteByIndex { index, key });
302    }
303}
304
305impl PendingIndexeddbChanges {
306    fn get(&mut self, store: &'static str) -> PendingStoreChanges<'_> {
307        PendingStoreChanges { operations: self.store_to_key_values.entry(store).or_default() }
308    }
309}
310
311impl PendingIndexeddbChanges {
312    fn new() -> Self {
313        Self { store_to_key_values: BTreeMap::new() }
314    }
315
316    /// Returns the list of stores that have pending operations. Should be used
317    /// as the list of store names when starting the indexeddb transaction
318    /// (`transaction_on_multi_with_mode`).
319    fn touched_stores(&self) -> Vec<&str> {
320        self.store_to_key_values
321            .iter()
322            .filter_map(
323                |(store, pending_operations)| {
324                    if !pending_operations.is_empty() { Some(*store) } else { None }
325                },
326            )
327            .collect()
328    }
329
330    /// Applies all the pending operations to the store.
331    async fn apply(self, tx: &Transaction<'_>) -> Result<()> {
332        for (store, operations) in self.store_to_key_values {
333            if operations.is_empty() {
334                continue;
335            }
336            let object_store = tx.object_store(store)?;
337            for op in operations {
338                match op {
339                    PendingOperation::Put { key, value } => {
340                        object_store.put(&value).with_key(key).build()?;
341                    }
342                    PendingOperation::Delete(key) => {
343                        object_store.delete(&key).build()?;
344                    }
345                    PendingOperation::DeleteByIndex { index, key } => {
346                        let range = KeyRange::Only(key);
347                        let ids = object_store
348                            .index(index)?
349                            .get_all_keys::<JsValue>()
350                            .with_query::<JsValue, _>(range)
351                            .await?;
352                        for id in ids {
353                            object_store.delete(id.unwrap()).await?;
354                        }
355                    }
356                }
357            }
358        }
359        Ok(())
360    }
361}
362
363impl IndexeddbCryptoStore {
364    pub(crate) async fn open_with_store_cipher(
365        prefix: &str,
366        store_cipher: Option<Arc<StoreCipher>>,
367    ) -> Result<Self> {
368        let name = format!("{prefix:0}::matrix-sdk-crypto");
369
370        let serializer = SafeEncodeSerializer::new(store_cipher);
371        debug!("IndexedDbCryptoStore: opening main store {name}");
372        let db = open_and_upgrade_db(&name, &serializer).await?;
373
374        Ok(Self {
375            name,
376            inner: db,
377            serializer,
378            static_account: RwLock::new(None),
379            save_changes_lock: Default::default(),
380        })
381    }
382
383    /// Open a new `IndexeddbCryptoStore` with default name and no passphrase
384    pub async fn open() -> Result<Self> {
385        IndexeddbCryptoStore::open_with_store_cipher("crypto", None).await
386    }
387
388    /// Open an `IndexeddbCryptoStore` with given name and passphrase.
389    ///
390    /// If the store previously existed, the encryption cipher is initialised
391    /// using the given passphrase and the details from the meta store. If the
392    /// store did not previously exist, a new encryption cipher is derived from
393    /// the passphrase, and the details are stored to the metastore.
394    ///
395    /// The store is then opened, or a new one created, using the encryption
396    /// cipher.
397    ///
398    /// # Arguments
399    ///
400    /// - `prefix` - Common prefix for the names of the two IndexedDB stores.
401    /// - `passphrase` - Passphrase which is used to derive a key to encrypt the
402    ///   key which is used to encrypt the store. Must be the same each time the
403    ///   store is opened.
404    pub async fn open_with_passphrase(prefix: &str, passphrase: &str) -> Result<Self> {
405        let db = open_meta_db(prefix).await?;
406        let store_cipher = load_store_cipher(&db).await?;
407
408        let store_cipher = match store_cipher {
409            Some(cipher) => {
410                debug!("IndexedDbCryptoStore: decrypting store cipher");
411                StoreCipher::import(passphrase, &cipher)
412                    .map_err(|_| CryptoStoreError::UnpicklingError)?
413            }
414            None => {
415                debug!("IndexedDbCryptoStore: encrypting new store cipher");
416                let cipher = StoreCipher::new().map_err(CryptoStoreError::backend)?;
417                #[cfg(not(test))]
418                let export = cipher.export(passphrase);
419                #[cfg(test)]
420                let export = cipher._insecure_export_fast_for_testing(passphrase);
421
422                let export = export.map_err(CryptoStoreError::backend)?;
423
424                save_store_cipher(&db, &export).await?;
425                cipher
426            }
427        };
428
429        // Must release the database access manually as it's not done when
430        // dropping it.
431        db.close();
432
433        IndexeddbCryptoStore::open_with_store_cipher(prefix, Some(store_cipher.into())).await
434    }
435
436    /// Open an `IndexeddbCryptoStore` with given name and key.
437    ///
438    /// If the store previously existed, the encryption cipher is initialised
439    /// using the given key and the details from the meta store. If the store
440    /// did not previously exist, a new encryption cipher is derived from the
441    /// passphrase, and the details are stored to the metastore.
442    ///
443    /// The store is then opened, or a new one created, using the encryption
444    /// cipher.
445    ///
446    /// # Arguments
447    ///
448    /// - `prefix` - Common prefix for the names of the two IndexedDB stores.
449    /// - `key` - Key with which to encrypt the key which is used to encrypt the
450    ///   store. Must be the same each time the store is opened.
451    pub async fn open_with_key(prefix: &str, key: &[u8; 32]) -> Result<Self> {
452        // The application might also use the provided key for something else,
453        // so to avoid key reuse, we pass the provided key through an HKDF
454        let mut chacha_key = zeroize::Zeroizing::new([0u8; 32]);
455        const HKDF_INFO: &[u8] = b"CRYPTOSTORE_CIPHER";
456        let hkdf = Hkdf::<Sha256>::new(None, key);
457        hkdf.expand(HKDF_INFO, &mut *chacha_key)
458            .expect("We should be able to generate a 32-byte key");
459
460        let db = open_meta_db(prefix).await?;
461        let store_cipher = load_store_cipher(&db).await?;
462
463        let store_cipher = match store_cipher {
464            Some(cipher) => {
465                debug!("IndexedDbCryptoStore: decrypting store cipher");
466                import_store_cipher_with_key(&chacha_key, key, &cipher, &db).await?
467            }
468            None => {
469                debug!("IndexedDbCryptoStore: encrypting new store cipher");
470                let cipher = StoreCipher::new().map_err(CryptoStoreError::backend)?;
471                let export = cipher
472                    .export_with_key(chacha_key.as_slice())
473                    .map_err(CryptoStoreError::backend)?;
474                save_store_cipher(&db, &export).await?;
475                cipher
476            }
477        };
478
479        // Must release the database access manually as it's not done when
480        // dropping it.
481        db.close();
482
483        IndexeddbCryptoStore::open_with_store_cipher(prefix, Some(store_cipher.into())).await
484    }
485
486    /// Open a new `IndexeddbCryptoStore` with given name and no passphrase
487    pub async fn open_with_name(name: &str) -> Result<Self> {
488        IndexeddbCryptoStore::open_with_store_cipher(name, None).await
489    }
490
491    /// Delete the IndexedDB databases for the given name.
492    #[cfg(test)]
493    pub fn delete_stores(prefix: &str) -> Result<()> {
494        Database::delete_by_name(&format!("{prefix:0}::matrix-sdk-crypto-meta"))?;
495        Database::delete_by_name(&format!("{prefix:0}::matrix-sdk-crypto"))?;
496        Ok(())
497    }
498
499    fn get_static_account(&self) -> Option<StaticAccountData> {
500        self.static_account.read().unwrap().clone()
501    }
502
503    /// Transform an [`InboundGroupSession`] into a `JsValue` holding a
504    /// [`InboundGroupSessionIndexedDbObject`], ready for storing.
505    async fn serialize_inbound_group_session(
506        &self,
507        session: &InboundGroupSession,
508    ) -> Result<JsValue> {
509        let obj =
510            InboundGroupSessionIndexedDbObject::from_session(session, &self.serializer).await?;
511        Ok(serde_wasm_bindgen::to_value(&obj)?)
512    }
513
514    /// Transform a JsValue holding a [`InboundGroupSessionIndexedDbObject`]
515    /// back into a [`InboundGroupSession`].
516    fn deserialize_inbound_group_session(
517        &self,
518        stored_value: JsValue,
519    ) -> Result<InboundGroupSession> {
520        let idb_object: InboundGroupSessionIndexedDbObject =
521            serde_wasm_bindgen::from_value(stored_value)?;
522        let pickled_session: PickledInboundGroupSession =
523            self.serializer.maybe_decrypt_value(idb_object.pickled_session)?;
524        let session = InboundGroupSession::from_pickle(pickled_session)
525            .map_err(|e| IndexeddbCryptoStoreError::CryptoStoreError(e.into()))?;
526
527        // Although a "backed up" flag is stored inside
528        // `idb_object.pickled_session`, it is not maintained when backups are
529        // reset. Overwrite the flag with the needs_backup value from the IDB
530        // 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
748                // to receive multiple secrets of the same name (indexeddb store
749                // entries must have a unique key), and allow the client to
750                // determine which one is the 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 impl
802// 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 the
807// 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
832        // points 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
870        // below, and we're pickling data as we go, so we don't want to
871        // invalidate data 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
911        // this 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
1220        // doesn't appear to be exposed
1221        // (https://github.com/Alorel/rust-indexed-db/issues/31). Instead we
1222        // replicate the behaviour with a cursor.
1223        let Some(mut cursor) = idx.open_cursor().await? else {
1224            return Ok(vec![]);
1225        };
1226
1227        let mut serialized_sessions = Vec::with_capacity(limit);
1228        for _ in 0..limit {
1229            let Some(value) = cursor.next_record().await? else {
1230                break;
1231            };
1232            serialized_sessions.push(value)
1233        }
1234
1235        tx.commit().await?;
1236
1237        // Deserialize and decrypt after the transaction is complete.
1238        let result = serialized_sessions
1239            .into_iter()
1240            .filter_map(|v| match self.deserialize_inbound_group_session(v) {
1241                Ok(session) => Some(session),
1242                Err(e) => {
1243                    warn!("Failed to deserialize inbound group session: {e}");
1244                    None
1245                }
1246            })
1247            .collect::<Vec<InboundGroupSession>>();
1248
1249        Ok(result)
1250    }
1251
1252    async fn mark_inbound_group_sessions_as_backed_up(
1253        &self,
1254        _backup_version: &str,
1255        room_and_session_ids: &[(&RoomId, &str)],
1256    ) -> Result<()> {
1257        let tx = self
1258            .inner
1259            .transaction(keys::INBOUND_GROUP_SESSIONS_V3)
1260            .with_mode(TransactionMode::Readwrite)
1261            .build()?;
1262
1263        let object_store = tx.object_store(keys::INBOUND_GROUP_SESSIONS_V3)?;
1264
1265        for (room_id, session_id) in room_and_session_ids {
1266            let key =
1267                self.serializer.encode_key(keys::INBOUND_GROUP_SESSIONS_V3, (room_id, session_id));
1268            if let Some(idb_object_js) = object_store.get(&key).await? {
1269                let mut idb_object: InboundGroupSessionIndexedDbObject =
1270                    serde_wasm_bindgen::from_value(idb_object_js)?;
1271                idb_object.needs_backup = false;
1272                object_store
1273                    .put(&serde_wasm_bindgen::to_value(&idb_object)?)
1274                    .with_key(key)
1275                    .build()?;
1276            } else {
1277                warn!(?key, "Could not find inbound group session to mark it as backed up.");
1278            }
1279        }
1280
1281        Ok(tx.commit().await?)
1282    }
1283
1284    async fn reset_backup_state(&self) -> Result<()> {
1285        let tx = self
1286            .inner
1287            .transaction(keys::INBOUND_GROUP_SESSIONS_V3)
1288            .with_mode(TransactionMode::Readwrite)
1289            .build()?;
1290
1291        if let Some(mut cursor) =
1292            tx.object_store(keys::INBOUND_GROUP_SESSIONS_V3)?.open_cursor().await?
1293        {
1294            while let Some(value) = cursor.next_record().await? {
1295                let mut idb_object: InboundGroupSessionIndexedDbObject =
1296                    serde_wasm_bindgen::from_value(value)?;
1297                if !idb_object.needs_backup {
1298                    idb_object.needs_backup = true;
1299                    // We don't bother to update the encrypted
1300                    // `InboundGroupSession` object stored inside
1301                    // `idb_object.data`, since that would require decryption
1302                    // and encryption. Instead, it will be patched up by
1303                    // `deserialize_inbound_group_session`.
1304                    let idb_object = serde_wasm_bindgen::to_value(&idb_object)?;
1305                    cursor.update(&idb_object).await?;
1306                }
1307            }
1308        }
1309
1310        Ok(tx.commit().await?)
1311    }
1312
1313    async fn save_tracked_users(&self, users: &[(&UserId, bool)]) -> Result<()> {
1314        let tx = self
1315            .inner
1316            .transaction(keys::TRACKED_USERS)
1317            .with_mode(TransactionMode::Readwrite)
1318            .build()?;
1319        let os = tx.object_store(keys::TRACKED_USERS)?;
1320
1321        for (user, dirty) in users {
1322            os.put(&JsValue::from(*dirty)).with_key(JsValue::from_str(user.as_str())).build()?;
1323        }
1324
1325        tx.commit().await?;
1326        Ok(())
1327    }
1328
1329    async fn get_device(
1330        &self,
1331        user_id: &UserId,
1332        device_id: &DeviceId,
1333    ) -> Result<Option<DeviceData>> {
1334        let key = self.serializer.encode_key(keys::DEVICES, (user_id, device_id));
1335        self.inner
1336            .transaction(keys::DEVICES)
1337            .with_mode(TransactionMode::Readonly)
1338            .build()?
1339            .object_store(keys::DEVICES)?
1340            .get(&key)
1341            .await?
1342            .map(|i| self.serializer.deserialize_value(i).map_err(Into::into))
1343            .transpose()
1344    }
1345
1346    async fn get_user_devices(
1347        &self,
1348        user_id: &UserId,
1349    ) -> Result<HashMap<OwnedDeviceId, DeviceData>> {
1350        let range = self.serializer.encode_to_range(keys::DEVICES, user_id);
1351        Ok(self
1352            .inner
1353            .transaction(keys::DEVICES)
1354            .with_mode(TransactionMode::Readonly)
1355            .build()?
1356            .object_store(keys::DEVICES)?
1357            .get_all()
1358            .with_query(&range)
1359            .await?
1360            .filter_map(Result::ok)
1361            .filter_map(|d| {
1362                let d: DeviceData = self.serializer.deserialize_value(d).ok()?;
1363                Some((d.device_id().to_owned(), d))
1364            })
1365            .collect::<HashMap<_, _>>())
1366    }
1367
1368    async fn get_own_device(&self) -> Result<DeviceData> {
1369        let account_info = self.get_static_account().ok_or(CryptoStoreError::AccountUnset)?;
1370        Ok(self.get_device(&account_info.user_id, &account_info.device_id).await?.unwrap())
1371    }
1372
1373    async fn get_user_identity(&self, user_id: &UserId) -> Result<Option<UserIdentityData>> {
1374        self.inner
1375            .transaction(keys::IDENTITIES)
1376            .with_mode(TransactionMode::Readonly)
1377            .build()?
1378            .object_store(keys::IDENTITIES)?
1379            .get(&self.serializer.encode_key(keys::IDENTITIES, user_id))
1380            .await?
1381            .map(|i| self.serializer.deserialize_value(i).map_err(Into::into))
1382            .transpose()
1383    }
1384
1385    async fn is_message_known(&self, hash: &OlmMessageHash) -> Result<bool> {
1386        Ok(self
1387            .inner
1388            .transaction(keys::OLM_HASHES)
1389            .with_mode(TransactionMode::Readonly)
1390            .build()?
1391            .object_store(keys::OLM_HASHES)?
1392            .get::<JsValue, _, _>(
1393                &self.serializer.encode_key(keys::OLM_HASHES, (&hash.sender_key, &hash.hash)),
1394            )
1395            .await?
1396            .is_some())
1397    }
1398
1399    async fn get_secrets_from_inbox(
1400        &self,
1401        secret_name: &SecretName,
1402    ) -> Result<Vec<zeroize::Zeroizing<String>>> {
1403        let range = self.serializer.encode_to_range(keys::SECRETS_INBOX_V2, secret_name.as_str());
1404
1405        self.inner
1406            .transaction(keys::SECRETS_INBOX_V2)
1407            .with_mode(TransactionMode::Readonly)
1408            .build()?
1409            .object_store(keys::SECRETS_INBOX_V2)?
1410            .get_all()
1411            .with_query(&range)
1412            .await?
1413            .map(|result| {
1414                let d = result?;
1415                let secret: String = self.serializer.deserialize_value(d)?;
1416                Ok(secret.into())
1417            })
1418            .collect()
1419    }
1420
1421    #[allow(clippy::unused_async)] // Mandated by trait on wasm.
1422    async fn delete_secrets_from_inbox(&self, secret_name: &SecretName) -> Result<()> {
1423        let range = self.serializer.encode_to_range(keys::SECRETS_INBOX_V2, secret_name.as_str());
1424
1425        let transaction = self
1426            .inner
1427            .transaction(keys::SECRETS_INBOX_V2)
1428            .with_mode(TransactionMode::Readwrite)
1429            .build()?;
1430        transaction.object_store(keys::SECRETS_INBOX_V2)?.delete(&range).build()?;
1431        transaction.commit().await?;
1432
1433        Ok(())
1434    }
1435
1436    async fn get_secret_request_by_info(
1437        &self,
1438        key_info: &SecretInfo,
1439    ) -> Result<Option<GossipRequest>> {
1440        let key = self.serializer.encode_key(keys::GOSSIP_REQUESTS, key_info.as_key());
1441
1442        let val = self
1443            .inner
1444            .transaction(keys::GOSSIP_REQUESTS)
1445            .with_mode(TransactionMode::Readonly)
1446            .build()?
1447            .object_store(keys::GOSSIP_REQUESTS)?
1448            .index(keys::GOSSIP_REQUESTS_BY_INFO_INDEX)?
1449            .get(key)
1450            .await?;
1451
1452        if let Some(val) = val {
1453            let deser = self.deserialize_gossip_request(val)?;
1454            Ok(Some(deser))
1455        } else {
1456            Ok(None)
1457        }
1458    }
1459
1460    async fn get_unsent_secret_requests(&self) -> Result<Vec<GossipRequest>> {
1461        let results = self
1462            .inner
1463            .transaction(keys::GOSSIP_REQUESTS)
1464            .with_mode(TransactionMode::Readonly)
1465            .build()?
1466            .object_store(keys::GOSSIP_REQUESTS)?
1467            .index(keys::GOSSIP_REQUESTS_UNSENT_INDEX)?
1468            .get_all()
1469            .await?
1470            .filter_map(Result::ok)
1471            .filter_map(|val| self.deserialize_gossip_request(val).ok())
1472            .collect();
1473
1474        Ok(results)
1475    }
1476
1477    async fn delete_outgoing_secret_requests(&self, request_id: &TransactionId) -> Result<()> {
1478        let jskey = self.serializer.encode_key(keys::GOSSIP_REQUESTS, request_id);
1479        let tx = self
1480            .inner
1481            .transaction(keys::GOSSIP_REQUESTS)
1482            .with_mode(TransactionMode::Readwrite)
1483            .build()?;
1484        tx.object_store(keys::GOSSIP_REQUESTS)?.delete(jskey).build()?;
1485        tx.commit().await.map_err(|e| e.into())
1486    }
1487
1488    async fn load_backup_keys(&self) -> Result<BackupKeys> {
1489        let key = {
1490            let tx = self
1491                .inner
1492                .transaction(keys::BACKUP_KEYS)
1493                .with_mode(TransactionMode::Readonly)
1494                .build()?;
1495            let store = tx.object_store(keys::BACKUP_KEYS)?;
1496
1497            let backup_version = store
1498                .get(&JsValue::from_str(keys::BACKUP_VERSION_V1))
1499                .await?
1500                .map(|i| self.serializer.deserialize_value(i))
1501                .transpose()?;
1502
1503            let decryption_key = store
1504                .get(&JsValue::from_str(keys::RECOVERY_KEY_V1))
1505                .await?
1506                .map(|i| self.serializer.deserialize_value(i))
1507                .transpose()?;
1508
1509            BackupKeys { backup_version, decryption_key }
1510        };
1511
1512        Ok(key)
1513    }
1514
1515    async fn load_dehydrated_device_pickle_key(&self) -> Result<Option<DehydratedDeviceKey>> {
1516        if let Some(pickle) = self
1517            .inner
1518            .transaction(keys::CORE)
1519            .with_mode(TransactionMode::Readonly)
1520            .build()?
1521            .object_store(keys::CORE)?
1522            .get(&JsValue::from_str(keys::DEHYDRATION_PICKLE_KEY))
1523            .await?
1524        {
1525            let pickle: DehydratedDeviceKey = self.serializer.deserialize_value(pickle)?;
1526
1527            Ok(Some(pickle))
1528        } else {
1529            Ok(None)
1530        }
1531    }
1532
1533    async fn delete_dehydrated_device_pickle_key(&self) -> Result<()> {
1534        self.remove_custom_value(keys::DEHYDRATION_PICKLE_KEY).await?;
1535        Ok(())
1536    }
1537
1538    async fn get_withheld_info(
1539        &self,
1540        room_id: &RoomId,
1541        session_id: &str,
1542    ) -> Result<Option<RoomKeyWithheldEntry>> {
1543        let key = self.serializer.encode_key(keys::WITHHELD_SESSIONS, (room_id, session_id));
1544        if let Some(pickle) = self
1545            .inner
1546            .transaction(keys::WITHHELD_SESSIONS)
1547            .with_mode(TransactionMode::Readonly)
1548            .build()?
1549            .object_store(keys::WITHHELD_SESSIONS)?
1550            .get(&key)
1551            .await?
1552        {
1553            let info = self.serializer.deserialize_value(pickle)?;
1554            Ok(Some(info))
1555        } else {
1556            Ok(None)
1557        }
1558    }
1559
1560    async fn get_withheld_sessions_by_room_id(
1561        &self,
1562        room_id: &RoomId,
1563    ) -> Result<Vec<RoomKeyWithheldEntry>> {
1564        let range = self.serializer.encode_to_range(keys::WITHHELD_SESSIONS, room_id);
1565
1566        self
1567            .inner
1568            .transaction(keys::WITHHELD_SESSIONS)
1569            .with_mode(TransactionMode::Readonly)
1570            .build()?
1571            .object_store(keys::WITHHELD_SESSIONS)?
1572            .get_all()
1573            .with_query(&range)
1574            .await?
1575            .map(|val| self.serializer.deserialize_value(val?).map_err(Into::into))
1576            .collect()
1577    }
1578
1579    async fn get_room_settings(&self, room_id: &RoomId) -> Result<Option<RoomSettings>> {
1580        let key = self.serializer.encode_key(keys::ROOM_SETTINGS, room_id);
1581        self.inner
1582            .transaction(keys::ROOM_SETTINGS)
1583            .with_mode(TransactionMode::Readonly)
1584            .build()?
1585            .object_store(keys::ROOM_SETTINGS)?
1586            .get(&key)
1587            .await?
1588            .map(|v| self.serializer.deserialize_value(v).map_err(Into::into))
1589            .transpose()
1590    }
1591
1592    async fn get_received_room_key_bundle_data(
1593        &self,
1594        room_id: &RoomId,
1595        user_id: &UserId,
1596    ) -> Result<Option<StoredRoomKeyBundleData>> {
1597        let key = self.serializer.encode_key(keys::RECEIVED_ROOM_KEY_BUNDLES, (room_id, user_id));
1598        let result = self
1599            .inner
1600            .transaction(keys::RECEIVED_ROOM_KEY_BUNDLES)
1601            .with_mode(TransactionMode::Readonly)
1602            .build()?
1603            .object_store(keys::RECEIVED_ROOM_KEY_BUNDLES)?
1604            .get(&key)
1605            .await?
1606            .map(|v| self.serializer.deserialize_value(v))
1607            .transpose()?;
1608
1609        Ok(result)
1610    }
1611
1612    async fn has_downloaded_all_room_keys(&self, room_id: &RoomId) -> Result<bool> {
1613        let key = self.serializer.encode_key(keys::ROOM_KEY_BACKUPS_FULLY_DOWNLOADED, room_id);
1614        let result = self
1615            .inner
1616            .transaction(keys::ROOM_KEY_BACKUPS_FULLY_DOWNLOADED)
1617            .with_mode(TransactionMode::Readonly)
1618            .build()?
1619            .object_store(keys::ROOM_KEY_BACKUPS_FULLY_DOWNLOADED)?
1620            .get::<JsValue, _, _>(&key)
1621            .await?
1622            .is_some();
1623
1624        Ok(result)
1625    }
1626
1627    async fn get_pending_key_bundle_details_for_room(&self, room_id: &RoomId) -> Result<Option<RoomPendingKeyBundleDetails >> {
1628        let key = self.serializer.encode_key(keys::ROOMS_PENDING_KEY_BUNDLE, room_id);
1629        let result = self
1630            .inner
1631            .transaction(keys::ROOMS_PENDING_KEY_BUNDLE)
1632            .with_mode(TransactionMode::Readonly)
1633            .build()?
1634            .object_store(keys::ROOMS_PENDING_KEY_BUNDLE)?
1635            .get(&key)
1636            .await?
1637            .map(|v| self.serializer.deserialize_value(v))
1638            .transpose()?;
1639        Ok(result)
1640    }
1641
1642    async fn get_all_rooms_pending_key_bundles(&self) -> Result<Vec<RoomPendingKeyBundleDetails>> {
1643        let result = self
1644            .inner
1645            .transaction(keys::ROOMS_PENDING_KEY_BUNDLE)
1646            .with_mode(TransactionMode::Readonly)
1647            .build()?
1648            .object_store(keys::ROOMS_PENDING_KEY_BUNDLE)?
1649            .get_all()
1650            .await?
1651            .map(|result| {
1652                result
1653                    .map_err(Into::into)
1654                    .and_then(|v| self.serializer.deserialize_value(v).map_err(Into::into))
1655            })
1656            .collect::<Result<Vec<_>>>()?;
1657        Ok(result)
1658    }
1659
1660    async fn get_custom_value(&self, key: &str) -> Result<Option<Vec<u8>>> {
1661        self.inner
1662            .transaction(keys::CORE)
1663            .with_mode(TransactionMode::Readonly)
1664            .build()?
1665            .object_store(keys::CORE)?
1666            .get(&JsValue::from_str(key))
1667            .await?
1668            .map(|v| self.serializer.deserialize_value(v).map_err(Into::into))
1669            .transpose()
1670    }
1671
1672    #[allow(clippy::unused_async)] // Mandated by trait on wasm.
1673    async fn set_custom_value(&self, key: &str, value: Vec<u8>) -> Result<()> {
1674        let transaction =
1675            self.inner.transaction(keys::CORE).with_mode(TransactionMode::Readwrite).build()?;
1676        transaction
1677            .object_store(keys::CORE)?
1678            .put(&self.serializer.serialize_value(&value)?)
1679            .with_key(JsValue::from_str(key))
1680            .build()?;
1681        transaction.commit().await?;
1682        Ok(())
1683    }
1684
1685    #[allow(clippy::unused_async)] // Mandated by trait on wasm.
1686    async fn remove_custom_value(&self, key: &str) -> Result<()> {
1687        let transaction =
1688            self.inner.transaction(keys::CORE).with_mode(TransactionMode::Readwrite).build()?;
1689        transaction.object_store(keys::CORE)?.delete(&JsValue::from_str(key)).build()?;
1690        transaction.commit().await?;
1691        Ok(())
1692    }
1693
1694    async fn try_take_leased_lock(
1695        &self,
1696        lease_duration_ms: u32,
1697        key: &str,
1698        holder: &str,
1699    ) -> Result<Option<CrossProcessLockGeneration>> {
1700        // As of 2023-06-23, the code below hasn't been tested yet.
1701        let key = JsValue::from_str(key);
1702        let txn = self
1703            .inner
1704            .transaction(keys::LEASE_LOCKS)
1705            .with_mode(TransactionMode::Readwrite)
1706            .build()?;
1707        let object_store = txn.object_store(keys::LEASE_LOCKS)?;
1708
1709        #[derive(Deserialize, Serialize)]
1710        struct Lease {
1711            holder: String,
1712            expiration: u64,
1713            generation: CrossProcessLockGeneration,
1714        }
1715
1716        let now: u64 = MilliSecondsSinceUnixEpoch::now().get().into();
1717        let expiration = now + lease_duration_ms as u64;
1718
1719        let lease = match object_store.get(&key).await? {
1720            Some(entry) => {
1721                let mut lease: Lease = self.serializer.deserialize_value(entry)?;
1722
1723                if lease.holder == holder {
1724                    // We had the lease before, extend it.
1725                    lease.expiration = expiration;
1726
1727                    Some(lease)
1728                } else {
1729                    // We didn't have it.
1730                    if lease.expiration < now {
1731                        // Steal it!
1732                        lease.holder = holder.to_owned();
1733                        lease.expiration = expiration;
1734                        lease.generation += 1;
1735
1736                        Some(lease)
1737                    } else {
1738                        // We tried our best.
1739                        None
1740                    }
1741                }
1742            }
1743            None => {
1744                let lease = Lease {
1745                    holder: holder.to_owned(),
1746                    expiration,
1747                    generation: FIRST_CROSS_PROCESS_LOCK_GENERATION,
1748                };
1749
1750                Some(lease)
1751            }
1752        };
1753
1754        Ok(if let Some(lease) = lease {
1755            object_store.put(&self.serializer.serialize_value(&lease)?).with_key(key).build()?;
1756
1757            Some(lease.generation)
1758        } else {
1759            None
1760        })
1761    }
1762
1763    #[allow(clippy::unused_async)]
1764    async fn get_size(&self) -> Result<Option<usize>> {
1765        Ok(None)
1766    }
1767
1768    #[allow(clippy::unused_async)]
1769    async fn close(&self) -> Result<()> {
1770        Ok(())
1771    }
1772
1773    #[allow(clippy::unused_async)]
1774    async fn reopen(&self) -> Result<()> {
1775        Ok(())
1776    }
1777}
1778
1779impl Drop for IndexeddbCryptoStore {
1780    fn drop(&mut self) {
1781        // Must release the database access manually as it's not done when
1782        // dropping it.
1783        self.inner.as_sys().close();
1784    }
1785}
1786
1787/// Open the meta store.
1788///
1789/// The meta store contains details about the encryption of the main store.
1790async fn open_meta_db(prefix: &str) -> Result<Database, IndexeddbCryptoStoreError> {
1791    let name = format!("{prefix:0}::matrix-sdk-crypto-meta");
1792
1793    debug!("IndexedDbCryptoStore: Opening meta-store {name}");
1794    Database::open(&name)
1795        .with_version(1u32)
1796        .with_on_upgrade_needed(|evt, tx| {
1797            let old_version = evt.old_version() as u32;
1798            if old_version < 1 {
1799                // migrating to version 1
1800                tx.db().create_object_store("matrix-sdk-crypto").build()?;
1801            }
1802            Ok(())
1803        })
1804        .await
1805        .map_err(Into::into)
1806}
1807
1808/// Load the serialised store cipher from the meta store.
1809///
1810/// # Arguments:
1811///
1812/// * `meta_db`: Connection to the meta store, as returned by [`open_meta_db`].
1813///
1814/// # Returns:
1815///
1816/// The serialised `StoreCipher` object.
1817async fn load_store_cipher(
1818    meta_db: &Database,
1819) -> Result<Option<Vec<u8>>, IndexeddbCryptoStoreError> {
1820    let tx: Transaction<'_> =
1821        meta_db.transaction("matrix-sdk-crypto").with_mode(TransactionMode::Readonly).build()?;
1822    let ob = tx.object_store("matrix-sdk-crypto")?;
1823
1824    let store_cipher: Option<Vec<u8>> = ob
1825        .get(&JsValue::from_str(keys::STORE_CIPHER))
1826        .await?
1827        .map(|k: JsValue| k.into_serde())
1828        .transpose()?;
1829    Ok(store_cipher)
1830}
1831
1832/// Save the serialised store cipher to the meta store.
1833///
1834/// # Arguments
1835///
1836/// - `meta_db`: Connection to the meta store, as returned by [`open_meta_db`].
1837/// - `store_cipher`: The serialised `StoreCipher` object.
1838async fn save_store_cipher(
1839    db: &Database,
1840    export: &Vec<u8>,
1841) -> Result<(), IndexeddbCryptoStoreError> {
1842    let tx: Transaction<'_> =
1843        db.transaction("matrix-sdk-crypto").with_mode(TransactionMode::Readwrite).build()?;
1844    let ob = tx.object_store("matrix-sdk-crypto")?;
1845
1846    ob.put(&JsValue::from_serde(&export)?)
1847        .with_key(JsValue::from_str(keys::STORE_CIPHER))
1848        .build()?;
1849    tx.commit().await?;
1850    Ok(())
1851}
1852
1853/// Given a serialised store cipher, try importing with the given key.
1854///
1855/// This is a helper for [`IndexeddbCryptoStore::open_with_key`].
1856///
1857/// # Arguments
1858///
1859/// - `chacha_key`: The key to use with [`StoreCipher::import_with_key`].
1860///   Derived from `original_key` via an HKDF.
1861/// - `original_key`: The key provided by the application. Used to provide a
1862///   migration path from an older key derivation system.
1863/// - `serialised_cipher`: The serialized `EncryptedStoreCipher`, retrieved from
1864///   the database.
1865/// - `db`: Connection to the database.
1866async fn import_store_cipher_with_key(
1867    chacha_key: &[u8; 32],
1868    original_key: &[u8],
1869    serialised_cipher: &[u8],
1870    db: &Database,
1871) -> Result<StoreCipher, IndexeddbCryptoStoreError> {
1872    let cipher = match StoreCipher::import_with_key(chacha_key, serialised_cipher) {
1873        Ok(cipher) => cipher,
1874        Err(matrix_sdk_store_encryption::Error::KdfMismatch) => {
1875            // Old versions of the matrix-js-sdk used to base64-encode their
1876            // encryption key, and pass it into
1877            // [`IndexeddbCryptoStore::open_with_passphrase`]. For backwards
1878            // compatibility, we fall back to that if we discover we have a
1879            // cipher encrypted with a KDF when we expected it to be encrypted
1880            // directly with a key.
1881            let cipher = StoreCipher::import(&base64_encode(original_key), serialised_cipher)
1882                .map_err(|_| CryptoStoreError::UnpicklingError)?;
1883
1884            // Loading the cipher with the passphrase was successful. Let's
1885            // update the stored version of the cipher so that it is encrypted
1886            // with a key, to save doing this again.
1887            debug!(
1888                "IndexedDbCryptoStore: Migrating passphrase-encrypted store cipher to key-encryption"
1889            );
1890
1891            let export = cipher.export_with_key(chacha_key).map_err(CryptoStoreError::backend)?;
1892            save_store_cipher(db, &export).await?;
1893            cipher
1894        }
1895        Err(_) => Err(CryptoStoreError::UnpicklingError)?,
1896    };
1897    Ok(cipher)
1898}
1899
1900/// Fetch items from an object store in batches, transform each item using the
1901/// supplied function, and stuff the transformed items into a single vector to
1902/// return.
1903async fn fetch_from_object_store_batched<R, F>(
1904    object_store: ObjectStore<'_>,
1905    f: F,
1906    batch_size: usize,
1907) -> Result<Vec<R>>
1908where
1909    F: Fn(JsValue) -> Result<R>,
1910{
1911    let mut result = Vec::new();
1912    let mut batch_n = 0;
1913
1914    // The empty string is before all keys in Indexed DB - first batch starts
1915    // there.
1916    let mut latest_key: JsValue = "".into();
1917
1918    loop {
1919        debug!("Fetching Indexed DB records starting from {}", batch_n * batch_size);
1920
1921        // See https://github.com/Alorel/rust-indexed-db/issues/31 - we would
1922        // like to use `get_all_with_key_and_limit` if it ever exists but for
1923        // now we use a cursor and manually limit batch size.
1924
1925        // Get hold of a cursor for this batch. (This should not panic in
1926        // expect() because we always use "", or the result of cursor.key(),
1927        // both of which are valid keys.)
1928        let after_latest_key = KeyRange::LowerBound(&latest_key, true);
1929        let cursor = object_store.open_cursor().with_query(&after_latest_key).await?;
1930
1931        // Fetch batch_size records into result
1932        let next_key = fetch_batch(cursor, batch_size, &f, &mut result).await?;
1933        if let Some(next_key) = next_key {
1934            latest_key = next_key;
1935        } else {
1936            break;
1937        }
1938
1939        batch_n += 1;
1940    }
1941
1942    Ok(result)
1943}
1944
1945/// Fetch batch_size records from the supplied cursor, and return the last key
1946/// we processed, or None if we reached the end of the cursor.
1947async fn fetch_batch<R, F, Q>(
1948    cursor: Option<Cursor<'_, Q>>,
1949    batch_size: usize,
1950    f: &F,
1951    result: &mut Vec<R>,
1952) -> Result<Option<JsValue>>
1953where
1954    F: Fn(JsValue) -> Result<R>,
1955    Q: QuerySource,
1956{
1957    let Some(mut cursor) = cursor else {
1958        // Cursor was None - there are no more records
1959        return Ok(None);
1960    };
1961
1962    let mut latest_key = None;
1963
1964    for _ in 0..batch_size {
1965        let Some(value) = cursor.next_record().await? else {
1966            return Ok(None);
1967        };
1968
1969        // Process the record
1970        let processed = f(value);
1971        if let Ok(processed) = processed {
1972            result.push(processed);
1973        }
1974        // else processing failed: don't return this record at all
1975
1976        // Remember that we have processed this record, so if we hit the end of
1977        // the batch, the next batch can start after this one
1978        if let Some(key) = cursor.key()? {
1979            latest_key = Some(key);
1980        }
1981    }
1982
1983    // We finished the batch but there are more records - return the key of the
1984    // last one we processed
1985    Ok(latest_key)
1986}
1987
1988/// The objects we store in the gossip_requests indexeddb object store
1989#[derive(Debug, Serialize, Deserialize)]
1990struct GossipRequestIndexedDbObject {
1991    /// Encrypted hash of the [`SecretInfo`] structure.
1992    info: String,
1993
1994    /// Encrypted serialised representation of the [`GossipRequest`] as a whole.
1995    request: Vec<u8>,
1996
1997    /// Whether the request has yet to be sent out.
1998    ///
1999    /// Since we only need to be able to find requests where this is `true`, we
2000    /// skip serialization in cases where it is `false`. That has the effect of
2001    /// omitting it from the indexeddb index.
2002    ///
2003    /// We also use a custom serializer because bools can't be used as keys in
2004    /// indexeddb.
2005    #[serde(
2006        default,
2007        skip_serializing_if = "std::ops::Not::not",
2008        with = "crate::serializer::foreign::bool"
2009    )]
2010    unsent: bool,
2011}
2012
2013/// The objects we store in the inbound_group_sessions3 indexeddb object store
2014#[derive(Serialize, Deserialize)]
2015struct InboundGroupSessionIndexedDbObject {
2016    /// Possibly encrypted
2017    /// [`matrix_sdk_crypto::olm::group_sessions::PickledInboundGroupSession`]
2018    pickled_session: MaybeEncrypted,
2019
2020    /// The (hashed) session ID of this session. This is somewhat redundant, but
2021    /// we have to pull it out to its own object so that we can do batched
2022    /// queries such as
2023    /// [`IndexeddbStore::get_inbound_group_sessions_for_device_batch`].
2024    ///
2025    /// Added in database schema v12, and lazily populated, so it is only
2026    /// present for sessions received or modified since DB schema v12.
2027    #[serde(default, skip_serializing_if = "Option::is_none")]
2028    session_id: Option<String>,
2029
2030    /// Whether the session data has yet to be backed up.
2031    ///
2032    /// Since we only need to be able to find entries where this is `true`, we
2033    /// skip serialization in cases where it is `false`. That has the effect of
2034    /// omitting it from the indexeddb index.
2035    ///
2036    /// We also use a custom serializer because bools can't be used as keys in
2037    /// indexeddb.
2038    #[serde(
2039        default,
2040        skip_serializing_if = "std::ops::Not::not",
2041        with = "crate::serializer::foreign::bool"
2042    )]
2043    needs_backup: bool,
2044
2045    /// Unused: for future compatibility. In future, will contain the order
2046    /// number (not the ID!) of the backup for which this key has been backed
2047    /// up. This will replace `needs_backup`, fixing the performance problem
2048    /// identified in https://github.com/element-hq/element-web/issues/26892
2049    /// because we won't need to update all records when we spot a new backup
2050    /// version. In this version of the code, this is always set to -1, meaning:
2051    /// "refer to the `needs_backup` property". See:
2052    /// https://github.com/element-hq/element-web/issues/26892#issuecomment-1906336076
2053    backed_up_to: i32,
2054
2055    /// The (hashed) curve25519 key of the device that sent us this room key,
2056    /// base64-encoded.
2057    ///
2058    /// Added in database schema v12, and lazily populated, so it is only
2059    /// present for sessions received or modified since DB schema v12.
2060    #[serde(default, skip_serializing_if = "Option::is_none")]
2061    sender_key: Option<String>,
2062
2063    /// The type of the [`SenderData`] within this session, converted to a u8
2064    /// from [`SenderDataType`].
2065    ///
2066    /// Added in database schema v12, and lazily populated, so it is only
2067    /// present for sessions received or modified since DB schema v12.
2068    #[serde(default, skip_serializing_if = "Option::is_none")]
2069    sender_data_type: Option<u8>,
2070}
2071
2072impl InboundGroupSessionIndexedDbObject {
2073    /// Build an [`InboundGroupSessionIndexedDbObject`] wrapping the given
2074    /// session.
2075    pub async fn from_session(
2076        session: &InboundGroupSession,
2077        serializer: &SafeEncodeSerializer,
2078    ) -> Result<Self, CryptoStoreError> {
2079        let session_id =
2080            serializer.encode_key_as_string(keys::INBOUND_GROUP_SESSIONS_V3, session.session_id());
2081
2082        let sender_key = serializer.encode_key_as_string(
2083            keys::INBOUND_GROUP_SESSIONS_V3,
2084            session.sender_key().to_base64(),
2085        );
2086
2087        Ok(InboundGroupSessionIndexedDbObject {
2088            pickled_session: serializer.maybe_encrypt_value(session.pickle().await)?,
2089            session_id: Some(session_id),
2090            needs_backup: !session.backed_up(),
2091            backed_up_to: -1,
2092            sender_key: Some(sender_key),
2093            sender_data_type: Some(session.sender_data_type() as u8),
2094        })
2095    }
2096}
2097
2098#[cfg(test)]
2099mod unit_tests {
2100    use matrix_sdk_crypto::{
2101        olm::{Curve25519PublicKey, InboundGroupSession, SenderData, SessionKey},
2102        types::EventEncryptionAlgorithm,
2103        vodozemac::Ed25519Keypair,
2104    };
2105    use matrix_sdk_store_encryption::EncryptedValueBase64;
2106    use matrix_sdk_test::async_test;
2107    use ruma::{device_id, room_id, user_id};
2108
2109    use super::InboundGroupSessionIndexedDbObject;
2110    use crate::serializer::{MaybeEncrypted, SafeEncodeSerializer};
2111
2112    #[test]
2113    fn needs_backup_is_serialized_as_a_u8_in_json() {
2114        let session_needs_backup = backup_test_session(true);
2115
2116        // Testing the exact JSON here is theoretically flaky in the face of
2117        // serialization changes in serde_json but it seems unlikely, and it's
2118        // simple enough to fix if we need to.
2119        assert!(
2120            serde_json::to_string(&session_needs_backup).unwrap().contains(r#""needs_backup":1"#),
2121        );
2122    }
2123
2124    #[test]
2125    fn doesnt_need_backup_is_serialized_with_missing_field_in_json() {
2126        let session_backed_up = backup_test_session(false);
2127
2128        assert!(
2129            !serde_json::to_string(&session_backed_up).unwrap().contains("needs_backup"),
2130            "The needs_backup field should be missing!"
2131        );
2132    }
2133
2134    pub fn backup_test_session(needs_backup: bool) -> InboundGroupSessionIndexedDbObject {
2135        InboundGroupSessionIndexedDbObject {
2136            pickled_session: MaybeEncrypted::Encrypted(EncryptedValueBase64::new(1, "", "")),
2137            session_id: None,
2138            needs_backup,
2139            backed_up_to: -1,
2140            sender_key: None,
2141            sender_data_type: None,
2142        }
2143    }
2144
2145    #[async_test]
2146    async fn test_sender_key_and_sender_data_type_are_serialized_in_json() {
2147        let sender_key = Curve25519PublicKey::from_bytes([0; 32]);
2148
2149        let sender_data = SenderData::sender_verified(
2150            user_id!("@test:user"),
2151            device_id!("ABC"),
2152            Ed25519Keypair::new().public_key(),
2153        );
2154
2155        let db_object = sender_data_test_session(sender_key, sender_data).await;
2156        let serialized = serde_json::to_string(&db_object).unwrap();
2157
2158        assert!(
2159            serialized.contains(r#""sender_key":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA""#)
2160        );
2161        assert!(serialized.contains(r#""sender_data_type":5"#));
2162    }
2163
2164    pub async fn sender_data_test_session(
2165        sender_key: Curve25519PublicKey,
2166        sender_data: SenderData,
2167    ) -> InboundGroupSessionIndexedDbObject {
2168        let session = InboundGroupSession::new(
2169            sender_key,
2170            Ed25519Keypair::new().public_key(),
2171            room_id!("!test:localhost"),
2172            // Arbitrary session data
2173            &SessionKey::from_base64(
2174                "AgAAAABTyn3CR8mzAxhsHH88td5DrRqfipJCnNbZeMrfzhON6O1Cyr9ewx/sDFLO6\
2175                 +NvyW92yGvMub7nuAEQb+SgnZLm7nwvuVvJgSZKpoJMVliwg8iY9TXKFT286oBtT2\
2176                 /8idy6TcpKax4foSHdMYlZXu5zOsGDdd9eYnYHpUEyDT0utuiaakZM3XBMNLEVDj9\
2177                 Ps929j1FGgne1bDeFVoty2UAOQK8s/0JJigbKSu6wQ/SzaCYpE/LD4Egk2Nxs1JE2\
2178                 33ii9J8RGPYOp7QWl0kTEc8mAlqZL7mKppo9AwgtmYweAg",
2179            )
2180            .unwrap(),
2181            sender_data,
2182            None,
2183            EventEncryptionAlgorithm::MegolmV1AesSha2,
2184            None,
2185            false,
2186        )
2187        .unwrap();
2188
2189        InboundGroupSessionIndexedDbObject::from_session(&session, &SafeEncodeSerializer::new(None))
2190            .await
2191            .unwrap()
2192    }
2193}
2194
2195#[cfg(all(test, target_family = "wasm"))]
2196mod wasm_unit_tests {
2197    use std::collections::BTreeMap;
2198
2199    use matrix_sdk_crypto::{
2200        olm::{Curve25519PublicKey, SenderData},
2201        types::{DeviceKeys, Signatures},
2202    };
2203    use matrix_sdk_test::async_test;
2204    use ruma::{owned_device_id, owned_user_id};
2205    use wasm_bindgen::JsValue;
2206
2207    use crate::crypto_store::unit_tests::sender_data_test_session;
2208
2209    fn assert_field_equals(js_value: &JsValue, field: &str, expected: u32) {
2210        assert_eq!(
2211            js_sys::Reflect::get(&js_value, &field.into()).unwrap(),
2212            JsValue::from_f64(expected.into())
2213        );
2214    }
2215
2216    #[async_test]
2217    fn test_needs_backup_is_serialized_as_a_u8_in_js() {
2218        let session_needs_backup = super::unit_tests::backup_test_session(true);
2219
2220        let js_value = serde_wasm_bindgen::to_value(&session_needs_backup).unwrap();
2221
2222        assert!(js_value.is_object());
2223        assert_field_equals(&js_value, "needs_backup", 1);
2224    }
2225
2226    #[async_test]
2227    fn test_doesnt_need_backup_is_serialized_with_missing_field_in_js() {
2228        let session_backed_up = super::unit_tests::backup_test_session(false);
2229
2230        let js_value = serde_wasm_bindgen::to_value(&session_backed_up).unwrap();
2231
2232        assert!(!js_sys::Reflect::has(&js_value, &"needs_backup".into()).unwrap());
2233    }
2234
2235    #[async_test]
2236    async fn test_sender_key_and_device_type_are_serialized_in_js() {
2237        let sender_key = Curve25519PublicKey::from_bytes([0; 32]);
2238
2239        let sender_data = SenderData::device_info(DeviceKeys::new(
2240            owned_user_id!("@test:user"),
2241            owned_device_id!("ABC"),
2242            vec![],
2243            BTreeMap::new(),
2244            Signatures::new(),
2245        ));
2246        let db_object = sender_data_test_session(sender_key, sender_data).await;
2247
2248        let js_value = serde_wasm_bindgen::to_value(&db_object).unwrap();
2249
2250        assert!(js_value.is_object());
2251        assert_field_equals(&js_value, "sender_data_type", 2);
2252        assert_eq!(
2253            js_sys::Reflect::get(&js_value, &"sender_key".into()).unwrap(),
2254            JsValue::from_str("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
2255        );
2256    }
2257}
2258
2259#[cfg(all(test, target_family = "wasm"))]
2260mod tests {
2261    use matrix_sdk_crypto::cryptostore_integration_tests;
2262
2263    use super::IndexeddbCryptoStore;
2264
2265    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
2266
2267    async fn get_store(
2268        name: &str,
2269        passphrase: Option<&str>,
2270        clear_data: bool,
2271    ) -> IndexeddbCryptoStore {
2272        if clear_data {
2273            IndexeddbCryptoStore::delete_stores(name).unwrap();
2274        }
2275        match passphrase {
2276            Some(pass) => IndexeddbCryptoStore::open_with_passphrase(name, pass)
2277                .await
2278                .expect("Can't create a passphrase protected store"),
2279            None => IndexeddbCryptoStore::open_with_name(name)
2280                .await
2281                .expect("Can't create store without passphrase"),
2282        }
2283    }
2284
2285    cryptostore_integration_tests!();
2286}
2287
2288#[cfg(all(test, target_family = "wasm"))]
2289mod encrypted_tests {
2290    use matrix_sdk_crypto::{
2291        cryptostore_integration_tests,
2292        olm::Account,
2293        store::{CryptoStore, types::PendingChanges},
2294        vodozemac::base64_encode,
2295    };
2296    use matrix_sdk_test::async_test;
2297    use ruma::{device_id, user_id};
2298
2299    use super::IndexeddbCryptoStore;
2300
2301    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
2302
2303    async fn get_store(
2304        name: &str,
2305        passphrase: Option<&str>,
2306        clear_data: bool,
2307    ) -> IndexeddbCryptoStore {
2308        if clear_data {
2309            IndexeddbCryptoStore::delete_stores(name).unwrap();
2310        }
2311
2312        let pass = passphrase.unwrap_or(name);
2313        IndexeddbCryptoStore::open_with_passphrase(&name, pass)
2314            .await
2315            .expect("Can't create a passphrase protected store")
2316    }
2317    cryptostore_integration_tests!();
2318
2319    /// Test that we can migrate a store created with a passphrase, to being
2320    /// encrypted with a key instead.
2321    #[async_test]
2322    async fn test_migrate_passphrase_to_key() {
2323        let store_name = "test_migrate_passphrase_to_key";
2324        let passdata: [u8; 32] = rand::random();
2325        let b64_passdata = base64_encode(passdata);
2326
2327        // Initialise the store with some account data
2328        IndexeddbCryptoStore::delete_stores(store_name).unwrap();
2329        let store = IndexeddbCryptoStore::open_with_passphrase(&store_name, &b64_passdata)
2330            .await
2331            .expect("Can't create a passphrase-protected store");
2332
2333        store
2334            .save_pending_changes(PendingChanges {
2335                account: Some(Account::with_device_id(
2336                    user_id!("@alice:example.org"),
2337                    device_id!("ALICEDEVICE"),
2338                )),
2339            })
2340            .await
2341            .expect("Can't save account");
2342
2343        // Now reopen the store, passing the key directly rather than as a b64
2344        // string.
2345        let store = IndexeddbCryptoStore::open_with_key(&store_name, &passdata)
2346            .await
2347            .expect("Can't create a key-protected store");
2348        let loaded_account =
2349            store.load_account().await.expect("Can't load account").expect("Account was not saved");
2350        assert_eq!(loaded_account.user_id, "@alice:example.org");
2351    }
2352}