matrix_sdk_indexeddb/crypto_store/migrations/
v7_to_v8.rs

1// Copyright 2024 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Migration code that modifies the data inside inbound_group_sessions2,
16//! ensuring that the keys are correctly encoded for this new store name.
17
18use indexed_db_futures::IdbQuerySource;
19use matrix_sdk_crypto::olm::InboundGroupSession;
20use tracing::{debug, info};
21use web_sys::{DomException, IdbTransactionMode};
22
23use crate::{
24    crypto_store::{
25        indexeddb_serializer::IndexeddbSerializer,
26        migrations::{do_schema_upgrade, old_keys, v7, MigrationDb},
27        Result,
28    },
29    IndexeddbCryptoStoreError,
30};
31
32/// In the migration v5 to v7, we incorrectly copied the keys in
33/// `inbound_group_sessions` verbatim into `inbound_group_sessions2`. What we
34/// should have done is re-hash them using the new table name, so we fix them up
35/// here.
36pub(crate) async fn data_migrate(name: &str, serializer: &IndexeddbSerializer) -> Result<()> {
37    let db = MigrationDb::new(name, 8).await?;
38
39    let txn = db.transaction_on_one_with_mode(
40        old_keys::INBOUND_GROUP_SESSIONS_V2,
41        IdbTransactionMode::Readwrite,
42    )?;
43
44    let store = txn.object_store(old_keys::INBOUND_GROUP_SESSIONS_V2)?;
45
46    let row_count = store.count()?.await?;
47    info!(row_count, "Fixing inbound group session data keys");
48
49    // Iterate through all rows
50    if let Some(cursor) = store.open_cursor()?.await? {
51        let mut idx = 0;
52        let mut updated = 0;
53        let mut deleted = 0;
54        loop {
55            idx += 1;
56
57            // Get the old key and session
58
59            let old_key = cursor.key().ok_or(matrix_sdk_crypto::CryptoStoreError::Backend(
60                "inbound_group_sessions2 cursor has no key".into(),
61            ))?;
62
63            let idb_object: v7::InboundGroupSessionIndexedDbObject2 =
64                serde_wasm_bindgen::from_value(cursor.value())?;
65            let pickled_session =
66                serializer.deserialize_value_from_bytes(&idb_object.pickled_session)?;
67            let session = InboundGroupSession::from_pickle(pickled_session)
68                .map_err(|e| IndexeddbCryptoStoreError::CryptoStoreError(e.into()))?;
69
70            if idx % 100 == 0 {
71                debug!("Migrating session {idx} of {row_count}");
72            }
73
74            // Work out what the key should be.
75            // (This is much the same as in
76            // `IndexeddbCryptoStore::get_inbound_group_session`)
77            let new_key = serializer.encode_key(
78                old_keys::INBOUND_GROUP_SESSIONS_V2,
79                (&session.room_id, session.session_id()),
80            );
81
82            if new_key != old_key {
83                // We have found an entry that is stored under the incorrect old key
84
85                // Delete the old entry under the wrong key
86                cursor.delete()?;
87
88                // Check for an existing entry with the new key
89                let new_value = store.get(&new_key)?.await?;
90
91                // If we found an existing entry, it is more up-to-date, so we don't need to do
92                // anything more.
93
94                // If we didn't find an existing entry, we must create one with the correct key
95                if new_value.is_none() {
96                    store.add_key_val(&new_key, &serde_wasm_bindgen::to_value(&idb_object)?)?;
97                    updated += 1;
98                } else {
99                    deleted += 1;
100                }
101            }
102
103            if !cursor.continue_cursor()?.await? {
104                debug!("Migrated {row_count} sessions: {updated} keys updated and {deleted} obsolete entries deleted.");
105                break;
106            }
107        }
108    }
109
110    txn.await.into_result()?;
111    Ok(())
112}
113
114/// Perform the schema upgrade v7 to v8, Just bumping the schema version.
115pub(crate) async fn schema_bump(name: &str) -> Result<(), DomException> {
116    do_schema_upgrade(name, 8, |_, _, _| {
117        // Just bump the version number to 8 to demonstrate that we have run the data
118        // changes from prepare_data_for_v8.
119        Ok(())
120    })
121    .await
122}