Skip to main content

bitwarden_member_administration/
account_recovery_v2_upgrade.rs

1//! Updating members' account recovery keys after their V1 to V2 upgrade.
2//!
3//! A V1 to V2 upgrade rotation does not re-encapsulate the member's account recovery key, because
4//! that requires trusting a server-supplied organization public key and the upgrade shows the
5//! member no prompt. The rotation writes a V2 upgrade token to the membership instead, and the
6//! organization keeps an account recovery key that wraps the member's V1 user key.
7//!
8//! The token carries both user keys, each one wrapped with the other, so opening the V1 user key
9//! yields the V2 one:
10//!
11//! ```text
12//! OrganizationPrivateKey -> AccountRecovery       -> V1 user key
13//! V1 user key            -> V2UpgradeToken        -> V2 user key
14//! V2 user key            +  OrganizationPublicKey -> new AccountRecovery
15//! ```
16//!
17//! An owner or admin runs
18//! [`OrganizationUsersManagementClient::upgrade_pending_account_recovery_keys`]
19//! for each organization whose key it holds. The server returns the pending memberships one page
20//! at a time. The client sends the upgrades of each page to the server before it reads the next
21//! page. For each membership, the client:
22//!
23//! 1. decapsulates the stored account recovery key into the member's V1 user key,
24//! 2. unwraps the V2 user key from the upgrade token, which cross-validates both halves,
25//! 3. compares the key id of that user key with the one the server reported,
26//! 4. encapsulates the V2 user key to the organization.
27//!
28//! The server reports the user key id and can name any key. It holds none of the member's user
29//! keys, so step 3 takes the key id of the user key the client recovered and compares it against
30//! the reported one. A mismatch means the membership names a user key the upgrade token does not
31//! carry.
32//!
33//! A membership is sent to the server without a key when its account recovery key or upgrade token
34//! is missing, malformed, does not decrypt, or carries a user key other than the reported one.
35//! That unenrolls the member from account recovery and drops a key that no longer opens the
36//! member's vault. A retry would read the same keys and fail again, so the membership would
37//! otherwise stay pending on every run. A membership that fails for any other reason is not sent
38//! and stays pending.
39
40use bitwarden_api_api::{
41    apis::organization_users_keys_api::OrganizationUsersKeysApi,
42    models::{
43        OrganizationUserPendingV2UpgradeResponseModel, OrganizationUserV2UpgradeRequestModel,
44        OrganizationUserV2UpgradesRequestModel,
45    },
46};
47use bitwarden_core::{
48    ApiError, MissingFieldError, OrganizationId,
49    key_management::{KeySlotIds, PrivateKeySlotId, SymmetricKeySlotId, V2UpgradeToken},
50    require,
51};
52use bitwarden_crypto::{EncString, KeyId, KeyStoreContext, PublicKey};
53use bitwarden_error::bitwarden_error;
54use bitwarden_organization_crypto::{
55    account_recovery::{AccountRecovery, AccountRecoveryMakeError, AccountRecoveryUnsealError},
56    organization_private_key::OrganizationPrivateKey,
57};
58use bitwarden_organizations::OrganizationUserType;
59use thiserror::Error;
60use tracing::warn;
61use uuid::Uuid;
62
63use crate::OrganizationUsersManagementClient;
64
65/// Errors returned when upgrading members' account recovery keys.
66#[bitwarden_error(flat)]
67#[derive(Debug, Error)]
68pub enum AccountRecoveryV2UpgradeError {
69    /// The request failed as a whole.
70    #[error(transparent)]
71    Api(#[from] ApiError),
72    /// A required field was missing from the server response.
73    #[error(transparent)]
74    MissingField(#[from] MissingFieldError),
75    /// The server returned a continuation token that is not a UUID.
76    #[error("The continuation token is malformed")]
77    MalformedContinuationToken,
78    /// The organization key is not in the key store.
79    #[error("The organization key is not available")]
80    OrganizationKeyMissing,
81    /// The wrapped private key from the server is corrupted, in no format this client knows, or was
82    /// wrapped with an organization key other than the one this client holds.
83    #[error("The organization's private key could not be unwrapped with the organization key")]
84    OrganizationPrivateKeyUnwrapFailed,
85    /// The unwrapped private key could not be stored in the key store.
86    #[error("The organization's private key could not be stored in the key store")]
87    OrganizationPrivateKeyStoreFailed,
88    /// The organization's private key was removed from the key store during the upgrade, for
89    /// example because the account was locked.
90    #[error("The organization's private key does not exist in the key store")]
91    OrganizationPrivateKeyNotInKeyStore,
92}
93
94/// Errors that stop one pending membership from being upgraded. They do not fail the
95/// organization's upgrade: the membership is either unenrolled from account recovery or left
96/// pending.
97#[derive(Debug, Error)]
98enum PendingMembershipError {
99    /// The server could not parse the membership's stored upgrade token, so the token holds no
100    /// usable V2 user key.
101    #[error("The membership has no upgrade token")]
102    MissingUpgradeToken,
103    /// The upgrade token in the response is missing a wrapped user key, or a wrapped user key could
104    /// not be parsed.
105    #[error("The upgrade token is malformed")]
106    MalformedUpgradeToken,
107    /// The account recovery key is in no format this client knows, for example because it is
108    /// corrupted.
109    #[error("The account recovery key is malformed")]
110    MalformedAccountRecoveryKey,
111    /// The account recovery key was encapsulated to a different organization key pair, or is
112    /// corrupted.
113    #[error(
114        "The account recovery key could not be decapsulated with the organization's private key"
115    )]
116    AccountRecoveryKeyDecapsulationFailed,
117    /// The organization's private key is not in the key store context.
118    #[error("The organization's private key does not exist in the key store context")]
119    OrganizationPrivateKeyNotInContext,
120    /// The upgrade token was created with a V1 user key other than the one in the account recovery
121    /// key, holds a wrapped user key in no known format, or was tampered with.
122    #[error("The upgrade token could not be unwrapped with the member's V1 user key")]
123    UpgradeTokenUnwrapFailed,
124    /// The server reported a key id in no format this client knows.
125    #[error("The membership's user key id is malformed")]
126    MalformedUserKeyId,
127    /// The V2 user key in the upgrade token has a key id other than the one the server reported.
128    #[error("The membership's user key id does not match the user key in the upgrade token")]
129    UserKeyIdMismatch,
130    /// The V2 user key could not be made into an account recovery key.
131    #[error(transparent)]
132    AccountRecoveryMakeFailed(AccountRecoveryMakeError),
133}
134
135/// Whether the account's role lets it read the organization's private key and set members'
136/// account recovery keys. The server accepts only owners and admins.
137fn has_account_recovery_permissions(user_type: &OrganizationUserType) -> bool {
138    matches!(
139        user_type,
140        OrganizationUserType::Owner | OrganizationUserType::Admin
141    )
142}
143
144impl OrganizationUsersManagementClient {
145    /// Whether the account can update the account recovery keys of this organization's members.
146    ///
147    /// The account must be an owner or an admin. It must also hold the organization key, which
148    /// unwraps the organization's private key.
149    pub fn can_administer_account_recovery_keys(
150        &self,
151        organization_id: OrganizationId,
152        user_type: &OrganizationUserType,
153    ) -> bool {
154        has_account_recovery_permissions(user_type)
155            && self
156                .key_store
157                .context()
158                .has_symmetric_key(SymmetricKeySlotId::Organization(organization_id))
159    }
160
161    /// Reads the organization's private key, wrapped with the organization key.
162    ///
163    /// The server requires the ManageUsers permission, which owners and admins always have, so
164    /// this request does not fail authorization for the roles that run the upgrade.
165    async fn download_wrapped_organization_private_key(
166        &self,
167        organization_id: OrganizationId,
168    ) -> Result<EncString, AccountRecoveryV2UpgradeError> {
169        Ok(EncString::from(require!(
170            self.api_configurations
171                .api_client
172                .organizations_api()
173                .get_private_key(organization_id.into())
174                .await?
175                .private_key
176        )))
177    }
178
179    /// Returns the organization's private key from the key store. When the key store does not
180    /// hold it, downloads the wrapped private key, then unwraps and persists it into the key store.
181    async fn get_or_download_organization_private_key(
182        &self,
183        organization_id: OrganizationId,
184    ) -> Result<OrganizationPrivateKey<KeySlotIds>, AccountRecoveryV2UpgradeError> {
185        let private_key_id = PrivateKeySlotId::Organization(organization_id);
186        if let Some(private_key) =
187            OrganizationPrivateKey::from_context(private_key_id, &self.key_store.context())
188        {
189            return Ok(private_key);
190        }
191
192        let wrapped_private_key = self
193            .download_wrapped_organization_private_key(organization_id)
194            .await?;
195        let mut ctx = self.key_store.context_mut();
196        let local_private_key_id = ctx
197            .unwrap_private_key(
198                SymmetricKeySlotId::Organization(organization_id),
199                &wrapped_private_key,
200            )
201            .map_err(|_| AccountRecoveryV2UpgradeError::OrganizationPrivateKeyUnwrapFailed)?;
202        ctx.persist_private_key(local_private_key_id, private_key_id)
203            .map_err(|_| AccountRecoveryV2UpgradeError::OrganizationPrivateKeyStoreFailed)?;
204        OrganizationPrivateKey::from_context(private_key_id, &ctx)
205            .ok_or(AccountRecoveryV2UpgradeError::OrganizationPrivateKeyNotInKeyStore)
206    }
207
208    /// Builds the request entries for one page of pending memberships.
209    fn upgrade_requests(
210        &self,
211        organization_id: OrganizationId,
212        organization_private_key: &OrganizationPrivateKey<KeySlotIds>,
213        pending: &[OrganizationUserPendingV2UpgradeResponseModel],
214    ) -> Result<Vec<OrganizationUserV2UpgradeRequestModel>, AccountRecoveryV2UpgradeError> {
215        let mut ctx = self.key_store.context();
216        let organization_public_key = organization_private_key
217            .public_key(&ctx)
218            .map_err(|_| AccountRecoveryV2UpgradeError::OrganizationPrivateKeyNotInKeyStore)?;
219
220        Ok(pending
221            .iter()
222            .filter_map(|membership| {
223                let organization_user_id = membership.organization_user_id;
224                let account_recovery_key = match make_new_account_recovery_key(
225                    organization_private_key,
226                    &organization_public_key,
227                    membership,
228                    &mut ctx,
229                ) {
230                    Ok(key) => Some(key),
231                    Err(
232                        e @ (PendingMembershipError::MissingUpgradeToken
233                        | PendingMembershipError::MalformedUpgradeToken
234                        | PendingMembershipError::MalformedAccountRecoveryKey
235                        | PendingMembershipError::AccountRecoveryKeyDecapsulationFailed
236                        | PendingMembershipError::UpgradeTokenUnwrapFailed
237                        | PendingMembershipError::UserKeyIdMismatch),
238                    ) => {
239                        // Left pending, the membership would fail the same way on every run,
240                        // because a retry reads the same keys.
241                        warn!(
242                            %organization_id,
243                            %organization_user_id,
244                            "Unenrolling a member from account recovery: {e}"
245                        );
246                        None
247                    }
248                    Err(
249                        e @ (PendingMembershipError::MalformedUserKeyId
250                        | PendingMembershipError::OrganizationPrivateKeyNotInContext
251                        | PendingMembershipError::AccountRecoveryMakeFailed(
252                            AccountRecoveryMakeError::PrivateKeyNotInContext
253                            | AccountRecoveryMakeError::EncapsulationFailed
254                            | AccountRecoveryMakeError::UntrustedPublicKey,
255                        )),
256                    ) => {
257                        // A malformed key id is not unenrolled: unenrolling also sends the key id,
258                        // and one malformed entry fails the whole request. The other errors are not
259                        // unenrolled either: they happen in this client, not in the membership's
260                        // keys, and a later run can succeed.
261                        warn!(
262                            %organization_id,
263                            %organization_user_id,
264                            "Leaving a membership pending: {e}"
265                        );
266                        return None;
267                    }
268                };
269
270                // The key id is sent back unchanged, because the server checks it against the
271                // member's user row.
272                let mut upgrade = OrganizationUserV2UpgradeRequestModel::new(
273                    organization_user_id,
274                    membership.user_key_id.clone(),
275                );
276                upgrade.account_recovery_key = account_recovery_key;
277                Some(upgrade)
278            })
279            .collect())
280    }
281
282    /// Sends the upgrades of one page of pending memberships. Reads the organization's private key
283    /// only when the page has pending memberships, and sends nothing when every membership is left
284    /// pending.
285    async fn upgrade_page(
286        &self,
287        api: &dyn OrganizationUsersKeysApi,
288        organization_id: OrganizationId,
289        pending: &[OrganizationUserPendingV2UpgradeResponseModel],
290    ) -> Result<(), AccountRecoveryV2UpgradeError> {
291        if pending.is_empty() {
292            return Ok(());
293        }
294
295        let organization_private_key = self
296            .get_or_download_organization_private_key(organization_id)
297            .await?;
298        let upgrades =
299            self.upgrade_requests(organization_id, &organization_private_key, pending)?;
300        if upgrades.is_empty() {
301            return Ok(());
302        }
303
304        api.post_v2_upgrades(
305            organization_id.into(),
306            Some(OrganizationUserV2UpgradesRequestModel::new(upgrades)),
307        )
308        .await?;
309        Ok(())
310    }
311}
312
313/// One page of pending memberships.
314struct PendingPage {
315    pending: Vec<OrganizationUserPendingV2UpgradeResponseModel>,
316    /// The continuation token of the next page, or `None` on the last page.
317    next: Option<Uuid>,
318}
319
320/// Reads one page of pending memberships.
321async fn fetch_pending(
322    api: &dyn OrganizationUsersKeysApi,
323    organization_id: OrganizationId,
324    continuation_token: Option<Uuid>,
325) -> Result<PendingPage, AccountRecoveryV2UpgradeError> {
326    let page = api
327        .get_pending_v2_upgrades(organization_id.into(), continuation_token)
328        .await?;
329    let next = page
330        .continuation_token
331        .map(|token| token.parse::<Uuid>())
332        .transpose()
333        .map_err(|_| AccountRecoveryV2UpgradeError::MalformedContinuationToken)?;
334
335    Ok(PendingPage {
336        pending: page.data.unwrap_or_default(),
337        next,
338    })
339}
340
341#[bitwarden_ffi::wasm_export]
342impl OrganizationUsersManagementClient {
343    /// Re-encapsulates the account recovery keys of members who have upgraded to a V2 user key.
344    ///
345    /// A membership whose account recovery key or upgrade token is malformed or fails to decrypt
346    /// is sent to the server without a key. That unenrolls the member from account recovery and
347    /// drops a key that no longer opens the member's vault.
348    ///
349    /// Callers that filter a list of organizations should check
350    /// `can_administer_account_recovery_keys` first.
351    pub async fn upgrade_pending_account_recovery_keys(
352        &self,
353        organization_id: OrganizationId,
354    ) -> Result<(), AccountRecoveryV2UpgradeError> {
355        if !self
356            .key_store
357            .context()
358            .has_symmetric_key(SymmetricKeySlotId::Organization(organization_id))
359        {
360            return Err(AccountRecoveryV2UpgradeError::OrganizationKeyMissing);
361        }
362
363        let api = self
364            .api_configurations
365            .api_client
366            .organization_users_keys_api();
367        let mut continuation_token = None;
368
369        loop {
370            let PendingPage { pending, next } =
371                fetch_pending(api, organization_id, continuation_token).await?;
372            self.upgrade_page(api, organization_id, &pending).await?;
373
374            let Some(next) = next else {
375                return Ok(());
376            };
377            continuation_token = Some(next);
378        }
379    }
380}
381
382/// Reads the V2 user key out of the membership's upgrade token and encapsulates it to the
383/// organization as the member's new account recovery key.
384fn make_new_account_recovery_key(
385    organization_private_key: &OrganizationPrivateKey<KeySlotIds>,
386    organization_public_key: &PublicKey,
387    membership: &OrganizationUserPendingV2UpgradeResponseModel,
388    ctx: &mut KeyStoreContext<KeySlotIds>,
389) -> Result<String, PendingMembershipError> {
390    let user_key_id: KeyId = membership
391        .user_key_id
392        .parse()
393        .map_err(|_| PendingMembershipError::MalformedUserKeyId)?;
394    let upgrade_token = V2UpgradeToken::try_from(
395        membership
396            .v2_upgrade_token
397            .as_deref()
398            .ok_or(PendingMembershipError::MissingUpgradeToken)?,
399    )
400    .map_err(|_| PendingMembershipError::MalformedUpgradeToken)?;
401    let account_recovery: AccountRecovery = membership
402        .account_recovery_key
403        .parse()
404        .map_err(|_| PendingMembershipError::MalformedAccountRecoveryKey)?;
405
406    let v1_user_key = account_recovery
407        .unseal_member_user_key(organization_private_key, ctx)
408        .map_err(|error| match error {
409            AccountRecoveryUnsealError::DecapsulationFailed => {
410                PendingMembershipError::AccountRecoveryKeyDecapsulationFailed
411            }
412            AccountRecoveryUnsealError::PrivateKeyNotInContext => {
413                PendingMembershipError::OrganizationPrivateKeyNotInContext
414            }
415        })?;
416    // Unwrapping cross-validates both halves of the token, so a tampered token fails here.
417    let v2_user_key = upgrade_token
418        .unwrap_v2(v1_user_key, ctx)
419        .map_err(|_| PendingMembershipError::UpgradeTokenUnwrapFailed)?;
420
421    // The key id is sent back to the server as it reported it, so the server's check against the
422    // member's user row cannot detect a token carrying a different key.
423    if ctx.get_symmetric_key_id(v2_user_key) != Some(user_key_id) {
424        return Err(PendingMembershipError::UserKeyIdMismatch);
425    }
426
427    let account_recovery = AccountRecovery::make(
428        v2_user_key,
429        organization_public_key,
430        &organization_private_key.trust_proof(),
431        ctx,
432    )
433    .map_err(PendingMembershipError::AccountRecoveryMakeFailed)?;
434
435    Ok(String::from(&account_recovery))
436}
437
438#[cfg(test)]
439mod tests {
440    use std::sync::{Arc, Mutex};
441
442    use bitwarden_api_api::{
443        apis::{ApiClient, ApiClientMock},
444        models::{
445            OrganizationPrivateKeyResponseModel,
446            OrganizationUserPendingV2UpgradeResponseModelListResponseModel,
447            V2UpgradeTokenResponseModel,
448        },
449    };
450    use bitwarden_core::{
451        client::ApiConfigurations, key_management::create_test_crypto_with_user_and_org_key,
452    };
453    use bitwarden_crypto::{
454        PublicKeyEncryptionAlgorithm, SymmetricCryptoKey, SymmetricKeyAlgorithm,
455    };
456
457    use super::*;
458
459    /// A well-formed key id matching none of the keys under test.
460    const UNRELATED_USER_KEY_ID: &str = "000102030405060708090a0b0c0d0e0f";
461
462    /// An organization with its key in the key store and its wrapped private key.
463    struct TestOrganization {
464        client: OrganizationUsersManagementClient,
465        organization_id: OrganizationId,
466        wrapped_private_key: String,
467    }
468
469    impl TestOrganization {
470        fn new() -> Self {
471            let organization_id = OrganizationId::new_v4();
472            let key_store = create_test_crypto_with_user_and_org_key(
473                SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
474                organization_id,
475                SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
476            );
477
478            let wrapped_private_key = {
479                let mut ctx = key_store.context();
480                let private_key = ctx.make_private_key(PublicKeyEncryptionAlgorithm::RsaOaepSha1);
481                ctx.wrap_private_key(
482                    SymmetricKeySlotId::Organization(organization_id),
483                    private_key,
484                )
485                .unwrap()
486                .to_string()
487            };
488
489            Self {
490                client: OrganizationUsersManagementClient {
491                    key_store,
492                    api_configurations: Arc::new(ApiConfigurations::from_api_client(
493                        ApiClient::new_mocked(|_| {}),
494                    )),
495                },
496                organization_id,
497                wrapped_private_key,
498            }
499        }
500
501        /// Replaces the API client. Memberships are built before the mock, because they need the
502        /// organization's key pair.
503        fn with_api(self, configure: impl FnOnce(&mut ApiClientMock)) -> Self {
504            Self {
505                client: OrganizationUsersManagementClient {
506                    key_store: self.client.key_store,
507                    api_configurations: Arc::new(ApiConfigurations::from_api_client(
508                        ApiClient::new_mocked(configure),
509                    )),
510                },
511                ..self
512            }
513        }
514
515        async fn upgrade(&self) -> Result<(), AccountRecoveryV2UpgradeError> {
516            self.client
517                .upgrade_pending_account_recovery_keys(self.organization_id)
518                .await
519        }
520
521        fn organization_private_key<'a>(
522            &self,
523            ctx: &mut KeyStoreContext<'a, KeySlotIds>,
524        ) -> OrganizationPrivateKey<KeySlotIds> {
525            OrganizationPrivateKey::unwrap_with_organization_key(
526                SymmetricKeySlotId::Organization(self.organization_id),
527                &self.wrapped_private_key.parse().unwrap(),
528                ctx,
529            )
530            .unwrap()
531        }
532
533        /// Builds a membership mid-upgrade: the account recovery key holds the V1 user key and
534        /// the upgrade token holds the V2 one. Also returns the expected V2 user key.
535        fn pending_membership(
536            &self,
537        ) -> (
538            OrganizationUserPendingV2UpgradeResponseModel,
539            SymmetricCryptoKey,
540        ) {
541            let mut ctx = self.client.key_store.context();
542            let organization_private_key = self.organization_private_key(&mut ctx);
543
544            let v1_user_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
545            let v2_user_key = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XAes256Gcm);
546            let token = V2UpgradeToken::create::<KeySlotIds>(v1_user_key, v2_user_key, &ctx)
547                .expect("the token wraps each user key with the other");
548
549            let account_recovery = AccountRecovery::make(
550                v1_user_key,
551                &organization_private_key.public_key(&ctx).unwrap(),
552                &organization_private_key.trust_proof(),
553                &ctx,
554            )
555            .unwrap();
556
557            // After the upgrade the member's current user key is the V2 one.
558            let user_key_id = ctx.get_symmetric_key_id(v2_user_key).unwrap();
559
560            #[allow(deprecated)]
561            let expected = ctx
562                .dangerous_get_symmetric_key(v2_user_key)
563                .unwrap()
564                .clone();
565
566            (
567                OrganizationUserPendingV2UpgradeResponseModel {
568                    object: None,
569                    organization_user_id: Uuid::new_v4(),
570                    user_key_id: user_key_id.to_string(),
571                    account_recovery_key: String::from(&account_recovery),
572                    v2_upgrade_token: Some(Box::new(V2UpgradeTokenResponseModel {
573                        wrapped_user_key1: Some(token.wrapped_user_key_1.to_string()),
574                        wrapped_user_key2: Some(token.wrapped_user_key_2.to_string()),
575                    })),
576                },
577                expected,
578            )
579        }
580
581        /// Runs `make_new_account_recovery_key` for one membership with this organization's key
582        /// pair.
583        fn make_new_account_recovery_key(
584            &self,
585            membership: &OrganizationUserPendingV2UpgradeResponseModel,
586        ) -> Result<String, PendingMembershipError> {
587            let mut ctx = self.client.key_store.context();
588            let organization_private_key = self.organization_private_key(&mut ctx);
589            let organization_public_key = organization_private_key.public_key(&ctx).unwrap();
590            make_new_account_recovery_key(
591                &organization_private_key,
592                &organization_public_key,
593                membership,
594                &mut ctx,
595            )
596        }
597
598        /// Decapsulates a posted account recovery key.
599        fn decapsulate(&self, account_recovery_key: &str) -> SymmetricCryptoKey {
600            let mut ctx = self.client.key_store.context();
601            let organization_private_key = self.organization_private_key(&mut ctx);
602            let key_id = account_recovery_key
603                .parse::<AccountRecovery>()
604                .unwrap()
605                .unseal_member_user_key(&organization_private_key, &mut ctx)
606                .unwrap();
607
608            #[allow(deprecated)]
609            ctx.dangerous_get_symmetric_key(key_id).unwrap().clone()
610        }
611    }
612
613    /// The upgrades of every POST, in order.
614    type PostedPages = Arc<Mutex<Vec<Vec<OrganizationUserV2UpgradeRequestModel>>>>;
615
616    /// Answers `get_pending_v2_upgrades` for `continuation_token` with one page, exactly once.
617    fn expect_page(
618        mock: &mut ApiClientMock,
619        continuation_token: Option<Uuid>,
620        pending: Vec<OrganizationUserPendingV2UpgradeResponseModel>,
621        next: Option<String>,
622    ) {
623        mock.organization_users_keys_api
624            .expect_get_pending_v2_upgrades()
625            .withf(move |_org, token| *token == continuation_token)
626            .returning(move |_org, _token| {
627                Ok(
628                    OrganizationUserPendingV2UpgradeResponseModelListResponseModel {
629                        object: None,
630                        data: Some(pending.clone()),
631                        continuation_token: next.clone(),
632                    },
633                )
634            })
635            .once();
636    }
637
638    /// Answers `get_pending_v2_upgrades` with a single page.
639    fn expect_pending(
640        mock: &mut ApiClientMock,
641        pending: Vec<OrganizationUserPendingV2UpgradeResponseModel>,
642    ) {
643        expect_page(mock, None, pending, None);
644    }
645
646    /// Records every `post_v2_upgrades` call.
647    fn expect_posts(mock: &mut ApiClientMock, posted: PostedPages) {
648        mock.organization_users_keys_api
649            .expect_post_v2_upgrades()
650            .returning(move |_org, model| {
651                posted.lock().unwrap().push(model.unwrap().upgrades);
652                Ok(())
653            });
654    }
655
656    /// Answers `get_private_key` with the given wrapped key, exactly once.
657    fn expect_get_private_key(mock: &mut ApiClientMock, wrapped: String) {
658        mock.organizations_api
659            .expect_get_private_key()
660            .returning(move |_org| {
661                Ok(OrganizationPrivateKeyResponseModel {
662                    object: None,
663                    private_key: Some(wrapped.clone()),
664                })
665            })
666            .once();
667    }
668
669    /// Runs the upgrade over a single page and returns the upgrades of the one POST.
670    async fn upgrade_single_page(
671        fixture: TestOrganization,
672        pending: Vec<OrganizationUserPendingV2UpgradeResponseModel>,
673    ) -> (TestOrganization, Vec<OrganizationUserV2UpgradeRequestModel>) {
674        let posted: PostedPages = Arc::default();
675        let wrapped_private_key = fixture.wrapped_private_key.clone();
676        let organization = fixture.with_api(|mock| {
677            expect_get_private_key(mock, wrapped_private_key);
678            expect_pending(mock, pending);
679            expect_posts(mock, posted.clone());
680        });
681
682        organization.upgrade().await.unwrap();
683
684        let mut posted = posted.lock().unwrap().clone();
685        assert_eq!(posted.len(), 1, "exactly one page is posted");
686        (organization, posted.remove(0))
687    }
688
689    #[tokio::test]
690    async fn test_pending_membership_is_posted_with_its_v2_user_key() {
691        let fixture = TestOrganization::new();
692        let (membership, expected_v2_user_key) = fixture.pending_membership();
693
694        let (organization, posted) = upgrade_single_page(fixture, vec![membership.clone()]).await;
695
696        let [upgrade] = posted.as_slice() else {
697            panic!("exactly one upgrade is posted, got {}", posted.len());
698        };
699        assert_eq!(
700            upgrade.organization_user_id,
701            membership.organization_user_id
702        );
703        assert_eq!(upgrade.user_key_id, membership.user_key_id);
704        assert_eq!(
705            organization.decapsulate(upgrade.account_recovery_key.as_ref().unwrap()),
706            expected_v2_user_key
707        );
708    }
709
710    #[tokio::test]
711    async fn test_no_pending_memberships_reads_no_private_key_and_posts_nothing() {
712        let organization = TestOrganization::new().with_api(|mock| expect_pending(mock, vec![]));
713
714        organization.upgrade().await.unwrap();
715    }
716
717    #[tokio::test]
718    async fn test_downloaded_organization_private_key_is_persisted_in_the_key_store() {
719        let fixture = TestOrganization::new();
720        let (membership, _) = fixture.pending_membership();
721
722        let (organization, _) = upgrade_single_page(fixture, vec![membership]).await;
723
724        let ctx = organization.client.key_store.context();
725        assert!(
726            OrganizationPrivateKey::from_context(
727                PrivateKeySlotId::Organization(organization.organization_id),
728                &ctx,
729            )
730            .is_some()
731        );
732    }
733
734    #[tokio::test]
735    async fn test_organization_private_key_in_the_key_store_is_not_downloaded() {
736        let posted: PostedPages = Arc::default();
737        let fixture = TestOrganization::new();
738        let (membership, expected_v2_user_key) = fixture.pending_membership();
739        {
740            let mut ctx = fixture.client.key_store.context_mut();
741            let private_key_id = ctx
742                .unwrap_private_key(
743                    SymmetricKeySlotId::Organization(fixture.organization_id),
744                    &fixture.wrapped_private_key.parse().unwrap(),
745                )
746                .unwrap();
747            ctx.persist_private_key(
748                private_key_id,
749                PrivateKeySlotId::Organization(fixture.organization_id),
750            )
751            .unwrap();
752        }
753        let organization = fixture.with_api(|mock| {
754            expect_pending(mock, vec![membership.clone()]);
755            expect_posts(mock, posted.clone());
756        });
757
758        organization.upgrade().await.unwrap();
759
760        let posted = posted.lock().unwrap().clone();
761        let [page] = posted.as_slice() else {
762            panic!("exactly one page is posted, got {}", posted.len());
763        };
764        let [upgrade] = page.as_slice() else {
765            panic!("exactly one upgrade is posted, got {}", page.len());
766        };
767        assert_eq!(
768            organization.decapsulate(upgrade.account_recovery_key.as_ref().unwrap()),
769            expected_v2_user_key
770        );
771    }
772
773    #[tokio::test]
774    async fn test_each_page_is_posted_and_the_next_page_is_read_with_its_continuation_token() {
775        let posted: PostedPages = Arc::default();
776
777        let fixture = TestOrganization::new();
778        let (first, _) = fixture.pending_membership();
779        let (second, _) = fixture.pending_membership();
780        let wrapped_private_key = fixture.wrapped_private_key.clone();
781        let next = first.organization_user_id;
782        let organization = fixture.with_api(|mock| {
783            expect_get_private_key(mock, wrapped_private_key);
784            expect_page(mock, None, vec![first.clone()], Some(next.to_string()));
785            expect_page(mock, Some(next), vec![second.clone()], None);
786            expect_posts(mock, posted.clone());
787        });
788
789        organization.upgrade().await.unwrap();
790
791        let posted_ids = posted
792            .lock()
793            .unwrap()
794            .iter()
795            .map(|page| {
796                page.iter()
797                    .map(|upgrade| upgrade.organization_user_id)
798                    .collect::<Vec<_>>()
799            })
800            .collect::<Vec<_>>();
801        assert_eq!(
802            posted_ids,
803            vec![
804                vec![first.organization_user_id],
805                vec![second.organization_user_id]
806            ]
807        );
808    }
809
810    #[tokio::test]
811    async fn test_empty_page_with_a_continuation_token_is_not_posted_and_the_next_page_is_read() {
812        let posted: PostedPages = Arc::default();
813
814        let fixture = TestOrganization::new();
815        let (membership, _) = fixture.pending_membership();
816        let wrapped_private_key = fixture.wrapped_private_key.clone();
817        let next = Uuid::new_v4();
818        let organization = fixture.with_api(|mock| {
819            expect_get_private_key(mock, wrapped_private_key);
820            expect_page(mock, None, vec![], Some(next.to_string()));
821            expect_page(mock, Some(next), vec![membership.clone()], None);
822            expect_posts(mock, posted.clone());
823        });
824
825        organization.upgrade().await.unwrap();
826
827        let posted = posted.lock().unwrap().clone();
828        let [page] = posted.as_slice() else {
829            panic!("exactly one page is posted, got {}", posted.len());
830        };
831        let [upgrade] = page.as_slice() else {
832            panic!("exactly one upgrade is posted, got {}", page.len());
833        };
834        assert_eq!(
835            upgrade.organization_user_id,
836            membership.organization_user_id
837        );
838    }
839
840    #[tokio::test]
841    async fn test_malformed_continuation_token_is_an_error() {
842        let organization = TestOrganization::new().with_api(|mock| {
843            expect_page(mock, None, vec![], Some("not a uuid".to_string()));
844        });
845
846        let result = organization.upgrade().await;
847
848        assert!(matches!(
849            result,
850            Err(AccountRecoveryV2UpgradeError::MalformedContinuationToken)
851        ));
852    }
853
854    #[tokio::test]
855    async fn test_membership_without_an_upgrade_token_is_posted_without_an_account_recovery_key() {
856        let fixture = TestOrganization::new();
857        let (mut unparsed, _) = fixture.pending_membership();
858        unparsed.v2_upgrade_token = None;
859
860        let (_, posted) = upgrade_single_page(fixture, vec![unparsed.clone()]).await;
861
862        let [upgrade] = posted.as_slice() else {
863            panic!("exactly one upgrade is posted, got {}", posted.len());
864        };
865        assert_eq!(upgrade.organization_user_id, unparsed.organization_user_id);
866        assert_eq!(upgrade.user_key_id, unparsed.user_key_id);
867        assert_eq!(upgrade.account_recovery_key, None);
868    }
869
870    #[tokio::test]
871    async fn test_membership_with_an_unparseable_upgrade_token_is_posted_without_an_account_recovery_key()
872     {
873        let fixture = TestOrganization::new();
874        let (mut unparseable, _) = fixture.pending_membership();
875        unparseable.v2_upgrade_token = Some(Box::new(V2UpgradeTokenResponseModel {
876            wrapped_user_key1: Some("not an enc string".to_string()),
877            wrapped_user_key2: None,
878        }));
879
880        let (_, posted) = upgrade_single_page(fixture, vec![unparseable.clone()]).await;
881
882        let [upgrade] = posted.as_slice() else {
883            panic!("exactly one upgrade is posted, got {}", posted.len());
884        };
885        assert_eq!(
886            upgrade.organization_user_id,
887            unparseable.organization_user_id
888        );
889        assert_eq!(upgrade.account_recovery_key, None);
890    }
891
892    #[tokio::test]
893    async fn test_membership_with_a_tampered_token_is_posted_without_an_account_recovery_key() {
894        let fixture = TestOrganization::new();
895        let (mut tampered, _) = fixture.pending_membership();
896        let (intact, expected_v2_user_key) = fixture.pending_membership();
897
898        // An unrelated token's wrapped key, which this member's V1 user key cannot open.
899        let (other, _) = fixture.pending_membership();
900        tampered
901            .v2_upgrade_token
902            .as_mut()
903            .unwrap()
904            .wrapped_user_key2 = other.v2_upgrade_token.unwrap().wrapped_user_key2;
905
906        let (organization, posted) =
907            upgrade_single_page(fixture, vec![tampered, intact.clone()]).await;
908
909        let [tampered_upgrade, intact_upgrade] = posted.as_slice() else {
910            panic!("both memberships are posted, got {}", posted.len());
911        };
912        assert_eq!(tampered_upgrade.account_recovery_key, None);
913        assert_eq!(
914            intact_upgrade.organization_user_id,
915            intact.organization_user_id
916        );
917        assert_eq!(
918            organization.decapsulate(intact_upgrade.account_recovery_key.as_ref().unwrap()),
919            expected_v2_user_key
920        );
921    }
922
923    #[tokio::test]
924    async fn test_membership_with_a_malformed_account_recovery_key_is_posted_without_one() {
925        let fixture = TestOrganization::new();
926        let (mut broken, _) = fixture.pending_membership();
927        broken.account_recovery_key = "not an enc string".to_string();
928
929        let (_, posted) = upgrade_single_page(fixture, vec![broken.clone()]).await;
930
931        let [upgrade] = posted.as_slice() else {
932            panic!("exactly one upgrade is posted, got {}", posted.len());
933        };
934        assert_eq!(upgrade.organization_user_id, broken.organization_user_id);
935        assert_eq!(upgrade.account_recovery_key, None);
936    }
937
938    /// The organization's private key cannot open a key encapsulated to another organization.
939    #[tokio::test]
940    async fn test_account_recovery_key_for_another_organization_is_posted_without_one() {
941        let fixture = TestOrganization::new();
942        let (mut foreign, _) = fixture.pending_membership();
943        let (other_organization_membership, _) = TestOrganization::new().pending_membership();
944        foreign.account_recovery_key = other_organization_membership.account_recovery_key;
945
946        let (_, posted) = upgrade_single_page(fixture, vec![foreign.clone()]).await;
947
948        let [upgrade] = posted.as_slice() else {
949            panic!("exactly one upgrade is posted, got {}", posted.len());
950        };
951        assert_eq!(upgrade.organization_user_id, foreign.organization_user_id);
952        assert_eq!(upgrade.account_recovery_key, None);
953    }
954
955    /// The server cannot detect this, because the key id it checks is the one it reported.
956    #[tokio::test]
957    async fn test_membership_whose_token_does_not_match_its_key_id_is_posted_without_a_key() {
958        let fixture = TestOrganization::new();
959        let (mut stale, _) = fixture.pending_membership();
960        stale.user_key_id = UNRELATED_USER_KEY_ID.to_string();
961
962        let (_, posted) = upgrade_single_page(fixture, vec![stale.clone()]).await;
963
964        let [upgrade] = posted.as_slice() else {
965            panic!("exactly one upgrade is posted, got {}", posted.len());
966        };
967        assert_eq!(upgrade.organization_user_id, stale.organization_user_id);
968        assert_eq!(upgrade.user_key_id, UNRELATED_USER_KEY_ID);
969        assert_eq!(upgrade.account_recovery_key, None);
970    }
971
972    /// The server rejects a whole request that carries a malformed key id.
973    #[tokio::test]
974    async fn test_membership_with_a_malformed_user_key_id_is_not_posted() {
975        let fixture = TestOrganization::new();
976        let (mut unparseable, _) = fixture.pending_membership();
977        unparseable.user_key_id = "not a key id".to_string();
978        let (intact, _) = fixture.pending_membership();
979
980        let (_, posted) = upgrade_single_page(fixture, vec![unparseable, intact.clone()]).await;
981
982        let [upgrade] = posted.as_slice() else {
983            panic!("exactly one upgrade is posted, got {}", posted.len());
984        };
985        assert_eq!(upgrade.organization_user_id, intact.organization_user_id);
986    }
987
988    #[tokio::test]
989    async fn test_page_whose_memberships_are_all_skipped_is_not_posted() {
990        let fixture = TestOrganization::new();
991        let (mut unparseable, _) = fixture.pending_membership();
992        unparseable.user_key_id = "not a key id".to_string();
993        let wrapped_private_key = fixture.wrapped_private_key.clone();
994        let organization = fixture.with_api(|mock| {
995            expect_get_private_key(mock, wrapped_private_key);
996            expect_pending(mock, vec![unparseable]);
997        });
998
999        organization.upgrade().await.unwrap();
1000    }
1001
1002    /// A private key the organization key cannot unwrap.
1003    #[tokio::test]
1004    async fn test_unusable_organization_private_key_is_an_error() {
1005        let fixture = TestOrganization::new();
1006        let (membership, _) = fixture.pending_membership();
1007        let organization = fixture.with_api(|mock| {
1008            expect_get_private_key(mock, "not an enc string".to_string());
1009            expect_pending(mock, vec![membership]);
1010        });
1011
1012        let result = organization.upgrade().await;
1013
1014        assert!(matches!(
1015            result,
1016            Err(AccountRecoveryV2UpgradeError::OrganizationPrivateKeyUnwrapFailed)
1017        ));
1018    }
1019
1020    #[tokio::test]
1021    async fn test_absent_organization_private_key_is_an_error() {
1022        let fixture = TestOrganization::new();
1023        let (membership, _) = fixture.pending_membership();
1024        let organization = fixture.with_api(|mock| {
1025            mock.organizations_api
1026                .expect_get_private_key()
1027                .returning(|_org| {
1028                    Ok(OrganizationPrivateKeyResponseModel {
1029                        object: None,
1030                        private_key: None,
1031                    })
1032                })
1033                .once();
1034            expect_pending(mock, vec![membership]);
1035        });
1036
1037        let result = organization.upgrade().await;
1038
1039        assert!(matches!(
1040            result,
1041            Err(AccountRecoveryV2UpgradeError::MissingField(_))
1042        ));
1043    }
1044
1045    #[tokio::test]
1046    async fn test_a_failed_pending_request_is_an_error() {
1047        let organization = TestOrganization::new().with_api(|mock| {
1048            mock.organization_users_keys_api
1049                .expect_get_pending_v2_upgrades()
1050                .returning(|_org, _token| {
1051                    Err(bitwarden_api_api::apis::Error::Io(std::io::Error::other(
1052                        "connection reset",
1053                    )))
1054                })
1055                .once();
1056        });
1057
1058        let result = organization.upgrade().await;
1059
1060        assert!(matches!(result, Err(AccountRecoveryV2UpgradeError::Api(_))));
1061    }
1062
1063    #[tokio::test]
1064    async fn test_organization_without_a_key_in_the_key_store_is_an_error() {
1065        let organization = TestOrganization::new();
1066
1067        let result = organization
1068            .client
1069            .upgrade_pending_account_recovery_keys(OrganizationId::new_v4())
1070            .await;
1071
1072        assert!(matches!(
1073            result,
1074            Err(AccountRecoveryV2UpgradeError::OrganizationKeyMissing)
1075        ));
1076    }
1077
1078    #[test]
1079    fn test_membership_with_a_malformed_user_key_id_fails_with_malformed_user_key_id() {
1080        let organization = TestOrganization::new();
1081        let (mut membership, _) = organization.pending_membership();
1082        membership.user_key_id = "not a key id".to_string();
1083
1084        assert!(matches!(
1085            organization.make_new_account_recovery_key(&membership),
1086            Err(PendingMembershipError::MalformedUserKeyId)
1087        ));
1088    }
1089
1090    #[test]
1091    fn test_membership_without_an_upgrade_token_fails_with_missing_upgrade_token() {
1092        let organization = TestOrganization::new();
1093        let (mut membership, _) = organization.pending_membership();
1094        membership.v2_upgrade_token = None;
1095
1096        assert!(matches!(
1097            organization.make_new_account_recovery_key(&membership),
1098            Err(PendingMembershipError::MissingUpgradeToken)
1099        ));
1100    }
1101
1102    #[test]
1103    fn test_upgrade_token_without_a_wrapped_user_key_fails_with_malformed_upgrade_token() {
1104        let organization = TestOrganization::new();
1105        let (mut membership, _) = organization.pending_membership();
1106        membership
1107            .v2_upgrade_token
1108            .as_mut()
1109            .unwrap()
1110            .wrapped_user_key1 = None;
1111
1112        assert!(matches!(
1113            organization.make_new_account_recovery_key(&membership),
1114            Err(PendingMembershipError::MalformedUpgradeToken)
1115        ));
1116    }
1117
1118    #[test]
1119    fn test_membership_with_an_unparseable_account_recovery_key_fails_with_malformed_account_recovery_key()
1120     {
1121        let organization = TestOrganization::new();
1122        let (mut membership, _) = organization.pending_membership();
1123        membership.account_recovery_key = "not an enc string".to_string();
1124
1125        assert!(matches!(
1126            organization.make_new_account_recovery_key(&membership),
1127            Err(PendingMembershipError::MalformedAccountRecoveryKey)
1128        ));
1129    }
1130
1131    #[test]
1132    fn test_account_recovery_key_for_another_organization_fails_with_decapsulation_failed() {
1133        let organization = TestOrganization::new();
1134        let (mut membership, _) = organization.pending_membership();
1135        membership.account_recovery_key = TestOrganization::new()
1136            .pending_membership()
1137            .0
1138            .account_recovery_key;
1139
1140        assert!(matches!(
1141            organization.make_new_account_recovery_key(&membership),
1142            Err(PendingMembershipError::AccountRecoveryKeyDecapsulationFailed)
1143        ));
1144    }
1145
1146    #[test]
1147    fn test_upgrade_token_of_another_member_fails_with_upgrade_token_unwrap_failed() {
1148        let organization = TestOrganization::new();
1149        let (mut membership, _) = organization.pending_membership();
1150        membership.v2_upgrade_token = organization.pending_membership().0.v2_upgrade_token;
1151
1152        assert!(matches!(
1153            organization.make_new_account_recovery_key(&membership),
1154            Err(PendingMembershipError::UpgradeTokenUnwrapFailed)
1155        ));
1156    }
1157
1158    #[test]
1159    fn test_reported_key_id_of_another_key_fails_with_user_key_id_mismatch() {
1160        let organization = TestOrganization::new();
1161        let (mut membership, _) = organization.pending_membership();
1162        membership.user_key_id = UNRELATED_USER_KEY_ID.to_string();
1163
1164        assert!(matches!(
1165            organization.make_new_account_recovery_key(&membership),
1166            Err(PendingMembershipError::UserKeyIdMismatch)
1167        ));
1168    }
1169
1170    #[test]
1171    fn test_public_key_of_another_organization_fails_with_untrusted_public_key() {
1172        let organization = TestOrganization::new();
1173        let (membership, _) = organization.pending_membership();
1174        let other_organization_public_key = {
1175            let other_organization = TestOrganization::new();
1176            let mut ctx = other_organization.client.key_store.context();
1177            other_organization
1178                .organization_private_key(&mut ctx)
1179                .public_key(&ctx)
1180                .unwrap()
1181        };
1182        let mut ctx = organization.client.key_store.context();
1183        let organization_private_key = organization.organization_private_key(&mut ctx);
1184
1185        let result = make_new_account_recovery_key(
1186            &organization_private_key,
1187            &other_organization_public_key,
1188            &membership,
1189            &mut ctx,
1190        );
1191
1192        assert!(matches!(
1193            result,
1194            Err(PendingMembershipError::AccountRecoveryMakeFailed(
1195                AccountRecoveryMakeError::UntrustedPublicKey
1196            ))
1197        ));
1198    }
1199
1200    #[test]
1201    fn test_administering_needs_an_administering_role_and_an_unlocked_organization_key() {
1202        let organization = TestOrganization::new();
1203
1204        assert!(organization.client.can_administer_account_recovery_keys(
1205            organization.organization_id,
1206            &OrganizationUserType::Owner,
1207        ));
1208        // Same role, an organization whose key this account does not hold.
1209        assert!(!organization.client.can_administer_account_recovery_keys(
1210            OrganizationId::new_v4(),
1211            &OrganizationUserType::Owner,
1212        ));
1213        // Organization key present, role without account recovery permissions.
1214        assert!(!organization.client.can_administer_account_recovery_keys(
1215            organization.organization_id,
1216            &OrganizationUserType::User,
1217        ));
1218    }
1219
1220    #[test]
1221    fn test_owners_and_admins_hold_account_recovery_permissions() {
1222        for user_type in [OrganizationUserType::Owner, OrganizationUserType::Admin] {
1223            assert!(has_account_recovery_permissions(&user_type));
1224        }
1225    }
1226
1227    /// The server rejects custom members, whatever their permissions.
1228    #[test]
1229    fn test_custom_and_plain_members_cannot_administer_account_recovery_keys() {
1230        for user_type in [OrganizationUserType::Custom, OrganizationUserType::User] {
1231            assert!(!has_account_recovery_permissions(&user_type));
1232        }
1233    }
1234}