Skip to main content

bitwarden_auth/registration/
post_keys_for_key_connector_registration.rs

1//! Initializes a new cryptographic state for a user and posts it to the server; enrolls the
2//! user to key connector unlock.
3use bitwarden_api_api::models::{
4    SetKeyConnectorKeyRequestModel, SsoJitProvisionFinishSetKeyConnectorKeyRequestModel,
5};
6use bitwarden_core::key_management::account_cryptographic_state::WrappedAccountCryptographicState;
7use bitwarden_crypto::EncString;
8use bitwarden_encoding::B64;
9use tracing::{error, info};
10
11use crate::registration::{RegistrationClient, RegistrationError};
12
13/// Result of Key Connector registration process.
14#[bitwarden_ffi::wasm_record]
15#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
16#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
17pub struct KeyConnectorRegistrationResult {
18    /// The account cryptographic state of the user.
19    pub account_cryptographic_state: WrappedAccountCryptographicState,
20    /// The key connector key used for unlocking.
21    pub key_connector_key: B64,
22    /// The encrypted user key, wrapped with the key connector key.
23    pub key_connector_key_wrapped_user_key: EncString,
24    /// The decrypted user key. This can be used to get the consuming client to an unlocked state.
25    pub user_key: B64,
26}
27
28#[bitwarden_ffi::wasm_export]
29impl RegistrationClient {
30    /// Initializes a new cryptographic state for a user and posts it to the server; enrolls the
31    /// user to key connector unlock.
32    ///
33    /// `accept_organization_invite` controls whether the server moves the organization
34    /// membership from Invited to Accepted. Send `false` for open-invite links so the membership
35    /// stays Invited for later Admin Console checks. Defaults to `true` when not set. Only used
36    /// when the `pm-34429-invite-link-auto-confirm` flag is on.
37    pub async fn post_keys_for_key_connector_registration(
38        &self,
39        key_connector_url: String,
40        sso_org_identifier: String,
41        accept_organization_invite: Option<bool>,
42    ) -> Result<KeyConnectorRegistrationResult, RegistrationError> {
43        let client = &self.client.internal;
44        let configuration = &client.get_api_configurations();
45        let key_connector_client = client.get_key_connector_client(key_connector_url);
46
47        internal_post_keys_for_key_connector_registration(
48            self,
49            &configuration.api_client,
50            &key_connector_client,
51            sso_org_identifier,
52            accept_organization_invite,
53        )
54        .await
55    }
56}
57
58async fn internal_post_keys_for_key_connector_registration(
59    registration_client: &RegistrationClient,
60    api_client: &bitwarden_api_api::apis::ApiClient,
61    key_connector_api_client: &bitwarden_api_key_connector::apis::ApiClient,
62    sso_org_identifier: String,
63    accept_organization_invite: Option<bool>,
64) -> Result<KeyConnectorRegistrationResult, RegistrationError> {
65    // First call crypto API to get all keys
66    info!("Initializing account cryptography");
67    let registration_crypto_result = registration_client
68        .client
69        .crypto()
70        .make_user_key_connector_registration()
71        .map_err(|_| RegistrationError::Crypto)?;
72
73    info!("Posting key connector key to key connector server");
74    let key_connector_key: B64 = registration_crypto_result.key_connector_key.into();
75    post_key_to_key_connector(key_connector_api_client, &key_connector_key).await?;
76
77    info!("Posting user account cryptographic state to server");
78    let request = SetKeyConnectorKeyRequestModel {
79        key_connector_key_wrapped_user_key: Some(
80            registration_crypto_result
81                .key_connector_key_wrapped_user_key
82                .to_string(),
83        ),
84        account_keys: Some(Box::new(registration_crypto_result.account_keys_request)),
85        ..SetKeyConnectorKeyRequestModel::new(sso_org_identifier.to_string())
86    };
87    // TODO: Remove the legacy flow when the pm-34429-invite-link-auto-confirm flag is removed
88    // with https://bitwarden.atlassian.net/browse/PM-40052
89    let response = if registration_client
90        .client
91        .flags()
92        .get()
93        .await
94        .invite_link_auto_confirm
95    {
96        api_client
97            .sso_jit_provision_finish_api()
98            .finish_jit_provision_for_key_connector(Some(
99                SsoJitProvisionFinishSetKeyConnectorKeyRequestModel::new(
100                    request,
101                    accept_organization_invite.unwrap_or(true),
102                ),
103            ))
104            .await
105    } else {
106        api_client
107            .accounts_key_management_api()
108            .post_set_key_connector_key(Some(request))
109            .await
110    };
111    response.map_err(|e| {
112        error!("Failed to post account cryptographic state to server: {e:?}");
113        RegistrationError::Api
114    })?;
115
116    info!("User initialized!");
117    // Note: This passing out of state and keys is temporary. Once SDK state management is more
118    // mature, the account cryptographic state and keys should be set directly here.
119    Ok(KeyConnectorRegistrationResult {
120        account_cryptographic_state: registration_crypto_result.account_cryptographic_state,
121        key_connector_key,
122        key_connector_key_wrapped_user_key: registration_crypto_result
123            .key_connector_key_wrapped_user_key,
124        user_key: registration_crypto_result.user_key.to_encoded().into(),
125    })
126}
127
128async fn post_key_to_key_connector(
129    key_connector_api_client: &bitwarden_api_key_connector::apis::ApiClient,
130    key_connector_key: &B64,
131) -> Result<(), RegistrationError> {
132    let request =
133        bitwarden_api_key_connector::models::user_key_request_model::UserKeyKeyRequestModel {
134            key: key_connector_key.to_string(),
135        };
136
137    let result = if key_connector_api_client
138        .user_keys_api()
139        .get_user_key()
140        .await
141        .is_ok()
142    {
143        info!("User's key connector key exists, updating");
144        key_connector_api_client
145            .user_keys_api()
146            .put_user_key(request)
147            .await
148    } else {
149        info!("User's key connector key does not exist, creating");
150        key_connector_api_client
151            .user_keys_api()
152            .post_user_key(request)
153            .await
154    };
155
156    result.map_err(|e| {
157        error!("Failed to post key connector key to key connector server: {e:?}");
158        RegistrationError::KeyConnectorApi
159    })
160}
161
162#[cfg(test)]
163mod tests {
164    use std::collections::HashMap;
165
166    use bitwarden_api_api::apis::ApiClient;
167    use bitwarden_core::Client;
168
169    use super::*;
170
171    const TEST_SSO_ORG_IDENTIFIER: &str = "test-org";
172
173    #[tokio::test]
174    async fn test_post_keys_for_key_connector_registration_success() {
175        let client = Client::new(None);
176        let registration_client = RegistrationClient::new(client);
177
178        let api_client = ApiClient::new_mocked(|mock| {
179            mock.accounts_key_management_api
180                .expect_post_set_key_connector_key()
181                .once()
182                .returning(move |_body| Ok(()));
183        });
184
185        let key_connector_api_client =
186            bitwarden_api_key_connector::apis::ApiClient::new_mocked(|mock| {
187                mock.user_keys_api
188                    .expect_get_user_key()
189                    .once()
190                    .returning(move || {
191                        Err(bitwarden_api_key_connector::apis::Error::ResponseError(
192                            bitwarden_api_key_connector::apis::ResponseContent {
193                                status: reqwest::StatusCode::NOT_FOUND,
194                                content: "Not Found".to_string(),
195                            },
196                        ))
197                    });
198                mock.user_keys_api
199                    .expect_post_user_key()
200                    .once()
201                    .returning(move |_body| Ok(()));
202            });
203
204        let result = internal_post_keys_for_key_connector_registration(
205            &registration_client,
206            &api_client,
207            &key_connector_api_client,
208            TEST_SSO_ORG_IDENTIFIER.to_string(),
209            Some(false),
210        )
211        .await;
212        assert!(result.is_ok());
213
214        // Assert that the mock expectations were met
215        if let ApiClient::Mock(mut mock) = api_client {
216            mock.accounts_key_management_api.checkpoint();
217        }
218        if let bitwarden_api_key_connector::apis::ApiClient::Mock(mut mock) =
219            key_connector_api_client
220        {
221            mock.user_keys_api.checkpoint();
222        }
223    }
224
225    #[tokio::test]
226    async fn test_post_keys_for_key_connector_registration_key_connector_api_failure() {
227        let client = Client::new(None);
228        let registration_client = RegistrationClient::new(client);
229
230        let api_client = ApiClient::new_mocked(|mock| {
231            // Should not be called if Key Connector API fails
232            mock.accounts_key_management_api
233                .expect_post_set_key_connector_key()
234                .never();
235        });
236
237        let key_connector_api_client =
238            bitwarden_api_key_connector::apis::ApiClient::new_mocked(|mock| {
239                mock.user_keys_api
240                    .expect_get_user_key()
241                    .once()
242                    .returning(move || {
243                        Err(bitwarden_api_key_connector::apis::Error::ResponseError(
244                            bitwarden_api_key_connector::apis::ResponseContent {
245                                status: reqwest::StatusCode::NOT_FOUND,
246                                content: "Not Found".to_string(),
247                            },
248                        ))
249                    });
250                mock.user_keys_api
251                    .expect_post_user_key()
252                    .once()
253                    .returning(move |_body| {
254                        Err(bitwarden_api_key_connector::apis::Error::Serde(
255                            serde_json::Error::io(std::io::Error::other("API error")),
256                        ))
257                    });
258            });
259
260        let result = internal_post_keys_for_key_connector_registration(
261            &registration_client,
262            &api_client,
263            &key_connector_api_client,
264            TEST_SSO_ORG_IDENTIFIER.to_string(),
265            None,
266        )
267        .await;
268
269        assert!(result.is_err());
270        assert!(matches!(
271            result.unwrap_err(),
272            RegistrationError::KeyConnectorApi
273        ));
274
275        // Assert that the mock expectations were met
276        if let ApiClient::Mock(mut mock) = api_client {
277            mock.accounts_key_management_api.checkpoint();
278        }
279        if let bitwarden_api_key_connector::apis::ApiClient::Mock(mut mock) =
280            key_connector_api_client
281        {
282            mock.user_keys_api.checkpoint();
283        }
284    }
285
286    #[tokio::test]
287    async fn test_post_keys_for_key_connector_registration_api_failure() {
288        let client = Client::new(None);
289        let registration_client = RegistrationClient::new(client);
290
291        let api_client = ApiClient::new_mocked(|mock| {
292            mock.accounts_key_management_api
293                .expect_post_set_key_connector_key()
294                .once()
295                .returning(move |_body| {
296                    Err(serde_json::Error::io(std::io::Error::other("API error")).into())
297                });
298        });
299
300        let key_connector_api_client =
301            bitwarden_api_key_connector::apis::ApiClient::new_mocked(|mock| {
302                mock.user_keys_api
303                    .expect_get_user_key()
304                    .once()
305                    .returning(move || {
306                        Err(bitwarden_api_key_connector::apis::Error::ResponseError(
307                            bitwarden_api_key_connector::apis::ResponseContent {
308                                status: reqwest::StatusCode::NOT_FOUND,
309                                content: "Not Found".to_string(),
310                            },
311                        ))
312                    });
313                mock.user_keys_api
314                    .expect_post_user_key()
315                    .once()
316                    .returning(move |_body| Ok(()));
317            });
318
319        let result = internal_post_keys_for_key_connector_registration(
320            &registration_client,
321            &api_client,
322            &key_connector_api_client,
323            TEST_SSO_ORG_IDENTIFIER.to_string(),
324            None,
325        )
326        .await;
327
328        assert!(result.is_err());
329        assert!(matches!(result.unwrap_err(), RegistrationError::Api));
330
331        // Assert that the mock expectations were met
332        if let ApiClient::Mock(mut mock) = api_client {
333            mock.accounts_key_management_api.checkpoint();
334        }
335        if let bitwarden_api_key_connector::apis::ApiClient::Mock(mut mock) =
336            key_connector_api_client
337        {
338            mock.user_keys_api.checkpoint();
339        }
340    }
341
342    async fn client_with_invite_link_auto_confirm() -> Client {
343        let client = Client::new(None);
344        client
345            .flags()
346            .load(HashMap::from([(
347                "pm-34429-invite-link-auto-confirm".to_string(),
348                true,
349            )]))
350            .await;
351        client
352    }
353
354    fn key_connector_api_client_not_found() -> bitwarden_api_key_connector::apis::ApiClient {
355        bitwarden_api_key_connector::apis::ApiClient::new_mocked(|mock| {
356            mock.user_keys_api
357                .expect_get_user_key()
358                .once()
359                .returning(move || {
360                    Err(bitwarden_api_key_connector::apis::Error::ResponseError(
361                        bitwarden_api_key_connector::apis::ResponseContent {
362                            status: reqwest::StatusCode::NOT_FOUND,
363                            content: "Not Found".to_string(),
364                        },
365                    ))
366                });
367            mock.user_keys_api
368                .expect_post_user_key()
369                .once()
370                .returning(move |_body| Ok(()));
371        })
372    }
373
374    #[tokio::test]
375    async fn test_post_keys_for_key_connector_registration_invite_link_auto_confirm_success() {
376        // `None` defaults to accepting the invite.
377        for (accept_organization_invite, expected_accept) in
378            [(None, true), (Some(true), true), (Some(false), false)]
379        {
380            let client = client_with_invite_link_auto_confirm().await;
381            let registration_client = RegistrationClient::new(client);
382
383            let api_client = ApiClient::new_mocked(|mock| {
384                mock.sso_jit_provision_finish_api
385                    .expect_finish_jit_provision_for_key_connector()
386                    .once()
387                    .withf(move |body| {
388                        let req = body.as_ref().unwrap();
389                        assert_eq!(req.accept_organization_invite, expected_accept);
390                        assert_eq!(
391                            req.key_connector_keys.org_identifier,
392                            TEST_SSO_ORG_IDENTIFIER
393                        );
394                        assert!(
395                            req.key_connector_keys
396                                .key_connector_key_wrapped_user_key
397                                .is_some()
398                        );
399                        assert!(req.key_connector_keys.account_keys.is_some());
400                        true
401                    })
402                    .returning(move |_body| Ok(()));
403                mock.accounts_key_management_api
404                    .expect_post_set_key_connector_key()
405                    .never();
406            });
407            let key_connector_api_client = key_connector_api_client_not_found();
408
409            let result = internal_post_keys_for_key_connector_registration(
410                &registration_client,
411                &api_client,
412                &key_connector_api_client,
413                TEST_SSO_ORG_IDENTIFIER.to_string(),
414                accept_organization_invite,
415            )
416            .await;
417            assert!(result.is_ok());
418
419            // Assert that the mock expectations were met
420            if let ApiClient::Mock(mut mock) = api_client {
421                mock.sso_jit_provision_finish_api.checkpoint();
422                mock.accounts_key_management_api.checkpoint();
423            }
424            if let bitwarden_api_key_connector::apis::ApiClient::Mock(mut mock) =
425                key_connector_api_client
426            {
427                mock.user_keys_api.checkpoint();
428            }
429        }
430    }
431
432    #[tokio::test]
433    async fn test_post_keys_for_key_connector_registration_invite_link_auto_confirm_api_failure() {
434        let client = client_with_invite_link_auto_confirm().await;
435        let registration_client = RegistrationClient::new(client);
436
437        let api_client = ApiClient::new_mocked(|mock| {
438            mock.sso_jit_provision_finish_api
439                .expect_finish_jit_provision_for_key_connector()
440                .once()
441                .returning(move |_body| {
442                    Err(serde_json::Error::io(std::io::Error::other("API error")).into())
443                });
444        });
445        let key_connector_api_client = key_connector_api_client_not_found();
446
447        let result = internal_post_keys_for_key_connector_registration(
448            &registration_client,
449            &api_client,
450            &key_connector_api_client,
451            TEST_SSO_ORG_IDENTIFIER.to_string(),
452            None,
453        )
454        .await;
455
456        assert!(matches!(result.unwrap_err(), RegistrationError::Api));
457
458        // Assert that the mock expectations were met
459        if let ApiClient::Mock(mut mock) = api_client {
460            mock.sso_jit_provision_finish_api.checkpoint();
461        }
462    }
463}