Skip to main content

vcon_server/
roles.rs

1//! The roles a membership holds: what a user is in a tenant, or as an
2//! operator. This is the one list of role names; a membership's row keeps
3//! its roles as [`Roles`] writes them.
4
5use std::fmt;
6
7use crate::access::{Scope, Scopes};
8
9/// One role.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum Role {
12    /// Reads a tenant's vCons.
13    Reader,
14    /// Stores vCons in a tenant.
15    Producer,
16    /// Deletes a tenant's vCons.
17    Records,
18    /// Reads deleted versions and sets legal holds in a tenant.
19    Legal,
20    /// Reads a tenant's audit log.
21    Auditor,
22    /// Administers a tenant.
23    TenantAdmin,
24    /// Administers the server; the one role of an operator membership.
25    Operator,
26}
27
28impl Role {
29    /// Every role, in the order a set is written.
30    pub const ALL: [Role; 7] = [
31        Role::Reader,
32        Role::Producer,
33        Role::Records,
34        Role::Legal,
35        Role::Auditor,
36        Role::TenantAdmin,
37        Role::Operator,
38    ];
39
40    /// The role's name, as the command line takes it and a row keeps it.
41    #[must_use]
42    pub fn name(self) -> &'static str {
43        match self {
44            Role::Reader => "reader",
45            Role::Producer => "producer",
46            Role::Records => "records",
47            Role::Legal => "legal",
48            Role::Auditor => "auditor",
49            Role::TenantAdmin => "tenant-admin",
50            Role::Operator => "operator",
51        }
52    }
53
54    /// The role with this name, if there is one.
55    #[must_use]
56    pub fn named(name: &str) -> Option<Role> {
57        Role::ALL.into_iter().find(|role| role.name() == name)
58    }
59
60    /// What the role lets its holder do: the one table of roles to
61    /// scopes. A key holds scopes directly; a membership holds roles, and
62    /// its scopes are those of its roles ([`Roles::scopes`]).
63    #[must_use]
64    pub fn scopes(self) -> Scopes {
65        Scopes::of(match self {
66            Role::Reader => &[Scope::Read],
67            Role::Producer => &[Scope::Write],
68            Role::Records => &[Scope::Delete],
69            Role::Legal => &[Scope::Legal],
70            Role::Auditor => &[Scope::Audit],
71            Role::TenantAdmin => &[Scope::TenantAdmin],
72            Role::Operator => &[Scope::Admin],
73        })
74    }
75
76    fn bit(self) -> u8 {
77        match self {
78            Role::Reader => 1,
79            Role::Producer => 1 << 1,
80            Role::Records => 1 << 2,
81            Role::Legal => 1 << 3,
82            Role::Auditor => 1 << 4,
83            Role::TenantAdmin => 1 << 5,
84            Role::Operator => 1 << 6,
85        }
86    }
87}
88
89/// A set of roles. It is written as its roles' names in the order of
90/// [`Role::ALL`], joined by commas; the empty set is written empty.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
92pub struct Roles(u8);
93
94impl Roles {
95    /// Every role a tenant membership may hold: all but `operator`.
96    pub const TENANT: Roles = Roles((1 << 6) - 1);
97
98    /// The scopes of the set: the union of its roles' scopes
99    /// ([`Role::scopes`]).
100    #[must_use]
101    pub fn scopes(self) -> Scopes {
102        Role::ALL
103            .into_iter()
104            .filter(|role| self.contains(*role))
105            .fold(Scopes::default(), |held, role| held.with(role.scopes()))
106    }
107
108    /// The roles of this set that count in a tenant whose cap is `cap`:
109    /// those the cap holds too, or all of them where the tenant has no
110    /// cap.
111    #[must_use]
112    pub fn within(self, cap: Option<Roles>) -> Roles {
113        cap.map_or(self, |cap| Roles(self.0 & cap.0))
114    }
115
116    /// The roles of this set that a tenant whose cap is `cap` does not
117    /// allow; none where the tenant has no cap.
118    #[must_use]
119    pub fn outside(self, cap: Option<Roles>) -> Roles {
120        cap.map_or(Roles::default(), |cap| self.without(cap))
121    }
122
123    /// Whether the set may be a tenant's cap: one or more of the roles a
124    /// tenant membership may hold.
125    #[must_use]
126    pub fn caps(self) -> bool {
127        self.fit(false)
128    }
129
130    /// The set of `roles`; a role given twice is held once.
131    #[must_use]
132    pub fn of(roles: &[Role]) -> Roles {
133        Roles(roles.iter().fold(0, |bits, role| bits | role.bit()))
134    }
135
136    /// The set of the roles `names` name, in any order and with repeats;
137    /// None if one is not a role's name.
138    #[must_use]
139    pub fn named(names: &[String]) -> Option<Roles> {
140        let roles: Vec<Role> = names
141            .iter()
142            .map(|name| Role::named(name))
143            .collect::<Option<_>>()?;
144        Some(Roles::of(&roles))
145    }
146
147    /// Reads a set as [`Roles`] writes it, and nothing else: a row's roles
148    /// in another order, with a repeat, or empty, are damage.
149    #[must_use]
150    pub fn parse(text: &str) -> Option<Roles> {
151        let roles: Vec<Role> = text.split(',').map(Role::named).collect::<Option<_>>()?;
152        let read = Roles::of(&roles);
153        (read.to_string() == text).then_some(read)
154    }
155
156    /// Whether the set holds `role`.
157    #[must_use]
158    pub fn contains(self, role: Role) -> bool {
159        self.0 & role.bit() != 0
160    }
161
162    /// Whether the set holds no role.
163    #[must_use]
164    pub fn is_empty(self) -> bool {
165        self.0 == 0
166    }
167
168    /// The roles of either set.
169    #[must_use]
170    pub fn with(self, other: Roles) -> Roles {
171        Roles(self.0 | other.0)
172    }
173
174    /// The roles of this set that `other` does not hold.
175    #[must_use]
176    pub fn without(self, other: Roles) -> Roles {
177        Roles(self.0 & !other.0)
178    }
179
180    /// The names of the set's roles, in the order of [`Role::ALL`].
181    #[must_use]
182    pub fn names(self) -> Vec<&'static str> {
183        Role::ALL
184            .into_iter()
185            .filter(|role| self.contains(*role))
186            .map(Role::name)
187            .collect()
188    }
189
190    /// Whether a membership may hold exactly this set: an operator
191    /// membership holds `operator` and nothing else, and a tenant
192    /// membership holds one or more of the other roles.
193    #[must_use]
194    pub fn fit(self, operator: bool) -> bool {
195        if operator {
196            self == Roles::of(&[Role::Operator])
197        } else {
198            !self.is_empty() && !self.contains(Role::Operator)
199        }
200    }
201}
202
203impl fmt::Display for Roles {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        f.write_str(&self.names().join(","))
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    fn scopes(of: &[Scope]) -> Scopes {
214        Scopes::of(of)
215    }
216
217    /// The table as the plan states it, written out a second time so a
218    /// change to one copy alone fails.
219    const TABLE: [(Role, Scope); 7] = [
220        (Role::Reader, Scope::Read),
221        (Role::Producer, Scope::Write),
222        (Role::Records, Scope::Delete),
223        (Role::Legal, Scope::Legal),
224        (Role::Auditor, Scope::Audit),
225        (Role::TenantAdmin, Scope::TenantAdmin),
226        (Role::Operator, Scope::Admin),
227    ];
228
229    #[test]
230    fn a_reader_reads() {
231        assert_eq!(Role::Reader.scopes(), scopes(&[Scope::Read]), "reader");
232    }
233
234    #[test]
235    fn a_producer_writes() {
236        assert_eq!(Role::Producer.scopes(), scopes(&[Scope::Write]), "producer");
237    }
238
239    #[test]
240    fn records_deletes() {
241        assert_eq!(Role::Records.scopes(), scopes(&[Scope::Delete]), "records");
242    }
243
244    #[test]
245    fn legal_holds_the_legal_scope() {
246        assert_eq!(Role::Legal.scopes(), scopes(&[Scope::Legal]), "legal");
247    }
248
249    #[test]
250    fn an_auditor_reads_the_audit_log() {
251        assert_eq!(Role::Auditor.scopes(), scopes(&[Scope::Audit]), "auditor");
252    }
253
254    #[test]
255    fn a_tenant_admin_holds_tenant_admin_and_no_vcon_scope() {
256        assert_eq!(
257            Role::TenantAdmin.scopes(),
258            scopes(&[Scope::TenantAdmin]),
259            "tenant-admin"
260        );
261    }
262
263    #[test]
264    fn an_operator_holds_admin() {
265        assert_eq!(Role::Operator.scopes(), scopes(&[Scope::Admin]), "operator");
266    }
267
268    #[test]
269    fn the_table_has_one_line_for_each_role_and_each_scope() {
270        assert_eq!(
271            TABLE.map(|(role, _)| role),
272            Role::ALL,
273            "every role, in the order of Role::ALL"
274        );
275        for scope in Scope::ALL {
276            let givers: Vec<Role> = Role::ALL
277                .into_iter()
278                .filter(|role| role.scopes().contains(scope))
279                .collect();
280            assert_eq!(givers.len(), 1, "{scope:?} is given by {givers:?}");
281        }
282        for (role, scope) in TABLE {
283            assert_eq!(role.scopes(), scopes(&[scope]), "{role:?}");
284        }
285    }
286
287    #[test]
288    fn a_sets_scopes_are_the_union_of_its_roles() {
289        assert_eq!(
290            Roles::of(&[Role::Reader, Role::Auditor]).scopes(),
291            scopes(&[Scope::Read, Scope::Audit]),
292            "two roles"
293        );
294        assert_eq!(
295            Roles::of(&[Role::Producer, Role::Reader, Role::Records])
296                .scopes()
297                .to_string(),
298            "write,read,delete",
299            "three roles, written in the scopes' order"
300        );
301    }
302
303    #[test]
304    fn every_subset_of_the_roles_gives_the_union_of_the_table() {
305        for bits in 0..(1_u8 << 7) {
306            let held: Vec<Role> = Role::ALL
307                .into_iter()
308                .enumerate()
309                .filter(|(place, _)| bits & (1 << place) != 0)
310                .map(|(_, role)| role)
311                .collect();
312            let want: Vec<Scope> = TABLE
313                .into_iter()
314                .filter(|(role, _)| held.contains(role))
315                .map(|(_, scope)| scope)
316                .collect();
317            assert_eq!(Roles::of(&held).scopes(), scopes(&want), "{held:?}");
318        }
319    }
320
321    #[test]
322    fn the_empty_set_gives_no_scope() {
323        assert!(Roles::default().scopes().is_empty(), "no role, no scope");
324    }
325
326    #[test]
327    fn a_role_named_twice_gives_its_scope_once() {
328        assert_eq!(
329            Roles::of(&[Role::Legal, Role::Legal]).scopes(),
330            scopes(&[Scope::Legal]),
331            "legal twice"
332        );
333    }
334
335    #[test]
336    fn every_tenant_role_together_gives_every_scope_but_admin() {
337        let all = Roles::TENANT.scopes();
338        for scope in Scope::ALL {
339            assert_eq!(all.contains(scope), scope != Scope::Admin, "{scope:?}");
340        }
341    }
342
343    #[test]
344    fn the_tenant_roles_are_every_role_but_operator() {
345        assert_eq!(
346            Roles::TENANT.names(),
347            [
348                "reader",
349                "producer",
350                "records",
351                "legal",
352                "auditor",
353                "tenant-admin"
354            ],
355            "the six roles of a tenant membership"
356        );
357        assert!(Roles::TENANT.fit(false), "they fit a tenant membership");
358    }
359
360    #[test]
361    fn no_tenant_role_gives_admin_and_operator_gives_no_tenant_scope() {
362        for role in Role::ALL {
363            assert_eq!(
364                role.scopes().contains(Scope::Admin),
365                role == Role::Operator,
366                "{role:?}"
367            );
368        }
369        assert_eq!(
370            Role::Operator.scopes().names(),
371            ["admin"],
372            "operator gives admin alone"
373        );
374    }
375
376    #[test]
377    fn with_no_cap_every_role_counts() {
378        let held = Roles::of(&[Role::Reader, Role::TenantAdmin]);
379        assert_eq!(held.within(None), held, "no cap");
380        assert_eq!(held.outside(None), Roles::default(), "nothing is outside");
381    }
382
383    #[test]
384    fn under_a_cap_only_the_roles_in_it_count() {
385        let held = Roles::of(&[Role::Reader, Role::Records, Role::Auditor]);
386        let cap = Roles::of(&[Role::Reader, Role::Producer, Role::Auditor]);
387        assert_eq!(
388            held.within(Some(cap)),
389            Roles::of(&[Role::Reader, Role::Auditor]),
390            "the roles both hold"
391        );
392        assert_eq!(
393            held.outside(Some(cap)),
394            Roles::of(&[Role::Records]),
395            "the role the cap leaves out"
396        );
397        assert_eq!(
398            held.within(Some(cap)).scopes().to_string(),
399            "read,audit",
400            "and the scopes are those of the roles that count"
401        );
402    }
403
404    #[test]
405    fn a_cap_holding_none_of_the_roles_leaves_no_role_and_no_scope() {
406        let held = Roles::of(&[Role::Legal]);
407        let cap = Roles::of(&[Role::Reader]);
408        assert!(held.within(Some(cap)).is_empty(), "no role counts");
409        assert!(held.within(Some(cap)).scopes().is_empty(), "no scope");
410        assert_eq!(held.outside(Some(cap)), held, "all of it is outside");
411    }
412
413    #[test]
414    fn a_cap_wider_than_the_roles_changes_nothing() {
415        let held = Roles::of(&[Role::Legal]);
416        assert_eq!(held.within(Some(Roles::TENANT)), held, "every tenant role");
417    }
418
419    #[test]
420    fn a_cap_is_a_set_a_tenant_membership_could_hold() {
421        assert!(Roles::of(&[Role::Reader]).caps(), "one tenant role");
422        assert!(Roles::TENANT.caps(), "every tenant role");
423        assert!(!Roles::default().caps(), "no role");
424        assert!(!Roles::of(&[Role::Operator]).caps(), "operator");
425        assert!(
426            !Roles::of(&[Role::Reader, Role::Operator]).caps(),
427            "operator with a tenant role"
428        );
429    }
430
431    #[test]
432    fn a_roles_name_is_not_its_scopes_name() {
433        assert_eq!(Role::named("tenant_admin"), None, "the scope's spelling");
434        assert_eq!(Scope::named("tenant-admin"), None, "the role's spelling");
435        assert_eq!(Role::named("read"), None, "a scope's name");
436        assert_eq!(Scope::named("reader"), None, "a role's name");
437    }
438}