larust_shield/lib.rs
1//! A lighter-weight take on `bezhansalleh/filament-shield` (a popular
2//! FilamentPHP plugin that auto-generates one CRUD-shaped permission bundle
3//! per admin-panel resource, then lets roles pick which abilities they
4//! carry) - requested directly, with an explicit "not to the degree they
5//! went on it" scope: no auto-scanning of `#[derive(Model)]` structs (this
6//! framework has no resource-registry to scan, and building one just for
7//! this would be new, load-bearing magic for a purely additive feature),
8//! and only the five abilities [`larust_auth::Policy`] already established
9//! (`view_any`/`view`/`create`/`update`/`delete`) - not Shield's fuller
10//! `delete_any`/`restore`/`force_delete`/... list, most of which have
11//! nothing real backing them in this codebase (migrations are
12//! forward-only, there's no soft-delete convention).
13//!
14//! An app declares its own resources exactly the way it already declares
15//! roles/permissions - a plain enum implementing one small marker trait:
16//!
17//! ```ignore
18//! #[derive(Copy, Clone)]
19//! enum Resource { Posts, Comments }
20//! impl larust_support::shield::ResourceName for Resource {
21//! fn name(&self) -> &'static str {
22//! match self {
23//! Resource::Posts => "posts",
24//! Resource::Comments => "comments",
25//! }
26//! }
27//! }
28//! ```
29//!
30//! [`ResourcePermission`] then implements [`larust_permissions::PermissionName`]
31//! directly - a `Resource` paired with an [`Ability`] *is* a permission, so
32//! every existing `larust-permissions` function
33//! (`create_permission`/`grant_role_permission`/`has_permission_to`/...)
34//! and both `@can`/`@role` Blade directives already understand it, with
35//! zero changes needed to either. This crate adds no new storage, no new
36//! tables, and no new checking primitive - only a second, resource-shaped
37//! way to name a permission `larust-permissions` already knows how to
38//! store and check.
39//!
40//! ```ignore
41//! shield::create_resource_permissions(Resource::Posts).await?; // all 5 at once
42//! shield::grant_resource_abilities(Role::Editor, Resource::Posts, &[Ability::View, Ability::Update]).await?;
43//! shield::can(&user, Resource::Posts, Ability::Update).await?; // bool
44//! shield::authorize_ability(&user, Resource::Posts, Ability::Update).await?; // straight to a 403
45//! ```
46//!
47//! ## Deliberately out of scope for this version
48//!
49//! - **No auto-discovery of resources.** An app lists its own resources by
50//! hand, the same way it already lists its own roles/permissions -
51//! consistent with this framework having no reflection-based registry
52//! anywhere else (see `docs/coming-from-laravel.md`'s "no service
53//! container, no reflection-based dependency injection").
54//! - **No admin UI for editing role/resource grants at runtime.** Shield's
55//! own headline feature is a settings screen; this crate is the
56//! underlying primitive an app could build one on top of, not the
57//! screen itself.
58//! - **No abilities beyond the five [`larust_auth::Policy`] already
59//! defines.** An app that genuinely needs `restore`/`force_delete`-style
60//! abilities can still reach `larust-permissions` directly with its own
61//! [`larust_permissions::PermissionName`] impl - this crate doesn't
62//! have to be the only way in.
63
64use larust_auth::{authorize, Authenticatable};
65use larust_core::AppError;
66use larust_permissions::{
67 create_permission, grant_role_permission, has_permission_to, PermissionName, RoleName,
68};
69use std::collections::HashMap;
70use std::sync::{Mutex, OnceLock};
71
72/// A caller-defined resource name - same shape and reasoning as
73/// [`larust_permissions::PermissionName`]/[`larust_permissions::RoleName`]:
74/// a plain enum, so a typo'd resource is a compile error, not a string
75/// that silently never matches anything.
76pub trait ResourceName: Copy + Send + Sync + 'static {
77 fn name(&self) -> &'static str;
78}
79
80/// The five abilities every resource gets, one-for-one with
81/// [`larust_auth::Policy`]'s own method names - deliberately not Shield's
82/// fuller list, see this crate's own doc comment for why.
83#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
84pub enum Ability {
85 ViewAny,
86 View,
87 Create,
88 Update,
89 Delete,
90}
91
92/// Every [`Ability`], in a fixed order - what [`create_resource_permissions`]
93/// creates all five of at once.
94pub const ALL_ABILITIES: [Ability; 5] = [
95 Ability::ViewAny,
96 Ability::View,
97 Ability::Create,
98 Ability::Update,
99 Ability::Delete,
100];
101
102impl Ability {
103 fn slug(self) -> &'static str {
104 match self {
105 Ability::ViewAny => "view-any",
106 Ability::View => "view",
107 Ability::Create => "create",
108 Ability::Update => "update",
109 Ability::Delete => "delete",
110 }
111 }
112}
113
114/// A `resource.ability` permission name, e.g. `"posts.update"` -
115/// [`PermissionName::name`] must return `&'static str`, but a resource's
116/// own name and an ability are only known at runtime once combined, so the
117/// composed string is built once per distinct pair and leaked into a
118/// small, process-wide cache (bounded by `resources × 5`, the same
119/// "leak a small, finite set of strings once" trick `Box::leak` is
120/// designed for) rather than reformatted - and re-leaked - on every call.
121fn interned_name(resource: &'static str, ability: Ability) -> &'static str {
122 static CACHE: OnceLock<Mutex<HashMap<(&'static str, Ability), &'static str>>> = OnceLock::new();
123 let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
124 let mut cache = cache
125 .lock()
126 .unwrap_or_else(|poisoned| poisoned.into_inner());
127 if let Some(existing) = cache.get(&(resource, ability)) {
128 return existing;
129 }
130 let leaked: &'static str = Box::leak(format!("{resource}.{}", ability.slug()).into_boxed_str());
131 cache.insert((resource, ability), leaked);
132 leaked
133}
134
135/// A resource paired with one ability - a real
136/// [`larust_permissions::PermissionName`], so every existing
137/// `larust-permissions` function and both `@can`/`@role` Blade directives
138/// already accept it directly.
139#[derive(Copy, Clone)]
140pub struct ResourcePermission<R: ResourceName> {
141 resource: R,
142 ability: Ability,
143}
144
145impl<R: ResourceName> ResourcePermission<R> {
146 pub fn new(resource: R, ability: Ability) -> Self {
147 Self { resource, ability }
148 }
149
150 pub fn view_any(resource: R) -> Self {
151 Self::new(resource, Ability::ViewAny)
152 }
153
154 pub fn view(resource: R) -> Self {
155 Self::new(resource, Ability::View)
156 }
157
158 pub fn create(resource: R) -> Self {
159 Self::new(resource, Ability::Create)
160 }
161
162 pub fn update(resource: R) -> Self {
163 Self::new(resource, Ability::Update)
164 }
165
166 pub fn delete(resource: R) -> Self {
167 Self::new(resource, Ability::Delete)
168 }
169}
170
171impl<R: ResourceName> PermissionName for ResourcePermission<R> {
172 fn name(&self) -> &'static str {
173 interned_name(self.resource.name(), self.ability)
174 }
175}
176
177/// [`create_permission`]s all five [`ALL_ABILITIES`] for `resource` at
178/// once - Shield's own "generate permissions for this resource" step,
179/// idempotent the same way [`create_permission`] itself already is.
180pub async fn create_resource_permissions<R: ResourceName>(resource: R) -> Result<(), AppError> {
181 for ability in ALL_ABILITIES {
182 create_permission(ResourcePermission::new(resource, ability)).await?;
183 }
184 Ok(())
185}
186
187/// [`grant_role_permission`] for exactly the abilities in `abilities` -
188/// Shield's own per-resource ability checkboxes on a role, as a single
189/// call: `grant_resource_abilities(Role::Editor, Resource::Posts,
190/// &[Ability::View, Ability::Update])` grants a role "can view and update
191/// posts, nothing else" in one line instead of one `grant_role_permission`
192/// call per ability. Each named permission must already exist (via
193/// [`create_resource_permissions`]) - same `NotFound`-on-an-uncreated-name
194/// contract every other `larust-permissions` write already has.
195pub async fn grant_resource_abilities<R: ResourceName>(
196 role: impl RoleName,
197 resource: R,
198 abilities: &[Ability],
199) -> Result<(), AppError> {
200 for &ability in abilities {
201 grant_role_permission(role, ResourcePermission::new(resource, ability)).await?;
202 }
203 Ok(())
204}
205
206/// `true` if `user` has `ability` on `resource` - [`has_permission_to`]
207/// under a resource-shaped name.
208pub async fn can<U: Authenticatable, R: ResourceName>(
209 user: &U,
210 resource: R,
211 ability: Ability,
212) -> Result<bool, AppError> {
213 has_permission_to(user, ResourcePermission::new(resource, ability)).await
214}
215
216/// [`can`], converted into a 403 on failure - same shape as
217/// [`larust_permissions::authorize_permission`].
218pub async fn authorize_ability<U: Authenticatable, R: ResourceName>(
219 user: &U,
220 resource: R,
221 ability: Ability,
222) -> Result<(), AppError> {
223 authorize(can(user, resource, ability).await?)
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229 use larust_permissions::{assign_role, has_role};
230
231 struct TestUser {
232 id: i64,
233 }
234
235 impl Authenticatable for TestUser {
236 fn auth_id(&self) -> i64 {
237 self.id
238 }
239
240 async fn find_for_auth(_id: i64) -> Result<Option<Self>, AppError> {
241 unreachable!("not exercised by this test")
242 }
243 }
244
245 #[derive(Copy, Clone)]
246 enum Resource {
247 Posts,
248 Comments,
249 }
250
251 impl ResourceName for Resource {
252 fn name(&self) -> &'static str {
253 match self {
254 Resource::Posts => "posts",
255 Resource::Comments => "comments",
256 }
257 }
258 }
259
260 #[derive(Copy, Clone)]
261 enum Role {
262 Editor,
263 }
264
265 impl RoleName for Role {
266 fn name(&self) -> &'static str {
267 match self {
268 Role::Editor => "editor",
269 }
270 }
271 }
272
273 async fn connect_test_db() {
274 let dir = tempfile::tempdir().unwrap().keep();
275 let database_url = format!("sqlite://{}/test.sqlite", dir.display());
276 larust_orm::connect(&database_url).await.unwrap();
277 }
278
279 #[tokio::test]
280 async fn resource_permissions_grant_exactly_the_abilities_a_role_was_given() {
281 connect_test_db().await;
282
283 create_resource_permissions(Resource::Posts).await.unwrap();
284 create_resource_permissions(Resource::Comments)
285 .await
286 .unwrap();
287
288 let alice = TestUser { id: 1 };
289 larust_permissions::create_role(Role::Editor).await.unwrap();
290 assign_role(&alice, Role::Editor).await.unwrap();
291
292 grant_resource_abilities(
293 Role::Editor,
294 Resource::Posts,
295 &[Ability::View, Ability::Update],
296 )
297 .await
298 .unwrap();
299
300 assert!(can(&alice, Resource::Posts, Ability::View).await.unwrap());
301 assert!(can(&alice, Resource::Posts, Ability::Update).await.unwrap());
302 // Only the two granted abilities - create/delete/view-any on
303 // Posts, and every ability on the untouched Comments resource,
304 // must still read false.
305 assert!(!can(&alice, Resource::Posts, Ability::Create).await.unwrap());
306 assert!(!can(&alice, Resource::Posts, Ability::Delete).await.unwrap());
307 assert!(!can(&alice, Resource::Posts, Ability::ViewAny)
308 .await
309 .unwrap());
310 assert!(!can(&alice, Resource::Comments, Ability::View)
311 .await
312 .unwrap());
313
314 authorize_ability(&alice, Resource::Posts, Ability::View)
315 .await
316 .unwrap();
317 match authorize_ability(&alice, Resource::Posts, Ability::Delete).await {
318 Err(AppError::Http { status, .. }) => {
319 assert_eq!(status, larust_core::axum::http::StatusCode::FORBIDDEN);
320 }
321 Err(other) => panic!("expected AppError::Http{{FORBIDDEN, ..}}, got {other:?}"),
322 Ok(()) => panic!("expected AppError::Http{{FORBIDDEN, ..}}, got Ok(())"),
323 }
324
325 // Sanity: has_role still works directly against the same role -
326 // ResourcePermission doesn't touch role storage at all.
327 assert!(has_role(&alice, Role::Editor).await.unwrap());
328 }
329}