Skip to main content

tablo_core/policy/
abilities.rs

1//! [`Abilities`]: a policy declared one ability at a time, denying every ability it does not
2//! declare.
3
4use topcoat::context::Cx;
5
6use super::{Ability, Policy};
7
8/// A check on the request alone.
9type RequestCheck = Box<dyn Fn(&Cx) -> bool + Send + Sync>;
10
11/// A check on the request and one record.
12type RecordCheck<M> = Box<dyn Fn(&Cx, &M) -> bool + Send + Sync>;
13
14/// The two checks of an ability asked at all and then of each record, such as `DeleteAny` and
15/// `Delete`.
16struct Pair<M> {
17    any: Option<RequestCheck>,
18    record: Option<RecordCheck<M>>,
19}
20
21impl<M> Default for Pair<M> {
22    fn default() -> Self {
23        Self {
24            any: None,
25            record: None,
26        }
27    }
28}
29
30impl<M> Pair<M> {
31    /// The `any` check, else allowed when a record check is declared: declaring who may delete
32    /// a record lets the request delete at all.
33    fn any_allows(&self, cx: &Cx) -> bool {
34        match &self.any {
35            Some(check) => check(cx),
36            None => self.record.is_some(),
37        }
38    }
39
40    fn record_allows(&self, cx: &Cx, record: &M) -> bool {
41        self.record.as_ref().is_some_and(|check| check(cx, record))
42    }
43}
44
45/// A policy that answers each [`Ability`] from the check declared for it, and denies every
46/// ability it declares none for.
47///
48/// A closure policy that ends in `_ => true` allows whatever it does not name, such as the
49/// restore a soft delete adds or an action declared later. `Abilities` allows only what it
50/// names:
51///
52/// ```rust
53/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
54/// # struct Post { #[key] #[auto] id: uuid::Uuid, locked: bool }
55/// # use tablo_core::Abilities;
56/// # use topcoat::context::Cx;
57/// # fn is_editor(_cx: &Cx) -> bool { true }
58/// let policy = Abilities::<Post>::new()
59///     .view_any(is_editor)
60///     .view(|_cx, _post| true)
61///     .create(is_editor)
62///     .update(|cx, post| is_editor(cx) && !post.locked);
63/// // No delete, restore or action: each is refused until the policy declares it.
64/// # let _ = policy;
65/// ```
66///
67/// A write's record check also allows the write at all: [`delete`](Self::delete) allows
68/// [`DeleteAny`](Ability::DeleteAny), [`restore`](Self::restore) allows
69/// [`RestoreAny`](Ability::RestoreAny), [`force_delete`](Self::force_delete) allows
70/// [`ForceDeleteAny`](Ability::ForceDeleteAny), and [`run`](Self::run) allows
71/// [`RunAny`](Ability::RunAny) for its action, since the panel asks the record's check before
72/// each of these writes. The `_any` methods narrow it; declared alone, they allow no record.
73/// [`view`](Self::view) does not allow [`ViewAny`](Ability::ViewAny): the list asks `ViewAny`
74/// alone and shows every row the resource's query returns, so [`view_any`](Self::view_any) is
75/// declared on its own.
76///
77/// Declaring an ability twice replaces its earlier check; combine the checks in one closure.
78///
79/// The model's type is named on `new`, `Abilities::<Post>::new()`: a closure is checked before
80/// the chain learns the model from where the policy goes.
81pub struct Abilities<M> {
82    view_any: Option<RequestCheck>,
83    view: Option<RecordCheck<M>>,
84    export: Option<RequestCheck>,
85    create: Option<RequestCheck>,
86    update: Option<RecordCheck<M>>,
87    delete: Pair<M>,
88    restore: Pair<M>,
89    force_delete: Pair<M>,
90    /// Each record action's checks, by its `NAME`.
91    actions: Vec<(&'static str, Pair<M>)>,
92    /// Each header action's check, by its `NAME`.
93    header_actions: Vec<(&'static str, RequestCheck)>,
94}
95
96impl<M> Default for Abilities<M> {
97    fn default() -> Self {
98        Self {
99            view_any: None,
100            view: None,
101            export: None,
102            create: None,
103            update: None,
104            delete: Pair::default(),
105            restore: Pair::default(),
106            force_delete: Pair::default(),
107            actions: Vec::new(),
108            header_actions: Vec::new(),
109        }
110    }
111}
112
113impl<M> Abilities<M> {
114    /// A policy that denies every ability.
115    pub fn new() -> Self {
116        Self::default()
117    }
118
119    /// Who may see the resource at all: [`ViewAny`](Ability::ViewAny), which opens the list
120    /// with every row of the resource's query, the sidebar entry, the export with
121    /// [`export`](Self::export), related tables, relationship options and header actions.
122    /// Refused until declared, whether or not [`view`](Self::view) is.
123    #[must_use]
124    pub fn view_any(mut self, check: impl Fn(&Cx) -> bool + Send + Sync + 'static) -> Self {
125        self.view_any = Some(Box::new(check));
126        self
127    }
128
129    /// Who may read the resource: [`view_any`](Self::view_any) and [`view`](Self::view) both
130    /// answered by `check`, which reads the request alone, for a resource whose readers see every
131    /// record its query returns. A [`view`](Self::view) declared after it narrows the records.
132    ///
133    /// ```rust
134    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
135    /// # struct Invoice { #[key] #[auto] id: uuid::Uuid }
136    /// # use tablo_core::Abilities;
137    /// # use topcoat::context::Cx;
138    /// # fn is_staff(_cx: &Cx) -> bool { true }
139    /// let policy = Abilities::<Invoice>::new().read(is_staff).export(is_staff);
140    /// # let _ = policy;
141    /// ```
142    #[must_use]
143    pub fn read(self, check: impl Fn(&Cx) -> bool + Send + Sync + 'static) -> Self
144    where
145        M: 'static,
146    {
147        let check = std::sync::Arc::new(check);
148        let record = std::sync::Arc::clone(&check);
149        self.view_any(move |cx| check(cx))
150            .view(move |cx, _: &M| record(cx))
151    }
152
153    /// Who may see a record: [`View`](Ability::View), asked by its detail page, its edit form,
154    /// each write to it and relationship options. The list and the export hold a row without it;
155    /// the list asks it only to offer the row's actions.
156    #[must_use]
157    pub fn view(mut self, check: impl Fn(&Cx, &M) -> bool + Send + Sync + 'static) -> Self {
158        self.view = Some(Box::new(check));
159        self
160    }
161
162    /// Who may download the list as CSV: [`Export`](Ability::Export), asked together with
163    /// [`view_any`](Self::view_any). Refused until declared.
164    #[must_use]
165    pub fn export(mut self, check: impl Fn(&Cx) -> bool + Send + Sync + 'static) -> Self {
166        self.export = Some(Box::new(check));
167        self
168    }
169
170    /// Who may create a record: [`Create`](Ability::Create).
171    #[must_use]
172    pub fn create(mut self, check: impl Fn(&Cx) -> bool + Send + Sync + 'static) -> Self {
173        self.create = Some(Box::new(check));
174        self
175    }
176
177    /// Who may edit a record: [`Update`](Ability::Update).
178    #[must_use]
179    pub fn update(mut self, check: impl Fn(&Cx, &M) -> bool + Send + Sync + 'static) -> Self {
180        self.update = Some(Box::new(check));
181        self
182    }
183
184    /// Who may delete at all: [`DeleteAny`](Ability::DeleteAny). Defaults to whether
185    /// [`delete`](Self::delete) is declared.
186    #[must_use]
187    pub fn delete_any(mut self, check: impl Fn(&Cx) -> bool + Send + Sync + 'static) -> Self {
188        self.delete.any = Some(Box::new(check));
189        self
190    }
191
192    /// Who may delete a record: [`Delete`](Ability::Delete).
193    #[must_use]
194    pub fn delete(mut self, check: impl Fn(&Cx, &M) -> bool + Send + Sync + 'static) -> Self {
195        self.delete.record = Some(Box::new(check));
196        self
197    }
198
199    /// Who may restore trashed records at all: [`RestoreAny`](Ability::RestoreAny). Defaults to
200    /// whether [`restore`](Self::restore) is declared.
201    #[must_use]
202    pub fn restore_any(mut self, check: impl Fn(&Cx) -> bool + Send + Sync + 'static) -> Self {
203        self.restore.any = Some(Box::new(check));
204        self
205    }
206
207    /// Who may restore a trashed record: [`Restore`](Ability::Restore).
208    #[must_use]
209    pub fn restore(mut self, check: impl Fn(&Cx, &M) -> bool + Send + Sync + 'static) -> Self {
210        self.restore.record = Some(Box::new(check));
211        self
212    }
213
214    /// Who may delete trashed records for good at all:
215    /// [`ForceDeleteAny`](Ability::ForceDeleteAny), which the panel also asks `DeleteAny` of.
216    /// Defaults to whether [`force_delete`](Self::force_delete) is declared.
217    #[must_use]
218    pub fn force_delete_any(mut self, check: impl Fn(&Cx) -> bool + Send + Sync + 'static) -> Self {
219        self.force_delete.any = Some(Box::new(check));
220        self
221    }
222
223    /// Who may delete a trashed record for good: [`ForceDelete`](Ability::ForceDelete), which
224    /// the panel also asks [`Delete`](Ability::Delete) of.
225    #[must_use]
226    pub fn force_delete(mut self, check: impl Fn(&Cx, &M) -> bool + Send + Sync + 'static) -> Self {
227        self.force_delete.record = Some(Box::new(check));
228        self
229    }
230
231    /// The checks of the record action `name`, added empty when none is declared yet.
232    fn action_mut(&mut self, name: &'static str) -> &mut Pair<M> {
233        let index = match self.actions.iter().position(|(action, _)| *action == name) {
234            Some(index) => index,
235            None => {
236                self.actions.push((name, Pair::default()));
237                self.actions.len() - 1
238            }
239        };
240        &mut self.actions[index].1
241    }
242
243    /// Declares the record action `name`'s check on the request.
244    pub(crate) fn set_action_any(&mut self, name: &'static str, check: RequestCheck) {
245        self.action_mut(name).any = Some(check);
246    }
247
248    /// Declares the record action `name`'s check on each record.
249    pub(crate) fn set_action_record(&mut self, name: &'static str, check: RecordCheck<M>) {
250        self.action_mut(name).record = Some(check);
251    }
252
253    /// Declares the header action `name`'s check, replacing an earlier one.
254    pub(crate) fn set_header_action(&mut self, name: &'static str, check: RequestCheck) {
255        self.header_actions.retain(|(action, _)| *action != name);
256        self.header_actions.push((name, check));
257    }
258
259    fn action(&self, name: &str) -> Option<&Pair<M>> {
260        self.actions
261            .iter()
262            .find(|(action, _)| *action == name)
263            .map(|(_, pair)| pair)
264    }
265}
266
267impl<M> std::fmt::Debug for Abilities<M> {
268    /// Lists the declared abilities by method name; their checks are closures.
269    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270        let declared = [
271            ("view_any", self.view_any.is_some()),
272            ("view", self.view.is_some()),
273            ("export", self.export.is_some()),
274            ("create", self.create.is_some()),
275            ("update", self.update.is_some()),
276            ("delete_any", self.delete.any.is_some()),
277            ("delete", self.delete.record.is_some()),
278            ("restore_any", self.restore.any.is_some()),
279            ("restore", self.restore.record.is_some()),
280            ("force_delete_any", self.force_delete.any.is_some()),
281            ("force_delete", self.force_delete.record.is_some()),
282        ];
283        f.debug_struct("Abilities")
284            .field(
285                "declared",
286                &declared
287                    .iter()
288                    .filter_map(|(name, set)| set.then_some(*name))
289                    .collect::<Vec<_>>(),
290            )
291            .field(
292                "actions",
293                &self
294                    .actions
295                    .iter()
296                    .map(|(name, _)| name)
297                    .collect::<Vec<_>>(),
298            )
299            .field(
300                "header_actions",
301                &self
302                    .header_actions
303                    .iter()
304                    .map(|(name, _)| name)
305                    .collect::<Vec<_>>(),
306            )
307            .finish()
308    }
309}
310
311impl<M: 'static> Policy<M> for Abilities<M> {
312    fn allows(&self, cx: &Cx, ability: Ability<'_, M>) -> bool {
313        // No catch-all arm: a new ability fails to compile here until it is given a check.
314        match ability {
315            Ability::ViewAny => self.view_any.as_ref().is_some_and(|check| check(cx)),
316            Ability::View(record) => self.view.as_ref().is_some_and(|check| check(cx, record)),
317            Ability::Export => self.export.as_ref().is_some_and(|check| check(cx)),
318            Ability::Create => self.create.as_ref().is_some_and(|check| check(cx)),
319            Ability::Update(record) => self.update.as_ref().is_some_and(|check| check(cx, record)),
320            Ability::DeleteAny => self.delete.any_allows(cx),
321            Ability::Delete(record) => self.delete.record_allows(cx, record),
322            Ability::RestoreAny => self.restore.any_allows(cx),
323            Ability::Restore(record) => self.restore.record_allows(cx, record),
324            Ability::ForceDeleteAny => self.force_delete.any_allows(cx),
325            Ability::ForceDelete(record) => self.force_delete.record_allows(cx, record),
326            Ability::RunAny { action } => self.action(action).is_some_and(|p| p.any_allows(cx)),
327            Ability::Run { action, record } => self
328                .action(action)
329                .is_some_and(|pair| pair.record_allows(cx, record)),
330            Ability::RunHeader { action } => self
331                .header_actions
332                .iter()
333                .find(|(name, _)| *name == action)
334                .is_some_and(|(_, check)| check(cx)),
335        }
336    }
337}