Skip to main content

bitwarden_pam/access_rules/
client.rs

1use std::sync::Arc;
2
3use bitwarden_core::{FromClient, OrganizationId, client::ApiConfigurations};
4
5use super::{
6    error::AccessRuleError,
7    models::{AccessRuleAddEditRequest, AccessRuleView},
8    validate::validate_request,
9};
10use crate::AccessRuleId;
11
12/// Client for PAM access rule CRUD operations.
13///
14/// Every operation, reads included, requires authority over the organization's access rules (an
15/// Owner, an Admin, or a Custom user who can manage access rules); the server answers anyone else
16/// with `403`. To tell whether a collection is gated, read its `has_enabled_access_rule` instead.
17#[bitwarden_ffi::wasm_object]
18#[derive(FromClient)]
19pub struct AccessRulesClient {
20    pub(crate) api_configurations: Arc<ApiConfigurations>,
21}
22
23#[bitwarden_ffi::wasm_export]
24impl AccessRulesClient {
25    /// Lists all access rules for an organization.
26    pub async fn list(
27        &self,
28        organization_id: OrganizationId,
29    ) -> Result<Vec<AccessRuleView>, AccessRuleError> {
30        let response = self
31            .api_configurations
32            .api_client
33            .access_rules_api()
34            .get_all(organization_id.into())
35            .await?;
36
37        response
38            .data
39            .unwrap_or_default()
40            .into_iter()
41            .map(AccessRuleView::try_from)
42            .collect()
43    }
44
45    /// Retrieves a single access rule by ID. Fails with
46    /// [`NotFound`](AccessRuleError::NotFound) for a rule not visible to the caller.
47    pub async fn get(
48        &self,
49        organization_id: OrganizationId,
50        id: AccessRuleId,
51    ) -> Result<AccessRuleView, AccessRuleError> {
52        let response = self
53            .api_configurations
54            .api_client
55            .access_rules_api()
56            .get(organization_id.into(), id.into())
57            .await
58            .map_err(AccessRuleError::from_api_error)?;
59
60        AccessRuleView::try_from(response)
61    }
62
63    /// Validates and creates a new access rule.
64    pub async fn create(
65        &self,
66        organization_id: OrganizationId,
67        request: AccessRuleAddEditRequest,
68    ) -> Result<AccessRuleView, AccessRuleError> {
69        validate_request(&request)?;
70
71        let response = self
72            .api_configurations
73            .api_client
74            .access_rules_api()
75            .post(organization_id.into(), request.try_into()?)
76            .await?;
77
78        AccessRuleView::try_from(response)
79    }
80
81    /// Validates and updates an existing access rule. Fails with
82    /// [`NotFound`](AccessRuleError::NotFound) for a rule deleted before the write landed.
83    pub async fn update(
84        &self,
85        organization_id: OrganizationId,
86        id: AccessRuleId,
87        request: AccessRuleAddEditRequest,
88    ) -> Result<AccessRuleView, AccessRuleError> {
89        validate_request(&request)?;
90
91        let response = self
92            .api_configurations
93            .api_client
94            .access_rules_api()
95            .put(organization_id.into(), id.into(), request.try_into()?)
96            .await
97            .map_err(AccessRuleError::from_api_error)?;
98
99        AccessRuleView::try_from(response)
100    }
101
102    /// Enables or disables a rule; no other field changes.
103    ///
104    /// Takes the rule as the caller already holds it, saving a read before the write.
105    pub async fn set_enabled(
106        &self,
107        organization_id: OrganizationId,
108        rule: AccessRuleView,
109        enabled: bool,
110    ) -> Result<AccessRuleView, AccessRuleError> {
111        let id = rule.id;
112        let request = AccessRuleAddEditRequest {
113            enabled,
114            ..rule.into()
115        };
116
117        self.update(organization_id, id, request).await
118    }
119
120    /// Deletes an access rule. Fails with [`NotFound`](AccessRuleError::NotFound) for an
121    /// already-gone rule.
122    pub async fn delete(
123        &self,
124        organization_id: OrganizationId,
125        id: AccessRuleId,
126    ) -> Result<(), AccessRuleError> {
127        self.api_configurations
128            .api_client
129            .access_rules_api()
130            .delete(organization_id.into(), id.into())
131            .await
132            .map_err(AccessRuleError::from_api_error)?;
133
134        Ok(())
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use bitwarden_api_api::{apis::ApiClient, models::AccessRuleResponseModel};
141    use uuid::uuid;
142
143    use super::*;
144    use crate::AccessCondition;
145
146    fn org_id() -> OrganizationId {
147        OrganizationId::new(uuid!("11111111-1111-1111-1111-111111111111"))
148    }
149
150    fn rule_id() -> AccessRuleId {
151        AccessRuleId::new(uuid!("22222222-2222-2222-2222-222222222222"))
152    }
153
154    fn client(api_client: ApiClient) -> AccessRulesClient {
155        AccessRulesClient {
156            api_configurations: Arc::new(ApiConfigurations::from_api_client(api_client)),
157        }
158    }
159
160    fn sample_response(id: uuid::Uuid, organization_id: uuid::Uuid) -> AccessRuleResponseModel {
161        let mut response = AccessRuleResponseModel::new();
162        response.id = Some(id);
163        response.organization_id = Some(organization_id);
164        response.name = Some("My rule".to_string());
165        response.conditions = Some(serde_json::json!([]));
166        response.creation_date = Some("2025-01-01T00:00:00Z".to_string());
167        response.revision_date = Some("2025-01-01T00:00:00Z".to_string());
168        response
169    }
170
171    fn sample_request() -> AccessRuleAddEditRequest {
172        AccessRuleAddEditRequest {
173            name: "My rule".to_string(),
174            description: None,
175            enabled: true,
176            conditions: vec![AccessCondition::HumanApproval],
177            single_active_lease: false,
178            default_lease_duration_seconds: None,
179            max_lease_duration_seconds: None,
180            allows_extensions: false,
181            max_extension_duration_seconds: None,
182            collections: Vec::new(),
183        }
184    }
185
186    #[tokio::test]
187    async fn list_returns_views() {
188        let organization_id = org_id();
189        let rule = rule_id();
190        let response = sample_response(rule.into(), organization_id.into());
191
192        let api_client = ApiClient::new_mocked(move |mock| {
193            mock.access_rules_api
194                .expect_get_all()
195                .returning(move |_org_id| {
196                    let mut list_response =
197                        bitwarden_api_api::models::AccessRuleResponseModelListResponseModel::new();
198                    list_response.data = Some(vec![response.clone()]);
199                    Ok(list_response)
200                })
201                .once();
202        });
203
204        let result = client(api_client).list(organization_id).await.unwrap();
205
206        assert_eq!(result.len(), 1);
207        assert_eq!(result[0].id, rule);
208    }
209
210    #[tokio::test]
211    async fn get_returns_view() {
212        let organization_id = org_id();
213        let rule = rule_id();
214        let response = sample_response(rule.into(), organization_id.into());
215
216        let api_client = ApiClient::new_mocked(move |mock| {
217            mock.access_rules_api
218                .expect_get()
219                .returning(move |_org_id, _id| Ok(response.clone()))
220                .once();
221        });
222
223        let result = client(api_client).get(organization_id, rule).await.unwrap();
224
225        assert_eq!(result.id, rule);
226    }
227
228    fn api_error(status: reqwest::StatusCode) -> bitwarden_api_api::ApiError {
229        bitwarden_api_api::ApiError::Response(bitwarden_api_api::ResponseContent {
230            status,
231            message: String::new(),
232        })
233    }
234
235    #[tokio::test]
236    async fn get_maps_not_found_to_not_found() {
237        let organization_id = org_id();
238        let rule = rule_id();
239
240        let api_client = ApiClient::new_mocked(move |mock| {
241            mock.access_rules_api
242                .expect_get()
243                .returning(move |_org_id, _id| Err(api_error(reqwest::StatusCode::NOT_FOUND)))
244                .once();
245        });
246
247        let result = client(api_client).get(organization_id, rule).await;
248
249        assert!(matches!(result, Err(AccessRuleError::NotFound)));
250    }
251
252    #[tokio::test]
253    async fn get_surfaces_other_api_errors_as_api() {
254        let organization_id = org_id();
255        let rule = rule_id();
256
257        let api_client = ApiClient::new_mocked(move |mock| {
258            mock.access_rules_api
259                .expect_get()
260                .returning(move |_org_id, _id| {
261                    Err(api_error(reqwest::StatusCode::INTERNAL_SERVER_ERROR))
262                })
263                .once();
264        });
265
266        let result = client(api_client).get(organization_id, rule).await;
267
268        assert!(matches!(result, Err(AccessRuleError::Api(_))));
269    }
270
271    #[tokio::test]
272    async fn update_maps_not_found_to_not_found() {
273        let organization_id = org_id();
274        let rule = rule_id();
275
276        let api_client = ApiClient::new_mocked(move |mock| {
277            mock.access_rules_api
278                .expect_put()
279                .returning(move |_org_id, _id, _request| {
280                    Err(api_error(reqwest::StatusCode::NOT_FOUND))
281                })
282                .once();
283        });
284
285        let result = client(api_client)
286            .update(organization_id, rule, sample_request())
287            .await;
288
289        assert!(matches!(result, Err(AccessRuleError::NotFound)));
290    }
291
292    #[tokio::test]
293    async fn delete_maps_not_found_to_not_found() {
294        let organization_id = org_id();
295        let rule = rule_id();
296
297        let api_client = ApiClient::new_mocked(move |mock| {
298            mock.access_rules_api
299                .expect_delete()
300                .returning(move |_org_id, _id| Err(api_error(reqwest::StatusCode::NOT_FOUND)))
301                .once();
302        });
303
304        let result = client(api_client).delete(organization_id, rule).await;
305
306        assert!(matches!(result, Err(AccessRuleError::NotFound)));
307    }
308
309    /// Org-scoped calls don't map `404` onto a missing rule the way by-id calls do.
310    #[tokio::test]
311    async fn list_leaves_not_found_as_api() {
312        let organization_id = org_id();
313
314        let api_client = ApiClient::new_mocked(move |mock| {
315            mock.access_rules_api
316                .expect_get_all()
317                .returning(move |_org_id| Err(api_error(reqwest::StatusCode::NOT_FOUND)))
318                .once();
319        });
320
321        let result = client(api_client).list(organization_id).await;
322
323        assert!(matches!(result, Err(AccessRuleError::Api(_))));
324    }
325
326    #[tokio::test]
327    async fn create_rejects_invalid_request_without_calling_the_api() {
328        let organization_id = org_id();
329        let mut request = sample_request();
330        request.name = String::new();
331
332        let api_client = ApiClient::new_mocked(|mock| {
333            mock.access_rules_api.expect_post().never();
334        });
335
336        let result = client(api_client).create(organization_id, request).await;
337
338        assert!(matches!(result, Err(AccessRuleError::Validation(_))));
339    }
340
341    #[tokio::test]
342    async fn create_returns_created_view() {
343        let organization_id = org_id();
344        let rule = rule_id();
345        let response = sample_response(rule.into(), organization_id.into());
346
347        let api_client = ApiClient::new_mocked(move |mock| {
348            mock.access_rules_api
349                .expect_post()
350                .returning(move |_org_id, _request| Ok(response.clone()))
351                .once();
352        });
353
354        let result = client(api_client)
355            .create(organization_id, sample_request())
356            .await
357            .unwrap();
358
359        assert_eq!(result.id, rule);
360    }
361
362    #[tokio::test]
363    async fn create_surfaces_api_error() {
364        let organization_id = org_id();
365
366        let api_client = ApiClient::new_mocked(move |mock| {
367            mock.access_rules_api
368                .expect_post()
369                .returning(move |_org_id, _request| {
370                    Err(bitwarden_api_api::ApiError::Response(
371                        bitwarden_api_api::ResponseContent {
372                            status: reqwest::StatusCode::BAD_REQUEST,
373                            message: "Invalid rule".to_string(),
374                        },
375                    ))
376                })
377                .once();
378        });
379
380        let result = client(api_client)
381            .create(organization_id, sample_request())
382            .await;
383
384        assert!(matches!(result, Err(AccessRuleError::Api(_))));
385    }
386
387    #[tokio::test]
388    async fn update_returns_updated_view() {
389        let organization_id = org_id();
390        let rule = rule_id();
391        let response = sample_response(rule.into(), organization_id.into());
392
393        let api_client = ApiClient::new_mocked(move |mock| {
394            mock.access_rules_api
395                .expect_put()
396                .returning(move |_org_id, _id, _request| Ok(response.clone()))
397                .once();
398        });
399
400        let result = client(api_client)
401            .update(organization_id, rule, sample_request())
402            .await
403            .unwrap();
404
405        assert_eq!(result.id, rule);
406    }
407
408    #[tokio::test]
409    async fn delete_succeeds() {
410        let organization_id = org_id();
411        let rule = rule_id();
412
413        let api_client = ApiClient::new_mocked(move |mock| {
414            mock.access_rules_api
415                .expect_delete()
416                .returning(move |_org_id, _id| Ok(()))
417                .once();
418        });
419
420        let result = client(api_client).delete(organization_id, rule).await;
421
422        assert!(result.is_ok());
423    }
424
425    /// Flipping `enabled` must not disturb any other field.
426    #[tokio::test]
427    async fn set_enabled_flips_enabled_and_preserves_every_other_field() {
428        let organization_id = org_id();
429        let rule = rule_id();
430        let mut response = sample_response(rule.into(), organization_id.into());
431        response.enabled = Some(true);
432        response.allows_extensions = Some(true);
433        response.max_extension_duration_seconds = Some(3600);
434        response.single_active_lease = Some(true);
435        response.default_lease_duration_seconds = Some(1800);
436        response.max_lease_duration_seconds = Some(7200);
437        response.description = Some("Production database access".to_string());
438
439        let view = AccessRuleView::try_from(response.clone()).unwrap();
440        let returned = response.clone();
441
442        let api_client = ApiClient::new_mocked(move |mock| {
443            mock.access_rules_api
444                .expect_put()
445                .withf(|_org_id, _id, request| {
446                    request.enabled == Some(false)
447                        && request.allows_extensions == Some(true)
448                        && request.max_extension_duration_seconds == Some(3600)
449                        && request.single_active_lease == Some(true)
450                        && request.default_lease_duration_seconds == Some(1800)
451                        && request.max_lease_duration_seconds == Some(7200)
452                        && request.name == "My rule"
453                        && request.description.as_deref() == Some("Production database access")
454                })
455                .returning(move |_org_id, _id, _request| Ok(returned.clone()))
456                .once();
457        });
458
459        let result = client(api_client)
460            .set_enabled(organization_id, view, false)
461            .await
462            .unwrap();
463
464        assert_eq!(result.id, rule);
465    }
466
467    #[tokio::test]
468    async fn set_enabled_targets_the_rule_it_was_given() {
469        let organization_id = org_id();
470        let rule = rule_id();
471        let response = sample_response(rule.into(), organization_id.into());
472        let view = AccessRuleView::try_from(response.clone()).unwrap();
473
474        let api_client = ApiClient::new_mocked(move |mock| {
475            mock.access_rules_api
476                .expect_put()
477                .withf(move |_org_id, id, _request| *id == uuid::Uuid::from(rule_id()))
478                .returning(move |_org_id, _id, _request| Ok(response.clone()))
479                .once();
480        });
481
482        client(api_client)
483            .set_enabled(organization_id, view, true)
484            .await
485            .unwrap();
486    }
487}