Skip to main content

ignite_core/
policy.rs

1//! Who is acting, and what they may do with each record: the signed-in user the panel passes
2//! to a resource's queries, and the policies that decide each action for a user and a record.
3//!
4//! The model follows Laravel and Filament:
5//!
6//! - The panel builds an [`ActingUser`] from the session on each request, as Laravel's
7//!   `auth()->user()`, and passes it to the resource's queries: the `*_for` methods of
8//!   [`RuntimeData`](crate::RuntimeData) and [`IgniteResource`](crate::IgniteResource). A
9//!   resource restricts its list and its records to the user there, as a Filament resource
10//!   does in `getEloquentQuery()`. A record the user's query does not find is 404.
11//! - A [`Policy`] decides each action for the user and the record, as a Laravel policy does:
12//!   `view_any`, `view`, `create`, `update` and `delete`. It is registered for a resource's
13//!   slug with [`Registries::register_policy`], as `Gate::policy` maps a model to its policy. A resource
14//!   without a policy is decided by its abilities alone, as before.
15//!
16//! ```ignore
17//! struct OwnBooks;
18//!
19//! impl Policy for OwnBooks {
20//!     fn update<'a>(&'a self, _: &'a Database, user: &'a ActingUser, book: &'a Row)
21//!         -> RuntimeFuture<'a, bool> {
22//!         let own = book.get("author_id").and_then(|v| v.as_i64()) == Some(user.id());
23//!         Box::pin(async move { Ok(own) })
24//!     }
25//! }
26//!
27//! register_policy("books", OwnBooks);
28//! ```
29
30use std::collections::BTreeSet;
31use std::sync::{Arc, PoisonError};
32
33use orbit_orm::Database;
34
35use crate::registries::Registries;
36use crate::runtime_resource::{Row, RuntimeFuture};
37
38/// The signed-in user an action is done for: the panel builds it from the session on each
39/// request and passes it to the resource's queries and to its [`Policy`]. It holds the user's
40/// id, name and email, and the abilities their roles grant (such as `books.update`).
41///
42/// An app builds one itself only to call a resource or a policy outside the panel, such as in
43/// a test, with [`new`](Self::new), [`with_ability`](Self::with_ability) and
44/// [`with_super_admin`](Self::with_super_admin).
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct ActingUser {
47    id: i64,
48    name: String,
49    email: String,
50    super_admin: bool,
51    abilities: BTreeSet<String>,
52}
53
54impl ActingUser {
55    /// The user with `id`, `name` and `email`, with no abilities and no super-admin role.
56    pub fn new(id: i64, name: impl Into<String>, email: impl Into<String>) -> Self {
57        ActingUser {
58            id,
59            name: name.into(),
60            email: email.into(),
61            super_admin: false,
62            abilities: BTreeSet::new(),
63        }
64    }
65
66    /// Adds the ability `name`, such as `books.update`.
67    pub fn with_ability(mut self, name: impl Into<String>) -> Self {
68        self.abilities.insert(name.into());
69        self
70    }
71
72    /// Sets whether the user holds the `super-admin` role.
73    pub fn with_super_admin(mut self, super_admin: bool) -> Self {
74        self.super_admin = super_admin;
75        self
76    }
77
78    /// The user's id, the `id` of their row in `users`.
79    pub fn id(&self) -> i64 {
80        self.id
81    }
82
83    /// The user's name.
84    pub fn name(&self) -> &str {
85        &self.name
86    }
87
88    /// The user's email.
89    pub fn email(&self) -> &str {
90        &self.email
91    }
92
93    /// Whether the user holds the `super-admin` role, which passes every ability check and
94    /// every policy, as Filament Shield's super admin does.
95    pub fn is_super_admin(&self) -> bool {
96        self.super_admin
97    }
98
99    /// Whether the user may do `ability`, such as `books.update`: their roles grant it, or
100    /// they are a super-admin.
101    pub fn can(&self, ability: &str) -> bool {
102        self.super_admin || self.abilities.contains(ability)
103    }
104}
105
106/// An action on a resource as a whole, as the methods of a Filament resource policy
107/// (`viewAny`, `view`, `create`, `update`, `delete`): each needs the resource's ability for it,
108/// `<slug>.<action>` unless the resource names another (see
109/// [`RuntimeResource::ability`](crate::RuntimeResource::ability)).
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
111pub enum ResourceAction {
112    /// See the list and the navigation entry, as `viewAny`.
113    ViewAny,
114    /// See one record, as `view`.
115    View,
116    /// Open the new form and save it, as `create`.
117    Create,
118    /// Open the edit form and save it, as `update`.
119    Update,
120    /// Delete a record, as `delete`.
121    Delete,
122}
123
124impl ResourceAction {
125    /// Every action, in the order the panel registers their abilities.
126    pub const ALL: [ResourceAction; 5] = [
127        ResourceAction::ViewAny,
128        ResourceAction::View,
129        ResourceAction::Create,
130        ResourceAction::Update,
131        ResourceAction::Delete,
132    ];
133
134    /// The action's name as the policy method and the default ability spell it, such as
135    /// `"viewAny"`.
136    pub fn as_str(self) -> &'static str {
137        match self {
138            ResourceAction::ViewAny => "viewAny",
139            ResourceAction::View => "view",
140            ResourceAction::Create => "create",
141            ResourceAction::Update => "update",
142            ResourceAction::Delete => "delete",
143        }
144    }
145}
146
147/// What a user may do with the records of one resource, decided for the user and, where there
148/// is one, the record, as a Laravel policy decides. Register it for the resource's slug with
149/// [`Registries::register_policy`]. The record is the row as the resource returns it: a
150/// [`RuntimeData`](crate::RuntimeData)'s [`Row`], or a static resource's record serialized to
151/// JSON.
152///
153/// The panel asks the policy after the user's ability (`<slug>.<action>`), as a policy that
154/// Filament Shield generates checks the permission first: an action needs both. A super-admin
155/// passes without asking, as Shield's super admin passes before any policy. Every method
156/// allows by default, so a policy writes only the actions it restricts. An error is a server
157/// error (500), not a refusal.
158///
159/// - [`view_any`](Self::view_any): the list, and the resource in the navigation and on the
160///   dashboard.
161/// - [`view`](Self::view): one record. The panel has no detail page yet, so nothing asks it,
162///   as nothing checks the `view` ability.
163/// - [`create`](Self::create): the new form and its save.
164/// - [`update`](Self::update): the edit form and its save, and the Edit button of the record.
165/// - [`delete`](Self::delete): the delete action, and the Delete button of the record.
166///
167/// A refusal answers 403 Forbidden. Which records a user sees at all is the resource's query,
168/// not the policy: see [`ActingUser`].
169pub trait Policy: Send + Sync + 'static {
170    /// Whether `user` may see the list of the resource.
171    fn view_any<'a>(&'a self, db: &'a Database, user: &'a ActingUser) -> RuntimeFuture<'a, bool> {
172        let _ = (db, user);
173        Box::pin(async { Ok(true) })
174    }
175
176    /// Whether `user` may see `record`.
177    fn view<'a>(
178        &'a self,
179        db: &'a Database,
180        user: &'a ActingUser,
181        record: &'a Row,
182    ) -> RuntimeFuture<'a, bool> {
183        let _ = (db, user, record);
184        Box::pin(async { Ok(true) })
185    }
186
187    /// Whether `user` may create a record.
188    fn create<'a>(&'a self, db: &'a Database, user: &'a ActingUser) -> RuntimeFuture<'a, bool> {
189        let _ = (db, user);
190        Box::pin(async { Ok(true) })
191    }
192
193    /// Whether `user` may change `record`.
194    fn update<'a>(
195        &'a self,
196        db: &'a Database,
197        user: &'a ActingUser,
198        record: &'a Row,
199    ) -> RuntimeFuture<'a, bool> {
200        let _ = (db, user, record);
201        Box::pin(async { Ok(true) })
202    }
203
204    /// Whether `user` may delete `record`.
205    fn delete<'a>(
206        &'a self,
207        db: &'a Database,
208        user: &'a ActingUser,
209        record: &'a Row,
210    ) -> RuntimeFuture<'a, bool> {
211        let _ = (db, user, record);
212        Box::pin(async { Ok(true) })
213    }
214}
215
216impl Registries {
217    /// Registers `policy` for the resource at `slug`, static or runtime, as Laravel's
218    /// `Gate::policy` maps a model to its policy. It takes effect from the next request on, and
219    /// replaces the policy the slug had. The slug need not be registered yet: a policy is kept
220    /// when its runtime resource is removed and registered again.
221    pub fn register_policy(&self, slug: impl Into<String>, policy: impl Policy) {
222        self.inner
223            .policies
224            .write()
225            .unwrap_or_else(PoisonError::into_inner)
226            .insert(slug.into(), Arc::new(policy));
227    }
228
229    /// Removes the policy of the resource at `slug`, so its abilities alone decide again.
230    /// Returns whether it had one.
231    pub fn unregister_policy(&self, slug: &str) -> bool {
232        self.inner
233            .policies
234            .write()
235            .unwrap_or_else(PoisonError::into_inner)
236            .remove(slug)
237            .is_some()
238    }
239
240    /// The policy of the resource at `slug`, if one is registered.
241    pub fn policy(&self, slug: &str) -> Option<Arc<dyn Policy>> {
242        self.inner
243            .policies
244            .read()
245            .unwrap_or_else(PoisonError::into_inner)
246            .get(slug)
247            .cloned()
248    }
249}
250
251/// Registers `policy` for the resource at `slug` on the default app, as 0.7.1 did. See
252/// [`Registries::register_policy`](crate::Registries::register_policy).
253pub fn register_policy(slug: impl Into<String>, policy: impl Policy) {
254    crate::Registries::default_app().register_policy(slug, policy);
255}
256
257/// Removes the policy of `slug` from the default app. See
258/// [`Registries::unregister_policy`](crate::Registries::unregister_policy).
259pub fn unregister_policy(slug: &str) -> bool {
260    crate::Registries::default_app().unregister_policy(slug)
261}
262
263/// The policy of `slug` on the default app. See
264/// [`Registries::policy`](crate::Registries::policy).
265pub fn policy(slug: &str) -> Option<Arc<dyn Policy>> {
266    crate::Registries::default_app().policy(slug)
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    #[test]
274    fn a_user_can_what_their_roles_grant() {
275        let user = ActingUser::new(7, "Ada", "ada@example.test").with_ability("books.update");
276        assert_eq!(user.id(), 7);
277        assert_eq!(user.name(), "Ada");
278        assert_eq!(user.email(), "ada@example.test");
279        assert!(user.can("books.update"));
280        assert!(!user.can("books.delete"));
281        assert!(!user.is_super_admin());
282    }
283
284    #[test]
285    fn a_super_admin_can_everything() {
286        let user = ActingUser::new(1, "Root", "root@example.test").with_super_admin(true);
287        assert!(user.is_super_admin());
288        assert!(user.can("books.delete"));
289        assert!(user.can("anything.at.all"));
290    }
291
292    // The panel's tests check that a policy's unwritten methods allow, on a database.
293    struct Nothing;
294
295    impl Policy for Nothing {}
296
297    #[test]
298    fn a_policy_is_registered_replaced_and_removed_by_slug() {
299        let registries = Registries::new();
300        assert!(registries.policy("policy-unit-books").is_none());
301        registries.register_policy("policy-unit-books", Nothing);
302        registries.register_policy("policy-unit-books", Nothing);
303        assert!(registries.policy("policy-unit-books").is_some());
304        assert!(registries.policy("policy-unit-other").is_none());
305        assert!(Registries::new().policy("policy-unit-books").is_none());
306        assert!(registries.unregister_policy("policy-unit-books"));
307        assert!(!registries.unregister_policy("policy-unit-books"));
308        assert!(registries.policy("policy-unit-books").is_none());
309    }
310}