Skip to main content

tablo_core/
policy.rs

1//! Authorizes resource abilities, denying by default.
2//!
3//! Combines [`Allow`], [`Deny`], [`ReadOnly`], [`when`], [`Abilities`] and closures with
4//! `and`/`or`.
5//!
6//! ```rust
7//! # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
8//! # struct Post { #[key] #[auto] id: uuid::Uuid, locked: bool }
9//! # use tablo_core::{Ability, Policy, when};
10//! # use topcoat::context::Cx;
11//! # fn not_suspended(cx: &Cx) -> bool { true }
12//! fn post_policy() -> impl Policy<Post> {
13//!     // No write to a locked post: an update, a delete, a restore or a record action.
14//!     when(not_suspended).and(|_cx: &Cx, ability: Ability<'_, Post>| {
15//!         ability.written_record().is_none_or(|post| !post.locked)
16//!     })
17//! }
18//! ```
19//!
20//! A closure ending in `_ => true` allows every ability it does not name, the ones a resource
21//! gains later included. Match every variant so that a new one fails to compile, read
22//! [`Ability::written_record`] to refuse writes by the record, or build with [`Abilities`], which
23//! denies what it does not declare.
24//!
25//! A policy does not await: it reads the request. What it needs beyond the signed-in user, a
26//! plan's limit say, the panel loads once per request as a [`Load`](crate::Load) value.
27//!
28//! [`can`](crate::can) asks a resource's policy from app code, and [`can_list`](crate::can_list)
29//! answers whether the current request may open a resource's list at all.
30
31use derive_where::derive_where;
32use topcoat::context::Cx;
33
34mod abilities;
35
36pub use abilities::Abilities;
37
38/// One thing a policy is asked to allow; record abilities are asked once per
39/// loaded row, and a record that cannot be viewed cannot be written by guessing
40/// its key.
41#[derive(Debug)]
42#[derive_where(Clone, Copy)]
43pub enum Ability<'a, M> {
44    /// Read the resource's rows: asked by the list and its live refresh, the sidebar entry, the
45    /// export, related tables, relationship options and relation columns, and the global search.
46    /// All but the global search show every row of the resource's query, asking no record
47    /// ability of it: a
48    /// policy cannot run in the database, so the rows a user must not see belong out of
49    /// [`ResourceDef::query`](crate::ResourceDef::query).
50    ViewAny,
51    /// Download the list as CSV, asked together with [`ViewAny`](Self::ViewAny): asked by the
52    /// export route, answered 403 when refused, and the list's Export button, hidden when
53    /// refused. The file holds every row the list's search and filters match, up to
54    /// [`Limits::export_rows`](crate::Limits::export_rows), so a role that may page through
55    /// the list need not take it whole. [`ReadOnly`] refuses it.
56    Export,
57    /// Open one record: asked by the detail page, the edit page and POST, deletes, record pages
58    /// and each global search result, which leaves out a record it refuses. Every write asks it
59    /// of the records it loads, and a list row it refuses shows without its actions or checkbox.
60    View(&'a M),
61    /// Open the create form and submit it: asked by the create page and POST, and the Create
62    /// button.
63    Create,
64    /// Edit one record: asked by the edit page and POST, and the row's Edit action.
65    Update(&'a M),
66    /// Delete at all: asked by the delete and bulk-delete POSTs before any record loads, the
67    /// Delete action and the bulk column.
68    DeleteAny,
69    /// Delete one record: asked of each record a delete removes, and by the row's Delete action
70    /// and checkbox.
71    Delete(&'a M),
72    /// Restore trashed records at all, on a resource that
73    /// [soft-deletes](crate::ResourceDef::soft_delete): asked by the restore POSTs and the
74    /// Restore buttons.
75    RestoreAny,
76    /// Restore one trashed record: asked of each record a restore brings back, and by its Restore
77    /// button and checkbox.
78    Restore(&'a M),
79    /// Delete trashed records for good at all, on a resource that
80    /// [soft-deletes](crate::ResourceDef::soft_delete). Allowed only with
81    /// [`DeleteAny`](Self::DeleteAny). Asked by the force-delete POSTs and the Delete
82    /// permanently buttons.
83    ForceDeleteAny,
84    /// Delete one trashed record for good. Allowed only with [`Delete`](Self::Delete) of it, so a
85    /// policy refusing a record's delete refuses its force delete too. Asked of each trashed
86    /// record a force delete removes, and by its button and checkbox.
87    ForceDelete(&'a M),
88    /// Run the custom [`Action`](crate::Action) whose [`NAME`](crate::Action::NAME) is `action`
89    /// at all, before [`Run`](Self::Run) is asked of each record: asked by the action's POSTs,
90    /// before any record loads, its buttons, and the bulk column for a bulk action.
91    RunAny {
92        /// The action's [`NAME`](crate::Action::NAME).
93        action: &'static str,
94    },
95    /// Run the custom [`Action`](crate::Action) whose [`NAME`](crate::Action::NAME) is `action`
96    /// on one record: asked of each record the action runs on, and by its button on the record's
97    /// row and pages and, for a bulk action, the record's checkbox.
98    Run {
99        /// The action's [`NAME`](crate::Action::NAME).
100        action: &'static str,
101        /// The record it runs on.
102        record: &'a M,
103    },
104    /// Run the [`HeaderAction`](crate::HeaderAction) whose `NAME` is `action` from the list's
105    /// header. It acts on no record, so nothing else of the policy is asked but `ViewAny`.
106    ///
107    /// It is not [`RunAny`](Self::RunAny): a policy that grants every record action with
108    /// `RunAny { .. } => true` grants no header action by it.
109    RunHeader {
110        /// The action's [`NAME`](crate::HeaderAction::NAME).
111        action: &'static str,
112    },
113}
114
115impl<'a, M> Ability<'a, M> {
116    /// The record the ability names, if any.
117    pub fn record(self) -> Option<&'a M> {
118        match self {
119            Self::View(record)
120            | Self::Update(record)
121            | Self::Delete(record)
122            | Self::Restore(record)
123            | Self::ForceDelete(record)
124            | Self::Run { record, .. } => Some(record),
125            Self::ViewAny
126            | Self::Export
127            | Self::Create
128            | Self::DeleteAny
129            | Self::RestoreAny
130            | Self::ForceDeleteAny
131            | Self::RunAny { .. }
132            | Self::RunHeader { .. } => None,
133        }
134    }
135
136    /// Whether the ability reads in the panel: [`ViewAny`](Self::ViewAny) or
137    /// [`View`](Self::View). [`Export`](Self::Export), which takes the rows out of it, is not one.
138    pub fn is_read(self) -> bool {
139        matches!(self, Self::ViewAny | Self::View(_))
140    }
141
142    /// The record the ability writes: an update, a delete, a restore, a force delete or a
143    /// record action's run on it. `None` for a read and for an ability over no existing record:
144    /// `Export`, `Create`, the `_any` abilities and `RunHeader`.
145    ///
146    /// A policy refusing every write to some records reads it, and so also refuses the record
147    /// actions and soft-delete writes a resource gains later. A header action writes no record
148    /// it is handed, so such a policy allows it unless it matches `RunHeader` too:
149    ///
150    /// ```rust
151    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
152    /// # struct User { #[key] #[auto] id: uuid::Uuid, name: String }
153    /// # use tablo_core::Ability;
154    /// # use topcoat::context::Cx;
155    /// fn keep_root(_cx: &Cx, ability: Ability<'_, User>) -> bool {
156    ///     ability
157    ///         .written_record()
158    ///         .is_none_or(|user| user.name != "root")
159    /// }
160    /// ```
161    pub fn written_record(self) -> Option<&'a M> {
162        match self {
163            Self::Update(record)
164            | Self::Delete(record)
165            | Self::Restore(record)
166            | Self::ForceDelete(record)
167            | Self::Run { record, .. } => Some(record),
168            Self::ViewAny
169            | Self::Export
170            | Self::View(_)
171            | Self::Create
172            | Self::DeleteAny
173            | Self::RestoreAny
174            | Self::ForceDeleteAny
175            | Self::RunAny { .. }
176            | Self::RunHeader { .. } => None,
177        }
178    }
179}
180
181/// Decides which [`Ability`]s the current user has over a resource's records.
182///
183/// Every handler asks the same abilities that decide which buttons render, so a hidden button is
184/// also a refused request, answered 403:
185///
186/// - a record is viewed before it is written: the edit, delete and action handlers ask
187///   [`View`](Ability::View) together with `Update`, `Delete` or `Run`;
188/// - a write is checked against the stored row: the update, delete and action handlers load the
189///   record inside the write's transaction and ask about that row, not the submitted key. A bulk
190///   delete or bulk action fails as a whole when any selected record is refused `View`, and skips
191///   the records refused `Delete` or `Run`;
192/// - running an action takes the policy and the action's own [`can_run`](crate::ActionDef::can_run)
193///   together, so a panel that mounts the resource with [`ReadOnly`] offers and runs none of its
194///   actions, and [`can`](crate::can) answers what the button shows;
195/// - a relationship choice asks the related resource's policy for `ViewAny` and `View`;
196/// - a policy is asked once per row and once per button, so it cannot query: the panel reads what
197///   it needs once for the request, as a [`Load`](crate::Load) value [`loaded`](crate::loaded)
198///   answers.
199///
200/// A closure `|cx: &Cx, ability: Ability<'_, M>| -> bool` is a policy, and the
201/// building blocks combine with `and` and `or`.
202/// [`ResourceDef::policy_fn`](crate::ResourceDef::policy_fn) takes a closure without naming its
203/// argument types.
204pub trait Policy<M>: Send + Sync + 'static {
205    /// Whether the current user may do `ability`.
206    fn allows(&self, cx: &Cx, ability: Ability<'_, M>) -> bool;
207}
208
209macro_rules! combinators {
210    ($($ty:ident $(<$($param:ident),+>)?),+ $(,)?) => {$(
211        impl$(<$($param),+>)? $ty$(<$($param),+>)? {
212            /// Allows what both `self` and `other` allow.
213            pub fn and<P>(self, other: P) -> And<Self, P> {
214                And(self, other)
215            }
216
217            /// Allows what either `self` or `other` allows.
218            pub fn or<P>(self, other: P) -> Or<Self, P> {
219                Or(self, other)
220            }
221        }
222    )+};
223}
224
225combinators!(Allow, Deny, ReadOnly, When<F>, And<A, B>, Or<A, B>, Abilities<M>);
226
227impl<M, F> Policy<M> for F
228where
229    F: Fn(&Cx, Ability<'_, M>) -> bool + Send + Sync + 'static,
230{
231    fn allows(&self, cx: &Cx, ability: Ability<'_, M>) -> bool {
232        self(cx, ability)
233    }
234}
235
236/// Allows every ability.
237#[derive(Debug, Clone, Copy, Default)]
238pub struct Allow;
239
240impl<M> Policy<M> for Allow {
241    fn allows(&self, _cx: &Cx, _ability: Ability<'_, M>) -> bool {
242        true
243    }
244}
245
246/// Allows nothing: the default policy.
247#[derive(Debug, Clone, Copy, Default)]
248pub struct Deny;
249
250impl<M> Policy<M> for Deny {
251    fn allows(&self, _cx: &Cx, _ability: Ability<'_, M>) -> bool {
252        false
253    }
254}
255
256/// Allows listing and viewing, and nothing else: no export, and no create, update, delete or
257/// custom action.
258#[derive(Debug, Clone, Copy, Default)]
259pub struct ReadOnly;
260
261impl<M> Policy<M> for ReadOnly {
262    fn allows(&self, _cx: &Cx, ability: Ability<'_, M>) -> bool {
263        ability.is_read()
264    }
265}
266
267/// Marks a request that writes nothing through the panel, whatever a policy allows: one made while
268/// a user acts as another under an [`Impersonation`](crate::Impersonation) that is not
269/// [`writable`](crate::Impersonation::writable). Every resource then answers as [`ReadOnly`] does,
270/// and no header action runs.
271#[derive(Debug, Clone, Copy)]
272pub(crate) struct WritesRefused;
273
274/// Whether the request writes nothing through the panel: see [`WritesRefused`].
275pub(crate) fn writes_refused(cx: &Cx) -> bool {
276    topcoat::context::try_context::<WritesRefused>(cx).is_some()
277}
278
279/// Allows every ability while `predicate` holds for the request.
280///
281/// ```rust
282/// # #[derive(Debug, Clone, toasty::Model)]
283/// # struct Staff { #[key] #[auto] id: uuid::Uuid, editor: bool }
284/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
285/// # struct Post { #[key] #[auto] id: uuid::Uuid }
286/// # use tablo_core::{PanelUser, Policy, ReadOnly, auth, when};
287/// # use topcoat::context::Cx;
288/// # impl PanelUser for Staff {
289/// #     fn user_id(&self) -> String { String::new() }
290/// #     fn display_name(&self) -> &str { "" }
291/// #     fn can_access_panel(&self, _panel: &tablo_core::PanelId) -> bool { true }
292/// # }
293/// fn editor(cx: &Cx) -> bool {
294///     auth::user::<Staff>(cx).is_some_and(|staff| staff.editor)
295/// }
296///
297/// fn post_policy() -> impl Policy<Post> {
298///     ReadOnly.or(when(editor))
299/// }
300/// ```
301pub fn when<F>(predicate: F) -> When<F>
302where
303    F: Fn(&Cx) -> bool + Send + Sync + 'static,
304{
305    When(predicate)
306}
307
308/// The policy [`when`] returns.
309#[derive(Debug, Clone, Copy)]
310pub struct When<F>(F);
311
312impl<M, F> Policy<M> for When<F>
313where
314    F: Fn(&Cx) -> bool + Send + Sync + 'static,
315{
316    fn allows(&self, cx: &Cx, _ability: Ability<'_, M>) -> bool {
317        (self.0)(cx)
318    }
319}
320
321/// The policy `and` returns: allows what both sides allow.
322#[derive(Debug, Clone, Copy)]
323pub struct And<A, B>(A, B);
324
325impl<M, A: Policy<M>, B: Policy<M>> Policy<M> for And<A, B> {
326    fn allows(&self, cx: &Cx, ability: Ability<'_, M>) -> bool {
327        self.0.allows(cx, ability) && self.1.allows(cx, ability)
328    }
329}
330
331/// The policy `or` returns: allows what either side allows.
332#[derive(Debug, Clone, Copy)]
333pub struct Or<A, B>(A, B);
334
335impl<M, A: Policy<M>, B: Policy<M>> Policy<M> for Or<A, B> {
336    fn allows(&self, cx: &Cx, ability: Ability<'_, M>) -> bool {
337        self.0.allows(cx, ability) || self.1.allows(cx, ability)
338    }
339}
340
341#[cfg(test)]
342mod tests;