Skip to main content

bitwarden_crypto/safe/
secret_protected_key_envelope.rs

1//! Secret protected key envelope is a cryptographic building block that allows sealing a symmetric
2//! key with a high-entropy secret (a random URL-fragment secret, a derived key, random bytes, etc.)
3//! of arbitrary length.
4//!
5//! It is implemented by using a cheap KDF (HKDF-SHA256) combined with symmetric key encryption
6//! (AES-256-GCM). Unlike the [crate::safe::PasswordProtectedKeyEnvelope], which protects a
7//! low-entropy secret (password, PIN) and therefore uses a hard KDF (Argon2ID, PBKDF2) to slow down
8//! brute-forcing, this envelope assumes the secret is high-entropy and not brute-forceable, so a
9//! cheap KDF is sufficient. The cheap KDF also natively accepts input material of arbitrary length.
10//!
11//! For the consumer, the output is an opaque blob that can be later unsealed with the same secret.
12//! The KDF salt is contained in the envelope, and does not need to be provided for unsealing.
13//!
14//! Internally, the envelope is a CoseEncrypt object that uses the standardized COSE "Direct Key
15//! with KDF" construction with the `direct+HKDF-SHA-256` recipient algorithm, as described in
16//! [RFC 9053 §6.1.2](https://datatracker.ietf.org/doc/html/rfc9053#name-direct-key-with-kdf). The
17//! random HKDF salt is placed in the single recipient's unprotected headers (the standardized
18//! `salt` header parameter), and the secret is used as the input keying material. The output from
19//! the KDF - "envelope key", is used directly as the content-encryption key that wraps the
20//! symmetric key sealed by the envelope.
21//!
22//! Note: AES-GCM is used here since the CEK is locally derived, so there is no nonce re-use
23//! problem.
24
25use std::{num::TryFromIntError, str::FromStr};
26
27use bitwarden_encoding::{B64, FromStrVisitor};
28use bitwarden_sensitive_value::ExposeSensitive;
29use ciborium::Value;
30use coset::{CborSerializable, CoseError, Header, HeaderBuilder, iana};
31use rand::Rng;
32use serde::{Deserialize, Serialize};
33use thiserror::Error;
34
35use crate::{
36    ContentFormat, EncodedSymmetricKey, KeySlotIds, KeyStoreContext, SymmetricCryptoKey,
37    cose::{
38        ContentNamespace, CoseExtractError, SafeObjectNamespace, extract_bytes,
39        symmetric::{
40            CoseAlgorithmPolicy, CoseContentEncryptionAlgorithm, decrypt_cose, encrypt_cose,
41        },
42    },
43    keys::KeyId,
44    safe::{
45        DecodeSealedKeyError, HighEntropySecret, decode_sealed_symmetric_key, extract_key_id,
46        extract_single_recipient,
47        helpers::{debug_fmt, set_safe_namespaces, validate_safe_namespaces},
48        set_contained_key_id,
49    },
50};
51
52/// The recipient algorithm used by the envelope: `direct+HKDF-SHA-256`
53/// (<https://datatracker.ietf.org/doc/html/rfc9053#name-direct-key-with-kdf>).
54const HKDF_ALGORITHM: coset::iana::Algorithm = iana::Algorithm::Direct_HKDF_SHA_256;
55/// The standardized COSE `salt` header algorithm parameter label (-20).
56const HKDF_SALT_LABEL: i64 = iana::HeaderAlgorithmParameter::Salt as i64;
57/// 32 matches the SHA-256 output size (HashLen), which is the RECOMMENDED salt size for HKDF:
58/// <https://datatracker.ietf.org/doc/html/rfc5869>
59const ENVELOPE_HKDF_SALT_SIZE: usize = 32;
60/// 32 is chosen to match the size of an AES-256-GCM key
61const ENVELOPE_HKDF_OUTPUT_KEY_SIZE: usize = 32;
62
63/// A secret-protected key envelope can seal a symmetric key, and protect it with a high-entropy
64/// secret of arbitrary length.
65///
66/// Unlike the [crate::safe::PasswordProtectedKeyEnvelope], which is meant for low-entropy secrets
67/// such as PINs and uses a compute-hard or memory-hard KDF, this envelope assumes the secret is
68/// high-entropy and thus uses a cheap KDF (HKDF). The KDF salt is stored in the envelope and does
69/// not have to be provided.
70///
71/// Internally, HKDF-SHA256 is used as the KDF and AES-256-GCM is used to encrypt the key.
72#[derive(Clone)]
73pub struct SecretProtectedKeyEnvelope {
74    cose_encrypt: coset::CoseEncrypt,
75}
76
77impl SecretProtectedKeyEnvelope {
78    /// Seals a symmetric key with a [`HighEntropySecret`], using a random salt.
79    ///
80    /// The secret is guaranteed to be high-entropy by the [`HighEntropySecret`] type, which the
81    /// cheap KDF used here relies on, since it cannot defend a low-entropy secret against
82    /// brute-forcing.
83    ///
84    /// This should never fail, except for memory allocation error, when running the KDF.
85    pub fn seal<Ids: KeySlotIds>(
86        key_to_seal: Ids::Symmetric,
87        secret: &HighEntropySecret,
88        namespace: SecretProtectedKeyEnvelopeNamespace,
89        ctx: &KeyStoreContext<Ids>,
90    ) -> Result<Self, SecretProtectedKeyEnvelopeError> {
91        let key_ref = ctx
92            .get_symmetric_key(key_to_seal)
93            .map_err(|_| SecretProtectedKeyEnvelopeError::KeyMissing)?;
94        Self::seal_ref(key_ref, secret, namespace)
95    }
96
97    /// Seals a key reference with a secret. This function is not public since callers are expected
98    /// to only work with key store references.
99    fn seal_ref(
100        key_to_seal: &SymmetricCryptoKey,
101        secret: &HighEntropySecret,
102        namespace: SecretProtectedKeyEnvelopeNamespace,
103    ) -> Result<Self, SecretProtectedKeyEnvelopeError> {
104        Self::seal_ref_with_settings(key_to_seal, secret, &HkdfSettings::new(), namespace)
105    }
106
107    /// Seals a key reference with a secret and custom provided settings. This function is not
108    /// public since callers are expected to only work with key store references.
109    fn seal_ref_with_settings(
110        key_to_seal: &SymmetricCryptoKey,
111        secret: &HighEntropySecret,
112        hkdf_settings: &HkdfSettings,
113        namespace: SecretProtectedKeyEnvelopeNamespace,
114    ) -> Result<Self, SecretProtectedKeyEnvelopeError> {
115        // The envelope key is directly derived from the KDF and used as the key to encrypt the key
116        // that should be sealed. The secret is guaranteed to be high-entropy by its type, which the
117        // cheap KDF relies on for brute-force resistance. The KDF context binds the derived key to
118        // the content-encryption algorithm, which is also declared in the protected header below.
119        // EXPOSE: derive_cek needs the raw secret bytes to feed the KDF; the bytes never leave this
120        // crate and are not logged.
121        // This envelope only uses AES-256-GCM; the KDF context is bound to its IANA algorithm id.
122        let cek = derive_cek(
123            hkdf_settings,
124            secret.as_bytes().expose_owned(),
125            iana::Algorithm::A256GCM,
126        )?;
127
128        let (content_format, key_to_seal_bytes) = match key_to_seal.to_encoded_raw() {
129            EncodedSymmetricKey::BitwardenLegacyKey(key_bytes) => {
130                (ContentFormat::BitwardenLegacyKey, key_bytes.to_vec())
131            }
132            EncodedSymmetricKey::CoseKey(key_bytes) => (ContentFormat::CoseKey, key_bytes.to_vec()),
133        };
134
135        let protected_header = {
136            let mut header = HeaderBuilder::from(content_format).build();
137            set_contained_key_id(&mut header, key_to_seal.key_id());
138            set_safe_namespaces(
139                &mut header,
140                SafeObjectNamespace::SecretProtectedKeyEnvelope,
141                namespace,
142            );
143            header
144        };
145
146        // The message is constructed by placing the KDF settings in a recipient struct's
147        // unprotected headers. The envelope key derived above is the content-encryption key, and
148        // the content-encryption algorithm is declared in the protected header by `encrypt_cose`.
149        let builder = coset::CoseEncryptBuilder::new().add_recipient(
150            coset::CoseRecipientBuilder::new()
151                .unprotected(hkdf_settings.into())
152                .build(),
153        );
154        // `cek` is the fixed-size key produced by `derive_cek`, so the length check inside
155        // `encrypt_cose` never trips here.
156        let cose_encrypt = encrypt_cose(
157            CoseContentEncryptionAlgorithm::Aes256Gcm,
158            builder,
159            protected_header,
160            &key_to_seal_bytes,
161            &cek,
162        )
163        .map_err(|_| SecretProtectedKeyEnvelopeError::Kdf)?;
164
165        Ok(SecretProtectedKeyEnvelope { cose_encrypt })
166    }
167
168    /// Unseals a symmetric key from the secret-protected envelope, and stores it in the key store
169    /// context.
170    pub fn unseal<Ids: KeySlotIds>(
171        &self,
172        secret: &HighEntropySecret,
173        namespace: SecretProtectedKeyEnvelopeNamespace,
174        ctx: &mut KeyStoreContext<Ids>,
175    ) -> Result<Ids::Symmetric, SecretProtectedKeyEnvelopeError> {
176        let key = self.unseal_ref(secret, namespace)?;
177        Ok(ctx.add_local_symmetric_key(key))
178    }
179
180    fn unseal_ref(
181        &self,
182        secret: &HighEntropySecret,
183        content_namespace: SecretProtectedKeyEnvelopeNamespace,
184    ) -> Result<SymmetricCryptoKey, SecretProtectedKeyEnvelopeError> {
185        // There must be exactly one recipient in the COSE Encrypt object, which contains the KDF
186        // parameters.
187        let recipient = extract_single_recipient(&self.cose_encrypt).map_err(|_| {
188            SecretProtectedKeyEnvelopeError::Parsing("Invalid number of recipients".to_string())
189        })?;
190
191        if recipient.unprotected.alg
192            != Some(coset::RegisteredLabelWithPrivate::Assigned(HKDF_ALGORITHM))
193        {
194            return Err(SecretProtectedKeyEnvelopeError::Parsing(
195                "Unknown or unsupported KDF algorithm".to_string(),
196            ));
197        }
198
199        validate_safe_namespaces(
200            &self.cose_encrypt.protected.header,
201            SafeObjectNamespace::SecretProtectedKeyEnvelope,
202            content_namespace,
203        )
204        .map_err(|_| SecretProtectedKeyEnvelopeError::InvalidNamespace)?;
205
206        let kdf_settings: HkdfSettings = (&recipient.unprotected).try_into().map_err(|_| {
207            SecretProtectedKeyEnvelopeError::Parsing(
208                "Invalid or missing KDF parameters".to_string(),
209            )
210        })?;
211        // The KDF context binds the derived key to the content-encryption algorithm declared in the
212        // protected header (RFC 9053 §6.1.2). `decrypt_cose` separately validates that this matches
213        // the cipher, and the header is authenticated as AEAD associated data.
214        let content_alg = content_encryption_algorithm(&self.cose_encrypt.protected.header)?;
215        // EXPOSE: derive_cek needs the raw secret bytes to feed the KDF; the bytes never leave this
216        // crate and are not logged.
217        let cek = derive_cek(&kdf_settings, secret.as_bytes().expose_owned(), content_alg)?;
218
219        // If decryption fails, the envelope-key is incorrect and thus the secret is incorrect
220        // since the KDF salt is guaranteed to be correct. The envelope always declares its
221        // content-encryption algorithm in the protected header, so no decryption fallback is
222        // needed.
223        let key_bytes = decrypt_cose(
224            &self.cose_encrypt,
225            CoseAlgorithmPolicy::RequireProtectedHeaderAlgorithm,
226            &cek,
227        )
228        .map_err(|_| SecretProtectedKeyEnvelopeError::WrongSecret)?;
229
230        decode_sealed_symmetric_key(&self.cose_encrypt.protected.header, key_bytes).map_err(|e| {
231            match e {
232                DecodeSealedKeyError::InvalidContentFormat => {
233                    SecretProtectedKeyEnvelopeError::Parsing("Invalid content format".to_string())
234                }
235                DecodeSealedKeyError::UnsupportedContentFormat => {
236                    SecretProtectedKeyEnvelopeError::Parsing(
237                        "Unknown or unsupported content format".to_string(),
238                    )
239                }
240                DecodeSealedKeyError::InvalidKey => {
241                    SecretProtectedKeyEnvelopeError::Parsing("Failed to decode key".to_string())
242                }
243            }
244        })
245    }
246
247    /// Re-seals the key with a new salt, and a new secret
248    pub fn reseal(
249        &self,
250        secret: &HighEntropySecret,
251        new_secret: &HighEntropySecret,
252        namespace: SecretProtectedKeyEnvelopeNamespace,
253    ) -> Result<Self, SecretProtectedKeyEnvelopeError> {
254        let unsealed = self.unseal_ref(secret, namespace)?;
255        Self::seal_ref(&unsealed, new_secret, namespace)
256    }
257
258    /// Get the key ID of the contained key, if the key ID is stored on the envelope headers.
259    /// Only COSE keys have a key ID, legacy keys do not.
260    pub fn contained_key_id(&self) -> Result<Option<KeyId>, SecretProtectedKeyEnvelopeError> {
261        extract_key_id(&self.cose_encrypt.protected.header)
262            .map_err(|_| SecretProtectedKeyEnvelopeError::Parsing("Invalid key id".to_string()))
263    }
264}
265
266impl From<&SecretProtectedKeyEnvelope> for Vec<u8> {
267    fn from(val: &SecretProtectedKeyEnvelope) -> Self {
268        val.cose_encrypt
269            .clone()
270            .to_vec()
271            .expect("Serialization to cose should not fail")
272    }
273}
274
275impl TryFrom<&Vec<u8>> for SecretProtectedKeyEnvelope {
276    type Error = CoseError;
277
278    fn try_from(value: &Vec<u8>) -> Result<Self, Self::Error> {
279        let cose_encrypt = coset::CoseEncrypt::from_slice(value)?;
280        Ok(SecretProtectedKeyEnvelope { cose_encrypt })
281    }
282}
283
284impl std::fmt::Debug for SecretProtectedKeyEnvelope {
285    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286        let mut s = f.debug_struct("SecretProtectedKeyEnvelope");
287
288        debug_fmt::<SecretProtectedKeyEnvelopeNamespace>(
289            &mut s,
290            &self.cose_encrypt.protected.header,
291        );
292
293        if let Ok(Some(key_id)) = self.contained_key_id() {
294            s.field("contained_key_id", &key_id);
295        }
296
297        s.finish()
298    }
299}
300
301impl FromStr for SecretProtectedKeyEnvelope {
302    type Err = SecretProtectedKeyEnvelopeError;
303
304    fn from_str(s: &str) -> Result<Self, Self::Err> {
305        let data = B64::try_from(s).map_err(|_| {
306            SecretProtectedKeyEnvelopeError::Parsing(
307                "Invalid SecretProtectedKeyEnvelope Base64 encoding".to_string(),
308            )
309        })?;
310        Self::try_from(&data.into_bytes()).map_err(|_| {
311            SecretProtectedKeyEnvelopeError::Parsing(
312                "Failed to parse SecretProtectedKeyEnvelope".to_string(),
313            )
314        })
315    }
316}
317
318impl From<SecretProtectedKeyEnvelope> for String {
319    fn from(val: SecretProtectedKeyEnvelope) -> Self {
320        let serialized: Vec<u8> = (&val).into();
321        B64::from(serialized).to_string()
322    }
323}
324
325impl<'de> Deserialize<'de> for SecretProtectedKeyEnvelope {
326    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
327    where
328        D: serde::Deserializer<'de>,
329    {
330        deserializer.deserialize_str(FromStrVisitor::new())
331    }
332}
333
334impl Serialize for SecretProtectedKeyEnvelope {
335    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
336    where
337        S: serde::Serializer,
338    {
339        let serialized: Vec<u8> = self.into();
340        serializer.serialize_str(&B64::from(serialized).to_string())
341    }
342}
343
344/// Raw HKDF settings. The salt is a fixed size, randomly generated value. Unlike a memory-hard KDF,
345/// HKDF has no difficulty parameters to tune, since the input secret is assumed to be high-entropy.
346struct HkdfSettings {
347    alg: iana::Algorithm,
348    salt: [u8; ENVELOPE_HKDF_SALT_SIZE],
349}
350
351impl HkdfSettings {
352    /// Creates HKDF settings with a freshly generated random salt.
353    fn new() -> Self {
354        Self {
355            alg: HKDF_ALGORITHM,
356            salt: make_salt(),
357        }
358    }
359}
360
361impl From<&HkdfSettings> for Header {
362    fn from(settings: &HkdfSettings) -> Header {
363        HeaderBuilder::new()
364            .value(HKDF_SALT_LABEL, Value::from(settings.salt.to_vec()))
365            .algorithm(settings.alg)
366            .build()
367    }
368}
369
370impl TryInto<HkdfSettings> for &Header {
371    type Error = SecretProtectedKeyEnvelopeError;
372
373    fn try_into(self) -> Result<HkdfSettings, SecretProtectedKeyEnvelopeError> {
374        Ok(HkdfSettings {
375            alg: match self.alg {
376                Some(coset::RegisteredLabelWithPrivate::Assigned(alg)) => alg,
377                _ => {
378                    return Err(SecretProtectedKeyEnvelopeError::Parsing(
379                        "Missing KDF algorithm".to_string(),
380                    ));
381                }
382            },
383            salt: extract_bytes(self, HKDF_SALT_LABEL, "salt")?
384                .try_into()
385                .map_err(|_| {
386                    SecretProtectedKeyEnvelopeError::Parsing("Invalid HKDF salt".to_string())
387                })?,
388        })
389    }
390}
391
392fn make_salt() -> [u8; ENVELOPE_HKDF_SALT_SIZE] {
393    let mut salt = [0u8; ENVELOPE_HKDF_SALT_SIZE];
394    bitwarden_random::rng().fill_bytes(&mut salt);
395    salt
396}
397
398/// Builds the serialized `COSE_KDF_Context` used as the HKDF `info` parameter, as required by the
399/// COSE "Direct Key with KDF" construction
400/// (<https://datatracker.ietf.org/doc/html/rfc9053#name-context-information-structu>):
401///
402/// ```cddl
403/// COSE_KDF_Context = [
404///     AlgorithmID : int / tstr,
405///     PartyUInfo  : [ identity / nil, nonce / nil, other / nil ],
406///     PartyVInfo  : [ identity / nil, nonce / nil, other / nil ],
407///     SuppPubInfo : [ keyDataLength : uint, protected : empty_or_serialized_map ],
408/// ]
409/// ```
410///
411/// The context binds the derived key to the content-encryption algorithm (`alg`) and the requested
412/// key length, providing domain separation. `PartyUInfo`/`PartyVInfo` are empty and `protected` is
413/// the empty (zero-length) map, since no additional negotiated parameters apply.
414fn kdf_context_info(alg: iana::Algorithm) -> Result<Vec<u8>, SecretProtectedKeyEnvelopeError> {
415    let empty_party_info = || Value::Array(vec![Value::Null, Value::Null, Value::Null]);
416    let context = Value::Array(vec![
417        // AlgorithmID: the content-encryption algorithm the derived key is used for. This is the
418        // algorithm declared in the protected header of the message (e.g. AES-256-GCM).
419        Value::Integer((alg as i64).into()),
420        empty_party_info(),
421        empty_party_info(),
422        Value::Array(vec![
423            // keyDataLength is expressed in bits.
424            Value::Integer((ENVELOPE_HKDF_OUTPUT_KEY_SIZE as u64 * 8).into()),
425            // An empty protected header is the zero-length byte string.
426            Value::Bytes(vec![]),
427        ]),
428    ]);
429
430    let mut info = Vec::new();
431    ciborium::into_writer(&context, &mut info).map_err(|_| SecretProtectedKeyEnvelopeError::Kdf)?;
432    Ok(info)
433}
434
435/// Reads the content-encryption algorithm declared in the protected header. This value is used as
436/// the `AlgorithmID` of the `COSE_KDF_Context`, binding the derived key to the message's declared
437/// algorithm (RFC 9053 §6.1.2).
438fn content_encryption_algorithm(
439    header: &Header,
440) -> Result<iana::Algorithm, SecretProtectedKeyEnvelopeError> {
441    match header.alg {
442        Some(coset::RegisteredLabelWithPrivate::Assigned(alg)) => Ok(alg),
443        _ => Err(SecretProtectedKeyEnvelopeError::Parsing(
444            "Missing or unsupported content encryption algorithm".to_string(),
445        )),
446    }
447}
448
449fn derive_cek(
450    hkdf_settings: &HkdfSettings,
451    secret: &[u8],
452    alg: iana::Algorithm,
453) -> Result<[u8; ENVELOPE_HKDF_OUTPUT_KEY_SIZE], SecretProtectedKeyEnvelopeError> {
454    // COSE "Direct Key with KDF" (RFC 9053 §6.1.2) using `direct+HKDF-SHA-256`: the secret is the
455    // input keying material, the random salt is the HKDF-Extract salt, and the serialized
456    // COSE_KDF_Context is the HKDF-Expand info. Full HKDF (extract + expand) is used since the
457    // secret can be of arbitrary length and is not required to be a uniformly random key.
458    let info = kdf_context_info(alg)?;
459    let hkdf = hkdf::Hkdf::<sha2::Sha256>::new(Some(&hkdf_settings.salt), secret);
460    let mut key = [0u8; ENVELOPE_HKDF_OUTPUT_KEY_SIZE];
461    hkdf.expand(&info, &mut key)
462        .map_err(|_| SecretProtectedKeyEnvelopeError::Kdf)?;
463    Ok(key)
464}
465
466/// Errors that can occur when sealing or unsealing a key with the `SecretProtectedKeyEnvelope`.
467#[derive(Debug, Error)]
468pub enum SecretProtectedKeyEnvelopeError {
469    /// The secret provided is incorrect or the envelope was tampered with
470    #[error("Wrong secret")]
471    WrongSecret,
472    /// The envelope could not be parsed correctly, or the KDF parameters are invalid
473    #[error("Parsing error {0}")]
474    Parsing(String),
475    /// The KDF failed to derive a key, possibly due to invalid parameters
476    #[error("Kdf error")]
477    Kdf,
478    /// There is no key for the provided key id in the key store
479    #[error("Key missing error")]
480    KeyMissing,
481    /// The key store could not be written to, for example due to being read-only
482    #[error("Could not write to key store")]
483    KeyStore,
484    /// The namespace provided in the envelope does not match any known namespaces, or is invalid
485    #[error("Invalid namespace")]
486    InvalidNamespace,
487}
488
489impl From<CoseExtractError> for SecretProtectedKeyEnvelopeError {
490    fn from(err: CoseExtractError) -> Self {
491        let CoseExtractError::MissingValue(label) = err;
492        SecretProtectedKeyEnvelopeError::Parsing(format!("Missing value for {}", label))
493    }
494}
495
496impl From<TryFromIntError> for SecretProtectedKeyEnvelopeError {
497    fn from(err: TryFromIntError) -> Self {
498        SecretProtectedKeyEnvelopeError::Parsing(format!("Invalid integer: {}", err))
499    }
500}
501
502#[cfg(feature = "wasm")]
503#[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
504const TS_CUSTOM_TYPES: &'static str = r#"
505export type SecretProtectedKeyEnvelope = Tagged<string, "SecretProtectedKeyEnvelope">;
506"#;
507
508bitwarden_ffi::impl_wire_string!(
509    SecretProtectedKeyEnvelope,
510    parse = |wire: String| wire.parse(),
511    format = String::from,
512);
513
514#[cfg(feature = "wasm")]
515impl TryFrom<wasm_bindgen::JsValue> for SecretProtectedKeyEnvelope {
516    type Error = SecretProtectedKeyEnvelopeError;
517
518    fn try_from(value: wasm_bindgen::JsValue) -> Result<Self, Self::Error> {
519        let string = value.as_string().ok_or_else(|| {
520            SecretProtectedKeyEnvelopeError::Parsing(
521                "SecretProtectedKeyEnvelope JsValue is not a string".to_string(),
522            )
523        })?;
524        SecretProtectedKeyEnvelope::from_str(&string)
525    }
526}
527
528/// The content-layer separation namespace for secret protected key envelopes.
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum SecretProtectedKeyEnvelopeNamespace {
531    /// Organization member invite links. The high-entropy secret is the random invite secret
532    /// carried in the invite link, and the sealed key is the invite key.
533    OrganizationInvite = 1,
534    /// Bitwarden Desktop biometric (Windows Hello) unlock. The high-entropy secret is a PRF derived
535    /// from the Windows Hello signing credential, and the sealed key is the user key.
536    DesktopBiometricUnlock = 2,
537    /// Used for threading the open-organization-invite data through the registration with email
538    /// verification process. Is generated per registration email.  
539    RegistrationOpenOrgInvite = 3,
540    /// This namespace is only used in tests
541    #[cfg(test)]
542    ExampleNamespace = -1,
543    /// This namespace is only used in tests
544    #[cfg(test)]
545    ExampleNamespace2 = -2,
546}
547
548impl SecretProtectedKeyEnvelopeNamespace {
549    /// Returns the numeric value of the namespace.
550    fn as_i64(&self) -> i64 {
551        *self as i64
552    }
553}
554
555impl TryFrom<i128> for SecretProtectedKeyEnvelopeNamespace {
556    type Error = SecretProtectedKeyEnvelopeError;
557
558    fn try_from(value: i128) -> Result<Self, Self::Error> {
559        match value {
560            1 => Ok(SecretProtectedKeyEnvelopeNamespace::OrganizationInvite),
561            2 => Ok(SecretProtectedKeyEnvelopeNamespace::DesktopBiometricUnlock),
562            3 => Ok(SecretProtectedKeyEnvelopeNamespace::RegistrationOpenOrgInvite),
563            #[cfg(test)]
564            -1 => Ok(SecretProtectedKeyEnvelopeNamespace::ExampleNamespace),
565            #[cfg(test)]
566            -2 => Ok(SecretProtectedKeyEnvelopeNamespace::ExampleNamespace2),
567            _ => Err(SecretProtectedKeyEnvelopeError::InvalidNamespace),
568        }
569    }
570}
571
572impl TryFrom<i64> for SecretProtectedKeyEnvelopeNamespace {
573    type Error = SecretProtectedKeyEnvelopeError;
574
575    fn try_from(value: i64) -> Result<Self, Self::Error> {
576        Self::try_from(i128::from(value))
577    }
578}
579
580impl From<SecretProtectedKeyEnvelopeNamespace> for i128 {
581    fn from(val: SecretProtectedKeyEnvelopeNamespace) -> Self {
582        val.as_i64().into()
583    }
584}
585
586impl ContentNamespace for SecretProtectedKeyEnvelopeNamespace {}
587
588#[cfg(test)]
589mod tests {
590    use super::*;
591    use crate::{KeyStore, SymmetricKeyAlgorithm, traits::tests::TestIds};
592
593    // A fixed, high-entropy (random) 32-byte secret. The envelope only accepts high-entropy
594    // secrets, so the test vectors must be sealed with random bytes rather than ASCII text.
595    const TESTVECTOR_SECRET_BYTES: &[u8] = &[
596        174, 83, 45, 9, 235, 3, 186, 62, 199, 125, 198, 108, 129, 205, 24, 21, 174, 148, 88, 80,
597        10, 238, 169, 66, 75, 202, 41, 201, 186, 244, 169, 67,
598    ];
599
600    fn testvector_secret() -> HighEntropySecret {
601        HighEntropySecret::from_internal(TESTVECTOR_SECRET_BYTES)
602    }
603
604    // Test vectors below are generated by sealing a key with `TESTVECTOR_SECRET_BYTES` and
605    // capturing the encoded key + the serialized envelope bytes (see the password-protected
606    // envelope for the same approach).
607    const TEST_UNSEALED_COSEKEY_ENCODED: &[u8] = &[
608        165, 1, 4, 2, 80, 214, 124, 137, 200, 1, 180, 227, 27, 77, 48, 119, 198, 210, 9, 149, 144,
609        3, 58, 0, 1, 17, 111, 4, 132, 3, 4, 5, 6, 32, 88, 32, 111, 105, 200, 46, 142, 185, 114,
610        127, 136, 152, 153, 40, 8, 62, 120, 184, 252, 175, 210, 2, 245, 237, 175, 195, 73, 211,
611        136, 23, 217, 203, 35, 10, 1,
612    ];
613    const TESTVECTOR_COSEKEY_ENVELOPE: &[u8] = &[
614        132, 88, 40, 165, 1, 3, 3, 24, 101, 58, 0, 1, 21, 92, 80, 214, 124, 137, 200, 1, 180, 227,
615        27, 77, 48, 119, 198, 210, 9, 149, 144, 58, 0, 1, 56, 129, 6, 58, 0, 1, 56, 128, 32, 161,
616        5, 76, 155, 157, 246, 33, 115, 165, 158, 222, 125, 222, 199, 188, 88, 84, 132, 235, 37,
617        236, 53, 75, 63, 253, 184, 134, 147, 83, 103, 87, 56, 81, 69, 202, 114, 23, 82, 25, 163,
618        68, 36, 13, 104, 187, 54, 143, 167, 113, 63, 62, 88, 146, 50, 214, 209, 170, 6, 235, 122,
619        44, 129, 149, 67, 213, 112, 112, 55, 51, 183, 165, 61, 168, 174, 215, 147, 110, 133, 164,
620        198, 29, 177, 84, 20, 203, 8, 0, 211, 218, 226, 62, 121, 51, 129, 230, 248, 66, 170, 83,
621        106, 109, 129, 131, 64, 162, 1, 41, 51, 88, 32, 123, 254, 226, 185, 81, 106, 88, 73, 109,
622        191, 241, 1, 143, 230, 179, 47, 36, 100, 235, 131, 4, 180, 12, 96, 125, 91, 184, 5, 175,
623        125, 188, 16, 246,
624    ];
625    const TEST_UNSEALED_LEGACYKEY_ENCODED: &[u8] = &[
626        23, 37, 64, 225, 53, 59, 143, 179, 18, 121, 128, 120, 86, 134, 93, 166, 214, 151, 210, 46,
627        240, 216, 69, 249, 247, 222, 110, 100, 185, 38, 173, 84, 202, 107, 132, 251, 144, 245, 105,
628        244, 220, 93, 212, 227, 98, 208, 173, 122, 245, 78, 244, 106, 174, 124, 109, 91, 53, 119,
629        96, 182, 45, 174, 206, 131,
630    ];
631    const TESTVECTOR_LEGACYKEY_ENVELOPE: &[u8] = &[
632        132, 88, 52, 164, 1, 3, 3, 120, 34, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47,
633        120, 46, 98, 105, 116, 119, 97, 114, 100, 101, 110, 46, 108, 101, 103, 97, 99, 121, 45,
634        107, 101, 121, 58, 0, 1, 56, 129, 6, 58, 0, 1, 56, 128, 32, 161, 5, 76, 20, 11, 52, 107,
635        155, 203, 125, 143, 165, 38, 59, 135, 88, 80, 84, 46, 227, 50, 142, 191, 103, 207, 31, 192,
636        201, 215, 163, 102, 18, 93, 181, 247, 229, 12, 166, 221, 143, 98, 86, 74, 138, 12, 165, 1,
637        206, 101, 240, 222, 51, 239, 216, 4, 85, 61, 212, 62, 44, 29, 1, 184, 4, 191, 189, 248,
638        174, 159, 11, 133, 205, 19, 22, 28, 148, 138, 238, 136, 253, 173, 250, 69, 186, 232, 91,
639        222, 238, 9, 175, 178, 214, 27, 120, 254, 212, 110, 129, 131, 64, 162, 1, 41, 51, 88, 32,
640        222, 10, 249, 242, 57, 196, 223, 240, 234, 177, 19, 72, 201, 32, 1, 129, 46, 6, 76, 38,
641        149, 151, 217, 94, 84, 67, 50, 107, 103, 74, 88, 72, 246,
642    ];
643
644    #[test]
645    fn test_registration_open_org_invite_namespace_maps_to_expected_discriminant() {
646        // The wire discriminant is load-bearing once shipped; a regression here would silently
647        // invalidate every envelope sealed by production callers.
648        assert_eq!(
649            SecretProtectedKeyEnvelopeNamespace::try_from(3i128).unwrap(),
650            SecretProtectedKeyEnvelopeNamespace::RegistrationOpenOrgInvite
651        );
652        assert_eq!(
653            i128::from(SecretProtectedKeyEnvelopeNamespace::RegistrationOpenOrgInvite),
654            3
655        );
656    }
657
658    #[test]
659    fn test_registration_open_org_invite_rejects_cross_namespace_unseal() {
660        // An envelope sealed under the new production namespace must not unseal under any
661        // other production namespace (here, the sibling production
662        // `DesktopBiometricUnlock`). Mirrors the sibling test in `data_envelope.rs` for the
663        // new variant.
664        let key_store = KeyStore::<TestIds>::default();
665        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
666        let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
667        let secret = testvector_secret();
668
669        let envelope = SecretProtectedKeyEnvelope::seal(
670            test_key,
671            &secret,
672            SecretProtectedKeyEnvelopeNamespace::RegistrationOpenOrgInvite,
673            &ctx,
674        )
675        .expect("seal");
676
677        assert!(matches!(
678            envelope.unseal(
679                &secret,
680                SecretProtectedKeyEnvelopeNamespace::DesktopBiometricUnlock,
681                &mut ctx,
682            ),
683            Err(SecretProtectedKeyEnvelopeError::InvalidNamespace)
684        ));
685
686        // Correct namespace still succeeds.
687        let _ = envelope
688            .unseal(
689                &secret,
690                SecretProtectedKeyEnvelopeNamespace::RegistrationOpenOrgInvite,
691                &mut ctx,
692            )
693            .expect("unseal under correct namespace succeeds");
694    }
695
696    #[test]
697    #[ignore = "Manual test to verify debug format"]
698    fn test_debug() {
699        let key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
700        let envelope = SecretProtectedKeyEnvelope::seal_ref(
701            &key,
702            &testvector_secret(),
703            SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
704        )
705        .unwrap();
706        println!("{:?}", envelope);
707    }
708
709    #[test]
710    fn test_testvector_cosekey() {
711        let key_store = KeyStore::<TestIds>::default();
712        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
713        let envelope = SecretProtectedKeyEnvelope::try_from(&TESTVECTOR_COSEKEY_ENVELOPE.to_vec())
714            .expect("Key envelope should be valid");
715        let key = envelope
716            .unseal(
717                &testvector_secret(),
718                SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
719                &mut ctx,
720            )
721            .expect("Unsealing should succeed");
722        let unsealed_key = ctx
723            .get_symmetric_key(key)
724            .expect("Key should exist in the key store");
725        assert_eq!(
726            unsealed_key.to_encoded().to_vec(),
727            TEST_UNSEALED_COSEKEY_ENCODED
728        );
729    }
730
731    #[test]
732    fn test_testvector_legacykey() {
733        let key_store = KeyStore::<TestIds>::default();
734        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
735        let envelope =
736            SecretProtectedKeyEnvelope::try_from(&TESTVECTOR_LEGACYKEY_ENVELOPE.to_vec())
737                .expect("Key envelope should be valid");
738        let key = envelope
739            .unseal(
740                &testvector_secret(),
741                SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
742                &mut ctx,
743            )
744            .expect("Unsealing should succeed");
745        let unsealed_key = ctx
746            .get_symmetric_key(key)
747            .expect("Key should exist in the key store");
748        assert_eq!(
749            unsealed_key.to_encoded().to_vec(),
750            TEST_UNSEALED_LEGACYKEY_ENCODED
751        );
752    }
753
754    #[test]
755    fn test_make_envelope() {
756        let key_store = KeyStore::<TestIds>::default();
757        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
758        let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
759
760        let secret = testvector_secret();
761
762        // Seal the key with a secret
763        let envelope = SecretProtectedKeyEnvelope::seal(
764            test_key,
765            &secret,
766            SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
767            &ctx,
768        )
769        .unwrap();
770        let serialized: Vec<u8> = (&envelope).into();
771
772        // Unseal the key from the envelope
773        let deserialized: SecretProtectedKeyEnvelope =
774            SecretProtectedKeyEnvelope::try_from(&serialized).unwrap();
775        let key = deserialized
776            .unseal(
777                &secret,
778                SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
779                &mut ctx,
780            )
781            .unwrap();
782
783        // Verify that the unsealed key matches the original key
784        let unsealed_key = ctx
785            .get_symmetric_key(key)
786            .expect("Key should exist in the key store");
787
788        let key_before_sealing = ctx
789            .get_symmetric_key(test_key)
790            .expect("Key should exist in the key store");
791
792        assert_eq!(unsealed_key, key_before_sealing);
793    }
794
795    #[test]
796    fn test_make_envelope_legacy_key() {
797        let key_store = KeyStore::<TestIds>::default();
798        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
799        let test_key = ctx.generate_symmetric_key();
800
801        let secret = testvector_secret();
802
803        // Seal the key with a secret
804        let envelope = SecretProtectedKeyEnvelope::seal(
805            test_key,
806            &secret,
807            SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
808            &ctx,
809        )
810        .unwrap();
811        let serialized: Vec<u8> = (&envelope).into();
812
813        // Unseal the key from the envelope
814        let deserialized: SecretProtectedKeyEnvelope =
815            SecretProtectedKeyEnvelope::try_from(&serialized).unwrap();
816        let key = deserialized
817            .unseal(
818                &secret,
819                SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
820                &mut ctx,
821            )
822            .unwrap();
823
824        // Verify that the unsealed key matches the original key
825        let unsealed_key = ctx
826            .get_symmetric_key(key)
827            .expect("Key should exist in the key store");
828
829        let key_before_sealing = ctx
830            .get_symmetric_key(test_key)
831            .expect("Key should exist in the key store");
832
833        assert_eq!(unsealed_key, key_before_sealing);
834    }
835
836    #[test]
837    fn test_reseal_envelope() {
838        let key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
839        let secret = testvector_secret();
840        let new_secret = HighEntropySecret::make(32).unwrap();
841
842        // Seal the key with a secret
843        let envelope: SecretProtectedKeyEnvelope = SecretProtectedKeyEnvelope::seal_ref(
844            &key,
845            &secret,
846            SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
847        )
848        .expect("Sealing should work");
849
850        // Reseal
851        let envelope = envelope
852            .reseal(
853                &secret,
854                &new_secret,
855                SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
856            )
857            .expect("Resealing should work");
858        let unsealed = envelope
859            .unseal_ref(
860                &new_secret,
861                SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
862            )
863            .expect("Unsealing should work");
864
865        // Verify that the unsealed key matches the original key
866        assert_eq!(unsealed, key);
867    }
868
869    #[test]
870    fn test_wrong_secret() {
871        let key_store = KeyStore::<TestIds>::default();
872        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
873        let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
874
875        let secret = testvector_secret();
876        let wrong_secret = HighEntropySecret::make(32).unwrap();
877
878        // Seal the key with a secret
879        let envelope = SecretProtectedKeyEnvelope::seal(
880            test_key,
881            &secret,
882            SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
883            &ctx,
884        )
885        .unwrap();
886
887        // Attempt to unseal with the wrong secret
888        let deserialized: SecretProtectedKeyEnvelope =
889            SecretProtectedKeyEnvelope::try_from(&(&envelope).into()).unwrap();
890        assert!(matches!(
891            deserialized.unseal(
892                &wrong_secret,
893                SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
894                &mut ctx
895            ),
896            Err(SecretProtectedKeyEnvelopeError::WrongSecret)
897        ));
898    }
899
900    #[test]
901    fn test_wrong_safe_namespace() {
902        let key_store = KeyStore::<TestIds>::default();
903        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
904        let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
905        let secret = testvector_secret();
906
907        let mut envelope = SecretProtectedKeyEnvelope::seal(
908            test_key,
909            &secret,
910            SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
911            &ctx,
912        )
913        .expect("Seal works");
914
915        if let Some((_, value)) = envelope
916            .cose_encrypt
917            .protected
918            .header
919            .rest
920            .iter_mut()
921            .find(|(label, _)| {
922                matches!(label, coset::Label::Int(label_value) if *label_value == crate::cose::SAFE_OBJECT_NAMESPACE)
923            })
924        {
925            *value = Value::Integer((SafeObjectNamespace::DataEnvelope as i64).into());
926        }
927
928        let deserialized: SecretProtectedKeyEnvelope =
929            SecretProtectedKeyEnvelope::try_from(&(&envelope).into())
930                .expect("Envelope should be valid");
931
932        assert!(matches!(
933            deserialized.unseal(
934                &secret,
935                SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
936                &mut ctx,
937            ),
938            Err(SecretProtectedKeyEnvelopeError::InvalidNamespace)
939        ));
940    }
941
942    #[test]
943    fn test_key_id() {
944        let key_store = KeyStore::<TestIds>::default();
945        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
946        let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
947        let key_id = ctx.get_symmetric_key(test_key).unwrap().key_id().unwrap();
948
949        let secret = testvector_secret();
950
951        // Seal the key with a secret
952        let envelope = SecretProtectedKeyEnvelope::seal(
953            test_key,
954            &secret,
955            SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
956            &ctx,
957        )
958        .unwrap();
959        let contained_key_id = envelope.contained_key_id().unwrap();
960        assert_eq!(Some(key_id), contained_key_id);
961    }
962
963    /// AES-CBC-HMAC keys have no stored key ID, but derive one from their key material, so a
964    /// sealed envelope still carries a contained key ID.
965    #[test]
966    fn test_derived_key_id_for_aes_cbc_hmac_key() {
967        let key_store = KeyStore::<TestIds>::default();
968        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
969        let test_key = ctx.generate_symmetric_key();
970        let key_id = ctx.get_symmetric_key(test_key).unwrap().key_id().unwrap();
971
972        let secret = testvector_secret();
973
974        // Seal the key with a secret
975        let envelope = SecretProtectedKeyEnvelope::seal(
976            test_key,
977            &secret,
978            SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
979            &ctx,
980        )
981        .unwrap();
982        let contained_key_id = envelope.contained_key_id().unwrap();
983        assert_eq!(Some(key_id), contained_key_id);
984    }
985}