matrix_sdk_indexeddb/crypto_store/migrations/v10_to_v11.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 moves from `backup_keys.backup_key_v1` to
16//! `backup_keys.backup_version_v1`, switching to a new serialization format.
17
18use indexed_db_futures::IdbQuerySource;
19use wasm_bindgen::JsValue;
20use web_sys::{DomException, IdbTransactionMode};
21
22use crate::crypto_store::{
23 indexeddb_serializer::IndexeddbSerializer,
24 keys,
25 migrations::{do_schema_upgrade, old_keys, MigrationDb},
26};
27
28/// Migrate data from `backup_keys.backup_key_v1` to
29/// `backup_keys.backup_version_v1`.
30pub(crate) async fn data_migrate(
31 name: &str,
32 serializer: &IndexeddbSerializer,
33) -> crate::crypto_store::Result<()> {
34 let db = MigrationDb::new(name, 11).await?;
35 let txn = db.transaction_on_one_with_mode(keys::BACKUP_KEYS, IdbTransactionMode::Readwrite)?;
36 let store = txn.object_store(keys::BACKUP_KEYS)?;
37
38 let bv = store.get(&JsValue::from_str(old_keys::BACKUP_KEY_V1))?.await?;
39
40 let Some(bv) = bv else {
41 return Ok(());
42 };
43
44 // backup_key_v1 was only ever serialized with the legacy format. Also, it's a
45 // string, so if we use `deserialize_value` on it, it will be incorrectly
46 // handled as a new-format object.
47 let bv: String = serializer.deserialize_legacy_value(bv)?;
48
49 // Re-serialize as new format, then store in the new field.
50 let serialized = serializer.serialize_value(&bv)?;
51 store.put_key_val(&JsValue::from_str(keys::BACKUP_VERSION_V1), &serialized)?.await?;
52 store.delete(&JsValue::from_str(old_keys::BACKUP_KEY_V1))?.await?;
53 Ok(())
54}
55
56/// Perform the schema upgrade v10 to v11, just bumping the schema version.
57pub(crate) async fn schema_bump(name: &str) -> crate::crypto_store::Result<(), DomException> {
58 // Just bump the version number to 11 to demonstrate that we have run the data
59 // changes from data_migrate.
60 do_schema_upgrade(name, 11, |_, _, _| Ok(())).await
61}