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/// An action on a resource as a whole, as the methods of a Filament resource policy
106/// (`viewAny`, `view`, `create`, `update`, `delete`): each needs the resource's ability for it,
107/// `<slug>.<action>` unless the resource names another (see
108/// [`RuntimeResource::ability`](crate::RuntimeResource::ability)).
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
110pub enum ResourceAction {
111 /// See the list and the navigation entry, as `viewAny`.
112 ViewAny,
113 /// See one record, as `view`.
114 View,
115 /// Open the new form and save it, as `create`.
116 Create,
117 /// Open the edit form and save it, as `update`.
118 Update,
119 /// Delete a record, as `delete`.
120 Delete,
121}
122
123impl ResourceAction {
124 /// Every action, in the order the panel registers their abilities.
125 pub const ALL: [ResourceAction; 5] = [
126 ResourceAction::ViewAny,
127 ResourceAction::View,
128 ResourceAction::Create,
129 ResourceAction::Update,
130 ResourceAction::Delete,
131 ];
132
133 /// The action's name as the policy method and the default ability spell it, such as
134 /// `"viewAny"`.
135 pub fn as_str(self) -> &'static str {
136 match self {
137 ResourceAction::ViewAny => "viewAny",
138 ResourceAction::View => "view",
139 ResourceAction::Create => "create",
140 ResourceAction::Update => "update",
141 ResourceAction::Delete => "delete",
142 }
143 }
144}
145
146/// What a user may do with the records of one resource, decided for the user and, where there
147/// is one, the record, as a Laravel policy decides. Register it for the resource's slug with
148/// [`register_policy`]. The record is the row as the resource returns it: a
149/// [`RuntimeData`](crate::RuntimeData)'s [`Row`], or a static resource's record serialized to
150/// JSON.
151///
152/// The panel asks the policy after the user's ability (`<slug>.<action>`), as a policy that
153/// Filament Shield generates checks the permission first: an action needs both. A super-admin
154/// passes without asking, as Shield's super admin passes before any policy. Every method
155/// allows by default, so a policy writes only the actions it restricts. An error is a server
156/// error (500), not a refusal.
157///
158/// - [`view_any`](Self::view_any): the list, and the resource in the navigation and on the
159/// dashboard.
160/// - [`view`](Self::view): one record. The panel has no detail page yet, so nothing asks it,
161/// as nothing checks the `view` ability.
162/// - [`create`](Self::create): the new form and its save.
163/// - [`update`](Self::update): the edit form and its save, and the Edit button of the record.
164/// - [`delete`](Self::delete): the delete action, and the Delete button of the record.
165///
166/// A refusal answers 403 Forbidden. Which records a user sees at all is the resource's query,
167/// not the policy: see [`ActingUser`].
168pub trait Policy: Send + Sync + 'static {
169 /// Whether `user` may see the list of the resource.
170 fn view_any<'a>(&'a self, db: &'a Database, user: &'a ActingUser) -> RuntimeFuture<'a, bool> {
171 let _ = (db, user);
172 Box::pin(async { Ok(true) })
173 }
174
175 /// Whether `user` may see `record`.
176 fn view<'a>(
177 &'a self,
178 db: &'a Database,
179 user: &'a ActingUser,
180 record: &'a Row,
181 ) -> RuntimeFuture<'a, bool> {
182 let _ = (db, user, record);
183 Box::pin(async { Ok(true) })
184 }
185
186 /// Whether `user` may create a record.
187 fn create<'a>(&'a self, db: &'a Database, user: &'a ActingUser) -> RuntimeFuture<'a, bool> {
188 let _ = (db, user);
189 Box::pin(async { Ok(true) })
190 }
191
192 /// Whether `user` may change `record`.
193 fn update<'a>(
194 &'a self,
195 db: &'a Database,
196 user: &'a ActingUser,
197 record: &'a Row,
198 ) -> RuntimeFuture<'a, bool> {
199 let _ = (db, user, record);
200 Box::pin(async { Ok(true) })
201 }
202
203 /// Whether `user` may delete `record`.
204 fn delete<'a>(
205 &'a self,
206 db: &'a Database,
207 user: &'a ActingUser,
208 record: &'a Row,
209 ) -> RuntimeFuture<'a, bool> {
210 let _ = (db, user, record);
211 Box::pin(async { Ok(true) })
212 }
213}
214
215/// The policies, by the slug of their resource.
216static POLICIES: RwLock<Option<HashMap<String, Arc<dyn Policy>>>> = RwLock::new(None);
217
218/// Registers `policy` for the resource at `slug`, static or runtime, as Laravel's
219/// `Gate::policy` maps a model to its policy. It takes effect from the next request on, and
220/// replaces the policy the slug had. The slug need not be registered yet: a policy is kept when
221/// its runtime resource is removed and registered again.
222pub fn register_policy(slug: impl Into<String>, policy: impl Policy) {
223 let mut guard = POLICIES.write().unwrap_or_else(PoisonError::into_inner);
224 guard
225 .get_or_insert_with(HashMap::new)
226 .insert(slug.into(), Arc::new(policy));
227}
228
229/// Removes the policy of the resource at `slug`, so its abilities alone decide again. Returns
230/// whether it had one.
231pub fn unregister_policy(slug: &str) -> bool {
232 let mut guard = POLICIES.write().unwrap_or_else(PoisonError::into_inner);
233 guard
234 .as_mut()
235 .is_some_and(|policies| policies.remove(slug).is_some())
236}
237
238/// The policy of the resource at `slug`, if one is registered.
239pub fn policy(slug: &str) -> Option<Arc<dyn Policy>> {
240 let guard = POLICIES.read().unwrap_or_else(PoisonError::into_inner);
241 guard
242 .as_ref()
243 .and_then(|policies| policies.get(slug).cloned())
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 #[test]
251 fn a_user_can_what_their_roles_grant() {
252 let user = ActingUser::new(7, "Ada", "ada@example.test").with_ability("books.update");
253 assert_eq!(user.id(), 7);
254 assert_eq!(user.name(), "Ada");
255 assert_eq!(user.email(), "ada@example.test");
256 assert!(user.can("books.update"));
257 assert!(!user.can("books.delete"));
258 assert!(!user.is_super_admin());
259 }
260
261 #[test]
262 fn a_super_admin_can_everything() {
263 let user = ActingUser::new(1, "Root", "root@example.test").with_super_admin(true);
264 assert!(user.is_super_admin());
265 assert!(user.can("books.delete"));
266 assert!(user.can("anything.at.all"));
267 }
268
269 // The panel's tests check that a policy's unwritten methods allow, on a database.
270 struct Nothing;
271
272 impl Policy for Nothing {}
273
274 #[test]
275 fn a_policy_is_registered_replaced_and_removed_by_slug() {
276 assert!(policy("policy-unit-books").is_none());
277 register_policy("policy-unit-books", Nothing);
278 register_policy("policy-unit-books", Nothing);
279 assert!(policy("policy-unit-books").is_some());
280 assert!(policy("policy-unit-other").is_none());
281 assert!(unregister_policy("policy-unit-books"));
282 assert!(!unregister_policy("policy-unit-books"));
283 assert!(policy("policy-unit-books").is_none());
284 }
285}