Skip to main content

bitwarden_organization_crypto_management/
key_id_backfill.rs

1//! Record organization key ids to the server for organizations where they were never captured.
2//!
3//! Key ids were introduced after organization keys, so organizations created before the server
4//! started tracking them hold a key whose id the server does not know about. Every member derives
5//! the same id from the organization key, but only Owners and Admins can record it.
6
7use bitwarden_api_api::models::SetOrganizationKeyIdRequest;
8use bitwarden_core::{OrganizationId, key_management::SymmetricKeySlotId};
9use bitwarden_crypto::KeyId;
10use bitwarden_error::bitwarden_error;
11use bitwarden_organizations::{OrganizationUserStatusType, OrganizationUserType};
12use bitwarden_state::repository::{RepositoryError, RepositoryOption};
13use thiserror::Error;
14use tracing::{error, info};
15
16use crate::OrganizationCryptoManagementClient;
17
18/// Errors returned by the organization key id backfill.
19#[derive(Debug, Error)]
20#[bitwarden_error(flat)]
21pub enum OrganizationKeyIdBackfillError {
22    /// The client is locked, so the organization keys are not available.
23    #[error("The client must be unlocked to backfill organization key ids")]
24    NotUnlocked,
25    /// The organization repository is not registered or could not be read.
26    #[error("Organization state is not available")]
27    OrganizationStateNotAvailable(#[from] RepositoryError),
28    /// One or more API calls failed. The other organizations were still attempted.
29    #[error("API call failed during organization key id backfill")]
30    Api,
31}
32
33#[bitwarden_ffi::wasm_export]
34impl OrganizationCryptoManagementClient {
35    /// Returns the organizations whose key id the server does not have, and that this account can
36    /// record the key id for.
37    ///
38    /// Returns [`OrganizationKeyIdBackfillError::NotUnlocked`] when the client is locked.
39    pub async fn organization_key_ids_needing_backfill(
40        &self,
41    ) -> Result<Vec<OrganizationId>, OrganizationKeyIdBackfillError> {
42        Ok(self
43            .backfill_targets()
44            .await?
45            .into_iter()
46            .map(|(organization_id, _)| organization_id)
47            .collect())
48    }
49
50    /// Records the key id of each organization key that the server does not have.
51    ///
52    /// A failure for one organization does not stop the others. Returns
53    /// [`OrganizationKeyIdBackfillError::Api`] when any organization failed. Makes no API calls
54    /// when no organization needs a backfill.
55    ///
56    /// Returns [`OrganizationKeyIdBackfillError::NotUnlocked`] when the client is locked.
57    pub async fn organization_key_id_backfill(&self) -> Result<(), OrganizationKeyIdBackfillError> {
58        let mut failed = false;
59
60        for (organization_id, key_id) in self.backfill_targets().await? {
61            info!(%organization_id, "Recording the organization key id with the server");
62            if let Err(e) = self
63                .api_configurations
64                .api_client
65                .organization_keys_api()
66                .set_organization_key_id(
67                    organization_id.into(),
68                    SetOrganizationKeyIdRequest {
69                        organization_key_id: key_id.to_string(),
70                    },
71                )
72                .await
73            {
74                // A 409 means the server holds a different key id for this organization.
75                error!(%organization_id, "Failed to post the organization key id: {e:?}");
76                failed = true;
77            }
78        }
79
80        if failed {
81            Err(OrganizationKeyIdBackfillError::Api)
82        } else {
83            Ok(())
84        }
85    }
86}
87
88impl OrganizationCryptoManagementClient {
89    /// Returns the organizations that need a backfill, each with the id of its organization key in
90    /// the key store.
91    async fn backfill_targets(
92        &self,
93    ) -> Result<Vec<(OrganizationId, KeyId)>, OrganizationKeyIdBackfillError> {
94        let organizations = self.repository.require()?.list().await?;
95
96        let ctx = self.key_store.context();
97        if !ctx.has_symmetric_key(SymmetricKeySlotId::User) {
98            return Err(OrganizationKeyIdBackfillError::NotUnlocked);
99        }
100
101        Ok(organizations
102            .into_iter()
103            // Only backfill if the org key id is not set on the server
104            .filter(|o| o.details.key_id.is_none())
105            // The server only authorizes confirmed Owners and Admins. It refuses custom users even
106            // with every permission, and provider users who are not members.
107            .filter(|o| {
108                o.membership.is_member
109                    && o.membership.status == OrganizationUserStatusType::Confirmed
110                    && matches!(
111                        o.membership.r#type,
112                        OrganizationUserType::Owner | OrganizationUserType::Admin
113                    )
114            })
115            // Without the organization key there is no key id to record.
116            .filter_map(|o| {
117                ctx.get_symmetric_key_id(SymmetricKeySlotId::Organization(o.details.id))
118                    .map(|key_id| (o.details.id, key_id))
119            })
120            .collect())
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use std::sync::{Arc, Mutex};
127
128    use bitwarden_api_api::apis::{ApiClient, ApiClientMock};
129    use bitwarden_core::client::ApiConfigurations;
130    use bitwarden_crypto::{KeyStore, SymmetricCryptoKey, SymmetricKeyAlgorithm};
131    use bitwarden_organizations::{
132        OrganizationDetails, OrganizationMembership, Permissions, ProfileOrganization,
133    };
134    use bitwarden_state::repository::Repository;
135    use bitwarden_test::MemoryRepository;
136
137    use super::*;
138
139    fn organization(user_type: OrganizationUserType) -> ProfileOrganization {
140        let default = ProfileOrganization::default();
141        ProfileOrganization {
142            details: OrganizationDetails {
143                id: OrganizationId::new_v4(),
144                ..default.details
145            },
146            membership: OrganizationMembership {
147                r#type: user_type,
148                ..default.membership
149            },
150            ..ProfileOrganization::default()
151        }
152    }
153
154    /// An unlocked client holding an organization key for each of `organization_ids`, with
155    /// `organizations` in its state and its API calls served by the configured mock.
156    async fn client(
157        organizations: &[ProfileOrganization],
158        organization_ids: &[OrganizationId],
159        configure: impl FnOnce(&mut ApiClientMock),
160    ) -> OrganizationCryptoManagementClient {
161        let repository = Arc::new(MemoryRepository::<ProfileOrganization>::default());
162        for organization in organizations {
163            repository
164                .set(organization.details.id, organization.clone())
165                .await
166                .expect("the repository is in memory");
167        }
168
169        let key_store = KeyStore::default();
170        {
171            let mut ctx = key_store.context_mut();
172            #[allow(deprecated)]
173            ctx.set_symmetric_key(
174                SymmetricKeySlotId::User,
175                SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
176            )
177            .expect("the context is mutable");
178            for organization_id in organization_ids {
179                #[allow(deprecated)]
180                ctx.set_symmetric_key(
181                    SymmetricKeySlotId::Organization(*organization_id),
182                    SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
183                )
184                .expect("the context is mutable");
185            }
186        }
187
188        OrganizationCryptoManagementClient {
189            key_store,
190            api_configurations: Arc::new(ApiConfigurations::from_api_client(
191                ApiClient::new_mocked(configure),
192            )),
193            repository: Some(repository),
194        }
195    }
196
197    /// An API configuration that fails the test if the key id is posted.
198    fn expect_no_posts(mock: &mut ApiClientMock) {
199        mock.organization_keys_api
200            .expect_set_organization_key_id()
201            .never();
202    }
203
204    fn organization_key_id(
205        client: &OrganizationCryptoManagementClient,
206        organization_id: OrganizationId,
207    ) -> String {
208        client
209            .key_store
210            .context()
211            .get_symmetric_key_id(SymmetricKeySlotId::Organization(organization_id))
212            .expect("an organization key has a key id")
213            .to_string()
214    }
215
216    async fn assert_backfill_posts_the_key_id(user_type: OrganizationUserType) {
217        let organization = organization(user_type);
218        let organization_id = organization.details.id;
219        // The posted id is checked against the key store's below, so the mock only records it.
220        let posted = Arc::new(Mutex::new(Vec::new()));
221        let recorder = posted.clone();
222        let client = client(&[organization], &[organization_id], |mock| {
223            mock.organization_keys_api
224                .expect_set_organization_key_id()
225                .once()
226                .returning(move |organization_id, body| {
227                    recorder.lock().unwrap().push((
228                        OrganizationId::new(organization_id),
229                        body.organization_key_id,
230                    ));
231                    Ok(())
232                });
233        })
234        .await;
235
236        assert_eq!(
237            client
238                .organization_key_ids_needing_backfill()
239                .await
240                .unwrap(),
241            vec![organization_id]
242        );
243        client.organization_key_id_backfill().await.unwrap();
244
245        assert_eq!(
246            *posted.lock().unwrap(),
247            vec![(
248                organization_id,
249                organization_key_id(&client, organization_id)
250            )]
251        );
252    }
253
254    #[tokio::test]
255    async fn test_backfill_posts_the_key_id_for_an_owner() {
256        assert_backfill_posts_the_key_id(OrganizationUserType::Owner).await;
257    }
258
259    #[tokio::test]
260    async fn test_backfill_posts_the_key_id_for_an_admin() {
261        assert_backfill_posts_the_key_id(OrganizationUserType::Admin).await;
262    }
263
264    /// Asserts that no organization needs a backfill, and that the backfill posts nothing.
265    async fn assert_nothing_to_backfill(
266        organizations: &[ProfileOrganization],
267        organization_ids: &[OrganizationId],
268    ) {
269        let client = client(organizations, organization_ids, expect_no_posts).await;
270
271        assert!(
272            client
273                .organization_key_ids_needing_backfill()
274                .await
275                .unwrap()
276                .is_empty()
277        );
278        client.organization_key_id_backfill().await.unwrap();
279    }
280
281    #[tokio::test]
282    async fn test_no_backfill_when_the_server_already_knows_the_key_id() {
283        let mut organization = organization(OrganizationUserType::Owner);
284        organization.details.key_id = Some(KeyId::make());
285        let organization_id = organization.details.id;
286
287        assert_nothing_to_backfill(&[organization], &[organization_id]).await;
288    }
289
290    #[tokio::test]
291    async fn test_no_backfill_for_custom_users_and_users() {
292        // The server rejects custom members, even with every permission.
293        let mut custom = organization(OrganizationUserType::Custom);
294        custom.membership.permissions = Permissions {
295            access_event_logs: true,
296            access_import_export: true,
297            access_reports: true,
298            create_new_collections: true,
299            edit_any_collection: true,
300            delete_any_collection: true,
301            manage_groups: true,
302            manage_sso: true,
303            manage_policies: true,
304            manage_users: true,
305            manage_reset_password: true,
306            manage_scim: true,
307            manage_access_rules: true,
308            manage_rotation: true,
309        };
310        let user = organization(OrganizationUserType::User);
311        let ids = [custom.details.id, user.details.id];
312
313        assert_nothing_to_backfill(&[custom, user], &ids).await;
314    }
315
316    #[tokio::test]
317    async fn test_no_backfill_for_provider_only_access() {
318        let mut organization = organization(OrganizationUserType::Owner);
319        organization.membership.is_member = false;
320        organization.membership.is_provider_user = true;
321        let organization_id = organization.details.id;
322
323        assert_nothing_to_backfill(&[organization], &[organization_id]).await;
324    }
325
326    #[tokio::test]
327    async fn test_no_backfill_for_a_revoked_owner() {
328        let mut organization = organization(OrganizationUserType::Owner);
329        organization.membership.status = OrganizationUserStatusType::Revoked;
330        let organization_id = organization.details.id;
331
332        assert_nothing_to_backfill(&[organization], &[organization_id]).await;
333    }
334
335    #[tokio::test]
336    async fn test_no_backfill_without_an_organization_key() {
337        let organization = organization(OrganizationUserType::Owner);
338
339        assert_nothing_to_backfill(&[organization], &[]).await;
340    }
341
342    #[tokio::test]
343    async fn test_a_failed_post_does_not_stop_the_other_organizations() {
344        let failing = organization(OrganizationUserType::Owner);
345        let succeeding = organization(OrganizationUserType::Admin);
346        let (failing_id, succeeding_id) = (failing.details.id, succeeding.details.id);
347
348        let client = client(
349            &[failing, succeeding],
350            &[failing_id, succeeding_id],
351            |mock| {
352                mock.organization_keys_api
353                    .expect_set_organization_key_id()
354                    .withf(move |org, _body| OrganizationId::new(*org) == failing_id)
355                    .returning(|_org, _body| {
356                        Err(bitwarden_api_api::apis::Error::Io(std::io::Error::other(
357                            "connection reset",
358                        )))
359                    })
360                    .once();
361                mock.organization_keys_api
362                    .expect_set_organization_key_id()
363                    .withf(move |org, _body| OrganizationId::new(*org) == succeeding_id)
364                    .returning(|_org, _body| Ok(()))
365                    .once();
366            },
367        )
368        .await;
369
370        assert!(matches!(
371            client.organization_key_id_backfill().await,
372            Err(OrganizationKeyIdBackfillError::Api)
373        ));
374    }
375
376    #[tokio::test]
377    async fn test_errors_without_an_organization_repository() {
378        let client = OrganizationCryptoManagementClient {
379            repository: None,
380            ..client(&[], &[], expect_no_posts).await
381        };
382
383        assert!(matches!(
384            client.organization_key_ids_needing_backfill().await,
385            Err(OrganizationKeyIdBackfillError::OrganizationStateNotAvailable(_))
386        ));
387        assert!(matches!(
388            client.organization_key_id_backfill().await,
389            Err(OrganizationKeyIdBackfillError::OrganizationStateNotAvailable(_))
390        ));
391    }
392
393    #[tokio::test]
394    async fn test_errors_when_the_client_is_locked() {
395        let organization = organization(OrganizationUserType::Owner);
396        let organization_id = organization.details.id;
397        let client = client(&[organization], &[organization_id], expect_no_posts).await;
398        client
399            .key_store
400            .context_mut()
401            .drop_symmetric_key(SymmetricKeySlotId::User)
402            .expect("the context is mutable");
403
404        assert!(matches!(
405            client.organization_key_ids_needing_backfill().await,
406            Err(OrganizationKeyIdBackfillError::NotUnlocked)
407        ));
408        assert!(matches!(
409            client.organization_key_id_backfill().await,
410            Err(OrganizationKeyIdBackfillError::NotUnlocked)
411        ));
412    }
413}