1// Copyright 2023 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.
1415use std::{future::IntoFuture, pin::Pin};
1617use futures_core::Future;
18use matrix_sdk_base::crypto::secret_storage::SecretStorageKey;
19use ruma::events::secret_storage::default_key::SecretStorageDefaultKeyEventContent;
2021use super::{Result, SecretStorage, SecretStore};
2223/// Future returned by [`SecretStorage::create_secret_store()`].
24#[derive(Debug)]
25pub struct CreateStore<'a> {
26pub(super) secret_storage: &'a SecretStorage,
27pub(super) passphrase: Option<&'a str>,
28}
2930impl<'a> CreateStore<'a> {
31/// Set the passphrase for the new [`SecretStore`].
32 ///
33 /// See the documentation for the [`SecretStorage::create_secret_store()`]
34 /// method for more info.
35pub fn with_passphrase(mut self, passphrase: &'a str) -> Self {
36self.passphrase = Some(passphrase);
3738self
39}
40}
4142impl<'a> IntoFuture for CreateStore<'a> {
43type Output = Result<SecretStore>;
44#[cfg(target_arch = "wasm32")]
45type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + 'a>>;
46#[cfg(not(target_arch = "wasm32"))]
47type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;
4849fn into_future(self) -> Self::IntoFuture {
50let Self { secret_storage, passphrase } = self;
5152 Box::pin(async move {
53// Prevent multiple simultaneous calls to this method.
54 //
55 // See the documentation for the lock in the `store_secret` method for more
56 // info.
57let client_copy = secret_storage.client.to_owned();
58let _guard = client_copy.locks().open_secret_store_lock.lock().await;
5960let new_key = if let Some(passphrase) = passphrase {
61 SecretStorageKey::new_from_passphrase(passphrase)
62 } else {
63 SecretStorageKey::new()
64 };
6566let content = new_key.event_content().to_owned();
6768 secret_storage.client.account().set_account_data(content).await?;
6970let store = SecretStore { client: secret_storage.client.to_owned(), key: new_key };
71 store.export_secrets().await?;
7273let default_key_content =
74 SecretStorageDefaultKeyEventContent::new(store.key.key_id().to_owned());
7576 store.client.account().set_account_data(default_key_content).await?;
7778Ok(store)
79 })
80 }
81}