Skip to main content

bitwarden_auth/registration/
post_keys_for_tde_registration.rs

1//! Initializes a new cryptographic state for a user and posts it to the server; enrolls in
2//! admin password reset and finally enrolls the user to TDE unlock.
3use bitwarden_api_api::models::{
4    DeviceKeysRequestModel, KeysRequestModel, OrganizationUserResetPasswordEnrollmentRequestModel,
5    SsoJitProvisionFinishTrustedDeviceRequestModel,
6};
7use bitwarden_core::{
8    OrganizationId, UserId,
9    key_management::{
10        account_cryptographic_state::WrappedAccountCryptographicState,
11        crypto::MakeTdeRegistrationResponse,
12    },
13};
14use bitwarden_encoding::B64;
15use tracing::info;
16
17use crate::registration::{RegistrationClient, RegistrationError};
18
19/// Request parameters for TDE (Trusted Device Encryption) registration.
20#[bitwarden_ffi::wasm_record]
21#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
22#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
23pub struct TdeRegistrationRequest {
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    /// User ID for the account being initialized
30    pub user_id: UserId,
31    /// Device identifier for TDE enrollment
32    pub device_identifier: String,
33    /// Whether to trust this device for TDE
34    pub trust_device: bool,
35    /// Whether the server moves the pending organization membership from Invited to Accepted and
36    /// enrolls the user in admin account recovery. Send `false` for open-invite links so the
37    /// membership stays Invited for later Admin Console checks. Defaults to `true` when not set.
38    /// Only used when the `pm-34429-invite-link-auto-confirm` flag is on.
39    #[serde(default)]
40    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
41    #[cfg_attr(feature = "wasm", tsify(optional))]
42    pub accept_organization_invite: Option<bool>,
43}
44
45/// Result of TDE registration process.
46#[bitwarden_ffi::wasm_record]
47#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
48#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
49pub struct TdeRegistrationResponse {
50    /// The account cryptographic state of the user
51    pub account_cryptographic_state: WrappedAccountCryptographicState,
52    /// The device key
53    pub device_key: B64,
54    /// The decrypted user key. This can be used to get the consuming client to an unlocked state.
55    pub user_key: B64,
56}
57
58#[bitwarden_ffi::wasm_export]
59impl RegistrationClient {
60    /// Initializes a new cryptographic state for a user and posts it to the server; enrolls in
61    /// admin password reset and finally enrolls the user to TDE unlock.
62    pub async fn post_keys_for_tde_registration(
63        &self,
64        request: TdeRegistrationRequest,
65    ) -> Result<TdeRegistrationResponse, RegistrationError> {
66        let client = &self.client.internal;
67        let api_client = &client.get_api_configurations().api_client;
68        internal_post_keys_for_tde_registration(self, api_client, request).await
69    }
70}
71
72async fn internal_post_keys_for_tde_registration(
73    registration_client: &RegistrationClient,
74    api_client: &bitwarden_api_api::apis::ApiClient,
75    request: TdeRegistrationRequest,
76) -> Result<TdeRegistrationResponse, RegistrationError> {
77    // First call crypto API to get all keys
78    info!("Initializing account cryptography");
79    let tde_registration_crypto_result = registration_client
80        .client
81        .crypto()
82        .make_user_tde_registration(request.org_public_key.clone())
83        .map_err(|_| RegistrationError::Crypto)?;
84
85    // TODO: Remove the legacy flow when the pm-34429-invite-link-auto-confirm flag is removed
86    // with https://bitwarden.atlassian.net/browse/PM-40052
87    if registration_client
88        .client
89        .flags()
90        .get()
91        .await
92        .invite_link_auto_confirm
93    {
94        sso_jit_provision_finish_trusted_device(
95            api_client,
96            &request,
97            &tde_registration_crypto_result,
98        )
99        .await?;
100    } else {
101        legacy_post_keys_for_tde_registration(
102            api_client,
103            &request,
104            &tde_registration_crypto_result,
105        )
106        .await?;
107    }
108
109    info!("User initialized!");
110    // Note: This passing out of state and keys is temporary. Once SDK state management is more
111    // mature, the account cryptographic state and keys should be set directly here.
112    Ok(TdeRegistrationResponse {
113        account_cryptographic_state: tde_registration_crypto_result.account_cryptographic_state,
114        device_key: tde_registration_crypto_result
115            .trusted_device_keys
116            .device_key,
117        user_key: tde_registration_crypto_result
118            .user_key
119            .to_encoded()
120            .to_vec()
121            .into(),
122    })
123}
124
125/// Posts the keys and trusts the device in one request. The server reads the device from
126/// the access token, so `request.device_identifier` is not sent.
127async fn sso_jit_provision_finish_trusted_device(
128    api_client: &bitwarden_api_api::apis::ApiClient,
129    request: &TdeRegistrationRequest,
130    tde_registration_crypto_result: &MakeTdeRegistrationResponse,
131) -> Result<(), RegistrationError> {
132    let accept_organization_invite = request.accept_organization_invite.unwrap_or(true);
133    let api_request = SsoJitProvisionFinishTrustedDeviceRequestModel {
134        device_keys: request
135            .trust_device
136            .then(|| Box::new(make_device_keys_request(tde_registration_crypto_result))),
137        // The server enrolls in admin account recovery only when it accepts the invite, and then
138        // it requires the account recovery key.
139        account_recovery_key: accept_organization_invite.then(|| {
140            tde_registration_crypto_result
141                .reset_password_key
142                .to_string()
143        }),
144        ..SsoJitProvisionFinishTrustedDeviceRequestModel::new(
145            make_keys_request(tde_registration_crypto_result)?,
146            request.org_id.into(),
147            accept_organization_invite,
148        )
149    };
150    info!("Posting user account cryptographic state to server");
151    api_client
152        .sso_jit_provision_finish_api()
153        .finish_trusted_device(Some(api_request))
154        .await
155        .map_err(|e| {
156            tracing::error!("Failed to finish SSO JIT provisioning: {e:?}");
157            RegistrationError::Api
158        })
159}
160
161async fn legacy_post_keys_for_tde_registration(
162    api_client: &bitwarden_api_api::apis::ApiClient,
163    request: &TdeRegistrationRequest,
164    tde_registration_crypto_result: &MakeTdeRegistrationResponse,
165) -> Result<(), RegistrationError> {
166    // Post the generated keys to the API here. The user now has keys and is "registered", but
167    // has no unlock method.
168    let keys_request = make_keys_request(tde_registration_crypto_result)?;
169    info!("Posting user account cryptographic state to server");
170    api_client
171        .accounts_api()
172        .post_keys(Some(keys_request))
173        .await
174        .map_err(|e| {
175            tracing::error!("Failed to post account keys: {e:?}");
176            RegistrationError::Api
177        })?;
178
179    // Next, enroll the user for reset password using the reset password key generated above.
180    info!("Enrolling into admin account recovery");
181    api_client
182        .organization_users_api()
183        .put_reset_password_enrollment(
184            request.org_id.into(),
185            request.user_id.into(),
186            Some(OrganizationUserResetPasswordEnrollmentRequestModel {
187                reset_password_key: Some(
188                    tde_registration_crypto_result
189                        .reset_password_key
190                        .to_string(),
191                ),
192                master_password_hash: None,
193            }),
194        )
195        .await
196        .map_err(|e| {
197            tracing::error!("Failed to enroll for reset password: {e:?}");
198            RegistrationError::Api
199        })?;
200
201    if request.trust_device {
202        // Next, enroll the user for TDE unlock
203        info!("Enrolling into trusted device decryption");
204        api_client
205            .devices_api()
206            .put_keys(
207                request.device_identifier.as_str(),
208                Some(make_device_keys_request(tde_registration_crypto_result)),
209            )
210            .await
211            .map_err(|e| {
212                tracing::error!("Failed to enroll device for TDE: {e:?}");
213                RegistrationError::Api
214            })?;
215    }
216
217    Ok(())
218}
219
220fn make_keys_request(
221    tde_registration_crypto_result: &MakeTdeRegistrationResponse,
222) -> Result<KeysRequestModel, RegistrationError> {
223    Ok(KeysRequestModel {
224        account_keys: Some(Box::new(
225            tde_registration_crypto_result.account_keys_request.clone(),
226        )),
227        // Note: This property is deprecated and will be removed
228        public_key: tde_registration_crypto_result
229            .account_keys_request
230            .account_public_key
231            .clone()
232            .ok_or(RegistrationError::Crypto)?,
233        // Note: This property is deprecated and will be removed
234        encrypted_private_key: tde_registration_crypto_result
235            .account_keys_request
236            .user_key_encrypted_account_private_key
237            .clone()
238            .ok_or(RegistrationError::Crypto)?,
239        user_key_id: tde_registration_crypto_result
240            .user_key
241            .key_id()
242            .map(|id| id.to_string()),
243    })
244}
245
246fn make_device_keys_request(
247    tde_registration_crypto_result: &MakeTdeRegistrationResponse,
248) -> DeviceKeysRequestModel {
249    let trusted_device_keys = &tde_registration_crypto_result.trusted_device_keys;
250    DeviceKeysRequestModel {
251        encrypted_user_key: trusted_device_keys.protected_user_key.to_string(),
252        encrypted_public_key: trusted_device_keys.protected_device_public_key.to_string(),
253        encrypted_private_key: trusted_device_keys.protected_device_private_key.to_string(),
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use std::{collections::HashMap, str::FromStr};
260
261    use bitwarden_api_api::{
262        apis::ApiClient,
263        models::{DeviceResponseModel, KeysResponseModel},
264    };
265    use bitwarden_core::Client;
266    use bitwarden_crypto::{EncString, UnsignedSharedKey};
267
268    use super::*;
269
270    const TEST_USER_ID: &str = "060000fb-0922-4dd3-b170-6e15cb5df8c8";
271    const TEST_ORG_ID: &str = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8";
272    const TEST_DEVICE_ID: &str = "test-device-id";
273
274    const TEST_ORG_PUBLIC_KEY: &[u8] = &[
275        48, 130, 1, 34, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 130, 1, 15, 0,
276        48, 130, 1, 10, 2, 130, 1, 1, 0, 173, 4, 54, 63, 125, 12, 254, 38, 115, 34, 95, 164, 148,
277        115, 86, 140, 129, 74, 19, 70, 212, 212, 130, 163, 105, 249, 101, 120, 154, 46, 194, 250,
278        229, 242, 156, 67, 109, 179, 187, 134, 59, 235, 60, 107, 144, 163, 35, 22, 109, 230, 134,
279        243, 44, 243, 79, 84, 76, 11, 64, 56, 236, 167, 98, 26, 30, 213, 143, 105, 52, 92, 129, 92,
280        88, 22, 115, 135, 63, 215, 79, 8, 11, 183, 124, 10, 73, 231, 170, 110, 210, 178, 22, 100,
281        76, 75, 118, 202, 252, 204, 67, 204, 152, 6, 244, 208, 161, 146, 103, 225, 233, 239, 88,
282        195, 88, 150, 230, 111, 62, 142, 12, 157, 184, 155, 34, 84, 237, 111, 11, 97, 56, 152, 130,
283        14, 72, 123, 140, 47, 137, 5, 97, 166, 4, 147, 111, 23, 65, 78, 63, 208, 198, 50, 161, 39,
284        80, 143, 100, 194, 37, 252, 194, 53, 207, 166, 168, 250, 165, 121, 9, 207, 90, 36, 213,
285        211, 84, 255, 14, 205, 114, 135, 217, 137, 105, 232, 58, 169, 222, 10, 13, 138, 203, 16,
286        12, 122, 72, 227, 95, 160, 111, 54, 200, 198, 143, 156, 15, 143, 196, 50, 150, 204, 144,
287        255, 162, 248, 50, 28, 47, 66, 9, 83, 158, 67, 9, 50, 147, 174, 147, 200, 199, 238, 190,
288        248, 60, 114, 218, 32, 209, 120, 218, 17, 234, 14, 128, 192, 166, 33, 60, 73, 227, 108,
289        201, 41, 160, 81, 133, 171, 205, 221, 2, 3, 1, 0, 1,
290    ];
291
292    #[tokio::test]
293    async fn test_post_keys_for_tde_registration_success() {
294        let client = Client::new(None);
295        let registration_client = RegistrationClient::new(client);
296
297        let api_client = ApiClient::new_mocked(|mock| {
298            mock.accounts_api
299                .expect_post_keys()
300                .once()
301                .withf(|body| {
302                    let body = body.as_ref().unwrap();
303                    let account_keys = body.account_keys.as_ref().unwrap();
304                    assert_eq!(
305                        Some(&body.public_key),
306                        account_keys.account_public_key.as_ref()
307                    );
308                    assert_eq!(
309                        Some(&body.encrypted_private_key),
310                        account_keys.user_key_encrypted_account_private_key.as_ref()
311                    );
312                    assert!(EncString::from_str(&body.encrypted_private_key).is_ok());
313                    assert!(body.user_key_id.is_some());
314                    true
315                })
316                .returning(move |_body| {
317                    Ok(KeysResponseModel {
318                        object: None,
319                        key: None,
320                        public_key: None,
321                        private_key: None,
322                        account_keys: None,
323                    })
324                });
325            mock.organization_users_api
326                .expect_put_reset_password_enrollment()
327                .once()
328                .withf(|org_id, user_id, body| {
329                    assert_eq!(*org_id, uuid::uuid!(TEST_ORG_ID));
330                    assert_eq!(*user_id, uuid::uuid!(TEST_USER_ID));
331                    let body = body.as_ref().unwrap();
332                    assert!(
333                        UnsignedSharedKey::from_str(body.reset_password_key.as_ref().unwrap())
334                            .is_ok()
335                    );
336                    assert!(body.master_password_hash.is_none());
337                    true
338                })
339                .returning(move |_org_id, _user_id, _body| Ok(()));
340            mock.devices_api
341                .expect_put_keys()
342                .once()
343                .returning(move |_device_id, body| {
344                    let body = body.unwrap();
345                    assert!(UnsignedSharedKey::from_str(body.encrypted_user_key.as_str()).is_ok());
346                    assert!(matches!(
347                        EncString::from_str(body.encrypted_private_key.as_str()).unwrap(),
348                        EncString::Aes256Cbc_HmacSha256_B64 { .. }
349                    ));
350                    assert!(matches!(
351                        EncString::from_str(body.encrypted_public_key.as_str()).unwrap(),
352                        EncString::Cose_Encrypt0_B64 { .. }
353                    ));
354
355                    Ok(DeviceResponseModel {
356                        object: None,
357                        id: None,
358                        name: None,
359                        r#type: None,
360                        identifier: None,
361                        creation_date: None,
362                        last_activity_date: None,
363                        is_trusted: None,
364                        encrypted_user_key: None,
365                        encrypted_public_key: None,
366                    })
367                });
368        });
369
370        let request = TdeRegistrationRequest {
371            org_id: TEST_ORG_ID.parse().unwrap(),
372            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
373            user_id: TEST_USER_ID.parse().unwrap(),
374            device_identifier: TEST_DEVICE_ID.to_string(),
375            trust_device: true,
376            accept_organization_invite: Some(false),
377        };
378
379        let result =
380            internal_post_keys_for_tde_registration(&registration_client, &api_client, request)
381                .await;
382
383        assert!(result.is_ok());
384        // Assert that the mock expectations were met
385        if let ApiClient::Mock(mut mock) = api_client {
386            mock.accounts_api.checkpoint();
387            mock.organization_users_api.checkpoint();
388            mock.devices_api.checkpoint();
389        }
390    }
391
392    #[tokio::test]
393    async fn test_post_keys_for_tde_registration_trust_device_false() {
394        let client = Client::new(None);
395        let registration_client = RegistrationClient::new(client);
396
397        let api_client = ApiClient::new_mocked(|mock| {
398            mock.accounts_api
399                .expect_post_keys()
400                .once()
401                .returning(move |_body| {
402                    Ok(KeysResponseModel {
403                        object: None,
404                        key: None,
405                        public_key: None,
406                        private_key: None,
407                        account_keys: None,
408                    })
409                });
410            mock.organization_users_api
411                .expect_put_reset_password_enrollment()
412                .once()
413                .returning(move |_org_id, _user_id, _body| Ok(()));
414            // Explicitly expect that put_keys is never called when trust_device is false
415            mock.devices_api.expect_put_keys().never();
416        });
417
418        let request = TdeRegistrationRequest {
419            org_id: TEST_ORG_ID.parse().unwrap(),
420            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
421            user_id: TEST_USER_ID.parse().unwrap(),
422            device_identifier: TEST_DEVICE_ID.to_string(),
423            trust_device: false, // trust_device is false
424            accept_organization_invite: None,
425        };
426
427        let result =
428            internal_post_keys_for_tde_registration(&registration_client, &api_client, request)
429                .await;
430
431        assert!(result.is_ok());
432        // Assert that the mock expectations were met (put_keys should not have been called)
433        if let ApiClient::Mock(mut mock) = api_client {
434            mock.accounts_api.checkpoint();
435            mock.organization_users_api.checkpoint();
436            mock.devices_api.checkpoint();
437        }
438    }
439
440    #[tokio::test]
441    async fn test_post_keys_for_tde_registration_post_keys_failure() {
442        let client = Client::new(None);
443        let registration_client = RegistrationClient::new(client);
444
445        let api_client = ApiClient::new_mocked(|mock| {
446            mock.accounts_api
447                .expect_post_keys()
448                .once()
449                .returning(move |_body| {
450                    Err(serde_json::Error::io(std::io::Error::other("API error")).into())
451                });
452            // Subsequent API calls should not be made if post_keys fails
453            mock.organization_users_api
454                .expect_put_reset_password_enrollment()
455                .never();
456            mock.devices_api.expect_put_keys().never();
457        });
458
459        let request = TdeRegistrationRequest {
460            org_id: TEST_ORG_ID.parse().unwrap(),
461            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
462            user_id: TEST_USER_ID.parse().unwrap(),
463            device_identifier: TEST_DEVICE_ID.to_string(),
464            trust_device: true,
465            accept_organization_invite: None,
466        };
467
468        let result =
469            internal_post_keys_for_tde_registration(&registration_client, &api_client, request)
470                .await;
471
472        assert!(result.is_err());
473        assert!(matches!(result.unwrap_err(), RegistrationError::Api));
474
475        // Assert that the mock expectations were met
476        if let ApiClient::Mock(mut mock) = api_client {
477            mock.accounts_api.checkpoint();
478            mock.organization_users_api.checkpoint();
479            mock.devices_api.checkpoint();
480        }
481    }
482
483    #[tokio::test]
484    async fn test_post_keys_for_tde_registration_reset_password_enrollment_failure() {
485        let client = Client::new(None);
486        let registration_client = RegistrationClient::new(client);
487
488        let api_client = ApiClient::new_mocked(|mock| {
489            mock.accounts_api
490                .expect_post_keys()
491                .once()
492                .returning(move |_body| {
493                    Ok(KeysResponseModel {
494                        object: None,
495                        key: None,
496                        public_key: None,
497                        private_key: None,
498                        account_keys: None,
499                    })
500                });
501            mock.organization_users_api
502                .expect_put_reset_password_enrollment()
503                .once()
504                .returning(move |_org_id, _user_id, _body| {
505                    Err(serde_json::Error::io(std::io::Error::other("API error")).into())
506                });
507            // Device key enrollment should not be made if reset password enrollment fails
508            mock.devices_api.expect_put_keys().never();
509        });
510
511        let request = TdeRegistrationRequest {
512            org_id: TEST_ORG_ID.parse().unwrap(),
513            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
514            user_id: TEST_USER_ID.parse().unwrap(),
515            device_identifier: TEST_DEVICE_ID.to_string(),
516            trust_device: true,
517            accept_organization_invite: None,
518        };
519
520        let result =
521            internal_post_keys_for_tde_registration(&registration_client, &api_client, request)
522                .await;
523
524        assert!(result.is_err());
525        assert!(matches!(result.unwrap_err(), RegistrationError::Api));
526
527        // Assert that the mock expectations were met
528        if let ApiClient::Mock(mut mock) = api_client {
529            mock.accounts_api.checkpoint();
530            mock.organization_users_api.checkpoint();
531            mock.devices_api.checkpoint();
532        }
533    }
534
535    #[tokio::test]
536    async fn test_post_keys_for_tde_registration_device_keys_failure() {
537        let client = Client::new(None);
538        let registration_client = RegistrationClient::new(client);
539
540        let api_client = ApiClient::new_mocked(|mock| {
541            mock.accounts_api
542                .expect_post_keys()
543                .once()
544                .returning(move |_body| {
545                    Ok(KeysResponseModel {
546                        object: None,
547                        key: None,
548                        public_key: None,
549                        private_key: None,
550                        account_keys: None,
551                    })
552                });
553            mock.organization_users_api
554                .expect_put_reset_password_enrollment()
555                .once()
556                .returning(move |_org_id, _user_id, _body| Ok(()));
557            mock.devices_api
558                .expect_put_keys()
559                .once()
560                .returning(move |_device_id, _body| {
561                    Err(serde_json::Error::io(std::io::Error::other("API error")).into())
562                });
563        });
564
565        let request = TdeRegistrationRequest {
566            org_id: TEST_ORG_ID.parse().unwrap(),
567            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
568            user_id: TEST_USER_ID.parse().unwrap(),
569            device_identifier: TEST_DEVICE_ID.to_string(),
570            trust_device: true, // trust_device is true, so device enrollment should be attempted
571            accept_organization_invite: None,
572        };
573
574        let result =
575            internal_post_keys_for_tde_registration(&registration_client, &api_client, request)
576                .await;
577
578        assert!(result.is_err());
579        assert!(matches!(result.unwrap_err(), RegistrationError::Api));
580
581        // Assert that the mock expectations were met
582        if let ApiClient::Mock(mut mock) = api_client {
583            mock.accounts_api.checkpoint();
584            mock.organization_users_api.checkpoint();
585            mock.devices_api.checkpoint();
586        }
587    }
588
589    async fn client_with_invite_link_auto_confirm() -> Client {
590        let client = Client::new(None);
591        client
592            .flags()
593            .load(HashMap::from([(
594                "pm-34429-invite-link-auto-confirm".to_string(),
595                true,
596            )]))
597            .await;
598        client
599    }
600
601    fn sso_jit_tde_request(
602        trust_device: bool,
603        accept_organization_invite: Option<bool>,
604    ) -> TdeRegistrationRequest {
605        TdeRegistrationRequest {
606            org_id: TEST_ORG_ID.parse().unwrap(),
607            org_public_key: TEST_ORG_PUBLIC_KEY.into(),
608            user_id: TEST_USER_ID.parse().unwrap(),
609            device_identifier: TEST_DEVICE_ID.to_string(),
610            trust_device,
611            accept_organization_invite,
612        }
613    }
614
615    #[tokio::test]
616    async fn test_post_keys_for_tde_registration_invite_link_auto_confirm_success() {
617        // `None` defaults to accepting the invite.
618        for (trust_device, accept_organization_invite, expected_accept) in [
619            (true, None, true),
620            (false, None, true),
621            (true, Some(true), true),
622            (true, Some(false), false),
623            (false, Some(false), false),
624        ] {
625            let client = client_with_invite_link_auto_confirm().await;
626            let registration_client = RegistrationClient::new(client);
627
628            let api_client = ApiClient::new_mocked(|mock| {
629                mock.sso_jit_provision_finish_api
630                    .expect_finish_trusted_device()
631                    .once()
632                    .withf(move |body| {
633                        let req = body.as_ref().unwrap();
634                        assert_eq!(req.organization_id, uuid::uuid!(TEST_ORG_ID));
635                        assert_eq!(req.accept_organization_invite, expected_accept);
636                        let account_keys = req.keys.account_keys.as_ref().unwrap();
637                        assert_eq!(
638                            Some(&req.keys.public_key),
639                            account_keys.account_public_key.as_ref()
640                        );
641                        assert_eq!(
642                            Some(&req.keys.encrypted_private_key),
643                            account_keys.user_key_encrypted_account_private_key.as_ref()
644                        );
645                        assert!(EncString::from_str(&req.keys.encrypted_private_key).is_ok());
646                        assert!(req.keys.user_key_id.is_some());
647                        if let Some(account_recovery_key) = &req.account_recovery_key {
648                            assert!(UnsignedSharedKey::from_str(account_recovery_key).is_ok());
649                        }
650                        assert_eq!(req.account_recovery_key.is_some(), expected_accept);
651                        assert_eq!(req.device_keys.is_some(), trust_device);
652                        if let Some(device_keys) = &req.device_keys {
653                            assert!(
654                                UnsignedSharedKey::from_str(
655                                    device_keys.encrypted_user_key.as_str()
656                                )
657                                .is_ok()
658                            );
659                            assert!(matches!(
660                                EncString::from_str(device_keys.encrypted_private_key.as_str())
661                                    .unwrap(),
662                                EncString::Aes256Cbc_HmacSha256_B64 { .. }
663                            ));
664                            assert!(matches!(
665                                EncString::from_str(device_keys.encrypted_public_key.as_str())
666                                    .unwrap(),
667                                EncString::Cose_Encrypt0_B64 { .. }
668                            ));
669                        }
670                        true
671                    })
672                    .returning(move |_body| Ok(()));
673                // The new endpoint replaces these three calls
674                mock.accounts_api.expect_post_keys().never();
675                mock.organization_users_api
676                    .expect_put_reset_password_enrollment()
677                    .never();
678                mock.devices_api.expect_put_keys().never();
679            });
680
681            let result = internal_post_keys_for_tde_registration(
682                &registration_client,
683                &api_client,
684                sso_jit_tde_request(trust_device, accept_organization_invite),
685            )
686            .await;
687
688            assert!(result.is_ok());
689            // Assert that the mock expectations were met
690            if let ApiClient::Mock(mut mock) = api_client {
691                mock.sso_jit_provision_finish_api.checkpoint();
692                mock.accounts_api.checkpoint();
693                mock.organization_users_api.checkpoint();
694                mock.devices_api.checkpoint();
695            }
696        }
697    }
698
699    #[tokio::test]
700    async fn test_post_keys_for_tde_registration_invite_link_auto_confirm_api_failure() {
701        let client = client_with_invite_link_auto_confirm().await;
702        let registration_client = RegistrationClient::new(client);
703
704        let api_client = ApiClient::new_mocked(|mock| {
705            mock.sso_jit_provision_finish_api
706                .expect_finish_trusted_device()
707                .once()
708                .returning(move |_body| {
709                    Err(serde_json::Error::io(std::io::Error::other("API error")).into())
710                });
711        });
712
713        let result = internal_post_keys_for_tde_registration(
714            &registration_client,
715            &api_client,
716            sso_jit_tde_request(true, None),
717        )
718        .await;
719
720        assert!(matches!(result.unwrap_err(), RegistrationError::Api));
721
722        // Assert that the mock expectations were met
723        if let ApiClient::Mock(mut mock) = api_client {
724            mock.sso_jit_provision_finish_api.checkpoint();
725        }
726    }
727}