Skip to main content

bitwarden_pam/approvals/
models.rs

1use bitwarden_api_api::models::{
2    AccessDecisionRequestModel, AccessDecisionVerdict as ApiAccessDecisionVerdict,
3    AccessRequestHistoryPageResponseModel, AccessRequestHistoryRequesterResponseModel,
4    AccessRequestRevokeRequestModel,
5};
6use bitwarden_collections::collection::CollectionId;
7use bitwarden_core::{UserId, require};
8use serde::{Deserialize, Serialize};
9
10use super::error::ApprovalError;
11use crate::{AccessDecisionVerdict, access_requests::AccessRequestView, error::PamDecodeError};
12
13/// How a request ended, as the approver history lists it.
14#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
15#[bitwarden_ffi::wasm_record]
16#[serde(rename_all = "snake_case")]
17pub enum AccessRequestHistoryStatus {
18    /// An approver denied the request, or withdrew an approval before it was started.
19    Denied,
20    /// An approver ended the lease early.
21    Revoked,
22    /// The requester withdrew the request.
23    Canceled,
24    /// The window closed with the request unanswered, or approved and never started.
25    Expired,
26    /// The lease ran to its end, or its holder ended it.
27    SessionEnded,
28}
29
30impl AccessRequestHistoryStatus {
31    /// The name the server reads in the `status` query parameter.
32    pub(crate) fn wire_name(self) -> &'static str {
33        match self {
34            Self::Denied => "denied",
35            Self::Revoked => "revoked",
36            Self::Canceled => "canceled",
37            Self::Expired => "expired",
38            Self::SessionEnded => "sessionEnded",
39        }
40    }
41}
42
43/// Which page of the approver history to read, and what to narrow it to. An empty list matches
44/// everything; values within a list are OR-ed, lists are AND-ed.
45#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
46#[bitwarden_ffi::wasm_record]
47#[serde(rename_all = "camelCase")]
48pub struct AccessRequestHistoryQuery {
49    /// 0-based.
50    pub page: u32,
51    /// Rows per page, 1 to 100.
52    pub page_size: u32,
53    /// How the request ended.
54    pub statuses: Vec<AccessRequestHistoryStatus>,
55    /// The request's collection.
56    pub collection_ids: Vec<CollectionId>,
57    /// Who made the request.
58    pub requester_ids: Vec<UserId>,
59}
60
61/// One page of the approver history: the ended requests on collections the caller manages, and
62/// the caller's own, newest request first.
63#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
64#[bitwarden_ffi::wasm_record]
65#[serde(rename_all = "camelCase")]
66pub struct AccessRequestHistoryPage {
67    /// The requests on this page.
68    pub requests: Vec<AccessRequestView>,
69    /// How many requests match the query, across all pages.
70    pub total: u32,
71    /// Everyone with a request in the history, whatever the query, for the Requester filter.
72    pub requesters: Vec<AccessRequestHistoryRequester>,
73    /// Every collection with a request in the history, whatever the query.
74    pub collection_ids: Vec<CollectionId>,
75}
76
77/// A requester with a request in the approver history.
78#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
79#[bitwarden_ffi::wasm_record]
80#[serde(rename_all = "camelCase")]
81pub struct AccessRequestHistoryRequester {
82    /// The requester's user id.
83    pub id: UserId,
84    /// The requester's name, if they set one.
85    pub name: Option<String>,
86    /// The requester's email.
87    pub email: Option<String>,
88}
89
90impl TryFrom<AccessRequestHistoryRequesterResponseModel> for AccessRequestHistoryRequester {
91    type Error = PamDecodeError;
92
93    fn try_from(response: AccessRequestHistoryRequesterResponseModel) -> Result<Self, Self::Error> {
94        Ok(Self {
95            id: UserId::new(require!(response.id)),
96            name: response.name,
97            email: response.email,
98        })
99    }
100}
101
102impl TryFrom<AccessRequestHistoryPageResponseModel> for AccessRequestHistoryPage {
103    type Error = PamDecodeError;
104
105    fn try_from(response: AccessRequestHistoryPageResponseModel) -> Result<Self, Self::Error> {
106        Ok(Self {
107            requests: response
108                .data
109                .unwrap_or_default()
110                .into_iter()
111                .map(AccessRequestView::try_from)
112                .collect::<Result<_, _>>()?,
113            total: u32::try_from(require!(response.total)).unwrap_or_default(),
114            requesters: response
115                .requesters
116                .unwrap_or_default()
117                .into_iter()
118                .map(AccessRequestHistoryRequester::try_from)
119                .collect::<Result<_, _>>()?,
120            collection_ids: response
121                .collection_ids
122                .unwrap_or_default()
123                .into_iter()
124                .map(CollectionId::new)
125                .collect(),
126        })
127    }
128}
129
130/// An approver's decision on a pending access request.
131#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
132#[bitwarden_ffi::wasm_record]
133#[serde(rename_all = "camelCase")]
134pub struct AccessDecisionRequest {
135    /// The verdict to record; [`AccessDecisionVerdict::Unknown`] cannot be submitted.
136    pub verdict: AccessDecisionVerdict,
137    /// An optional note shown to the requester.
138    pub comment: Option<String>,
139}
140
141impl TryFrom<AccessDecisionRequest> for AccessDecisionRequestModel {
142    type Error = ApprovalError;
143
144    fn try_from(request: AccessDecisionRequest) -> Result<Self, Self::Error> {
145        let verdict = match request.verdict {
146            AccessDecisionVerdict::Approve => ApiAccessDecisionVerdict::Approve,
147            AccessDecisionVerdict::Deny => ApiAccessDecisionVerdict::Deny,
148            AccessDecisionVerdict::Unknown => return Err(ApprovalError::UnsubmittableVerdict),
149        };
150
151        Ok(Self {
152            verdict,
153            comment: request.comment,
154        })
155    }
156}
157
158/// An approver revoking an approved access request the requester has not started.
159#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
160#[bitwarden_ffi::wasm_record]
161#[serde(rename_all = "camelCase")]
162pub struct AccessRequestRevokeRequest {
163    /// Why the approval is revoked. Required by the server; recorded with the approver's decision
164    /// and shown to the requester.
165    pub reason: String,
166}
167
168impl From<AccessRequestRevokeRequest> for AccessRequestRevokeRequestModel {
169    fn from(request: AccessRequestRevokeRequest) -> Self {
170        Self {
171            reason: Some(request.reason),
172        }
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    #[test]
181    fn approve_converts_to_model() {
182        let request = AccessDecisionRequest {
183            verdict: AccessDecisionVerdict::Approve,
184            comment: Some("Looks fine".to_string()),
185        };
186
187        let model = AccessDecisionRequestModel::try_from(request).unwrap();
188
189        assert_eq!(model.verdict, ApiAccessDecisionVerdict::Approve);
190        assert_eq!(model.comment, Some("Looks fine".to_string()));
191    }
192
193    #[test]
194    fn deny_converts_to_model() {
195        let request = AccessDecisionRequest {
196            verdict: AccessDecisionVerdict::Deny,
197            comment: None,
198        };
199
200        let model = AccessDecisionRequestModel::try_from(request).unwrap();
201
202        assert_eq!(model.verdict, ApiAccessDecisionVerdict::Deny);
203        assert_eq!(model.comment, None);
204    }
205
206    #[test]
207    fn unknown_verdict_is_rejected() {
208        let request = AccessDecisionRequest {
209            verdict: AccessDecisionVerdict::Unknown,
210            comment: None,
211        };
212
213        let result = AccessDecisionRequestModel::try_from(request);
214
215        assert!(matches!(result, Err(ApprovalError::UnsubmittableVerdict)));
216    }
217
218    #[test]
219    fn revoke_converts_to_model() {
220        let model = AccessRequestRevokeRequestModel::from(AccessRequestRevokeRequest {
221            reason: "Approved by mistake".to_string(),
222        });
223
224        assert_eq!(model.reason.as_deref(), Some("Approved by mistake"));
225    }
226
227    #[test]
228    fn history_status_wire_names_match_server() {
229        let cases = [
230            (AccessRequestHistoryStatus::Denied, "denied"),
231            (AccessRequestHistoryStatus::Revoked, "revoked"),
232            (AccessRequestHistoryStatus::Canceled, "canceled"),
233            (AccessRequestHistoryStatus::Expired, "expired"),
234            (AccessRequestHistoryStatus::SessionEnded, "sessionEnded"),
235        ];
236
237        for (status, expected) in cases {
238            assert_eq!(status.wire_name(), expected, "{status:?}");
239        }
240    }
241}