larust_permissions/lib.rs
1//! Roles and permissions - Laravel's `spatie/laravel-permission`, the
2//! single most commonly-installed third-party Laravel package (see
3//! `crates/larust-convert/src/composer.rs`'s `TIER_1` table, which points
4//! here for it), narrowed to its core role/permission-assignment shape.
5//!
6//! **A hybrid design, not a straight port** - worth explaining up front,
7//! since it deliberately bends a rule this codebase otherwise holds hard.
8//! `larust_auth::Policy`'s own doc comment states the house style plainly:
9//! "a typo in an ability name is a compile error, not a silently-always-
10//! false runtime lookup." Spatie's package is the opposite by *design* -
11//! an admin edits roles and permissions from a settings screen, with no
12//! redeploy, which is the entire point of the package existing instead of
13//! everyone just writing `Policy` methods. That's genuinely runtime data,
14//! not a corner this crate is cutting.
15//!
16//! So the split is: **names are compile-checked, assignment is not.** An
17//! app defines its own permission/role set as a plain Rust type
18//! implementing [`PermissionName`]/[`RoleName`] - a typo in
19//! `Permission::EditPosts` is caught by `rustc`, same as any other
20//! misspelled identifier. What *is* runtime data, stored in SQLite, is
21//! purely the assignment graph: which roles exist, which permissions each
22//! role carries, and which users have which roles/permissions - exactly
23//! the part an admin actually needs to change without a redeploy.
24//!
25//! Re-exported through `larust_support::permission` (see
26//! `crates/larust-support/src/lib.rs`) so generated apps depend only on
27//! `larust-support`, never on this crate directly.
28//!
29//! **`@can(expr)`/`@role(expr)` template directives now exist** (see
30//! `larust_view::ast::Node::Can`/`Node::Role`, and their codegen in
31//! `larust-macros/src/view.rs`) - a `.blade.xr` template checks
32//! `has_permission_to`/`has_role` directly, without a route handler
33//! pre-computing a bool and passing it in as a plain context variable.
34//! `expr` is a raw Rust expression (`@can(Permission::EditPosts)`, not a
35//! quoted string), carrying this crate's own "names are compile-checked"
36//! half of its hybrid design all the way into templates - a typo'd
37//! variant name is a `rustc` error at the template's own call site, the
38//! same guarantee this crate's Rust-side callers already have. Requires a
39//! `user: &U` (`U: Authenticatable`) binding in the `view!` context and an
40//! async, `Result`-returning call site, checked eagerly at macro-expansion
41//! time - the same shape `@wire(...)`'s own `session` requirement already
42//! established.
43//!
44//! **[`AdminRole`]/[`is_admin`]/[`authorize_admin`]** are Laravel's
45//! `$user->isAdmin()` - a compile-checked marker trait naming which of an
46//! app's own [`RoleName`] variants is the "admin" one, rather than a
47//! hardcoded `"admin"` string that would silently never match an app
48//! whose top role happens to be spelled differently (this repo's own
49//! `demo` app calls its top role `Role::Moderator`).
50//!
51//! ## Deliberately out of scope for this version
52//!
53//! - **No `role:admin`/`permission:edit-posts` middleware-string
54//! recognition** in `xr convert`. `crates/larust-convert/src/routes.rs`
55//! already blanket-defers every `Route::middleware(...)->group(...)`
56//! call, deliberately (its own doc comment: "exactly the kind of
57//! semantic judgment call this phase avoids") - this crate doesn't
58//! special-case spatie's own aliases within that existing boundary.
59
60use larust_auth::{authorize, Authenticatable};
61use larust_core::AppError;
62use larust_orm::Backend;
63use sqlx::AnyPool;
64use std::collections::HashSet;
65use std::sync::{Mutex, OnceLock};
66
67/// A caller-defined permission name - implemented on an app's own enum
68/// (or unit structs), the same "typo is a compile error" precedent
69/// `larust_auth::Policy`/`larust_queue::Job::JOB_TYPE`/
70/// `larust_notifications::Notification::NOTIFICATION_TYPE` already set. A
71/// method, not an associated const, because an app's permission set is
72/// naturally one enum with many variants, and Rust has no per-variant
73/// associated consts:
74///
75/// ```ignore
76/// #[derive(Copy, Clone)]
77/// enum Permission { EditPosts, DeleteUsers }
78/// impl larust_support::permission::PermissionName for Permission {
79/// fn name(&self) -> &'static str {
80/// match self {
81/// Permission::EditPosts => "edit-posts",
82/// Permission::DeleteUsers => "delete-users",
83/// }
84/// }
85/// }
86/// ```
87pub trait PermissionName: Copy + Send + Sync + 'static {
88 fn name(&self) -> &'static str;
89}
90
91/// A caller-defined role name - see [`PermissionName`]'s own doc comment,
92/// same shape and same reasoning.
93pub trait RoleName: Copy + Send + Sync + 'static {
94 fn name(&self) -> &'static str;
95}
96
97/// Names which of an app's own [`RoleName`] variants is its "admin" one -
98/// Laravel's own `$user->isAdmin()` is usually a hand-rolled method apps
99/// write for themselves (there's no such method on Laravel's base `User`);
100/// this is the compile-checked equivalent, one implementation per app
101/// instead of one per project reinventing the same `hasRole('admin')`
102/// one-liner. Deliberately a trait, not a hardcoded `"admin"` string
103/// literal baked into [`is_admin`] itself - this crate has no way to know
104/// an app's own role variant is actually *named* `Admin` (the demo app's
105/// own top-level role, for instance, is `Role::Moderator`), and a magic
106/// string would be exactly the "silently-always-false on a typo" failure
107/// mode this crate's own module doc comment says it avoids everywhere
108/// else. One method, returning the app's own designated variant:
109///
110/// ```ignore
111/// impl larust_support::permission::AdminRole for Role {
112/// fn admin() -> Self { Role::Admin }
113/// }
114/// ```
115pub trait AdminRole: RoleName {
116 fn admin() -> Self;
117}
118
119/// Same lazy self-bootstrap idiom `larust-notifications`'s `ensure_table`
120/// establishes - plain `CREATE TABLE IF NOT EXISTS` statements, no
121/// migration file and no explicit startup call needed anywhere.
122///
123/// Memoized, but **not** behind a single process-wide flag - that was a
124/// real regression once already (see `larust-notifications`'s own doc
125/// comment): `larust_testing::test_transaction` swaps in a *different*
126/// `&'static AnyPool` per test (a fresh, never-migrated-by-this-module
127/// database), so one global "already ensured" bool would wrongly skip
128/// table creation for a database that never actually got it. Keyed by
129/// the pool's own memory address instead: production always resolves the
130/// same process-wide pool (`larust_orm::pool()`'s own `OnceLock`), so
131/// this ensures once for the life of the process; each test's own
132/// swapped-in pool is a different address, so it gets its own cache entry
133/// and is ensured fresh. Safe to key on the raw address rather than the
134/// pool's identity via some other means: a pool is never deallocated
135/// before process exit (the process-wide one lives in a `OnceLock` that's
136/// never cleared; a test's own lives for that whole test), so no address
137/// is ever reused by an unrelated pool while an entry for it is still
138/// live in this cache. The short lock below is only ever held for a
139/// `HashSet` lookup/insert, never across the `.await` calls that actually
140/// touch the database, so concurrent callers first hitting a genuinely
141/// new pool can't serialize behind each other here - at worst, more than
142/// one of them redundantly runs the (idempotent, `IF NOT EXISTS`)
143/// statements once before the cache entry lands, which is still strictly
144/// better than every call paying that cost forever.
145///
146/// `user_id`/`role_id`/`permission_id` are plain `INTEGER`, not typed
147/// foreign keys into an app-owned `users` table this crate has no
148/// visibility into - the same reasoning `larust-notifications`'s own
149/// `notifiable_id` column already uses. `user_permissions` (direct,
150/// role-independent grants) covers spatie's own "direct permission" case,
151/// for fidelity with the package this is standing in for.
152async fn ensure_tables(pool: &AnyPool) -> Result<(), AppError> {
153 static ENSURED_POOLS: OnceLock<Mutex<HashSet<usize>>> = OnceLock::new();
154 let key = pool as *const AnyPool as usize;
155 let cache = ENSURED_POOLS.get_or_init(|| Mutex::new(HashSet::new()));
156 if cache
157 .lock()
158 .unwrap_or_else(|poisoned| poisoned.into_inner())
159 .contains(&key)
160 {
161 return Ok(());
162 }
163
164 let (roles_table, permissions_table) = match larust_orm::backend() {
165 Backend::Sqlite => (
166 "CREATE TABLE IF NOT EXISTS roles (\
167 id INTEGER PRIMARY KEY AUTOINCREMENT, \
168 name TEXT NOT NULL UNIQUE\
169 )",
170 "CREATE TABLE IF NOT EXISTS permissions (\
171 id INTEGER PRIMARY KEY AUTOINCREMENT, \
172 name TEXT NOT NULL UNIQUE\
173 )",
174 ),
175 Backend::MySql => (
176 "CREATE TABLE IF NOT EXISTS roles (\
177 id INTEGER PRIMARY KEY AUTO_INCREMENT, \
178 name VARCHAR(255) NOT NULL UNIQUE\
179 )",
180 "CREATE TABLE IF NOT EXISTS permissions (\
181 id INTEGER PRIMARY KEY AUTO_INCREMENT, \
182 name VARCHAR(255) NOT NULL UNIQUE\
183 )",
184 ),
185 Backend::Postgres => (
186 "CREATE TABLE IF NOT EXISTS roles (\
187 id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
188 name TEXT NOT NULL UNIQUE\
189 )",
190 "CREATE TABLE IF NOT EXISTS permissions (\
191 id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
192 name TEXT NOT NULL UNIQUE\
193 )",
194 ),
195 };
196
197 for statement in [
198 roles_table,
199 permissions_table,
200 "CREATE TABLE IF NOT EXISTS role_permissions (\
201 role_id INTEGER NOT NULL REFERENCES roles(id), \
202 permission_id INTEGER NOT NULL REFERENCES permissions(id), \
203 PRIMARY KEY (role_id, permission_id)\
204 )",
205 "CREATE TABLE IF NOT EXISTS user_roles (\
206 user_id INTEGER NOT NULL, \
207 role_id INTEGER NOT NULL REFERENCES roles(id), \
208 PRIMARY KEY (user_id, role_id)\
209 )",
210 "CREATE TABLE IF NOT EXISTS user_permissions (\
211 user_id INTEGER NOT NULL, \
212 permission_id INTEGER NOT NULL REFERENCES permissions(id), \
213 PRIMARY KEY (user_id, permission_id)\
214 )",
215 ] {
216 sqlx::query(statement)
217 .execute(pool)
218 .await
219 .map_err(|source| AppError::Internal(Box::new(source)))?;
220 }
221
222 cache
223 .lock()
224 .unwrap_or_else(|poisoned| poisoned.into_inner())
225 .insert(key);
226 Ok(())
227}
228
229/// Three different ways to say "insert this row, and if it collides with
230/// an existing unique/primary key, silently do nothing instead of
231/// erroring": `INSERT OR IGNORE` (SQLite), `INSERT IGNORE` (MySQL), and
232/// `INSERT ... ON CONFLICT DO NOTHING` (Postgres - no `INSERT OR IGNORE`
233/// syntax at all, and the conflict clause goes at the *end*, not as a
234/// prefix verb, unlike the other two). Every one of this crate's 5
235/// idempotent-insert call sites builds its SQL through this one function
236/// instead of duplicating the three-way branch (and, for Postgres, its own
237/// `$N` placeholder numbering - see `larust_orm::placeholder`) five times.
238fn insert_ignore_sql(table: &str, columns: &[&str]) -> String {
239 let backend = larust_orm::backend();
240 let column_list = columns.join(", ");
241 let placeholders = (1..=columns.len())
242 .map(|n| larust_orm::placeholder(backend, n))
243 .collect::<Vec<_>>()
244 .join(", ");
245 match backend {
246 Backend::Sqlite => {
247 format!("INSERT OR IGNORE INTO {table} ({column_list}) VALUES ({placeholders})")
248 }
249 Backend::MySql => {
250 format!("INSERT IGNORE INTO {table} ({column_list}) VALUES ({placeholders})")
251 }
252 Backend::Postgres => format!(
253 "INSERT INTO {table} ({column_list}) VALUES ({placeholders}) ON CONFLICT DO NOTHING"
254 ),
255 }
256}
257
258async fn role_id(pool: &AnyPool, role: &str) -> Result<Option<i64>, AppError> {
259 let sql = format!(
260 "SELECT id FROM roles WHERE name = {}",
261 larust_orm::placeholder(larust_orm::backend(), 1)
262 );
263 let row: Option<(i64,)> = sqlx::query_as(&sql)
264 .bind(role)
265 .fetch_optional(pool)
266 .await
267 .map_err(|source| AppError::Internal(Box::new(source)))?;
268 Ok(row.map(|(id,)| id))
269}
270
271async fn permission_id(pool: &AnyPool, permission: &str) -> Result<Option<i64>, AppError> {
272 let sql = format!(
273 "SELECT id FROM permissions WHERE name = {}",
274 larust_orm::placeholder(larust_orm::backend(), 1)
275 );
276 let row: Option<(i64,)> = sqlx::query_as(&sql)
277 .bind(permission)
278 .fetch_optional(pool)
279 .await
280 .map_err(|source| AppError::Internal(Box::new(source)))?;
281 Ok(row.map(|(id,)| id))
282}
283
284/// Creates `role` if it doesn't already exist - idempotent (`INSERT OR
285/// IGNORE`), matching the `Role::firstOrCreate`-style call a spatie-backed
286/// app's own seeder would make. Typically called once, at app boot or
287/// from a seeder, for every variant of the app's `RoleName` enum.
288pub async fn create_role(role: impl RoleName) -> Result<(), AppError> {
289 let pool = larust_orm::pool()?;
290 ensure_tables(pool).await?;
291 sqlx::query(&insert_ignore_sql("roles", &["name"]))
292 .bind(role.name())
293 .execute(pool)
294 .await
295 .map_err(|source| AppError::Internal(Box::new(source)))?;
296 Ok(())
297}
298
299/// Creates `permission` if it doesn't already exist - see [`create_role`],
300/// same idempotent shape.
301pub async fn create_permission(permission: impl PermissionName) -> Result<(), AppError> {
302 let pool = larust_orm::pool()?;
303 ensure_tables(pool).await?;
304 sqlx::query(&insert_ignore_sql("permissions", &["name"]))
305 .bind(permission.name())
306 .execute(pool)
307 .await
308 .map_err(|source| AppError::Internal(Box::new(source)))?;
309 Ok(())
310}
311
312/// Grants `role` the ability to do `permission` - every user later
313/// assigned `role` inherits it (see [`has_permission_to`]). `NotFound` if
314/// either `role` or `permission` hasn't been [`create_role`]/
315/// [`create_permission`]d yet - deliberately not auto-created from this
316/// call, so a typo'd name here fails loudly instead of silently seeding a
317/// stray row nothing else references.
318pub async fn grant_role_permission(
319 role: impl RoleName,
320 permission: impl PermissionName,
321) -> Result<(), AppError> {
322 let pool = larust_orm::pool()?;
323 ensure_tables(pool).await?;
324
325 let Some(role_id) = role_id(pool, role.name()).await? else {
326 return Err(AppError::NotFound);
327 };
328 let Some(permission_id) = permission_id(pool, permission.name()).await? else {
329 return Err(AppError::NotFound);
330 };
331
332 sqlx::query(&insert_ignore_sql(
333 "role_permissions",
334 &["role_id", "permission_id"],
335 ))
336 .bind(role_id)
337 .bind(permission_id)
338 .execute(pool)
339 .await
340 .map_err(|source| AppError::Internal(Box::new(source)))?;
341 Ok(())
342}
343
344/// Assigns `role` to `user` - Laravel's `$user->assignRole('admin')`.
345/// `NotFound` if `role` hasn't been [`create_role`]d yet, same reasoning
346/// as [`grant_role_permission`].
347pub async fn assign_role<U: Authenticatable>(
348 user: &U,
349 role: impl RoleName,
350) -> Result<(), AppError> {
351 let pool = larust_orm::pool()?;
352 ensure_tables(pool).await?;
353
354 let Some(role_id) = role_id(pool, role.name()).await? else {
355 return Err(AppError::NotFound);
356 };
357
358 sqlx::query(&insert_ignore_sql("user_roles", &["user_id", "role_id"]))
359 .bind(user.auth_id())
360 .bind(role_id)
361 .execute(pool)
362 .await
363 .map_err(|source| AppError::Internal(Box::new(source)))?;
364 Ok(())
365}
366
367/// Removes `role` from `user`, if they had it - a legal no-op if they
368/// didn't (same "no meaningful double-removal error" reasoning
369/// `larust-notifications`'s `mark_as_read` already applies to marking an
370/// already-read notification read again). A nonexistent *role name* is
371/// still `NotFound`, distinct from "existing role, not currently assigned".
372pub async fn remove_role<U: Authenticatable>(
373 user: &U,
374 role: impl RoleName,
375) -> Result<(), AppError> {
376 let pool = larust_orm::pool()?;
377 ensure_tables(pool).await?;
378
379 let Some(role_id) = role_id(pool, role.name()).await? else {
380 return Err(AppError::NotFound);
381 };
382
383 let backend = larust_orm::backend();
384 let delete_sql = format!(
385 "DELETE FROM user_roles WHERE user_id = {} AND role_id = {}",
386 larust_orm::placeholder(backend, 1),
387 larust_orm::placeholder(backend, 2),
388 );
389 sqlx::query(&delete_sql)
390 .bind(user.auth_id())
391 .bind(role_id)
392 .execute(pool)
393 .await
394 .map_err(|source| AppError::Internal(Box::new(source)))?;
395 Ok(())
396}
397
398/// `true` if `user` currently has `role` assigned. An unrecognized role
399/// name (never [`create_role`]d) simply reads as `false`, not an error -
400/// unlike the write-side functions above, a read has no "which row did
401/// you mean" ambiguity to fail loudly about.
402pub async fn has_role<U: Authenticatable>(user: &U, role: impl RoleName) -> Result<bool, AppError> {
403 let pool = larust_orm::pool()?;
404 ensure_tables(pool).await?;
405
406 // `(i64,)`, not `(bool,)`: `SELECT EXISTS(...)` returns a 0/1 integer
407 // on both backends, and sqlx's `Any` driver - unlike the concrete
408 // `Sqlite`/`MySql` types - doesn't coerce an integer column into
409 // `bool` (confirmed empirically: decoding straight into `bool` here
410 // fails with "Rust type `bool` is not compatible with SQL type
411 // `BIGINT`" through `Any`), so the `!= 0` conversion is done by hand.
412 let backend = larust_orm::backend();
413 let sql = format!(
414 "SELECT EXISTS(\
415 SELECT 1 FROM user_roles ur \
416 JOIN roles r ON r.id = ur.role_id \
417 WHERE ur.user_id = {} AND r.name = {}\
418 )",
419 larust_orm::placeholder(backend, 1),
420 larust_orm::placeholder(backend, 2),
421 );
422 let (exists,): (i64,) = sqlx::query_as(&sql)
423 .bind(user.auth_id())
424 .bind(role.name())
425 .fetch_one(pool)
426 .await
427 .map_err(|source| AppError::Internal(Box::new(source)))?;
428 Ok(exists != 0)
429}
430
431/// Grants `permission` to `user` directly, bypassing roles entirely -
432/// Laravel's `$user->givePermissionTo('edit-posts')`. `NotFound` if
433/// `permission` hasn't been [`create_permission`]d yet.
434pub async fn give_permission_to<U: Authenticatable>(
435 user: &U,
436 permission: impl PermissionName,
437) -> Result<(), AppError> {
438 let pool = larust_orm::pool()?;
439 ensure_tables(pool).await?;
440
441 let Some(permission_id) = permission_id(pool, permission.name()).await? else {
442 return Err(AppError::NotFound);
443 };
444
445 sqlx::query(&insert_ignore_sql(
446 "user_permissions",
447 &["user_id", "permission_id"],
448 ))
449 .bind(user.auth_id())
450 .bind(permission_id)
451 .execute(pool)
452 .await
453 .map_err(|source| AppError::Internal(Box::new(source)))?;
454 Ok(())
455}
456
457/// `true` if `user` has `permission` - granted directly via
458/// [`give_permission_to`], *or* inherited through any role assigned via
459/// [`assign_role`] that was in turn granted it via
460/// [`grant_role_permission`]. One query, not two round trips. Same
461/// "unrecognized name reads as `false`" reasoning as [`has_role`].
462pub async fn has_permission_to<U: Authenticatable>(
463 user: &U,
464 permission: impl PermissionName,
465) -> Result<bool, AppError> {
466 let pool = larust_orm::pool()?;
467 ensure_tables(pool).await?;
468
469 // `(i64,)`, not `(bool,)` - see `has_role`'s own comment on why.
470 let backend = larust_orm::backend();
471 let sql = format!(
472 "SELECT EXISTS(\
473 SELECT 1 FROM user_permissions up \
474 JOIN permissions p ON p.id = up.permission_id \
475 WHERE up.user_id = {} AND p.name = {}\
476 ) OR EXISTS(\
477 SELECT 1 FROM user_roles ur \
478 JOIN role_permissions rp ON rp.role_id = ur.role_id \
479 JOIN permissions p ON p.id = rp.permission_id \
480 WHERE ur.user_id = {} AND p.name = {}\
481 )",
482 larust_orm::placeholder(backend, 1),
483 larust_orm::placeholder(backend, 2),
484 larust_orm::placeholder(backend, 3),
485 larust_orm::placeholder(backend, 4),
486 );
487 let (exists,): (i64,) = sqlx::query_as(&sql)
488 .bind(user.auth_id())
489 .bind(permission.name())
490 .bind(user.auth_id())
491 .bind(permission.name())
492 .fetch_one(pool)
493 .await
494 .map_err(|source| AppError::Internal(Box::new(source)))?;
495 Ok(exists != 0)
496}
497
498/// [`has_permission_to`], converted into a 403 on failure - the same
499/// "reuse the primitive, don't reinvent the check" pattern
500/// `larust_auth::Policy`'s own `authorize_*` sugar methods already use
501/// for `larust_auth::authorize`.
502pub async fn authorize_permission<U: Authenticatable>(
503 user: &U,
504 permission: impl PermissionName,
505) -> Result<(), AppError> {
506 authorize(has_permission_to(user, permission).await?)
507}
508
509/// Laravel's `$user->isAdmin()`, without a magic `"admin"` string on
510/// either side: [`has_role`] against whichever role `R` names as its
511/// [`AdminRole::admin`]. `R` is turbofished at the call site
512/// (`is_admin::<User, Role>(&user)`), or wrapped in a zero-argument
513/// app-level helper the same way `demo`'s own `Post::can_manage` wraps
514/// `has_permission_to` - see `larust-permissions`' own crate-level doc
515/// comment for that pattern.
516pub async fn is_admin<U: Authenticatable, R: AdminRole>(user: &U) -> Result<bool, AppError> {
517 has_role(user, R::admin()).await
518}
519
520/// [`is_admin`], converted into a 403 on failure - same shape as
521/// [`authorize_permission`].
522pub async fn authorize_admin<U: Authenticatable, R: AdminRole>(user: &U) -> Result<(), AppError> {
523 authorize(is_admin::<U, R>(user).await?)
524}
525
526#[cfg(test)]
527mod tests {
528 use super::*;
529
530 struct TestUser {
531 id: i64,
532 }
533
534 impl Authenticatable for TestUser {
535 fn auth_id(&self) -> i64 {
536 self.id
537 }
538
539 async fn find_for_auth(_id: i64) -> Result<Option<Self>, AppError> {
540 unreachable!("not exercised by these tests")
541 }
542 }
543
544 #[derive(Copy, Clone)]
545 enum Role {
546 Admin,
547 Editor,
548 /// Deliberately never [`create_role`]d - exercises the `NotFound`
549 /// path on every write-side function that takes a role.
550 Uncreated,
551 }
552
553 impl RoleName for Role {
554 fn name(&self) -> &'static str {
555 match self {
556 Role::Admin => "admin",
557 Role::Editor => "editor",
558 Role::Uncreated => "uncreated",
559 }
560 }
561 }
562
563 impl AdminRole for Role {
564 fn admin() -> Self {
565 Role::Admin
566 }
567 }
568
569 #[derive(Copy, Clone)]
570 enum Permission {
571 EditPosts,
572 DeleteUsers,
573 }
574
575 impl PermissionName for Permission {
576 fn name(&self) -> &'static str {
577 match self {
578 Permission::EditPosts => "edit-posts",
579 Permission::DeleteUsers => "delete-users",
580 }
581 }
582 }
583
584 async fn connect_test_db() {
585 let dir = tempfile::tempdir().unwrap().keep();
586 let database_url = format!("sqlite://{}/test.sqlite", dir.display());
587 larust_orm::connect(&database_url).await.unwrap();
588 }
589
590 /// All scenarios share one test function, not several - `larust_orm::
591 /// connect()` sets a process-wide pool exactly once (a second call in
592 /// the same test binary errors with "connect() called more than
593 /// once"), the same constraint `larust-notifications`'s own test
594 /// suite documents and works around. Each scenario uses its own,
595 /// disjoint user ids so they can't interfere with each other despite
596 /// sharing one table/connection.
597 #[tokio::test]
598 async fn permissions_crate_behaves_correctly_across_every_scenario() {
599 connect_test_db().await;
600
601 create_role(Role::Admin).await.unwrap();
602 create_role(Role::Editor).await.unwrap();
603 create_permission(Permission::EditPosts).await.unwrap();
604 create_permission(Permission::DeleteUsers).await.unwrap();
605 // create_* is idempotent - calling it again for the same name is
606 // a no-op, not an error.
607 create_role(Role::Admin).await.unwrap();
608
609 // A role's permissions are inherited by anyone assigned that role.
610 grant_role_permission(Role::Editor, Permission::EditPosts)
611 .await
612 .unwrap();
613 let alice = TestUser { id: 1 };
614 assert!(!has_role(&alice, Role::Editor).await.unwrap());
615 assert!(!has_permission_to(&alice, Permission::EditPosts)
616 .await
617 .unwrap());
618 assign_role(&alice, Role::Editor).await.unwrap();
619 assert!(has_role(&alice, Role::Editor).await.unwrap());
620 assert!(has_permission_to(&alice, Permission::EditPosts)
621 .await
622 .unwrap());
623 // Alice was never granted delete-users, directly or via a role.
624 assert!(!has_permission_to(&alice, Permission::DeleteUsers)
625 .await
626 .unwrap());
627
628 // A direct grant works independently of any role.
629 let bob = TestUser { id: 2 };
630 assert!(!has_permission_to(&bob, Permission::DeleteUsers)
631 .await
632 .unwrap());
633 give_permission_to(&bob, Permission::DeleteUsers)
634 .await
635 .unwrap();
636 assert!(has_permission_to(&bob, Permission::DeleteUsers)
637 .await
638 .unwrap());
639 assert!(!has_role(&bob, Role::Admin).await.unwrap());
640
641 // Removing a role revokes the permissions it carried.
642 remove_role(&alice, Role::Editor).await.unwrap();
643 assert!(!has_role(&alice, Role::Editor).await.unwrap());
644 assert!(!has_permission_to(&alice, Permission::EditPosts)
645 .await
646 .unwrap());
647 // Removing a role the user never had is a legal no-op.
648 remove_role(&alice, Role::Admin).await.unwrap();
649
650 // authorize_permission mirrors has_permission_to as a 403.
651 let carol = TestUser { id: 3 };
652 assign_role(&carol, Role::Admin).await.unwrap();
653 grant_role_permission(Role::Admin, Permission::DeleteUsers)
654 .await
655 .unwrap();
656 authorize_permission(&carol, Permission::DeleteUsers)
657 .await
658 .unwrap();
659 match authorize_permission(&carol, Permission::EditPosts).await {
660 Err(AppError::Http { status, .. }) => {
661 assert_eq!(status, larust_core::axum::http::StatusCode::FORBIDDEN);
662 }
663 Err(other) => panic!("expected AppError::Http{{FORBIDDEN, ..}}, got {other:?}"),
664 Ok(()) => panic!("expected AppError::Http{{FORBIDDEN, ..}}, got Ok(())"),
665 }
666
667 // Assigning/granting a nonexistent name fails loudly (NotFound)
668 // rather than silently seeding a stray row.
669 let dave = TestUser { id: 4 };
670 assert!(matches!(
671 assign_role(&dave, Role::Uncreated).await,
672 Err(AppError::NotFound)
673 ));
674 assert!(matches!(
675 remove_role(&dave, Role::Uncreated).await,
676 Err(AppError::NotFound)
677 ));
678 assert!(matches!(
679 grant_role_permission(Role::Uncreated, Permission::EditPosts).await,
680 Err(AppError::NotFound)
681 ));
682 // A read against an unrecognized role/permission name is `false`,
683 // not an error - no write-side ambiguity to fail loudly about.
684 assert!(!has_role(&dave, Role::Uncreated).await.unwrap());
685
686 // is_admin/authorize_admin are has_role/authorize_permission under
687 // a friendlier name, resolved through `AdminRole::admin()` rather
688 // than a hardcoded "admin" string - carol was assigned Role::Admin
689 // above, alice never was.
690 assert!(is_admin::<_, Role>(&carol).await.unwrap());
691 assert!(!is_admin::<_, Role>(&alice).await.unwrap());
692 authorize_admin::<_, Role>(&carol).await.unwrap();
693 match authorize_admin::<_, Role>(&alice).await {
694 Err(AppError::Http { status, .. }) => {
695 assert_eq!(status, larust_core::axum::http::StatusCode::FORBIDDEN);
696 }
697 Err(other) => panic!("expected AppError::Http{{FORBIDDEN, ..}}, got {other:?}"),
698 Ok(()) => panic!("expected AppError::Http{{FORBIDDEN, ..}}, got Ok(())"),
699 }
700 }
701}