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