Skip to main content

bitwarden_core/key_management/
pin_lock_system.rs

1//! Pin-based unlock in Bitwarden works using a `PasswordProtectedKeyEnvelope`, which is sealed with
2//! the PIN and contains the user-key. When unlocking with PIN, the envelope is unsealed with the
3//! PIN and the key is loaded into the key-store.
4//!
5//! There are two modes of PIN-based unlock: Before-first-unlock (BFU) and after-first-unlock (AFU).
6//! In BFU mode, the PIN envelope is persisted to disk. In AFU mode, the PIN envelope is only stored
7//! in memory. The memory copy is always loaded into memory when transitioning from BFU to AFU mode
8//! with an unlock.
9
10use bitwarden_crypto::{
11    Decryptable, EncString, KeyId, KeyStore, PrimitiveEncryptable, SymmetricKeyAlgorithm,
12    safe::{PasswordProtectedKeyEnvelope, PasswordProtectedKeyEnvelopeNamespace},
13};
14use serde::{Deserialize, Serialize};
15use tracing::warn;
16
17use crate::{
18    Client,
19    key_management::{KeySlotIds, SymmetricKeySlotId},
20};
21
22/// Pin unlock can be configured to use one of two modes. Before-first-unlock and
23/// after-first-unlock. In AFU mode, the PIN is available only after unlocking once with the master
24/// password or another unlock method. In BFU mode, PIN unlock is available right after app start.
25/// For this, the PIN-encrypted vault key is stored on disk.
26#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
27#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
28#[bitwarden_ffi::wasm_record]
29pub enum PinLockType {
30    /// Pin unlock is available after app start
31    BeforeFirstUnlock,
32    /// Pin unlock is available after unlocking with another method at least once during the app
33    /// session
34    AfterFirstUnlock,
35}
36
37#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
38#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
39#[bitwarden_ffi::wasm_record]
40/// Current availability state for PIN-based unlock.
41pub enum PinUnlockStatus {
42    /// A PIN is configured and the PIN envelope is available for decryption, so PIN-based unlock
43    /// can be attempted.
44    Available,
45    /// A PIN is configured, but the vault must be unlocked using another method first.
46    NeedsUnlock,
47    /// No PIN is configured.
48    NotSet,
49}
50
51pub(crate) enum UnlockError {
52    NoPinSet,
53    PinWrong,
54    InternalError,
55}
56
57#[derive(Debug, PartialEq, Eq)]
58pub(crate) enum MigrationFailed {
59    /// Vault is locked
60    Locked,
61    /// The encrypted PIN is under a key other than the user key, which cannot be recovered.
62    /// V2 -> V2 key rotation is not currently supported here.
63    UnrecoverablePinKey,
64    /// The encrypted PIN uses an unknown encryption algorithm.
65    UnsupportedPinEncryption,
66    /// V1 -> V2 migration is required but no V2 upgrade token is stored.
67    MissingV2UpgradeToken,
68    /// A PIN envelope is stored but no encrypted PIN to re-enroll it with.
69    MissingEncryptedPin,
70    /// Re-enrollment could not decrypt the encrypted PIN.
71    PinDecryption,
72    /// Re-sealing the envelope under the new user key failed.
73    Reenrollment,
74}
75
76/// What [`PinLockSystem::migrate_pin_envelope_if_needed`] should do with the PIN enrollment,
77/// decided from the encrypted PIN alone.
78#[derive(Debug, PartialEq, Eq)]
79enum PinMigrationAction {
80    /// The encrypted PIN is under the current user key. Nothing to do.
81    UpToDate,
82    /// The encrypted PIN is under the previous V1 user key. Re-enroll under the current V2 user
83    /// key, recovering the V1 key from the upgrade token.
84    MigrateV1ToV2,
85    /// Terminal failure; no migration is possible.
86    Failed(MigrationFailed),
87}
88
89/// Decides what to do with the PIN enrollment, from the algorithms of the encrypted PIN and the
90/// user key.
91///
92/// - A V1 (AES-CBC-HMAC) PIN under a V2 user key is a V1 -> V2 upgrade.
93/// - Otherwise the PIN must be under the user key itself. A key id, when the PIN carries one, must
94///   match; V1 PINs may carry none.
95fn classify_encrypted_pin(
96    pin_algorithm: Option<SymmetricKeyAlgorithm>,
97    pin_key_id: Option<&KeyId>,
98    user_key_algorithm: SymmetricKeyAlgorithm,
99    user_key_id: &KeyId,
100) -> PinMigrationAction {
101    let Some(pin_algorithm) = pin_algorithm else {
102        return PinMigrationAction::Failed(MigrationFailed::UnsupportedPinEncryption);
103    };
104
105    let pin_is_v1 = pin_algorithm == SymmetricKeyAlgorithm::Aes256CbcHmac;
106    let user_key_is_v1 = user_key_algorithm == SymmetricKeyAlgorithm::Aes256CbcHmac;
107    if pin_is_v1 && !user_key_is_v1 {
108        return PinMigrationAction::MigrateV1ToV2;
109    }
110
111    match pin_key_id {
112        Some(pin_key_id) if pin_key_id == user_key_id => PinMigrationAction::UpToDate,
113        None if pin_is_v1 => PinMigrationAction::UpToDate,
114        _ => PinMigrationAction::Failed(MigrationFailed::UnrecoverablePinKey),
115    }
116}
117
118/// Number of characters in `pin`, stored unencrypted so a lock screen can read it while locked,
119/// e.g. to try the PIN as soon as that many characters are typed.
120fn pin_length(pin: &str) -> u32 {
121    pin.chars().count() as u32
122}
123
124/// Provides PIN-based unlock functionality. This includes enrolling into PIN-based unlock,
125/// unlocking using the PIN and handling necessary operations (PIN envelope refreshing when
126/// transitioning to after-first-unlock mode).
127pub struct PinLockSystem<'a> {
128    client: &'a Client,
129}
130
131impl PinLockSystem<'_> {
132    fn key_store(&self) -> &KeyStore<KeySlotIds> {
133        self.client.internal.get_key_store()
134    }
135
136    /// Creates a PIN lock system view for a client instance.
137    pub fn with_client(client: &Client) -> PinLockSystem<'_> {
138        PinLockSystem { client }
139    }
140
141    /// Retrieves the currently active PIN envelope.
142    ///
143    /// If both envelopes are present, the ephemeral envelope is preferred.
144    async fn get_active_pin_envelope(&self) -> Option<PasswordProtectedKeyEnvelope> {
145        let mut pin_protected_key_envelope = self
146            .client
147            .km_state_bridge()
148            .get_ephemeral_pin_envelope()
149            .await;
150        if pin_protected_key_envelope.is_none() {
151            pin_protected_key_envelope = self
152                .client
153                .km_state_bridge()
154                .get_persistent_pin_envelope()
155                .await;
156        }
157        pin_protected_key_envelope
158    }
159
160    /// Attempts to unlock the user key using `pin`.
161    ///
162    /// Returns [`UnlockError::NoPinSet`] if no PIN is configured,
163    /// [`UnlockError::PinWrong`] if `pin` is incorrect, and
164    /// [`UnlockError::InternalError`] for other failures.
165    pub(crate) async fn unlock(&self, pin: &str) -> Result<(), UnlockError> {
166        let pin_envelope = Self::get_active_pin_envelope(self)
167            .await
168            .ok_or(UnlockError::NoPinSet)?;
169
170        // Unseal to key ctx
171        let mut ctx = self.key_store().context_mut();
172        let key_slot = pin_envelope
173            .unseal(
174                pin,
175                PasswordProtectedKeyEnvelopeNamespace::PinUnlock,
176                &mut ctx,
177            )
178            .map_err(|e| match e {
179                bitwarden_crypto::safe::PasswordProtectedKeyEnvelopeError::WrongPassword => {
180                    UnlockError::PinWrong
181                }
182                _ => UnlockError::InternalError,
183            })?;
184
185        // The key is currently in the local ctx and would be dropped when ctx goes out of scope.
186        // Persist it to the keystore
187        ctx.persist_symmetric_key(key_slot, SymmetricKeySlotId::User)
188            .map_err(|_| UnlockError::InternalError)
189    }
190
191    /// Brings the PIN enrollment in line with the current user key.
192    ///
193    /// After a V2 upgrade, the encrypted PIN is still encrypted with the V1 user key. It is
194    /// decrypted with the V1 key recovered from the upgrade token, and re-enrolled under the
195    /// current user key with the same lock type. Both lock types store the encrypted PIN, so it
196    /// alone decides what to do. See [`classify_encrypted_pin`].
197    async fn migrate_pin_envelope_if_needed(&self) -> Result<(), MigrationFailed> {
198        // No PIN configured
199        let Some(lock_type) = self.get_pin_lock_type().await else {
200            return Ok(());
201        };
202        let encrypted_pin = self
203            .client
204            .km_state_bridge()
205            .get_encrypted_pin()
206            .await
207            .ok_or(MigrationFailed::MissingEncryptedPin)?;
208
209        // Scoped so the context is dropped before the awaits below.
210        let (user_key_id, user_key_algorithm) = {
211            let ctx = self.key_store().context();
212            (
213                ctx.get_symmetric_key_id(SymmetricKeySlotId::User)
214                    .ok_or(MigrationFailed::Locked)?,
215                ctx.get_symmetric_key_algorithm(SymmetricKeySlotId::User)
216                    .map_err(|_| MigrationFailed::Locked)?,
217            )
218        };
219
220        match classify_encrypted_pin(
221            encrypted_pin.algorithm(),
222            encrypted_pin.key_id().as_ref(),
223            user_key_algorithm,
224            &user_key_id,
225        ) {
226            PinMigrationAction::UpToDate => return Ok(()),
227            PinMigrationAction::Failed(error) => return Err(error),
228            PinMigrationAction::MigrateV1ToV2 => {}
229        }
230
231        let token = self
232            .client
233            .km_state_bridge()
234            .get_v2_upgrade_token()
235            .await
236            .ok_or(MigrationFailed::MissingV2UpgradeToken)?;
237
238        // The unwrapped V1 key only lives in this context, so it is scoped with the decryption.
239        let pin: String = {
240            let mut ctx = self.key_store().context_mut();
241            let v1_slot = token
242                .unwrap_v1(SymmetricKeySlotId::User, &mut ctx)
243                .map_err(|_| MigrationFailed::PinDecryption)?;
244            encrypted_pin
245                .decrypt(&mut ctx, v1_slot)
246                .map_err(|_| MigrationFailed::PinDecryption)?
247        };
248
249        // Do a fresh enrollment with the current user-key
250        self.set_pin(pin, lock_type)
251            .await
252            .map_err(|_| MigrationFailed::Reenrollment)
253    }
254
255    /// Refreshes in-memory PIN unlock material after a successful non-PIN unlock.
256    ///
257    /// This recreates the ephemeral PIN envelope from the encrypted PIN, when available.
258    pub(crate) async fn on_unlock(&self) {
259        // Remove once all clients, ios, android implement the state bridge
260        if !self.client.km_state_bridge().is_bridge_registered() {
261            return;
262        }
263
264        if let Err(e) = self.migrate_pin_envelope_if_needed().await {
265            warn!("PIN migration failed: {e:?}, unenrolling PIN");
266            self.unset_pin().await;
267            return;
268        }
269
270        let encrypted_pin = self.client.km_state_bridge().get_encrypted_pin().await;
271
272        // If PIN unlock is not enabled, do nothing
273        let Some(encrypted_pin) = encrypted_pin else {
274            return;
275        };
276
277        self.backfill_pin_length(&encrypted_pin).await;
278
279        // Re-sealing runs a full KDF. Clients that re-initialize crypto for an already unlocked
280        // session (e.g. a browser popup) would pay it on every initialization, so keep an existing
281        // envelope that already holds the current user key.
282        if let Some(existing_envelope) = self
283            .client
284            .km_state_bridge()
285            .get_ephemeral_pin_envelope()
286            .await
287        {
288            let user_key_id = self
289                .key_store()
290                .context()
291                .get_symmetric_key_id(SymmetricKeySlotId::User);
292            if user_key_id.is_some()
293                && existing_envelope.contained_key_id().ok().flatten() == user_key_id
294            {
295                return;
296            }
297        }
298
299        // Make the fresh PIN envelope
300        let Ok(pin_envelope) = (|| -> Result<PasswordProtectedKeyEnvelope, ()> {
301            let mut ctx = self.key_store().context_mut();
302            let pin: String = encrypted_pin
303                .decrypt(&mut ctx, SymmetricKeySlotId::User)
304                .map_err(|_| ())?;
305            PasswordProtectedKeyEnvelope::seal(
306                SymmetricKeySlotId::User,
307                pin.as_str(),
308                PasswordProtectedKeyEnvelopeNamespace::PinUnlock,
309                &ctx,
310            )
311            .map_err(|_| ())
312        })() else {
313            warn!("Failed to create PIN envelope");
314            return;
315        };
316
317        // Store it to memory
318        self.client
319            .km_state_bridge()
320            .set_ephemeral_pin_envelope(&pin_envelope)
321            .await;
322    }
323
324    /// Stores the length of a PIN set before lengths were stored.
325    ///
326    /// Decrypting the encrypted PIN needs the user key, so this runs on unlock.
327    async fn backfill_pin_length(&self, encrypted_pin: &EncString) {
328        if self.get_pin_length().await.is_some() {
329            return;
330        }
331
332        // Statement scoped, so the key context is dropped before the await below.
333        let pin: Result<String, _> = encrypted_pin.decrypt(
334            &mut self.key_store().context_mut(),
335            SymmetricKeySlotId::User,
336        );
337        let Ok(pin) = pin else {
338            warn!("Failed to decrypt PIN to store its length");
339            return;
340        };
341
342        self.client
343            .km_state_bridge()
344            .set_pin_length(&pin_length(&pin))
345            .await;
346    }
347
348    /// Sets the PIN and stores the generated envelope according to the lock type.
349    pub async fn set_pin(&self, pin: String, lock_type: PinLockType) -> Result<(), ()> {
350        // Clear the existing configuration
351        self.client
352            .km_state_bridge()
353            .clear_persistent_pin_envelope()
354            .await;
355        self.client
356            .km_state_bridge()
357            .clear_ephemeral_pin_envelope()
358            .await;
359        self.client.km_state_bridge().clear_encrypted_pin().await;
360        self.client.km_state_bridge().clear_pin_length().await;
361
362        let pin_envelope: PasswordProtectedKeyEnvelope = PasswordProtectedKeyEnvelope::seal(
363            SymmetricKeySlotId::User,
364            pin.as_str(),
365            PasswordProtectedKeyEnvelopeNamespace::PinUnlock,
366            &self.key_store().context_mut(),
367        )
368        .map_err(|_| ())?;
369        let encrypted_pin = pin
370            .encrypt(
371                &mut self.key_store().context_mut(),
372                SymmetricKeySlotId::User,
373            )
374            .map_err(|_| ())?;
375
376        self.client
377            .km_state_bridge()
378            .set_encrypted_pin(&encrypted_pin)
379            .await;
380        self.client
381            .km_state_bridge()
382            .set_pin_length(&pin_length(&pin))
383            .await;
384        self.client
385            .km_state_bridge()
386            .set_ephemeral_pin_envelope(&pin_envelope)
387            .await;
388
389        if lock_type == PinLockType::BeforeFirstUnlock {
390            self.client
391                .km_state_bridge()
392                .set_persistent_pin_envelope(&pin_envelope)
393                .await;
394        }
395
396        Ok(())
397    }
398
399    /// Clears both persistent and ephemeral PIN envelopes.
400    pub async fn unset_pin(&self) {
401        self.client
402            .km_state_bridge()
403            .clear_persistent_pin_envelope()
404            .await;
405        self.client
406            .km_state_bridge()
407            .clear_ephemeral_pin_envelope()
408            .await;
409        self.client.km_state_bridge().clear_encrypted_pin().await;
410        self.client.km_state_bridge().clear_pin_length().await;
411    }
412
413    /// Returns the number of characters in the PIN, readable while locked. `None` when no PIN is
414    /// set, or for a PIN set before its length was stored that hasn't unlocked since.
415    pub async fn get_pin_length(&self) -> Option<u32> {
416        self.client.km_state_bridge().get_pin_length().await
417    }
418
419    /// Returns the lock type for the currently configured PIN.
420    pub async fn get_pin_lock_type(&self) -> Option<PinLockType> {
421        if self
422            .client
423            .km_state_bridge()
424            .get_persistent_pin_envelope()
425            .await
426            .is_some()
427        {
428            return Some(PinLockType::BeforeFirstUnlock);
429        }
430
431        // Encrypted pin is set for either lock type, persistent pin only for BFU. The ephemeral
432        // envelope may not be set after restarting a client, until the client enters AFU
433        // mode.
434        if self
435            .client
436            .km_state_bridge()
437            .get_encrypted_pin()
438            .await
439            .is_some()
440        {
441            return Some(PinLockType::AfterFirstUnlock);
442        }
443
444        None
445    }
446
447    /// Returns the current PIN unlock status.
448    ///
449    /// If a lock type is configured but no ephemeral envelope is currently present,
450    /// the status is [`PinUnlockStatus::NeedsUnlock`].
451    pub async fn get_pin_status(&self) -> PinUnlockStatus {
452        match Self::get_pin_lock_type(self).await {
453            Some(PinLockType::BeforeFirstUnlock) => {
454                if self.get_active_pin_envelope().await.is_some() {
455                    PinUnlockStatus::Available
456                } else {
457                    PinUnlockStatus::NeedsUnlock
458                }
459            }
460            Some(PinLockType::AfterFirstUnlock) => {
461                if self
462                    .client
463                    .km_state_bridge()
464                    .get_ephemeral_pin_envelope()
465                    .await
466                    .is_some()
467                {
468                    PinUnlockStatus::Available
469                } else {
470                    // This should not happen as AFU should always have the ephemeral envelope, but
471                    // we handle it just in case.
472                    PinUnlockStatus::NeedsUnlock
473                }
474            }
475            None => PinUnlockStatus::NotSet,
476        }
477    }
478
479    /// Returns the configured PIN, if an encrypted PIN is available and decryptable.
480    pub async fn get_pin(&self) -> Option<String> {
481        let encrypted_pin = self.client.km_state_bridge().get_encrypted_pin().await?;
482        encrypted_pin
483            .decrypt(
484                &mut self.client.internal.get_key_store().context_mut(),
485                SymmetricKeySlotId::User,
486            )
487            .ok()
488    }
489
490    /// Validates that the provided PIN can decrypt the stored PIN envelope.
491    pub async fn validate_pin(&self, pin: String) -> bool {
492        let pin_envelope = self.get_active_pin_envelope().await;
493        let Some(pin_envelope) = pin_envelope else {
494            return false;
495        };
496
497        pin_envelope
498            .unseal(
499                pin.as_str(),
500                PasswordProtectedKeyEnvelopeNamespace::PinUnlock,
501                &mut self.key_store().context_mut(),
502            )
503            .is_ok()
504    }
505}
506
507#[cfg(test)]
508mod tests {
509    use bitwarden_crypto::{EncString, KeyId, SymmetricKeyAlgorithm};
510
511    use super::*;
512    use crate::key_management::{V2UpgradeToken, state_bridge::test_support::InMemoryStateBridge};
513
514    fn decrypt_encrypted_pin(client: &Client, encrypted_pin: &EncString) -> String {
515        encrypted_pin
516            .decrypt(
517                &mut client.internal.get_key_store().context_mut(),
518                SymmetricKeySlotId::User,
519            )
520            .expect("encrypted pin should decrypt successfully")
521    }
522
523    /// The PIN [`TESTVECTOR_LEGACY_ENVELOPE`] was sealed with.
524    const TESTVECTOR_LEGACY_ENVELOPE_PIN: &str = "1234";
525    /// A `PinUnlock` envelope sealed under an AES-CBC-HMAC (V1) key by a client predating derived
526    /// key ids, so it carries no contained key id.
527    ///
528    /// The migration never unseals this envelope — it reads the contained key id and then
529    /// re-enrolls from the key store — so the key sealed inside is arbitrary and deliberately
530    /// unrelated to the user key the tests install.
531    ///
532    /// The current seal path always writes a contained key id, so re-recording this requires
533    /// temporarily changing `set_contained_key_id(&mut header, key_to_seal.key_id())` in
534    /// `bitwarden-crypto/src/safe/password_protected_key_envelope.rs` to pass `None`, sealing a
535    /// `PinUnlock` envelope for an `Aes256CbcHmac` key with [`TESTVECTOR_LEGACY_ENVELOPE_PIN`],
536    /// printing `Vec::from(&envelope)`, and then reverting that change.
537    const TESTVECTOR_LEGACY_ENVELOPE: &[u8] = &[
538        132, 88, 52, 164, 1, 3, 3, 120, 34, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47,
539        120, 46, 98, 105, 116, 119, 97, 114, 100, 101, 110, 46, 108, 101, 103, 97, 99, 121, 45,
540        107, 101, 121, 58, 0, 1, 56, 129, 1, 58, 0, 1, 56, 128, 1, 161, 5, 76, 148, 49, 223, 205,
541        195, 252, 91, 216, 65, 200, 121, 104, 88, 80, 89, 120, 16, 161, 14, 97, 191, 97, 138, 42,
542        102, 234, 49, 186, 2, 255, 31, 4, 232, 178, 100, 53, 37, 181, 172, 129, 193, 51, 109, 8,
543        160, 29, 254, 181, 242, 102, 73, 229, 89, 150, 227, 252, 120, 156, 71, 202, 200, 241, 74,
544        241, 206, 16, 155, 83, 49, 242, 13, 209, 10, 217, 251, 164, 244, 69, 41, 52, 9, 192, 140,
545        248, 251, 244, 84, 154, 15, 100, 222, 102, 117, 185, 129, 131, 71, 161, 1, 58, 0, 1, 21,
546        87, 165, 1, 58, 0, 1, 21, 87, 58, 0, 1, 21, 89, 3, 58, 0, 1, 21, 90, 26, 0, 1, 0, 0, 58, 0,
547        1, 21, 91, 4, 58, 0, 1, 21, 88, 80, 64, 184, 87, 20, 40, 186, 214, 56, 87, 53, 118, 100, 5,
548        21, 13, 3, 246,
549    ];
550
551    /// Parses [`TESTVECTOR_LEGACY_ENVELOPE`], asserting it really has no contained key id.
552    fn legacy_envelope() -> PasswordProtectedKeyEnvelope {
553        let envelope = PasswordProtectedKeyEnvelope::try_from(&TESTVECTOR_LEGACY_ENVELOPE.to_vec())
554            .expect("legacy envelope test vector parses");
555        assert_eq!(
556            envelope.contained_key_id().expect("readable"),
557            None,
558            "legacy envelope test vector must have no contained key id",
559        );
560        envelope
561    }
562
563    /// Returns the `KeyId` of the symmetric key currently in `SymmetricKeySlotId::User`.
564    fn user_key_id(client: &Client) -> KeyId {
565        client
566            .internal
567            .get_key_store()
568            .context()
569            .get_symmetric_key_id(SymmetricKeySlotId::User)
570            .expect("user key present")
571    }
572
573    /// Asserts the envelope wraps `expected_key_id` and unseals successfully under `pin`.
574    fn assert_envelope_wraps_user_key(
575        client: &Client,
576        envelope: &PasswordProtectedKeyEnvelope,
577        pin: &str,
578        expected_key_id: &KeyId,
579    ) {
580        assert_eq!(
581            envelope
582                .contained_key_id()
583                .expect("contained key id readable"),
584            Some(expected_key_id.clone()),
585            "envelope wraps a key other than the current user key",
586        );
587        let _ = envelope
588            .unseal(
589                pin,
590                PasswordProtectedKeyEnvelopeNamespace::PinUnlock,
591                &mut client.internal.get_key_store().context_mut(),
592            )
593            .expect("envelope unseals with the configured pin");
594    }
595
596    fn client_with_user_key() -> Client {
597        let client = Client::new(None);
598        client
599            .km_state_bridge()
600            .register_bridge(Box::new(InMemoryStateBridge::default()));
601        {
602            let key_store = client.internal.get_key_store();
603            let mut ctx = key_store.context_mut();
604            let user_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XAes256Gcm);
605            ctx.persist_symmetric_key(user_key, SymmetricKeySlotId::User)
606                .expect("persisting user key should succeed");
607        }
608        client
609    }
610
611    fn seal_envelope(client: &Client, pin: &str) -> PasswordProtectedKeyEnvelope {
612        PasswordProtectedKeyEnvelope::seal(
613            SymmetricKeySlotId::User,
614            pin,
615            PasswordProtectedKeyEnvelopeNamespace::PinUnlock,
616            &client.internal.get_key_store().context_mut(),
617        )
618        .expect("seal succeeds")
619    }
620
621    #[tokio::test]
622    async fn set_pin_bfu_persists_both_envelopes() {
623        let client = client_with_user_key();
624        let user_key_id = user_key_id(&client);
625        let system = PinLockSystem::with_client(&client);
626
627        system
628            .set_pin("1234".into(), PinLockType::BeforeFirstUnlock)
629            .await
630            .expect("set_pin succeeds");
631
632        let bridge = client.km_state_bridge();
633        let persistent = bridge
634            .get_persistent_pin_envelope()
635            .await
636            .expect("persistent envelope present");
637        let ephemeral = bridge
638            .get_ephemeral_pin_envelope()
639            .await
640            .expect("ephemeral envelope present");
641        let encrypted_pin = bridge
642            .get_encrypted_pin()
643            .await
644            .expect("encrypted pin present");
645
646        assert_envelope_wraps_user_key(&client, &persistent, "1234", &user_key_id);
647        assert_envelope_wraps_user_key(&client, &ephemeral, "1234", &user_key_id);
648        assert_eq!(decrypt_encrypted_pin(&client, &encrypted_pin), "1234");
649
650        assert_eq!(
651            system.get_pin_lock_type().await,
652            Some(PinLockType::BeforeFirstUnlock)
653        );
654        assert_eq!(system.get_pin_status().await, PinUnlockStatus::Available);
655    }
656
657    #[tokio::test]
658    async fn set_pin_afu_persists_only_ephemeral() {
659        let client = client_with_user_key();
660        let user_key_id = user_key_id(&client);
661        let system = PinLockSystem::with_client(&client);
662
663        system
664            .set_pin("1234".into(), PinLockType::AfterFirstUnlock)
665            .await
666            .expect("set_pin succeeds");
667
668        let bridge = client.km_state_bridge();
669        assert!(bridge.get_persistent_pin_envelope().await.is_none());
670        let ephemeral = bridge
671            .get_ephemeral_pin_envelope()
672            .await
673            .expect("ephemeral envelope present");
674        let encrypted_pin = bridge
675            .get_encrypted_pin()
676            .await
677            .expect("encrypted pin present");
678
679        assert_envelope_wraps_user_key(&client, &ephemeral, "1234", &user_key_id);
680        assert_eq!(decrypt_encrypted_pin(&client, &encrypted_pin), "1234");
681
682        assert_eq!(
683            system.get_pin_lock_type().await,
684            Some(PinLockType::AfterFirstUnlock)
685        );
686        assert_eq!(system.get_pin_status().await, PinUnlockStatus::Available);
687    }
688
689    #[tokio::test]
690    async fn set_pin_overwrites_existing_state() {
691        let client = client_with_user_key();
692        let system = PinLockSystem::with_client(&client);
693
694        system
695            .set_pin("first".into(), PinLockType::BeforeFirstUnlock)
696            .await
697            .expect("first set_pin");
698        system
699            .set_pin("second".into(), PinLockType::AfterFirstUnlock)
700            .await
701            .expect("second set_pin");
702
703        let bridge = client.km_state_bridge();
704        assert!(
705            bridge.get_persistent_pin_envelope().await.is_none(),
706            "switching to AFU must clear the persistent envelope"
707        );
708        assert_eq!(
709            system.get_pin_lock_type().await,
710            Some(PinLockType::AfterFirstUnlock)
711        );
712        assert!(system.validate_pin("second".into()).await);
713        assert!(!system.validate_pin("first".into()).await);
714    }
715
716    #[tokio::test]
717    async fn unset_pin_clears_all_state() {
718        let client = client_with_user_key();
719        let system = PinLockSystem::with_client(&client);
720
721        system
722            .set_pin("1234".into(), PinLockType::BeforeFirstUnlock)
723            .await
724            .expect("set_pin succeeds");
725        system.unset_pin().await;
726
727        let bridge = client.km_state_bridge();
728        assert!(bridge.get_persistent_pin_envelope().await.is_none());
729        assert!(bridge.get_ephemeral_pin_envelope().await.is_none());
730        assert!(bridge.get_encrypted_pin().await.is_none());
731        assert_eq!(system.get_pin_lock_type().await, None);
732        assert_eq!(system.get_pin_status().await, PinUnlockStatus::NotSet);
733    }
734
735    #[tokio::test]
736    async fn unlock_with_correct_pin_persists_user_key() {
737        let client = client_with_user_key();
738        let system = PinLockSystem::with_client(&client);
739
740        let pre_unlock_user_key_id = user_key_id(&client);
741        // Snapshot ciphertext under the original user key, then drop the key from memory.
742        system
743            .set_pin("1234".into(), PinLockType::BeforeFirstUnlock)
744            .await
745            .expect("set_pin succeeds");
746        client.internal.get_key_store().clear();
747
748        assert!(system.unlock("1234").await.is_ok());
749        let post_unlock_user_key_id = user_key_id(&client);
750        assert_eq!(post_unlock_user_key_id, pre_unlock_user_key_id);
751    }
752
753    #[tokio::test]
754    async fn unlock_with_wrong_pin_returns_pin_wrong() {
755        let client = client_with_user_key();
756        let system = PinLockSystem::with_client(&client);
757        system
758            .set_pin("1234".into(), PinLockType::BeforeFirstUnlock)
759            .await
760            .expect("set_pin succeeds");
761
762        assert!(matches!(
763            system.unlock("wrong").await,
764            Err(UnlockError::PinWrong)
765        ));
766    }
767
768    #[tokio::test]
769    async fn unlock_with_no_pin_set_returns_no_pin_set() {
770        let client = client_with_user_key();
771        let system = PinLockSystem::with_client(&client);
772
773        assert!(matches!(
774            system.unlock("anything").await,
775            Err(UnlockError::NoPinSet)
776        ));
777    }
778
779    #[tokio::test]
780    async fn unlock_prefers_ephemeral_envelope_over_persistent() {
781        let client = client_with_user_key();
782        let system = PinLockSystem::with_client(&client);
783        system
784            .set_pin("persistent".into(), PinLockType::BeforeFirstUnlock)
785            .await
786            .expect("set_pin succeeds");
787
788        // Replace the ephemeral envelope with one sealed under a different PIN
789        // (same user key still in the slot).
790        let ephemeral = seal_envelope(&client, "ephemeral");
791        client
792            .km_state_bridge()
793            .set_ephemeral_pin_envelope(&ephemeral)
794            .await;
795
796        assert!(system.unlock("ephemeral").await.is_ok());
797        assert!(matches!(
798            system.unlock("persistent").await,
799            Err(UnlockError::PinWrong)
800        ));
801    }
802
803    #[tokio::test]
804    async fn get_pin_status_available_bfu() {
805        let client = client_with_user_key();
806        let system = PinLockSystem::with_client(&client);
807        system
808            .set_pin("1234".into(), PinLockType::BeforeFirstUnlock)
809            .await
810            .expect("set_pin succeeds");
811
812        // Simulate app restart: ephemeral memory state is gone, only persisted disk state remains.
813        client
814            .km_state_bridge()
815            .clear_ephemeral_pin_envelope()
816            .await;
817
818        assert_eq!(system.get_pin_status().await, PinUnlockStatus::Available);
819        assert_eq!(
820            system.get_pin_lock_type().await,
821            Some(PinLockType::BeforeFirstUnlock)
822        );
823    }
824
825    #[tokio::test]
826    async fn on_unlock_rebuilds_ephemeral_envelope() {
827        let client = client_with_user_key();
828        let user_key_id = user_key_id(&client);
829        let system = PinLockSystem::with_client(&client);
830        system
831            .set_pin("1234".into(), PinLockType::AfterFirstUnlock)
832            .await
833            .expect("set_pin succeeds");
834        client
835            .km_state_bridge()
836            .clear_ephemeral_pin_envelope()
837            .await;
838        assert_eq!(system.get_pin_status().await, PinUnlockStatus::NeedsUnlock);
839
840        system.on_unlock().await;
841
842        let rebuilt = client
843            .km_state_bridge()
844            .get_ephemeral_pin_envelope()
845            .await
846            .expect("on_unlock should restore the ephemeral envelope");
847        assert_envelope_wraps_user_key(&client, &rebuilt, "1234", &user_key_id);
848        assert_eq!(system.get_pin_status().await, PinUnlockStatus::Available);
849        assert!(system.unlock("1234").await.is_ok());
850    }
851
852    #[tokio::test]
853    async fn on_unlock_keeps_ephemeral_envelope_for_current_user_key() {
854        let client = client_with_user_key();
855        let system = PinLockSystem::with_client(&client);
856        system
857            .set_pin("1234".into(), PinLockType::AfterFirstUnlock)
858            .await
859            .expect("set_pin succeeds");
860        let before = client
861            .km_state_bridge()
862            .get_ephemeral_pin_envelope()
863            .await
864            .expect("set_pin stores an ephemeral envelope");
865
866        system.on_unlock().await;
867
868        let after = client
869            .km_state_bridge()
870            .get_ephemeral_pin_envelope()
871            .await
872            .expect("the ephemeral envelope is kept");
873        assert_eq!(Vec::<u8>::from(&before), Vec::<u8>::from(&after));
874        assert!(system.unlock("1234").await.is_ok());
875    }
876
877    #[tokio::test]
878    async fn on_unlock_rebuilds_ephemeral_envelope_for_other_user_key() {
879        let client = client_with_user_key();
880        let user_key_id = user_key_id(&client);
881        let system = PinLockSystem::with_client(&client);
882        system
883            .set_pin("1234".into(), PinLockType::AfterFirstUnlock)
884            .await
885            .expect("set_pin succeeds");
886
887        let other_client = client_with_user_key();
888        PinLockSystem::with_client(&other_client)
889            .set_pin("1234".into(), PinLockType::AfterFirstUnlock)
890            .await
891            .expect("set_pin succeeds");
892        let foreign_envelope = other_client
893            .km_state_bridge()
894            .get_ephemeral_pin_envelope()
895            .await
896            .expect("set_pin stores an ephemeral envelope");
897        client
898            .km_state_bridge()
899            .set_ephemeral_pin_envelope(&foreign_envelope)
900            .await;
901
902        system.on_unlock().await;
903
904        let rebuilt = client
905            .km_state_bridge()
906            .get_ephemeral_pin_envelope()
907            .await
908            .expect("on_unlock should restore the ephemeral envelope");
909        assert_envelope_wraps_user_key(&client, &rebuilt, "1234", &user_key_id);
910        assert!(system.unlock("1234").await.is_ok());
911    }
912
913    #[tokio::test]
914    async fn on_unlock_is_noop_when_no_encrypted_pin() {
915        let client = client_with_user_key();
916        let system = PinLockSystem::with_client(&client);
917
918        system.on_unlock().await;
919
920        assert_eq!(system.get_pin_status().await, PinUnlockStatus::NotSet);
921    }
922
923    #[tokio::test]
924    async fn on_unlock_is_noop_when_bridge_not_registered() {
925        let client = Client::new(None);
926        let system = PinLockSystem::with_client(&client);
927
928        // Must not panic even though no StateBridgeImpl is registered.
929        system.on_unlock().await;
930    }
931
932    #[tokio::test]
933    async fn get_pin_returns_set_pin() {
934        let client = client_with_user_key();
935        let system = PinLockSystem::with_client(&client);
936
937        assert_eq!(system.get_pin().await, None);
938
939        system
940            .set_pin("1234".into(), PinLockType::AfterFirstUnlock)
941            .await
942            .expect("set_pin succeeds");
943        assert_eq!(system.get_pin().await, Some("1234".to_owned()));
944
945        system.unset_pin().await;
946        assert_eq!(system.get_pin().await, None);
947    }
948
949    #[tokio::test]
950    async fn validate_pin_matches_only_correct_pin() {
951        let client = client_with_user_key();
952        let system = PinLockSystem::with_client(&client);
953
954        assert!(!system.validate_pin("anything".into()).await);
955
956        system
957            .set_pin("1234".into(), PinLockType::AfterFirstUnlock)
958            .await
959            .expect("set_pin succeeds");
960        assert!(system.validate_pin("1234".into()).await);
961        assert!(!system.validate_pin("wrong".into()).await);
962    }
963
964    /// Snapshot of the persisted state a client would have after a V1→V2 user-key upgrade,
965    /// before the PIN envelope has been re-sealed.
966    struct V1State {
967        envelope: PasswordProtectedKeyEnvelope,
968        encrypted_pin: EncString,
969        token: V2UpgradeToken,
970    }
971
972    /// Builds a client with a V2 user key in the `User` slot plus the disk-shaped artifacts
973    /// of a prior V1 PIN enrollment: a V1 key sealed in a PIN envelope, an encrypted PIN under that
974    /// V1 key, and a V2 upgrade token tying the two.
975    fn fresh_v1_state_with_v2_user_key(pin: &str) -> (Client, V1State) {
976        let client = Client::new(None);
977        client
978            .km_state_bridge()
979            .register_bridge(Box::new(InMemoryStateBridge::default()));
980
981        let state = {
982            let key_store = client.internal.get_key_store();
983            let mut ctx = key_store.context_mut();
984
985            let v1_local = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
986            let v2_local = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XAes256Gcm);
987
988            let envelope = PasswordProtectedKeyEnvelope::seal(
989                v1_local,
990                pin,
991                PasswordProtectedKeyEnvelopeNamespace::PinUnlock,
992                &ctx,
993            )
994            .expect("v1 envelope seals");
995            let encrypted_pin = pin
996                .encrypt(&mut ctx, v1_local)
997                .expect("pin encrypts under v1 key");
998            let token =
999                V2UpgradeToken::create(v1_local, v2_local, &ctx).expect("upgrade token created");
1000
1001            ctx.persist_symmetric_key(v2_local, SymmetricKeySlotId::User)
1002                .expect("persisting v2 user key succeeds");
1003
1004            V1State {
1005                envelope,
1006                encrypted_pin,
1007                token,
1008            }
1009        };
1010
1011        (client, state)
1012    }
1013
1014    /// Like `client_with_user_key`, but installs a V1 (Aes256CbcHmac) user key, so
1015    /// `get_symmetric_key_id(User)` returns `None`.
1016    fn client_with_v1_user_key() -> Client {
1017        let client = Client::new(None);
1018        client
1019            .km_state_bridge()
1020            .register_bridge(Box::new(InMemoryStateBridge::default()));
1021        {
1022            let key_store = client.internal.get_key_store();
1023            let mut ctx = key_store.context_mut();
1024            let user_key = ctx.generate_symmetric_key();
1025            ctx.persist_symmetric_key(user_key, SymmetricKeySlotId::User)
1026                .expect("persisting v1 user key should succeed");
1027        }
1028        client
1029    }
1030
1031    fn assert_pin_envelopes_equal(
1032        envelope_1: &PasswordProtectedKeyEnvelope,
1033        envelope_2: &PasswordProtectedKeyEnvelope,
1034    ) {
1035        assert_eq!(
1036            serde_json::to_string(envelope_1).expect("envelope serializes"),
1037            serde_json::to_string(envelope_2).expect("envelope serializes"),
1038            "envelopes should be identical",
1039        );
1040    }
1041
1042    async fn assert_pin_fully_unenrolled(client: &Client) {
1043        let bridge = client.km_state_bridge();
1044        assert!(bridge.get_persistent_pin_envelope().await.is_none());
1045        assert!(bridge.get_ephemeral_pin_envelope().await.is_none());
1046        assert!(bridge.get_encrypted_pin().await.is_none());
1047        assert_eq!(
1048            PinLockSystem::with_client(client).get_pin_status().await,
1049            PinUnlockStatus::NotSet,
1050        );
1051    }
1052
1053    // ------------------------------------------------------------------------------------
1054    // PIN migration
1055    //
1056    // One scenario per outcome of `migrate_pin_envelope_if_needed`, in the order of
1057    // `classify_encrypted_pin`, then the failures, then `on_unlock` end to end.
1058    // ------------------------------------------------------------------------------------
1059
1060    /// Stores the V1 PIN enrollment from `state` the way `lock_type` persists it.
1061    async fn store_v1_pin(client: &Client, state: &V1State, lock_type: &PinLockType) {
1062        let bridge = client.km_state_bridge();
1063        bridge.set_encrypted_pin(&state.encrypted_pin).await;
1064        if *lock_type == PinLockType::BeforeFirstUnlock {
1065            bridge.set_persistent_pin_envelope(&state.envelope).await;
1066        }
1067    }
1068
1069    #[tokio::test]
1070    async fn migrate_without_pin_is_noop() {
1071        let client = client_with_user_key();
1072        let system = PinLockSystem::with_client(&client);
1073
1074        system
1075            .migrate_pin_envelope_if_needed()
1076            .await
1077            .expect("migration succeeds");
1078
1079        assert_pin_fully_unenrolled(&client).await;
1080    }
1081
1082    /// The encrypted PIN is under the current V2 user key.
1083    #[tokio::test]
1084    async fn migrate_up_to_date_v2_pin_is_noop() {
1085        let client = client_with_user_key();
1086        let system = PinLockSystem::with_client(&client);
1087        system
1088            .set_pin("1234".into(), PinLockType::BeforeFirstUnlock)
1089            .await
1090            .expect("set_pin succeeds");
1091
1092        let bridge = client.km_state_bridge();
1093        let persistent_before = bridge.get_persistent_pin_envelope().await.expect("present");
1094        let encrypted_pin_before = bridge.get_encrypted_pin().await.expect("present");
1095
1096        system
1097            .migrate_pin_envelope_if_needed()
1098            .await
1099            .expect("migration succeeds");
1100
1101        let persistent_after = bridge.get_persistent_pin_envelope().await.expect("present");
1102        let encrypted_pin_after = bridge.get_encrypted_pin().await.expect("present");
1103        assert_pin_envelopes_equal(&persistent_before, &persistent_after);
1104        assert_eq!(
1105            encrypted_pin_before.to_string(),
1106            encrypted_pin_after.to_string()
1107        );
1108    }
1109
1110    /// The encrypted PIN is under the current V1 user key. The envelope predates derived key ids,
1111    /// which must not matter: every existing V1 PIN user is in this state.
1112    #[tokio::test]
1113    async fn migrate_up_to_date_v1_pin_is_noop() {
1114        let client = client_with_v1_user_key();
1115        let encrypted_pin = TESTVECTOR_LEGACY_ENVELOPE_PIN
1116            .encrypt(
1117                &mut client.internal.get_key_store().context_mut(),
1118                SymmetricKeySlotId::User,
1119            )
1120            .expect("encrypt under v1 user key");
1121
1122        let bridge = client.km_state_bridge();
1123        bridge.set_persistent_pin_envelope(&legacy_envelope()).await;
1124        bridge.set_encrypted_pin(&encrypted_pin).await;
1125
1126        let system = PinLockSystem::with_client(&client);
1127        system
1128            .migrate_pin_envelope_if_needed()
1129            .await
1130            .expect("migration succeeds");
1131
1132        let persistent_after = bridge.get_persistent_pin_envelope().await.expect("present");
1133        let encrypted_pin_after = bridge.get_encrypted_pin().await.expect("present");
1134        assert_pin_envelopes_equal(&legacy_envelope(), &persistent_after);
1135        assert_eq!(encrypted_pin.to_string(), encrypted_pin_after.to_string());
1136    }
1137
1138    /// The encrypted PIN is under the V1 key the upgrade token unwraps. It is re-enrolled under
1139    /// the V2 user key, keeping its lock type.
1140    #[tokio::test]
1141    async fn migrate_v1_pin_with_v2_user_key_reenrolls() {
1142        for lock_type in [
1143            PinLockType::BeforeFirstUnlock,
1144            PinLockType::AfterFirstUnlock,
1145        ] {
1146            let pin = "1234";
1147            let (client, state) = fresh_v1_state_with_v2_user_key(pin);
1148            store_v1_pin(&client, &state, &lock_type).await;
1149            client
1150                .km_state_bridge()
1151                .set_v2_upgrade_token(&state.token)
1152                .await;
1153
1154            let system = PinLockSystem::with_client(&client);
1155            system
1156                .migrate_pin_envelope_if_needed()
1157                .await
1158                .expect("migration succeeds");
1159
1160            let bridge = client.km_state_bridge();
1161            let encrypted_pin = bridge.get_encrypted_pin().await.expect("present");
1162            let ephemeral = bridge.get_ephemeral_pin_envelope().await.expect("present");
1163
1164            assert_eq!(decrypt_encrypted_pin(&client, &encrypted_pin), pin);
1165            assert_envelope_wraps_user_key(&client, &ephemeral, pin, &user_key_id(&client));
1166            assert_eq!(system.get_pin_lock_type().await, Some(lock_type));
1167            assert!(system.unlock(pin).await.is_ok());
1168        }
1169    }
1170
1171    #[test]
1172    fn pin_length_counts_characters_not_bytes() {
1173        assert_eq!(pin_length("1234"), 4);
1174        assert_eq!(pin_length("ü1"), 2);
1175    }
1176
1177    /// Legacy compat encryption gives V1 PINs a key id. It is the algorithm, not a missing key id,
1178    /// that marks a PIN as V1.
1179    #[test]
1180    fn classify_v1_pin_with_key_id() {
1181        let user_key_id = KeyId::from([1; 16]);
1182        let other_key_id = KeyId::from([2; 16]);
1183
1184        assert_eq!(
1185            classify_encrypted_pin(
1186                Some(SymmetricKeyAlgorithm::Aes256CbcHmac),
1187                Some(&other_key_id),
1188                SymmetricKeyAlgorithm::XAes256Gcm,
1189                &user_key_id
1190            ),
1191            PinMigrationAction::MigrateV1ToV2,
1192        );
1193        assert_eq!(
1194            classify_encrypted_pin(
1195                Some(SymmetricKeyAlgorithm::Aes256CbcHmac),
1196                Some(&user_key_id),
1197                SymmetricKeyAlgorithm::Aes256CbcHmac,
1198                &user_key_id
1199            ),
1200            PinMigrationAction::UpToDate,
1201        );
1202        assert_eq!(
1203            classify_encrypted_pin(
1204                Some(SymmetricKeyAlgorithm::Aes256CbcHmac),
1205                Some(&other_key_id),
1206                SymmetricKeyAlgorithm::Aes256CbcHmac,
1207                &user_key_id
1208            ),
1209            PinMigrationAction::Failed(MigrationFailed::UnrecoverablePinKey),
1210        );
1211    }
1212
1213    /// The encrypted PIN is under a previous V2 user key, which nothing can recover.
1214    #[tokio::test]
1215    async fn migrate_v2_pin_with_rotated_user_key_fails() {
1216        let client = client_with_user_key();
1217        let encrypted_pin = {
1218            let mut ctx = client.internal.get_key_store().context_mut();
1219            let other_v2 = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XAes256Gcm);
1220            "1234"
1221                .encrypt(&mut ctx, other_v2)
1222                .expect("encrypt under other v2 key")
1223        };
1224        client
1225            .km_state_bridge()
1226            .set_encrypted_pin(&encrypted_pin)
1227            .await;
1228
1229        let system = PinLockSystem::with_client(&client);
1230        assert_eq!(
1231            system.migrate_pin_envelope_if_needed().await,
1232            Err(MigrationFailed::UnrecoverablePinKey),
1233        );
1234    }
1235
1236    #[tokio::test]
1237    async fn migrate_without_user_key_fails_locked() {
1238        let client = Client::new(None);
1239        client
1240            .km_state_bridge()
1241            .register_bridge(Box::new(InMemoryStateBridge::default()));
1242        let (_, state) = fresh_v1_state_with_v2_user_key("1234");
1243        client
1244            .km_state_bridge()
1245            .set_encrypted_pin(&state.encrypted_pin)
1246            .await;
1247
1248        let system = PinLockSystem::with_client(&client);
1249        assert_eq!(
1250            system.migrate_pin_envelope_if_needed().await,
1251            Err(MigrationFailed::Locked),
1252        );
1253    }
1254
1255    #[tokio::test]
1256    async fn migrate_envelope_without_encrypted_pin_fails() {
1257        let client = client_with_v1_user_key();
1258        client
1259            .km_state_bridge()
1260            .set_persistent_pin_envelope(&legacy_envelope())
1261            .await;
1262
1263        let system = PinLockSystem::with_client(&client);
1264        assert_eq!(
1265            system.migrate_pin_envelope_if_needed().await,
1266            Err(MigrationFailed::MissingEncryptedPin),
1267        );
1268    }
1269
1270    #[tokio::test]
1271    async fn migrate_v1_pin_without_token_fails() {
1272        let (client, state) = fresh_v1_state_with_v2_user_key("1234");
1273        store_v1_pin(&client, &state, &PinLockType::AfterFirstUnlock).await;
1274
1275        let system = PinLockSystem::with_client(&client);
1276        assert_eq!(
1277            system.migrate_pin_envelope_if_needed().await,
1278            Err(MigrationFailed::MissingV2UpgradeToken),
1279        );
1280    }
1281
1282    /// The token unwraps a V1 key other than the one the PIN is encrypted with.
1283    #[tokio::test]
1284    async fn migrate_v1_pin_with_mismatched_token_fails() {
1285        let (client, state) = fresh_v1_state_with_v2_user_key("1234");
1286        store_v1_pin(&client, &state, &PinLockType::AfterFirstUnlock).await;
1287
1288        // Wraps the current V2 user key, but alongside an unrelated V1 key.
1289        let unrelated_token = {
1290            let mut ctx = client.internal.get_key_store().context_mut();
1291            let other_v1 = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
1292            V2UpgradeToken::create(other_v1, SymmetricKeySlotId::User, &ctx)
1293                .expect("unrelated token created")
1294        };
1295        client
1296            .km_state_bridge()
1297            .set_v2_upgrade_token(&unrelated_token)
1298            .await;
1299
1300        let system = PinLockSystem::with_client(&client);
1301        assert_eq!(
1302            system.migrate_pin_envelope_if_needed().await,
1303            Err(MigrationFailed::PinDecryption),
1304        );
1305    }
1306
1307    /// An AfterFirstUnlock PIN is available again after unlocking onto the upgraded key.
1308    #[tokio::test]
1309    async fn on_unlock_restores_afu_pin_after_upgrade() {
1310        let pin = "1234";
1311        let (client, state) = fresh_v1_state_with_v2_user_key(pin);
1312        store_v1_pin(&client, &state, &PinLockType::AfterFirstUnlock).await;
1313        client
1314            .km_state_bridge()
1315            .set_v2_upgrade_token(&state.token)
1316            .await;
1317
1318        let system = PinLockSystem::with_client(&client);
1319        assert_eq!(system.get_pin_status().await, PinUnlockStatus::NeedsUnlock);
1320
1321        system.on_unlock().await;
1322
1323        assert_eq!(system.get_pin_status().await, PinUnlockStatus::Available);
1324        assert!(system.unlock(pin).await.is_ok());
1325    }
1326
1327    #[tokio::test]
1328    async fn on_unlock_unenrolls_when_migration_fails() {
1329        // Reuse the missing-upgrade-token scenario to drive migration failure end-to-end.
1330        let (client, state) = fresh_v1_state_with_v2_user_key("1234");
1331        store_v1_pin(&client, &state, &PinLockType::BeforeFirstUnlock).await;
1332
1333        let system = PinLockSystem::with_client(&client);
1334        system.on_unlock().await;
1335
1336        assert_pin_fully_unenrolled(&client).await;
1337    }
1338
1339    // ------------------------------------------------------------------------------------
1340    // PIN length
1341    // ------------------------------------------------------------------------------------
1342
1343    #[tokio::test]
1344    async fn set_pin_stores_its_length() {
1345        let client = client_with_user_key();
1346        let system = PinLockSystem::with_client(&client);
1347
1348        system
1349            .set_pin("123456".into(), PinLockType::AfterFirstUnlock)
1350            .await
1351            .expect("set_pin succeeds");
1352
1353        assert_eq!(system.get_pin_length().await, Some(6));
1354    }
1355
1356    #[tokio::test]
1357    async fn unset_pin_clears_its_length() {
1358        let client = client_with_user_key();
1359        let system = PinLockSystem::with_client(&client);
1360        system
1361            .set_pin("1234".into(), PinLockType::AfterFirstUnlock)
1362            .await
1363            .expect("set_pin succeeds");
1364
1365        system.unset_pin().await;
1366
1367        assert_eq!(system.get_pin_length().await, None);
1368    }
1369
1370    #[tokio::test]
1371    async fn on_unlock_stores_the_length_of_a_pin_set_before_lengths_were() {
1372        let client = client_with_user_key();
1373        let system = PinLockSystem::with_client(&client);
1374        system
1375            .set_pin("12345".into(), PinLockType::BeforeFirstUnlock)
1376            .await
1377            .expect("set_pin succeeds");
1378        client.km_state_bridge().clear_pin_length().await;
1379
1380        system.on_unlock().await;
1381
1382        assert_eq!(system.get_pin_length().await, Some(5));
1383    }
1384}