Skip to main content

rustango_cms/
access.rs

1//! Viewer-aware access helpers for public templates (#members).
2//!
3//! The built-in menus (`auto_menu()`, curated `menu()`/`_menus`) already
4//! hide pages the current viewer can't access. These Tera helpers extend
5//! the same protection to **hand-written** links and lists:
6//!
7//!   * `{{ child | can_view }}` / `can_view(page=child)` — a boolean:
8//!     may the current viewer see this page? Guard a raw link with it:
9//!     `{% if child | can_view %}<a href="{{ child | page_href }}">…</a>{% endif %}`.
10//!   * `{{ children | visible }}` — filter a list of page-shaped objects
11//!     (or menu items) down to the ones the viewer may access. Recurses
12//!     into a nested `children` key, so nested menus / page trees are
13//!     filtered at every level in one call.
14//!
15//! Both read a render-scoped [`AccessContext`] the pipeline installs (via
16//! [`install`]) right before `tera.render` — the same await-free
17//! thread-local pattern as `pageurl` / `auto_menu` (Tera 1.x can't pass
18//! the context into fn/filter args). With no context installed, or on a
19//! tenant with nothing gated, both helpers treat every page as visible —
20//! the guard ([`crate::view_restriction_guard`]) is still the actual
21//! access control; these helpers are only a rendering convenience.
22//!
23//! Page-shaped values are matched on their `path` (materialized tree
24//! path) + `page_type_id` — present on the `children` / `ancestors`
25//! context vars and on any serialized [`crate::page::Page`]. A value
26//! lacking `path` is treated as visible (the helper can't decide; the
27//! guard still protects the target).
28
29use std::cell::RefCell;
30use std::sync::Arc;
31
32use tera::{Filter, Function, Tera, Value};
33
34use crate::view_restriction::AccessContext;
35
36thread_local! {
37    /// Per-thread access oracle. Lives only for one `tera.render` call,
38    /// installed + cleared via [`AccessGuard`].
39    static CURRENT_ACCESS: RefCell<Option<Arc<AccessContext>>> = const { RefCell::new(None) };
40}
41
42/// RAII guard. While in scope the access context is installed; on drop
43/// it's cleared. Bind it across `tera.render(…)` and let it drop after.
44#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
45pub struct AccessGuard {
46    _priv: (),
47}
48
49impl Drop for AccessGuard {
50    fn drop(&mut self) {
51        CURRENT_ACCESS.with(|cell| {
52            *cell.borrow_mut() = None;
53        });
54    }
55}
56
57/// Install `ctx` for the duration of the returned guard so `can_view` /
58/// `visible` resolve against it on this thread.
59pub fn install(ctx: AccessContext) -> AccessGuard {
60    CURRENT_ACCESS.with(|cell| {
61        *cell.borrow_mut() = Some(Arc::new(ctx));
62    });
63    AccessGuard { _priv: () }
64}
65
66/// Register `can_view` (function + filter) and `visible` (filter) on
67/// `tera`. Wired from [`crate::urls::register_tera_helpers`].
68pub fn register_tera_function(tera: &mut Tera) {
69    tera.register_function("can_view", CanViewFn);
70    tera.register_filter("can_view", CanViewFilter);
71    tera.register_filter("visible", VisibleFilter);
72}
73
74/// Resolve whether the current viewer may see the page described by a
75/// Tera value (a page-shaped object with `path` + `page_type_id`).
76///
77/// Visible when no context is installed or the tenant gates nothing. A
78/// value with no `path` key is not a page (an external menu link) and has
79/// nothing to gate. A malformed page fails closed: a non-string
80/// `path` is hidden, and a missing `page_type_id` is hidden whenever a
81/// page type is gated, since the type check can't be answered.
82fn value_visible(value: &Value) -> bool {
83    CURRENT_ACCESS.with(|cell| match cell.borrow().as_ref() {
84        None => true,
85        Some(ctx) => {
86            if ctx.is_unrestricted() {
87                return true;
88            }
89            let Some(path) = value.get("path") else {
90                return true;
91            };
92            let Some(path) = path.as_str() else {
93                return false;
94            };
95            match value.get("page_type_id").and_then(Value::as_i64) {
96                Some(tid) => ctx.can_view(path, tid),
97                None => !ctx.gates_by_type() && ctx.can_view(path, 0),
98            }
99        }
100    })
101}
102
103struct CanViewFn;
104
105impl Function for CanViewFn {
106    fn call(&self, args: &std::collections::HashMap<String, Value>) -> tera::Result<Value> {
107        let visible = args.get("page").map(value_visible).unwrap_or(true);
108        Ok(Value::Bool(visible))
109    }
110}
111
112struct CanViewFilter;
113
114impl Filter for CanViewFilter {
115    fn filter(
116        &self,
117        value: &Value,
118        _args: &std::collections::HashMap<String, Value>,
119    ) -> tera::Result<Value> {
120        Ok(Value::Bool(value_visible(value)))
121    }
122}
123
124struct VisibleFilter;
125
126impl Filter for VisibleFilter {
127    fn filter(
128        &self,
129        value: &Value,
130        _args: &std::collections::HashMap<String, Value>,
131    ) -> tera::Result<Value> {
132        Ok(filter_list(value))
133    }
134}
135
136/// Filter an array of page-shaped values to the visible ones, recursing
137/// into each item's nested `children` array (for nested menus / trees).
138/// Non-arrays pass through unchanged.
139fn filter_list(value: &Value) -> Value {
140    match value {
141        Value::Array(items) => Value::Array(
142            items
143                .iter()
144                .filter(|it| value_visible(it))
145                .map(filter_children)
146                .collect(),
147        ),
148        other => other.clone(),
149    }
150}
151
152/// Clone a page/menu item, filtering its nested `children` array (if
153/// any) so nested structures are pruned at every level.
154fn filter_children(item: &Value) -> Value {
155    let mut out = item.clone();
156    if let Some(obj) = out.as_object_mut() {
157        if let Some(Value::Array(kids)) = obj.get("children") {
158            let filtered: Vec<Value> = kids
159                .iter()
160                .filter(|k| value_visible(k))
161                .map(filter_children)
162                .collect();
163            obj.insert("children".to_owned(), Value::Array(filtered));
164        }
165    }
166    out
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use crate::view_restriction::AccessContext;
173    use serde_json::json;
174    use tera::{Context, Tera};
175
176    fn tera() -> Tera {
177        let mut t = Tera::default();
178        register_tera_function(&mut t);
179        t
180    }
181
182    fn render(expr: &str, ctx: &Context) -> String {
183        let mut t = tera();
184        t.add_raw_template("t.html", expr).unwrap();
185        t.render("t.html", ctx).unwrap()
186    }
187
188    #[test]
189    fn can_view_filter_reflects_context() {
190        let _g = install(AccessContext::deny_prefix_for_test("0001/0002/"));
191        let mut ctx = Context::new();
192        ctx.insert(
193            "gated",
194            &json!({ "path": "0001/0002/", "page_type_id": 5, "title": "M" }),
195        );
196        ctx.insert(
197            "open",
198            &json!({ "path": "0001/0003/", "page_type_id": 5, "title": "O" }),
199        );
200        assert_eq!(render("{{ gated | can_view }}", &ctx), "false");
201        assert_eq!(render("{{ open | can_view }}", &ctx), "true");
202    }
203
204    /// A malformed page fails closed; a pathless menu link stays.
205    #[test]
206    fn can_view_fails_closed_on_malformed_pages() {
207        let _g = install(AccessContext::deny_type_for_test(5));
208        let mut ctx = Context::new();
209        ctx.insert("no_type", &json!({ "path": "0001/0003/" }));
210        ctx.insert("bad_path", &json!({ "path": 7, "page_type_id": 4 }));
211        ctx.insert("link", &json!({ "title": "Docs", "url": "https://x.test" }));
212        ctx.insert("open", &json!({ "path": "0001/0003/", "page_type_id": 4 }));
213        assert_eq!(render("{{ no_type | can_view }}", &ctx), "false");
214        assert_eq!(render("{{ bad_path | can_view }}", &ctx), "false");
215        assert_eq!(render("{{ link | can_view }}", &ctx), "true");
216        assert_eq!(render("{{ open | can_view }}", &ctx), "true");
217    }
218
219    #[test]
220    fn can_view_defaults_true_without_context() {
221        // No context installed (e.g. an ungated render) → everything visible.
222        let mut ctx = Context::new();
223        ctx.insert("p", &json!({ "path": "0001/0002/", "page_type_id": 5 }));
224        assert_eq!(render("{{ p | can_view }}", &ctx), "true");
225    }
226
227    #[test]
228    fn visible_filter_drops_denied_and_recurses() {
229        let _g = install(AccessContext::deny_prefix_for_test("0001/0002/"));
230        let mut ctx = Context::new();
231        ctx.insert(
232            "items",
233            &json!([
234                { "title": "Open",  "path": "0001/0003/", "page_type_id": 4,
235                  "children": [
236                      { "title": "OpenKid",  "path": "0001/0003/0009/", "page_type_id": 4 },
237                      { "title": "GatedKid", "path": "0001/0002/0008/", "page_type_id": 5 }
238                  ] },
239                { "title": "Gated", "path": "0001/0002/", "page_type_id": 5 }
240            ]),
241        );
242        // Top level: "Gated" dropped; nested: "GatedKid" dropped, "OpenKid" kept.
243        let out = render(
244            "{% for i in items | visible %}{{ i.title }}[{% for c in i.children %}{{ c.title }} {% endfor %}]{% endfor %}",
245            &ctx,
246        );
247        assert_eq!(out, "Open[OpenKid ]");
248    }
249
250    #[test]
251    fn guard_clears_thread_local() {
252        {
253            let _g = install(AccessContext::deny_prefix_for_test("0001/"));
254            let mut ctx = Context::new();
255            ctx.insert("p", &json!({ "path": "0001/0002/", "page_type_id": 5 }));
256            assert_eq!(render("{{ p | can_view }}", &ctx), "false");
257        }
258        // After the guard drops, no context → default visible.
259        let mut ctx = Context::new();
260        ctx.insert("p", &json!({ "path": "0001/0002/", "page_type_id": 5 }));
261        assert_eq!(render("{{ p | can_view }}", &ctx), "true");
262    }
263}