Skip to main content

bitwarden_crypto/safe/
password_protected_key_envelope.rs

1//! Password protected key envelope is a cryptographic building block that allows sealing a
2//! symmetric key with a low entropy secret (password, PIN, etc.).
3//!
4//! It is implemented by using a KDF combined with secret key encryption. The KDF prevents
5//! brute-force by requiring work to be done to derive the key from the password. The algorithms
6//! depend on the key store's [`CipherSuite`]: the standard suite uses Argon2id + AES-256-GCM,
7//! while the FIPS suite uses the FIPS-approved PBKDF2 + AES-256-GCM.
8//!
9//! For the consumer, the output is an opaque blob that can be later unsealed with the same
10//! password. The KDF parameters and salt are contained in the envelope, and don't need to be
11//! provided for unsealing.
12//!
13//! Internally, the envelope is a CoseEncrypt object. The KDF parameters / salt are placed in the
14//! single recipient's unprotected headers. The output from the KDF - "envelope key", is used to
15//! wrap the symmetric key, that is sealed by the envelope.
16
17use std::{num::TryFromIntError, str::FromStr};
18
19use argon2::Params;
20use bitwarden_encoding::{B64, FromStrVisitor};
21use ciborium::{Value, value::Integer};
22use coset::{CborSerializable, CoseError, Header, HeaderBuilder};
23use rand::Rng;
24use serde::{Deserialize, Serialize};
25use thiserror::Error;
26
27use crate::{
28    CipherSuite, ContentFormat, EncodedSymmetricKey, KeySlotIds, KeyStoreContext,
29    SymmetricCryptoKey,
30    cose::{
31        ALG_ARGON2ID13, ALG_PBKDF2_SHA256, ARGON2_ITERATIONS, ARGON2_MEMORY, ARGON2_PARALLELISM,
32        ARGON2_SALT, ContentNamespace, CoseExtractError, PBKDF2_ITERATIONS, PBKDF2_SALT,
33        SafeObjectNamespace, extract_bytes, extract_integer,
34        symmetric::{
35            CoseAlgorithmPolicy, CoseContentEncryptionAlgorithm, decrypt_cose, encrypt_cose,
36        },
37    },
38    keys::KeyId,
39    safe::{
40        DecodeSealedKeyError, decode_sealed_symmetric_key, extract_key_id,
41        helpers::{debug_fmt, set_safe_namespaces, validate_safe_namespaces},
42        set_contained_key_id,
43    },
44    slow_crypto_span::{SlowCryptoOp, measure},
45};
46
47/// 16 is the RECOMMENDED salt size for all applications:
48/// <https://datatracker.ietf.org/doc/rfc9106/>
49const ENVELOPE_ARGON2_SALT_SIZE: usize = 16;
50/// 32 is chosen to match the size of an XChaCha20-Poly1305 key
51const ENVELOPE_ARGON2_OUTPUT_KEY_SIZE: usize = 32;
52const ENVELOPE_PBKDF2_SALT_SIZE: usize = 16;
53
54/// A password-protected key envelope can seal a symmetric key, and protect it with a password. It
55/// does so by using a Key Derivation Function (KDF), to increase the difficulty of brute-forcing
56/// the password.
57///
58/// The KDF parameters such as iterations and salt are stored in the envelope and do not have to
59/// be provided.
60///
61/// The algorithms used depend on the key store's [`CipherSuite`]: the standard suite uses Argon2id
62/// as the KDF, while the FIPS suite uses PBKDF2. Both suites encrypt the key with AES-256-GCM; the
63/// KDF and content-encryption algorithms are recorded in the envelope, so unsealing does not need
64/// to know the suite up front.
65#[derive(Clone)]
66pub struct PasswordProtectedKeyEnvelope {
67    cose_encrypt: coset::CoseEncrypt,
68}
69
70impl PasswordProtectedKeyEnvelope {
71    /// Seals a symmetric key with a password, using the current default KDF parameters and a random
72    /// salt.
73    ///
74    /// This should never fail, except for memory allocation error, when running the KDF.
75    pub fn seal<Ids: KeySlotIds>(
76        key_to_seal: Ids::Symmetric,
77        password: &str,
78        namespace: PasswordProtectedKeyEnvelopeNamespace,
79        ctx: &KeyStoreContext<Ids>,
80    ) -> Result<Self, PasswordProtectedKeyEnvelopeError> {
81        let key_ref = ctx
82            .get_symmetric_key(key_to_seal)
83            .map_err(|_| PasswordProtectedKeyEnvelopeError::KeyMissing)?;
84        let kdf = suite_kdf(ctx.cipher_suite());
85        Self::seal_ref_with_settings(key_ref, password, &kdf, namespace)
86    }
87
88    /// Seals a key reference with a password, using the standard cipher suite (Argon2id +
89    /// AES-256-GCM). This function is not public since callers are expected to only work
90    /// with key store references.
91    #[cfg(test)]
92    fn seal_ref(
93        key_to_seal: &SymmetricCryptoKey,
94        password: &str,
95        namespace: PasswordProtectedKeyEnvelopeNamespace,
96    ) -> Result<Self, PasswordProtectedKeyEnvelopeError> {
97        let kdf = suite_kdf(CipherSuite::Standard);
98        Self::seal_ref_with_settings(key_to_seal, password, &kdf, namespace)
99    }
100
101    /// Seals a key reference with a password, KDF settings, and content-encryption algorithm. This
102    /// function is not public since callers are expected to only work with key store references,
103    /// and to not control the KDF difficulty where possible.
104    fn seal_ref_with_settings(
105        key_to_seal: &SymmetricCryptoKey,
106        password: &str,
107        kdf: &EnvelopeKdf,
108        namespace: PasswordProtectedKeyEnvelopeNamespace,
109    ) -> Result<Self, PasswordProtectedKeyEnvelopeError> {
110        // Cose does not yet have a standardized way to protect a key using a password.
111        // This implements content encryption using direct encryption with a KDF derived key,
112        // similar to "Direct Key with KDF" mentioned in the COSE spec. The KDF settings are
113        // placed in a single recipient struct.
114
115        // The envelope key is directly derived from the KDF and used as the key to encrypt the key
116        // that should be sealed.
117        let envelope_key =
118            derive_key(kdf, password).map_err(|_| PasswordProtectedKeyEnvelopeError::Kdf)?;
119
120        let (content_format, key_to_seal_bytes) = match key_to_seal.to_encoded_raw() {
121            EncodedSymmetricKey::BitwardenLegacyKey(key_bytes) => {
122                (ContentFormat::BitwardenLegacyKey, key_bytes.to_vec())
123            }
124            EncodedSymmetricKey::CoseKey(key_bytes) => (ContentFormat::CoseKey, key_bytes.to_vec()),
125        };
126
127        let protected_header = {
128            let mut header = HeaderBuilder::from(content_format).build();
129            set_contained_key_id(&mut header, key_to_seal.key_id());
130            set_safe_namespaces(
131                &mut header,
132                SafeObjectNamespace::PasswordProtectedKeyEnvelope,
133                namespace,
134            );
135            header
136        };
137
138        // The message is constructed by placing the KDF settings in a single recipient struct's
139        // unprotected headers. They do not need to live in the protected header, since to
140        // authenticate the protected header, the settings must be correct.
141        let builder = coset::CoseEncryptBuilder::new().add_recipient({
142            let mut recipient = coset::CoseRecipientBuilder::new()
143                .unprotected(kdf.into())
144                .build();
145            recipient.protected.header.alg = Some(kdf.cose_alg());
146            recipient
147        });
148
149        let cose_encrypt = encrypt_cose(
150            CoseContentEncryptionAlgorithm::Aes256Gcm,
151            builder,
152            protected_header,
153            &key_to_seal_bytes,
154            &envelope_key,
155        )
156        .map_err(|_| PasswordProtectedKeyEnvelopeError::Kdf)?;
157
158        Ok(PasswordProtectedKeyEnvelope { cose_encrypt })
159    }
160
161    /// Unseals a symmetric key from the password-protected envelope, and stores it in the key store
162    /// context.
163    pub fn unseal<Ids: KeySlotIds>(
164        &self,
165        password: &str,
166        namespace: PasswordProtectedKeyEnvelopeNamespace,
167        ctx: &mut KeyStoreContext<Ids>,
168    ) -> Result<Ids::Symmetric, PasswordProtectedKeyEnvelopeError> {
169        let key = self.unseal_ref(password, namespace)?;
170        Ok(ctx.add_local_symmetric_key(key))
171    }
172
173    fn unseal_ref(
174        &self,
175        password: &str,
176        content_namespace: PasswordProtectedKeyEnvelopeNamespace,
177    ) -> Result<SymmetricCryptoKey, PasswordProtectedKeyEnvelopeError> {
178        // There must be exactly one recipient in the COSE Encrypt object, which contains the KDF
179        // parameters.
180        let recipient = self
181            .cose_encrypt
182            .recipients
183            .first()
184            .filter(|_| self.cose_encrypt.recipients.len() == 1)
185            .ok_or_else(|| {
186                PasswordProtectedKeyEnvelopeError::Parsing(
187                    "Invalid number of recipients".to_string(),
188                )
189            })?;
190
191        validate_safe_namespaces(
192            &self.cose_encrypt.protected.header,
193            SafeObjectNamespace::PasswordProtectedKeyEnvelope,
194            content_namespace,
195        )
196        .map_err(|_| PasswordProtectedKeyEnvelopeError::InvalidNamespace)?;
197
198        // The KDF algorithm and its parameters are read from the recipient. This dispatches to
199        // the correct KDF (Argon2id or PBKDF2), and errors on an unknown algorithm.
200        let kdf = EnvelopeKdf::try_from(recipient)?;
201        let envelope_key =
202            derive_key(&kdf, password).map_err(|_| PasswordProtectedKeyEnvelopeError::Kdf)?;
203
204        // If decryption fails, the envelope-key is incorrect and thus the password is incorrect
205        // since the KDF parameters & salt are guaranteed to be correct. Envelopes sealed before the
206        // content-encryption algorithm was written to the protected header omit it, so
207        // XChaCha20-Poly1305 (the only algorithm such legacy envelopes ever used) is supplied as
208        // the decryption fallback. Envelopes that declare their algorithm (including all
209        // AES-256-GCM envelopes) dispatch on the protected header regardless of this fallback.
210        let key_bytes = decrypt_cose(
211            &self.cose_encrypt,
212            CoseAlgorithmPolicy::ProtectedHeaderAlgorithmOrLegacyDefault(
213                CoseContentEncryptionAlgorithm::XChaCha20Poly1305,
214            ),
215            &envelope_key,
216        )
217        .map_err(|_| PasswordProtectedKeyEnvelopeError::WrongPassword)?;
218
219        decode_sealed_symmetric_key(&self.cose_encrypt.protected.header, key_bytes).map_err(|e| {
220            match e {
221                DecodeSealedKeyError::InvalidContentFormat => {
222                    PasswordProtectedKeyEnvelopeError::Parsing("Invalid content format".to_string())
223                }
224                DecodeSealedKeyError::UnsupportedContentFormat => {
225                    PasswordProtectedKeyEnvelopeError::Parsing(
226                        "Unknown or unsupported content format".to_string(),
227                    )
228                }
229                DecodeSealedKeyError::InvalidKey => {
230                    PasswordProtectedKeyEnvelopeError::Parsing("Failed to decode key".to_string())
231                }
232            }
233        })
234    }
235
236    /// Re-seals the envelope for a new password, but the same KDF settings.
237    ///
238    /// Note:
239    /// Resealing a legacy Argon2id + XChaCha20-Poly1305 envelope upgrades it to Argon2id +
240    /// AES-256-GCM and the encrypt path never uses XChaCha20-Poly1305.
241    pub fn reseal(
242        &self,
243        password: &str,
244        new_password: &str,
245        namespace: PasswordProtectedKeyEnvelopeNamespace,
246    ) -> Result<Self, PasswordProtectedKeyEnvelopeError> {
247        // Determine the existing envelope's KDF family from its single recipient, so the resealed
248        // envelope keeps the same KDF family. The content-encryption algorithm is always
249        // AES-256-GCM, so resealing never uses XChaCha20-Poly1305.
250        let recipient = self
251            .cose_encrypt
252            .recipients
253            .first()
254            .filter(|_| self.cose_encrypt.recipients.len() == 1)
255            .ok_or_else(|| {
256                PasswordProtectedKeyEnvelopeError::Parsing(
257                    "Invalid number of recipients".to_string(),
258                )
259            })?;
260
261        let unsealed = self.unseal_ref(password, namespace)?;
262        Self::seal_ref_with_settings(
263            &unsealed,
264            new_password,
265            &EnvelopeKdf::try_from(recipient)?,
266            namespace,
267        )
268    }
269
270    /// Get the key ID of the contained key, if the key ID is stored on the envelope headers.
271    /// Only COSE keys have a key ID, legacy keys do not.
272    pub fn contained_key_id(&self) -> Result<Option<KeyId>, PasswordProtectedKeyEnvelopeError> {
273        extract_key_id(&self.cose_encrypt.protected.header)
274            .map_err(|_| PasswordProtectedKeyEnvelopeError::Parsing("Invalid key id".to_string()))
275    }
276}
277
278impl From<&PasswordProtectedKeyEnvelope> for Vec<u8> {
279    fn from(val: &PasswordProtectedKeyEnvelope) -> Self {
280        val.cose_encrypt
281            .clone()
282            .to_vec()
283            .expect("Serialization to cose should not fail")
284    }
285}
286
287impl TryFrom<&Vec<u8>> for PasswordProtectedKeyEnvelope {
288    type Error = CoseError;
289
290    fn try_from(value: &Vec<u8>) -> Result<Self, Self::Error> {
291        let cose_encrypt = coset::CoseEncrypt::from_slice(value)?;
292        Ok(PasswordProtectedKeyEnvelope { cose_encrypt })
293    }
294}
295
296impl std::fmt::Debug for PasswordProtectedKeyEnvelope {
297    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298        let mut s = f.debug_struct("PasswordProtectedKeyEnvelope");
299
300        if let Some(recipient) = self.cose_encrypt.recipients.first() {
301            match EnvelopeKdf::try_from(recipient) {
302                Ok(EnvelopeKdf::Argon2id(settings)) => {
303                    s.field("kdf", &"Argon2id");
304                    s.field("argon2_iterations", &settings.iterations);
305                    s.field("argon2_memory_kib", &settings.memory);
306                    s.field("argon2_parallelism", &settings.parallelism);
307                }
308                Ok(EnvelopeKdf::Pbkdf2(settings)) => {
309                    s.field("kdf", &"PBKDF2-HMAC-SHA256");
310                    s.field("pbkdf2_iterations", &settings.iterations);
311                }
312                Err(_) => {}
313            }
314        }
315
316        debug_fmt::<PasswordProtectedKeyEnvelopeNamespace>(
317            &mut s,
318            &self.cose_encrypt.protected.header,
319        );
320
321        if let Ok(Some(key_id)) = self.contained_key_id() {
322            s.field("contained_key_id", &key_id);
323        }
324
325        s.finish()
326    }
327}
328
329impl FromStr for PasswordProtectedKeyEnvelope {
330    type Err = PasswordProtectedKeyEnvelopeError;
331
332    fn from_str(s: &str) -> Result<Self, Self::Err> {
333        let data = B64::try_from(s).map_err(|_| {
334            PasswordProtectedKeyEnvelopeError::Parsing(
335                "Invalid PasswordProtectedKeyEnvelope Base64 encoding".to_string(),
336            )
337        })?;
338        Self::try_from(&data.into_bytes()).map_err(|_| {
339            PasswordProtectedKeyEnvelopeError::Parsing(
340                "Failed to parse PasswordProtectedKeyEnvelope".to_string(),
341            )
342        })
343    }
344}
345
346impl From<PasswordProtectedKeyEnvelope> for String {
347    fn from(val: PasswordProtectedKeyEnvelope) -> Self {
348        let serialized: Vec<u8> = (&val).into();
349        B64::from(serialized).to_string()
350    }
351}
352
353impl<'de> Deserialize<'de> for PasswordProtectedKeyEnvelope {
354    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
355    where
356        D: serde::Deserializer<'de>,
357    {
358        deserializer.deserialize_str(FromStrVisitor::new())
359    }
360}
361
362impl Serialize for PasswordProtectedKeyEnvelope {
363    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
364    where
365        S: serde::Serializer,
366    {
367        let serialized: Vec<u8> = self.into();
368        serializer.serialize_str(&B64::from(serialized).to_string())
369    }
370}
371
372/// Default PBKDF2-HMAC-SHA256 iteration count for FIPS envelopes
373const ENVELOPE_PBKDF2_ITERATIONS: u32 = 600_000;
374
375/// The KDF used to derive the envelope key from the password. The variant, and thus the algorithm,
376/// is selected from the key store's [`CipherSuite`] at seal time and recorded in the envelope's
377/// recipient so unsealing can dispatch on it.
378enum EnvelopeKdf {
379    Argon2id(Argon2RawSettings),
380    Pbkdf2(Pbkdf2RawSettings),
381}
382
383impl EnvelopeKdf {
384    /// The COSE algorithm discriminant written to the recipient's protected header.
385    fn cose_alg(&self) -> coset::Algorithm {
386        match self {
387            EnvelopeKdf::Argon2id(_) => coset::Algorithm::PrivateUse(ALG_ARGON2ID13),
388            EnvelopeKdf::Pbkdf2(_) => coset::Algorithm::PrivateUse(ALG_PBKDF2_SHA256),
389        }
390    }
391}
392
393impl From<&EnvelopeKdf> for Header {
394    fn from(kdf: &EnvelopeKdf) -> Header {
395        match kdf {
396            EnvelopeKdf::Argon2id(settings) => settings.into(),
397            EnvelopeKdf::Pbkdf2(settings) => settings.into(),
398        }
399    }
400}
401
402impl TryFrom<&coset::CoseRecipient> for EnvelopeKdf {
403    type Error = PasswordProtectedKeyEnvelopeError;
404
405    fn try_from(recipient: &coset::CoseRecipient) -> Result<Self, Self::Error> {
406        let alg = recipient.protected.header.alg.as_ref();
407        if alg == Some(&coset::Algorithm::PrivateUse(ALG_ARGON2ID13)) {
408            Ok(EnvelopeKdf::Argon2id((&recipient.unprotected).try_into()?))
409        } else if alg == Some(&coset::Algorithm::PrivateUse(ALG_PBKDF2_SHA256)) {
410            Ok(EnvelopeKdf::Pbkdf2((&recipient.unprotected).try_into()?))
411        } else {
412            Err(PasswordProtectedKeyEnvelopeError::Parsing(
413                "Unknown or unsupported KDF algorithm".to_string(),
414            ))
415        }
416    }
417}
418
419/// Returns the KDF settings for the given cipher suite.
420fn suite_kdf(suite: CipherSuite) -> EnvelopeKdf {
421    match suite {
422        CipherSuite::Standard => EnvelopeKdf::Argon2id(Argon2RawSettings::local_kdf_settings()),
423        CipherSuite::Fips => EnvelopeKdf::Pbkdf2(Pbkdf2RawSettings::local_kdf_settings()),
424    }
425}
426
427/// Raw argon2 settings differ from the [crate::keys::Kdf::Argon2id] struct defined for existing
428/// master-password unlock. The memory is represented in kibibytes (KiB) instead of mebibytes (MiB),
429/// and the salt is a fixed size of 32 bytes, and randomly generated, instead of being derived from
430/// the email.
431struct Argon2RawSettings {
432    iterations: u32,
433    /// Memory in KiB
434    memory: u32,
435    parallelism: u32,
436    salt: [u8; ENVELOPE_ARGON2_SALT_SIZE],
437}
438
439impl Argon2RawSettings {
440    /// Creates default Argon2 settings based on the device. This currently is a static preset
441    /// based on the target os
442    fn local_kdf_settings() -> Self {
443        let mut salt = [0u8; ENVELOPE_ARGON2_SALT_SIZE];
444        bitwarden_random::rng().fill_bytes(&mut salt);
445
446        // iOS has memory limitations in the auto-fill context. So, the memory is halved
447        // but the iterations are doubled
448        if cfg!(target_os = "ios") {
449            // The SECOND RECOMMENDED option from: https://datatracker.ietf.org/doc/rfc9106/, with halved memory and doubled iteration count
450            Self {
451                iterations: 6,
452                memory: 32 * 1024, // 32 MiB
453                parallelism: 4,
454                salt,
455            }
456        } else {
457            // The SECOND RECOMMENDED option from: https://datatracker.ietf.org/doc/rfc9106/
458            // The FIRST RECOMMENDED option currently still has too much memory consumption for most
459            // clients except desktop.
460            Self {
461                iterations: 3,
462                memory: 64 * 1024, // 64 MiB
463                parallelism: 4,
464                salt,
465            }
466        }
467    }
468}
469
470impl From<&Argon2RawSettings> for Header {
471    fn from(settings: &Argon2RawSettings) -> Header {
472        let builder = HeaderBuilder::new()
473            .value(ARGON2_ITERATIONS, Integer::from(settings.iterations).into())
474            .value(ARGON2_MEMORY, Integer::from(settings.memory).into())
475            .value(
476                ARGON2_PARALLELISM,
477                Integer::from(settings.parallelism).into(),
478            )
479            .value(ARGON2_SALT, Value::from(settings.salt.to_vec()));
480
481        let mut header = builder.build();
482        header.alg = Some(coset::Algorithm::PrivateUse(ALG_ARGON2ID13));
483        header
484    }
485}
486
487impl TryInto<Params> for &Argon2RawSettings {
488    type Error = PasswordProtectedKeyEnvelopeError;
489
490    fn try_into(self) -> Result<Params, PasswordProtectedKeyEnvelopeError> {
491        Params::new(
492            self.memory,
493            self.iterations,
494            self.parallelism,
495            Some(ENVELOPE_ARGON2_OUTPUT_KEY_SIZE),
496        )
497        .map_err(|_| PasswordProtectedKeyEnvelopeError::Kdf)
498    }
499}
500
501impl TryInto<Argon2RawSettings> for &Header {
502    type Error = PasswordProtectedKeyEnvelopeError;
503
504    fn try_into(self) -> Result<Argon2RawSettings, PasswordProtectedKeyEnvelopeError> {
505        Ok(Argon2RawSettings {
506            iterations: extract_integer(self, ARGON2_ITERATIONS, "iterations")?.try_into()?,
507            memory: extract_integer(self, ARGON2_MEMORY, "memory")?.try_into()?,
508            parallelism: extract_integer(self, ARGON2_PARALLELISM, "parallelism")?.try_into()?,
509            salt: extract_bytes(self, ARGON2_SALT, "salt")?
510                .try_into()
511                .map_err(|_| {
512                    PasswordProtectedKeyEnvelopeError::Parsing("Invalid Argon2 salt".to_string())
513                })?,
514        })
515    }
516}
517
518/// Raw PBKDF2-HMAC-SHA256 settings for FIPS envelopes. Like [`Argon2RawSettings`], the salt is a
519/// fixed size and randomly generated, and lives in the envelope alongside the iteration count.
520struct Pbkdf2RawSettings {
521    iterations: u32,
522    salt: [u8; ENVELOPE_PBKDF2_SALT_SIZE],
523}
524
525impl Pbkdf2RawSettings {
526    /// Creates default PBKDF2 settings with a random salt.
527    fn local_kdf_settings() -> Self {
528        let mut salt = [0u8; ENVELOPE_PBKDF2_SALT_SIZE];
529        bitwarden_random::rng().fill_bytes(&mut salt);
530
531        Self {
532            iterations: ENVELOPE_PBKDF2_ITERATIONS,
533            salt,
534        }
535    }
536}
537
538impl From<&Pbkdf2RawSettings> for Header {
539    fn from(settings: &Pbkdf2RawSettings) -> Header {
540        let builder = HeaderBuilder::new()
541            .value(PBKDF2_ITERATIONS, Integer::from(settings.iterations).into())
542            .value(PBKDF2_SALT, Value::from(settings.salt.to_vec()));
543
544        let mut header = builder.build();
545        header.alg = Some(coset::Algorithm::PrivateUse(ALG_PBKDF2_SHA256));
546        header
547    }
548}
549
550impl TryInto<Pbkdf2RawSettings> for &Header {
551    type Error = PasswordProtectedKeyEnvelopeError;
552
553    fn try_into(self) -> Result<Pbkdf2RawSettings, PasswordProtectedKeyEnvelopeError> {
554        Ok(Pbkdf2RawSettings {
555            iterations: extract_integer(self, PBKDF2_ITERATIONS, "iterations")?.try_into()?,
556            salt: extract_bytes(self, PBKDF2_SALT, "salt")?
557                .try_into()
558                .map_err(|_| {
559                    PasswordProtectedKeyEnvelopeError::Parsing("Invalid PBKDF2 salt".to_string())
560                })?,
561        })
562    }
563}
564
565/// Derives the envelope key from the password using the configured KDF.
566fn derive_key(
567    kdf: &EnvelopeKdf,
568    password: &str,
569) -> Result<[u8; ENVELOPE_ARGON2_OUTPUT_KEY_SIZE], PasswordProtectedKeyEnvelopeError> {
570    match kdf {
571        EnvelopeKdf::Argon2id(settings) => derive_argon2_key(settings, password),
572        EnvelopeKdf::Pbkdf2(settings) => derive_pbkdf2_key(settings, password),
573    }
574}
575
576fn derive_argon2_key(
577    argon2_settings: &Argon2RawSettings,
578    password: &str,
579) -> Result<[u8; ENVELOPE_ARGON2_OUTPUT_KEY_SIZE], PasswordProtectedKeyEnvelopeError> {
580    use argon2::*;
581
582    let mut hash = [0u8; ENVELOPE_ARGON2_OUTPUT_KEY_SIZE];
583    let argon = Argon2::new(
584        Algorithm::Argon2id,
585        Version::V0x13,
586        argon2_settings.try_into()?,
587    );
588    measure(SlowCryptoOp::Argon2id, || {
589        argon.hash_password_into(password.as_bytes(), &argon2_settings.salt, &mut hash)
590    })
591    .map_err(|_| PasswordProtectedKeyEnvelopeError::Kdf)?;
592
593    Ok(hash)
594}
595
596fn derive_pbkdf2_key(
597    pbkdf2_settings: &Pbkdf2RawSettings,
598    password: &str,
599) -> Result<[u8; ENVELOPE_ARGON2_OUTPUT_KEY_SIZE], PasswordProtectedKeyEnvelopeError> {
600    Ok(measure(SlowCryptoOp::Pbkdf2, || {
601        crate::util::pbkdf2(
602            password.as_bytes(),
603            &pbkdf2_settings.salt,
604            pbkdf2_settings.iterations,
605        )
606    }))
607}
608
609/// Errors that can occur when sealing or unsealing a key with the `PasswordProtectedKeyEnvelope`.
610#[derive(Debug, Error)]
611pub enum PasswordProtectedKeyEnvelopeError {
612    /// The password provided is incorrect or the envelope was tampered with
613    #[error("Wrong password")]
614    WrongPassword,
615    /// The envelope could not be parsed correctly, or the KDF parameters are invalid
616    #[error("Parsing error {0}")]
617    Parsing(String),
618    /// The KDF failed to derive a key, possibly due to invalid parameters or memory allocation
619    /// issues
620    #[error("Kdf error")]
621    Kdf,
622    /// There is no key for the provided key id in the key store
623    #[error("Key missing error")]
624    KeyMissing,
625    /// The key store could not be written to, for example due to being read-only
626    #[error("Could not write to key store")]
627    KeyStore,
628    /// The namespace provided in the envelope does not match any known namespaces, or is invalid
629    #[error("Invalid namespace")]
630    InvalidNamespace,
631}
632
633impl From<CoseExtractError> for PasswordProtectedKeyEnvelopeError {
634    fn from(err: CoseExtractError) -> Self {
635        let CoseExtractError::MissingValue(label) = err;
636        PasswordProtectedKeyEnvelopeError::Parsing(format!("Missing value for {}", label))
637    }
638}
639
640impl From<TryFromIntError> for PasswordProtectedKeyEnvelopeError {
641    fn from(err: TryFromIntError) -> Self {
642        PasswordProtectedKeyEnvelopeError::Parsing(format!("Invalid integer: {}", err))
643    }
644}
645
646#[cfg(feature = "wasm")]
647#[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
648const TS_CUSTOM_TYPES: &'static str = r#"
649export type PasswordProtectedKeyEnvelope = Tagged<string, "PasswordProtectedKeyEnvelope">;
650"#;
651
652bitwarden_ffi::impl_wire_string!(
653    PasswordProtectedKeyEnvelope,
654    parse = |wire: String| wire.parse(),
655    format = String::from,
656);
657
658#[cfg(feature = "wasm")]
659impl TryFrom<wasm_bindgen::JsValue> for PasswordProtectedKeyEnvelope {
660    type Error = PasswordProtectedKeyEnvelopeError;
661
662    fn try_from(value: wasm_bindgen::JsValue) -> Result<Self, Self::Error> {
663        let string = value.as_string().ok_or_else(|| {
664            PasswordProtectedKeyEnvelopeError::Parsing(
665                "PasswordProtectedKeyEnvelope JsValue is not a string".to_string(),
666            )
667        })?;
668        PasswordProtectedKeyEnvelope::from_str(&string)
669    }
670}
671
672/// The content-layer separation namespace for password protected key envelopes.
673#[derive(Debug, Clone, Copy, PartialEq, Eq)]
674pub enum PasswordProtectedKeyEnvelopeNamespace {
675    /// The namespace for unlocking vaults with a PIN.
676    PinUnlock = 1,
677    /// This namespace is only used in tests
678    #[cfg(test)]
679    ExampleNamespace = -1,
680    /// This namespace is only used in tests
681    #[cfg(test)]
682    ExampleNamespace2 = -2,
683}
684
685impl PasswordProtectedKeyEnvelopeNamespace {
686    /// Returns the numeric value of the namespace.
687    fn as_i64(&self) -> i64 {
688        *self as i64
689    }
690}
691
692impl TryFrom<i128> for PasswordProtectedKeyEnvelopeNamespace {
693    type Error = PasswordProtectedKeyEnvelopeError;
694
695    fn try_from(value: i128) -> Result<Self, Self::Error> {
696        match value {
697            1 => Ok(PasswordProtectedKeyEnvelopeNamespace::PinUnlock),
698            #[cfg(test)]
699            -1 => Ok(PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace),
700            #[cfg(test)]
701            -2 => Ok(PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace2),
702            _ => Err(PasswordProtectedKeyEnvelopeError::InvalidNamespace),
703        }
704    }
705}
706
707impl TryFrom<i64> for PasswordProtectedKeyEnvelopeNamespace {
708    type Error = PasswordProtectedKeyEnvelopeError;
709
710    fn try_from(value: i64) -> Result<Self, Self::Error> {
711        Self::try_from(i128::from(value))
712    }
713}
714
715impl From<PasswordProtectedKeyEnvelopeNamespace> for i128 {
716    fn from(val: PasswordProtectedKeyEnvelopeNamespace) -> Self {
717        val.as_i64().into()
718    }
719}
720
721impl ContentNamespace for PasswordProtectedKeyEnvelopeNamespace {}
722
723#[cfg(test)]
724mod tests {
725    use super::*;
726    use crate::{KeyStore, SymmetricKeyAlgorithm, traits::tests::TestIds};
727
728    const TEST_UNSEALED_COSEKEY_ENCODED: &[u8] = &[
729        165, 1, 4, 2, 80, 63, 208, 189, 183, 204, 37, 72, 170, 179, 236, 190, 208, 22, 65, 227,
730        183, 3, 58, 0, 1, 17, 111, 4, 132, 3, 4, 5, 6, 32, 88, 32, 88, 25, 68, 85, 205, 28, 133,
731        28, 90, 147, 160, 145, 48, 3, 178, 184, 30, 11, 122, 132, 64, 59, 51, 233, 191, 117, 159,
732        117, 23, 168, 248, 36, 1,
733    ];
734    const TESTVECTOR_COSEKEY_ENVELOPE: &[u8] = &[
735        132, 68, 161, 3, 24, 101, 161, 5, 88, 24, 1, 31, 58, 230, 10, 92, 195, 233, 212, 7, 166,
736        252, 67, 115, 221, 58, 3, 191, 218, 188, 181, 192, 28, 11, 88, 84, 141, 183, 137, 167, 166,
737        161, 33, 82, 30, 255, 23, 10, 179, 149, 88, 24, 39, 60, 74, 232, 133, 44, 90, 98, 117, 31,
738        41, 69, 251, 76, 250, 141, 229, 83, 191, 6, 237, 107, 127, 93, 238, 110, 49, 125, 201, 37,
739        162, 120, 157, 32, 116, 195, 208, 143, 83, 254, 223, 93, 97, 158, 0, 24, 95, 197, 249, 35,
740        240, 3, 20, 71, 164, 97, 180, 29, 203, 69, 31, 151, 249, 244, 197, 91, 101, 174, 129, 131,
741        71, 161, 1, 58, 0, 1, 21, 87, 165, 1, 58, 0, 1, 21, 87, 58, 0, 1, 21, 89, 3, 58, 0, 1, 21,
742        90, 26, 0, 1, 0, 0, 58, 0, 1, 21, 91, 4, 58, 0, 1, 21, 88, 80, 165, 253, 56, 243, 255, 54,
743        246, 252, 231, 230, 33, 252, 49, 175, 1, 111, 246,
744    ];
745    const TEST_UNSEALED_LEGACYKEY_ENCODED: &[u8] = &[
746        135, 114, 97, 155, 115, 209, 215, 224, 175, 159, 231, 208, 15, 244, 40, 171, 239, 137, 57,
747        98, 207, 167, 231, 138, 145, 254, 28, 136, 236, 60, 23, 163, 4, 246, 219, 117, 104, 246,
748        86, 10, 152, 52, 90, 85, 58, 6, 70, 39, 111, 128, 93, 145, 143, 180, 77, 129, 178, 242, 82,
749        72, 57, 61, 192, 64,
750    ];
751    const TESTVECTOR_LEGACYKEY_ENVELOPE: &[u8] = &[
752        132, 88, 38, 161, 3, 120, 34, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47, 120,
753        46, 98, 105, 116, 119, 97, 114, 100, 101, 110, 46, 108, 101, 103, 97, 99, 121, 45, 107,
754        101, 121, 161, 5, 88, 24, 218, 72, 22, 79, 149, 30, 12, 36, 180, 212, 44, 21, 167, 208,
755        214, 221, 7, 91, 178, 12, 104, 17, 45, 219, 88, 80, 114, 38, 14, 165, 85, 229, 103, 108,
756        17, 175, 41, 43, 203, 175, 119, 125, 227, 127, 163, 214, 213, 138, 12, 216, 163, 204, 38,
757        222, 47, 11, 44, 231, 239, 170, 63, 8, 249, 56, 102, 18, 134, 34, 232, 193, 44, 19, 228,
758        17, 187, 199, 238, 187, 2, 13, 30, 112, 103, 110, 5, 31, 238, 58, 4, 24, 19, 239, 135, 57,
759        206, 190, 144, 83, 128, 204, 59, 155, 21, 80, 180, 34, 129, 131, 71, 161, 1, 58, 0, 1, 21,
760        87, 165, 1, 58, 0, 1, 21, 87, 58, 0, 1, 21, 89, 3, 58, 0, 1, 21, 90, 26, 0, 1, 0, 0, 58, 0,
761        1, 21, 91, 4, 58, 0, 1, 21, 88, 80, 212, 91, 185, 112, 92, 177, 108, 33, 182, 202, 26, 141,
762        11, 133, 95, 235, 246,
763    ];
764
765    const TESTVECTOR_PASSWORD: &str = "test_password";
766
767    // FIPS (PBKDF2-HMAC-SHA256 + AES-256-GCM) test vector, generated by `generate_fips_test_vector`
768    // with a low iteration count. Locks the FIPS envelope wire format for backward compatibility.
769    const TEST_UNSEALED_FIPS_ENCODED: &[u8] = &[
770        165, 1, 4, 2, 80, 40, 136, 73, 38, 113, 191, 48, 29, 141, 167, 113, 250, 16, 155, 74, 5, 3,
771        58, 0, 1, 17, 111, 4, 132, 3, 4, 5, 6, 32, 88, 32, 3, 78, 100, 122, 143, 20, 156, 26, 63,
772        89, 134, 100, 93, 32, 137, 121, 214, 98, 147, 183, 198, 61, 176, 86, 176, 65, 220, 38, 211,
773        233, 121, 100, 1,
774    ];
775    const TESTVECTOR_FIPS_ENVELOPE: &[u8] = &[
776        132, 88, 40, 165, 1, 3, 3, 24, 101, 58, 0, 1, 21, 92, 80, 40, 136, 73, 38, 113, 191, 48,
777        29, 141, 167, 113, 250, 16, 155, 74, 5, 58, 0, 1, 56, 129, 1, 58, 0, 1, 56, 128, 32, 161,
778        5, 76, 26, 141, 71, 238, 227, 209, 118, 32, 47, 159, 178, 11, 88, 84, 3, 184, 23, 73, 5,
779        232, 28, 144, 109, 242, 86, 211, 155, 157, 221, 76, 72, 122, 18, 64, 20, 190, 25, 34, 166,
780        3, 34, 125, 59, 172, 105, 238, 123, 17, 123, 55, 203, 107, 157, 37, 186, 240, 79, 103, 95,
781        160, 196, 38, 71, 202, 212, 241, 77, 159, 165, 31, 43, 163, 126, 182, 127, 90, 119, 35, 29,
782        155, 119, 121, 163, 98, 158, 18, 120, 199, 91, 197, 46, 224, 63, 215, 119, 191, 60, 21,
783        129, 131, 71, 161, 1, 58, 0, 1, 21, 97, 163, 1, 58, 0, 1, 21, 97, 58, 0, 1, 21, 98, 25, 19,
784        136, 58, 0, 1, 21, 99, 80, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 246,
785    ];
786
787    #[test]
788    #[ignore = "Manual test to verify debug format"]
789    fn test_debug() {
790        let key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
791        let envelope = PasswordProtectedKeyEnvelope::seal_ref(
792            &key,
793            "test_password",
794            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
795        )
796        .unwrap();
797        println!("{:?}", envelope);
798    }
799
800    #[test]
801    fn test_testvector_cosekey() {
802        let key_store = KeyStore::<TestIds>::default();
803        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
804        let envelope =
805            PasswordProtectedKeyEnvelope::try_from(&TESTVECTOR_COSEKEY_ENVELOPE.to_vec())
806                .expect("Key envelope should be valid");
807        let key = envelope
808            .unseal(
809                TESTVECTOR_PASSWORD,
810                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
811                &mut ctx,
812            )
813            .expect("Unsealing should succeed");
814        let unsealed_key = ctx
815            .get_symmetric_key(key)
816            .expect("Key should exist in the key store");
817        assert_eq!(
818            unsealed_key.to_encoded().to_vec(),
819            TEST_UNSEALED_COSEKEY_ENCODED
820        );
821    }
822
823    #[test]
824    fn test_testvector_legacykey() {
825        let key_store = KeyStore::<TestIds>::default();
826        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
827        let envelope =
828            PasswordProtectedKeyEnvelope::try_from(&TESTVECTOR_LEGACYKEY_ENVELOPE.to_vec())
829                .expect("Key envelope should be valid");
830        let key = envelope
831            .unseal(
832                TESTVECTOR_PASSWORD,
833                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
834                &mut ctx,
835            )
836            .expect("Unsealing should succeed");
837        let unsealed_key = ctx
838            .get_symmetric_key(key)
839            .expect("Key should exist in the key store");
840        assert_eq!(
841            unsealed_key.to_encoded().to_vec(),
842            TEST_UNSEALED_LEGACYKEY_ENCODED
843        );
844    }
845
846    #[test]
847    #[ignore = "Manual test to generate a FIPS (PBKDF2 + AES-GCM) test vector"]
848    fn generate_fips_test_vector() {
849        let key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
850        let envelope = PasswordProtectedKeyEnvelope::seal_ref_with_settings(
851            &key,
852            TESTVECTOR_PASSWORD,
853            &EnvelopeKdf::Pbkdf2(Pbkdf2RawSettings {
854                // Low iteration count keeps the test vector cheap to verify.
855                iterations: 5000,
856                salt: [7u8; ENVELOPE_PBKDF2_SALT_SIZE],
857            }),
858            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
859        )
860        .unwrap();
861        println!(
862            "const TEST_UNSEALED_FIPS_ENCODED: &[u8] = &{:?};",
863            key.to_encoded().to_vec()
864        );
865        println!(
866            "const TESTVECTOR_FIPS_ENVELOPE: &[u8] = &{:?};",
867            Vec::<u8>::from(&envelope)
868        );
869    }
870
871    #[test]
872    fn test_testvector_fips() {
873        let envelope = PasswordProtectedKeyEnvelope::try_from(&TESTVECTOR_FIPS_ENVELOPE.to_vec())
874            .expect("Key envelope should be valid");
875        let key = envelope
876            .unseal_ref(
877                TESTVECTOR_PASSWORD,
878                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
879            )
880            .expect("Unsealing should succeed");
881        assert_eq!(key.to_encoded().to_vec(), TEST_UNSEALED_FIPS_ENCODED);
882    }
883
884    #[test]
885    fn test_make_envelope() {
886        let key_store = KeyStore::<TestIds>::default();
887        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
888        let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
889
890        let password = "test_password";
891
892        // Seal the key with a password
893        let envelope = PasswordProtectedKeyEnvelope::seal(
894            test_key,
895            password,
896            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
897            &ctx,
898        )
899        .unwrap();
900        let serialized: Vec<u8> = (&envelope).into();
901
902        // Unseal the key from the envelope
903        let deserialized: PasswordProtectedKeyEnvelope =
904            PasswordProtectedKeyEnvelope::try_from(&serialized).unwrap();
905        let key = deserialized
906            .unseal(
907                password,
908                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
909                &mut ctx,
910            )
911            .unwrap();
912
913        // Verify that the unsealed key matches the original key
914        let unsealed_key = ctx
915            .get_symmetric_key(key)
916            .expect("Key should exist in the key store");
917
918        let key_before_sealing = ctx
919            .get_symmetric_key(test_key)
920            .expect("Key should exist in the key store");
921
922        assert_eq!(unsealed_key, key_before_sealing);
923    }
924
925    #[test]
926    fn test_make_envelope_legacy_key() {
927        let key_store = KeyStore::<TestIds>::default();
928        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
929        let test_key = ctx.generate_symmetric_key();
930
931        let password = "test_password";
932
933        // Seal the key with a password
934        let envelope = PasswordProtectedKeyEnvelope::seal(
935            test_key,
936            password,
937            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
938            &ctx,
939        )
940        .unwrap();
941        let serialized: Vec<u8> = (&envelope).into();
942
943        // Unseal the key from the envelope
944        let deserialized: PasswordProtectedKeyEnvelope =
945            PasswordProtectedKeyEnvelope::try_from(&serialized).unwrap();
946        let key = deserialized
947            .unseal(
948                password,
949                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
950                &mut ctx,
951            )
952            .unwrap();
953
954        // Verify that the unsealed key matches the original key
955        let unsealed_key = ctx
956            .get_symmetric_key(key)
957            .expect("Key should exist in the key store");
958
959        let key_before_sealing = ctx
960            .get_symmetric_key(test_key)
961            .expect("Key should exist in the key store");
962
963        assert_eq!(unsealed_key, key_before_sealing);
964    }
965
966    #[test]
967    fn test_reseal_envelope() {
968        let key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
969        let password = "test_password";
970        let new_password = "new_test_password";
971
972        // Seal the key with a password
973        let envelope: PasswordProtectedKeyEnvelope = PasswordProtectedKeyEnvelope::seal_ref(
974            &key,
975            password,
976            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
977        )
978        .expect("Sealing should work");
979
980        // Reseal
981        let envelope = envelope
982            .reseal(
983                password,
984                new_password,
985                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
986            )
987            .expect("Resealing should work");
988
989        // Resealing keeps the Argon2id KDF but always writes AES-256-GCM content, never
990        // XChaCha20-Poly1305.
991        assert_eq!(
992            envelope.cose_encrypt.recipients[0].protected.header.alg,
993            Some(coset::Algorithm::PrivateUse(ALG_ARGON2ID13))
994        );
995        assert_eq!(
996            envelope.cose_encrypt.protected.header.alg,
997            Some(coset::Algorithm::Assigned(coset::iana::Algorithm::A256GCM))
998        );
999
1000        let unsealed = envelope
1001            .unseal_ref(
1002                new_password,
1003                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1004            )
1005            .expect("Unsealing should work");
1006
1007        // Verify that the unsealed key matches the original key
1008        assert_eq!(unsealed, key);
1009    }
1010
1011    #[test]
1012    fn test_wrong_password() {
1013        let key_store = KeyStore::<TestIds>::default();
1014        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
1015        let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
1016
1017        let password = "test_password";
1018        let wrong_password = "wrong_password";
1019
1020        // Seal the key with a password
1021        let envelope = PasswordProtectedKeyEnvelope::seal(
1022            test_key,
1023            password,
1024            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1025            &ctx,
1026        )
1027        .unwrap();
1028
1029        // Attempt to unseal with the wrong password
1030        let deserialized: PasswordProtectedKeyEnvelope =
1031            PasswordProtectedKeyEnvelope::try_from(&(&envelope).into()).unwrap();
1032        assert!(matches!(
1033            deserialized.unseal(
1034                wrong_password,
1035                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1036                &mut ctx
1037            ),
1038            Err(PasswordProtectedKeyEnvelopeError::WrongPassword)
1039        ));
1040    }
1041
1042    #[test]
1043    fn test_wrong_safe_namespace() {
1044        let key_store = KeyStore::<TestIds>::default();
1045        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
1046        let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
1047        let password = "test_password";
1048
1049        let mut envelope = PasswordProtectedKeyEnvelope::seal(
1050            test_key,
1051            password,
1052            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1053            &ctx,
1054        )
1055        .expect("Seal works");
1056
1057        if let Some((_, value)) = envelope
1058            .cose_encrypt
1059            .protected
1060            .header
1061            .rest
1062            .iter_mut()
1063            .find(|(label, _)| {
1064                matches!(label, coset::Label::Int(label_value) if *label_value == crate::cose::SAFE_OBJECT_NAMESPACE)
1065            })
1066        {
1067            *value = Value::Integer((SafeObjectNamespace::DataEnvelope as i64).into());
1068        }
1069
1070        let deserialized: PasswordProtectedKeyEnvelope =
1071            PasswordProtectedKeyEnvelope::try_from(&(&envelope).into())
1072                .expect("Envelope should be valid");
1073
1074        let a = deserialized.unseal(
1075            password,
1076            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1077            &mut ctx,
1078        );
1079        println!("Error: {a:?}");
1080        assert!(matches!(
1081            a,
1082            Err(PasswordProtectedKeyEnvelopeError::InvalidNamespace)
1083        ));
1084    }
1085
1086    #[test]
1087    fn test_key_id() {
1088        let key_store = KeyStore::<TestIds>::default();
1089        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
1090        let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
1091        let key_id = ctx.get_symmetric_key(test_key).unwrap().key_id().unwrap();
1092
1093        let password = "test_password";
1094
1095        // Seal the key with a password
1096        let envelope = PasswordProtectedKeyEnvelope::seal(
1097            test_key,
1098            password,
1099            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1100            &ctx,
1101        )
1102        .unwrap();
1103        let contained_key_id = envelope.contained_key_id().unwrap();
1104        assert_eq!(Some(key_id), contained_key_id);
1105    }
1106
1107    /// AES-CBC-HMAC keys have no stored key ID, but derive one from their key material, so a
1108    /// sealed envelope still carries a contained key ID.
1109    #[test]
1110    fn test_derived_key_id_for_aes_cbc_hmac_key() {
1111        let key_store = KeyStore::<TestIds>::default();
1112        let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
1113        let test_key = ctx.generate_symmetric_key();
1114        let key_id = ctx.get_symmetric_key(test_key).unwrap().key_id().unwrap();
1115
1116        let password = "test_password";
1117
1118        // Seal the key with a password
1119        let envelope = PasswordProtectedKeyEnvelope::seal(
1120            test_key,
1121            password,
1122            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1123            &ctx,
1124        )
1125        .unwrap();
1126        let contained_key_id = envelope.contained_key_id().unwrap();
1127        assert_eq!(Some(key_id), contained_key_id);
1128    }
1129
1130    /// Builds a key store configured with the given cipher suite.
1131    fn key_store_with_suite(suite: CipherSuite) -> KeyStore<TestIds> {
1132        let key_store = KeyStore::<TestIds>::default();
1133        key_store.set_cipher_suite(suite);
1134        key_store
1135    }
1136
1137    #[test]
1138    fn test_standard_suite_uses_argon2_and_aes_gcm() {
1139        let key_store = key_store_with_suite(CipherSuite::Standard);
1140        let mut ctx = key_store.context_mut();
1141        let test_key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
1142        let key_id = ctx.add_local_symmetric_key(test_key);
1143
1144        let envelope = PasswordProtectedKeyEnvelope::seal(
1145            key_id,
1146            "test_password",
1147            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1148            &ctx,
1149        )
1150        .unwrap();
1151
1152        // Recipient declares Argon2id, content is AES-256-GCM (never XChaCha20-Poly1305).
1153        assert_eq!(
1154            envelope.cose_encrypt.recipients[0].protected.header.alg,
1155            Some(coset::Algorithm::PrivateUse(ALG_ARGON2ID13))
1156        );
1157        assert_eq!(
1158            envelope.cose_encrypt.protected.header.alg,
1159            Some(coset::Algorithm::Assigned(coset::iana::Algorithm::A256GCM))
1160        );
1161    }
1162
1163    #[test]
1164    fn test_fips_suite_uses_pbkdf2_and_aes_gcm() {
1165        let key_store = key_store_with_suite(CipherSuite::Fips);
1166        let mut ctx = key_store.context_mut();
1167        let test_key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
1168        let key_id = ctx.add_local_symmetric_key(test_key);
1169
1170        let password = "test_password";
1171        let envelope = PasswordProtectedKeyEnvelope::seal(
1172            key_id,
1173            password,
1174            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1175            &ctx,
1176        )
1177        .unwrap();
1178
1179        // Recipient declares PBKDF2, content is AES-256-GCM.
1180        assert_eq!(
1181            envelope.cose_encrypt.recipients[0].protected.header.alg,
1182            Some(coset::Algorithm::PrivateUse(ALG_PBKDF2_SHA256))
1183        );
1184        assert_eq!(
1185            envelope.cose_encrypt.protected.header.alg,
1186            Some(coset::Algorithm::Assigned(coset::iana::Algorithm::A256GCM))
1187        );
1188
1189        // Round-trips.
1190        let serialized: Vec<u8> = (&envelope).into();
1191        let deserialized = PasswordProtectedKeyEnvelope::try_from(&serialized).unwrap();
1192        let unsealed = deserialized
1193            .unseal(
1194                password,
1195                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1196                &mut ctx,
1197            )
1198            .unwrap();
1199        let unsealed_key = ctx.get_symmetric_key(unsealed).unwrap();
1200        let original = ctx.get_symmetric_key(key_id).unwrap();
1201        assert_eq!(unsealed_key, original);
1202    }
1203
1204    #[test]
1205    fn test_fips_wrong_password() {
1206        let key_store = key_store_with_suite(CipherSuite::Fips);
1207        let mut ctx = key_store.context_mut();
1208        let key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
1209
1210        let envelope = PasswordProtectedKeyEnvelope::seal(
1211            key_id,
1212            "test_password",
1213            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1214            &ctx,
1215        )
1216        .unwrap();
1217
1218        assert!(matches!(
1219            envelope.unseal(
1220                "wrong_password",
1221                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1222                &mut ctx,
1223            ),
1224            Err(PasswordProtectedKeyEnvelopeError::WrongPassword)
1225        ));
1226    }
1227
1228    #[test]
1229    fn test_reseal_preserves_fips_suite() {
1230        let key_store = key_store_with_suite(CipherSuite::Fips);
1231        let mut ctx = key_store.context_mut();
1232        let key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
1233
1234        let envelope = PasswordProtectedKeyEnvelope::seal(
1235            key_id,
1236            "test_password",
1237            PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1238            &ctx,
1239        )
1240        .unwrap();
1241
1242        let resealed = envelope
1243            .reseal(
1244                "test_password",
1245                "new_password",
1246                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1247            )
1248            .unwrap();
1249
1250        // The resealed envelope keeps the FIPS algorithm suite.
1251        assert_eq!(
1252            resealed.cose_encrypt.recipients[0].protected.header.alg,
1253            Some(coset::Algorithm::PrivateUse(ALG_PBKDF2_SHA256))
1254        );
1255        assert_eq!(
1256            resealed.cose_encrypt.protected.header.alg,
1257            Some(coset::Algorithm::Assigned(coset::iana::Algorithm::A256GCM))
1258        );
1259
1260        let unsealed = resealed
1261            .unseal_ref(
1262                "new_password",
1263                PasswordProtectedKeyEnvelopeNamespace::ExampleNamespace,
1264            )
1265            .unwrap();
1266        assert!(matches!(
1267            unsealed,
1268            SymmetricCryptoKey::XChaCha20Poly1305Key(_)
1269        ));
1270    }
1271}