1use std::{num::TryFromIntError, str::FromStr};
26
27use bitwarden_encoding::{B64, FromStrVisitor};
28use bitwarden_sensitive_value::ExposeSensitive;
29use ciborium::Value;
30use coset::{CborSerializable, CoseError, Header, HeaderBuilder, iana};
31use rand::Rng;
32use serde::{Deserialize, Serialize};
33use thiserror::Error;
34
35use crate::{
36 ContentFormat, EncodedSymmetricKey, KeySlotIds, KeyStoreContext, SymmetricCryptoKey,
37 cose::{
38 ContentNamespace, CoseExtractError, SafeObjectNamespace, extract_bytes,
39 symmetric::{
40 CoseAlgorithmPolicy, CoseContentEncryptionAlgorithm, decrypt_cose, encrypt_cose,
41 },
42 },
43 keys::KeyId,
44 safe::{
45 DecodeSealedKeyError, HighEntropySecret, decode_sealed_symmetric_key, extract_key_id,
46 extract_single_recipient,
47 helpers::{debug_fmt, set_safe_namespaces, validate_safe_namespaces},
48 set_contained_key_id,
49 },
50};
51
52const HKDF_ALGORITHM: coset::iana::Algorithm = iana::Algorithm::Direct_HKDF_SHA_256;
55const HKDF_SALT_LABEL: i64 = iana::HeaderAlgorithmParameter::Salt as i64;
57const ENVELOPE_HKDF_SALT_SIZE: usize = 32;
60const ENVELOPE_HKDF_OUTPUT_KEY_SIZE: usize = 32;
62
63#[derive(Clone)]
73pub struct SecretProtectedKeyEnvelope {
74 cose_encrypt: coset::CoseEncrypt,
75}
76
77impl SecretProtectedKeyEnvelope {
78 pub fn seal<Ids: KeySlotIds>(
86 key_to_seal: Ids::Symmetric,
87 secret: &HighEntropySecret,
88 namespace: SecretProtectedKeyEnvelopeNamespace,
89 ctx: &KeyStoreContext<Ids>,
90 ) -> Result<Self, SecretProtectedKeyEnvelopeError> {
91 let key_ref = ctx
92 .get_symmetric_key(key_to_seal)
93 .map_err(|_| SecretProtectedKeyEnvelopeError::KeyMissing)?;
94 Self::seal_ref(key_ref, secret, namespace)
95 }
96
97 fn seal_ref(
100 key_to_seal: &SymmetricCryptoKey,
101 secret: &HighEntropySecret,
102 namespace: SecretProtectedKeyEnvelopeNamespace,
103 ) -> Result<Self, SecretProtectedKeyEnvelopeError> {
104 Self::seal_ref_with_settings(key_to_seal, secret, &HkdfSettings::new(), namespace)
105 }
106
107 fn seal_ref_with_settings(
110 key_to_seal: &SymmetricCryptoKey,
111 secret: &HighEntropySecret,
112 hkdf_settings: &HkdfSettings,
113 namespace: SecretProtectedKeyEnvelopeNamespace,
114 ) -> Result<Self, SecretProtectedKeyEnvelopeError> {
115 let cek = derive_cek(
123 hkdf_settings,
124 secret.as_bytes().expose_owned(),
125 iana::Algorithm::A256GCM,
126 )?;
127
128 let (content_format, key_to_seal_bytes) = match key_to_seal.to_encoded_raw() {
129 EncodedSymmetricKey::BitwardenLegacyKey(key_bytes) => {
130 (ContentFormat::BitwardenLegacyKey, key_bytes.to_vec())
131 }
132 EncodedSymmetricKey::CoseKey(key_bytes) => (ContentFormat::CoseKey, key_bytes.to_vec()),
133 };
134
135 let protected_header = {
136 let mut header = HeaderBuilder::from(content_format).build();
137 set_contained_key_id(&mut header, key_to_seal.key_id());
138 set_safe_namespaces(
139 &mut header,
140 SafeObjectNamespace::SecretProtectedKeyEnvelope,
141 namespace,
142 );
143 header
144 };
145
146 let builder = coset::CoseEncryptBuilder::new().add_recipient(
150 coset::CoseRecipientBuilder::new()
151 .unprotected(hkdf_settings.into())
152 .build(),
153 );
154 let cose_encrypt = encrypt_cose(
157 CoseContentEncryptionAlgorithm::Aes256Gcm,
158 builder,
159 protected_header,
160 &key_to_seal_bytes,
161 &cek,
162 )
163 .map_err(|_| SecretProtectedKeyEnvelopeError::Kdf)?;
164
165 Ok(SecretProtectedKeyEnvelope { cose_encrypt })
166 }
167
168 pub fn unseal<Ids: KeySlotIds>(
171 &self,
172 secret: &HighEntropySecret,
173 namespace: SecretProtectedKeyEnvelopeNamespace,
174 ctx: &mut KeyStoreContext<Ids>,
175 ) -> Result<Ids::Symmetric, SecretProtectedKeyEnvelopeError> {
176 let key = self.unseal_ref(secret, namespace)?;
177 Ok(ctx.add_local_symmetric_key(key))
178 }
179
180 fn unseal_ref(
181 &self,
182 secret: &HighEntropySecret,
183 content_namespace: SecretProtectedKeyEnvelopeNamespace,
184 ) -> Result<SymmetricCryptoKey, SecretProtectedKeyEnvelopeError> {
185 let recipient = extract_single_recipient(&self.cose_encrypt).map_err(|_| {
188 SecretProtectedKeyEnvelopeError::Parsing("Invalid number of recipients".to_string())
189 })?;
190
191 if recipient.unprotected.alg
192 != Some(coset::RegisteredLabelWithPrivate::Assigned(HKDF_ALGORITHM))
193 {
194 return Err(SecretProtectedKeyEnvelopeError::Parsing(
195 "Unknown or unsupported KDF algorithm".to_string(),
196 ));
197 }
198
199 validate_safe_namespaces(
200 &self.cose_encrypt.protected.header,
201 SafeObjectNamespace::SecretProtectedKeyEnvelope,
202 content_namespace,
203 )
204 .map_err(|_| SecretProtectedKeyEnvelopeError::InvalidNamespace)?;
205
206 let kdf_settings: HkdfSettings = (&recipient.unprotected).try_into().map_err(|_| {
207 SecretProtectedKeyEnvelopeError::Parsing(
208 "Invalid or missing KDF parameters".to_string(),
209 )
210 })?;
211 let content_alg = content_encryption_algorithm(&self.cose_encrypt.protected.header)?;
215 let cek = derive_cek(&kdf_settings, secret.as_bytes().expose_owned(), content_alg)?;
218
219 let key_bytes = decrypt_cose(
224 &self.cose_encrypt,
225 CoseAlgorithmPolicy::RequireProtectedHeaderAlgorithm,
226 &cek,
227 )
228 .map_err(|_| SecretProtectedKeyEnvelopeError::WrongSecret)?;
229
230 decode_sealed_symmetric_key(&self.cose_encrypt.protected.header, key_bytes).map_err(|e| {
231 match e {
232 DecodeSealedKeyError::InvalidContentFormat => {
233 SecretProtectedKeyEnvelopeError::Parsing("Invalid content format".to_string())
234 }
235 DecodeSealedKeyError::UnsupportedContentFormat => {
236 SecretProtectedKeyEnvelopeError::Parsing(
237 "Unknown or unsupported content format".to_string(),
238 )
239 }
240 DecodeSealedKeyError::InvalidKey => {
241 SecretProtectedKeyEnvelopeError::Parsing("Failed to decode key".to_string())
242 }
243 }
244 })
245 }
246
247 pub fn reseal(
249 &self,
250 secret: &HighEntropySecret,
251 new_secret: &HighEntropySecret,
252 namespace: SecretProtectedKeyEnvelopeNamespace,
253 ) -> Result<Self, SecretProtectedKeyEnvelopeError> {
254 let unsealed = self.unseal_ref(secret, namespace)?;
255 Self::seal_ref(&unsealed, new_secret, namespace)
256 }
257
258 pub fn contained_key_id(&self) -> Result<Option<KeyId>, SecretProtectedKeyEnvelopeError> {
261 extract_key_id(&self.cose_encrypt.protected.header)
262 .map_err(|_| SecretProtectedKeyEnvelopeError::Parsing("Invalid key id".to_string()))
263 }
264}
265
266impl From<&SecretProtectedKeyEnvelope> for Vec<u8> {
267 fn from(val: &SecretProtectedKeyEnvelope) -> Self {
268 val.cose_encrypt
269 .clone()
270 .to_vec()
271 .expect("Serialization to cose should not fail")
272 }
273}
274
275impl TryFrom<&Vec<u8>> for SecretProtectedKeyEnvelope {
276 type Error = CoseError;
277
278 fn try_from(value: &Vec<u8>) -> Result<Self, Self::Error> {
279 let cose_encrypt = coset::CoseEncrypt::from_slice(value)?;
280 Ok(SecretProtectedKeyEnvelope { cose_encrypt })
281 }
282}
283
284impl std::fmt::Debug for SecretProtectedKeyEnvelope {
285 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286 let mut s = f.debug_struct("SecretProtectedKeyEnvelope");
287
288 debug_fmt::<SecretProtectedKeyEnvelopeNamespace>(
289 &mut s,
290 &self.cose_encrypt.protected.header,
291 );
292
293 if let Ok(Some(key_id)) = self.contained_key_id() {
294 s.field("contained_key_id", &key_id);
295 }
296
297 s.finish()
298 }
299}
300
301impl FromStr for SecretProtectedKeyEnvelope {
302 type Err = SecretProtectedKeyEnvelopeError;
303
304 fn from_str(s: &str) -> Result<Self, Self::Err> {
305 let data = B64::try_from(s).map_err(|_| {
306 SecretProtectedKeyEnvelopeError::Parsing(
307 "Invalid SecretProtectedKeyEnvelope Base64 encoding".to_string(),
308 )
309 })?;
310 Self::try_from(&data.into_bytes()).map_err(|_| {
311 SecretProtectedKeyEnvelopeError::Parsing(
312 "Failed to parse SecretProtectedKeyEnvelope".to_string(),
313 )
314 })
315 }
316}
317
318impl From<SecretProtectedKeyEnvelope> for String {
319 fn from(val: SecretProtectedKeyEnvelope) -> Self {
320 let serialized: Vec<u8> = (&val).into();
321 B64::from(serialized).to_string()
322 }
323}
324
325impl<'de> Deserialize<'de> for SecretProtectedKeyEnvelope {
326 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
327 where
328 D: serde::Deserializer<'de>,
329 {
330 deserializer.deserialize_str(FromStrVisitor::new())
331 }
332}
333
334impl Serialize for SecretProtectedKeyEnvelope {
335 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
336 where
337 S: serde::Serializer,
338 {
339 let serialized: Vec<u8> = self.into();
340 serializer.serialize_str(&B64::from(serialized).to_string())
341 }
342}
343
344struct HkdfSettings {
347 alg: iana::Algorithm,
348 salt: [u8; ENVELOPE_HKDF_SALT_SIZE],
349}
350
351impl HkdfSettings {
352 fn new() -> Self {
354 Self {
355 alg: HKDF_ALGORITHM,
356 salt: make_salt(),
357 }
358 }
359}
360
361impl From<&HkdfSettings> for Header {
362 fn from(settings: &HkdfSettings) -> Header {
363 HeaderBuilder::new()
364 .value(HKDF_SALT_LABEL, Value::from(settings.salt.to_vec()))
365 .algorithm(settings.alg)
366 .build()
367 }
368}
369
370impl TryInto<HkdfSettings> for &Header {
371 type Error = SecretProtectedKeyEnvelopeError;
372
373 fn try_into(self) -> Result<HkdfSettings, SecretProtectedKeyEnvelopeError> {
374 Ok(HkdfSettings {
375 alg: match self.alg {
376 Some(coset::RegisteredLabelWithPrivate::Assigned(alg)) => alg,
377 _ => {
378 return Err(SecretProtectedKeyEnvelopeError::Parsing(
379 "Missing KDF algorithm".to_string(),
380 ));
381 }
382 },
383 salt: extract_bytes(self, HKDF_SALT_LABEL, "salt")?
384 .try_into()
385 .map_err(|_| {
386 SecretProtectedKeyEnvelopeError::Parsing("Invalid HKDF salt".to_string())
387 })?,
388 })
389 }
390}
391
392fn make_salt() -> [u8; ENVELOPE_HKDF_SALT_SIZE] {
393 let mut salt = [0u8; ENVELOPE_HKDF_SALT_SIZE];
394 bitwarden_random::rng().fill_bytes(&mut salt);
395 salt
396}
397
398fn kdf_context_info(alg: iana::Algorithm) -> Result<Vec<u8>, SecretProtectedKeyEnvelopeError> {
415 let empty_party_info = || Value::Array(vec![Value::Null, Value::Null, Value::Null]);
416 let context = Value::Array(vec![
417 Value::Integer((alg as i64).into()),
420 empty_party_info(),
421 empty_party_info(),
422 Value::Array(vec![
423 Value::Integer((ENVELOPE_HKDF_OUTPUT_KEY_SIZE as u64 * 8).into()),
425 Value::Bytes(vec![]),
427 ]),
428 ]);
429
430 let mut info = Vec::new();
431 ciborium::into_writer(&context, &mut info).map_err(|_| SecretProtectedKeyEnvelopeError::Kdf)?;
432 Ok(info)
433}
434
435fn content_encryption_algorithm(
439 header: &Header,
440) -> Result<iana::Algorithm, SecretProtectedKeyEnvelopeError> {
441 match header.alg {
442 Some(coset::RegisteredLabelWithPrivate::Assigned(alg)) => Ok(alg),
443 _ => Err(SecretProtectedKeyEnvelopeError::Parsing(
444 "Missing or unsupported content encryption algorithm".to_string(),
445 )),
446 }
447}
448
449fn derive_cek(
450 hkdf_settings: &HkdfSettings,
451 secret: &[u8],
452 alg: iana::Algorithm,
453) -> Result<[u8; ENVELOPE_HKDF_OUTPUT_KEY_SIZE], SecretProtectedKeyEnvelopeError> {
454 let info = kdf_context_info(alg)?;
459 let hkdf = hkdf::Hkdf::<sha2::Sha256>::new(Some(&hkdf_settings.salt), secret);
460 let mut key = [0u8; ENVELOPE_HKDF_OUTPUT_KEY_SIZE];
461 hkdf.expand(&info, &mut key)
462 .map_err(|_| SecretProtectedKeyEnvelopeError::Kdf)?;
463 Ok(key)
464}
465
466#[derive(Debug, Error)]
468pub enum SecretProtectedKeyEnvelopeError {
469 #[error("Wrong secret")]
471 WrongSecret,
472 #[error("Parsing error {0}")]
474 Parsing(String),
475 #[error("Kdf error")]
477 Kdf,
478 #[error("Key missing error")]
480 KeyMissing,
481 #[error("Could not write to key store")]
483 KeyStore,
484 #[error("Invalid namespace")]
486 InvalidNamespace,
487}
488
489impl From<CoseExtractError> for SecretProtectedKeyEnvelopeError {
490 fn from(err: CoseExtractError) -> Self {
491 let CoseExtractError::MissingValue(label) = err;
492 SecretProtectedKeyEnvelopeError::Parsing(format!("Missing value for {}", label))
493 }
494}
495
496impl From<TryFromIntError> for SecretProtectedKeyEnvelopeError {
497 fn from(err: TryFromIntError) -> Self {
498 SecretProtectedKeyEnvelopeError::Parsing(format!("Invalid integer: {}", err))
499 }
500}
501
502#[cfg(feature = "wasm")]
503#[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
504const TS_CUSTOM_TYPES: &'static str = r#"
505export type SecretProtectedKeyEnvelope = Tagged<string, "SecretProtectedKeyEnvelope">;
506"#;
507
508bitwarden_ffi::impl_wire_string!(
509 SecretProtectedKeyEnvelope,
510 parse = |wire: String| wire.parse(),
511 format = String::from,
512);
513
514#[cfg(feature = "wasm")]
515impl TryFrom<wasm_bindgen::JsValue> for SecretProtectedKeyEnvelope {
516 type Error = SecretProtectedKeyEnvelopeError;
517
518 fn try_from(value: wasm_bindgen::JsValue) -> Result<Self, Self::Error> {
519 let string = value.as_string().ok_or_else(|| {
520 SecretProtectedKeyEnvelopeError::Parsing(
521 "SecretProtectedKeyEnvelope JsValue is not a string".to_string(),
522 )
523 })?;
524 SecretProtectedKeyEnvelope::from_str(&string)
525 }
526}
527
528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum SecretProtectedKeyEnvelopeNamespace {
531 OrganizationInvite = 1,
534 DesktopBiometricUnlock = 2,
537 RegistrationOpenOrgInvite = 3,
540 #[cfg(test)]
542 ExampleNamespace = -1,
543 #[cfg(test)]
545 ExampleNamespace2 = -2,
546}
547
548impl SecretProtectedKeyEnvelopeNamespace {
549 fn as_i64(&self) -> i64 {
551 *self as i64
552 }
553}
554
555impl TryFrom<i128> for SecretProtectedKeyEnvelopeNamespace {
556 type Error = SecretProtectedKeyEnvelopeError;
557
558 fn try_from(value: i128) -> Result<Self, Self::Error> {
559 match value {
560 1 => Ok(SecretProtectedKeyEnvelopeNamespace::OrganizationInvite),
561 2 => Ok(SecretProtectedKeyEnvelopeNamespace::DesktopBiometricUnlock),
562 3 => Ok(SecretProtectedKeyEnvelopeNamespace::RegistrationOpenOrgInvite),
563 #[cfg(test)]
564 -1 => Ok(SecretProtectedKeyEnvelopeNamespace::ExampleNamespace),
565 #[cfg(test)]
566 -2 => Ok(SecretProtectedKeyEnvelopeNamespace::ExampleNamespace2),
567 _ => Err(SecretProtectedKeyEnvelopeError::InvalidNamespace),
568 }
569 }
570}
571
572impl TryFrom<i64> for SecretProtectedKeyEnvelopeNamespace {
573 type Error = SecretProtectedKeyEnvelopeError;
574
575 fn try_from(value: i64) -> Result<Self, Self::Error> {
576 Self::try_from(i128::from(value))
577 }
578}
579
580impl From<SecretProtectedKeyEnvelopeNamespace> for i128 {
581 fn from(val: SecretProtectedKeyEnvelopeNamespace) -> Self {
582 val.as_i64().into()
583 }
584}
585
586impl ContentNamespace for SecretProtectedKeyEnvelopeNamespace {}
587
588#[cfg(test)]
589mod tests {
590 use super::*;
591 use crate::{KeyStore, SymmetricKeyAlgorithm, traits::tests::TestIds};
592
593 const TESTVECTOR_SECRET_BYTES: &[u8] = &[
596 174, 83, 45, 9, 235, 3, 186, 62, 199, 125, 198, 108, 129, 205, 24, 21, 174, 148, 88, 80,
597 10, 238, 169, 66, 75, 202, 41, 201, 186, 244, 169, 67,
598 ];
599
600 fn testvector_secret() -> HighEntropySecret {
601 HighEntropySecret::from_internal(TESTVECTOR_SECRET_BYTES)
602 }
603
604 const TEST_UNSEALED_COSEKEY_ENCODED: &[u8] = &[
608 165, 1, 4, 2, 80, 214, 124, 137, 200, 1, 180, 227, 27, 77, 48, 119, 198, 210, 9, 149, 144,
609 3, 58, 0, 1, 17, 111, 4, 132, 3, 4, 5, 6, 32, 88, 32, 111, 105, 200, 46, 142, 185, 114,
610 127, 136, 152, 153, 40, 8, 62, 120, 184, 252, 175, 210, 2, 245, 237, 175, 195, 73, 211,
611 136, 23, 217, 203, 35, 10, 1,
612 ];
613 const TESTVECTOR_COSEKEY_ENVELOPE: &[u8] = &[
614 132, 88, 40, 165, 1, 3, 3, 24, 101, 58, 0, 1, 21, 92, 80, 214, 124, 137, 200, 1, 180, 227,
615 27, 77, 48, 119, 198, 210, 9, 149, 144, 58, 0, 1, 56, 129, 6, 58, 0, 1, 56, 128, 32, 161,
616 5, 76, 155, 157, 246, 33, 115, 165, 158, 222, 125, 222, 199, 188, 88, 84, 132, 235, 37,
617 236, 53, 75, 63, 253, 184, 134, 147, 83, 103, 87, 56, 81, 69, 202, 114, 23, 82, 25, 163,
618 68, 36, 13, 104, 187, 54, 143, 167, 113, 63, 62, 88, 146, 50, 214, 209, 170, 6, 235, 122,
619 44, 129, 149, 67, 213, 112, 112, 55, 51, 183, 165, 61, 168, 174, 215, 147, 110, 133, 164,
620 198, 29, 177, 84, 20, 203, 8, 0, 211, 218, 226, 62, 121, 51, 129, 230, 248, 66, 170, 83,
621 106, 109, 129, 131, 64, 162, 1, 41, 51, 88, 32, 123, 254, 226, 185, 81, 106, 88, 73, 109,
622 191, 241, 1, 143, 230, 179, 47, 36, 100, 235, 131, 4, 180, 12, 96, 125, 91, 184, 5, 175,
623 125, 188, 16, 246,
624 ];
625 const TEST_UNSEALED_LEGACYKEY_ENCODED: &[u8] = &[
626 23, 37, 64, 225, 53, 59, 143, 179, 18, 121, 128, 120, 86, 134, 93, 166, 214, 151, 210, 46,
627 240, 216, 69, 249, 247, 222, 110, 100, 185, 38, 173, 84, 202, 107, 132, 251, 144, 245, 105,
628 244, 220, 93, 212, 227, 98, 208, 173, 122, 245, 78, 244, 106, 174, 124, 109, 91, 53, 119,
629 96, 182, 45, 174, 206, 131,
630 ];
631 const TESTVECTOR_LEGACYKEY_ENVELOPE: &[u8] = &[
632 132, 88, 52, 164, 1, 3, 3, 120, 34, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47,
633 120, 46, 98, 105, 116, 119, 97, 114, 100, 101, 110, 46, 108, 101, 103, 97, 99, 121, 45,
634 107, 101, 121, 58, 0, 1, 56, 129, 6, 58, 0, 1, 56, 128, 32, 161, 5, 76, 20, 11, 52, 107,
635 155, 203, 125, 143, 165, 38, 59, 135, 88, 80, 84, 46, 227, 50, 142, 191, 103, 207, 31, 192,
636 201, 215, 163, 102, 18, 93, 181, 247, 229, 12, 166, 221, 143, 98, 86, 74, 138, 12, 165, 1,
637 206, 101, 240, 222, 51, 239, 216, 4, 85, 61, 212, 62, 44, 29, 1, 184, 4, 191, 189, 248,
638 174, 159, 11, 133, 205, 19, 22, 28, 148, 138, 238, 136, 253, 173, 250, 69, 186, 232, 91,
639 222, 238, 9, 175, 178, 214, 27, 120, 254, 212, 110, 129, 131, 64, 162, 1, 41, 51, 88, 32,
640 222, 10, 249, 242, 57, 196, 223, 240, 234, 177, 19, 72, 201, 32, 1, 129, 46, 6, 76, 38,
641 149, 151, 217, 94, 84, 67, 50, 107, 103, 74, 88, 72, 246,
642 ];
643
644 #[test]
645 fn test_registration_open_org_invite_namespace_maps_to_expected_discriminant() {
646 assert_eq!(
649 SecretProtectedKeyEnvelopeNamespace::try_from(3i128).unwrap(),
650 SecretProtectedKeyEnvelopeNamespace::RegistrationOpenOrgInvite
651 );
652 assert_eq!(
653 i128::from(SecretProtectedKeyEnvelopeNamespace::RegistrationOpenOrgInvite),
654 3
655 );
656 }
657
658 #[test]
659 fn test_registration_open_org_invite_rejects_cross_namespace_unseal() {
660 let key_store = KeyStore::<TestIds>::default();
665 let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
666 let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
667 let secret = testvector_secret();
668
669 let envelope = SecretProtectedKeyEnvelope::seal(
670 test_key,
671 &secret,
672 SecretProtectedKeyEnvelopeNamespace::RegistrationOpenOrgInvite,
673 &ctx,
674 )
675 .expect("seal");
676
677 assert!(matches!(
678 envelope.unseal(
679 &secret,
680 SecretProtectedKeyEnvelopeNamespace::DesktopBiometricUnlock,
681 &mut ctx,
682 ),
683 Err(SecretProtectedKeyEnvelopeError::InvalidNamespace)
684 ));
685
686 let _ = envelope
688 .unseal(
689 &secret,
690 SecretProtectedKeyEnvelopeNamespace::RegistrationOpenOrgInvite,
691 &mut ctx,
692 )
693 .expect("unseal under correct namespace succeeds");
694 }
695
696 #[test]
697 #[ignore = "Manual test to verify debug format"]
698 fn test_debug() {
699 let key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
700 let envelope = SecretProtectedKeyEnvelope::seal_ref(
701 &key,
702 &testvector_secret(),
703 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
704 )
705 .unwrap();
706 println!("{:?}", envelope);
707 }
708
709 #[test]
710 fn test_testvector_cosekey() {
711 let key_store = KeyStore::<TestIds>::default();
712 let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
713 let envelope = SecretProtectedKeyEnvelope::try_from(&TESTVECTOR_COSEKEY_ENVELOPE.to_vec())
714 .expect("Key envelope should be valid");
715 let key = envelope
716 .unseal(
717 &testvector_secret(),
718 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
719 &mut ctx,
720 )
721 .expect("Unsealing should succeed");
722 let unsealed_key = ctx
723 .get_symmetric_key(key)
724 .expect("Key should exist in the key store");
725 assert_eq!(
726 unsealed_key.to_encoded().to_vec(),
727 TEST_UNSEALED_COSEKEY_ENCODED
728 );
729 }
730
731 #[test]
732 fn test_testvector_legacykey() {
733 let key_store = KeyStore::<TestIds>::default();
734 let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
735 let envelope =
736 SecretProtectedKeyEnvelope::try_from(&TESTVECTOR_LEGACYKEY_ENVELOPE.to_vec())
737 .expect("Key envelope should be valid");
738 let key = envelope
739 .unseal(
740 &testvector_secret(),
741 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
742 &mut ctx,
743 )
744 .expect("Unsealing should succeed");
745 let unsealed_key = ctx
746 .get_symmetric_key(key)
747 .expect("Key should exist in the key store");
748 assert_eq!(
749 unsealed_key.to_encoded().to_vec(),
750 TEST_UNSEALED_LEGACYKEY_ENCODED
751 );
752 }
753
754 #[test]
755 fn test_make_envelope() {
756 let key_store = KeyStore::<TestIds>::default();
757 let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
758 let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
759
760 let secret = testvector_secret();
761
762 let envelope = SecretProtectedKeyEnvelope::seal(
764 test_key,
765 &secret,
766 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
767 &ctx,
768 )
769 .unwrap();
770 let serialized: Vec<u8> = (&envelope).into();
771
772 let deserialized: SecretProtectedKeyEnvelope =
774 SecretProtectedKeyEnvelope::try_from(&serialized).unwrap();
775 let key = deserialized
776 .unseal(
777 &secret,
778 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
779 &mut ctx,
780 )
781 .unwrap();
782
783 let unsealed_key = ctx
785 .get_symmetric_key(key)
786 .expect("Key should exist in the key store");
787
788 let key_before_sealing = ctx
789 .get_symmetric_key(test_key)
790 .expect("Key should exist in the key store");
791
792 assert_eq!(unsealed_key, key_before_sealing);
793 }
794
795 #[test]
796 fn test_make_envelope_legacy_key() {
797 let key_store = KeyStore::<TestIds>::default();
798 let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
799 let test_key = ctx.generate_symmetric_key();
800
801 let secret = testvector_secret();
802
803 let envelope = SecretProtectedKeyEnvelope::seal(
805 test_key,
806 &secret,
807 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
808 &ctx,
809 )
810 .unwrap();
811 let serialized: Vec<u8> = (&envelope).into();
812
813 let deserialized: SecretProtectedKeyEnvelope =
815 SecretProtectedKeyEnvelope::try_from(&serialized).unwrap();
816 let key = deserialized
817 .unseal(
818 &secret,
819 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
820 &mut ctx,
821 )
822 .unwrap();
823
824 let unsealed_key = ctx
826 .get_symmetric_key(key)
827 .expect("Key should exist in the key store");
828
829 let key_before_sealing = ctx
830 .get_symmetric_key(test_key)
831 .expect("Key should exist in the key store");
832
833 assert_eq!(unsealed_key, key_before_sealing);
834 }
835
836 #[test]
837 fn test_reseal_envelope() {
838 let key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
839 let secret = testvector_secret();
840 let new_secret = HighEntropySecret::make(32).unwrap();
841
842 let envelope: SecretProtectedKeyEnvelope = SecretProtectedKeyEnvelope::seal_ref(
844 &key,
845 &secret,
846 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
847 )
848 .expect("Sealing should work");
849
850 let envelope = envelope
852 .reseal(
853 &secret,
854 &new_secret,
855 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
856 )
857 .expect("Resealing should work");
858 let unsealed = envelope
859 .unseal_ref(
860 &new_secret,
861 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
862 )
863 .expect("Unsealing should work");
864
865 assert_eq!(unsealed, key);
867 }
868
869 #[test]
870 fn test_wrong_secret() {
871 let key_store = KeyStore::<TestIds>::default();
872 let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
873 let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
874
875 let secret = testvector_secret();
876 let wrong_secret = HighEntropySecret::make(32).unwrap();
877
878 let envelope = SecretProtectedKeyEnvelope::seal(
880 test_key,
881 &secret,
882 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
883 &ctx,
884 )
885 .unwrap();
886
887 let deserialized: SecretProtectedKeyEnvelope =
889 SecretProtectedKeyEnvelope::try_from(&(&envelope).into()).unwrap();
890 assert!(matches!(
891 deserialized.unseal(
892 &wrong_secret,
893 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
894 &mut ctx
895 ),
896 Err(SecretProtectedKeyEnvelopeError::WrongSecret)
897 ));
898 }
899
900 #[test]
901 fn test_wrong_safe_namespace() {
902 let key_store = KeyStore::<TestIds>::default();
903 let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
904 let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
905 let secret = testvector_secret();
906
907 let mut envelope = SecretProtectedKeyEnvelope::seal(
908 test_key,
909 &secret,
910 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
911 &ctx,
912 )
913 .expect("Seal works");
914
915 if let Some((_, value)) = envelope
916 .cose_encrypt
917 .protected
918 .header
919 .rest
920 .iter_mut()
921 .find(|(label, _)| {
922 matches!(label, coset::Label::Int(label_value) if *label_value == crate::cose::SAFE_OBJECT_NAMESPACE)
923 })
924 {
925 *value = Value::Integer((SafeObjectNamespace::DataEnvelope as i64).into());
926 }
927
928 let deserialized: SecretProtectedKeyEnvelope =
929 SecretProtectedKeyEnvelope::try_from(&(&envelope).into())
930 .expect("Envelope should be valid");
931
932 assert!(matches!(
933 deserialized.unseal(
934 &secret,
935 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
936 &mut ctx,
937 ),
938 Err(SecretProtectedKeyEnvelopeError::InvalidNamespace)
939 ));
940 }
941
942 #[test]
943 fn test_key_id() {
944 let key_store = KeyStore::<TestIds>::default();
945 let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
946 let test_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
947 let key_id = ctx.get_symmetric_key(test_key).unwrap().key_id().unwrap();
948
949 let secret = testvector_secret();
950
951 let envelope = SecretProtectedKeyEnvelope::seal(
953 test_key,
954 &secret,
955 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
956 &ctx,
957 )
958 .unwrap();
959 let contained_key_id = envelope.contained_key_id().unwrap();
960 assert_eq!(Some(key_id), contained_key_id);
961 }
962
963 #[test]
966 fn test_derived_key_id_for_aes_cbc_hmac_key() {
967 let key_store = KeyStore::<TestIds>::default();
968 let mut ctx: KeyStoreContext<'_, TestIds> = key_store.context_mut();
969 let test_key = ctx.generate_symmetric_key();
970 let key_id = ctx.get_symmetric_key(test_key).unwrap().key_id().unwrap();
971
972 let secret = testvector_secret();
973
974 let envelope = SecretProtectedKeyEnvelope::seal(
976 test_key,
977 &secret,
978 SecretProtectedKeyEnvelopeNamespace::ExampleNamespace,
979 &ctx,
980 )
981 .unwrap();
982 let contained_key_id = envelope.contained_key_id().unwrap();
983 assert_eq!(Some(key_id), contained_key_id);
984 }
985}