Skip to main content

bitwarden_crypto_sync_handler/
crypto_sync_handler.rs

1//! Key management work that runs on every sync.
2
3#[cfg(any(feature = "uniffi", feature = "wasm"))]
4use bitwarden_core::key_management::crypto::{ReinitUserCryptoError, ReinitUserCryptoRequest};
5#[cfg(not(target_arch = "wasm32"))]
6use bitwarden_core::key_management::{
7    MasterPasswordError, V2UpgradeTokenError, WebAuthnPrfError,
8    account_cryptographic_state::AccountKeysResponseParseError,
9};
10use bitwarden_core::{
11    Client,
12    key_management::{
13        MasterPasswordUnlockData, V2UpgradeToken, WebAuthnPrfUnlockData, WebAuthnPrfUnlockOption,
14        account_cryptographic_state::WrappedAccountCryptographicState,
15    },
16};
17use bitwarden_crypto::KeyId;
18#[cfg(feature = "wasm")]
19use bitwarden_encrypted_migrator::EncryptedMigratorClientExt as _;
20use serde::{Deserialize, Serialize};
21#[cfg(any(feature = "uniffi", feature = "wasm"))]
22use tracing::debug;
23use tracing::warn;
24
25/// The parts of a sync response the key management sync handler needs.
26#[derive(Serialize, Deserialize, Debug, Clone, Default)]
27#[serde(rename_all = "camelCase", deny_unknown_fields)]
28#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
29#[bitwarden_ffi::wasm_record]
30pub struct CryptoSyncData {
31    /// The account's user decryption options, as the server reports them on sync.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    #[cfg_attr(feature = "wasm", tsify(optional))]
34    pub user_decryption: Option<CryptoSyncUserDecryption>,
35    /// The account's cryptographic state, as the server reports it on sync.
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    #[cfg_attr(feature = "wasm", tsify(optional))]
38    pub account_cryptographic_state: Option<WrappedAccountCryptographicState>,
39}
40
41/// The user decryption options a sync response carries, narrowed to the parts key management owns.
42#[derive(Serialize, Deserialize, Debug, Clone, Default)]
43#[serde(rename_all = "camelCase", deny_unknown_fields)]
44#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
45#[bitwarden_ffi::wasm_record]
46pub struct CryptoSyncUserDecryption {
47    /// Unlock data for accounts that have a master password.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    #[cfg_attr(feature = "wasm", tsify(optional))]
50    pub master_password_unlock: Option<MasterPasswordUnlockData>,
51    /// Token allowing unlock after a V1 to V2 upgrade, when one is outstanding.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    #[cfg_attr(feature = "wasm", tsify(optional))]
54    pub v2_upgrade_token: Option<V2UpgradeToken>,
55    /// The WebAuthn PRF credentials the account can unlock with.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    #[cfg_attr(feature = "wasm", tsify(optional))]
58    pub web_authn_prf_options: Option<Vec<WebAuthnPrfUnlockOption>>,
59    /// The id of the account's current user key.
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    #[cfg_attr(feature = "wasm", tsify(optional))]
62    pub user_key_id: Option<KeyId>,
63}
64
65/// Errors returned when a sync response cannot be converted into [`CryptoSyncData`].
66///
67/// The conversion happens before anything is written to state, so returning one of these leaves
68/// state untouched rather than partially updated.
69#[cfg(not(target_arch = "wasm32"))]
70#[derive(Debug, thiserror::Error)]
71pub enum CryptoSyncDataParseError {
72    /// The sync response carried master password unlock data that could not be parsed.
73    #[error("Sync response carried unparseable master password unlock data")]
74    MasterPasswordUnlock(#[source] MasterPasswordError),
75    /// The sync response carried a V2 upgrade token that could not be parsed.
76    #[error("Sync response carried an unparseable V2 upgrade token")]
77    V2UpgradeToken(#[source] V2UpgradeTokenError),
78    /// The sync response carried a WebAuthn PRF unlock option that could not be parsed.
79    #[error("Sync response carried an unparseable WebAuthn PRF unlock option")]
80    WebAuthnPrfOption(#[source] WebAuthnPrfError),
81    /// The sync response carried a user key id that could not be parsed.
82    #[error("Sync response carried an unparseable user key id")]
83    UserKeyId(#[source] bitwarden_crypto::CryptoError),
84    /// The sync response carried account cryptographic state that could not be parsed.
85    #[error("Sync response carried unparseable account cryptographic state")]
86    AccountCryptographicState(#[source] AccountKeysResponseParseError),
87}
88
89#[cfg(not(target_arch = "wasm32"))]
90impl TryFrom<&bitwarden_api_api::models::SyncResponseModel> for CryptoSyncData {
91    type Error = CryptoSyncDataParseError;
92
93    fn try_from(
94        response: &bitwarden_api_api::models::SyncResponseModel,
95    ) -> Result<Self, Self::Error> {
96        Ok(Self {
97            user_decryption: response
98                .user_decryption
99                .as_deref()
100                .map(CryptoSyncUserDecryption::try_from)
101                .transpose()?,
102            account_cryptographic_state: response
103                .profile
104                .as_deref()
105                .and_then(|p| p.account_keys.as_deref())
106                .map(WrappedAccountCryptographicState::try_from)
107                .transpose()
108                .map_err(CryptoSyncDataParseError::AccountCryptographicState)?,
109        })
110    }
111}
112
113#[cfg(not(target_arch = "wasm32"))]
114impl TryFrom<&bitwarden_api_api::models::UserDecryptionResponseModel> for CryptoSyncUserDecryption {
115    type Error = CryptoSyncDataParseError;
116
117    fn try_from(
118        response: &bitwarden_api_api::models::UserDecryptionResponseModel,
119    ) -> Result<Self, Self::Error> {
120        Ok(Self {
121            master_password_unlock: response
122                .master_password_unlock
123                .as_deref()
124                .map(MasterPasswordUnlockData::try_from)
125                .transpose()
126                .map_err(CryptoSyncDataParseError::MasterPasswordUnlock)?,
127            v2_upgrade_token: response
128                .v2_upgrade_token
129                .as_deref()
130                .map(V2UpgradeToken::try_from)
131                .transpose()
132                .map_err(CryptoSyncDataParseError::V2UpgradeToken)?,
133            web_authn_prf_options: response
134                .web_authn_prf_options
135                .as_deref()
136                .map(|options| {
137                    options
138                        .iter()
139                        .map(WebAuthnPrfUnlockOption::try_from)
140                        .collect::<Result<Vec<_>, _>>()
141                })
142                .transpose()
143                .map_err(CryptoSyncDataParseError::WebAuthnPrfOption)?,
144            user_key_id: response
145                .user_key_id
146                .as_deref()
147                .map(str::parse)
148                .transpose()
149                .map_err(CryptoSyncDataParseError::UserKeyId)?,
150        })
151    }
152}
153
154/// Runs the key management sync work for the given sync data.
155async fn handle_crypto_sync(client: &Client, data: &CryptoSyncData) {
156    // A replayed payload is refused whole: taking its user decryption options would let the
157    // server swap out the key id and unlock data that belong to the state it just tried to undo.
158    if is_replayed_state(client, data).await {
159        warn!("WARNING: Refusing a V2 to V1 account cryptographic state downgrade.");
160        return;
161    }
162
163    // Handlers MUST NOT fail, to avoid partial state writes
164    handle_user_decryption_options(client, data).await;
165    handle_account_cryptographic_state(client, data).await;
166    handle_v2_upgrade(client, data).await;
167
168    // Further key management sync handlers go here.
169}
170
171/// Persists the user decryption options the server reported.
172async fn handle_user_decryption_options(client: &Client, data: &CryptoSyncData) {
173    let Some(user_decryption) = data.user_decryption.as_ref() else {
174        return;
175    };
176
177    // This is necessary until all clients implement the state bridge.
178    let state_bridge = client.km_state_bridge();
179    if !state_bridge.is_bridge_registered() {
180        return;
181    }
182
183    match user_decryption.master_password_unlock.as_ref() {
184        Some(master_password_unlock) => {
185            state_bridge
186                .set_masterpassword_unlock_data(master_password_unlock)
187                .await;
188            state_bridge
189                .set_kdf_config(&master_password_unlock.kdf)
190                .await;
191        }
192        None => state_bridge.clear_masterpassword_unlock_data().await,
193    }
194
195    match user_decryption.v2_upgrade_token.as_ref() {
196        Some(v2_upgrade_token) => state_bridge.set_v2_upgrade_token(v2_upgrade_token).await,
197        None => state_bridge.clear_v2_upgrade_token().await,
198    }
199
200    // An absent list and an empty list both mean the account has no PRF-capable credentials.
201    match user_decryption.web_authn_prf_options.as_ref() {
202        Some(options) if !options.is_empty() => {
203            state_bridge
204                .set_webauthn_prf_unlock_data(&WebAuthnPrfUnlockData {
205                    options: options.clone(),
206                })
207                .await
208        }
209        _ => state_bridge.clear_webauthn_prf_unlock_data().await,
210    }
211
212    // The stored key id mirrors the server's. An absent one means the server has no id recorded for
213    // this user key, so a previously stored id no longer describes anything and is dropped.
214    match user_decryption.user_key_id.as_ref() {
215        Some(user_key_id) => state_bridge.set_user_key_id(user_key_id).await,
216        None => state_bridge.clear_user_key_id().await,
217    }
218}
219
220/// Persists the account cryptographic state the server reported.
221async fn handle_account_cryptographic_state(client: &Client, data: &CryptoSyncData) {
222    let Some(incoming) = data.account_cryptographic_state.as_ref() else {
223        return;
224    };
225
226    // This is necessary until all clients implement the state bridge.
227    let state_bridge = client.km_state_bridge();
228    if !state_bridge.is_bridge_registered() {
229        return;
230    }
231
232    state_bridge.set_account_cryptographic_state(incoming).await;
233}
234
235/// Applies a V1 to V2 upgrade done on another device to an unlocked client.
236///
237/// The upgrade token and V2 state are stored above, but an unlocked client still holds the V1 user
238/// key, in memory and in client state. Re-initializing swaps it for the V2 key and writes that
239/// back, so the client does not prompt for a second, destructive, V2 to V2 rotation.
240///
241///   unlocked client (K1) ── sync(V2 state + token) ──▶ reinit ──▶ K2 in memory and in state
242///   locked client       ── sync(V2 state + token) ──▶ nothing, the next unlock upgrades
243#[cfg(any(feature = "uniffi", feature = "wasm"))]
244async fn handle_v2_upgrade(client: &Client, data: &CryptoSyncData) {
245    let Some(account_cryptographic_state) = data.account_cryptographic_state.clone() else {
246        return;
247    };
248    let Some(upgrade_token) = data
249        .user_decryption
250        .as_ref()
251        .and_then(|user_decryption| user_decryption.v2_upgrade_token.clone())
252    else {
253        return;
254    };
255
256    let result = client
257        .crypto()
258        .reinit_user_crypto(ReinitUserCryptoRequest {
259            account_cryptographic_state,
260            upgrade_token,
261        })
262        .await;
263
264    match result {
265        Ok(()) => {}
266        Err(ReinitUserCryptoError::NotUnlocked) => debug!("Locked, skipping V2 upgrade reinit"),
267        // Handlers MUST NOT fail, to avoid partial state writes
268        Err(e) => warn!(error = ?e, "Failed to apply the V2 upgrade to the unlocked client"),
269    }
270}
271
272#[cfg(not(any(feature = "uniffi", feature = "wasm")))]
273async fn handle_v2_upgrade(_client: &Client, _data: &CryptoSyncData) {}
274
275/// Whether the sync carries a state that constitutes a cryptographic downgrade
276///
277/// Currently, the only downgrade defined is a V2 -> V1 encryption downgrade
278async fn is_replayed_state(client: &Client, data: &CryptoSyncData) -> bool {
279    let Some(incoming) = data.account_cryptographic_state.as_ref() else {
280        return false;
281    };
282    let Some(local) = client
283        .km_state_bridge()
284        .get_account_cryptographic_state()
285        .await
286    else {
287        return false;
288    };
289
290    if is_v2_to_v1_downgrade(&local, incoming) {
291        return true;
292    }
293
294    // If we define more downgrade types in the future, check them here.
295    false
296}
297
298/// Whether the incoming state moves a locally V2 account back to V1.
299///
300/// V1 accounts carry no security state, so staying on V1 or upgrading to V2 is never a downgrade.
301fn is_v2_to_v1_downgrade(
302    local: &WrappedAccountCryptographicState,
303    incoming: &WrappedAccountCryptographicState,
304) -> bool {
305    matches!(local, WrappedAccountCryptographicState::V2 { .. })
306        && matches!(incoming, WrappedAccountCryptographicState::V1 { .. })
307}
308
309/// Client for the key management work that runs on every sync.
310#[derive(Clone)]
311#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
312#[bitwarden_ffi::wasm_object]
313pub struct CryptoSyncHandlerClient {
314    client: Client,
315}
316
317impl CryptoSyncHandlerClient {
318    fn new(client: Client) -> Self {
319        Self { client }
320    }
321}
322
323#[bitwarden_ffi::wasm_export]
324#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
325impl CryptoSyncHandlerClient {
326    /// Runs the key management sync work. Call this after each sync, once the user's cryptographic
327    /// state has been applied.
328    pub async fn on_sync(&self, data: CryptoSyncData) {
329        handle_crypto_sync(&self.client, &data).await;
330        #[cfg(feature = "wasm")]
331        self.client
332            .encrypted_migrator()
333            .trigger_background_migrations();
334    }
335}
336
337/// Extension trait to add the key management sync handler client to the main Bitwarden SDK client.
338pub trait CryptoSyncHandlerClientExt {
339    /// Get the key management sync handler client.
340    fn crypto_sync_handler(&self) -> CryptoSyncHandlerClient;
341}
342
343impl CryptoSyncHandlerClientExt for Client {
344    fn crypto_sync_handler(&self) -> CryptoSyncHandlerClient {
345        CryptoSyncHandlerClient::new(self.clone())
346    }
347}
348
349/// [`bitwarden_sync::SyncHandler`] implementation of the same work, reading the sync data straight
350/// off the generated sync response model.
351///
352/// Unused while the clients still own sync — they call [`CryptoSyncHandlerClient::on_sync`] instead
353/// — but this is the entry point that survives once sync moves into the SDK.
354///
355/// Not available on `wasm32`: [`bitwarden_sync::SyncHandler`] requires `Send` futures, while the
356/// generated `bitwarden-api-api` client is `?Send` on that target. `bitwarden-sync` is not exposed
357/// to the wasm bindings either, so nothing is lost — wasm callers use
358/// [`CryptoSyncHandlerClient::on_sync`].
359#[cfg(not(target_arch = "wasm32"))]
360pub struct CryptoSyncHandler {
361    client: Client,
362}
363
364#[cfg(not(target_arch = "wasm32"))]
365impl CryptoSyncHandler {
366    /// Creates a handler bound to the given client.
367    pub fn new(client: Client) -> Self {
368        Self { client }
369    }
370}
371
372#[cfg(not(target_arch = "wasm32"))]
373#[async_trait::async_trait]
374impl bitwarden_sync::SyncHandler for CryptoSyncHandler {
375    async fn on_sync(
376        &self,
377        response: &bitwarden_api_api::models::SyncResponseModel,
378    ) -> Result<(), bitwarden_sync::SyncHandlerError> {
379        // Parsing happens up front so that a malformed response fails the sync without having
380        // written any state.
381        let data = CryptoSyncData::try_from(response)?;
382
383        handle_crypto_sync(&self.client, &data).await;
384        Ok(())
385    }
386}
387
388#[cfg(all(test, not(target_arch = "wasm32")))]
389mod tests {
390    use bitwarden_api_api::models::{
391        KdfType, MasterPasswordUnlockKdfResponseModel, MasterPasswordUnlockResponseModel,
392        SyncResponseModel, UserDecryptionResponseModel, WebAuthnPrfDecryptionOption,
393    };
394    use bitwarden_core::key_management::{
395        KeySlotIds, state_bridge::test_support::InMemoryStateBridge,
396    };
397    use bitwarden_crypto::{KeyStore, PublicKeyEncryptionAlgorithm, SymmetricKeyAlgorithm};
398
399    use super::*;
400
401    const TEST_USER_KEY: &str = "2.Q/2PhzcC7GdeiMHhWguYAQ==|GpqzVdr0go0ug5cZh1n+uixeBC3oC90CIe0hd/HWA/pTRDZ8ane4fmsEIcuc8eMKUt55Y2q/fbNzsYu41YTZzzsJUSeqVjT8/iTQtgnNdpo=|dwI+uyvZ1h/iZ03VQ+/wrGEFYVewBUUl/syYgjsNMbE=";
402    const TEST_SALT: &str = "[email protected]";
403    const TEST_USER_KEY_ID: &str = "000102030405060708090a0b0c0d0e0f";
404
405    fn master_password_unlock(
406        master_key_encrypted_user_key: Option<String>,
407    ) -> MasterPasswordUnlockResponseModel {
408        MasterPasswordUnlockResponseModel {
409            kdf: Box::new(MasterPasswordUnlockKdfResponseModel {
410                kdf_type: KdfType::PBKDF2_SHA256,
411                iterations: 600_000,
412                memory: None,
413                parallelism: None,
414            }),
415            master_key_encrypted_user_key,
416            salt: Some(TEST_SALT.to_string()),
417            contained_key_id: None,
418        }
419    }
420
421    fn sync_response(user_decryption: UserDecryptionResponseModel) -> SyncResponseModel {
422        SyncResponseModel {
423            user_decryption: Some(Box::new(user_decryption)),
424            ..Default::default()
425        }
426    }
427
428    #[test]
429    fn test_try_from_empty_response_is_empty_data() {
430        let data = CryptoSyncData::try_from(&SyncResponseModel::default()).unwrap();
431
432        assert!(data.user_decryption.is_none());
433        assert!(data.account_cryptographic_state.is_none());
434    }
435
436    #[test]
437    fn test_try_from_valid_master_password_unlock_succeeds() {
438        let response = sync_response(UserDecryptionResponseModel {
439            master_password_unlock: Some(Box::new(master_password_unlock(Some(
440                TEST_USER_KEY.to_string(),
441            )))),
442            ..Default::default()
443        });
444
445        let data = CryptoSyncData::try_from(&response).unwrap();
446
447        let user_decryption = data.user_decryption.unwrap();
448        assert_eq!(
449            user_decryption.master_password_unlock.unwrap().salt,
450            TEST_SALT
451        );
452    }
453
454    #[test]
455    fn test_try_from_malformed_master_password_unlock_errors() {
456        // Missing wrapped user key.
457        let response = sync_response(UserDecryptionResponseModel {
458            master_password_unlock: Some(Box::new(master_password_unlock(None))),
459            ..Default::default()
460        });
461
462        assert!(matches!(
463            CryptoSyncData::try_from(&response),
464            Err(CryptoSyncDataParseError::MasterPasswordUnlock(_))
465        ));
466    }
467
468    #[test]
469    fn test_try_from_malformed_webauthn_prf_option_errors() {
470        let response = sync_response(UserDecryptionResponseModel {
471            web_authn_prf_options: Some(vec![WebAuthnPrfDecryptionOption::default()]),
472            ..Default::default()
473        });
474
475        assert!(matches!(
476            CryptoSyncData::try_from(&response),
477            Err(CryptoSyncDataParseError::WebAuthnPrfOption(_))
478        ));
479    }
480
481    #[test]
482    fn test_try_from_valid_user_key_id_succeeds() {
483        let response = sync_response(UserDecryptionResponseModel {
484            user_key_id: Some(TEST_USER_KEY_ID.to_string()),
485            ..Default::default()
486        });
487
488        let data = CryptoSyncData::try_from(&response).unwrap();
489
490        let user_key_id = data.user_decryption.unwrap().user_key_id.unwrap();
491        assert_eq!(user_key_id.to_string(), TEST_USER_KEY_ID);
492    }
493
494    #[test]
495    fn test_try_from_absent_user_key_id_is_none() {
496        // The account has other unlock data, but the server has no key id recorded for it yet.
497        let response = sync_response(UserDecryptionResponseModel {
498            master_password_unlock: Some(Box::new(master_password_unlock(Some(
499                TEST_USER_KEY.to_string(),
500            )))),
501            ..Default::default()
502        });
503
504        let data = CryptoSyncData::try_from(&response).unwrap();
505
506        assert!(data.user_decryption.unwrap().user_key_id.is_none());
507    }
508
509    #[test]
510    fn test_try_from_malformed_user_key_id_errors() {
511        for malformed in [
512            "not hex at all",
513            // Valid hex, but not 16 bytes worth.
514            "00ff",
515            // Odd number of hex digits.
516            "000102030405060708090a0b0c0d0e0",
517        ] {
518            let response = sync_response(UserDecryptionResponseModel {
519                user_key_id: Some(malformed.to_string()),
520                ..Default::default()
521            });
522
523            assert!(
524                matches!(
525                    CryptoSyncData::try_from(&response),
526                    Err(CryptoSyncDataParseError::UserKeyId(_))
527                ),
528                "{malformed:?} should not parse as a key id"
529            );
530        }
531    }
532
533    /// The key id has to reach the state bridge, not just the parsed data. An absent id clears a
534    /// previously stored one.
535    #[tokio::test]
536    async fn test_handle_crypto_sync_writes_and_clears_user_key_id() {
537        let client = Client::new(None);
538        client
539            .km_state_bridge()
540            .register_bridge(Box::new(InMemoryStateBridge::default()));
541
542        let with_key_id = CryptoSyncData::try_from(&sync_response(UserDecryptionResponseModel {
543            user_key_id: Some(TEST_USER_KEY_ID.to_string()),
544            ..Default::default()
545        }))
546        .unwrap();
547        handle_crypto_sync(&client, &with_key_id).await;
548
549        let stored = client.km_state_bridge().get_user_key_id().await.unwrap();
550        assert_eq!(stored.to_string(), TEST_USER_KEY_ID);
551
552        let without_key_id =
553            CryptoSyncData::try_from(&sync_response(UserDecryptionResponseModel::default()))
554                .unwrap();
555        handle_crypto_sync(&client, &without_key_id).await;
556
557        assert!(client.km_state_bridge().get_user_key_id().await.is_none());
558    }
559
560    /// A client with an in-memory state bridge registered.
561    fn client_with_bridge() -> Client {
562        let client = Client::new(None);
563        client
564            .km_state_bridge()
565            .register_bridge(Box::new(InMemoryStateBridge::default()));
566        client
567    }
568
569    fn make_v2_state() -> WrappedAccountCryptographicState {
570        let store: KeyStore<KeySlotIds> = KeyStore::default();
571        let mut ctx = store.context_mut();
572        let (_, state) =
573            WrappedAccountCryptographicState::make(&mut ctx).expect("making a V2 state succeeds");
574        state
575    }
576
577    fn make_v1_state() -> WrappedAccountCryptographicState {
578        let store: KeyStore<KeySlotIds> = KeyStore::default();
579        let mut ctx = store.context_mut();
580        let user_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
581        let private_key = ctx.make_private_key(PublicKeyEncryptionAlgorithm::RsaOaepSha1);
582
583        WrappedAccountCryptographicState::V1 {
584            private_key: ctx
585                .wrap_private_key(user_key, private_key)
586                .expect("wrapping the private key succeeds"),
587        }
588    }
589
590    /// Runs the handler for the given incoming state and returns what the bridge holds afterwards.
591    async fn sync_account_cryptographic_state(
592        client: &Client,
593        incoming: &WrappedAccountCryptographicState,
594    ) -> Option<WrappedAccountCryptographicState> {
595        let data = CryptoSyncData {
596            account_cryptographic_state: Some(incoming.clone()),
597            ..Default::default()
598        };
599        handle_crypto_sync(client, &data).await;
600        client
601            .km_state_bridge()
602            .get_account_cryptographic_state()
603            .await
604    }
605
606    #[tokio::test]
607    async fn test_account_cryptographic_state_is_persisted_when_there_is_no_local_state() {
608        let client = client_with_bridge();
609        let incoming = make_v2_state();
610
611        let stored = sync_account_cryptographic_state(&client, &incoming).await;
612
613        assert_eq!(stored.as_ref(), Some(&incoming));
614    }
615
616    #[tokio::test]
617    async fn test_account_cryptographic_state_upgrade_from_v1_to_v2_is_persisted() {
618        let client = client_with_bridge();
619        client
620            .km_state_bridge()
621            .set_account_cryptographic_state(&make_v1_state())
622            .await;
623        let incoming = make_v2_state();
624
625        let stored = sync_account_cryptographic_state(&client, &incoming).await;
626
627        assert_eq!(stored.as_ref(), Some(&incoming));
628    }
629
630    #[tokio::test]
631    async fn test_account_cryptographic_state_downgrade_from_v2_to_v1_is_rejected() {
632        let client = client_with_bridge();
633        let local = make_v2_state();
634        client
635            .km_state_bridge()
636            .set_account_cryptographic_state(&local)
637            .await;
638
639        let stored = sync_account_cryptographic_state(&client, &make_v1_state()).await;
640
641        assert_eq!(stored.as_ref(), Some(&local));
642    }
643}