Skip to main content

bitwarden_crypto/store/
context.rs

1use std::{
2    cell::Cell,
3    sync::{RwLockReadGuard, RwLockWriteGuard},
4};
5
6use coset::iana::KeyOperation;
7use serde::Serialize;
8use zeroize::Zeroizing;
9
10use super::{CipherSuite, KeyStoreInner};
11use crate::{
12    BitwardenLegacyKeyBytes, ContentFormat, CoseEncrypt0Bytes, CoseKeyBytes, CoseSerializable,
13    CryptoError, EncString, KeyDecryptable, KeyEncryptable, KeyId, KeySlotId, KeySlotIds, LocalId,
14    Pkcs8PrivateKeyBytes, PrivateKey, PublicKey, PublicKeyEncryptionAlgorithm, Result, Signature,
15    SignatureAlgorithm, SignedObject, SignedPublicKey, SignedPublicKeyMessage, SigningKey,
16    SymmetricCryptoKey, SymmetricKeyAlgorithm, VerifyingKey, derive_shareable_key,
17    error::UnsupportedOperationError, hazmat::symmetric_encryption::Aes256CbcHmacSha256, signing,
18    store::backend::StoreBackend,
19};
20
21/// The context of a crypto operation using [super::KeyStore]
22///
23/// This will usually be accessed from an implementation of [crate::Decryptable] or
24/// [crate::CompositeEncryptable], [crate::PrimitiveEncryptable],
25/// but can also be obtained
26/// through [super::KeyStore::context]
27///
28/// This context contains access to the user keys stored in the [super::KeyStore] (sometimes
29/// referred to as `global keys`) and it also contains it's own individual secure backend for key
30/// storage. Keys stored in this individual backend are usually referred to as `local keys`, they
31/// will be cleared when this context goes out of scope and is dropped and they do not affect either
32/// the global [super::KeyStore] or other instances of contexts.
33///
34/// This context-local storage is recommended for ephemeral and temporary keys that are decrypted
35/// during the course of a decrypt/encrypt operation, but won't be used after the operation itself
36/// is complete.
37///
38/// ```rust
39/// # use bitwarden_crypto::*;
40/// # key_slot_ids! {
41/// #     #[symmetric]
42/// #     pub enum SymmKeySlotIds {
43/// #         User,
44/// #         #[local]
45/// #         Local(LocalId),
46/// #     }
47/// #     #[private]
48/// #     pub enum PrivateKeySlotIds {
49/// #         UserPrivate,
50/// #         #[local]
51/// #         Local(LocalId),
52/// #     }
53/// #     #[signing]
54/// #     pub enum SigningKeySlotIds {
55/// #         UserSigning,
56/// #         #[local]
57/// #         Local(LocalId),
58/// #     }
59/// #     pub Ids => SymmKeySlotIds, PrivateKeySlotIds, SigningKeySlotIds;
60/// # }
61/// struct Data {
62///     key: EncString,
63///     name: String,
64/// }
65/// # impl IdentifyKey<SymmKeySlotIds> for Data {
66/// #    fn key_identifier(&self) -> SymmKeySlotIds {
67/// #        SymmKeySlotIds::User
68/// #    }
69/// # }
70///
71///
72/// impl CompositeEncryptable<Ids, SymmKeySlotIds, EncString> for Data {
73///     fn encrypt_composite(&self, ctx: &mut KeyStoreContext<Ids>, key: SymmKeySlotIds) -> Result<EncString, CryptoError> {
74///         let local_key_id = ctx.unwrap_symmetric_key(key, &self.key)?;
75///         self.name.encrypt(ctx, local_key_id)
76///     }
77/// }
78/// ```
79#[must_use]
80pub struct KeyStoreContext<'a, Ids: KeySlotIds> {
81    pub(super) global_keys: GlobalKeys<'a, Ids>,
82
83    pub(super) local_symmetric_keys: Box<dyn StoreBackend<Ids::Symmetric>>,
84    pub(super) local_private_keys: Box<dyn StoreBackend<Ids::Private>>,
85    pub(super) local_signing_keys: Box<dyn StoreBackend<Ids::Signing>>,
86
87    pub(super) security_state_version: u64,
88
89    pub(super) cipher_suite: CipherSuite,
90
91    // Make sure the context is !Send & !Sync
92    pub(super) _phantom: std::marker::PhantomData<(Cell<()>, RwLockReadGuard<'static, ()>)>,
93}
94
95/// A KeyStoreContext is usually limited to a read only access to the global keys,
96/// which allows us to have multiple read only contexts at the same time and do multitheaded
97/// encryption/decryption. We also have the option to create a read/write context, which allows us
98/// to modify the global keys, but only allows one context at a time. This is controlled by a
99/// [std::sync::RwLock] on the global keys, and this struct stores both types of guards.
100pub(crate) enum GlobalKeys<'a, Ids: KeySlotIds> {
101    ReadOnly(RwLockReadGuard<'a, KeyStoreInner<Ids>>),
102    ReadWrite(RwLockWriteGuard<'a, KeyStoreInner<Ids>>),
103}
104
105impl<Ids: KeySlotIds> GlobalKeys<'_, Ids> {
106    /// Get a shared reference to the underlying `KeyStoreInner`.
107    ///
108    /// This returns a shared reference regardless of whether the global keys were locked
109    /// for read-only or read-write access. Callers who need mutable access should use
110    /// `get_mut` which will return an error when the context is read-only.
111    pub fn get(&self) -> &KeyStoreInner<Ids> {
112        match self {
113            GlobalKeys::ReadOnly(keys) => keys,
114            GlobalKeys::ReadWrite(keys) => keys,
115        }
116    }
117
118    /// Get a mutable reference to the underlying `KeyStoreInner`.
119    ///
120    /// This will succeed only when the context was created with write access. If the
121    /// context is read-only an error (`CryptoError::ReadOnlyKeyStore`) is returned.
122    ///
123    /// # Errors
124    /// Returns [`CryptoError::ReadOnlyKeyStore`] when attempting to get mutable access from
125    /// a read-only context.
126    pub fn get_mut(&mut self) -> Result<&mut KeyStoreInner<Ids>> {
127        match self {
128            GlobalKeys::ReadOnly(_) => Err(CryptoError::ReadOnlyKeyStore),
129            GlobalKeys::ReadWrite(keys) => Ok(keys),
130        }
131    }
132}
133
134impl<Ids: KeySlotIds> KeyStoreContext<'_, Ids> {
135    /// Clears all the local keys stored in this context
136    /// This will not affect the global keys even if this context has write access.
137    /// To clear the global keys, you need to use [super::KeyStore::clear] instead.
138    pub fn clear_local(&mut self) {
139        self.local_symmetric_keys.clear();
140        self.local_private_keys.clear();
141        self.local_signing_keys.clear();
142    }
143
144    /// Returns the version of the security state of the key context. This describes the user's
145    /// encryption version and can be used to disable certain old / dangerous format features
146    /// safely.
147    pub fn get_security_state_version(&self) -> u64 {
148        self.security_state_version
149    }
150
151    /// Returns the [CipherSuite] this context operates under, which determines the algorithms
152    /// operations are allowed to use in the current environment.
153    pub fn cipher_suite(&self) -> CipherSuite {
154        self.cipher_suite
155    }
156
157    /// Remove all symmetric keys from the context for which the predicate returns false
158    /// This will also remove the keys from the global store if this context has write access
159    pub fn retain_symmetric_keys(&mut self, f: fn(Ids::Symmetric) -> bool) {
160        if let Ok(keys) = self.global_keys.get_mut() {
161            keys.symmetric_keys.retain(f);
162        }
163        self.local_symmetric_keys.retain(f);
164    }
165
166    /// Remove all private keys from the context for which the predicate returns false
167    /// This will also remove the keys from the global store if this context has write access
168    pub fn retain_private_keys(&mut self, f: fn(Ids::Private) -> bool) {
169        if let Ok(keys) = self.global_keys.get_mut() {
170            keys.private_keys.retain(f);
171        }
172        self.local_private_keys.retain(f);
173    }
174
175    /// Drop a symmetric key from the context by its identifier.
176    /// This will also remove the key from the global store if this context has write access and the
177    /// key is not local.
178    pub fn drop_symmetric_key(&mut self, key_id: Ids::Symmetric) -> Result<()> {
179        if key_id.is_local() {
180            self.local_symmetric_keys.remove(key_id);
181        } else {
182            self.global_keys.get_mut()?.symmetric_keys.remove(key_id);
183        }
184        Ok(())
185    }
186
187    /// Drop a private key from the context by its identifier.
188    /// This will also remove the key from the global store if this context has write access and the
189    /// key is not local.
190    pub fn drop_private_key(&mut self, key_id: Ids::Private) -> Result<()> {
191        if key_id.is_local() {
192            self.local_private_keys.remove(key_id);
193        } else {
194            self.global_keys.get_mut()?.private_keys.remove(key_id);
195        }
196        Ok(())
197    }
198
199    /// Drop a signing key from the context by its identifier.
200    /// This will also remove the key from the global store if this context has write access and the
201    /// key is not local.
202    pub fn drop_signing_key(&mut self, key_id: Ids::Signing) -> Result<()> {
203        if key_id.is_local() {
204            self.local_signing_keys.remove(key_id);
205        } else {
206            self.global_keys.get_mut()?.signing_keys.remove(key_id);
207        }
208        Ok(())
209    }
210
211    // TODO: All these encrypt x key with x key look like they need to be made generic,
212    // but I haven't found the best way to do that yet.
213
214    /// Decrypt a symmetric key into the context by using an already existing symmetric key
215    ///
216    /// # Arguments
217    ///
218    /// * `wrapping_key` - The key id used to decrypt the `wrapped_key`. It must already exist in
219    ///   the context
220    /// * `new_key_id` - The key id where the decrypted key will be stored. If it already exists, it
221    ///   will be overwritten
222    /// * `wrapped_key` - The key to decrypt
223    #[bitwarden_logging::instrument(err, fields(wrapping_key = ?wrapping_key))]
224    pub fn unwrap_symmetric_key(
225        &mut self,
226        wrapping_key: Ids::Symmetric,
227        wrapped_key: &EncString,
228    ) -> Result<Ids::Symmetric> {
229        let wrapping_key = self.get_symmetric_key(wrapping_key)?;
230
231        let key = match (wrapped_key, wrapping_key) {
232            (EncString::Aes256Cbc_B64 { .. }, SymmetricCryptoKey::Aes256CbcKey(_)) => {
233                return Err(CryptoError::OperationNotSupported(
234                    UnsupportedOperationError::DecryptionNotImplementedForKey,
235                ));
236            }
237            (
238                EncString::Aes256Cbc_HmacSha256_B64 { iv, mac, data },
239                SymmetricCryptoKey::Aes256CbcHmacKey(key),
240            ) => SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(
241                Aes256CbcHmacSha256::decrypt(iv, data, mac, key.as_composite_key())
242                    .map_err(|_| CryptoError::Decrypt)?,
243            ))?,
244            (
245                EncString::Cose_Encrypt0_B64 { data },
246                SymmetricCryptoKey::XChaCha20Poly1305Key(key),
247            ) => {
248                let (content_bytes, content_format) =
249                    crate::cose::symmetric::decrypt_xchacha20_poly1305(
250                        &CoseEncrypt0Bytes::from(data.clone()),
251                        key,
252                    )?;
253                match content_format {
254                    ContentFormat::BitwardenLegacyKey => {
255                        SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(content_bytes))?
256                    }
257                    ContentFormat::CoseKey => SymmetricCryptoKey::try_from_cose(&content_bytes)?,
258                    _ => return Err(CryptoError::InvalidKey),
259                }
260            }
261            (EncString::Cose_Encrypt0_B64 { data }, SymmetricCryptoKey::XAes256GcmKey(key)) => {
262                let (content_bytes, content_format) = crate::cose::symmetric::decrypt_xaes256_gcm(
263                    &CoseEncrypt0Bytes::from(data.clone()),
264                    key,
265                )?;
266                match content_format {
267                    ContentFormat::BitwardenLegacyKey => {
268                        SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(content_bytes))?
269                    }
270                    ContentFormat::CoseKey => SymmetricCryptoKey::try_from_cose(&content_bytes)?,
271                    _ => return Err(CryptoError::InvalidKey),
272                }
273            }
274            (EncString::Cose_Encrypt0_B64 { data }, SymmetricCryptoKey::Aes256CbcHmacKey(key)) => {
275                let (content_bytes, content_format) =
276                    crate::cose::symmetric::decrypt_aes256_cbc_hmac_aead(
277                        &CoseEncrypt0Bytes::from(data.clone()),
278                        key,
279                    )?;
280                match content_format {
281                    ContentFormat::BitwardenLegacyKey => {
282                        SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(content_bytes))?
283                    }
284                    ContentFormat::CoseKey => SymmetricCryptoKey::try_from_cose(&content_bytes)?,
285                    _ => return Err(CryptoError::InvalidKey),
286                }
287            }
288            (EncString::Unparseable { .. }, _) => return Err(CryptoError::UnparseableEncString),
289            _ => {
290                tracing::warn!(
291                    "Unsupported unwrap operation for the given key and data {:?}, {:?}",
292                    wrapping_key,
293                    wrapped_key
294                );
295                return Err(CryptoError::InvalidKey);
296            }
297        };
298
299        let new_key_id = Ids::Symmetric::new_local(LocalId::new());
300
301        #[allow(deprecated)]
302        self.set_symmetric_key(new_key_id, key)?;
303
304        // Returning the new key identifier for convenience
305        Ok(new_key_id)
306    }
307
308    /// Move a symmetric key from a local identifier to a global identifier within the context
309    ///
310    /// The key value is copied to `to` and the original identifier `from` is removed.
311    ///
312    /// # Errors
313    /// Returns an error if the source key does not exist or if setting the destination key
314    /// fails (for example due to read-only global store).
315    pub fn persist_symmetric_key(
316        &mut self,
317        from: Ids::Symmetric,
318        to: Ids::Symmetric,
319    ) -> Result<()> {
320        if !from.is_local() || to.is_local() {
321            return Err(CryptoError::InvalidKeyStoreOperation);
322        }
323        let key = self.get_symmetric_key(from)?.to_owned();
324        self.drop_symmetric_key(from)?;
325        #[allow(deprecated)]
326        self.set_symmetric_key(to, key)?;
327        Ok(())
328    }
329
330    /// Move a private key from a local identifier to a global identifier within the context
331    ///
332    /// The key value is copied to `to` and the original identifier `from` is removed.
333    ///
334    /// # Errors
335    /// Returns an error if the source key does not exist or if setting the destination key
336    /// fails (for example due to read-only global store).
337    pub fn persist_private_key(&mut self, from: Ids::Private, to: Ids::Private) -> Result<()> {
338        if !from.is_local() || to.is_local() {
339            return Err(CryptoError::InvalidKeyStoreOperation);
340        }
341        let key = self.get_private_key(from)?.to_owned();
342        self.drop_private_key(from)?;
343        #[allow(deprecated)]
344        self.set_private_key(to, key)?;
345        Ok(())
346    }
347
348    /// Move a signing key from a local identifier to a global identifier within the context
349    ///
350    /// The key value at `from` will be copied to `to` and the original `from` will be removed.
351    ///
352    /// # Errors
353    /// Returns an error if the source key does not exist or updating the destination fails.
354    pub fn persist_signing_key(&mut self, from: Ids::Signing, to: Ids::Signing) -> Result<()> {
355        if !from.is_local() || to.is_local() {
356            return Err(CryptoError::InvalidKeyStoreOperation);
357        }
358        let key = self.get_signing_key(from)?.to_owned();
359        self.drop_signing_key(from)?;
360        #[allow(deprecated)]
361        self.set_signing_key(to, key)?;
362        Ok(())
363    }
364
365    /// Wrap (encrypt) a signing key with a symmetric key.
366    ///
367    /// The signing key identified by `key_to_wrap` will be serialized to COSE and encrypted
368    /// with the symmetric `wrapping_key`, returning an `EncString` suitable for storage or
369    /// transport.
370    ///
371    /// # Errors
372    /// Returns an error if either key id does not exist or the encryption fails.
373    pub fn wrap_signing_key(
374        &self,
375        wrapping_key: Ids::Symmetric,
376        key_to_wrap: Ids::Signing,
377    ) -> Result<EncString> {
378        let wrapping_key = self.get_symmetric_key(wrapping_key)?;
379        let signing_key = self.get_signing_key(key_to_wrap)?.to_owned();
380        signing_key.to_cose().encrypt_with_key(wrapping_key)
381    }
382
383    /// Wrap (encrypt) a private key with a symmetric key.
384    ///
385    /// The private key identified by `key_to_wrap` will be serialized to DER (PKCS#8) and
386    /// encrypted with `wrapping_key`, returning an `EncString` suitable for storage.
387    ///
388    /// # Errors
389    /// Returns an error if the keys are missing or serialization/encryption fails.
390    pub fn wrap_private_key(
391        &self,
392        wrapping_key: Ids::Symmetric,
393        key_to_wrap: Ids::Private,
394    ) -> Result<EncString> {
395        let wrapping_key = self.get_symmetric_key(wrapping_key)?;
396        let private_key = self.get_private_key(key_to_wrap)?.to_owned();
397        private_key.to_der()?.encrypt_with_key(wrapping_key)
398    }
399
400    /// Decrypt and import a previously wrapped private key into the context.
401    ///
402    /// The `wrapped_key` will be decrypted using `wrapping_key` and parsed as a PKCS#8
403    /// private key; the resulting key will be inserted as a local private key and the
404    /// new local identifier returned.
405    ///
406    /// # Errors
407    /// Returns an error if decryption or parsing fails.
408    #[bitwarden_logging::instrument(err, fields(wrapping_key = ?wrapping_key))]
409    pub fn unwrap_private_key(
410        &mut self,
411        wrapping_key: Ids::Symmetric,
412        wrapped_key: &EncString,
413    ) -> Result<Ids::Private> {
414        let wrapping_key = self.get_symmetric_key(wrapping_key)?;
415        let private_key_bytes: Vec<u8> = wrapped_key.decrypt_with_key(wrapping_key)?;
416        let private_key = PrivateKey::from_der(&Pkcs8PrivateKeyBytes::from(private_key_bytes))?;
417        Ok(self.add_local_private_key(private_key))
418    }
419
420    /// Decrypt and import a previously wrapped signing key into the context.
421    ///
422    /// The wrapped COSE key will be decrypted with `wrapping_key` and parsed into a
423    /// `SigningKey` which is inserted as a local signing key. The new local identifier
424    /// is returned.
425    ///
426    /// # Errors
427    /// Returns an error if decryption or parsing fails.
428    pub fn unwrap_signing_key(
429        &mut self,
430        wrapping_key: Ids::Symmetric,
431        wrapped_key: &EncString,
432    ) -> Result<Ids::Signing> {
433        let wrapping_key = self.get_symmetric_key(wrapping_key)?;
434        let signing_key_bytes: Vec<u8> = wrapped_key.decrypt_with_key(wrapping_key)?;
435        let signing_key = SigningKey::from_cose(&CoseKeyBytes::from(signing_key_bytes))?;
436        Ok(self.add_local_signing_key(signing_key))
437    }
438
439    /// Return the verifying (public) key corresponding to a signing key identifier.
440    ///
441    /// This converts the stored `SigningKey` into a `VerifyingKey` suitable for
442    /// signature verification operations.
443    ///
444    /// # Errors
445    /// Returns an error if the signing key id does not exist.
446    pub fn get_verifying_key(&self, signing_key_id: Ids::Signing) -> Result<VerifyingKey> {
447        let signing_key = self.get_signing_key(signing_key_id)?;
448        Ok(signing_key.to_verifying_key())
449    }
450
451    /// Return the public key corresponding to an private key identifier.
452    ///
453    /// This converts the stored private key into its public key representation.
454    ///
455    /// # Errors
456    /// Returns an error if the private key id does not exist.
457    pub fn get_public_key(&self, private_key_id: Ids::Private) -> Result<PublicKey> {
458        let private_key = self.get_private_key(private_key_id)?;
459        Ok(private_key.to_public_key())
460    }
461
462    /// Encrypt and return a symmetric key from the context by using an already existing symmetric
463    /// key
464    ///
465    /// # Arguments
466    ///
467    /// * `wrapping_key` - The key id used to wrap (encrypt) the `key_to_wrap`. It must already
468    ///   exist in the context
469    /// * `key_to_wrap` - The key id to wrap. It must already exist in the context
470    pub fn wrap_symmetric_key(
471        &self,
472        wrapping_key: Ids::Symmetric,
473        key_to_wrap: Ids::Symmetric,
474    ) -> Result<EncString> {
475        use SymmetricCryptoKey::*;
476
477        let wrapping_key_instance = self.get_symmetric_key(wrapping_key)?;
478        let key_to_wrap_instance = self.get_symmetric_key(key_to_wrap)?;
479        // `Aes256CbcHmacKey` can wrap keys by encrypting their byte serialization obtained using
480        // `SymmetricCryptoKey::to_encoded()`. General-purpose COSE wrapping keys serialize the
481        // wrapped key without padding and authenticate whether it is a legacy key or a COSE key
482        // through the content format.
483        match (wrapping_key_instance, key_to_wrap_instance) {
484            (
485                Aes256CbcHmacKey(_),
486                Aes256CbcHmacKey(_)
487                | Aes256CbcKey(_)
488                | XChaCha20Poly1305Key(_)
489                | Aes256GcmKey(_)
490                | XAes256GcmKey(_),
491            ) => self.encrypt_data_with_symmetric_key(
492                wrapping_key,
493                key_to_wrap_instance
494                    .to_encoded()
495                    .as_ref()
496                    .to_vec()
497                    .as_slice(),
498                ContentFormat::BitwardenLegacyKey,
499            ),
500            (XChaCha20Poly1305Key(_), _) | (XAes256GcmKey(_), _) => {
501                let encoded = key_to_wrap_instance.to_encoded_raw();
502                let content_format = encoded.content_format();
503                self.encrypt_data_with_symmetric_key(
504                    wrapping_key,
505                    Into::<Vec<u8>>::into(encoded).as_slice(),
506                    content_format,
507                )
508            }
509            _ => Err(CryptoError::OperationNotSupported(
510                UnsupportedOperationError::EncryptionNotImplementedForKey,
511            )),
512        }
513    }
514
515    /// Returns `true` if the context has a symmetric key with the given identifier
516    pub fn has_symmetric_key(&self, key_id: Ids::Symmetric) -> bool {
517        self.get_symmetric_key(key_id).is_ok()
518    }
519
520    /// Returns `true` if the context has a private key with the given identifier
521    pub fn has_private_key(&self, key_id: Ids::Private) -> bool {
522        self.get_private_key(key_id).is_ok()
523    }
524
525    /// Returns `true` if the context has a signing key with the given identifier
526    pub fn has_signing_key(&self, key_id: Ids::Signing) -> bool {
527        self.get_signing_key(key_id).is_ok()
528    }
529
530    /// Generate a new random symmetric key and store it in the context
531    pub fn generate_symmetric_key(&mut self) -> Ids::Symmetric {
532        self.add_local_symmetric_key(SymmetricCryptoKey::make_aes256_cbc_hmac_key())
533    }
534
535    /// Generate a new symmetric encryption key using the specified algorithm and store it in the
536    /// context as a local key
537    pub fn make_symmetric_key(&mut self, algorithm: SymmetricKeyAlgorithm) -> Ids::Symmetric {
538        self.add_local_symmetric_key(SymmetricCryptoKey::make(algorithm))
539    }
540
541    /// Makes a new private encryption key using the current default algorithm, and stores it in
542    /// the context as a local key
543    pub fn make_private_key(&mut self, algorithm: PublicKeyEncryptionAlgorithm) -> Ids::Private {
544        self.add_local_private_key(PrivateKey::make(algorithm))
545    }
546
547    /// Makes a new signing key using the current default algorithm, and stores it in the context as
548    /// a local key
549    pub fn make_signing_key(&mut self, algorithm: SignatureAlgorithm) -> Ids::Signing {
550        self.add_local_signing_key(SigningKey::make(algorithm))
551    }
552
553    /// Derive a shareable key using hkdf from secret and name and store it in the context.
554    ///
555    /// A specialized variant of this function was called `CryptoService.makeSendKey` in the
556    /// Bitwarden `clients` repository.
557    pub fn derive_shareable_key(
558        &mut self,
559        secret: Zeroizing<[u8; 16]>,
560        name: &str,
561        info: Option<&str>,
562    ) -> Result<Ids::Symmetric> {
563        let key_id = Ids::Symmetric::new_local(LocalId::new());
564        #[allow(deprecated)]
565        self.set_symmetric_key(
566            key_id,
567            SymmetricCryptoKey::Aes256CbcHmacKey(derive_shareable_key(secret, name, info)),
568        )?;
569        Ok(key_id)
570    }
571
572    /// Return a reference to a symmetric key stored in the context.
573    ///
574    /// Deprecated: intended only for internal use and tests. This exposes the underlying
575    /// `SymmetricCryptoKey` reference directly and should not be used by external code. Use
576    /// the higher-level APIs (for example encryption/decryption helpers) or `get_symmetric_key`
577    /// internally when possible.
578    ///
579    /// # Errors
580    /// Returns [`CryptoError::MissingKeyId`] if the key id does not exist in the context.
581    #[deprecated(note = "This function should ideally never be used outside this crate")]
582    pub fn dangerous_get_symmetric_key(
583        &self,
584        key_id: Ids::Symmetric,
585    ) -> Result<&SymmetricCryptoKey> {
586        self.get_symmetric_key(key_id)
587    }
588
589    /// Return the key id if the symmetric key exists in the context
590    pub fn get_symmetric_key_id(&self, key_slot_id: Ids::Symmetric) -> Option<KeyId> {
591        let Ok(key) = self.get_symmetric_key(key_slot_id) else {
592            return None;
593        };
594        key.key_id()
595    }
596
597    /// Return a reference to a signing key stored in the context.
598    ///
599    /// Deprecated: intended only for internal use and tests. This exposes the underlying
600    /// `SigningKey` reference directly and should not be used by external code. Use the
601    /// higher-level APIs (for example signing helpers) or `get_signing_key` internally when
602    /// possible
603    ///
604    /// # Errors
605    /// Returns [`CryptoError::MissingKeyId`] if the key id does not exist in
606    /// the context.
607    #[deprecated(note = "This function should ideally never be used outside this crate")]
608    pub fn dangerous_get_signing_key(&self, key_id: Ids::Signing) -> Result<&SigningKey> {
609        self.get_signing_key(key_id)
610    }
611
612    /// Return a reference to an asymmetric (private) key stored in the context.
613    ///
614    /// Deprecated: intended only for internal use and tests. This exposes the underlying
615    /// `PrivateKey` reference directly and should not be used by external code. Prefer
616    /// using the public key via `get_public_key` or other higher-level APIs instead.
617    ///
618    /// # Errors
619    /// Returns [`CryptoError::MissingKeyId`] if the key id does not exist in the context.
620    #[deprecated(note = "This function should ideally never be used outside this crate")]
621    pub fn dangerous_get_private_key(&self, key_id: Ids::Private) -> Result<&PrivateKey> {
622        self.get_private_key(key_id)
623    }
624
625    /// Makes a signed public key from a private key and signing key stored in context.
626    /// Signing a public key asserts ownership, and makes the claim to other users that if they want
627    /// to share with you, they can use this public key.
628    pub fn make_signed_public_key(
629        &self,
630        private_key_id: Ids::Private,
631        signing_key_id: Ids::Signing,
632    ) -> Result<SignedPublicKey> {
633        let public_key = self.get_private_key(private_key_id)?.to_public_key();
634        let signing_key = self.get_signing_key(signing_key_id)?;
635        let signed_public_key =
636            SignedPublicKeyMessage::from_public_key(&public_key)?.sign(signing_key)?;
637        Ok(signed_public_key)
638    }
639
640    pub(crate) fn get_symmetric_key(&self, key_id: Ids::Symmetric) -> Result<&SymmetricCryptoKey> {
641        if key_id.is_local() {
642            self.local_symmetric_keys.get(key_id)
643        } else {
644            self.global_keys.get().symmetric_keys.get(key_id)
645        }
646        .ok_or_else(|| crate::CryptoError::MissingKeyId(format!("{key_id:?}")))
647    }
648
649    pub(super) fn get_private_key(&self, key_id: Ids::Private) -> Result<&PrivateKey> {
650        if key_id.is_local() {
651            self.local_private_keys.get(key_id)
652        } else {
653            self.global_keys.get().private_keys.get(key_id)
654        }
655        .ok_or_else(|| crate::CryptoError::MissingKeyId(format!("{key_id:?}")))
656    }
657
658    pub(super) fn get_signing_key(&self, key_id: Ids::Signing) -> Result<&SigningKey> {
659        if key_id.is_local() {
660            self.local_signing_keys.get(key_id)
661        } else {
662            self.global_keys.get().signing_keys.get(key_id)
663        }
664        .ok_or_else(|| crate::CryptoError::MissingKeyId(format!("{key_id:?}")))
665    }
666
667    /// Set a symmetric key in the context.
668    ///
669    /// # Errors
670    /// Returns [`CryptoError::ReadOnlyKeyStore`] if the context does not have write access when
671    /// attempting to modify the global store.
672    #[deprecated(note = "This function should ideally never be used outside this crate")]
673    pub fn set_symmetric_key(
674        &mut self,
675        key_id: Ids::Symmetric,
676        key: SymmetricCryptoKey,
677    ) -> Result<()> {
678        self.set_symmetric_key_internal(key_id, key)
679    }
680
681    pub(crate) fn set_symmetric_key_internal(
682        &mut self,
683        key_id: Ids::Symmetric,
684        key: SymmetricCryptoKey,
685    ) -> Result<()> {
686        if key_id.is_local() {
687            self.local_symmetric_keys.upsert(key_id, key);
688        } else {
689            self.global_keys
690                .get_mut()?
691                .symmetric_keys
692                .upsert(key_id, key);
693        }
694        Ok(())
695    }
696
697    /// Add a new symmetric key to the local context, returning a new unique identifier for it.
698    pub fn add_local_symmetric_key(&mut self, key: SymmetricCryptoKey) -> Ids::Symmetric {
699        let key_id = Ids::Symmetric::new_local(LocalId::new());
700        self.local_symmetric_keys.upsert(key_id, key);
701        key_id
702    }
703
704    /// Get the type of a symmetric key stored in the context.
705    pub fn get_symmetric_key_algorithm(
706        &self,
707        key_id: Ids::Symmetric,
708    ) -> Result<SymmetricKeyAlgorithm> {
709        let key = self.get_symmetric_key(key_id)?;
710        match key {
711            // Note this is dropped soon
712            SymmetricCryptoKey::Aes256CbcKey(_) => Err(CryptoError::OperationNotSupported(
713                UnsupportedOperationError::EncryptionNotImplementedForKey,
714            )),
715            SymmetricCryptoKey::Aes256CbcHmacKey(_) => Ok(SymmetricKeyAlgorithm::Aes256CbcHmac),
716            SymmetricCryptoKey::XChaCha20Poly1305Key(_) => {
717                Ok(SymmetricKeyAlgorithm::XChaCha20Poly1305)
718            }
719            SymmetricCryptoKey::Aes256GcmKey(_) => Ok(SymmetricKeyAlgorithm::Aes256Gcm),
720            SymmetricCryptoKey::XAes256GcmKey(_) => Ok(SymmetricKeyAlgorithm::XAes256Gcm),
721        }
722    }
723
724    /// Returns `true` if the given symmetric key uses V1 (Aes256CbcHmac) encryption.
725    #[bitwarden_logging::instrument(err, fields(key_id = ?key_id))]
726    pub fn is_v1_symmetric_key(&self, key_id: Ids::Symmetric) -> Result<bool> {
727        let algorithm = self.get_symmetric_key_algorithm(key_id)?;
728        Ok(algorithm == SymmetricKeyAlgorithm::Aes256CbcHmac)
729    }
730
731    /// Set a private key in the context.
732    ///
733    /// # Errors
734    /// Returns [`CryptoError::ReadOnlyKeyStore`] if attempting to write to the global store when
735    /// the context is read-only.
736    #[deprecated(note = "This function should ideally never be used outside this crate")]
737    pub fn set_private_key(&mut self, key_id: Ids::Private, key: PrivateKey) -> Result<()> {
738        if key_id.is_local() {
739            self.local_private_keys.upsert(key_id, key);
740        } else {
741            self.global_keys.get_mut()?.private_keys.upsert(key_id, key);
742        }
743        Ok(())
744    }
745
746    /// Add a new private key to the local context, returning a new unique identifier for it.
747    pub fn add_local_private_key(&mut self, key: PrivateKey) -> Ids::Private {
748        let key_id = Ids::Private::new_local(LocalId::new());
749        self.local_private_keys.upsert(key_id, key);
750        key_id
751    }
752
753    /// Sets a signing key in the context
754    ///
755    /// # Errors
756    /// Returns [`CryptoError::ReadOnlyKeyStore`] if attempting to write to the global store when
757    /// the context is read-only.
758    #[deprecated(note = "This function should ideally never be used outside this crate")]
759    pub fn set_signing_key(&mut self, key_id: Ids::Signing, key: SigningKey) -> Result<()> {
760        if key_id.is_local() {
761            self.local_signing_keys.upsert(key_id, key);
762        } else {
763            self.global_keys.get_mut()?.signing_keys.upsert(key_id, key);
764        }
765        Ok(())
766    }
767
768    /// Add a new signing key to the local context, returning a new unique identifier for it.
769    pub fn add_local_signing_key(&mut self, key: SigningKey) -> Ids::Signing {
770        let key_id = Ids::Signing::new_local(LocalId::new());
771        self.local_signing_keys.upsert(key_id, key);
772        key_id
773    }
774
775    #[bitwarden_logging::instrument(err, level = "debug", fields(key = ?key))]
776    pub(crate) fn decrypt_data_with_symmetric_key(
777        &self,
778        key: Ids::Symmetric,
779        data: &EncString,
780    ) -> Result<Vec<u8>> {
781        let key = self.get_symmetric_key(key)?;
782
783        match (data, key) {
784            (EncString::Aes256Cbc_B64 { .. }, SymmetricCryptoKey::Aes256CbcKey(_)) => {
785                Err(CryptoError::OperationNotSupported(
786                    UnsupportedOperationError::DecryptionNotImplementedForKey,
787                ))
788            }
789            (
790                EncString::Aes256Cbc_HmacSha256_B64 { iv, mac, data },
791                SymmetricCryptoKey::Aes256CbcHmacKey(key),
792            ) => Aes256CbcHmacSha256::decrypt(iv, data, mac, key.as_composite_key())
793                .map_err(|_| CryptoError::Decrypt),
794            (
795                EncString::Cose_Encrypt0_B64 { data },
796                SymmetricCryptoKey::XChaCha20Poly1305Key(key),
797            ) => {
798                let (data, _) = crate::cose::symmetric::decrypt_xchacha20_poly1305(
799                    &CoseEncrypt0Bytes::from(data.clone()),
800                    key,
801                )?;
802                Ok(data)
803            }
804            (EncString::Cose_Encrypt0_B64 { data }, SymmetricCryptoKey::XAes256GcmKey(key)) => {
805                let (data, _) = crate::cose::symmetric::decrypt_xaes256_gcm(
806                    &CoseEncrypt0Bytes::from(data.clone()),
807                    key,
808                )?;
809                Ok(data)
810            }
811            (EncString::Cose_Encrypt0_B64 { data }, SymmetricCryptoKey::Aes256CbcHmacKey(key)) => {
812                let (data, _) = crate::cose::symmetric::decrypt_aes256_cbc_hmac_aead(
813                    &CoseEncrypt0Bytes::from(data.clone()),
814                    key,
815                )?;
816                Ok(data)
817            }
818            (EncString::Unparseable { .. }, _) => Err(CryptoError::UnparseableEncString),
819            _ => {
820                tracing::warn!("Unsupported decryption operation for the given key and data");
821                Err(CryptoError::InvalidKey)
822            }
823        }
824    }
825
826    pub(crate) fn encrypt_data_with_symmetric_key(
827        &self,
828        key: Ids::Symmetric,
829        data: &[u8],
830        content_format: ContentFormat,
831    ) -> Result<EncString> {
832        let key = self.get_symmetric_key(key)?;
833        match key {
834            SymmetricCryptoKey::Aes256CbcKey(_) => Err(CryptoError::OperationNotSupported(
835                UnsupportedOperationError::EncryptionNotImplementedForKey,
836            )),
837            SymmetricCryptoKey::Aes256CbcHmacKey(key) => EncString::encrypt_aes256_hmac(data, key),
838            SymmetricCryptoKey::XChaCha20Poly1305Key(key) => {
839                if !key.supported_operations.contains(&KeyOperation::Encrypt) {
840                    return Err(CryptoError::KeyOperationNotSupported(KeyOperation::Encrypt));
841                }
842                EncString::encrypt_xchacha20_poly1305(data, key, content_format)
843            }
844            SymmetricCryptoKey::Aes256GcmKey(_) => Err(CryptoError::OperationNotSupported(
845                UnsupportedOperationError::EncryptionNotImplementedForKey,
846            )),
847            SymmetricCryptoKey::XAes256GcmKey(key) => {
848                if !key.supported_operations.contains(&KeyOperation::Encrypt) {
849                    return Err(CryptoError::KeyOperationNotSupported(KeyOperation::Encrypt));
850                }
851                EncString::encrypt_xaes256_gcm(data, key, content_format)
852            }
853        }
854    }
855
856    /// Signs the given data using the specified signing key, for the given
857    /// [crate::SigningNamespace] and returns the signature and the serialized message. See
858    /// [crate::SigningKey::sign]
859    pub fn sign<Message: Serialize>(
860        &self,
861        key: Ids::Signing,
862        message: &Message,
863        namespace: &crate::SigningNamespace,
864    ) -> Result<SignedObject> {
865        self.get_signing_key(key)?.sign(message, namespace)
866    }
867
868    /// Signs the given data using the specified signing key, for the given
869    /// [crate::SigningNamespace] and returns the signature and the serialized message. See
870    /// [crate::SigningKey::sign_detached]
871    #[allow(unused)]
872    pub(crate) fn sign_detached<Message: Serialize>(
873        &self,
874        key: Ids::Signing,
875        message: &Message,
876        namespace: &crate::SigningNamespace,
877    ) -> Result<(Signature, signing::SerializedMessage)> {
878        self.get_signing_key(key)?.sign_detached(message, namespace)
879    }
880
881    /// A test helper to assert that the symmetric keys corresponding to the given identifiers are
882    /// equal.
883    #[cfg(any(test, feature = "test-utils"))]
884    pub fn assert_symmetric_keys_equal(&self, key_id_1: Ids::Symmetric, key_id_2: Ids::Symmetric) {
885        let key_1 = self
886            .get_symmetric_key(key_id_1)
887            .expect("Key 1 should exist in context");
888        let key_2 = self
889            .get_symmetric_key(key_id_2)
890            .expect("Key 2 should exist in context");
891        if key_1 != key_2 {
892            panic!(
893                "Symmetric keys with ids {:?} and {:?} are not equal",
894                key_id_1, key_id_2,
895            );
896        }
897    }
898
899    /// A test helper to assert that the symmetric keys corresponding to the given identifiers are
900    /// not equal.
901    #[cfg(any(test, feature = "test-utils"))]
902    pub fn assert_symmetric_keys_not_equal(
903        &self,
904        key_id_1: Ids::Symmetric,
905        key_id_2: Ids::Symmetric,
906    ) {
907        let key_1 = self
908            .get_symmetric_key(key_id_1)
909            .expect("Key 1 should exist in context");
910        let key_2 = self
911            .get_symmetric_key(key_id_2)
912            .expect("Key 2 should exist in context");
913        if key_1 == key_2 {
914            panic!(
915                "Symmetric keys with ids {:?} and {:?} are equal",
916                key_id_1, key_id_2,
917            );
918        }
919    }
920}
921
922#[cfg(test)]
923#[allow(deprecated)]
924mod tests {
925    use serde::{Deserialize, Serialize};
926
927    use crate::{
928        CompositeEncryptable, CryptoError, Decryptable, EncString, SignatureAlgorithm, SigningKey,
929        SigningNamespace, SymmetricCryptoKey, SymmetricKeyAlgorithm,
930        store::{
931            KeyStore,
932            tests::{Data, DataView},
933        },
934        traits::tests::{TestIds, TestSigningKey, TestSymmKey},
935    };
936
937    #[test]
938    fn test_set_signing_key() {
939        let store: KeyStore<TestIds> = KeyStore::default();
940
941        // Generate and insert a key
942        let key_a0_id = TestSigningKey::A(0);
943        let key_a0 = SigningKey::make(SignatureAlgorithm::Ed25519);
944        store
945            .context_mut()
946            .set_signing_key(key_a0_id, key_a0)
947            .unwrap();
948    }
949
950    #[test]
951    fn test_set_keys_for_encryption() {
952        let store: KeyStore<TestIds> = KeyStore::default();
953
954        // Generate and insert a key
955        let key_a0_id = TestSymmKey::A(0);
956        let mut ctx = store.context_mut();
957        let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
958        ctx.persist_symmetric_key(local_key_id, TestSymmKey::A(0))
959            .unwrap();
960
961        assert!(ctx.has_symmetric_key(key_a0_id));
962
963        // Encrypt some data with the key
964        let data = DataView("Hello, World!".to_string(), key_a0_id);
965        let _encrypted: Data = data.encrypt_composite(&mut ctx, key_a0_id).unwrap();
966    }
967
968    #[test]
969    fn test_key_encryption() {
970        let store: KeyStore<TestIds> = KeyStore::default();
971
972        let mut ctx = store.context();
973
974        // Generate and insert a key
975        let key_1_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
976
977        assert!(ctx.has_symmetric_key(key_1_id));
978
979        // Generate and insert a new key
980        let key_2_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
981
982        assert!(ctx.has_symmetric_key(key_2_id));
983
984        // Encrypt the new key with the old key
985        let key_2_enc = ctx.wrap_symmetric_key(key_1_id, key_2_id).unwrap();
986
987        // Decrypt the new key with the old key in a different identifier
988        let new_key_id = ctx.unwrap_symmetric_key(key_1_id, &key_2_enc).unwrap();
989
990        // Now `key_2_id` and `new_key_id` contain the same key, so we should be able to encrypt
991        // with one and decrypt with the other
992
993        let data = DataView("Hello, World!".to_string(), key_2_id);
994        let encrypted = data.encrypt_composite(&mut ctx, key_2_id).unwrap();
995
996        let decrypted1 = encrypted.decrypt(&mut ctx, key_2_id).unwrap();
997        let decrypted2 = encrypted.decrypt(&mut ctx, new_key_id).unwrap();
998
999        // Assert that the decrypted data is the same
1000        assert_eq!(decrypted1.0, decrypted2.0);
1001    }
1002
1003    #[test]
1004    fn test_wrap_unwrap() {
1005        let store: KeyStore<TestIds> = KeyStore::default();
1006        let mut ctx = store.context_mut();
1007
1008        let cbc = TestSymmKey::A(1);
1009        let xchacha = TestSymmKey::A(2);
1010        let aes_gcm = TestSymmKey::A(3);
1011        let xaes = TestSymmKey::A(4);
1012        for (id, key) in [
1013            (
1014                cbc,
1015                SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1016            ),
1017            (
1018                xchacha,
1019                SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XChaCha20Poly1305),
1020            ),
1021            (
1022                aes_gcm,
1023                SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256Gcm),
1024            ),
1025            (
1026                xaes,
1027                SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XAes256Gcm),
1028            ),
1029        ] {
1030            ctx.set_symmetric_key(id, key).unwrap();
1031        }
1032
1033        for (wrapping_key, wrapped_key) in [
1034            (cbc, cbc),
1035            (cbc, xchacha),
1036            (xchacha, cbc),
1037            (xchacha, xchacha),
1038            (xaes, cbc),
1039            (xaes, xchacha),
1040            (xaes, aes_gcm),
1041            (xaes, xaes),
1042            (cbc, xaes),
1043            (xchacha, xaes),
1044        ] {
1045            let encrypted = ctx.wrap_symmetric_key(wrapping_key, wrapped_key).unwrap();
1046            let unwrapped = ctx.unwrap_symmetric_key(wrapping_key, &encrypted).unwrap();
1047            ctx.assert_symmetric_keys_equal(unwrapped, wrapped_key);
1048        }
1049    }
1050
1051    #[test]
1052    fn test_signing() {
1053        let store: KeyStore<TestIds> = KeyStore::default();
1054
1055        // Generate and insert a key
1056        let key_a0_id = TestSigningKey::A(0);
1057        let key_a0 = SigningKey::make(SignatureAlgorithm::Ed25519);
1058        let verifying_key = key_a0.to_verifying_key();
1059        store
1060            .context_mut()
1061            .set_signing_key(key_a0_id, key_a0)
1062            .unwrap();
1063
1064        assert!(store.context().has_signing_key(key_a0_id));
1065
1066        // Sign some data with the key
1067        #[derive(Serialize, Deserialize)]
1068        struct TestData {
1069            data: String,
1070        }
1071        let signed_object = store
1072            .context()
1073            .sign(
1074                key_a0_id,
1075                &TestData {
1076                    data: "Hello".to_string(),
1077                },
1078                &SigningNamespace::ExampleNamespace,
1079            )
1080            .unwrap();
1081        let payload: Result<TestData, CryptoError> =
1082            signed_object.verify_and_unwrap(&verifying_key, &SigningNamespace::ExampleNamespace);
1083        assert!(payload.is_ok());
1084
1085        let (signature, serialized_message) = store
1086            .context()
1087            .sign_detached(
1088                key_a0_id,
1089                &TestData {
1090                    data: "Hello".to_string(),
1091                },
1092                &SigningNamespace::ExampleNamespace,
1093            )
1094            .unwrap();
1095        assert!(signature.verify(
1096            serialized_message.as_bytes(),
1097            &verifying_key,
1098            &SigningNamespace::ExampleNamespace
1099        ))
1100    }
1101
1102    #[test]
1103    fn test_encrypt_fails_when_operation_not_allowed() {
1104        use coset::iana::KeyOperation;
1105        let store = KeyStore::<TestIds>::default();
1106        let mut ctx = store.context_mut();
1107        let key_id = TestSymmKey::A(0);
1108        // Key with only Decrypt allowed
1109        let key = SymmetricCryptoKey::XChaCha20Poly1305Key(crate::XChaCha20Poly1305Key {
1110            key_id: [0u8; 16].into(),
1111            enc_key: Box::pin([0u8; 32].into()),
1112            supported_operations: vec![KeyOperation::Decrypt],
1113        });
1114        ctx.set_symmetric_key(key_id, key).unwrap();
1115        let data = DataView("should fail".to_string(), key_id);
1116        let result = data.encrypt_composite(&mut ctx, key_id);
1117        assert!(
1118            matches!(
1119                result,
1120                Err(CryptoError::KeyOperationNotSupported(KeyOperation::Encrypt))
1121            ),
1122            "Expected encrypt to fail with KeyOperationNotSupported",
1123        );
1124    }
1125
1126    #[test]
1127    fn test_xaes_data_roundtrip_and_encrypt_operation() {
1128        use coset::iana::KeyOperation;
1129
1130        let store = KeyStore::<TestIds>::default();
1131        let mut ctx = store.context_mut();
1132        let key_id = TestSymmKey::A(0);
1133        ctx.set_symmetric_key(
1134            key_id,
1135            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XAes256Gcm),
1136        )
1137        .unwrap();
1138
1139        let plaintext = b"data encrypted directly by the key store";
1140        let encrypted = ctx
1141            .encrypt_data_with_symmetric_key(key_id, plaintext, crate::ContentFormat::OctetStream)
1142            .unwrap();
1143        assert_eq!(
1144            ctx.decrypt_data_with_symmetric_key(key_id, &encrypted)
1145                .unwrap(),
1146            plaintext
1147        );
1148
1149        let no_encrypt = TestSymmKey::A(1);
1150        ctx.set_symmetric_key(
1151            no_encrypt,
1152            SymmetricCryptoKey::XAes256GcmKey(crate::XAes256GcmKey {
1153                key_id: [1; 16].into(),
1154                enc_key: Box::pin([1; 32].into()),
1155                supported_operations: vec![KeyOperation::Decrypt],
1156            }),
1157        )
1158        .unwrap();
1159        assert!(matches!(
1160            ctx.encrypt_data_with_symmetric_key(
1161                no_encrypt,
1162                plaintext,
1163                crate::ContentFormat::OctetStream,
1164            ),
1165            Err(CryptoError::KeyOperationNotSupported(KeyOperation::Encrypt))
1166        ));
1167    }
1168
1169    #[test]
1170    fn test_xaes_key_store_rejects_unsupported_inputs() {
1171        let store = KeyStore::<TestIds>::default();
1172        let mut ctx = store.context_mut();
1173        let xaes = TestSymmKey::A(0);
1174        ctx.set_symmetric_key(
1175            xaes,
1176            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XAes256Gcm),
1177        )
1178        .unwrap();
1179
1180        let non_key = ctx
1181            .encrypt_data_with_symmetric_key(xaes, b"not a key", crate::ContentFormat::OctetStream)
1182            .unwrap();
1183        assert!(matches!(
1184            ctx.unwrap_symmetric_key(xaes, &non_key),
1185            Err(CryptoError::InvalidKey)
1186        ));
1187
1188        let legacy_data =
1189            EncString::encrypt_aes256_hmac(b"data", &crate::derive_symmetric_key("test key"))
1190                .unwrap();
1191        assert!(matches!(
1192            ctx.decrypt_data_with_symmetric_key(xaes, &legacy_data),
1193            Err(CryptoError::InvalidKey)
1194        ));
1195    }
1196
1197    #[test]
1198    fn test_move_key() {
1199        let store: KeyStore<TestIds> = KeyStore::default();
1200        let mut ctx = store.context_mut();
1201
1202        // Generate and insert a key
1203        let key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
1204
1205        assert!(ctx.has_symmetric_key(key));
1206
1207        // Move the key to a new identifier
1208        let new_key_id = TestSymmKey::A(1);
1209        ctx.persist_symmetric_key(key, new_key_id).unwrap();
1210
1211        // Ensure the old key id is gone and the new `one has the key
1212        assert!(!ctx.has_symmetric_key(key));
1213        assert!(ctx.has_symmetric_key(new_key_id));
1214    }
1215
1216    #[test]
1217    fn test_encrypt_decrypt_data_fails_when_key_is_type_0() {
1218        let store = KeyStore::<TestIds>::default();
1219        let mut ctx = store.context_mut();
1220
1221        let key_id = TestSymmKey::A(0);
1222        let key = SymmetricCryptoKey::Aes256CbcKey(crate::Aes256CbcKey {
1223            enc_key: Box::pin([0u8; 32].into()),
1224        });
1225        ctx.set_symmetric_key_internal(key_id, key).unwrap();
1226
1227        let data_to_encrypt: Vec<u8> = vec![1, 2, 3, 4, 5];
1228        let result = ctx.encrypt_data_with_symmetric_key(
1229            key_id,
1230            &data_to_encrypt,
1231            crate::ContentFormat::OctetStream,
1232        );
1233        assert!(
1234            matches!(
1235                result,
1236                Err(CryptoError::OperationNotSupported(
1237                    crate::error::UnsupportedOperationError::EncryptionNotImplementedForKey
1238                ))
1239            ),
1240            "Expected encrypt to fail when using deprecated type 0 keys",
1241        );
1242
1243        let data_to_decrypt = EncString::Aes256Cbc_B64 {
1244            iv: [0; 16],
1245            data: data_to_encrypt,
1246        }; // dummy value; shouldn't matter
1247        let result = ctx.decrypt_data_with_symmetric_key(key_id, &data_to_decrypt);
1248        assert!(
1249            matches!(
1250                result,
1251                Err(CryptoError::OperationNotSupported(
1252                    crate::error::UnsupportedOperationError::DecryptionNotImplementedForKey
1253                ))
1254            ),
1255            "Expected decrypt to fail when using deprecated type 0 keys",
1256        );
1257    }
1258
1259    /// An unparseable `EncString` must fail at decryption time, with a precise error.
1260    #[test]
1261    fn test_decrypt_and_unwrap_fail_for_unparseable_enc_string() {
1262        let store = KeyStore::<TestIds>::default();
1263        let mut ctx = store.context_mut();
1264
1265        let key_id = TestSymmKey::A(0);
1266        ctx.set_symmetric_key_internal(key_id, SymmetricCryptoKey::make_aes256_cbc_hmac_key())
1267            .unwrap();
1268
1269        let unparseable: EncString = "2.AAECAw==|Y3Q=|AAECAw==".parse().unwrap();
1270
1271        assert!(matches!(
1272            ctx.decrypt_data_with_symmetric_key(key_id, &unparseable),
1273            Err(CryptoError::UnparseableEncString)
1274        ));
1275        assert!(matches!(
1276            ctx.unwrap_symmetric_key(key_id, &unparseable),
1277            Err(CryptoError::UnparseableEncString)
1278        ));
1279    }
1280
1281    #[test]
1282    fn test_wrap_unwrap_key_fails_when_key_is_type_0() {
1283        let store = KeyStore::<TestIds>::default();
1284        let mut ctx = store.context_mut();
1285
1286        let wrapping_key_id = TestSymmKey::A(0);
1287        let wrapping_key = SymmetricCryptoKey::Aes256CbcKey(crate::Aes256CbcKey {
1288            enc_key: Box::pin([0u8; 32].into()),
1289        });
1290        ctx.set_symmetric_key_internal(wrapping_key_id, wrapping_key)
1291            .unwrap();
1292
1293        let key_to_wrap_id = TestSymmKey::A(1);
1294        let key_to_wrap = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
1295        ctx.set_symmetric_key_internal(key_to_wrap_id, key_to_wrap)
1296            .unwrap();
1297
1298        let result = ctx.wrap_symmetric_key(wrapping_key_id, key_to_wrap_id);
1299        assert!(
1300            matches!(
1301                result,
1302                Err(CryptoError::OperationNotSupported(
1303                    crate::error::UnsupportedOperationError::EncryptionNotImplementedForKey
1304                ))
1305            ),
1306            "Expected encrypt to fail when using deprecated type 0 keys",
1307        );
1308
1309        let wrapped_key = &EncString::Aes256Cbc_B64 {
1310            iv: [0; 16],
1311            data: vec![0],
1312        }; // dummy value; shouldn't matter
1313        let result = ctx.unwrap_symmetric_key(wrapping_key_id, wrapped_key);
1314        assert!(
1315            matches!(
1316                result,
1317                Err(CryptoError::OperationNotSupported(
1318                    crate::error::UnsupportedOperationError::DecryptionNotImplementedForKey
1319                ))
1320            ),
1321            "Expected decrypt to fail when using deprecated type 0 keys",
1322        );
1323    }
1324
1325    /// Type 7 EncString sealed with [`aes_cbc_hmac_key`]; same vector as in `enc_string`.
1326    const AES256_CBC_HMAC_COSE_ENC_STRING: &str = "7.g1g/owE6AAERegN4I2FwcGxpY2F0aW9uL3guYml0d2FyZGVuLnV0ZjgtcGFkZGVkBFCsTs/7Lgh6WRgNHdGZULjpoQVQXYJbsJat2eG+9CcclU7mqVhwKiZITE/+y7LqmpX+A+QS7iZ3Ng/0/+zZnW/TFQ//5t5qnJl6p0GV3t804h4rSfwEGtXvI27//Uaup0KEq+XU8kwx5m4VSq8JarD48spPgxlrmpLncTpFgIh+Z6YDPc300PsAbOj+bHT+dSLFH7cRHA==";
1327    const AES256_CBC_HMAC_COSE_PLAINTEXT: &str = "Type 7 AES-256-CBC-HMAC test vector";
1328
1329    /// Type 7 EncString wrapping [`wrapped_cbc_hmac_key`] with [`aes_cbc_hmac_key`].
1330    const AES256_CBC_HMAC_COSE_WRAPPED_KEY: &str = "7.g1g+owE6AAERegN4ImFwcGxpY2F0aW9uL3guYml0d2FyZGVuLmxlZ2FjeS1rZXkEUKxOz/suCHpZGA0d0ZlQuOmhBVA/xHqu2ZfcJysRNmVH5qYlWHBIVgSz8gOKwZsPx3fPmRMza6dheBgQND7/vHtmRYVCp8UGYoT8WT2bgSl2vJy5QY782m9IzoXCLdLl21G0lGTRuwJtAOGfNwx1C8HR1ph44rgUug7rAP2qCc6Dfji2IXL6Y4qxblTC3LoelNcQsDgI";
1331
1332    /// Type 2 key with `enc_key = 0..32`, `mac_key = 32..64`.
1333    fn aes_cbc_hmac_key() -> SymmetricCryptoKey {
1334        SymmetricCryptoKey::Aes256CbcHmacKey(crate::Aes256CbcHmacKey::new(
1335            &std::array::from_fn(|i| i as u8),
1336            &std::array::from_fn(|i| (i + 32) as u8),
1337        ))
1338    }
1339
1340    /// Type 2 key with `enc_key = 64..96`, `mac_key = 96..128`.
1341    fn wrapped_cbc_hmac_key() -> SymmetricCryptoKey {
1342        SymmetricCryptoKey::Aes256CbcHmacKey(crate::Aes256CbcHmacKey::new(
1343            &std::array::from_fn(|i| (i + 64) as u8),
1344            &std::array::from_fn(|i| (i + 96) as u8),
1345        ))
1346    }
1347
1348    #[test]
1349    #[ignore = "Generates test vectors; run manually"]
1350    fn generate_aes256_cbc_hmac_wrapped_key_vector() {
1351        let wrapping_key = aes_cbc_hmac_key();
1352        let SymmetricCryptoKey::Aes256CbcHmacKey(key) = &wrapping_key else {
1353            unreachable!();
1354        };
1355        let protected_header = coset::HeaderBuilder::from(crate::ContentFormat::BitwardenLegacyKey)
1356            .key_id(key.key_id().as_slice().to_vec())
1357            .build();
1358        let message = crate::cose::symmetric::encrypt_cose0(
1359            crate::cose::symmetric::CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead,
1360            coset::CoseEncrypt0Builder::new(),
1361            protected_header,
1362            wrapped_cbc_hmac_key().to_encoded().as_ref(),
1363            key.as_composite_key(),
1364        )
1365        .unwrap();
1366        let enc_string = EncString::Cose_Encrypt0_B64 {
1367            data: coset::CborSerializable::to_vec(message).unwrap(),
1368        };
1369        println!(
1370            "const AES256_CBC_HMAC_COSE_WRAPPED_KEY: &str = \"{}\";",
1371            enc_string.to_string()
1372        );
1373    }
1374
1375    #[test]
1376    fn test_decrypt_type7_data_with_type2_key() {
1377        let store = KeyStore::<TestIds>::default();
1378        let mut ctx = store.context_mut();
1379        let key_id = TestSymmKey::A(0);
1380        ctx.set_symmetric_key(key_id, aes_cbc_hmac_key()).unwrap();
1381
1382        let enc_string: EncString = AES256_CBC_HMAC_COSE_ENC_STRING.parse().unwrap();
1383        let decrypted = ctx
1384            .decrypt_data_with_symmetric_key(key_id, &enc_string)
1385            .unwrap();
1386        assert_eq!(decrypted, AES256_CBC_HMAC_COSE_PLAINTEXT.as_bytes());
1387    }
1388
1389    #[test]
1390    fn test_unwrap_type7_key_with_type2_key() {
1391        let store = KeyStore::<TestIds>::default();
1392        let mut ctx = store.context_mut();
1393        let wrapping_key_id = TestSymmKey::A(0);
1394        let expected_key_id = TestSymmKey::A(1);
1395        ctx.set_symmetric_key(wrapping_key_id, aes_cbc_hmac_key())
1396            .unwrap();
1397        ctx.set_symmetric_key(expected_key_id, wrapped_cbc_hmac_key())
1398            .unwrap();
1399
1400        let wrapped_key: EncString = AES256_CBC_HMAC_COSE_WRAPPED_KEY.parse().unwrap();
1401        let unwrapped_key_id = ctx
1402            .unwrap_symmetric_key(wrapping_key_id, &wrapped_key)
1403            .unwrap();
1404        ctx.assert_symmetric_keys_equal(unwrapped_key_id, expected_key_id);
1405    }
1406}