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
27pub trait SealableVersionedData: Serialize + DeserializeOwned {
31 const NAMESPACE: DataEnvelopeNamespace;
33}
34
35pub trait SealableData: Serialize + DeserializeOwned {}
49
50#[derive(Clone)]
61pub struct DataEnvelope {
62 envelope_data: CoseEncrypt0Bytes,
63}
64
65impl DataEnvelope {
66 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 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 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 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 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 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 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 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 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 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 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 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 fn unseal_ref<T>(
212 &self,
213 namespace: DataEnvelopeNamespace,
214 cek: CoseKeyView,
215 ) -> Result<T, DataEnvelopeError>
216 where
217 T: DeserializeOwned + SealableVersionedData,
218 {
219 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 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 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 let serialized_message =
255 SerializedMessage::from_bytes(unpadded_message, CoapContentFormat::Cbor);
256 serialized_message
257 .decode()
258 .map_err(|_| DataEnvelopeError::Decoding)
259 }
260}
261
262pub(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#[derive(Debug, Error)]
348pub enum DataEnvelopeError {
349 #[error("Unsupported content format")]
351 UnsupportedContentFormat,
352 #[error("Failed to decode COSE message")]
354 CoseDecoding,
355 #[error("Failed to decode the content of the envelope")]
357 Decoding,
358 #[error("Encoding error")]
360 Encoding,
361 #[error("KeyStore error")]
363 KeyStore,
364 #[error("Decryption error")]
366 Decryption,
367 #[error("Encryption error")]
369 Encryption,
370 #[error("Parsing error: {0}")]
372 Parsing(String),
373 #[error("Invalid namespace")]
375 InvalidNamespace,
376 #[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#[macro_export]
435macro_rules! generate_versioned_sealable {
436 (
437 $enum_name:ident,
439 $namespace:path,
441 [ $( $variant_ty:ident => $rename:literal ),+ $(,)? ]
443 ) => {
444 #[derive(Serialize, Deserialize, Debug, PartialEq)]
446 #[serde(tag = "version", content = "content")]
447 enum $enum_name {
448 $(
449 #[serde(rename = $rename)]
450 $variant_ty($variant_ty),
452 )+
453 }
454
455 impl SealableVersionedData for $enum_name
457 where
458 $( $variant_ty: SealableData ),+
459 {
460 const NAMESPACE: DataEnvelopeNamespace = $namespace;
462 }
463
464 $(
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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
482pub enum DataEnvelopeNamespace {
483 VaultItem = 1,
485 OrganizationInvite = 2,
488 RegistrationOpenOrgInviteData = 3,
492 PamTargetSystem = 4,
496 PamRotationConfig = 5,
499 #[cfg(test)]
501 ExampleNamespace = -1,
502 #[cfg(test)]
504 ExampleNamespace2 = -2,
505}
506
507impl DataEnvelopeNamespace {
508 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 const TEST_VECTOR_CEK: &str =
573 "pQEEAlB5RTKA0xXdA7C4iQE4QfVUAzoAARFvBIEEIFggQYqnsrAfeFFTaXGXB54YrksB6eQcctMpnaZ8rG6rMJ0B";
574 const TEST_VECTOR_ENVELOPE: &str = "g1hLpQE6AAERbwN4I2FwcGxpY2F0aW9uL3guYml0d2FyZGVuLmNib3ItcGFkZGVkBFB5RTKA0xXdA7C4iQE4QfVUOgABOIECOgABOIAgoQVYGLfQrYHVWxRxO6A8m/yp5DPbBIn3h8nijlhQj4jFwDLWfFz7le1Oy8dTls5vdEFg/FjjsPvXicI2bdb5KDdJCz/YkEu0kqjpQwdCcALpJLVJwgQQeKIeU2klBHEPZjnlLpRRXeCUp5c5BYQ=";
575
576 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 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 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 let data: TestData = TestDataV1 { field: 42 }.into();
680
681 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 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 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 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 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 let cek = Aes256GcmKey::make();
753 let envelope =
754 DataEnvelope::seal_ref(&data, DataEnvelopeNamespace::ExampleNamespace, &cek).unwrap();
755
756 let result: Result<TestData, DataEnvelopeError> =
758 unseal_with_cek(&envelope, DataEnvelopeNamespace::ExampleNamespace2, &cek);
759 assert!(matches!(result, Err(DataEnvelopeError::InvalidNamespace)));
760
761 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 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 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 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 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 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 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 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 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 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 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}