Skip to main content

bitwarden_core/client/
encryption_settings.rs

1#[cfg(any(feature = "internal", feature = "secrets"))]
2use bitwarden_crypto::KeyStore;
3#[cfg(feature = "secrets")]
4use bitwarden_crypto::SymmetricCryptoKey;
5#[cfg(feature = "internal")]
6use bitwarden_crypto::UnsignedSharedKey;
7use bitwarden_error::bitwarden_error;
8use thiserror::Error;
9#[cfg(feature = "internal")]
10use tracing::{info, instrument};
11
12#[cfg(any(feature = "secrets", feature = "internal"))]
13use crate::OrganizationId;
14#[cfg(any(feature = "internal", feature = "secrets"))]
15use crate::key_management::{KeyIds, SymmetricKeyId};
16use crate::{MissingPrivateKeyError, error::UserIdAlreadySetError};
17
18#[allow(missing_docs)]
19#[bitwarden_error(flat)]
20#[derive(Debug, Error)]
21pub enum EncryptionSettingsError {
22    #[error("Cryptography error, {0}")]
23    Crypto(#[from] bitwarden_crypto::CryptoError),
24
25    #[error("Cryptography Initialization error")]
26    CryptoInitialization,
27
28    #[error(transparent)]
29    MissingPrivateKey(#[from] MissingPrivateKeyError),
30
31    #[error(transparent)]
32    UserIdAlreadySet(#[from] UserIdAlreadySetError),
33
34    #[error("Wrong Pin")]
35    WrongPin,
36
37    /// The user-key could not be set to the state, and the sdk will remain locked
38    #[error("Unable to set user-key to state")]
39    UserKeyStateUpdateFailed,
40
41    #[error("Unable to retrieve user-key from state")]
42    UserKeyStateRetrievalFailed,
43
44    #[error("Invalid upgrade token")]
45    InvalidUpgradeToken,
46
47    /// The local user data key could not be initialized.
48    #[error("Unable to initialize local user data key")]
49    LocalUserDataKeyInitFailed,
50
51    /// The local user data key could not be loaded into the key store context.
52    #[error("Unable to load local user data key into key store")]
53    LocalUserDataKeyLoadFailed,
54}
55
56#[allow(missing_docs)]
57pub struct EncryptionSettings {}
58
59impl EncryptionSettings {
60    /// Initialize the encryption settings with only a single decrypted organization key.
61    /// This is used only for logging in Secrets Manager with an access token
62    #[cfg(feature = "secrets")]
63    pub(crate) fn new_single_org_key(
64        organization_id: OrganizationId,
65        key: SymmetricCryptoKey,
66        store: &KeyStore<KeyIds>,
67    ) {
68        // FIXME: [PM-18098] When this is part of crypto we won't need to use deprecated methods
69        #[allow(deprecated)]
70        store
71            .context_mut()
72            .set_symmetric_key(SymmetricKeyId::Organization(organization_id), key)
73            .expect("Mutable context");
74    }
75
76    #[cfg(feature = "internal")]
77    #[instrument(err, skip_all)]
78    pub(crate) fn set_org_keys(
79        org_enc_keys: Vec<(OrganizationId, UnsignedSharedKey)>,
80        store: &KeyStore<KeyIds>,
81    ) -> Result<(), EncryptionSettingsError> {
82        use crate::key_management::PrivateKeyId;
83
84        let mut ctx = store.context_mut();
85
86        // FIXME: [PM-11690] - Early abort to handle private key being corrupt
87        if org_enc_keys.is_empty() {
88            info!("No organization keys to set");
89            return Ok(());
90        }
91
92        if !ctx.has_private_key(PrivateKeyId::UserPrivateKey) {
93            info!("User private key is missing, cannot set organization keys");
94            return Err(MissingPrivateKeyError.into());
95        }
96
97        // Make sure we only keep the keys given in the arguments and not any of the previous
98        // ones, which might be from organizations that the user is no longer a part of anymore
99        ctx.retain_symmetric_keys(|key_ref| !matches!(key_ref, SymmetricKeyId::Organization(_)));
100
101        info!("Decrypting organization keys");
102        // Decrypt the org keys with the private key
103        for (org_id, org_enc_key) in org_enc_keys {
104            let _span =
105                tracing::span!(tracing::Level::INFO, "decapsulate_org_key", org_id = %org_id)
106                    .entered();
107            match org_enc_key.decapsulate(PrivateKeyId::UserPrivateKey, &mut ctx) {
108                Err(e) => {
109                    tracing::error!("Failed to decapsulate organization key: {}", e);
110                    return Err(e.into());
111                }
112                Ok(org_symmetric_key) => {
113                    tracing::info!(
114                        org_id = %org_id,
115                        "Successfully decapsulated organization key for org",
116                    );
117                    ctx.persist_symmetric_key(
118                        org_symmetric_key,
119                        SymmetricKeyId::Organization(org_id),
120                    )?;
121                }
122            }
123        }
124
125        Ok(())
126    }
127}