bitwarden-crypto 3.0.0

Internal crate for the bitwarden crate. Do not use.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
use std::pin::Pin;

use bitwarden_encoding::B64;
use coset::{CborSerializable, RegisteredLabelWithPrivate, iana::KeyOperation};
use hybrid_array::Array;
use rand::RngExt;
#[cfg(test)]
use rand::SeedableRng;
#[cfg(test)]
use rand_chacha::ChaChaRng;
use serde::{Deserialize, Serialize};
#[cfg(test)]
use sha2::Digest;
use subtle::{Choice, ConstantTimeEq};
use typenum::U32;
#[cfg(feature = "wasm")]
use wasm_bindgen::convert::{FromWasmAbi, IntoWasmAbi, OptionFromWasmAbi};
use zeroize::{Zeroize, ZeroizeOnDrop};

use super::{key_encryptable::CryptoKey, key_id::KeyId};
use crate::{BitwardenLegacyKeyBytes, ContentFormat, CoseKeyBytes, CryptoError, cose};

#[cfg(feature = "wasm")]
#[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
const TS_CUSTOM_TYPES: &'static str = r#"
export type SymmetricKey = Tagged<string, "SymmetricKey">;
"#;

#[cfg(feature = "wasm")]
impl wasm_bindgen::describe::WasmDescribe for SymmetricCryptoKey {
    fn describe() {
        <String as wasm_bindgen::describe::WasmDescribe>::describe();
    }
}

#[cfg(feature = "wasm")]
impl FromWasmAbi for SymmetricCryptoKey {
    type Abi = <String as FromWasmAbi>::Abi;

    unsafe fn from_abi(abi: Self::Abi) -> Self {
        use wasm_bindgen::UnwrapThrowExt;
        let string = unsafe { String::from_abi(abi) };
        let b64 = B64::try_from(string).unwrap_throw();
        SymmetricCryptoKey::try_from(b64).unwrap_throw()
    }
}

#[cfg(feature = "wasm")]
impl OptionFromWasmAbi for SymmetricCryptoKey {
    fn is_none(abi: &Self::Abi) -> bool {
        <String as OptionFromWasmAbi>::is_none(abi)
    }
}

#[cfg(feature = "wasm")]
impl IntoWasmAbi for SymmetricCryptoKey {
    type Abi = <String as IntoWasmAbi>::Abi;

    fn into_abi(self) -> Self::Abi {
        let string: String = self.to_base64().to_string();
        string.into_abi()
    }
}

/// The symmetric key algorithm to use when generating a new symmetric key.
#[derive(Debug, PartialEq)]
pub enum SymmetricKeyAlgorithm {
    /// Used for V1 user keys and data encryption
    Aes256CbcHmac,
    /// Used for V2 user keys and data envelopes
    XChaCha20Poly1305,
}

/// [Aes256CbcKey] is a symmetric encryption key, consisting of one 256-bit key,
/// used to decrypt legacy type 0 enc strings. The data is not authenticated
/// so this should be used with caution, and removed where possible.
#[derive(ZeroizeOnDrop, Clone)]
pub struct Aes256CbcKey {
    /// Uses a pinned heap data structure, as noted in [Pinned heap data][crate#pinned-heap-data]
    pub(crate) enc_key: Pin<Box<Array<u8, U32>>>,
}

impl ConstantTimeEq for Aes256CbcKey {
    fn ct_eq(&self, other: &Self) -> Choice {
        self.enc_key.ct_eq(&other.enc_key)
    }
}

impl PartialEq for Aes256CbcKey {
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}

/// [Aes256CbcHmacKey] is a symmetric encryption key consisting
/// of two 256-bit keys, one for encryption and one for MAC
#[derive(ZeroizeOnDrop, Clone)]
pub struct Aes256CbcHmacKey {
    /// Uses a pinned heap data structure, as noted in [Pinned heap data][crate#pinned-heap-data]
    pub(crate) enc_key: Pin<Box<Array<u8, U32>>>,
    /// Uses a pinned heap data structure, as noted in [Pinned heap data][crate#pinned-heap-data]
    pub(crate) mac_key: Pin<Box<Array<u8, U32>>>,
}

impl ConstantTimeEq for Aes256CbcHmacKey {
    fn ct_eq(&self, other: &Self) -> Choice {
        self.enc_key.ct_eq(&other.enc_key) & self.mac_key.ct_eq(&other.mac_key)
    }
}

impl PartialEq for Aes256CbcHmacKey {
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}

/// [XChaCha20Poly1305Key] is a symmetric encryption key consisting
/// of one 256-bit key, and contains a key id. In contrast to the
/// [Aes256CbcKey] and [Aes256CbcHmacKey], this key type is used to create
/// CoseEncrypt0 messages.
#[derive(Zeroize, Clone)]
pub struct XChaCha20Poly1305Key {
    pub(crate) key_id: KeyId,
    pub(crate) enc_key: Pin<Box<Array<u8, U32>>>,
    /// Controls which key operations are allowed with this key. Note: Only checking decrypt is
    /// implemented right now, and implementing is tracked here <https://bitwarden.atlassian.net/browse/PM-27513>.
    /// Further, disabling decrypt will also disable unwrap. The only use-case so far is
    /// `DataEnvelope`.
    #[zeroize(skip)]
    pub(crate) supported_operations: Vec<KeyOperation>,
}

impl XChaCha20Poly1305Key {
    /// Creates a new XChaCha20Poly1305Key with a securely sampled cryptographic key and key id.
    pub fn make() -> Self {
        let mut rng = rand::rng();
        let mut enc_key = Box::pin(Array::<u8, U32>::default());
        rng.fill(enc_key.as_mut_slice());
        let key_id = KeyId::make();

        Self {
            enc_key,
            key_id,
            supported_operations: vec![
                KeyOperation::Decrypt,
                KeyOperation::Encrypt,
                KeyOperation::WrapKey,
                KeyOperation::UnwrapKey,
            ],
        }
    }

    pub(crate) fn disable_key_operation(&mut self, op: KeyOperation) -> &mut Self {
        self.supported_operations.retain(|k| *k != op);
        self
    }
}

impl ConstantTimeEq for XChaCha20Poly1305Key {
    fn ct_eq(&self, other: &Self) -> Choice {
        self.enc_key.ct_eq(&other.enc_key) & self.key_id.ct_eq(&other.key_id)
    }
}

impl PartialEq for XChaCha20Poly1305Key {
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}

/// A symmetric encryption key. Used to encrypt and decrypt [`EncString`](crate::EncString)
#[derive(ZeroizeOnDrop, Clone)]
pub enum SymmetricCryptoKey {
    #[allow(missing_docs)]
    Aes256CbcKey(Aes256CbcKey),
    #[allow(missing_docs)]
    Aes256CbcHmacKey(Aes256CbcHmacKey),
    /// Data encrypted by XChaCha20Poly1305Key keys has type
    /// [`Cose_Encrypt0_B64`](crate::EncString::Cose_Encrypt0_B64)
    XChaCha20Poly1305Key(XChaCha20Poly1305Key),
}

impl SymmetricCryptoKey {
    // enc type 0 old static format
    const AES256_CBC_KEY_LEN: usize = 32;
    // enc type 2 old static format
    const AES256_CBC_HMAC_KEY_LEN: usize = 64;

    /// Generate a new random AES256_CBC [SymmetricCryptoKey]
    ///
    /// WARNING: This function should only be used with a proper cryptographic RNG. If you do not
    /// have a good reason for using this function, use
    /// [SymmetricCryptoKey::make_aes256_cbc_hmac_key] instead.
    pub(crate) fn make_aes256_cbc_hmac_key_internal(mut rng: impl rand::CryptoRng) -> Self {
        let mut enc_key = Box::pin(Array::<u8, U32>::default());
        let mut mac_key = Box::pin(Array::<u8, U32>::default());

        rng.fill(enc_key.as_mut_slice());
        rng.fill(mac_key.as_mut_slice());

        Self::Aes256CbcHmacKey(Aes256CbcHmacKey { enc_key, mac_key })
    }

    /// Make a new [SymmetricCryptoKey] for the specified algorithm
    pub fn make(algorithm: SymmetricKeyAlgorithm) -> Self {
        match algorithm {
            SymmetricKeyAlgorithm::Aes256CbcHmac => Self::make_aes256_cbc_hmac_key(),
            SymmetricKeyAlgorithm::XChaCha20Poly1305 => Self::make_xchacha20_poly1305_key(),
        }
    }

    /// Generate a new random AES256_CBC_HMAC [SymmetricCryptoKey]
    pub fn make_aes256_cbc_hmac_key() -> Self {
        let rng = rand::rng();
        Self::make_aes256_cbc_hmac_key_internal(rng)
    }

    /// Generate a new random XChaCha20Poly1305 [SymmetricCryptoKey]
    pub fn make_xchacha20_poly1305_key() -> Self {
        let mut rng = rand::rng();
        let mut enc_key = Box::pin(Array::<u8, U32>::default());
        rng.fill(enc_key.as_mut_slice());
        Self::XChaCha20Poly1305Key(XChaCha20Poly1305Key {
            enc_key,
            key_id: KeyId::make(),
            supported_operations: vec![
                KeyOperation::Decrypt,
                KeyOperation::Encrypt,
                KeyOperation::WrapKey,
                KeyOperation::UnwrapKey,
            ],
        })
    }

    /// Encodes the key to a byte array representation, that is separated by size.
    /// [SymmetricCryptoKey::Aes256CbcHmacKey] and [SymmetricCryptoKey::Aes256CbcKey] are
    /// encoded as 64 and 32 bytes respectively. [SymmetricCryptoKey::XChaCha20Poly1305Key]
    /// is encoded as at least 65 bytes, using padding.
    ///
    /// This can be used for storage and transmission in the old byte array format.
    /// When the wrapping key is a COSE key, and the wrapped key is a COSE key, then this should
    /// not use the byte representation but instead use the COSE key representation.
    pub fn to_encoded(&self) -> BitwardenLegacyKeyBytes {
        let encoded_key = self.to_encoded_raw();
        match encoded_key {
            EncodedSymmetricKey::BitwardenLegacyKey(_) => {
                let encoded_key: Vec<u8> = encoded_key.into();
                BitwardenLegacyKeyBytes::from(encoded_key)
            }
            EncodedSymmetricKey::CoseKey(_) => {
                let mut encoded_key: Vec<u8> = encoded_key.into();
                pad_key(&mut encoded_key, (Self::AES256_CBC_HMAC_KEY_LEN + 1) as u8); // This is less than 255
                BitwardenLegacyKeyBytes::from(encoded_key)
            }
        }
    }

    /// Generate a new random [SymmetricCryptoKey] for unit tests. Note: DO NOT USE THIS
    /// IN PRODUCTION CODE.
    #[cfg(test)]
    pub fn generate_seeded_for_unit_tests(seed: &str) -> Self {
        // Keep this separate from the other generate function to not break test vectors.
        let mut seeded_rng = ChaChaRng::from_seed(sha2::Sha256::digest(seed.as_bytes()).into());
        let mut enc_key = Box::pin(Array::<u8, U32>::default());
        let mut mac_key = Box::pin(Array::<u8, U32>::default());

        seeded_rng.fill(enc_key.as_mut_slice());
        seeded_rng.fill(mac_key.as_mut_slice());

        SymmetricCryptoKey::Aes256CbcHmacKey(Aes256CbcHmacKey { enc_key, mac_key })
    }

    /// Creates the byte representation of the key, without any padding. This should not
    /// be used directly for creating serialized key representations, instead,
    /// [SymmetricCryptoKey::to_encoded] should be used.
    ///
    /// [SymmetricCryptoKey::Aes256CbcHmacKey] and [SymmetricCryptoKey::Aes256CbcKey] are
    /// encoded as 64 and 32 byte arrays respectively, representing the key bytes directly.
    /// [SymmetricCryptoKey::XChaCha20Poly1305Key] is encoded as a COSE key, serialized to a byte
    /// array. The COSE key can be either directly encrypted using COSE, where the content
    /// format hints an the key type, or can be represented as a byte array, if padded to be
    /// larger than the byte array representation of the other key types using the
    /// aforementioned [SymmetricCryptoKey::to_encoded] function.
    pub(crate) fn to_encoded_raw(&self) -> EncodedSymmetricKey {
        match self {
            Self::Aes256CbcKey(key) => {
                EncodedSymmetricKey::BitwardenLegacyKey(key.enc_key.to_vec().into())
            }
            Self::Aes256CbcHmacKey(key) => {
                let mut buf = Vec::with_capacity(64);
                buf.extend_from_slice(&key.enc_key);
                buf.extend_from_slice(&key.mac_key);
                EncodedSymmetricKey::BitwardenLegacyKey(buf.into())
            }
            Self::XChaCha20Poly1305Key(key) => {
                let builder = coset::CoseKeyBuilder::new_symmetric_key(key.enc_key.to_vec());
                let mut cose_key = builder.key_id((&key.key_id).into());
                for op in &key.supported_operations {
                    cose_key = cose_key.add_key_op(*op);
                }
                let mut cose_key = cose_key.build();
                cose_key.alg = Some(RegisteredLabelWithPrivate::PrivateUse(
                    cose::XCHACHA20_POLY1305,
                ));
                EncodedSymmetricKey::CoseKey(
                    cose_key
                        .to_vec()
                        .expect("cose key serialization should not fail")
                        .into(),
                )
            }
        }
    }

    pub(crate) fn try_from_cose(serialized_key: &[u8]) -> Result<Self, CryptoError> {
        let cose_key =
            coset::CoseKey::from_slice(serialized_key).map_err(|_| CryptoError::InvalidKey)?;
        let key = SymmetricCryptoKey::try_from(&cose_key)?;
        Ok(key)
    }

    #[allow(missing_docs)]
    pub fn to_base64(&self) -> B64 {
        B64::from(self.to_encoded().as_ref())
    }

    /// Returns the key ID of the key, if it has one. Only
    /// [SymmetricCryptoKey::XChaCha20Poly1305Key] has a key ID.
    pub fn key_id(&self) -> Option<KeyId> {
        match self {
            Self::Aes256CbcKey(_) => None,
            Self::Aes256CbcHmacKey(_) => None,
            Self::XChaCha20Poly1305Key(key) => Some(key.key_id.clone()),
        }
    }
}

impl ConstantTimeEq for SymmetricCryptoKey {
    /// Note: This is constant time with respect to comparing two keys of the same type, but not
    /// constant type with respect to the fact that different keys are compared. If two types of
    /// different keys are compared, then this does have different timing.
    fn ct_eq(&self, other: &SymmetricCryptoKey) -> Choice {
        use SymmetricCryptoKey::*;
        match (self, other) {
            (Aes256CbcKey(a), Aes256CbcKey(b)) => a.ct_eq(b),
            (Aes256CbcKey(_), _) => Choice::from(0),

            (Aes256CbcHmacKey(a), Aes256CbcHmacKey(b)) => a.ct_eq(b),
            (Aes256CbcHmacKey(_), _) => Choice::from(0),

            (XChaCha20Poly1305Key(a), XChaCha20Poly1305Key(b)) => a.ct_eq(b),
            (XChaCha20Poly1305Key(_), _) => Choice::from(0),
        }
    }
}

impl PartialEq for SymmetricCryptoKey {
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}

impl TryFrom<String> for SymmetricCryptoKey {
    type Error = CryptoError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        let bytes = B64::try_from(value).map_err(|_| CryptoError::InvalidKey)?;
        Self::try_from(bytes)
    }
}

impl TryFrom<B64> for SymmetricCryptoKey {
    type Error = CryptoError;

    fn try_from(value: B64) -> Result<Self, Self::Error> {
        Self::try_from(&BitwardenLegacyKeyBytes::from(&value))
    }
}

impl TryFrom<&BitwardenLegacyKeyBytes> for SymmetricCryptoKey {
    type Error = CryptoError;

    fn try_from(value: &BitwardenLegacyKeyBytes) -> Result<Self, Self::Error> {
        let slice = value.as_ref();

        // Raw byte serialized keys are either 32, 64, or more bytes long. If they are 32/64, they
        // are the raw serializations of the AES256-CBC, and AES256-CBC-HMAC keys. If they
        // are longer, they are COSE keys. The COSE keys are padded to the minimum length of
        // 65 bytes, when serialized to raw byte arrays.

        if slice.len() == Self::AES256_CBC_HMAC_KEY_LEN || slice.len() == Self::AES256_CBC_KEY_LEN {
            Self::try_from(EncodedSymmetricKey::BitwardenLegacyKey(value.clone()))
        } else if slice.len() > Self::AES256_CBC_HMAC_KEY_LEN {
            let unpadded_value = unpad_key(slice)?;
            Ok(Self::try_from_cose(unpadded_value)?)
        } else {
            Err(CryptoError::InvalidKeyLen)
        }
    }
}

impl TryFrom<EncodedSymmetricKey> for SymmetricCryptoKey {
    type Error = CryptoError;

    fn try_from(value: EncodedSymmetricKey) -> Result<Self, Self::Error> {
        match value {
            EncodedSymmetricKey::BitwardenLegacyKey(key)
                if key.as_ref().len() == Self::AES256_CBC_KEY_LEN =>
            {
                let mut enc_key = Box::pin(Array::<u8, U32>::default());
                enc_key.copy_from_slice(&key.as_ref()[..Self::AES256_CBC_KEY_LEN]);
                Ok(Self::Aes256CbcKey(Aes256CbcKey { enc_key }))
            }
            EncodedSymmetricKey::BitwardenLegacyKey(key)
                if key.as_ref().len() == Self::AES256_CBC_HMAC_KEY_LEN =>
            {
                let mut enc_key = Box::pin(Array::<u8, U32>::default());
                enc_key.copy_from_slice(&key.as_ref()[..32]);

                let mut mac_key = Box::pin(Array::<u8, U32>::default());
                mac_key.copy_from_slice(&key.as_ref()[32..]);

                Ok(Self::Aes256CbcHmacKey(Aes256CbcHmacKey {
                    enc_key,
                    mac_key,
                }))
            }
            EncodedSymmetricKey::CoseKey(key) => Self::try_from_cose(key.as_ref()),
            _ => Err(CryptoError::InvalidKey),
        }
    }
}

impl CryptoKey for SymmetricCryptoKey {}

// We manually implement these to make sure we don't print any sensitive data
impl std::fmt::Debug for SymmetricCryptoKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SymmetricCryptoKey::Aes256CbcKey(key) => key.fmt(f),
            SymmetricCryptoKey::Aes256CbcHmacKey(key) => key.fmt(f),
            SymmetricCryptoKey::XChaCha20Poly1305Key(key) => key.fmt(f),
        }
    }
}

impl std::fmt::Debug for Aes256CbcKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut debug_struct = f.debug_struct("SymmetricKey::Aes256Cbc");
        #[cfg(feature = "dangerous-crypto-debug")]
        debug_struct.field("key", &hex::encode(self.enc_key.as_slice()));
        debug_struct.finish()
    }
}

impl std::fmt::Debug for Aes256CbcHmacKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut debug_struct = f.debug_struct("SymmetricKey::Aes256CbcHmac");
        #[cfg(feature = "dangerous-crypto-debug")]
        debug_struct
            .field("enc_key", &hex::encode(self.enc_key.as_slice()))
            .field("mac_key", &hex::encode(self.mac_key.as_slice()));
        debug_struct.finish()
    }
}

impl std::fmt::Debug for XChaCha20Poly1305Key {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut debug_struct = f.debug_struct("SymmetricKey::XChaCha20Poly1305");
        debug_struct.field("key_id", &self.key_id);
        debug_struct.field(
            "supported_operations",
            &self
                .supported_operations
                .iter()
                .map(|key_operation: &KeyOperation| cose::debug_key_operation(*key_operation))
                .collect::<Vec<_>>(),
        );
        #[cfg(feature = "dangerous-crypto-debug")]
        debug_struct.field("key", &hex::encode(self.enc_key.as_slice()));
        debug_struct.finish()
    }
}

/// Pad a key to a minimum length using PKCS7-like padding.
/// The last N bytes of the padded bytes all have the value N.
/// For example, padded to size 4, the value 0,0 becomes 0,0,2,2.
///
/// Keys that have the type [SymmetricCryptoKey::XChaCha20Poly1305Key] must be distinguishable
/// from [SymmetricCryptoKey::Aes256CbcHmacKey] keys, when both are encoded as byte arrays
/// with no additional content format included in the encoding message. For this reason, the
/// padding is used to make sure that the byte representation uniquely separates the keys by
/// size of the byte array. The previous key types [SymmetricCryptoKey::Aes256CbcHmacKey] and
/// [SymmetricCryptoKey::Aes256CbcKey] are 64 and 32 bytes long respectively.
fn pad_key(key_bytes: &mut Vec<u8>, min_length: u8) {
    crate::keys::utils::pad_bytes(key_bytes, min_length as usize)
        .expect("Padding cannot fail since the min_length is < 255")
}

/// Unpad a key that is padded using the PKCS7-like padding defined by [pad_key].
/// The last N bytes of the padded bytes all have the value N.
/// For example, padded to size 4, the value 0,0 becomes 0,0,2,2.
///
/// Keys that have the type [SymmetricCryptoKey::XChaCha20Poly1305Key] must be distinguishable
/// from [SymmetricCryptoKey::Aes256CbcHmacKey] keys, when both are encoded as byte arrays
/// with no additional content format included in the encoding message. For this reason, the
/// padding is used to make sure that the byte representation uniquely separates the keys by
/// size of the byte array the previous key types [SymmetricCryptoKey::Aes256CbcHmacKey] and
/// [SymmetricCryptoKey::Aes256CbcKey] are 64 and 32 bytes long respectively.
fn unpad_key(key_bytes: &[u8]) -> Result<&[u8], CryptoError> {
    crate::keys::utils::unpad_bytes(key_bytes).map_err(|_| CryptoError::InvalidKey)
}

/// Encoded representation of [SymmetricCryptoKey]
pub enum EncodedSymmetricKey {
    /// An Aes256-CBC-HMAC key, or a Aes256-CBC key
    BitwardenLegacyKey(BitwardenLegacyKeyBytes),
    /// A symmetric key encoded as a COSE key
    CoseKey(CoseKeyBytes),
}
impl From<EncodedSymmetricKey> for Vec<u8> {
    fn from(val: EncodedSymmetricKey) -> Self {
        match val {
            EncodedSymmetricKey::BitwardenLegacyKey(key) => key.to_vec(),
            EncodedSymmetricKey::CoseKey(key) => key.to_vec(),
        }
    }
}
impl EncodedSymmetricKey {
    /// Returns the content format of the encoded symmetric key.
    #[allow(private_interfaces)]
    pub fn content_format(&self) -> ContentFormat {
        match self {
            EncodedSymmetricKey::BitwardenLegacyKey(_) => ContentFormat::BitwardenLegacyKey,
            EncodedSymmetricKey::CoseKey(_) => ContentFormat::CoseKey,
        }
    }
}

// Note: Deserialize and Serialize are only implemented until external usages of
// symmetric crypto keys are removed. We do not want to support these, but while
// these have to be supported, we want to have type-safety over having raw byte
// arrays.
impl<'de> Deserialize<'de> for SymmetricCryptoKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let encoded_key = BitwardenLegacyKeyBytes::deserialize(deserializer)?;
        SymmetricCryptoKey::try_from(&encoded_key).map_err(serde::de::Error::custom)
    }
}

impl Serialize for SymmetricCryptoKey {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let encoded_key = self.to_encoded();
        encoded_key.serialize(serializer)
    }
}

/// Test only helper for deriving a symmetric key.
#[cfg(test)]
pub fn derive_symmetric_key(name: &str) -> Aes256CbcHmacKey {
    use zeroize::Zeroizing;

    use crate::{derive_shareable_key, generate_random_bytes};

    let secret: Zeroizing<[u8; 16]> = generate_random_bytes();
    derive_shareable_key(secret, name, None)
}

#[cfg(test)]
mod tests {
    use bitwarden_encoding::B64;
    use coset::iana::KeyOperation;
    use hybrid_array::Array;
    use typenum::U32;

    use super::{SymmetricCryptoKey, derive_symmetric_key};
    use crate::{
        Aes256CbcHmacKey, Aes256CbcKey, BitwardenLegacyKeyBytes, XChaCha20Poly1305Key,
        keys::{
            KeyId,
            symmetric_crypto_key::{pad_key, unpad_key},
        },
    };

    #[test]
    #[ignore = "Manual test to verify debug format"]
    fn test_key_debug() {
        let aes_key = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
        println!("{:?}", aes_key);
        let xchacha_key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
        println!("{:?}", xchacha_key);
    }

    #[test]
    fn test_serialize_deserialize_symmetric_crypto_key() {
        let key = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
        let serialized = serde_json::to_string(&key).unwrap();
        let deserialized: SymmetricCryptoKey = serde_json::from_str(&serialized).unwrap();
        assert_eq!(key, deserialized);
    }

    #[test]
    fn test_symmetric_crypto_key() {
        let key = SymmetricCryptoKey::Aes256CbcHmacKey(derive_symmetric_key("test"));
        let key2 = SymmetricCryptoKey::try_from(key.to_base64()).unwrap();

        assert_eq!(key, key2);

        let key = "UY4B5N4DA4UisCNClgZtRr6VLy9ZF5BXXC7cDZRqourKi4ghEMgISbCsubvgCkHf5DZctQjVot11/vVvN9NNHQ==".to_string();
        let key2 = SymmetricCryptoKey::try_from(key.clone()).unwrap();
        assert_eq!(key, key2.to_base64().to_string());
    }

    #[test]
    fn test_encode_decode_old_symmetric_crypto_key() {
        let key = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
        let encoded = key.to_encoded();
        let decoded = SymmetricCryptoKey::try_from(&encoded).unwrap();
        assert_eq!(key, decoded);
    }

    #[test]
    fn test_decode_new_symmetric_crypto_key() {
        let key: B64 = ("pQEEAlDib+JxbqMBlcd3KTUesbufAzoAARFvBIQDBAUGIFggt79surJXmqhPhYuuqi9ZyPfieebmtw2OsmN5SDrb4yUB").parse()
        .unwrap();
        let key = BitwardenLegacyKeyBytes::from(&key);
        let key = SymmetricCryptoKey::try_from(&key).unwrap();
        match key {
            SymmetricCryptoKey::XChaCha20Poly1305Key(_) => (),
            _ => panic!("Invalid key type"),
        }
    }

    #[test]
    fn test_encode_xchacha20_poly1305_key() {
        let key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
        let encoded = key.to_encoded();
        let decoded = SymmetricCryptoKey::try_from(&encoded).unwrap();
        assert_eq!(key, decoded);
    }

    #[test]
    fn test_pad_unpad_key_63() {
        let original_key = vec![1u8; 63];
        let mut key_bytes = original_key.clone();
        let mut encoded_bytes = vec![1u8; 65];
        encoded_bytes[63] = 2;
        encoded_bytes[64] = 2;
        pad_key(&mut key_bytes, 65);
        assert_eq!(encoded_bytes, key_bytes);
        let unpadded_key = unpad_key(&key_bytes).unwrap();
        assert_eq!(original_key, unpadded_key);
    }

    #[test]
    fn test_pad_unpad_key_64() {
        let original_key = vec![1u8; 64];
        let mut key_bytes = original_key.clone();
        let mut encoded_bytes = vec![1u8; 65];
        encoded_bytes[64] = 1;
        pad_key(&mut key_bytes, 65);
        assert_eq!(encoded_bytes, key_bytes);
        let unpadded_key = unpad_key(&key_bytes).unwrap();
        assert_eq!(original_key, unpadded_key);
    }

    #[test]
    fn test_pad_unpad_key_65() {
        let original_key = vec![1u8; 65];
        let mut key_bytes = original_key.clone();
        let mut encoded_bytes = vec![1u8; 66];
        encoded_bytes[65] = 1;
        pad_key(&mut key_bytes, 65);
        assert_eq!(encoded_bytes, key_bytes);
        let unpadded_key = unpad_key(&key_bytes).unwrap();
        assert_eq!(original_key, unpadded_key);
    }

    #[test]
    fn test_eq_aes_cbc_hmac() {
        let key1 = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
        let key2 = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
        assert_ne!(key1, key2);
        let key3 = SymmetricCryptoKey::try_from(key1.to_base64()).unwrap();
        assert_eq!(key1, key3);
    }

    #[test]
    fn test_eq_aes_cbc() {
        let key1 =
            SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(vec![1u8; 32])).unwrap();
        let key2 =
            SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(vec![2u8; 32])).unwrap();
        assert_ne!(key1, key2);
        let key3 = SymmetricCryptoKey::try_from(key1.to_base64()).unwrap();
        assert_eq!(key1, key3);
    }

    #[test]
    fn test_eq_xchacha20_poly1305() {
        let key1 = SymmetricCryptoKey::make_xchacha20_poly1305_key();
        let key2 = SymmetricCryptoKey::make_xchacha20_poly1305_key();
        assert_ne!(key1, key2);
        let key3 = SymmetricCryptoKey::try_from(key1.to_base64()).unwrap();
        assert_eq!(key1, key3);
    }

    #[test]
    fn test_neq_different_key_types() {
        let key1 = SymmetricCryptoKey::Aes256CbcKey(Aes256CbcKey {
            enc_key: Box::pin(Array::<u8, U32>::default()),
        });
        let key2 = SymmetricCryptoKey::XChaCha20Poly1305Key(XChaCha20Poly1305Key {
            enc_key: Box::pin(Array::<u8, U32>::default()),
            key_id: KeyId::from([0; 16]),
            supported_operations: vec![
                KeyOperation::Decrypt,
                KeyOperation::Encrypt,
                KeyOperation::WrapKey,
                KeyOperation::UnwrapKey,
            ],
        });
        assert_ne!(key1, key2);
    }

    #[test]
    fn test_eq_variant_aes256_cbc() {
        let key1 = Aes256CbcKey {
            enc_key: Box::pin(Array::from([1u8; 32])),
        };
        let key2 = Aes256CbcKey {
            enc_key: Box::pin(Array::from([1u8; 32])),
        };
        let key3 = Aes256CbcKey {
            enc_key: Box::pin(Array::from([2u8; 32])),
        };
        assert_eq!(key1, key2);
        assert_ne!(key1, key3);
    }

    #[test]
    fn test_eq_variant_aes256_cbc_hmac() {
        let key1 = Aes256CbcHmacKey {
            enc_key: Box::pin(Array::from([1u8; 32])),
            mac_key: Box::pin(Array::from([2u8; 32])),
        };
        let key2 = Aes256CbcHmacKey {
            enc_key: Box::pin(Array::from([1u8; 32])),
            mac_key: Box::pin(Array::from([2u8; 32])),
        };
        let key3 = Aes256CbcHmacKey {
            enc_key: Box::pin(Array::from([3u8; 32])),
            mac_key: Box::pin(Array::from([4u8; 32])),
        };
        assert_eq!(key1, key2);
        assert_ne!(key1, key3);
    }

    #[test]
    fn test_eq_variant_xchacha20_poly1305() {
        let key1 = XChaCha20Poly1305Key {
            enc_key: Box::pin(Array::from([1u8; 32])),
            key_id: KeyId::from([0; 16]),
            supported_operations: vec![
                KeyOperation::Decrypt,
                KeyOperation::Encrypt,
                KeyOperation::WrapKey,
                KeyOperation::UnwrapKey,
            ],
        };
        let key2 = XChaCha20Poly1305Key {
            enc_key: Box::pin(Array::from([1u8; 32])),
            key_id: KeyId::from([0; 16]),
            supported_operations: vec![
                KeyOperation::Decrypt,
                KeyOperation::Encrypt,
                KeyOperation::WrapKey,
                KeyOperation::UnwrapKey,
            ],
        };
        let key3 = XChaCha20Poly1305Key {
            enc_key: Box::pin(Array::from([2u8; 32])),
            key_id: KeyId::from([1; 16]),
            supported_operations: vec![
                KeyOperation::Decrypt,
                KeyOperation::Encrypt,
                KeyOperation::WrapKey,
                KeyOperation::UnwrapKey,
            ],
        };
        assert_eq!(key1, key2);
        assert_ne!(key1, key3);
    }

    #[test]
    fn test_neq_different_key_id() {
        let key1 = XChaCha20Poly1305Key {
            enc_key: Box::pin(Array::<u8, U32>::default()),
            key_id: KeyId::from([0; 16]),
            supported_operations: vec![
                KeyOperation::Decrypt,
                KeyOperation::Encrypt,
                KeyOperation::WrapKey,
                KeyOperation::UnwrapKey,
            ],
        };
        let key2 = XChaCha20Poly1305Key {
            enc_key: Box::pin(Array::<u8, U32>::default()),
            key_id: KeyId::from([1; 16]),
            supported_operations: vec![
                KeyOperation::Decrypt,
                KeyOperation::Encrypt,
                KeyOperation::WrapKey,
                KeyOperation::UnwrapKey,
            ],
        };
        assert_ne!(key1, key2);

        let key1 = SymmetricCryptoKey::XChaCha20Poly1305Key(key1);
        let key2 = SymmetricCryptoKey::XChaCha20Poly1305Key(key2);
        assert_ne!(key1, key2);
    }
}