Skip to main content

bitwarden_core/key_management/
local_user_data_key_state.rs

1use tracing::info;
2
3use crate::{
4    Client, UserId,
5    key_management::{self, local_user_data_key::WrappedLocalUserDataKey},
6};
7
8pub(crate) struct InitLocalUserDataKeyError;
9
10/// Stores [`WrappedLocalUserDataKey`] in state if one does not already exist.
11pub(crate) async fn initialize_local_user_data_key_into_state(
12    client: &Client,
13    user_id: UserId,
14) -> Result<(), InitLocalUserDataKeyError> {
15    let repo = client
16        .platform()
17        .state()
18        .get::<key_management::LocalUserDataKeyState>()
19        .map_err(|_| InitLocalUserDataKeyError)?;
20
21    // Idempotent: only set if no key is present yet.
22    if let Ok(Some(_)) = repo.get(user_id).await {
23        info!("WrappedLocalUserDataKey already exists in state, skipping");
24        return Ok(());
25    }
26
27    info!("Setting WrappedLocalUserDataKey to state from user key");
28    let wrapped_local_user_data_key = {
29        let key_store = client.internal.get_key_store();
30        let mut ctx = key_store.context();
31        WrappedLocalUserDataKey::from_context_user_key(&mut ctx)
32            .map_err(|_| InitLocalUserDataKeyError)?
33    };
34
35    repo.set(user_id, wrapped_local_user_data_key.into())
36        .await
37        .map_err(|_| InitLocalUserDataKeyError)
38}
39
40pub(crate) struct UnableToGetError;
41
42/// Retrieves the [`WrappedLocalUserDataKey`] from state.
43pub(crate) async fn get_local_user_data_key_from_state(
44    client: &Client,
45    user_id: UserId,
46) -> Result<WrappedLocalUserDataKey, UnableToGetError> {
47    info!("Getting the WrappedLocalUserDataKey from state");
48    let user_local_data_key_state = client
49        .platform()
50        .state()
51        .get::<key_management::LocalUserDataKeyState>()
52        .map_err(|_| UnableToGetError)?
53        .get(user_id)
54        .await
55        .map_err(|_| UnableToGetError)?
56        .ok_or(UnableToGetError)?;
57
58    Ok(WrappedLocalUserDataKey(
59        user_local_data_key_state.wrapped_key,
60    ))
61}