Skip to main content

rustango_cms/
permissions.rs

1//! Per-page permission engine.
2//!
3//! Three pieces:
4//!
5//! 1. [`PagePermission`] — `(page_id, role_id, permission)` grants
6//!    stored in `cms_page_permission`. Sites grant fine-grained
7//!    actions per role per subtree.
8//! 2. [`user_can`] — `(user_id, page_id, action) → bool`. Walks the
9//!    page's ancestor chain collecting grants; superusers short-circuit
10//!    to `true`.
11//! 3. [`Action`] — the canonical set of action strings the engine
12//!    recognizes. Stored as text so the framework's permission system
13//!    can interoperate via codenames if/when we expose them.
14//!
15//! Permissions **inherit** down the tree: a grant on a page applies
16//! to every descendant unless overridden by a closer grant. There are
17//! no explicit denies — any matching grant in the chain returns
18//! `true`.
19
20use chrono::{DateTime, Utc};
21use rustango::sql::Auto;
22use rustango::Model;
23use serde::{Deserialize, Serialize};
24
25/// Canonical action set the engine recognizes. Stored as text so
26/// authors can extend the surface without a schema change.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum Action {
29    View,
30    Add,
31    Edit,
32    Publish,
33    Delete,
34    /// Top-level "may use this admin surface at all" verb — used by
35    /// the `cms_admin.access` codename + `with_cms_admin_access`
36    /// middleware to gate the protected router. Unlike the CRUD
37    /// verbs it doesn't pair with a resource model; it pairs with a
38    /// router surface.
39    Access,
40    /// Framework-admin variant of [`Action::Access`]. Maps to the
41    /// `auth.access_admin` codename the framework's
42    /// `permission_required` middleware enforces on
43    /// `/__admin/` + `/admin/`. Surfaced as a separate variant so the
44    /// matrix can present "framework admin access" as a one-cell row
45    /// without inventing a new codename layout.
46    AccessAdmin,
47}
48
49impl Action {
50    #[must_use]
51    pub fn as_str(self) -> &'static str {
52        match self {
53            Self::View => "view",
54            Self::Add => "add",
55            Self::Edit => "edit",
56            Self::Publish => "publish",
57            Self::Delete => "delete",
58            Self::Access => "access",
59            Self::AccessAdmin => "access_admin",
60        }
61    }
62
63    /// The canonical set; iteration order is also the order the
64    /// admin permission editor renders columns in. `Access` is
65    /// deliberately omitted — its column lives in a separate Access
66    /// section row, not the CRUD grid.
67    #[must_use]
68    pub fn all() -> &'static [Action] {
69        &[
70            Self::View,
71            Self::Add,
72            Self::Edit,
73            Self::Publish,
74            Self::Delete,
75        ]
76    }
77}
78
79/// One `(page_id, role_id, permission)` grant. UNIQUE at the SQL
80/// layer so a role can't be granted the same action twice on the
81/// same page.
82#[derive(Model, Debug, Clone, Serialize, Deserialize)]
83#[rustango(
84    table = "cms_page_permission",
85    app = "cms",
86    admin(
87        list_display = "page_id, role_id, permission",
88        ordering = "page_id, role_id, permission",
89    )
90)]
91pub struct PagePermission {
92    #[rustango(primary_key)]
93    pub id: Auto<i64>,
94
95    #[rustango(fk = "cms_page", on = "id", index)]
96    pub page_id: i64,
97
98    #[rustango(fk = "rustango_roles", on = "id", index)]
99    pub role_id: i64,
100
101    /// One of the strings in [`Action::as_str`]. Stored verbatim
102    /// so adding actions later doesn't need a schema migration.
103    #[rustango(max_length = 32)]
104    pub permission: String,
105
106    #[rustango(auto_now_add)]
107    pub created_at: Auto<DateTime<Utc>>,
108}
109
110/// Resolve `(user_id, page_id, action) → bool` against the per-page
111/// permission table. Walks ancestors via the `cms_page.path`
112/// materialized prefix and collects matching grants in one query.
113///
114/// Short-circuits to `true` for tenant superusers. Returns `false`
115/// when the user has no roles assigned (there is no per-user override
116/// table).
117///
118/// # Errors
119/// Propagates driver / query failures from the four underlying
120/// fetches (user, page, user-roles, permission grants).
121pub async fn user_can(
122    pool: &rustango::sql::Pool,
123    user_id: i64,
124    page_id: i64,
125    action: Action,
126) -> Result<bool, rustango::sql::ExecError> {
127    use rustango::core::Column as _;
128    use rustango::sql::FetcherPool as _;
129
130    // 1) Superuser short-circuit.
131    let user = rustango::tenancy::auth::User::objects()
132        .where_(rustango::tenancy::auth::User::id.eq(user_id))
133        .first(pool)
134        .await?;
135    let Some(user) = user else {
136        return Ok(false);
137    };
138    if !user.active {
139        return Ok(false);
140    }
141    if user.is_superuser {
142        return Ok(true);
143    }
144
145    // 2) Resolve the user's role ids.
146    let memberships: Vec<rustango::tenancy::permissions::UserRole> =
147        rustango::tenancy::permissions::UserRole::objects()
148            .where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
149            .fetch(pool)
150            .await?;
151    if memberships.is_empty() {
152        return Ok(false);
153    }
154    let role_ids: Vec<i64> = memberships.iter().map(|m| m.role_id).collect();
155
156    // 3) Walk the target page's ancestor chain. `cms_page.path` is a
157    //    materialized prefix in path-encoded form (`{depth}-{id}/...`
158    //    when the page is at depth N). We use a simpler approach:
159    //    fetch the page, then re-fetch every ancestor by id via the
160    //    parent_id chain — bounded by tree depth, fine for the admin.
161    let target = crate::page::Page::objects()
162        .where_(crate::page::Page::id.eq(page_id))
163        .first(pool)
164        .await?;
165    let Some(mut current) = target else {
166        return Ok(false);
167    };
168    let mut chain_ids: Vec<i64> = Vec::new();
169    chain_ids.push(current.id.get().copied().unwrap_or_default());
170    while let Some(pid) = current.parent_id {
171        let parent = crate::page::Page::objects()
172            .where_(crate::page::Page::id.eq(pid))
173            .first(pool)
174            .await?;
175        match parent {
176            Some(p) => {
177                chain_ids.push(pid);
178                current = p;
179            }
180            None => break,
181        }
182    }
183
184    // 4) Any matching grant in the chain returns true.
185    let grants: Vec<PagePermission> = PagePermission::objects()
186        .where_(PagePermission::page_id.is_in(chain_ids.iter().copied()))
187        .where_(PagePermission::role_id.is_in(role_ids.iter().copied()))
188        .where_(PagePermission::permission.eq(action.as_str().to_owned()))
189        .fetch(pool)
190        .await?;
191    Ok(!grants.is_empty())
192}
193
194/// One `(collection_id, role_id, permission)` grant — the media
195/// collection analogue of [`PagePermission`]. Same UNIQUE
196/// shape and same inheritance semantics (parent collection grants
197/// flow to children).
198#[derive(Model, Debug, Clone, Serialize, Deserialize)]
199#[rustango(
200    table = "cms_collection_permission",
201    app = "cms",
202    admin(
203        list_display = "collection_id, role_id, permission",
204        ordering = "collection_id, role_id, permission",
205    )
206)]
207pub struct CollectionPermission {
208    #[rustango(primary_key)]
209    pub id: Auto<i64>,
210
211    #[rustango(fk = "cms_media_collection", on = "id", index)]
212    pub collection_id: i64,
213
214    #[rustango(fk = "rustango_roles", on = "id", index)]
215    pub role_id: i64,
216
217    #[rustango(max_length = 32)]
218    pub permission: String,
219
220    #[rustango(auto_now_add)]
221    pub created_at: Auto<DateTime<Utc>>,
222}
223
224/// Resolve `(user_id, collection_id, action) → bool` against the
225/// per-collection permission table. Walks the collection's
226/// ancestor chain (via `parent_id`) and short-circuits to `true`
227/// for superusers.
228///
229/// # Errors
230/// Driver / query failures from the underlying fetches.
231pub async fn user_can_in_collection(
232    pool: &rustango::sql::Pool,
233    user_id: i64,
234    collection_id: i64,
235    action: Action,
236) -> Result<bool, rustango::sql::ExecError> {
237    use rustango::core::Column as _;
238    use rustango::sql::FetcherPool as _;
239
240    let user = rustango::tenancy::auth::User::objects()
241        .where_(rustango::tenancy::auth::User::id.eq(user_id))
242        .first(pool)
243        .await?;
244    let Some(user) = user else {
245        return Ok(false);
246    };
247    if !user.active {
248        return Ok(false);
249    }
250    if user.is_superuser {
251        return Ok(true);
252    }
253
254    let memberships: Vec<rustango::tenancy::permissions::UserRole> =
255        rustango::tenancy::permissions::UserRole::objects()
256            .where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
257            .fetch(pool)
258            .await?;
259    if memberships.is_empty() {
260        return Ok(false);
261    }
262    let role_ids: Vec<i64> = memberships.iter().map(|m| m.role_id).collect();
263
264    // Walk the collection's parent chain.
265    let target = crate::media::MediaCollection::objects()
266        .where_(crate::media::MediaCollection::id.eq(collection_id))
267        .first(pool)
268        .await?;
269    let Some(mut current) = target else {
270        return Ok(false);
271    };
272    let mut chain_ids: Vec<i64> = Vec::new();
273    chain_ids.push(current.id.get().copied().unwrap_or_default());
274    while let Some(pid) = current.parent_id {
275        let parent = crate::media::MediaCollection::objects()
276            .where_(crate::media::MediaCollection::id.eq(pid))
277            .first(pool)
278            .await?;
279        match parent {
280            Some(p) => {
281                chain_ids.push(pid);
282                current = p;
283            }
284            None => break,
285        }
286    }
287
288    let grants: Vec<CollectionPermission> = CollectionPermission::objects()
289        .where_(CollectionPermission::collection_id.is_in(chain_ids.iter().copied()))
290        .where_(CollectionPermission::role_id.is_in(role_ids.iter().copied()))
291        .where_(CollectionPermission::permission.eq(action.as_str().to_owned()))
292        .fetch(pool)
293        .await?;
294    Ok(!grants.is_empty())
295}
296
297/// Which of `pages` — `(id, parent_id)` pairs — `user_id` may view: the
298/// set [`user_can`] with [`Action::View`] would allow, in a bounded number
299/// of queries instead of one walk per page. For list views, so a listing
300/// never shows a row its detail view refuses.
301///
302/// Superusers see every page; inactive, unknown and role-less users see
303/// none.
304///
305/// # Errors
306/// Driver / query failures.
307pub async fn viewable_page_ids(
308    pool: &rustango::sql::Pool,
309    user_id: i64,
310    pages: &[(i64, Option<i64>)],
311) -> Result<std::collections::HashSet<i64>, rustango::sql::ExecError> {
312    use rustango::core::Column as _;
313    use rustango::sql::FetcherPool as _;
314    use std::collections::{HashMap, HashSet};
315
316    let user = rustango::tenancy::auth::User::objects()
317        .where_(rustango::tenancy::auth::User::id.eq(user_id))
318        .first(pool)
319        .await?;
320    match user {
321        Some(u) if u.active && u.is_superuser => return Ok(pages.iter().map(|p| p.0).collect()),
322        Some(u) if u.active => {}
323        _ => return Ok(HashSet::new()),
324    }
325    let role_ids: Vec<i64> = rustango::tenancy::permissions::UserRole::objects()
326        .where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
327        .fetch(pool)
328        .await?
329        .into_iter()
330        .map(|m| m.role_id)
331        .collect();
332    if role_ids.is_empty() {
333        return Ok(HashSet::new());
334    }
335    let granted: HashSet<i64> = PagePermission::objects()
336        .where_(PagePermission::role_id.is_in(role_ids))
337        .where_(PagePermission::permission.eq(Action::View.as_str().to_owned()))
338        .fetch(pool)
339        .await?
340        .into_iter()
341        .map(|g| g.page_id)
342        .collect();
343    if granted.is_empty() {
344        return Ok(HashSet::new());
345    }
346
347    // Every ancestor's parent, fetched a tree level at a time.
348    let mut parent_of: HashMap<i64, Option<i64>> = pages.iter().copied().collect();
349    loop {
350        let missing: HashSet<i64> = parent_of
351            .values()
352            .flatten()
353            .copied()
354            .filter(|id| !parent_of.contains_key(id))
355            .collect();
356        if missing.is_empty() {
357            break;
358        }
359        let found: Vec<crate::page::Page> = crate::page::Page::objects()
360            .where_(crate::page::Page::id.is_in(missing.iter().copied()))
361            .fetch(pool)
362            .await?;
363        for id in missing {
364            // A dangling parent ends the chain, as it does in `user_can`.
365            let parent = found
366                .iter()
367                .find(|p| p.id.get().copied() == Some(id))
368                .and_then(|p| p.parent_id);
369            parent_of.insert(id, parent);
370        }
371    }
372
373    let viewable = |mut id: i64| {
374        // Bounded by the map, so a parent cycle cannot spin forever.
375        for _ in 0..=parent_of.len() {
376            if granted.contains(&id) {
377                return true;
378            }
379            match parent_of.get(&id).copied().flatten() {
380                Some(parent) => id = parent,
381                None => return false,
382            }
383        }
384        false
385    };
386    Ok(pages.iter().map(|p| p.0).filter(|&id| viewable(id)).collect())
387}
388
389/// Resolve the full action matrix for a user on a page in one shot.
390/// Useful for the admin form-state computation where every action
391/// is checked together (so the page editor can disable Publish but
392/// allow Edit, etc.). Returns a fresh HashMap with one entry per
393/// action — `true` when granted, `false` when not.
394///
395/// # Errors
396/// Propagates driver errors as `user_can` would.
397pub async fn user_can_matrix(
398    pool: &rustango::sql::Pool,
399    user_id: i64,
400    page_id: i64,
401) -> Result<std::collections::HashMap<&'static str, bool>, rustango::sql::ExecError> {
402    let mut out = std::collections::HashMap::new();
403    for action in Action::all() {
404        let allowed = user_can(pool, user_id, page_id, *action).await?;
405        out.insert(action.as_str(), allowed);
406    }
407    Ok(out)
408}
409
410/// Resolve the full set of role codenames a user inherits via their
411/// `UserRole` memberships. Used by the admin chrome to gate sidebar
412/// items + by handlers to enforce CRUD access against the
413/// permissions matrix.
414///
415/// Superusers and inactive users are caller's concern — this helper
416/// just returns the codename union for whatever role memberships
417/// exist. Empty set when the user has no roles assigned.
418///
419/// # Errors
420/// Propagates driver / query failures from the three underlying
421/// fetches (memberships, role permissions).
422pub async fn user_codenames(
423    pool: &rustango::sql::Pool,
424    user_id: i64,
425) -> Result<std::collections::HashSet<String>, rustango::sql::ExecError> {
426    use rustango::core::Column as _;
427    use rustango::sql::FetcherPool as _;
428
429    let memberships: Vec<rustango::tenancy::permissions::UserRole> =
430        rustango::tenancy::permissions::UserRole::objects()
431            .where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
432            .fetch(pool)
433            .await?;
434    if memberships.is_empty() {
435        return Ok(std::collections::HashSet::new());
436    }
437    let role_ids: Vec<i64> = memberships.iter().map(|m| m.role_id).collect();
438    let grants: Vec<rustango::tenancy::permissions::RolePermission> =
439        rustango::tenancy::permissions::RolePermission::objects()
440            .where_(
441                rustango::tenancy::permissions::RolePermission::role_id
442                    .is_in(role_ids.iter().copied()),
443            )
444            .fetch(pool)
445            .await?;
446    Ok(grants.into_iter().map(|g| g.codename).collect())
447}