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::{
19 error::OpenDbError, query_source::QuerySource, transaction::TransactionMode, Build,
20};
21use matrix_sdk_crypto::olm::InboundGroupSession;
22use tracing::{debug, info};
23use wasm_bindgen::JsValue;
24
25use crate::{
26 crypto_store::{
27 migrations::{do_schema_upgrade, old_keys, v7, MigrationDb},
28 Result,
29 },
30 serializer::SafeEncodeSerializer,
31 IndexeddbCryptoStoreError,
32};
33
34/// In the migration v5 to v7, we incorrectly copied the keys in
35/// `inbound_group_sessions` verbatim into `inbound_group_sessions2`. What we
36/// should have done is re-hash them using the new table name, so we fix them up
37/// here.
38pub(crate) async fn data_migrate(name: &str, serializer: &SafeEncodeSerializer) -> Result<()> {
39 let db = MigrationDb::new(name, 8).await?;
40
41 let txn = db
42 .transaction(old_keys::INBOUND_GROUP_SESSIONS_V2)
43 .with_mode(TransactionMode::Readwrite)
44 .build()?;
45
46 let store = txn.object_store(old_keys::INBOUND_GROUP_SESSIONS_V2)?;
47
48 let row_count = store.count().await?;
49 info!(row_count, "Fixing inbound group session data keys");
50
51 // Iterate through all rows
52 if let Some(mut cursor) = store.open_cursor().await? {
53 let mut idx = 0;
54 let mut updated = 0;
55 let mut deleted = 0;
56 while let Some(value) = cursor.next_record::<JsValue>().await? {
57 idx += 1;
58
59 // Get the old key and session
60
61 let old_key =
62 cursor.key::<JsValue>()?.ok_or(matrix_sdk_crypto::CryptoStoreError::Backend(
63 "inbound_group_sessions2 cursor has no key".into(),
64 ))?;
65
66 let idb_object: v7::InboundGroupSessionIndexedDbObject2 =
67 serde_wasm_bindgen::from_value(value)?;
68 let pickled_session =
69 serializer.deserialize_value_from_bytes(&idb_object.pickled_session)?;
70 let session = InboundGroupSession::from_pickle(pickled_session)
71 .map_err(|e| IndexeddbCryptoStoreError::CryptoStoreError(e.into()))?;
72
73 if idx % 100 == 0 {
74 debug!("Migrating session {idx} of {row_count}");
75 }
76
77 // Work out what the key should be.
78 // (This is much the same as in
79 // `IndexeddbCryptoStore::get_inbound_group_session`)
80 let new_key = serializer.encode_key(
81 old_keys::INBOUND_GROUP_SESSIONS_V2,
82 (&session.room_id, session.session_id()),
83 );
84
85 if new_key != old_key {
86 // We have found an entry that is stored under the incorrect old key
87
88 // Delete the old entry under the wrong key
89 cursor.delete()?;
90
91 // Check for an existing entry with the new key
92 let new_value = store.get::<JsValue, _, _>(&new_key).await?;
93
94 // If we found an existing entry, it is more up-to-date, so we don't need to do
95 // anything more.
96
97 // If we didn't find an existing entry, we must create one with the correct key
98 if new_value.is_none() {
99 store
100 .add(&serde_wasm_bindgen::to_value(&idb_object)?)
101 .with_key(new_key)
102 .build()?;
103 updated += 1;
104 } else {
105 deleted += 1;
106 }
107 }
108 }
109
110 debug!(
111 "Migrated {row_count} sessions: {updated} keys updated \
112 and {deleted} obsolete entries deleted."
113 );
114 }
115
116 txn.commit().await?;
117 Ok(())
118}
119
120/// Perform the schema upgrade v7 to v8, Just bumping the schema version.
121pub(crate) async fn schema_bump(name: &str) -> Result<(), OpenDbError> {
122 do_schema_upgrade(name, 8, |_, _| {
123 // Just bump the version number to 8 to demonstrate that we have run the data
124 // changes from prepare_data_for_v8.
125 Ok(())
126 })
127 .await
128}