Skip to main content

rustango_cms/admin/
resources.rs

1//! Admin-resource registry — single source of truth for the CRUD
2//! permissions matrix on `/cms-admin/roles/{id}/edit`.
3//!
4//! Each entry describes one sidebar resource (Pages, Library, Media,
5//! Redirects, Users, …) with:
6//! - a stable string `key` used in the matrix form (`perm[key][action]`),
7//! - a human `label` shown in the row header,
8//! - a `codename_prefix` mapping the row to the existing
9//!   `rustango_role_permissions` codename system (so matrix toggles
10//!   read/write the same column the framework already enforces),
11//! - the `section` group used to bucket rows (Content / Media / Site /
12//!   Audit / Identity / Custom),
13//! - the subset of [`crate::permissions::Action`] columns that apply
14//!   (read-only rows like Page types and History skip Add/Edit/Delete).
15//!
16//! Three sources contribute rows at runtime:
17//! 1. The static built-in list ([`built_in_resources`]).
18//! 2. Every registered [`crate::library::LibraryTypeHandler`] — each
19//!    one auto-adds a `library_item:<type_name>` row so per-snippet
20//!    CRUD is grantable independently.
21//! 3. Every registered
22//!    [`crate::admin::admin_page::AdminPageHandler`] whose
23//!    `permission_resource()` returns `Some` — custom admin pages
24//!    appear in the matrix without any role-editor code change.
25
26use crate::permissions::Action;
27
28/// One row in the role permissions matrix.
29#[derive(Debug, Clone)]
30pub struct AdminResource {
31    /// Stable form key. Format: snake_case for built-ins
32    /// (`pages`, `media`, `documents`); `library_item:<type_name>`
33    /// for library-type rows; `custom:<slug>` for third-party
34    /// admin pages.
35    pub key: String,
36    /// Sidebar / matrix label.
37    pub label: String,
38    /// Codename prefix used in `rustango_role_permissions.codename`.
39    /// Combined with an action via `.` — `{prefix}.{action}` —
40    /// matching the existing `cms_page.view` / `cms_media.add`
41    /// convention.
42    pub codename_prefix: String,
43    /// Visual bucket used in the matrix grouping.
44    pub section: ResourceSection,
45    /// Which action columns apply to this resource. Cells outside
46    /// this set render `—` and don't accept toggles.
47    pub actions: &'static [Action],
48}
49
50/// Visual / logical grouping for the matrix rows. Rendered as the
51/// row-header band above its members.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum ResourceSection {
54    Access,
55    Content,
56    Media,
57    Site,
58    Audit,
59    Identity,
60    /// Public members-area access tiers (#members) — permission
61    /// codenames a page/type restriction can require. Roles carry
62    /// these; admins assign the roles to members.
63    Membership,
64    Custom,
65}
66
67impl ResourceSection {
68    #[must_use]
69    pub fn label(self) -> &'static str {
70        match self {
71            Self::Access => "Access",
72            Self::Content => "Content",
73            Self::Media => "Media & documents",
74            Self::Site => "Site structure",
75            Self::Audit => "Audit",
76            Self::Identity => "Identity",
77            Self::Membership => "Membership (public site)",
78            Self::Custom => "Custom admin pages",
79        }
80    }
81
82    #[must_use]
83    pub fn order(self) -> u8 {
84        match self {
85            Self::Access => 0,
86            Self::Content => 1,
87            Self::Media => 2,
88            Self::Site => 3,
89            Self::Audit => 4,
90            Self::Identity => 5,
91            Self::Membership => 6,
92            Self::Custom => 7,
93        }
94    }
95}
96
97const ALL_ACTIONS: &[Action] = &[
98    Action::View,
99    Action::Add,
100    Action::Edit,
101    Action::Publish,
102    Action::Delete,
103];
104const CRUD_ACTIONS: &[Action] = &[Action::View, Action::Add, Action::Edit, Action::Delete];
105const READ_ONLY: &[Action] = &[Action::View];
106const VIEW_EDIT: &[Action] = &[Action::View, Action::Edit];
107const ACCESS_ONLY: &[Action] = &[Action::Access];
108const ACCESS_ADMIN_ONLY: &[Action] = &[Action::AccessAdmin];
109
110/// Built-in sidebar resources, in matrix display order. Library-type
111/// rows and custom-admin-page rows are appended dynamically by
112/// [`all_resources`].
113#[must_use]
114pub fn built_in_resources() -> Vec<AdminResource> {
115    vec![
116        AdminResource {
117            key: "cms_admin".to_owned(),
118            label: "Access the CMS admin".to_owned(),
119            codename_prefix: "cms_admin".to_owned(),
120            section: ResourceSection::Access,
121            actions: ACCESS_ONLY,
122        },
123        // #10 — framework admin access. The framework's
124        // `permission_required` middleware (rustango#311) gates
125        // `/__admin/` + `/admin/` on the `auth.access_admin`
126        // codename. Surfacing the row here lets admins grant /
127        // revoke framework-admin access from the same matrix that
128        // controls CMS access, so they don't have to know two
129        // different codename surfaces.
130        AdminResource {
131            key: "rustango_admin".to_owned(),
132            label: "Access the framework admin (/admin/)".to_owned(),
133            codename_prefix: "auth".to_owned(),
134            section: ResourceSection::Access,
135            actions: ACCESS_ADMIN_ONLY,
136        },
137        AdminResource {
138            key: "pages".to_owned(),
139            label: "Pages".to_owned(),
140            codename_prefix: "cms_page".to_owned(),
141            section: ResourceSection::Content,
142            actions: ALL_ACTIONS,
143        },
144        AdminResource {
145            key: "page_types".to_owned(),
146            label: "Page types".to_owned(),
147            codename_prefix: "cms_page_type".to_owned(),
148            section: ResourceSection::Content,
149            actions: READ_ONLY,
150        },
151        AdminResource {
152            key: "library".to_owned(),
153            label: "Library (all)".to_owned(),
154            codename_prefix: "cms_library".to_owned(),
155            section: ResourceSection::Content,
156            actions: CRUD_ACTIONS,
157        },
158        AdminResource {
159            key: "media".to_owned(),
160            label: "Media".to_owned(),
161            codename_prefix: "cms_media".to_owned(),
162            section: ResourceSection::Media,
163            actions: CRUD_ACTIONS,
164        },
165        AdminResource {
166            key: "documents".to_owned(),
167            label: "Documents".to_owned(),
168            codename_prefix: "cms_document".to_owned(),
169            section: ResourceSection::Media,
170            actions: CRUD_ACTIONS,
171        },
172        AdminResource {
173            key: "collections".to_owned(),
174            label: "Media folders".to_owned(),
175            codename_prefix: "cms_media_collection".to_owned(),
176            section: ResourceSection::Media,
177            actions: CRUD_ACTIONS,
178        },
179        AdminResource {
180            key: "locales".to_owned(),
181            label: "Locales".to_owned(),
182            codename_prefix: "cms_locale".to_owned(),
183            section: ResourceSection::Site,
184            actions: CRUD_ACTIONS,
185        },
186        AdminResource {
187            key: "redirects".to_owned(),
188            label: "Redirects".to_owned(),
189            codename_prefix: "cms_redirect".to_owned(),
190            section: ResourceSection::Site,
191            actions: CRUD_ACTIONS,
192        },
193        AdminResource {
194            key: "navigation".to_owned(),
195            label: "Navigation menus".to_owned(),
196            codename_prefix: "cms_navigation_menu".to_owned(),
197            section: ResourceSection::Site,
198            actions: CRUD_ACTIONS,
199        },
200        AdminResource {
201            key: "workflows".to_owned(),
202            label: "Workflows".to_owned(),
203            codename_prefix: "cms_workflow".to_owned(),
204            section: ResourceSection::Site,
205            actions: CRUD_ACTIONS,
206        },
207        AdminResource {
208            key: "settings".to_owned(),
209            label: "Settings".to_owned(),
210            codename_prefix: "cms_settings".to_owned(),
211            section: ResourceSection::Site,
212            actions: VIEW_EDIT,
213        },
214        AdminResource {
215            key: "history".to_owned(),
216            label: "Revision history".to_owned(),
217            codename_prefix: "cms_history".to_owned(),
218            section: ResourceSection::Audit,
219            actions: READ_ONLY,
220        },
221        AdminResource {
222            key: "users".to_owned(),
223            label: "Users".to_owned(),
224            codename_prefix: "rustango_users".to_owned(),
225            section: ResourceSection::Identity,
226            actions: CRUD_ACTIONS,
227        },
228        AdminResource {
229            key: "roles".to_owned(),
230            label: "Roles".to_owned(),
231            codename_prefix: "rustango_roles".to_owned(),
232            section: ResourceSection::Identity,
233            actions: CRUD_ACTIONS,
234        },
235        // #members — public members-area access tiers. Each is a single
236        // "Access" permission codename a page/type view-restriction can
237        // require (`members.access`, `members_pro.access`,
238        // `members_moderator.access`). Ticking one grants that codename
239        // to the role; a member holding the role then satisfies the
240        // gate. These auto-surface as matrix checkboxes with no extra
241        // wiring (the matrix is data-driven from `all_resources`).
242        AdminResource {
243            key: "members_area".to_owned(),
244            label: "Access members area".to_owned(),
245            codename_prefix: "members".to_owned(),
246            section: ResourceSection::Membership,
247            actions: ACCESS_ONLY,
248        },
249        AdminResource {
250            key: "members_pro".to_owned(),
251            label: "Pro member".to_owned(),
252            codename_prefix: "members_pro".to_owned(),
253            section: ResourceSection::Membership,
254            actions: ACCESS_ONLY,
255        },
256        AdminResource {
257            key: "members_moderator".to_owned(),
258            label: "Moderator".to_owned(),
259            codename_prefix: "members_moderator".to_owned(),
260            section: ResourceSection::Membership,
261            actions: ACCESS_ONLY,
262        },
263    ]
264}
265
266/// The membership permission codenames a page/type view-restriction can
267/// require (#members), as `(codename, label)` — for the restriction
268/// editor's permission picker. Derived from the built-in Membership
269/// resources so the picker and the role matrix never drift.
270#[must_use]
271pub fn membership_codenames() -> Vec<(String, String)> {
272    built_in_resources()
273        .into_iter()
274        .filter(|r| r.section == ResourceSection::Membership)
275        .map(|r| (format!("{}.access", r.codename_prefix), r.label))
276        .collect()
277}
278
279/// Full resource list = built-ins + library-type rows + custom
280/// admin-page rows. Library-type rows let an admin grant CRUD on a
281/// specific snippet kind (e.g. Author) without granting the whole
282/// library tab. Custom-page rows surface third-party admin views.
283#[must_use]
284pub fn all_resources() -> Vec<AdminResource> {
285    let mut out = built_in_resources();
286
287    // Library-type rows — one per registered LibraryTypeHandler.
288    for handler in crate::library::registered_handlers() {
289        let type_name = handler.type_name();
290        out.push(AdminResource {
291            key: format!("library_item:{type_name}"),
292            label: format!("Library — {}", handler.verbose_name()),
293            codename_prefix: format!("cms_library_item__{type_name}"),
294            section: ResourceSection::Content,
295            actions: CRUD_ACTIONS,
296        });
297    }
298
299    // Custom admin page rows — opt-in via `permission_resource()`.
300    for handler in super::admin_page::registered_admin_pages() {
301        if let Some(prefix) = handler.permission_resource() {
302            out.push(AdminResource {
303                key: format!("custom:{}", handler.slug()),
304                label: handler.label().to_owned(),
305                codename_prefix: prefix.to_owned(),
306                section: ResourceSection::Custom,
307                actions: handler.permission_actions(),
308            });
309        }
310    }
311
312    out
313}
314
315/// Group resources by section in display order, preserving the order
316/// resources are returned by [`all_resources`].
317#[must_use]
318pub fn grouped() -> Vec<(ResourceSection, Vec<AdminResource>)> {
319    let mut by_section: std::collections::BTreeMap<u8, (ResourceSection, Vec<AdminResource>)> =
320        std::collections::BTreeMap::new();
321    for r in all_resources() {
322        let entry = by_section
323            .entry(r.section.order())
324            .or_insert_with(|| (r.section, Vec::new()));
325        entry.1.push(r);
326    }
327    by_section.into_values().collect()
328}
329
330/// Build the canonical codename for `(resource, action)`. Always
331/// `{prefix}.{action_str}` — e.g. `cms_page.view`,
332/// `cms_library_item__author.edit`.
333#[must_use]
334pub fn codename(resource: &AdminResource, action: Action) -> String {
335    format!("{}.{}", resource.codename_prefix, action.as_str())
336}
337
338/// Reverse mapping: given a codename, find the matching `(key,
339/// action)` pair so existing role grants can be rendered as
340/// pre-checked matrix cells. Returns `None` if the codename doesn't
341/// match any registered resource (e.g. a legacy free-form codename
342/// the admin hasn't migrated yet).
343#[must_use]
344pub fn parse_codename(codename: &str) -> Option<(String, Action)> {
345    let (prefix, action_str) = codename.rsplit_once('.')?;
346    let action = match action_str {
347        "view" => Action::View,
348        "add" => Action::Add,
349        "edit" | "change" => Action::Edit,
350        "publish" => Action::Publish,
351        "delete" => Action::Delete,
352        "access" => Action::Access,
353        "access_admin" => Action::AccessAdmin,
354        _ => return None,
355    };
356    let resources = all_resources();
357    let r = resources.iter().find(|r| r.codename_prefix == prefix)?;
358    Some((r.key.clone(), action))
359}
360
361/// The actions a role currently holds on `resource`, given the set of
362/// granted `(role_id, codename)` pairs. Only the resource's own
363/// `actions` are considered, in declaration order. Drives each
364/// `(resource × role)` cell of the tenant permission-overview matrix.
365#[must_use]
366pub fn granted_actions(
367    resource: &AdminResource,
368    role_id: i64,
369    granted: &std::collections::HashSet<(i64, String)>,
370) -> Vec<&'static str> {
371    resource
372        .actions
373        .iter()
374        .copied()
375        .filter(|a| granted.contains(&(role_id, codename(resource, *a))))
376        .map(Action::as_str)
377        .collect()
378}
379
380#[cfg(test)]
381mod overview_tests {
382    use super::*;
383    use std::collections::HashSet;
384
385    fn pages_resource() -> AdminResource {
386        AdminResource {
387            key: "pages".to_owned(),
388            label: "Pages".to_owned(),
389            codename_prefix: "cms_page".to_owned(),
390            section: ResourceSection::Content,
391            actions: Action::all(),
392        }
393    }
394
395    #[test]
396    fn granted_actions_filters_to_held_codenames_in_order() {
397        let res = pages_resource();
398        let granted: HashSet<(i64, String)> = [
399            (1, "cms_page.edit".to_owned()),
400            (1, "cms_page.view".to_owned()),
401            (2, "cms_page.view".to_owned()),
402            // a grant for a different resource must not leak in
403            (1, "cms_media.delete".to_owned()),
404        ]
405        .into_iter()
406        .collect();
407        // Role 1: view + edit, returned in Action::all() order (view before edit).
408        assert_eq!(granted_actions(&res, 1, &granted), vec!["view", "edit"]);
409        // Role 2: only view.
410        assert_eq!(granted_actions(&res, 2, &granted), vec!["view"]);
411        // Role 3: nothing.
412        assert!(granted_actions(&res, 3, &granted).is_empty());
413    }
414
415    #[test]
416    fn granted_actions_only_considers_resource_actions() {
417        // A read-only resource (View only) never reports edit/delete even
418        // if a stray codename grant exists.
419        let res = AdminResource {
420            key: "history".to_owned(),
421            label: "History".to_owned(),
422            codename_prefix: "cms_history".to_owned(),
423            section: ResourceSection::Audit,
424            actions: &[Action::View],
425        };
426        let granted: HashSet<(i64, String)> =
427            [(1, "cms_history.delete".to_owned())].into_iter().collect();
428        assert!(granted_actions(&res, 1, &granted).is_empty());
429    }
430}