Skip to main content

bitwarden_auth/registration/
post_keys_for_jit_password_registration.rs

1//! Initializes a new cryptographic state for a user and posts it to the server;
2//! enrolls the user to master password unlock.
3use bitwarden_api_api::models::{
4    OrganizationUserResetPasswordEnrollmentRequestModel, SetInitialPasswordRequestModel,
5    SsoJitProvisionFinishPasswordRequestModel,
6};
7use bitwarden_core::{
8    OrganizationId, UserId,
9    key_management::{
10        MasterPasswordUnlockData, account_cryptographic_state::WrappedAccountCryptographicState,
11        crypto::MakeJitMasterPasswordRegistrationResponse,
12    },
13};
14use bitwarden_encoding::B64;
15use tracing::{error, info};
16
17use crate::registration::{RegistrationClient, RegistrationError};
18
19/// Request parameters for SSO JIT master password registration.
20#[bitwarden_ffi::wasm_record]
21#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
22#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
23pub struct JitMasterPasswordRegistrationRequest {
24    /// Organization ID to enroll in
25    pub org_id: OrganizationId,
26    /// Organization's public key for encrypting the reset password key. This should be verified by
27    /// the client and not verifying may compromise the security of the user's account.
28    pub org_public_key: B64,
29    /// Organization SSO identifier
30    pub organization_sso_identifier: String,
31    /// User ID for the account being initialized
32    pub user_id: UserId,
33    /// Salt for master password hashing, usually email
34    pub salt: String,
35    /// Master password for the account
36    pub master_password: String,
37    /// Optional hint for the master password
38    pub master_password_hint: Option<String>,
39    /// Should enroll user into admin password reset
40    pub reset_password_enroll: bool,
41    /// Whether the server moves the pending organization membership from Invited to Accepted and
42    /// the user is enrolled in admin account recovery. Send `false` for open-invite links so the
43    /// membership stays Invited and is Accepted by the client after successful registration.
44    /// This also skips account recovery enrollment, even when `reset_password_enroll` is `true`.
45    /// Defaults to `true` when not set. Only used when the
46    /// `pm-34429-invite-link-auto-confirm` flag is on.
47    #[serde(default)]
48    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
49    #[cfg_attr(feature = "wasm", tsify(optional))]
50    pub accept_organization_invite: Option<bool>,
51}
52
53/// Result of JIT master password registration process.
54#[bitwarden_ffi::wasm_record]
55#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
56#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
57pub struct JitMasterPasswordRegistrationResponse {
58    /// The account cryptographic state of the user
59    pub account_cryptographic_state: WrappedAccountCryptographicState,
60    /// The master password unlock data
61    pub master_password_unlock: MasterPasswordUnlockData,
62    /// The decrypted user key.
63    pub user_key: B64,
64}
65
66#[bitwarden_ffi::wasm_export]
67impl RegistrationClient {
68    /// Initializes a new cryptographic state for a user and posts it to the server;
69    /// enrolls the user to master password unlock.
70    pub async fn post_keys_for_jit_password_registration(
71        &self,
72        request: JitMasterPasswordRegistrationRequest,
73    ) -> Result<JitMasterPasswordRegistrationResponse, RegistrationError> {
74        let client = &self.client.internal;
75        let api_client = &client.get_api_configurations().api_client;
76        internal_post_keys_for_jit_password_registration(self, api_client, request).await
77    }
78}
79
80async fn internal_post_keys_for_jit_password_registration(
81    registration_client: &RegistrationClient,
82    api_client: &bitwarden_api_api::apis::ApiClient,
83    mut request: JitMasterPasswordRegistrationRequest,
84) -> Result<JitMasterPasswordRegistrationResponse, RegistrationError> {
85    // First call crypto API to get all keys
86    info!("Initializing account cryptography");
87    let registration_crypto_result = registration_client
88        .client
89        .crypto()
90        .make_user_jit_master_password_registration(
91            // Take the password out of the request instead of cloning it, so no second copy of
92            // it is made.
93            std::mem::take(&mut request.master_password),
94            request.salt.clone(),
95            request.org_public_key.clone(),
96        )
97        .map_err(|_| RegistrationError::Crypto)?;
98
99    // TODO: Remove the legacy flow when the pm-34429-invite-link-auto-confirm flag is removed
100    // with https://bitwarden.atlassian.net/browse/PM-40052
101    if registration_client
102        .client
103        .flags()
104        .get()
105        .await
106        .invite_link_auto_confirm
107    {
108        sso_jit_provision_finish_password(api_client, &request, &registration_crypto_result)
109            .await?;
110    } else {
111        legacy_post_keys_for_jit_password_registration(
112            api_client,
113            &request,
114            &registration_crypto_result,
115        )
116        .await?;
117    }
118
119    info!("User initialized!");
120    // Note: This passing out of state and keys is temporary. Once SDK state management is more
121    // mature, the account cryptographic state and keys should be set directly here.
122    Ok(JitMasterPasswordRegistrationResponse {
123        account_cryptographic_state: registration_crypto_result.account_cryptographic_state,
124        master_password_unlock: registration_crypto_result.master_password_unlock_data,
125        user_key: registration_crypto_result
126            .user_key
127            .to_encoded()
128            .to_vec()
129            .into(),
130    })
131}
132
133async fn legacy_post_keys_for_jit_password_registration(
134    api_client: &bitwarden_api_api::apis::ApiClient,
135    request: &JitMasterPasswordRegistrationRequest,
136    registration_crypto_result: &MakeJitMasterPasswordRegistrationResponse,
137) -> Result<(), RegistrationError> {
138    // Post the generated keys to the API here. The user now has keys and is "registered", but
139    // has no unlock method.
140    let api_request = SetInitialPasswordRequestModel {
141        account_keys: Some(Box::new(
142            registration_crypto_result.account_keys_request.clone(),
143        )),
144        master_password_unlock: Some(Box::new(
145            (&registration_crypto_result.master_password_unlock_data).into(),
146        )),
147        master_password_authentication: Some(Box::new(
148            (&registration_crypto_result.master_password_authentication_data).into(),
149        )),
150        master_password_hint: request.master_password_hint.clone(),
151        org_identifier: request.organization_sso_identifier.clone(),
152        // TODO Deprecated fields below, to be removed with https://bitwarden.atlassian.net/browse/PM-27327
153        kdf_parallelism: None,
154        master_password_hash: None,
155        key: None,
156        keys: None,
157        kdf: None,
158        kdf_iterations: None,
159        kdf_memory: None,
160    };
161    info!("Posting user account cryptographic state to server");
162    api_client
163        .accounts_api()
164        .post_set_password(Some(api_request))
165        .await
166        .map_err(|e| {
167            error!("Failed to post account keys: {e:?}");
168            RegistrationError::Api
169        })?;
170
171    // Enroll the user for reset password using the reset password key generated above.
172    if request.reset_password_enroll {
173        enroll_in_account_recovery(
174            api_client,
175            request.org_id,
176            request.user_id,
177            registration_crypto_result,
178        )
179        .await?;
180    }
181
182    Ok(())
183}
184
185async fn sso_jit_provision_finish_password(
186    api_client: &bitwarden_api_api::apis::ApiClient,
187    request: &JitMasterPasswordRegistrationRequest,
188    registration_crypto_result: &MakeJitMasterPasswordRegistrationResponse,
189) -> Result<(), RegistrationError> {
190    let accept_organization_invite = request.accept_organization_invite.unwrap_or(true);
191    let api_request = SsoJitProvisionFinishPasswordRequestModel {
192        account_keys: Some(Box::new(
193            registration_crypto_result.account_keys_request.clone(),
194        )),
195        master_password_hint: request.master_password_hint.clone(),
196        ..SsoJitProvisionFinishPasswordRequestModel::new(
197            (&registration_crypto_result.master_password_authentication_data).into(),
198            (&registration_crypto_result.master_password_unlock_data).into(),
199            request.organization_sso_identifier.clone(),
200            accept_organization_invite,
201        )
202    };
203    info!("Posting user account cryptographic state to server");
204    api_client
205        .sso_jit_provision_finish_api()
206        .finish_jit_provision_for_password(Some(api_request))
207        .await
208        .map_err(|e| {
209            error!("Failed to finish SSO JIT provisioning: {e:?}");
210            RegistrationError::Api
211        })?;
212
213    // Enrollment accepts the invite, so skip it when the membership must stay Invited.
214    if accept_organization_invite && request.reset_password_enroll {
215        enroll_in_account_recovery(
216            api_client,
217            request.org_id,
218            request.user_id,
219            registration_crypto_result,
220        )
221        .await?;
222    }
223
224    Ok(())
225}
226
227/// Enrolls the user into admin account recovery with the reset password key generated during
228/// registration.
229async fn enroll_in_account_recovery(
230    api_client: &bitwarden_api_api::apis::ApiClient,
231    org_id: OrganizationId,
232    user_id: UserId,
233    registration_crypto_result: &MakeJitMasterPasswordRegistrationResponse,
234) -> Result<(), RegistrationError> {
235    info!("Enrolling into admin account recovery");
236    api_client
237        .organization_users_api()
238        .put_reset_password_enrollment(
239            org_id.into(),
240            user_id.into(),
241            Some(OrganizationUserResetPasswordEnrollmentRequestModel {
242                reset_password_key: Some(registration_crypto_result.reset_password_key.to_string()),
243                master_password_hash: Some(
244                    registration_crypto_result
245                        .master_password_authentication_data
246                        .master_password_authentication_hash
247                        .to_string(),
248                ),
249            }),
250        )
251        .await
252        .map_err(|e| {
253            error!("Failed to enroll for reset password: {e:?}");
254            RegistrationError::Api
255        })
256}
257
258#[cfg(test)]
259mod tests {
260    use std::{collections::HashMap, num::NonZeroU32, str::FromStr};
261
262    use bitwarden_api_api::{
263        apis::ApiClient,
264        models::{KdfRequestModel, KdfType},
265    };
266    use bitwarden_core::Client;
267    use bitwarden_crypto::{EncString, Kdf, UnsignedSharedKey};
268
269    use super::*;
270
271    const TEST_USER_ID: &str = "060000fb-0922-4dd3-b170-6e15cb5df8c8";
272    const TEST_ORG_ID: &str = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8";
273    const TEST_SSO_ORG_IDENTIFIER: &str = "test-org";
274
275    const TEST_ORG_PUBLIC_KEY: &[u8] = &[
276        48, 130, 1, 34, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 130, 1, 15, 0,
277        48, 130, 1, 10, 2, 130, 1, 1, 0, 173, 4, 54, 63, 125, 12, 254, 38, 115, 34, 95, 164, 148,
278        115, 86, 140, 129, 74, 19, 70, 212, 212, 130, 163, 105, 249, 101, 120, 154, 46, 194, 250,
279        229, 242, 156, 67, 109, 179, 187, 134, 59, 235, 60, 107, 144, 163, 35, 22, 109, 230, 134,
280        243, 44, 243, 79, 84, 76, 11, 64, 56, 236, 167, 98, 26, 30, 213, 143, 105, 52, 92, 129, 92,
281        88, 22, 115, 135, 63, 215, 79, 8, 11, 183, 124, 10, 73, 231, 170, 110, 210, 178, 22, 100,
282        76, 75, 118, 202, 252, 204, 67, 204, 152, 6, 244, 208, 161, 146, 103, 225, 233, 239, 88,
283        195, 88, 150, 230, 111, 62, 142, 12, 157, 184, 155, 34, 84, 237, 111, 11, 97, 56, 152, 130,
284        14, 72, 123, 140, 47, 137, 5, 97, 166, 4, 147, 111, 23, 65, 78, 63, 208, 198, 50, 161, 39,
285        80, 143, 100, 194, 37, 252, 194, 53, 207, 166, 168, 250, 165, 121, 9, 207, 90, 36, 213,
286        211, 84, 255, 14, 205, 114, 135, 217, 137, 105, 232, 58, 169, 222, 10, 13, 138, 203, 16,
287        12, 122, 72, 227, 95, 160, 111, 54, 200, 198, 143, 156, 15, 143, 196, 50, 150, 204, 144,
288        255, 162, 248, 50, 28, 47, 66, 9, 83, 158, 67, 9, 50, 147, 174, 147, 200, 199, 238, 190,
289        248, 60, 114, 218, 32, 209, 120, 218, 17, 234, 14, 128, 192, 166, 33, 60, 73, 227, 108,
290        201, 41, 160, 81, 133, 171, 205, 221, 2, 3, 1, 0, 1,
291    ];
292
293    #[tokio::test]
294    async fn test_post_keys_for_jit_password_registration_success() {
295        let client = Client::new(None);
296        let registration_client = RegistrationClient::new(client);
297
298        let expected_hint = "test hint";
299
300        let api_client = ApiClient::new_mocked(|mock| {
301            mock.accounts_api
302                .expect_post_set_password()
303                .once()
304                .withf(move |body| {
305                    if let Some(req) = body {
306                        assert_eq!(req.org_identifier, TEST_SSO_ORG_IDENTIFIER);
307                        assert_eq!(req.master_password_hint, Some(expected_hint.to_string()));
308                        assert!(req.account_keys.is_some());
309                        let account_keys = req.account_keys.as_ref().unwrap();
310                        assert!(
311                            account_keys
312                                .user_key_encrypted_account_private_key
313                                .is_some()
314                        );
315                        assert!(account_keys.account_public_key.is_some());
316                        assert!(account_keys.public_key_encryption_key_pair.is_some());
317                        let public_key_encryption_key_pair = account_keys
318                            .public_key_encryption_key_pair
319                            .as_ref()
320                            .unwrap();
321                        assert!(public_key_encryption_key_pair.public_key.is_some());
322                        assert!(public_key_encryption_key_pair.signed_public_key.is_some());
323                        assert!(public_key_encryption_key_pair.wrapped_private_key.is_some());
324                        assert!(account_keys.signature_key_pair.is_some());
325                        let signature_key_pair = account_keys.signature_key_pair.as_ref().unwrap();
326                        assert_eq!(
327                            signature_key_pair.signature_algorithm,
328                            Some("mldsa44".to_string())
329                        );
330                        assert!(signature_key_pair.verifying_key.is_some());
331                        assert!(signature_key_pair.wrapped_signing_key.is_some());
332                        assert!(account_keys.security_state.is_some());
333                        let security_state = account_keys.security_state.as_ref().unwrap();
334                        assert!(security_state.security_state.is_some());
335                        assert_eq!(security_state.security_version, 2);
336                        assert!(req.master_password_unlock.is_some());
337                        let master_password_unlock = req.master_password_unlock.as_ref().unwrap();
338                        assert_eq!(master_password_unlock.salt, "[email protected]".to_string());
339                        assert_eq!(
340                            master_password_unlock.kdf,
341                            Box::new(KdfRequestModel {
342                                kdf_type: KdfType::Argon2id,
343                                iterations: 6,
344                                memory: Some(32),
345                                parallelism: Some(4),
346                            })
347                        );
348                        assert!(req.master_password_authentication.is_some());
349                        let master_password_authentication =
350                            req.master_password_authentication.as_ref().unwrap();
351                        assert_eq!(
352                            master_password_authentication.salt,
353                            "[email protected]".to_string()
354                        );
355                        assert_eq!(
356                            master_password_authentication.kdf,
357                            Box::new(KdfRequestModel {
358                                kdf_type: KdfType::Argon2id,
359                                iterations: 6,
360                                memory: Some(32),
361                                parallelism: Some(4),
362                            })
363                        );
364                        true
365                    } else {
366                        false
367                    }
368                })
369                .returning(move |_body| Ok(()));
370            mock.organization_users_api
371                .expect_put_reset_password_enrollment()
372                .once()
373                .withf(move |org_id, user_id, body| {
374                    assert_eq!(*org_id, uuid::uuid!(TEST_ORG_ID));
375                    assert_eq!(*user_id, uuid::uuid!(TEST_USER_ID));
376                    if let Some(enrollment_request) = body {
377                        assert!(
378                            UnsignedSharedKey::from_str(
379                                enrollment_request.reset_password_key.as_ref().unwrap()
380                            )
381                            .is_ok()
382                        );
383                        assert!(
384                            B64::from_str(
385                                enrollment_request.master_password_hash.as_ref().unwrap()
386                            )
387                            .is_ok()
388                        );
389                        true
390                    } else {
391                        false
392                    }
393                })
394                .returning(move |_org_id, _user_id, _body| Ok(()));
395        });
396
397        let request = JitMasterPasswordRegistrationRequest {
398            org_id: TEST_ORG_ID.parse().unwrap(),
399            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
400            organization_sso_identifier: TEST_SSO_ORG_IDENTIFIER.to_string(),
401            user_id: TEST_USER_ID.parse().unwrap(),
402            salt: "[email protected]".to_string(),
403            master_password: "test-password-123".to_string(),
404            master_password_hint: Some(expected_hint.to_string()),
405            reset_password_enroll: true,
406            accept_organization_invite: Some(false),
407        };
408
409        let result = internal_post_keys_for_jit_password_registration(
410            &registration_client,
411            &api_client,
412            request,
413        )
414        .await;
415
416        assert!(result.is_ok());
417        let result = result.unwrap();
418        assert!(matches!(
419            result.account_cryptographic_state,
420            WrappedAccountCryptographicState::V2 { .. }
421        ));
422        assert_eq!(result.master_password_unlock.salt, "[email protected]");
423        assert!(matches!(
424            result.master_password_unlock.master_key_wrapped_user_key,
425            EncString::Aes256Cbc_HmacSha256_B64 { .. }
426        ));
427        assert_eq!(
428            result.master_password_unlock.kdf,
429            Kdf::Argon2id {
430                iterations: NonZeroU32::new(6).unwrap(),
431                memory: NonZeroU32::new(32).unwrap(),
432                parallelism: NonZeroU32::new(4).unwrap(),
433            }
434        );
435
436        // Assert that the mock expectations were met
437        if let ApiClient::Mock(mut mock) = api_client {
438            mock.accounts_api.checkpoint();
439            mock.organization_users_api.checkpoint();
440        }
441    }
442
443    #[tokio::test]
444    async fn test_post_keys_for_jit_password_registration_api_failure() {
445        let client = Client::new(None);
446        let registration_client = RegistrationClient::new(client);
447
448        let api_client = ApiClient::new_mocked(|mock| {
449            mock.accounts_api
450                .expect_post_set_password()
451                .once()
452                .returning(move |_body| {
453                    Err(serde_json::Error::io(std::io::Error::other("API error")).into())
454                });
455            mock.organization_users_api
456                .expect_put_reset_password_enrollment()
457                .never();
458        });
459
460        let request = JitMasterPasswordRegistrationRequest {
461            org_id: TEST_ORG_ID.parse().unwrap(),
462            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
463            organization_sso_identifier: TEST_SSO_ORG_IDENTIFIER.to_string(),
464            user_id: TEST_USER_ID.parse().unwrap(),
465            salt: "[email protected]".to_string(),
466            master_password: "test-password-123".to_string(),
467            master_password_hint: Some("test hint".to_string()),
468            reset_password_enroll: true,
469            accept_organization_invite: None,
470        };
471
472        let result = internal_post_keys_for_jit_password_registration(
473            &registration_client,
474            &api_client,
475            request,
476        )
477        .await;
478
479        assert!(result.is_err());
480        assert!(matches!(result.unwrap_err(), RegistrationError::Api));
481
482        // Assert that the mock expectations were met
483        if let ApiClient::Mock(mut mock) = api_client {
484            mock.accounts_api.checkpoint();
485            mock.organization_users_api.checkpoint();
486        }
487    }
488
489    #[tokio::test]
490    async fn test_post_keys_for_jit_password_registration_reset_password_enrollment_failure() {
491        let client = Client::new(None);
492        let registration_client = RegistrationClient::new(client);
493
494        let api_client = ApiClient::new_mocked(|mock| {
495            mock.accounts_api
496                .expect_post_set_password()
497                .once()
498                .returning(move |_body| Ok(()));
499            mock.organization_users_api
500                .expect_put_reset_password_enrollment()
501                .once()
502                .returning(move |_org_id, _user_id, _body| {
503                    Err(serde_json::Error::io(std::io::Error::other("API error")).into())
504                });
505        });
506
507        let request = JitMasterPasswordRegistrationRequest {
508            org_id: TEST_ORG_ID.parse().unwrap(),
509            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
510            organization_sso_identifier: TEST_SSO_ORG_IDENTIFIER.to_string(),
511            user_id: TEST_USER_ID.parse().unwrap(),
512            salt: "[email protected]".to_string(),
513            master_password: "test-password-123".to_string(),
514            master_password_hint: Some("test hint".to_string()),
515            reset_password_enroll: true,
516            accept_organization_invite: None,
517        };
518
519        let result = internal_post_keys_for_jit_password_registration(
520            &registration_client,
521            &api_client,
522            request,
523        )
524        .await;
525
526        assert!(result.is_err());
527        assert!(matches!(result.unwrap_err(), RegistrationError::Api));
528
529        // Assert that the mock expectations were met
530        if let ApiClient::Mock(mut mock) = api_client {
531            mock.accounts_api.checkpoint();
532            mock.organization_users_api.checkpoint();
533        }
534    }
535
536    #[tokio::test]
537    async fn test_post_keys_for_jit_password_registration_reset_password_enroll_false() {
538        let client = Client::new(None);
539        let registration_client = RegistrationClient::new(client);
540
541        let api_client = ApiClient::new_mocked(|mock| {
542            mock.accounts_api
543                .expect_post_set_password()
544                .once()
545                .returning(move |_body| Ok(()));
546            mock.organization_users_api
547                .expect_put_reset_password_enrollment()
548                .never();
549        });
550
551        let request = JitMasterPasswordRegistrationRequest {
552            org_id: TEST_ORG_ID.parse().unwrap(),
553            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
554            organization_sso_identifier: TEST_SSO_ORG_IDENTIFIER.to_string(),
555            user_id: TEST_USER_ID.parse().unwrap(),
556            salt: "[email protected]".to_string(),
557            master_password: "test-password-123".to_string(),
558            master_password_hint: Some("test hint".to_string()),
559            reset_password_enroll: false,
560            accept_organization_invite: None,
561        };
562
563        let result = internal_post_keys_for_jit_password_registration(
564            &registration_client,
565            &api_client,
566            request,
567        )
568        .await;
569
570        assert!(result.is_ok());
571
572        // Assert that the mock expectations were met
573        if let ApiClient::Mock(mut mock) = api_client {
574            mock.accounts_api.checkpoint();
575            mock.organization_users_api.checkpoint();
576        }
577    }
578
579    async fn client_with_invite_link_auto_confirm() -> Client {
580        let client = Client::new(None);
581        client
582            .flags()
583            .load(HashMap::from([(
584                "pm-34429-invite-link-auto-confirm".to_string(),
585                true,
586            )]))
587            .await;
588        client
589    }
590
591    fn sso_jit_password_request(
592        reset_password_enroll: bool,
593        accept_organization_invite: Option<bool>,
594    ) -> JitMasterPasswordRegistrationRequest {
595        JitMasterPasswordRegistrationRequest {
596            org_id: TEST_ORG_ID.parse().unwrap(),
597            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
598            organization_sso_identifier: TEST_SSO_ORG_IDENTIFIER.to_string(),
599            user_id: TEST_USER_ID.parse().unwrap(),
600            salt: "[email protected]".to_string(),
601            master_password: "test-password-123".to_string(),
602            master_password_hint: Some("test hint".to_string()),
603            reset_password_enroll,
604            accept_organization_invite,
605        }
606    }
607
608    /// Runs the invite-link-auto-confirm flow and checks the accept value sent to the server and
609    /// whether account recovery enrollment is called.
610    async fn assert_sso_jit_password_flow(
611        request: JitMasterPasswordRegistrationRequest,
612        expected_accept: bool,
613        expect_enrollment: bool,
614    ) {
615        let client = client_with_invite_link_auto_confirm().await;
616        let registration_client = RegistrationClient::new(client);
617
618        let api_client = ApiClient::new_mocked(|mock| {
619            mock.sso_jit_provision_finish_api
620                .expect_finish_jit_provision_for_password()
621                .once()
622                .withf(move |body| {
623                    let req = body.as_ref().unwrap();
624                    assert_eq!(req.org_identifier, TEST_SSO_ORG_IDENTIFIER);
625                    assert_eq!(req.master_password_hint, Some("test hint".to_string()));
626                    assert_eq!(req.accept_organization_invite, expected_accept);
627                    assert!(req.account_keys.is_some());
628                    assert!(req.keys.is_none());
629                    assert_eq!(req.master_password_unlock.salt, "[email protected]");
630                    assert_eq!(req.master_password_authentication.salt, "[email protected]");
631                    let expected_kdf = Box::new(KdfRequestModel {
632                        kdf_type: KdfType::Argon2id,
633                        iterations: 6,
634                        memory: Some(32),
635                        parallelism: Some(4),
636                    });
637                    assert_eq!(req.master_password_unlock.kdf, expected_kdf);
638                    assert_eq!(req.master_password_authentication.kdf, expected_kdf);
639                    true
640                })
641                .returning(move |_body| Ok(()));
642            mock.accounts_api.expect_post_set_password().never();
643            mock.organization_users_api
644                .expect_put_reset_password_enrollment()
645                .times(usize::from(expect_enrollment))
646                .withf(move |org_id, user_id, body| {
647                    assert_eq!(*org_id, uuid::uuid!(TEST_ORG_ID));
648                    assert_eq!(*user_id, uuid::uuid!(TEST_USER_ID));
649                    let enrollment_request = body.as_ref().unwrap();
650                    assert!(
651                        UnsignedSharedKey::from_str(
652                            enrollment_request.reset_password_key.as_ref().unwrap()
653                        )
654                        .is_ok()
655                    );
656                    assert!(
657                        B64::from_str(enrollment_request.master_password_hash.as_ref().unwrap())
658                            .is_ok()
659                    );
660                    true
661                })
662                .returning(move |_org_id, _user_id, _body| Ok(()));
663        });
664
665        let result = internal_post_keys_for_jit_password_registration(
666            &registration_client,
667            &api_client,
668            request,
669        )
670        .await;
671
672        let result = result.unwrap();
673        assert!(matches!(
674            result.account_cryptographic_state,
675            WrappedAccountCryptographicState::V2 { .. }
676        ));
677        assert_eq!(result.master_password_unlock.salt, "[email protected]");
678
679        // Assert that the mock expectations were met
680        if let ApiClient::Mock(mut mock) = api_client {
681            mock.sso_jit_provision_finish_api.checkpoint();
682            mock.accounts_api.checkpoint();
683            mock.organization_users_api.checkpoint();
684        }
685    }
686
687    #[tokio::test]
688    async fn test_post_keys_for_jit_password_registration_invite_link_auto_confirm_accept_defaults_to_true()
689     {
690        assert_sso_jit_password_flow(sso_jit_password_request(true, None), true, true).await;
691    }
692
693    #[tokio::test]
694    async fn test_post_keys_for_jit_password_registration_invite_link_auto_confirm_accept_true_enrolls()
695     {
696        assert_sso_jit_password_flow(sso_jit_password_request(true, Some(true)), true, true).await;
697    }
698
699    #[tokio::test]
700    async fn test_post_keys_for_jit_password_registration_invite_link_auto_confirm_accept_true_reset_password_enroll_false()
701     {
702        assert_sso_jit_password_flow(sso_jit_password_request(false, Some(true)), true, false)
703            .await;
704    }
705
706    #[tokio::test]
707    async fn test_post_keys_for_jit_password_registration_invite_link_auto_confirm_accept_false_skips_enrollment()
708     {
709        // Enrollment would accept the invite, so it is skipped even when requested
710        assert_sso_jit_password_flow(sso_jit_password_request(true, Some(false)), false, false)
711            .await;
712    }
713
714    #[tokio::test]
715    async fn test_post_keys_for_jit_password_registration_invite_link_auto_confirm_enrollment_failure()
716     {
717        let client = client_with_invite_link_auto_confirm().await;
718        let registration_client = RegistrationClient::new(client);
719
720        let api_client = ApiClient::new_mocked(|mock| {
721            mock.sso_jit_provision_finish_api
722                .expect_finish_jit_provision_for_password()
723                .once()
724                .returning(move |_body| Ok(()));
725            mock.organization_users_api
726                .expect_put_reset_password_enrollment()
727                .once()
728                .returning(move |_org_id, _user_id, _body| {
729                    Err(serde_json::Error::io(std::io::Error::other("API error")).into())
730                });
731        });
732
733        let result = internal_post_keys_for_jit_password_registration(
734            &registration_client,
735            &api_client,
736            sso_jit_password_request(true, Some(true)),
737        )
738        .await;
739
740        assert!(matches!(result.unwrap_err(), RegistrationError::Api));
741
742        // Assert that the mock expectations were met
743        if let ApiClient::Mock(mut mock) = api_client {
744            mock.sso_jit_provision_finish_api.checkpoint();
745            mock.organization_users_api.checkpoint();
746        }
747    }
748
749    #[tokio::test]
750    async fn test_post_keys_for_jit_password_registration_invite_link_auto_confirm_api_failure() {
751        let client = client_with_invite_link_auto_confirm().await;
752        let registration_client = RegistrationClient::new(client);
753
754        let api_client = ApiClient::new_mocked(|mock| {
755            mock.sso_jit_provision_finish_api
756                .expect_finish_jit_provision_for_password()
757                .once()
758                .returning(move |_body| {
759                    Err(serde_json::Error::io(std::io::Error::other("API error")).into())
760                });
761        });
762
763        let result = internal_post_keys_for_jit_password_registration(
764            &registration_client,
765            &api_client,
766            sso_jit_password_request(true, None),
767        )
768        .await;
769
770        assert!(matches!(result.unwrap_err(), RegistrationError::Api));
771
772        // Assert that the mock expectations were met
773        if let ApiClient::Mock(mut mock) = api_client {
774            mock.sso_jit_provision_finish_api.checkpoint();
775        }
776    }
777}