bitwarden-core 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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
//! User account cryptographic state
//!
//! This module contains initialization and unwrapping of the user account cryptographic state.
//! The user account cryptographic state contains keys and cryptographic objects unlocked by
//! the user-key, or protected by keys unlocked by the user-key.
//!
//! V1 users have only a private key protected by an AES256-CBC-HMAC user key.
//! V2 users have a private key, a signing key, a signed public key and a signed security state,
//! all protected by a Cose serialized AEAD key, currently XChaCha20-Poly1305.

use std::sync::RwLock;

use bitwarden_api_api::models::{
    AccountKeysRequestModel, PrivateKeysResponseModel, SecurityStateModel,
    WrappedAccountCryptographicStateRequestModel,
};
use bitwarden_crypto::{
    CoseSerializable, CryptoError, EncString, KeyStore, KeyStoreContext,
    PublicKeyEncryptionAlgorithm, SignatureAlgorithm, SignedPublicKey, SymmetricKeyAlgorithm,
};
use bitwarden_encoding::B64;
use bitwarden_error::bitwarden_error;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{info, instrument};
#[cfg(feature = "wasm")]
use tsify::Tsify;

use crate::{
    MissingFieldError,
    key_management::{
        KeySlotIds, PrivateKeySlotId, SecurityState, SignedSecurityState, SigningKeySlotId,
        SymmetricKeySlotId,
    },
    require,
};

/// Errors that can occur during initialization of the account cryptographic state.
#[derive(Debug, Error)]
#[bitwarden_error(flat)]
pub enum AccountCryptographyInitializationError {
    /// The encryption algorithm from the user key does not match one of the encrypted items.
    /// This would mean that the user's account is corrupt.
    #[error("The encryption type of the user key does not match the account cryptographic state")]
    WrongUserKeyType,
    /// The provide user-key is incorrect or out-of-date. This may happen when a use-key changed
    /// and a local unlock-method is not yet updated.
    #[error("Wrong user key")]
    WrongUserKey,
    /// The decrypted data is corrupt.
    #[error("Decryption succeeded but produced corrupt data")]
    CorruptData,
    /// The decrypted data is corrupt.
    #[error("Signature or mac verification failed, the data may have been tampered with")]
    TamperedData,
    /// The key store is already initialized with account keys. Currently, updating keys is not a
    /// supported operation
    #[error("Key store is already initialized")]
    KeyStoreAlreadyInitialized,
    /// A generic cryptographic error occurred.
    #[error("A generic cryptographic error occurred: {0}")]
    GenericCrypto(CryptoError),
}

impl From<CryptoError> for AccountCryptographyInitializationError {
    fn from(err: CryptoError) -> Self {
        AccountCryptographyInitializationError::GenericCrypto(err)
    }
}

/// Errors that can occur during rotation of the account cryptographic state.
#[derive(Debug, Error)]
#[bitwarden_error(flat)]
pub enum RotateCryptographyStateError {
    /// The key is missing from the key store
    #[error("The provided key is missing from the key store")]
    KeyMissing,
    /// The provided data was invalid
    #[error("The provided data was invalid")]
    InvalidData,
}

/// Errors that can occur when parsing a `PrivateKeysResponseModel` into a
/// `WrappedAccountCryptographicState`.
#[derive(Debug, Error)]
pub enum AccountKeysResponseParseError {
    /// A required field was missing from the API response.
    #[error(transparent)]
    MissingField(#[from] MissingFieldError),
    /// A field value could not be parsed into the expected type.
    #[error("Malformed field value in API response")]
    MalformedField,
    /// The encryption type of the private key does not match the presence/absence of V2 fields.
    #[error("Inconsistent account cryptographic state in API response")]
    InconsistentState,
}

/// Any keys / cryptographic protection "downstream" from the account symmetric key (user key).
/// Private keys are protected by the user key.
#[derive(Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
#[allow(clippy::large_enum_variant)]
pub enum WrappedAccountCryptographicState {
    /// A V1 user has only a private key.
    V1 {
        /// The user's encryption private key, wrapped by the user key.
        private_key: EncString,
    },
    /// A V2 user has a private key, a signing key, a signed public key and a signed security state.
    /// The SignedPublicKey ensures that others can verify the public key is claimed by an identity
    /// they want to share data to. The signed security state protects against cryptographic
    /// downgrades.
    V2 {
        /// The user's encryption private key, wrapped by the user key.
        private_key: EncString,
        /// The user's public-key for the private key, signed by the user's signing key.
        /// Note: This is optional for backwards compatibility. After a few releases, this will be
        /// made non-optional once all clients store the response on sync.
        signed_public_key: Option<SignedPublicKey>,
        /// The user's signing key, wrapped by the user key.
        signing_key: EncString,
        /// The user's signed security state.
        security_state: SignedSecurityState,
    },
}

impl std::fmt::Debug for WrappedAccountCryptographicState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WrappedAccountCryptographicState::V1 { .. } => f
                .debug_struct("WrappedAccountCryptographicState::V1")
                .finish(),
            WrappedAccountCryptographicState::V2 { security_state, .. } => f
                .debug_struct("WrappedAccountCryptographicState::V2")
                .field("security_state", security_state)
                .finish(),
        }
    }
}

impl TryFrom<&PrivateKeysResponseModel> for WrappedAccountCryptographicState {
    type Error = AccountKeysResponseParseError;

    fn try_from(response: &PrivateKeysResponseModel) -> Result<Self, Self::Error> {
        let private_key: EncString =
            require!(&response.public_key_encryption_key_pair.wrapped_private_key)
                .parse()
                .map_err(|_| AccountKeysResponseParseError::MalformedField)?;

        let is_v2_encryption = matches!(private_key, EncString::Cose_Encrypt0_B64 { .. });

        if is_v2_encryption {
            let signature_key_pair = response
                .signature_key_pair
                .as_ref()
                .ok_or(AccountKeysResponseParseError::InconsistentState)?;

            let signing_key: EncString = require!(&signature_key_pair.wrapped_signing_key)
                .parse()
                .map_err(|_| AccountKeysResponseParseError::MalformedField)?;

            let signed_public_key: Option<SignedPublicKey> = response
                .public_key_encryption_key_pair
                .signed_public_key
                .as_ref()
                .map(|spk| spk.parse())
                .transpose()
                .map_err(|_| AccountKeysResponseParseError::MalformedField)?;

            let security_state_model = response
                .security_state
                .as_ref()
                .ok_or(AccountKeysResponseParseError::InconsistentState)?;
            let security_state: SignedSecurityState =
                require!(&security_state_model.security_state)
                    .parse()
                    .map_err(|_| AccountKeysResponseParseError::MalformedField)?;

            Ok(WrappedAccountCryptographicState::V2 {
                private_key,
                signed_public_key,
                signing_key,
                security_state,
            })
        } else {
            if response.signature_key_pair.is_some() || response.security_state.is_some() {
                return Err(AccountKeysResponseParseError::InconsistentState);
            }

            Ok(WrappedAccountCryptographicState::V1 { private_key })
        }
    }
}

impl WrappedAccountCryptographicState {
    /// Converts to a WrappedAccountCryptographicStateRequestModel in order to make API requests.
    /// Since the [WrappedAccountCryptographicState] is encrypted, the key store needs to
    /// contain the user key required to unlock this state. This request model only supports v2
    /// encryption.
    pub fn to_wrapped_request_model(
        &self,
        user_key: &SymmetricKeySlotId,
        ctx: &mut KeyStoreContext<KeySlotIds>,
    ) -> Result<WrappedAccountCryptographicStateRequestModel, AccountCryptographyInitializationError>
    {
        match self {
            WrappedAccountCryptographicState::V1 { .. } => {
                Err(AccountCryptographyInitializationError::WrongUserKeyType)
            }
            WrappedAccountCryptographicState::V2 {
                private_key,
                signing_key,
                security_state,
                signed_public_key,
                ..
            } => {
                let private_key = private_key.clone();
                let private_key_tmp_id = ctx.unwrap_private_key(*user_key, &private_key)?;
                let public_key = ctx.get_public_key(private_key_tmp_id)?;

                let signing_key_tmp_id = ctx.unwrap_signing_key(*user_key, signing_key)?;
                let verifying_key = ctx.get_verifying_key(signing_key_tmp_id)?;

                Ok(WrappedAccountCryptographicStateRequestModel {
                    signature_key_pair: Box::new(
                        bitwarden_api_api::models::SignatureKeyPairRequestModel {
                            wrapped_signing_key: Some(signing_key.to_string()),
                            verifying_key: Some(B64::from(verifying_key.to_cose()).to_string()),
                            signature_algorithm: Some(verifying_key.algorithm().to_string()),
                        },
                    ),
                    public_key_encryption_key_pair: Box::new(
                        bitwarden_api_api::models::PublicKeyEncryptionKeyPairRequestModel {
                            wrapped_private_key: Some(private_key.to_string()),
                            public_key: Some(B64::from(public_key.to_der()?).to_string()),
                            signed_public_key: signed_public_key.clone().map(|spk| spk.into()),
                        },
                    ),
                    // Convert the verified state's version to i32 for the API model
                    security_state: Box::new(SecurityStateModel {
                        security_state: Some(security_state.into()),
                        security_version: security_state
                            .to_owned()
                            .verify_and_unwrap(&verifying_key)
                            .map_err(|_| AccountCryptographyInitializationError::TamperedData)?
                            .version() as i32,
                    }),
                })
            }
        }
    }

    /// Converts to a AccountKeysRequestModel in order to make API requests. Since the
    /// [WrappedAccountCryptographicState] is encrypted, the key store needs to contain the
    /// user key required to unlock this state.
    #[instrument(skip_all, err)]
    pub fn to_request_model(
        &self,
        user_key: &SymmetricKeySlotId,
        ctx: &mut KeyStoreContext<KeySlotIds>,
    ) -> Result<AccountKeysRequestModel, AccountCryptographyInitializationError> {
        let private_key = match self {
            WrappedAccountCryptographicState::V1 { private_key }
            | WrappedAccountCryptographicState::V2 { private_key, .. } => private_key.clone(),
        };
        let private_key_tmp_id = ctx.unwrap_private_key(*user_key, &private_key)?;
        let public_key = ctx.get_public_key(private_key_tmp_id)?;

        let signature_keypair = match self {
            WrappedAccountCryptographicState::V1 { .. } => None,
            WrappedAccountCryptographicState::V2 { signing_key, .. } => {
                let signing_key_tmp_id = ctx.unwrap_signing_key(*user_key, signing_key)?;
                let verifying_key = ctx.get_verifying_key(signing_key_tmp_id)?;
                Some((signing_key.clone(), verifying_key))
            }
        };

        Ok(AccountKeysRequestModel {
            // Note: This property is deprecated and should be removed after a transition period.
            user_key_encrypted_account_private_key: Some(private_key.to_string()),
            // Note: This property is deprecated and should be removed after a transition period.
            account_public_key: Some(B64::from(public_key.to_der()?).to_string()),
            signature_key_pair: signature_keypair
                .as_ref()
                .map(|(signing_key, verifying_key)| {
                    Box::new(bitwarden_api_api::models::SignatureKeyPairRequestModel {
                        wrapped_signing_key: Some(signing_key.to_string()),
                        verifying_key: Some(B64::from(verifying_key.to_cose()).to_string()),
                        signature_algorithm: Some(verifying_key.algorithm().to_string()),
                    })
                }),
            public_key_encryption_key_pair: Some(Box::new(
                bitwarden_api_api::models::PublicKeyEncryptionKeyPairRequestModel {
                    wrapped_private_key: match self {
                        WrappedAccountCryptographicState::V1 { private_key }
                        | WrappedAccountCryptographicState::V2 { private_key, .. } => {
                            Some(private_key.to_string())
                        }
                    },
                    public_key: Some(B64::from(public_key.to_der()?).to_string()),
                    signed_public_key: match self.signed_public_key() {
                        Ok(Some(spk)) => Some(spk.clone().into()),
                        _ => None,
                    },
                },
            )),
            security_state: match (self, signature_keypair.as_ref()) {
                (_, None) | (WrappedAccountCryptographicState::V1 { .. }, Some(_)) => None,
                (
                    WrappedAccountCryptographicState::V2 { security_state, .. },
                    Some((_, verifying_key)),
                ) => {
                    // Convert the verified state's version to i32 for the API model
                    Some(Box::new(SecurityStateModel {
                        security_state: Some(security_state.into()),
                        security_version: security_state
                            .to_owned()
                            .verify_and_unwrap(verifying_key)
                            .map_err(|_| AccountCryptographyInitializationError::TamperedData)?
                            .version() as i32,
                    }))
                }
            },
        })
    }

    /// Creates a new V2 account cryptographic state with fresh keys. This does not change the user
    /// state, but does set some keys to the local context.
    pub fn make(
        ctx: &mut KeyStoreContext<KeySlotIds>,
    ) -> Result<(SymmetricKeySlotId, Self), AccountCryptographyInitializationError> {
        let user_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
        let private_key = ctx.make_private_key(PublicKeyEncryptionAlgorithm::RsaOaepSha1);
        let signing_key = ctx.make_signing_key(SignatureAlgorithm::MlDsa44);
        let signed_public_key = ctx.make_signed_public_key(private_key, signing_key)?;

        let security_state = SecurityState::new();
        let signed_security_state = security_state.sign(signing_key, ctx)?;

        Ok((
            user_key,
            WrappedAccountCryptographicState::V2 {
                private_key: ctx.wrap_private_key(user_key, private_key)?,
                signed_public_key: Some(signed_public_key),
                signing_key: ctx.wrap_signing_key(user_key, signing_key)?,
                security_state: signed_security_state,
            },
        ))
    }

    #[cfg(test)]
    fn make_v1(
        ctx: &mut KeyStoreContext<KeySlotIds>,
    ) -> Result<(SymmetricKeySlotId, Self), AccountCryptographyInitializationError> {
        let user_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
        let private_key = ctx.make_private_key(PublicKeyEncryptionAlgorithm::RsaOaepSha1);

        Ok((
            user_key,
            WrappedAccountCryptographicState::V1 {
                private_key: ctx.wrap_private_key(user_key, private_key)?,
            },
        ))
    }

    /// Re-wraps the account cryptographic state with a new user key. If the cryptographic state is
    /// a V1 state, it gets upgraded to a V2 state
    #[instrument(skip(self, ctx), err)]
    pub fn rotate(
        &self,
        current_user_key: &SymmetricKeySlotId,
        new_user_key: &SymmetricKeySlotId,
        ctx: &mut KeyStoreContext<KeySlotIds>,
    ) -> Result<Self, RotateCryptographyStateError> {
        match self {
            WrappedAccountCryptographicState::V1 { private_key } => {
                // To upgrade a V1 state to a V2 state,
                // 1. The private key is re-encrypted
                // 2. The signing key is generated
                // 3. The public key is signed and
                // 4. The security state is initialized and signed.

                // 1. Re-encrypt private key
                let private_key_id = ctx
                    .unwrap_private_key(*current_user_key, private_key)
                    .map_err(|_| RotateCryptographyStateError::InvalidData)?;
                let new_private_key = ctx
                    .wrap_private_key(*new_user_key, private_key_id)
                    .map_err(|_| RotateCryptographyStateError::KeyMissing)?;

                // 2. The signing key is generated
                let signing_key_id = ctx.make_signing_key(SignatureAlgorithm::MlDsa44);
                let new_signing_key = ctx
                    .wrap_signing_key(*new_user_key, signing_key_id)
                    .map_err(|_| RotateCryptographyStateError::KeyMissing)?;

                // 3. The public key is signed and
                let signed_public_key = ctx
                    .make_signed_public_key(private_key_id, signing_key_id)
                    .map_err(|_| RotateCryptographyStateError::KeyMissing)?;

                // 4. The security state is initialized and signed.
                let security_state = SecurityState::new();
                let signed_security_state = security_state
                    .sign(signing_key_id, ctx)
                    .map_err(|_| RotateCryptographyStateError::KeyMissing)?;

                Ok(WrappedAccountCryptographicState::V2 {
                    private_key: new_private_key,
                    signed_public_key: Some(signed_public_key),
                    signing_key: new_signing_key,
                    security_state: signed_security_state,
                })
            }
            WrappedAccountCryptographicState::V2 {
                private_key,
                signed_public_key,
                signing_key,
                security_state,
            } => {
                // To rotate a V2 state, the private and signing keys are re-encrypted with the new
                // user key.
                // 1. Re-encrypt private key
                let private_key_id = ctx
                    .unwrap_private_key(*current_user_key, private_key)
                    .map_err(|_| RotateCryptographyStateError::KeyMissing)?;
                let new_private_key = ctx
                    .wrap_private_key(*new_user_key, private_key_id)
                    .map_err(|_| RotateCryptographyStateError::KeyMissing)?;

                // 2. Re-encrypt signing key
                let signing_key_id = ctx
                    .unwrap_signing_key(*current_user_key, signing_key)
                    .map_err(|_| RotateCryptographyStateError::KeyMissing)?;
                let new_signing_key = ctx
                    .wrap_signing_key(*new_user_key, signing_key_id)
                    .map_err(|_| RotateCryptographyStateError::KeyMissing)?;

                Ok(WrappedAccountCryptographicState::V2 {
                    private_key: new_private_key,
                    signed_public_key: signed_public_key.clone(),
                    signing_key: new_signing_key,
                    security_state: security_state.clone(),
                })
            }
        }
    }

    /// Set the decrypted account cryptographic state to the context's non-local storage.
    /// This needs a mutable context passed in that already has a user_key set to a local key slot,
    /// for which the id is passed in as `user_key`. Note, that this function drops the context
    /// and clears the existing local state, after persisting it.
    pub(crate) fn set_to_context(
        &self,
        security_state_rwlock: &RwLock<Option<SecurityState>>,
        user_key: SymmetricKeySlotId,
        store: &KeyStore<KeySlotIds>,
        mut ctx: KeyStoreContext<KeySlotIds>,
    ) -> Result<(), AccountCryptographyInitializationError> {
        if ctx.has_symmetric_key(SymmetricKeySlotId::User)
            || ctx.has_private_key(PrivateKeySlotId::UserPrivateKey)
            || ctx.has_signing_key(SigningKeySlotId::UserSigningKey)
        {
            return Err(AccountCryptographyInitializationError::KeyStoreAlreadyInitialized);
        }

        match self {
            WrappedAccountCryptographicState::V1 { private_key } => {
                info!(state = ?self, "Initializing V1 account cryptographic state");
                if ctx.get_symmetric_key_algorithm(user_key)?
                    != SymmetricKeyAlgorithm::Aes256CbcHmac
                {
                    return Err(AccountCryptographyInitializationError::WrongUserKeyType);
                }

                // Some users have unreadable V1 private keys. In this case, we set no keys to
                // state.
                if let Ok(private_key_id) = ctx.unwrap_private_key(user_key, private_key) {
                    ctx.persist_private_key(private_key_id, PrivateKeySlotId::UserPrivateKey)?;
                } else {
                    tracing::warn!(
                        "V1 private key could not be unwrapped, skipping setting private key"
                    );
                }

                ctx.persist_symmetric_key(user_key, SymmetricKeySlotId::User)?;
                #[cfg(feature = "dangerous-crypto-debug")]
                #[allow(deprecated)]
                {
                    let user_key = ctx
                        .dangerous_get_symmetric_key(SymmetricKeySlotId::User)
                        .expect("User key should be set");
                    let private_key = ctx
                        .dangerous_get_private_key(PrivateKeySlotId::UserPrivateKey)
                        .ok();
                    let public_key = ctx.get_public_key(PrivateKeySlotId::UserPrivateKey).ok();
                    info!(
                        ?user_key,
                        ?private_key,
                        ?public_key,
                        "V1 account cryptographic state set to context"
                    );
                }
            }
            WrappedAccountCryptographicState::V2 {
                private_key,
                signed_public_key,
                signing_key,
                security_state,
            } => {
                info!(state = ?self, "Initializing V2 account cryptographic state");
                if ctx.get_symmetric_key_algorithm(user_key)?
                    != SymmetricKeyAlgorithm::XChaCha20Poly1305
                {
                    return Err(AccountCryptographyInitializationError::WrongUserKeyType);
                }

                let private_key_id = ctx
                    .unwrap_private_key(user_key, private_key)
                    .map_err(|_| AccountCryptographyInitializationError::WrongUserKey)?;
                let signing_key_id = ctx
                    .unwrap_signing_key(user_key, signing_key)
                    .map_err(|_| AccountCryptographyInitializationError::WrongUserKey)?;

                if let Some(signed_public_key) = signed_public_key {
                    signed_public_key
                        .to_owned()
                        .verify_and_unwrap(&ctx.get_verifying_key(signing_key_id)?)
                        .map_err(|_| AccountCryptographyInitializationError::TamperedData)?;
                }

                let verifying_key = ctx.get_verifying_key(signing_key_id)?;
                let security_state: SecurityState = security_state
                    .to_owned()
                    .verify_and_unwrap(&verifying_key)
                    .map_err(|_| AccountCryptographyInitializationError::TamperedData)?;
                info!(
                    security_state_version = security_state.version(),
                    verifying_key = ?verifying_key,
                    "V2 account cryptographic state verified"
                );
                ctx.persist_private_key(private_key_id, PrivateKeySlotId::UserPrivateKey)?;
                ctx.persist_signing_key(signing_key_id, SigningKeySlotId::UserSigningKey)?;
                ctx.persist_symmetric_key(user_key, SymmetricKeySlotId::User)?;

                #[cfg(feature = "dangerous-crypto-debug")]
                #[allow(deprecated)]
                {
                    let user_key = ctx
                        .dangerous_get_symmetric_key(SymmetricKeySlotId::User)
                        .expect("User key should be set");
                    let private_key = ctx
                        .dangerous_get_private_key(PrivateKeySlotId::UserPrivateKey)
                        .ok();
                    let signing_key = ctx
                        .dangerous_get_signing_key(SigningKeySlotId::UserSigningKey)
                        .ok();
                    let verifying_key =
                        ctx.get_verifying_key(SigningKeySlotId::UserSigningKey).ok();
                    let public_key = ctx.get_public_key(PrivateKeySlotId::UserPrivateKey).ok();
                    info!(
                        ?user_key,
                        ?private_key,
                        ?signing_key,
                        ?verifying_key,
                        ?public_key,
                        ?signed_public_key,
                        ?security_state,
                        "V2 account cryptographic state set to context."
                    );
                }

                // Not manually dropping ctx here would lead to a deadlock, since storing the state
                // needs to acquire a lock on the inner key store
                drop(ctx);
                store.set_security_state_version(security_state.version());
                *security_state_rwlock.write().expect("RwLock not poisoned") = Some(security_state);
            }
        }

        Ok(())
    }

    /// Retrieve the signed public key from the wrapped state, if present.
    fn signed_public_key(
        &self,
    ) -> Result<Option<&SignedPublicKey>, AccountCryptographyInitializationError> {
        match self {
            WrappedAccountCryptographicState::V1 { .. } => Ok(None),
            WrappedAccountCryptographicState::V2 {
                signed_public_key, ..
            } => Ok(signed_public_key.as_ref()),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{str::FromStr, sync::RwLock};

    use bitwarden_crypto::{KeyStore, PrimitiveEncryptable};

    use super::*;
    use crate::key_management::{PrivateKeySlotId, SigningKeySlotId, SymmetricKeySlotId};

    #[test]
    #[ignore = "Manual test to verify debug format"]
    fn test_debug() {
        let store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut ctx = store.context_mut();

        let (_, v1) = WrappedAccountCryptographicState::make_v1(&mut ctx).unwrap();
        println!("{:?}", v1);

        let v1 = format!("{v1:?}");
        assert!(!v1.contains("private_key"));

        let (_, v2) = WrappedAccountCryptographicState::make(&mut ctx).unwrap();
        println!("{:?}", v2);

        let v2 = format!("{v2:?}");
        assert!(!v2.contains("private_key"));
        assert!(!v2.contains("signed_public_key"));
        assert!(!v2.contains("signing_key"));
    }

    #[test]
    fn test_set_to_context_v1() {
        // Prepare a temporary store to create wrapped state using a known user key
        let temp_store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut temp_ctx = temp_store.context_mut();

        // Create a V1-style user key (Aes256CbcHmac) and add to temp context
        let user_key = temp_ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);

        // Make a private key and wrap it with the user key
        let private_key_id = temp_ctx.make_private_key(PublicKeyEncryptionAlgorithm::RsaOaepSha1);
        let wrapped_private = temp_ctx.wrap_private_key(user_key, private_key_id).unwrap();

        // Construct the V1 wrapped state
        let wrapped = WrappedAccountCryptographicState::V1 {
            private_key: wrapped_private,
        };
        #[allow(deprecated)]
        let user_key = temp_ctx
            .dangerous_get_symmetric_key(user_key)
            .unwrap()
            .to_owned();
        drop(temp_ctx);
        drop(temp_store);

        // Now attempt to set this wrapped state into a fresh store using the same user key
        let store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut ctx = store.context_mut();
        let user_key = ctx.add_local_symmetric_key(user_key);
        let security_state = RwLock::new(None);

        // This should succeed and move keys into the expected global slots
        wrapped
            .set_to_context(&security_state, user_key, &store, ctx)
            .unwrap();
        let ctx = store.context();

        // Assert that the private key and user symmetric key were set in the store
        assert!(ctx.has_private_key(PrivateKeySlotId::UserPrivateKey));
        assert!(ctx.has_symmetric_key(SymmetricKeySlotId::User));
    }

    #[test]
    fn test_set_to_context_v2() {
        // Prepare a temporary store to create wrapped state using a known user key
        let temp_store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut temp_ctx = temp_store.context_mut();

        // Create a V2-style user key (XChaCha20Poly1305) and add to temp context
        let user_key = temp_ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);

        // Make keys
        let private_key_id = temp_ctx.make_private_key(PublicKeyEncryptionAlgorithm::RsaOaepSha1);
        let signing_key_id = temp_ctx.make_signing_key(SignatureAlgorithm::Ed25519);
        let signed_public_key = temp_ctx
            .make_signed_public_key(private_key_id, signing_key_id)
            .unwrap();

        // Sign and wrap security state
        let security_state = SecurityState::new();
        let signed_security_state = security_state.sign(signing_key_id, &mut temp_ctx).unwrap();

        // Wrap the private and signing keys with the user key
        let wrapped_private = temp_ctx.wrap_private_key(user_key, private_key_id).unwrap();
        let wrapped_signing = temp_ctx.wrap_signing_key(user_key, signing_key_id).unwrap();

        let wrapped = WrappedAccountCryptographicState::V2 {
            private_key: wrapped_private,
            signed_public_key: Some(signed_public_key),
            signing_key: wrapped_signing,
            security_state: signed_security_state,
        };
        #[allow(deprecated)]
        let user_key = temp_ctx
            .dangerous_get_symmetric_key(user_key)
            .unwrap()
            .to_owned();
        drop(temp_ctx);
        drop(temp_store);

        // Now attempt to set this wrapped state into a fresh store using the same user key
        let store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut ctx = store.context_mut();
        let user_key = ctx.add_local_symmetric_key(user_key);
        let security_state = RwLock::new(None);

        wrapped
            .set_to_context(&security_state, user_key, &store, ctx)
            .unwrap();

        assert!(store.context().has_symmetric_key(SymmetricKeySlotId::User));
        // Assert that the account keys and security state were set
        assert!(
            store
                .context()
                .has_private_key(PrivateKeySlotId::UserPrivateKey)
        );
        assert!(
            store
                .context()
                .has_signing_key(SigningKeySlotId::UserSigningKey)
        );
        // Ensure security state was recorded
        assert!(security_state.read().unwrap().is_some());
    }

    #[test]
    fn test_to_private_keys_request_model_v2() {
        let temp_store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut temp_ctx = temp_store.context_mut();
        let (user_key, wrapped_account_cryptography_state) =
            WrappedAccountCryptographicState::make(&mut temp_ctx).unwrap();

        wrapped_account_cryptography_state
            .set_to_context(&RwLock::new(None), user_key, &temp_store, temp_ctx)
            .unwrap();

        let mut ctx = temp_store.context_mut();
        let model = wrapped_account_cryptography_state
            .to_request_model(&SymmetricKeySlotId::User, &mut ctx)
            .expect("to_private_keys_request_model should succeed");
        drop(ctx);

        let ctx = temp_store.context();

        let sig_pair = model
            .signature_key_pair
            .expect("signature_key_pair present");
        assert_eq!(
            sig_pair.verifying_key.unwrap(),
            B64::from(
                ctx.get_verifying_key(SigningKeySlotId::UserSigningKey)
                    .unwrap()
                    .to_cose()
            )
            .to_string()
        );

        let pk_pair = model.public_key_encryption_key_pair.unwrap();
        assert_eq!(
            pk_pair.public_key.unwrap(),
            B64::from(
                ctx.get_public_key(PrivateKeySlotId::UserPrivateKey)
                    .unwrap()
                    .to_der()
                    .unwrap()
            )
            .to_string()
        );

        let signed_security_state = model
            .security_state
            .clone()
            .expect("security_state present");
        let security_state =
            SignedSecurityState::from_str(signed_security_state.security_state.unwrap().as_str())
                .unwrap()
                .verify_and_unwrap(
                    &ctx.get_verifying_key(SigningKeySlotId::UserSigningKey)
                        .unwrap(),
                )
                .expect("security state should verify");
        assert_eq!(
            security_state.version(),
            model.security_state.unwrap().security_version as u64
        );
    }

    #[test]
    fn test_set_to_context_v1_corrupt_private_key() {
        // Test that a V1 account with a corrupt private key (valid EncString but invalid key data)
        // can still initialize, but skips setting the private key
        let temp_store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut temp_ctx = temp_store.context_mut();

        let user_key = temp_ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
        let corrupt_private_key = "not a private key"
            .encrypt(&mut temp_ctx, user_key)
            .unwrap();

        // Construct the V1 wrapped state with corrupt private key
        let wrapped = WrappedAccountCryptographicState::V1 {
            private_key: corrupt_private_key,
        };

        #[expect(deprecated)]
        let user_key_material = temp_ctx
            .dangerous_get_symmetric_key(user_key)
            .unwrap()
            .to_owned();
        drop(temp_ctx);
        drop(temp_store);

        // Now attempt to set this wrapped state into a fresh store
        let store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut ctx = store.context_mut();
        let user_key = ctx.add_local_symmetric_key(user_key_material);
        let security_state = RwLock::new(None);

        wrapped
            .set_to_context(&security_state, user_key, &store, ctx)
            .unwrap();

        let ctx = store.context();

        // The user symmetric key should be set
        assert!(ctx.has_symmetric_key(SymmetricKeySlotId::User));
        // But the private key should NOT be set (due to corruption)
        assert!(!ctx.has_private_key(PrivateKeySlotId::UserPrivateKey));
    }

    #[test]
    fn test_try_from_response_v2_roundtrip() {
        use bitwarden_api_api::models::{
            PublicKeyEncryptionKeyPairResponseModel, SecurityStateModel,
            SignatureKeyPairResponseModel,
        };

        let temp_store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut temp_ctx = temp_store.context_mut();
        let (user_key, wrapped_state) =
            WrappedAccountCryptographicState::make(&mut temp_ctx).unwrap();

        wrapped_state
            .set_to_context(&RwLock::new(None), user_key, &temp_store, temp_ctx)
            .unwrap();

        let mut ctx = temp_store.context_mut();
        let request_model = wrapped_state
            .to_request_model(&SymmetricKeySlotId::User, &mut ctx)
            .unwrap();
        drop(ctx);

        let pk_pair = request_model.public_key_encryption_key_pair.unwrap();
        let sig_pair = request_model.signature_key_pair.unwrap();
        let sec_state = request_model.security_state.unwrap();

        let response = PrivateKeysResponseModel {
            object: None,
            public_key_encryption_key_pair: Box::new(PublicKeyEncryptionKeyPairResponseModel {
                object: None,
                wrapped_private_key: pk_pair.wrapped_private_key,
                public_key: pk_pair.public_key,
                signed_public_key: pk_pair.signed_public_key,
            }),
            signature_key_pair: Some(Box::new(SignatureKeyPairResponseModel {
                object: None,
                wrapped_signing_key: sig_pair.wrapped_signing_key,
                verifying_key: sig_pair.verifying_key,
            })),
            security_state: Some(Box::new(SecurityStateModel {
                security_state: sec_state.security_state,
                security_version: sec_state.security_version,
            })),
        };

        let parsed = WrappedAccountCryptographicState::try_from(&response)
            .expect("V2 response should parse successfully");

        assert_eq!(parsed, wrapped_state);
    }

    #[test]
    fn test_try_from_response_v1() {
        use bitwarden_api_api::models::PublicKeyEncryptionKeyPairResponseModel;

        let temp_store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut temp_ctx = temp_store.context_mut();
        let (_user_key, wrapped_state) =
            WrappedAccountCryptographicState::make_v1(&mut temp_ctx).unwrap();

        let wrapped_private_key = match &wrapped_state {
            WrappedAccountCryptographicState::V1 { private_key } => private_key.to_string(),
            _ => panic!("Expected V1"),
        };
        drop(temp_ctx);

        let response = PrivateKeysResponseModel {
            object: None,
            public_key_encryption_key_pair: Box::new(PublicKeyEncryptionKeyPairResponseModel {
                object: None,
                wrapped_private_key: Some(wrapped_private_key),
                public_key: None,
                signed_public_key: None,
            }),
            signature_key_pair: None,
            security_state: None,
        };

        let parsed = WrappedAccountCryptographicState::try_from(&response)
            .expect("V1 response should parse successfully");

        assert_eq!(parsed, wrapped_state);
    }

    #[test]
    fn test_try_from_response_missing_private_key() {
        use bitwarden_api_api::models::PublicKeyEncryptionKeyPairResponseModel;

        let response = PrivateKeysResponseModel {
            object: None,
            public_key_encryption_key_pair: Box::new(PublicKeyEncryptionKeyPairResponseModel {
                object: None,
                wrapped_private_key: None,
                public_key: None,
                signed_public_key: None,
            }),
            signature_key_pair: None,
            security_state: None,
        };

        let result = WrappedAccountCryptographicState::try_from(&response);
        assert!(result.is_err());
        assert!(
            matches!(
                result.unwrap_err(),
                AccountKeysResponseParseError::MissingField(_)
            ),
            "Should return MissingField error"
        );
    }

    #[test]
    fn test_try_from_response_v2_encryption_missing_signature_key_pair() {
        use bitwarden_api_api::models::PublicKeyEncryptionKeyPairResponseModel;

        // Create a V2 state to get a COSE-encrypted private key
        let temp_store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut temp_ctx = temp_store.context_mut();
        let (user_key, wrapped_state) =
            WrappedAccountCryptographicState::make(&mut temp_ctx).unwrap();

        wrapped_state
            .set_to_context(&RwLock::new(None), user_key, &temp_store, temp_ctx)
            .unwrap();

        let mut ctx = temp_store.context_mut();
        let request_model = wrapped_state
            .to_request_model(&SymmetricKeySlotId::User, &mut ctx)
            .unwrap();
        drop(ctx);

        let pk_pair = request_model.public_key_encryption_key_pair.unwrap();

        // V2-encrypted private key but no signature_key_pair or security_state
        let response = PrivateKeysResponseModel {
            object: None,
            public_key_encryption_key_pair: Box::new(PublicKeyEncryptionKeyPairResponseModel {
                object: None,
                wrapped_private_key: pk_pair.wrapped_private_key,
                public_key: pk_pair.public_key,
                signed_public_key: None,
            }),
            signature_key_pair: None,
            security_state: None,
        };

        let result = WrappedAccountCryptographicState::try_from(&response);
        assert!(matches!(
            result.unwrap_err(),
            AccountKeysResponseParseError::InconsistentState
        ));
    }

    #[test]
    fn test_try_from_response_v1_encryption_with_unexpected_v2_fields() {
        use bitwarden_api_api::models::{
            PublicKeyEncryptionKeyPairResponseModel, SignatureKeyPairResponseModel,
        };

        // Create a V1 state to get an AES-encrypted private key
        let temp_store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut temp_ctx = temp_store.context_mut();
        let (_user_key, wrapped_state) =
            WrappedAccountCryptographicState::make_v1(&mut temp_ctx).unwrap();

        let wrapped_private_key = match &wrapped_state {
            WrappedAccountCryptographicState::V1 { private_key } => private_key.to_string(),
            _ => panic!("Expected V1"),
        };
        drop(temp_ctx);

        // V1-encrypted private key but with a signature_key_pair present
        let response = PrivateKeysResponseModel {
            object: None,
            public_key_encryption_key_pair: Box::new(PublicKeyEncryptionKeyPairResponseModel {
                object: None,
                wrapped_private_key: Some(wrapped_private_key),
                public_key: None,
                signed_public_key: None,
            }),
            signature_key_pair: Some(Box::new(SignatureKeyPairResponseModel {
                object: None,
                wrapped_signing_key: Some("bogus".to_string()),
                verifying_key: None,
            })),
            security_state: None,
        };

        let result = WrappedAccountCryptographicState::try_from(&response);
        assert!(matches!(
            result.unwrap_err(),
            AccountKeysResponseParseError::InconsistentState
        ));
    }

    #[test]
    fn test_rotate_v1_to_v2() {
        // Create a key store and context
        let store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut ctx = store.context_mut();

        // Create a V1-style user key and add to context
        let (old_user_key_id, wrapped_state) =
            WrappedAccountCryptographicState::make_v1(&mut ctx).unwrap();
        let new_user_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
        #[allow(deprecated)]
        let new_user_key_owned = ctx
            .dangerous_get_symmetric_key(new_user_key_id)
            .unwrap()
            .to_owned();
        wrapped_state
            .set_to_context(&RwLock::new(None), old_user_key_id, &store, ctx)
            .unwrap();

        // The previous context got consumed, so we are creating a new one here. Setting the state
        // to context persisted the user-key and other keys
        let mut ctx = store.context_mut();
        let new_user_key_id = ctx.add_local_symmetric_key(new_user_key_owned.clone());

        // Rotate the state
        let rotated_state = wrapped_state
            .rotate(&SymmetricKeySlotId::User, &new_user_key_id, &mut ctx)
            .unwrap();

        // We need to ensure two things after a rotation from V1 to V2:
        // 1. The new state is valid and can be set to context
        // 2. The new state uses the same private and signing keys

        // 1. The new state is valid and can be set to context
        match rotated_state {
            WrappedAccountCryptographicState::V2 { .. } => {}
            _ => panic!("Expected V2 after rotation from V1"),
        }
        let store_2 = KeyStore::<KeySlotIds>::default();
        let mut ctx_2 = store_2.context_mut();
        let user_key_id = ctx_2.add_local_symmetric_key(new_user_key_owned.clone());
        rotated_state
            .set_to_context(&RwLock::new(None), user_key_id, &store_2, ctx_2)
            .unwrap();
        // The context was consumed, so we create a new one to inspect the keys
        let ctx_2 = store_2.context();

        // 2. The new state uses the same private and signing keys
        let public_key_before_rotation = ctx
            .get_public_key(PrivateKeySlotId::UserPrivateKey)
            .expect("Private key should be present in context before rotation");
        let public_key_after_rotation = ctx_2
            .get_public_key(PrivateKeySlotId::UserPrivateKey)
            .expect("Private key should be present in context after rotation");
        assert_eq!(
            public_key_before_rotation.to_der().unwrap(),
            public_key_after_rotation.to_der().unwrap(),
            "Private key should be preserved during rotation from V2 to V2"
        );
    }

    #[test]
    fn test_rotate_v2() {
        // Create a key store and context
        let store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut ctx = store.context_mut();

        // Create a V2-style user key and add to context
        let (old_user_key_id, wrapped_state) =
            WrappedAccountCryptographicState::make(&mut ctx).unwrap();
        let new_user_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
        #[allow(deprecated)]
        let new_user_key_owned = ctx
            .dangerous_get_symmetric_key(new_user_key_id)
            .unwrap()
            .to_owned();
        wrapped_state
            .set_to_context(&RwLock::new(None), old_user_key_id, &store, ctx)
            .unwrap();

        // The previous context got consumed, so we are creating a new one here. Setting the state
        // to context persisted the user-key and other keys
        let mut ctx = store.context_mut();
        let new_user_key_id = ctx.add_local_symmetric_key(new_user_key_owned.clone());

        // Rotate the state
        let rotated_state = wrapped_state
            .rotate(&SymmetricKeySlotId::User, &new_user_key_id, &mut ctx)
            .unwrap();

        // We need to ensure two things after a rotation from V1 to V2:
        // 1. The new state is valid and can be set to context
        // 2. The new state uses the same private and signing keys

        // 1. The new state is valid and can be set to context
        match rotated_state {
            WrappedAccountCryptographicState::V2 { .. } => {}
            _ => panic!("Expected V2 after rotation from V2"),
        }
        let store_2 = KeyStore::<KeySlotIds>::default();
        let mut ctx_2 = store_2.context_mut();
        let user_key_id = ctx_2.add_local_symmetric_key(new_user_key_owned.clone());
        rotated_state
            .set_to_context(&RwLock::new(None), user_key_id, &store_2, ctx_2)
            .unwrap();
        // The context was consumed, so we create a new one to inspect the keys
        let ctx_2 = store_2.context();

        // 2. The new state uses the same private and signing keys
        let verifying_key_before_rotation = ctx
            .get_verifying_key(SigningKeySlotId::UserSigningKey)
            .expect("Signing key should be present in context before rotation");
        let verifying_key_after_rotation = ctx_2
            .get_verifying_key(SigningKeySlotId::UserSigningKey)
            .expect("Signing key should be present in context after rotation");
        assert_eq!(
            verifying_key_before_rotation.to_cose(),
            verifying_key_after_rotation.to_cose(),
            "Signing key should be preserved during rotation from V2 to V2"
        );

        let public_key_before_rotation = ctx
            .get_public_key(PrivateKeySlotId::UserPrivateKey)
            .expect("Private key should be present in context before rotation");
        let public_key_after_rotation = ctx_2
            .get_public_key(PrivateKeySlotId::UserPrivateKey)
            .expect("Private key should be present in context after rotation");
        assert_eq!(
            public_key_before_rotation.to_der().unwrap(),
            public_key_after_rotation.to_der().unwrap(),
            "Private key should be preserved during rotation from V2 to V2"
        );
    }

    #[test]
    fn test_to_wrapped_request_model_v1_returns_wrong_user_key_type() {
        let store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut ctx = store.context_mut();
        let (user_key_id, wrapped) = WrappedAccountCryptographicState::make_v1(&mut ctx).unwrap();
        let result = wrapped.to_wrapped_request_model(&user_key_id, &mut ctx);
        assert!(matches!(
            result.unwrap_err(),
            AccountCryptographyInitializationError::WrongUserKeyType
        ));
    }

    #[test]
    fn test_to_wrapped_request_model_v2() {
        let store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut ctx = store.context_mut();
        let (user_key_id, wrapped) = WrappedAccountCryptographicState::make(&mut ctx).unwrap();
        let result = wrapped
            .to_wrapped_request_model(&user_key_id, &mut ctx)
            .unwrap();

        let wrapped_signing_key_str = result
            .signature_key_pair
            .wrapped_signing_key
            .as_ref()
            .unwrap();
        assert!(!wrapped_signing_key_str.is_empty());

        let enc_signing_key: EncString = wrapped_signing_key_str.parse().unwrap();
        let signing_key_tmp = ctx
            .unwrap_signing_key(user_key_id, &enc_signing_key)
            .unwrap();
        let verifying_key = ctx.get_verifying_key(signing_key_tmp).unwrap();
        let expected = B64::from(verifying_key.to_cose()).to_string();
        assert!(
            result
                .signature_key_pair
                .verifying_key
                .as_ref()
                .is_some_and(|s| s == &expected),
            "verifying_key should match expected value"
        );

        assert_eq!(
            result.signature_key_pair.signature_algorithm.as_deref(),
            Some("mldsa44")
        );

        assert!(
            result
                .public_key_encryption_key_pair
                .wrapped_private_key
                .as_ref()
                .is_some_and(|s| !s.is_empty()),
            "wrapped_private_key should be non-empty"
        );
        let wrapped_private_key_str = result
            .public_key_encryption_key_pair
            .wrapped_private_key
            .as_ref()
            .unwrap();
        let enc_private_key: EncString = wrapped_private_key_str.parse().unwrap();
        let private_key_tmp = ctx
            .unwrap_private_key(user_key_id, &enc_private_key)
            .unwrap();
        let public_key = ctx.get_public_key(private_key_tmp).unwrap();

        let expected = B64::from(public_key.to_der().unwrap()).to_string();
        assert!(
            result
                .public_key_encryption_key_pair
                .public_key
                .as_ref()
                .is_some_and(|s| s == &expected),
            "public_key should match expected value"
        );
        assert!(
            result
                .public_key_encryption_key_pair
                .signed_public_key
                .is_some(),
            "signed_public_key should be present"
        );
        assert!(
            result
                .security_state
                .security_state
                .as_ref()
                .is_some_and(|s| !s.is_empty()),
            "security_state string should be non-empty"
        );
        assert!(result.security_state.security_version == 2);
    }

    #[test]
    fn test_to_wrapped_request_model_wrong_user_key_returns_error() {
        let store: KeyStore<KeySlotIds> = KeyStore::default();
        let mut ctx = store.context_mut();
        let (_user_key_id, wrapped) = WrappedAccountCryptographicState::make(&mut ctx).unwrap();

        // Create a different XChaCha20Poly1305 user key that wasn't used to wrap these keys
        let wrong_user_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);

        let result = wrapped.to_wrapped_request_model(&wrong_user_key_id, &mut ctx);
        assert!(result.is_err());
        // Decryption failure, not a key type mismatch
        assert!(!matches!(
            result.unwrap_err(),
            AccountCryptographyInitializationError::WrongUserKeyType
        ));
    }
}