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 [`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, HashMap};
31use std::sync::{Arc, PoisonError, RwLock};
32
33use orbit_orm::Database;
34
35use crate::runtime_resource::{Row, RuntimeFuture};
36
37/// The signed-in user an action is done for: the panel builds it from the session on each
38/// request and passes it to the resource's queries and to its [`Policy`]. It holds the user's
39/// id, name and email, and the abilities their roles grant (such as `books.update`).
40///
41/// An app builds one itself only to call a resource or a policy outside the panel, such as in
42/// a test, with [`new`](Self::new), [`with_ability`](Self::with_ability) and
43/// [`with_super_admin`](Self::with_super_admin).
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct ActingUser {
46 id: i64,
47 name: String,
48 email: String,
49 super_admin: bool,
50 abilities: BTreeSet<String>,
51}
52
53impl ActingUser {
54 /// The user with `id`, `name` and `email`, with no abilities and no super-admin role.
55 pub fn new(id: i64, name: impl Into<String>, email: impl Into<String>) -> Self {
56 ActingUser {
57 id,
58 name: name.into(),
59 email: email.into(),
60 super_admin: false,
61 abilities: BTreeSet::new(),
62 }
63 }
64
65 /// Adds the ability `name`, such as `books.update`.
66 pub fn with_ability(mut self, name: impl Into<String>) -> Self {
67 self.abilities.insert(name.into());
68 self
69 }
70
71 /// Sets whether the user holds the `super-admin` role.
72 pub fn with_super_admin(mut self, super_admin: bool) -> Self {
73 self.super_admin = super_admin;
74 self
75 }
76
77 /// The user's id, the `id` of their row in `users`.
78 pub fn id(&self) -> i64 {
79 self.id
80 }
81
82 /// The user's name.
83 pub fn name(&self) -> &str {
84 &self.name
85 }
86
87 /// The user's email.
88 pub fn email(&self) -> &str {
89 &self.email
90 }
91
92 /// Whether the user holds the `super-admin` role, which passes every ability check and
93 /// every policy, as Filament Shield's super admin does.
94 pub fn is_super_admin(&self) -> bool {
95 self.super_admin
96 }
97
98 /// Whether the user may do `ability`, such as `books.update`: their roles grant it, or
99 /// they are a super-admin.
100 pub fn can(&self, ability: &str) -> bool {
101 self.super_admin || self.abilities.contains(ability)
102 }
103}
104
105/// What a user may do with the records of one resource, decided for the user and, where there
106/// is one, the record, as a Laravel policy decides. Register it for the resource's slug with
107/// [`register_policy`]. The record is the row as the resource returns it: a
108/// [`RuntimeData`](crate::RuntimeData)'s [`Row`], or a static resource's record serialized to
109/// JSON.
110///
111/// The panel asks the policy after the user's ability (`<slug>.<action>`), as a policy that
112/// Filament Shield generates checks the permission first: an action needs both. A super-admin
113/// passes without asking, as Shield's super admin passes before any policy. Every method
114/// allows by default, so a policy writes only the actions it restricts. An error is a server
115/// error (500), not a refusal.
116///
117/// - [`view_any`](Self::view_any): the list, and the resource in the navigation and on the
118/// dashboard.
119/// - [`view`](Self::view): one record. The panel has no detail page yet, so nothing asks it,
120/// as nothing checks the `view` ability.
121/// - [`create`](Self::create): the new form and its save.
122/// - [`update`](Self::update): the edit form and its save, and the Edit button of the record.
123/// - [`delete`](Self::delete): the delete action, and the Delete button of the record.
124///
125/// A refusal answers 403 Forbidden. Which records a user sees at all is the resource's query,
126/// not the policy: see [`ActingUser`].
127pub trait Policy: Send + Sync + 'static {
128 /// Whether `user` may see the list of the resource.
129 fn view_any<'a>(&'a self, db: &'a Database, user: &'a ActingUser) -> RuntimeFuture<'a, bool> {
130 let _ = (db, user);
131 Box::pin(async { Ok(true) })
132 }
133
134 /// Whether `user` may see `record`.
135 fn view<'a>(
136 &'a self,
137 db: &'a Database,
138 user: &'a ActingUser,
139 record: &'a Row,
140 ) -> RuntimeFuture<'a, bool> {
141 let _ = (db, user, record);
142 Box::pin(async { Ok(true) })
143 }
144
145 /// Whether `user` may create a record.
146 fn create<'a>(&'a self, db: &'a Database, user: &'a ActingUser) -> RuntimeFuture<'a, bool> {
147 let _ = (db, user);
148 Box::pin(async { Ok(true) })
149 }
150
151 /// Whether `user` may change `record`.
152 fn update<'a>(
153 &'a self,
154 db: &'a Database,
155 user: &'a ActingUser,
156 record: &'a Row,
157 ) -> RuntimeFuture<'a, bool> {
158 let _ = (db, user, record);
159 Box::pin(async { Ok(true) })
160 }
161
162 /// Whether `user` may delete `record`.
163 fn delete<'a>(
164 &'a self,
165 db: &'a Database,
166 user: &'a ActingUser,
167 record: &'a Row,
168 ) -> RuntimeFuture<'a, bool> {
169 let _ = (db, user, record);
170 Box::pin(async { Ok(true) })
171 }
172}
173
174/// The policies, by the slug of their resource.
175static POLICIES: RwLock<Option<HashMap<String, Arc<dyn Policy>>>> = RwLock::new(None);
176
177/// Registers `policy` for the resource at `slug`, static or runtime, as Laravel's
178/// `Gate::policy` maps a model to its policy. It takes effect from the next request on, and
179/// replaces the policy the slug had. The slug need not be registered yet: a policy is kept when
180/// its runtime resource is removed and registered again.
181pub fn register_policy(slug: impl Into<String>, policy: impl Policy) {
182 let mut guard = POLICIES.write().unwrap_or_else(PoisonError::into_inner);
183 guard
184 .get_or_insert_with(HashMap::new)
185 .insert(slug.into(), Arc::new(policy));
186}
187
188/// Removes the policy of the resource at `slug`, so its abilities alone decide again. Returns
189/// whether it had one.
190pub fn unregister_policy(slug: &str) -> bool {
191 let mut guard = POLICIES.write().unwrap_or_else(PoisonError::into_inner);
192 guard
193 .as_mut()
194 .is_some_and(|policies| policies.remove(slug).is_some())
195}
196
197/// The policy of the resource at `slug`, if one is registered.
198pub fn policy(slug: &str) -> Option<Arc<dyn Policy>> {
199 let guard = POLICIES.read().unwrap_or_else(PoisonError::into_inner);
200 guard
201 .as_ref()
202 .and_then(|policies| policies.get(slug).cloned())
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 #[test]
210 fn a_user_can_what_their_roles_grant() {
211 let user = ActingUser::new(7, "Ada", "ada@example.test").with_ability("books.update");
212 assert_eq!(user.id(), 7);
213 assert_eq!(user.name(), "Ada");
214 assert_eq!(user.email(), "ada@example.test");
215 assert!(user.can("books.update"));
216 assert!(!user.can("books.delete"));
217 assert!(!user.is_super_admin());
218 }
219
220 #[test]
221 fn a_super_admin_can_everything() {
222 let user = ActingUser::new(1, "Root", "root@example.test").with_super_admin(true);
223 assert!(user.is_super_admin());
224 assert!(user.can("books.delete"));
225 assert!(user.can("anything.at.all"));
226 }
227
228 // The panel's tests check that a policy's unwritten methods allow, on a database.
229 struct Nothing;
230
231 impl Policy for Nothing {}
232
233 #[test]
234 fn a_policy_is_registered_replaced_and_removed_by_slug() {
235 assert!(policy("policy-unit-books").is_none());
236 register_policy("policy-unit-books", Nothing);
237 register_policy("policy-unit-books", Nothing);
238 assert!(policy("policy-unit-books").is_some());
239 assert!(policy("policy-unit-other").is_none());
240 assert!(unregister_policy("policy-unit-books"));
241 assert!(!unregister_policy("policy-unit-books"));
242 assert!(policy("policy-unit-books").is_none());
243 }
244}