Skip to main content

bitwarden_crypto/safe/
data_envelope.rs

1use std::str::FromStr;
2
3use bitwarden_encoding::{B64, FromStrVisitor, NotB64EncodedError};
4#[allow(unused_imports)]
5use coset::{CborSerializable, ProtectedHeader, RegisteredLabel, iana::CoapContentFormat};
6use serde::{Deserialize, Serialize, de::DeserializeOwned};
7use thiserror::Error;
8
9use crate::{
10    Aes256GcmKey, CONTENT_TYPE_PADDED_CBOR, CoseEncrypt0Bytes, CoseKeyView, CryptoError, EncString,
11    EncodingError, KeyId, KeySlotIds, SerializedMessage, SymmetricCryptoKey,
12    cose::{
13        ContentNamespace, SafeObjectNamespace,
14        symmetric::{
15            CoseAlgorithmPolicy, CoseContentEncryptionAlgorithm, decrypt_cose0, encrypt_cose0,
16        },
17    },
18    safe::{
19        ContentEncryptionKey,
20        helpers::{debug_fmt, set_safe_namespaces, validate_safe_namespaces},
21    },
22    utils::pad_bytes,
23};
24
25pub(crate) const DATA_ENVELOPE_PADDING_SIZE: usize = 64;
26
27/// Marker trait for data that can be sealed in a `DataEnvelope`.
28///
29/// Do not manually implement this! Use the generate_versioned_sealable! macro instead.
30pub trait SealableVersionedData: Serialize + DeserializeOwned {
31    /// The namespace to use when sealing this type of data. This must be unique per struct.
32    const NAMESPACE: DataEnvelopeNamespace;
33}
34
35/// Marker trait for data that can be sealed in a `DataEnvelope`.
36///
37/// Note: If you implement this trait, you agree to the following:
38/// The struct serialization format is stable. Struct modifications must maintain backward
39/// compatibility with existing serialized data. Changes that break deserialization are considered
40/// breaking changes and require a new version and struct.
41///
42/// Ideally, when creating a new struct, create a test vector (a sealed DataEnvelope for a test
43/// value), and create a unit test ensuring that it permanently deserializes correctly.
44///
45/// To make breaking changes, introduce a new version. This should use the
46/// `generate_versioned_sealable!` macro to auto-generate the versioning code. Please see the
47/// examples directory.
48pub trait SealableData: Serialize + DeserializeOwned {}
49
50/// `DataEnvelope` allows sealing structs entire structs to encrypted blobs.
51///
52/// Sealing a struct results in an encrypted blob, and a content-encryption-key. The
53/// content-encryption-key must be provided again when unsealing the data. A content encryption key
54/// allows easy key-rotation of the encrypting-key, as now just the content-encryption-keys need to
55/// be re-uploaded, instead of all data.
56///
57/// The content-encryption-key cannot be re-used for encrypting other data.
58///
59/// Note: This is explicitly meant for structured data, not large binary blobs (files).
60#[derive(Clone)]
61pub struct DataEnvelope {
62    envelope_data: CoseEncrypt0Bytes,
63}
64
65impl DataEnvelope {
66    /// Seals a struct into an encrypted blob, and stores the content-encryption-key in the provided
67    /// context.
68    pub fn seal<Ids: KeySlotIds, T>(
69        data: T,
70        ctx: &mut crate::store::KeyStoreContext<Ids>,
71    ) -> Result<(Self, Ids::Symmetric), DataEnvelopeError>
72    where
73        T: Serialize + SealableVersionedData,
74    {
75        // The content-encryption-key is a fresh, single-use content-encryption-key (CEK) stored in
76        // the context.
77        let cek_id = ContentEncryptionKey::make(ctx);
78        let mut cek = match ctx.get_symmetric_key(cek_id) {
79            Ok(SymmetricCryptoKey::Aes256GcmKey(key)) => key.clone(),
80            _ => return Err(DataEnvelopeError::KeyStore),
81        };
82        let envelope = Self::seal_ref(&data, T::NAMESPACE, &cek)?;
83
84        // Restrict the CEK to decryption only before persisting it: once the data is sealed, the
85        // CEK must never be used to encrypt, wrap, or unwrap again.
86        cek.disable_key_operation(coset::iana::KeyOperation::Encrypt)
87            .disable_key_operation(coset::iana::KeyOperation::WrapKey)
88            .disable_key_operation(coset::iana::KeyOperation::UnwrapKey);
89        ctx.set_symmetric_key_internal(cek_id, SymmetricCryptoKey::Aes256GcmKey(cek))
90            .map_err(|_| DataEnvelopeError::KeyStore)?;
91        Ok((envelope, cek_id))
92    }
93
94    /// Seals a struct into an encrypted blob. The content encryption key is wrapped with the
95    /// provided wrapping key
96    pub fn seal_with_wrapping_key<Ids: KeySlotIds, T>(
97        data: T,
98        wrapping_key: &Ids::Symmetric,
99        ctx: &mut crate::store::KeyStoreContext<Ids>,
100    ) -> Result<(Self, EncString), DataEnvelopeError>
101    where
102        T: Serialize + SealableVersionedData,
103    {
104        let (envelope, cek) = Self::seal(data, ctx)?;
105
106        let wrapped_cek = ctx
107            .wrap_symmetric_key(*wrapping_key, cek)
108            .map_err(|_| DataEnvelopeError::Encryption)?;
109
110        Ok((envelope, wrapped_cek))
111    }
112
113    /// Seals a struct into an encrypted blob using the provided content-encryption-key, and returns
114    /// the encrypted blob.
115    fn seal_ref<T>(
116        data: &T,
117        namespace: DataEnvelopeNamespace,
118        cek: &Aes256GcmKey,
119    ) -> Result<DataEnvelope, DataEnvelopeError>
120    where
121        T: Serialize + SealableVersionedData,
122    {
123        // Serialize the message
124        let serialized_message =
125            SerializedMessage::encode(&data).map_err(|_| DataEnvelopeError::Encoding)?;
126        if serialized_message.content_type() != coset::iana::CoapContentFormat::Cbor {
127            return Err(DataEnvelopeError::UnsupportedContentFormat);
128        }
129
130        let serialized_and_padded_message =
131            pad_cbor(serialized_message.as_bytes()).map_err(|_| DataEnvelopeError::Encoding)?;
132
133        // Build the COSE headers
134        let mut protected_header = coset::HeaderBuilder::new()
135            .key_id(cek.key_id.as_slice().to_vec())
136            .content_type(CONTENT_TYPE_PADDED_CBOR.to_string())
137            .build();
138        set_safe_namespaces(
139            &mut protected_header,
140            SafeObjectNamespace::DataEnvelope,
141            namespace,
142        );
143
144        // Encrypt the message. `encrypt_cose0` declares the content-encryption algorithm
145        // (AES-256-GCM) in the protected header and stores a fresh nonce in the unprotected `iv`
146        // header.
147        let encrypt0 = encrypt_cose0(
148            CoseContentEncryptionAlgorithm::Aes256Gcm,
149            coset::CoseEncrypt0Builder::new(),
150            protected_header,
151            &serialized_and_padded_message,
152            cek.enc_key.as_slice(),
153        )
154        .map_err(|_| DataEnvelopeError::Encoding)?;
155
156        // Serialize the COSE message
157        let envelope_data = encrypt0
158            .to_vec()
159            .map(CoseEncrypt0Bytes::from)
160            .map_err(|_| DataEnvelopeError::Encoding)?;
161
162        Ok(DataEnvelope { envelope_data })
163    }
164
165    /// Unseals the data from the encrypted blob using a content-encryption-key stored in the
166    /// context.
167    pub fn unseal<Ids: KeySlotIds, T>(
168        &self,
169        cek_keyslot: Ids::Symmetric,
170        ctx: &mut crate::store::KeyStoreContext<Ids>,
171    ) -> Result<T, DataEnvelopeError>
172    where
173        T: DeserializeOwned + SealableVersionedData,
174    {
175        let cek = ctx
176            .get_symmetric_key(cek_keyslot)
177            .map_err(|_| DataEnvelopeError::KeyStore)?;
178
179        // AES-256-GCM (current), XAES-256-GCM, and XChaCha20-Poly1305 (legacy)
180        // content-encryption keys are accepted. The typed key's algorithm must match the algorithm
181        // in the envelope's protected header.
182        let view = match cek {
183            SymmetricCryptoKey::Aes256CbcKey(_) | SymmetricCryptoKey::Aes256CbcHmacKey(_) => {
184                return Err(DataEnvelopeError::UnsupportedContentFormat);
185            }
186            cek => cek
187                .as_cose_key_view()
188                .ok_or(DataEnvelopeError::UnsupportedContentFormat)?,
189        };
190        self.unseal_ref(T::NAMESPACE, view)
191    }
192
193    /// Unseals the data from the encrypted blob and wrapped content-encryption-key.
194    pub fn unseal_with_wrapping_key<Ids: KeySlotIds, T>(
195        &self,
196        wrapping_key: &Ids::Symmetric,
197        wrapped_cek: &EncString,
198        ctx: &mut crate::store::KeyStoreContext<Ids>,
199    ) -> Result<T, DataEnvelopeError>
200    where
201        T: DeserializeOwned + SealableVersionedData,
202    {
203        let cek = ctx
204            .unwrap_symmetric_key(*wrapping_key, wrapped_cek)
205            .map_err(|_| DataEnvelopeError::Decryption)?;
206        self.unseal(cek, ctx)
207    }
208
209    /// Unseals the data from the encrypted blob using the provided content-encryption-key, which
210    /// may be an AES-256-GCM, XAES-256-GCM, or legacy XChaCha20-Poly1305 key.
211    fn unseal_ref<T>(
212        &self,
213        namespace: DataEnvelopeNamespace,
214        cek: CoseKeyView,
215    ) -> Result<T, DataEnvelopeError>
216    where
217        T: DeserializeOwned + SealableVersionedData,
218    {
219        // Parse the COSE message
220        let msg = coset::CoseEncrypt0::from_slice(self.envelope_data.as_ref())
221            .map_err(|_| DataEnvelopeError::CoseDecoding)?;
222        let content_format =
223            content_format(&msg.protected).map_err(|_| DataEnvelopeError::Decoding)?;
224
225        // Validate the message
226        if msg.protected.header.key_id != cek.key_id().as_slice() {
227            return Err(DataEnvelopeError::WrongKey);
228        }
229
230        validate_safe_namespaces(
231            &msg.protected.header,
232            SafeObjectNamespace::DataEnvelope,
233            namespace,
234        )
235        .map_err(|_| DataEnvelopeError::InvalidNamespace)?;
236
237        if content_format != CONTENT_TYPE_PADDED_CBOR {
238            return Err(DataEnvelopeError::UnsupportedContentFormat);
239        }
240
241        // Bind the protected content-encryption algorithm to the independently typed CEK before
242        // attempting decryption. DataEnvelope has no legacy format that omits the algorithm.
243        let decrypted_message = decrypt_cose0(
244            &msg,
245            CoseAlgorithmPolicy::Exactly(cek.algorithm()),
246            cek.key_bytes(),
247        )
248        .map_err(|_| DataEnvelopeError::Decryption)?;
249
250        let unpadded_message =
251            unpad_cbor(&decrypted_message).map_err(|_| DataEnvelopeError::Decryption)?;
252
253        // Deserialize the message
254        let serialized_message =
255            SerializedMessage::from_bytes(unpadded_message, CoapContentFormat::Cbor);
256        serialized_message
257            .decode()
258            .map_err(|_| DataEnvelopeError::Decoding)
259    }
260}
261
262/// Helper function to extract the content type from a `ProtectedHeader`. The content type is a
263/// standardized header set on the protected headers of the signature object. Currently we only
264/// support registered values, but PrivateUse values are also allowed in the COSE specification.
265pub(super) fn content_format(protected_header: &ProtectedHeader) -> Result<String, EncodingError> {
266    protected_header
267        .header
268        .content_type
269        .as_ref()
270        .and_then(|ct| match ct {
271            RegisteredLabel::Text(content_format) => Some(content_format.clone()),
272            _ => None,
273        })
274        .ok_or(EncodingError::InvalidCoseEncoding)
275}
276
277impl From<&DataEnvelope> for Vec<u8> {
278    fn from(val: &DataEnvelope) -> Self {
279        val.envelope_data.to_vec()
280    }
281}
282
283impl From<Vec<u8>> for DataEnvelope {
284    fn from(data: Vec<u8>) -> Self {
285        DataEnvelope {
286            envelope_data: CoseEncrypt0Bytes::from(data),
287        }
288    }
289}
290
291impl std::fmt::Debug for DataEnvelope {
292    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
293        let mut s = f.debug_struct("DataEnvelope");
294        if let Ok(msg) = coset::CoseEncrypt0::from_slice(self.envelope_data.as_ref()) {
295            debug_fmt::<DataEnvelopeNamespace>(&mut s, &msg.protected.header);
296            if let Ok(encrypted_by) = KeyId::try_from(msg.protected.header.key_id.as_slice()) {
297                s.field("encrypted_by", &encrypted_by);
298            }
299        }
300        s.finish()
301    }
302}
303
304impl FromStr for DataEnvelope {
305    type Err = NotB64EncodedError;
306
307    fn from_str(s: &str) -> Result<Self, Self::Err> {
308        let data = B64::try_from(s)?;
309        Ok(Self::from(data.into_bytes()))
310    }
311}
312
313impl From<DataEnvelope> for String {
314    fn from(val: DataEnvelope) -> Self {
315        let serialized: Vec<u8> = (&val).into();
316        B64::from(serialized).to_string()
317    }
318}
319
320impl<'de> Deserialize<'de> for DataEnvelope {
321    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
322    where
323        D: serde::Deserializer<'de>,
324    {
325        deserializer.deserialize_str(FromStrVisitor::new())
326    }
327}
328
329impl Serialize for DataEnvelope {
330    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
331    where
332        S: serde::Serializer,
333    {
334        let serialized: Vec<u8> = self.into();
335        serializer.serialize_str(&B64::from(serialized).to_string())
336    }
337}
338
339impl std::fmt::Display for DataEnvelope {
340    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341        let serialized: Vec<u8> = self.into();
342        write!(f, "{}", B64::from(serialized))
343    }
344}
345
346/// Error type for `DataEnvelope` operations.
347#[derive(Debug, Error)]
348pub enum DataEnvelopeError {
349    /// Indicates that the content format is not supported.
350    #[error("Unsupported content format")]
351    UnsupportedContentFormat,
352    /// Indicates that there was an error during decoding of the message.
353    #[error("Failed to decode COSE message")]
354    CoseDecoding,
355    /// Indicates that there was an error during decoding of the message.
356    #[error("Failed to decode the content of the envelope")]
357    Decoding,
358    /// Indicates that there was an error during encoding of the message.
359    #[error("Encoding error")]
360    Encoding,
361    /// Indicates that there was an error with the key store.
362    #[error("KeyStore error")]
363    KeyStore,
364    /// Indicates that there was an error during decryption.
365    #[error("Decryption error")]
366    Decryption,
367    /// Indicates that there was an error during encryption.
368    #[error("Encryption error")]
369    Encryption,
370    /// Indicates that there was an error parsing the DataEnvelope.
371    #[error("Parsing error: {0}")]
372    Parsing(String),
373    /// Indicates that the data envelope namespace is invalid.
374    #[error("Invalid namespace")]
375    InvalidNamespace,
376    /// Indicates that the wrong key was used for decryption.
377    #[error("Wrong key used for decryption")]
378    WrongKey,
379}
380
381#[cfg(feature = "wasm")]
382#[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
383const TS_CUSTOM_TYPES: &'static str = r#"
384export type DataEnvelope = Tagged<string, "DataEnvelope">;
385"#;
386
387bitwarden_ffi::impl_wire_string!(DataEnvelope, parse = |wire: String| wire.parse());
388
389fn pad_cbor(data: &[u8]) -> Result<Vec<u8>, CryptoError> {
390    let mut data = data.to_vec();
391    pad_bytes(&mut data, DATA_ENVELOPE_PADDING_SIZE).map_err(|_| CryptoError::InvalidPadding)?;
392    Ok(data)
393}
394
395fn unpad_cbor(data: &[u8]) -> Result<Vec<u8>, CryptoError> {
396    let unpadded = crate::utils::unpad_bytes(data).map_err(|_| CryptoError::InvalidPadding)?;
397    Ok(unpadded.to_vec())
398}
399
400/// Generates a versioned enum that implements `SealableData`.
401///
402/// This serializes to an adjacently tagged enum, with the "version" field being set to the provided
403/// version, and the "content" field being the serialized struct.
404///
405///
406/// ```
407/// use bitwarden_crypto::{safe::{DataEnvelopeNamespace, SealableData, SealableVersionedData}, generate_versioned_sealable};
408/// use serde::{Deserialize, Serialize};
409///
410/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
411/// struct MyItemV1 {
412///     a: u32,
413///     b: String,
414/// }
415/// impl SealableData for MyItemV1 {}
416///
417/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
418/// struct MyItemV2 {
419///     a: u32,
420///     b: bool,
421///     c: bool,
422/// }
423/// impl SealableData for MyItemV2 {}
424///
425/// generate_versioned_sealable!(
426///     MyItem,
427///     DataEnvelopeNamespace::VaultItem,
428///     [
429///         MyItemV1 => "1",
430///         MyItemV2 => "2",
431///     ]
432/// );
433/// ```
434#[macro_export]
435macro_rules! generate_versioned_sealable {
436    (
437        // Provide the name
438        $enum_name:ident,
439        // Provide the namespace
440        $namespace:path,
441        // Provide mappings from the variant to version. This must not be changed later.
442        [ $( $variant_ty:ident => $rename:literal ),+ $(,)? ]
443    ) => {
444        // Implement the enum
445        #[derive(Serialize, Deserialize, Debug, PartialEq)]
446        #[serde(tag = "version", content = "content")]
447        enum $enum_name {
448            $(
449                #[serde(rename = $rename)]
450                // Strip the `MyItem` prefix from type name if you want shorter variant names
451                $variant_ty($variant_ty),
452            )+
453        }
454
455        // Implement the SealableVersionedData trait for the enum
456        impl SealableVersionedData for $enum_name
457        where
458            $( $variant_ty: SealableData ),+
459        {
460            // Implement with the specified namespace
461            const NAMESPACE: DataEnvelopeNamespace = $namespace;
462        }
463
464        // Implement Into from each variant to the enum
465        $(
466            impl From<$variant_ty> for $enum_name {
467                fn from(value: $variant_ty) -> Self {
468                    Self::$variant_ty(value)
469                }
470            }
471        )+
472    };
473}
474
475/// Data envelopes are domain-separated within bitwarden, to prevent cross protocol attacks.
476///
477/// A new struct shall use a new data envelope namespace. Generally, this means
478/// that a data envelope namespace has exactly one associated valid message struct. Internal
479/// versioning within a namespace is permitted and up to the domain owner to ensure is done
480/// correctly.
481#[derive(Debug, Clone, Copy, PartialEq, Eq)]
482pub enum DataEnvelopeNamespace {
483    /// The namespace for vault items ("ciphers")
484    VaultItem = 1,
485    /// The namespace for organization member invite data (the organization public-key thumbprint
486    /// and the invite secret), sealed with the invite key.
487    OrganizationInvite = 2,
488    /// Namespace for the invite context payload sealed on registration-start and unsealed on
489    /// registration-finish so an anonymous, email-verified new user can complete an open
490    /// organization invite in a single flow.
491    RegistrationOpenOrgInviteData = 3,
492    /// Namespace for PAM target systems (`bitwarden-pam-sealed::TargetSystemSealed`), sealed by
493    /// the admin client so a hostile server cannot change what the access connector rotates or
494    /// how.
495    PamTargetSystem = 4,
496    /// Namespace for PAM rotation configs (`bitwarden-pam-sealed::RotationConfigSealed`), sealed
497    /// for the same reason as [`DataEnvelopeNamespace::PamTargetSystem`].
498    PamRotationConfig = 5,
499    /// This namespace is only used in tests
500    #[cfg(test)]
501    ExampleNamespace = -1,
502    /// This namespace is only used in tests
503    #[cfg(test)]
504    ExampleNamespace2 = -2,
505}
506
507impl DataEnvelopeNamespace {
508    /// Returns the numeric value of the namespace.
509    fn as_i64(&self) -> i64 {
510        *self as i64
511    }
512}
513
514impl TryFrom<i128> for DataEnvelopeNamespace {
515    type Error = DataEnvelopeError;
516
517    fn try_from(value: i128) -> Result<Self, Self::Error> {
518        match value {
519            1 => Ok(DataEnvelopeNamespace::VaultItem),
520            2 => Ok(DataEnvelopeNamespace::OrganizationInvite),
521            3 => Ok(DataEnvelopeNamespace::RegistrationOpenOrgInviteData),
522            4 => Ok(DataEnvelopeNamespace::PamTargetSystem),
523            5 => Ok(DataEnvelopeNamespace::PamRotationConfig),
524            #[cfg(test)]
525            -1 => Ok(DataEnvelopeNamespace::ExampleNamespace),
526            #[cfg(test)]
527            -2 => Ok(DataEnvelopeNamespace::ExampleNamespace2),
528            _ => Err(DataEnvelopeError::InvalidNamespace),
529        }
530    }
531}
532
533impl TryFrom<i64> for DataEnvelopeNamespace {
534    type Error = DataEnvelopeError;
535
536    fn try_from(value: i64) -> Result<Self, Self::Error> {
537        Self::try_from(i128::from(value))
538    }
539}
540
541impl From<DataEnvelopeNamespace> for i128 {
542    fn from(val: DataEnvelopeNamespace) -> Self {
543        val.as_i64().into()
544    }
545}
546
547impl ContentNamespace for DataEnvelopeNamespace {}
548
549#[cfg(test)]
550mod tests {
551    use serde::Deserialize;
552
553    use super::*;
554    use crate::{SymmetricKeyAlgorithm, safe::KeyEncryptionKey, traits::tests::TestIds};
555
556    #[derive(Serialize, Deserialize, Debug, PartialEq)]
557    struct TestDataV1 {
558        field: u32,
559    }
560    impl SealableData for TestDataV1 {}
561
562    generate_versioned_sealable!(
563        TestData,
564        DataEnvelopeNamespace::ExampleNamespace,
565        [
566            TestDataV1 => "1",
567        ]
568    );
569
570    /// Legacy XChaCha20-Poly1305 test vector, kept to prove that DataEnvelopes sealed before the
571    /// switch to AES-256-GCM still decrypt (the algorithm is recovered from the protected header).
572    const TEST_VECTOR_CEK: &str =
573        "pQEEAlB5RTKA0xXdA7C4iQE4QfVUAzoAARFvBIEEIFggQYqnsrAfeFFTaXGXB54YrksB6eQcctMpnaZ8rG6rMJ0B";
574    const TEST_VECTOR_ENVELOPE: &str = "g1hLpQE6AAERbwN4I2FwcGxpY2F0aW9uL3guYml0d2FyZGVuLmNib3ItcGFkZGVkBFB5RTKA0xXdA7C4iQE4QfVUOgABOIECOgABOIAgoQVYGLfQrYHVWxRxO6A8m/yp5DPbBIn3h8nijlhQj4jFwDLWfFz7le1Oy8dTls5vdEFg/FjjsPvXicI2bdb5KDdJCz/YkEu0kqjpQwdCcALpJLVJwgQQeKIeU2klBHEPZjnlLpRRXeCUp5c5BYQ=";
575
576    /// AES-256-GCM test vector, generated by `generate_aes_gcm_test_vectors`. Locks the current
577    /// (FIPS-compatible) DataEnvelope wire format for backward compatibility.
578    const TEST_VECTOR_AES_GCM_CEK: &str =
579        "pQEEAlDLIx+izSLk9h9sVjHFzpKoAwMEgQQgWCDWM3iwTX2/LHTIaXS0cPIKCYFZethtKyD6Pucdt4fkGQQEBAQ=";
580    const TEST_VECTOR_AES_GCM_ENVELOPE: &str = "g1hHpQEDA3gjYXBwbGljYXRpb24veC5iaXR3YXJkZW4uY2Jvci1wYWRkZWQEUMsjH6LNIuT2H2xWMcXOkqg6AAE4gQI6AAE4gCChBUyoF/oGEm+lJYrjjgdYUGIH5LnQjqFMWo2BJORVPYH2+hEWkxIn3tRgAMHNwIr0nTXMVD1EyVGZOsHSDMPqn2HaYrDeR5s+Rg0ezZ2WLh8n2FbdC44A/ExOms4IHcyT";
581
582    /// Test helper: unseal an envelope with an AES-256-GCM content-encryption key.
583    fn unseal_with_cek<T>(
584        envelope: &DataEnvelope,
585        namespace: DataEnvelopeNamespace,
586        cek: &Aes256GcmKey,
587    ) -> Result<T, DataEnvelopeError>
588    where
589        T: serde::de::DeserializeOwned + SealableVersionedData,
590    {
591        envelope.unseal_ref(namespace, CoseKeyView::Aes256Gcm(cek))
592    }
593
594    #[test]
595    #[ignore = "Manual test to verify debug format"]
596    fn test_debug() {
597        let data: TestData = TestDataV1 { field: 42 }.into();
598        let envelope = DataEnvelope::seal_ref(
599            &data,
600            DataEnvelopeNamespace::ExampleNamespace,
601            &Aes256GcmKey::make(),
602        )
603        .unwrap();
604        println!("{:?}", envelope);
605    }
606
607    #[test]
608    #[ignore]
609    fn generate_aes_gcm_test_vectors() {
610        let data: TestData = TestDataV1 { field: 123 }.into();
611        let cek = Aes256GcmKey::make();
612        let envelope =
613            DataEnvelope::seal_ref(&data, DataEnvelopeNamespace::ExampleNamespace, &cek).unwrap();
614        let unsealed_data: TestData =
615            unseal_with_cek(&envelope, DataEnvelopeNamespace::ExampleNamespace, &cek).unwrap();
616        assert_eq!(unsealed_data, data);
617        println!(
618            "const TEST_VECTOR_AES_GCM_CEK: &str = \"{}\";",
619            B64::from(SymmetricCryptoKey::Aes256GcmKey(cek).to_encoded())
620        );
621        println!(
622            "const TEST_VECTOR_AES_GCM_ENVELOPE: &str = \"{}\";",
623            String::from(envelope)
624        );
625    }
626
627    #[test]
628    fn test_data_envelope_legacy_xchacha20_test_vector() {
629        let cek = SymmetricCryptoKey::try_from(B64::try_from(TEST_VECTOR_CEK).unwrap()).unwrap();
630        let SymmetricCryptoKey::XChaCha20Poly1305Key(ref cek) = cek else {
631            panic!("Invalid CEK type");
632        };
633
634        let envelope: DataEnvelope = TEST_VECTOR_ENVELOPE.parse().unwrap();
635        let unsealed_data: TestData = envelope
636            .unseal_ref(
637                DataEnvelopeNamespace::ExampleNamespace,
638                CoseKeyView::XChaCha20Poly1305(cek),
639            )
640            .unwrap();
641        assert_eq!(unsealed_data, TestDataV1 { field: 123 }.into());
642    }
643
644    #[test]
645    fn test_data_envelope_aes_gcm_test_vector() {
646        let cek =
647            SymmetricCryptoKey::try_from(B64::try_from(TEST_VECTOR_AES_GCM_CEK).unwrap()).unwrap();
648        let SymmetricCryptoKey::Aes256GcmKey(ref cek) = cek else {
649            panic!("Invalid CEK type");
650        };
651
652        let envelope: DataEnvelope = TEST_VECTOR_AES_GCM_ENVELOPE.parse().unwrap();
653        let unsealed_data: TestData =
654            unseal_with_cek(&envelope, DataEnvelopeNamespace::ExampleNamespace, cek).unwrap();
655        assert_eq!(unsealed_data, TestDataV1 { field: 123 }.into());
656    }
657
658    #[test]
659    fn test_data_envelope_uses_aes_gcm() {
660        let data: TestData = TestDataV1 { field: 42 }.into();
661        let envelope = DataEnvelope::seal_ref(
662            &data,
663            DataEnvelopeNamespace::ExampleNamespace,
664            &Aes256GcmKey::make(),
665        )
666        .unwrap();
667
668        // New envelopes declare AES-256-GCM in their protected header.
669        let msg = coset::CoseEncrypt0::from_slice(envelope.envelope_data.as_ref()).unwrap();
670        assert_eq!(
671            msg.protected.header.alg,
672            Some(coset::Algorithm::Assigned(coset::iana::Algorithm::A256GCM))
673        );
674    }
675
676    #[test]
677    fn test_data_envelope() {
678        // Create an instance of TestData
679        let data: TestData = TestDataV1 { field: 42 }.into();
680
681        // Seal the data
682        let cek = Aes256GcmKey::make();
683        let envelope =
684            DataEnvelope::seal_ref(&data, DataEnvelopeNamespace::ExampleNamespace, &cek).unwrap();
685        let unsealed_data: TestData =
686            unseal_with_cek(&envelope, DataEnvelopeNamespace::ExampleNamespace, &cek).unwrap();
687
688        // Verify that the unsealed data matches the original data
689        assert_eq!(unsealed_data, data);
690    }
691
692    #[test]
693    fn test_data_envelope_with_keystore_roundtrip() {
694        let data: TestData = TestDataV1 { field: 7 }.into();
695        let key_store = crate::store::KeyStore::<TestIds>::default();
696        let mut ctx = key_store.context_mut();
697
698        let (envelope, cek_id) = DataEnvelope::seal(data, &mut ctx).unwrap();
699
700        // The CEK stored in the key store is an AES-256-GCM key.
701        assert_eq!(
702            ctx.get_symmetric_key_algorithm(cek_id).unwrap(),
703            SymmetricKeyAlgorithm::Aes256Gcm
704        );
705
706        let unsealed: TestData = envelope.unseal(cek_id, &mut ctx).unwrap();
707        assert_eq!(unsealed, TestDataV1 { field: 7 }.into());
708    }
709
710    #[test]
711    fn test_data_envelope_wrapping_key_roundtrip() {
712        let data: TestData = TestDataV1 { field: 99 }.into();
713        let key_store = crate::store::KeyStore::<TestIds>::default();
714        let mut ctx = key_store.context_mut();
715
716        let wrapping_key = KeyEncryptionKey::make(&mut ctx);
717
718        let (envelope, wrapped_cek) =
719            DataEnvelope::seal_with_wrapping_key(data, &wrapping_key, &mut ctx).unwrap();
720        let unsealed: TestData = envelope
721            .unseal_with_wrapping_key(&wrapping_key, &wrapped_cek, &mut ctx)
722            .unwrap();
723        assert_eq!(unsealed, TestDataV1 { field: 99 }.into());
724    }
725
726    #[test]
727    fn test_namespace_validation_success() {
728        let data: TestData = TestDataV1 { field: 123 }.into();
729
730        // Test with ExampleNamespace
731        let cek1 = Aes256GcmKey::make();
732        let envelope1 =
733            DataEnvelope::seal_ref(&data, DataEnvelopeNamespace::ExampleNamespace, &cek1).unwrap();
734        let unsealed_data1: TestData =
735            unseal_with_cek(&envelope1, DataEnvelopeNamespace::ExampleNamespace, &cek1).unwrap();
736        assert_eq!(unsealed_data1, data);
737
738        // Test with ExampleNamespace2
739        let cek2 = Aes256GcmKey::make();
740        let envelope2 =
741            DataEnvelope::seal_ref(&data, DataEnvelopeNamespace::ExampleNamespace2, &cek2).unwrap();
742        let unsealed_data2: TestData =
743            unseal_with_cek(&envelope2, DataEnvelopeNamespace::ExampleNamespace2, &cek2).unwrap();
744        assert_eq!(unsealed_data2, data);
745    }
746
747    #[test]
748    fn test_namespace_validation_failure() {
749        let data: TestData = TestDataV1 { field: 456 }.into();
750
751        // Seal with ExampleNamespace
752        let cek = Aes256GcmKey::make();
753        let envelope =
754            DataEnvelope::seal_ref(&data, DataEnvelopeNamespace::ExampleNamespace, &cek).unwrap();
755
756        // Try to unseal with wrong namespace - should fail
757        let result: Result<TestData, DataEnvelopeError> =
758            unseal_with_cek(&envelope, DataEnvelopeNamespace::ExampleNamespace2, &cek);
759        assert!(matches!(result, Err(DataEnvelopeError::InvalidNamespace)));
760
761        // Verify correct namespace still works
762        let unsealed_data: TestData =
763            unseal_with_cek(&envelope, DataEnvelopeNamespace::ExampleNamespace, &cek).unwrap();
764        assert_eq!(unsealed_data, data);
765    }
766
767    #[test]
768    fn test_namespace_validation_with_keystore() {
769        let data: TestData = TestDataV1 { field: 789 }.into();
770        let key_store = crate::store::KeyStore::<TestIds>::default();
771        let mut ctx = key_store.context_mut();
772
773        // Seal with keystore using ExampleNamespace2
774        let cek = Aes256GcmKey::make();
775        let envelope =
776            DataEnvelope::seal_ref(&data, DataEnvelopeNamespace::ExampleNamespace2, &cek).unwrap();
777        ctx.set_symmetric_key_internal(
778            crate::traits::tests::TestSymmKey::A(0),
779            SymmetricCryptoKey::Aes256GcmKey(cek),
780        )
781        .unwrap();
782
783        // Try to unseal with wrong namespace - should fail
784        let result: Result<TestData, DataEnvelopeError> =
785            envelope.unseal(crate::traits::tests::TestSymmKey::A(0), &mut ctx);
786        assert!(matches!(result, Err(DataEnvelopeError::InvalidNamespace)));
787    }
788
789    #[test]
790    fn test_registration_open_org_invite_namespace_maps_to_expected_discriminant() {
791        // The wire discriminant is load-bearing once shipped; a regression here would silently
792        // invalidate every envelope sealed by production callers.
793        assert_eq!(
794            DataEnvelopeNamespace::try_from(3i128).unwrap(),
795            DataEnvelopeNamespace::RegistrationOpenOrgInviteData
796        );
797        assert_eq!(
798            i128::from(DataEnvelopeNamespace::RegistrationOpenOrgInviteData),
799            3
800        );
801    }
802
803    #[test]
804    fn test_registration_open_org_invite_data_rejects_cross_namespace_unseal() {
805        // AC 1.iii analogue: an envelope sealed under the new production namespace must not
806        // unseal under any other `DataEnvelopeNamespace` (here, the sibling production
807        // `VaultItem`). Mirrors `test_namespace_cross_contamination_protection` for the new
808        // variant.
809        let data: TestData = TestDataV1 { field: 42 }.into();
810
811        let cek = Aes256GcmKey::make();
812        let envelope = DataEnvelope::seal_ref(
813            &data,
814            DataEnvelopeNamespace::RegistrationOpenOrgInviteData,
815            &cek,
816        )
817        .unwrap();
818
819        assert!(matches!(
820            unseal_with_cek::<TestData>(&envelope, DataEnvelopeNamespace::VaultItem, &cek),
821            Err(DataEnvelopeError::InvalidNamespace)
822        ));
823
824        // Correct namespace still succeeds.
825        let round_tripped: TestData = unseal_with_cek(
826            &envelope,
827            DataEnvelopeNamespace::RegistrationOpenOrgInviteData,
828            &cek,
829        )
830        .unwrap();
831        assert_eq!(round_tripped, data);
832    }
833
834    #[test]
835    fn test_pam_namespaces_map_to_expected_discriminants() {
836        // The wire discriminants are load-bearing once shipped; a regression here would silently
837        // invalidate every envelope sealed by production callers (bitwarden-pam-sealed).
838        assert_eq!(
839            DataEnvelopeNamespace::try_from(4i128).unwrap(),
840            DataEnvelopeNamespace::PamTargetSystem
841        );
842        assert_eq!(i128::from(DataEnvelopeNamespace::PamTargetSystem), 4);
843
844        assert_eq!(
845            DataEnvelopeNamespace::try_from(5i128).unwrap(),
846            DataEnvelopeNamespace::PamRotationConfig
847        );
848        assert_eq!(i128::from(DataEnvelopeNamespace::PamRotationConfig), 5);
849    }
850
851    #[test]
852    fn test_pam_target_system_rejects_cross_namespace_unseal() {
853        // A target-system blob must not unseal under the sibling PamRotationConfig namespace (or
854        // vice versa).
855        let data: TestData = TestDataV1 { field: 42 }.into();
856
857        let cek = Aes256GcmKey::make();
858        let envelope =
859            DataEnvelope::seal_ref(&data, DataEnvelopeNamespace::PamTargetSystem, &cek).unwrap();
860
861        assert!(matches!(
862            unseal_with_cek::<TestData>(&envelope, DataEnvelopeNamespace::PamRotationConfig, &cek),
863            Err(DataEnvelopeError::InvalidNamespace)
864        ));
865
866        let round_tripped: TestData =
867            unseal_with_cek(&envelope, DataEnvelopeNamespace::PamTargetSystem, &cek).unwrap();
868        assert_eq!(round_tripped, data);
869    }
870
871    #[test]
872    fn test_namespace_cross_contamination_protection() {
873        let data1: TestData = TestDataV1 { field: 111 }.into();
874        let data2: TestData = TestDataV1 { field: 222 }.into();
875
876        // Seal two different pieces of data with different namespaces
877        let cek1 = Aes256GcmKey::make();
878        let envelope1 =
879            DataEnvelope::seal_ref(&data1, DataEnvelopeNamespace::ExampleNamespace, &cek1).unwrap();
880        let cek2 = Aes256GcmKey::make();
881        let envelope2 =
882            DataEnvelope::seal_ref(&data2, DataEnvelopeNamespace::ExampleNamespace2, &cek2)
883                .unwrap();
884
885        // Verify each envelope only opens with its correct namespace
886        let unsealed1: TestData =
887            unseal_with_cek(&envelope1, DataEnvelopeNamespace::ExampleNamespace, &cek1).unwrap();
888        assert_eq!(unsealed1, data1);
889
890        let unsealed2: TestData =
891            unseal_with_cek(&envelope2, DataEnvelopeNamespace::ExampleNamespace2, &cek2).unwrap();
892        assert_eq!(unsealed2, data2);
893
894        // Cross-unsealing should fail
895        assert!(matches!(
896            unseal_with_cek::<TestData>(
897                &envelope1,
898                DataEnvelopeNamespace::ExampleNamespace2,
899                &cek1
900            ),
901            Err(DataEnvelopeError::InvalidNamespace)
902        ));
903        assert!(matches!(
904            unseal_with_cek::<TestData>(&envelope2, DataEnvelopeNamespace::ExampleNamespace, &cek2),
905            Err(DataEnvelopeError::InvalidNamespace)
906        ));
907    }
908}