Skip to main content

rustango_cms/
view_restriction.rs

1//! `PageViewRestriction` — gate published pages behind a password,
2//! a login requirement, or a group membership check.
3//!
4//! Restrictions inherit down the subtree: a restriction on `/members`
5//! covers every descendant unless a descendant declares its own
6//! restriction. The public renderer walks the ancestor chain at
7//! request time and applies the *nearest* restriction it finds.
8//!
9//! Four kinds (including #members):
10//!   * `password` — anonymous visitor sees a prompt form, enters
11//!     the password, gets a signed cookie that skips the prompt on
12//!     subsequent visits.
13//!   * `login`    — anonymous visitor redirected to
14//!     `/members/login?next=<url>`. Any authenticated member/admin passes.
15//!   * `groups`   — logged-in visitor must be a member of at least
16//!     one of the named roles (raw `role_id` match). Anonymous →
17//!     /members/login; logged-in but not in any allowed group → 403.
18//!   * `permission` — logged-in visitor must hold at least one of the
19//!     named permission **codenames**, resolved through the framework
20//!     permission engine (`has_any_perm_pool` — superuser + per-user
21//!     grant/deny baked in). This is the members-area gate; roles carry
22//!     the codenames, admins assign the roles.
23//!
24//! A page-**type** can also declare a `login`/`permission` restriction
25//! for every page of that type (see [`TypeViewRestriction`] +
26//! [`effective_or_type_for_page`]).
27
28use chrono::{DateTime, Utc};
29use rustango::sql::Auto;
30use rustango::Model;
31use serde::{Deserialize, Serialize};
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum RestrictionKind {
36    Password,
37    Login,
38    Groups,
39    /// Gate by the framework **permission engine**: the viewer must
40    /// hold at least one of the restriction's permission codenames
41    /// (checked via `rustango::tenancy::has_any_perm_pool`, which bakes
42    /// in superuser bypass + per-user grant/deny overrides). Roles like
43    /// "Pro" / "Moderator" *carry* those codenames; admins assign the
44    /// roles. Distinct from `Groups`, which matches raw `role_id`s.
45    Permission,
46}
47
48impl RestrictionKind {
49    #[must_use]
50    pub fn as_str(self) -> &'static str {
51        match self {
52            Self::Password => "password",
53            Self::Login => "login",
54            Self::Groups => "groups",
55            Self::Permission => "permission",
56        }
57    }
58
59    #[must_use]
60    pub fn parse(s: &str) -> Option<Self> {
61        Some(match s {
62            "password" => Self::Password,
63            "login" => Self::Login,
64            "groups" => Self::Groups,
65            "permission" => Self::Permission,
66            _ => return None,
67        })
68    }
69}
70
71/// A page-**type**-level view restriction declared by a
72/// [`crate::page_type::PageTypeHandler::view_restriction`] hook. Only
73/// `Login` and `Permission` kinds make sense at the type level
74/// (`password` + `groups` need per-page configuration). Applied only
75/// when a page carries no page/subtree restriction of its own.
76#[derive(Debug, Clone)]
77pub struct TypeViewRestriction {
78    pub kind: RestrictionKind,
79    pub codenames: Vec<String>,
80}
81
82impl TypeViewRestriction {
83    /// Require any authenticated member (login-gate the whole type).
84    #[must_use]
85    pub fn login() -> Self {
86        Self {
87            kind: RestrictionKind::Login,
88            codenames: Vec::new(),
89        }
90    }
91
92    /// Require at least one of `codenames` via the permission engine.
93    #[must_use]
94    pub fn permission<I, S>(codenames: I) -> Self
95    where
96        I: IntoIterator<Item = S>,
97        S: Into<String>,
98    {
99        Self {
100            kind: RestrictionKind::Permission,
101            codenames: codenames.into_iter().map(Into::into).collect(),
102        }
103    }
104}
105
106#[derive(Model, Debug, Clone, Serialize, Deserialize)]
107#[rustango(
108    table = "cms_page_view_restriction",
109    app = "cms",
110    display = "page_id",
111    admin(
112        list_display = "page_id, kind, created_at",
113        ordering = "-created_at",
114        list_filter = "kind",
115    )
116)]
117pub struct PageViewRestriction {
118    #[rustango(primary_key)]
119    pub id: Auto<i64>,
120
121    /// One restriction per page — application-enforced UNIQUE.
122    #[rustango(fk = "cms_page", on = "id", index)]
123    pub page_id: i64,
124
125    /// `RestrictionKind::as_str()`.
126    #[rustango(max_length = 16, index)]
127    pub kind: String,
128
129    /// Argon2id PHC hash. Empty string when `kind != password`.
130    #[rustango(max_length = 255)]
131    pub password_hash: String,
132
133    /// JSON array of `rustango_roles.id` integers — admitted groups
134    /// when `kind = groups`. Empty array on other kinds.
135    pub group_ids: serde_json::Value,
136
137    /// JSON array of permission codename strings — admitted permissions
138    /// when `kind = permission` (any one grants access). Empty array on
139    /// other kinds. See [`RestrictionKind::Permission`].
140    #[rustango(default = "'[]'")]
141    pub codenames: serde_json::Value,
142
143    #[rustango(auto_now_add)]
144    pub created_at: Auto<DateTime<Utc>>,
145
146    #[rustango(auto_now)]
147    pub updated_at: Auto<DateTime<Utc>>,
148}
149
150impl PageViewRestriction {
151    /// Convenience parser returning the typed kind.
152    #[must_use]
153    pub fn parsed_kind(&self) -> Option<RestrictionKind> {
154        RestrictionKind::parse(&self.kind)
155    }
156
157    /// Read `group_ids` as `Vec<i64>`. Returns empty when the field
158    /// is malformed or missing.
159    #[must_use]
160    pub fn parsed_groups(&self) -> Vec<i64> {
161        self.group_ids
162            .as_array()
163            .map(|arr| arr.iter().filter_map(|v| v.as_i64()).collect::<Vec<_>>())
164            .unwrap_or_default()
165    }
166
167    /// Read `codenames` as `Vec<String>`. Returns empty when the field
168    /// is malformed or missing (a NULL column on a pre-migration row).
169    #[must_use]
170    pub fn parsed_codenames(&self) -> Vec<String> {
171        self.codenames
172            .as_array()
173            .map(|arr| {
174                arr.iter()
175                    .filter_map(|v| v.as_str().map(str::to_owned))
176                    .collect::<Vec<_>>()
177            })
178            .unwrap_or_default()
179    }
180}
181
182/// Look up a direct (non-inherited) restriction on a single page.
183///
184/// # Errors
185/// Driver / query failures.
186pub async fn direct_for_page(
187    pool: &rustango::sql::Pool,
188    page_id: i64,
189) -> Result<Option<PageViewRestriction>, rustango::sql::ExecError> {
190    use rustango::core::Column as _;
191    use rustango::sql::FetcherPool as _;
192    let rows: Vec<PageViewRestriction> = PageViewRestriction::objects()
193        .where_(PageViewRestriction::page_id.eq(page_id))
194        .fetch(pool)
195        .await?;
196    Ok(rows.into_iter().next())
197}
198
199/// Walk the page + every ancestor in path order (current page first,
200/// then parent, then grand-parent, …) and return the *nearest*
201/// restriction found. Used by the public renderer middleware.
202///
203/// # Errors
204/// Driver / query failures.
205pub async fn effective_for_page(
206    pool: &rustango::sql::Pool,
207    page: &crate::page::Page,
208) -> Result<Option<PageViewRestriction>, rustango::sql::ExecError> {
209    use rustango::core::Column as _;
210    use rustango::sql::FetcherPool as _;
211
212    // Collect the page's own id + every ancestor id from the
213    // materialized path. `tree::MaterializedPath::ancestors_of`
214    // returns ancestor paths in root-first order; we want
215    // nearest-first, so iterate path segments + own id in reverse.
216    let own_id = page.id.get().copied().unwrap_or_default();
217    let ancestor_ids: Vec<i64> = if let Some(parent_id) = page.parent_id {
218        // Pull every ancestor row in one query via materialized-path
219        // ancestor list, then collect ids in nearest-first order.
220        let ancestor_paths = crate::tree::MaterializedPath::ancestors_of(&page.path);
221        let ancestors: Vec<crate::page::Page> = if ancestor_paths.is_empty() {
222            Vec::new()
223        } else {
224            crate::page::Page::objects()
225                .where_(crate::page::Page::path.is_in(ancestor_paths.iter().cloned()))
226                .fetch(pool)
227                .await?
228        };
229        // Sort by depth desc so the deepest (nearest) ancestor comes
230        // first; if no ancestors loaded, fall back to just parent_id.
231        let mut by_id: std::collections::HashMap<i64, &crate::page::Page> = ancestors
232            .iter()
233            .filter_map(|a| a.id.get().copied().map(|id| (id, a)))
234            .collect();
235        let mut chain: Vec<i64> = Vec::new();
236        let mut current_parent = Some(parent_id);
237        while let Some(pid) = current_parent {
238            chain.push(pid);
239            current_parent = by_id.remove(&pid).and_then(|a| a.parent_id);
240        }
241        chain
242    } else {
243        Vec::new()
244    };
245
246    let mut search: Vec<i64> = Vec::with_capacity(ancestor_ids.len() + 1);
247    search.push(own_id);
248    search.extend(ancestor_ids);
249
250    // One query for every candidate page, then pick the first hit
251    // in our nearest-first order.
252    let restrictions: Vec<PageViewRestriction> = if search.is_empty() {
253        Vec::new()
254    } else {
255        PageViewRestriction::objects()
256            .where_(PageViewRestriction::page_id.is_in(search.iter().copied()))
257            .fetch(pool)
258            .await?
259    };
260    if restrictions.is_empty() {
261        return Ok(None);
262    }
263    let by_page: std::collections::HashMap<i64, PageViewRestriction> =
264        restrictions.into_iter().map(|r| (r.page_id, r)).collect();
265    for pid in search {
266        if let Some(r) = by_page.get(&pid) {
267            return Ok(Some(r.clone()));
268        }
269    }
270    Ok(None)
271}
272
273/// The page's effective restriction (own + inherited from any
274/// ancestor), OR — when none is set anywhere on the branch — the
275/// restriction its page **type** declares via
276/// [`crate::page_type::PageTypeHandler::view_restriction`]. A concrete
277/// page/subtree restriction is more specific and always wins over the
278/// type-level one.
279///
280/// The type-level restriction is returned as a *synthesized*
281/// (unsaved) [`PageViewRestriction`] so the enforcement path
282/// ([`crate::view_restriction_guard::enforce`]) treats it identically
283/// to a stored one — no separate code path.
284///
285/// # Errors
286/// Driver / query failures from the page-restriction lookup.
287pub async fn effective_or_type_for_page(
288    pool: &rustango::sql::Pool,
289    page: &crate::page::Page,
290) -> Result<Option<PageViewRestriction>, rustango::sql::ExecError> {
291    if let Some(r) = effective_for_page(pool, page).await? {
292        return Ok(Some(r));
293    }
294    Ok(type_restriction_for_page(pool, page)
295        .await?
296        .map(|tvr| synthesize_type_restriction(page, &tvr)))
297}
298
299/// Resolve the page-type handler's declared restriction, if any.
300///
301/// A lookup failure is an error, not "unrestricted": the caller denies
302/// on error, where a silent `None` used to serve the page.
303async fn type_restriction_for_page(
304    pool: &rustango::sql::Pool,
305    page: &crate::page::Page,
306) -> Result<Option<TypeViewRestriction>, rustango::sql::ExecError> {
307    use rustango::core::Column as _;
308    use rustango::sql::FetcherPool as _;
309    let pts: Vec<crate::PageType> = crate::PageType::objects()
310        .where_(crate::PageType::id.eq(page.page_type_id))
311        .fetch(pool)
312        .await?;
313    Ok(pts
314        .into_iter()
315        .next()
316        .and_then(|pt| crate::page_type::find_handler(&pt.type_name)?.view_restriction()))
317}
318
319/// Build an unsaved [`PageViewRestriction`] mirroring a type-level
320/// descriptor so the guard can enforce it with its existing logic.
321fn synthesize_type_restriction(
322    page: &crate::page::Page,
323    tvr: &TypeViewRestriction,
324) -> PageViewRestriction {
325    synthesize_restriction(page.id.get().copied().unwrap_or_default(), tvr)
326}
327
328/// Build an unsaved [`PageViewRestriction`] for a given page id from a
329/// type-level descriptor.
330fn synthesize_restriction(page_id: i64, tvr: &TypeViewRestriction) -> PageViewRestriction {
331    use rustango::sql::Auto;
332    PageViewRestriction {
333        id: Auto::Unset,
334        page_id,
335        kind: tvr.kind.as_str().to_owned(),
336        password_hash: String::new(),
337        group_ids: serde_json::json!([]),
338        codenames: serde_json::json!(tvr.codenames),
339        created_at: Auto::Unset,
340        updated_at: Auto::Unset,
341    }
342}
343
344/// Bulk-resolve the effective page/subtree restriction for many pages
345/// at once — for viewer-aware menu filtering, where calling
346/// [`effective_for_page`] per item would be an N+1 on every render.
347///
348/// `pages` are `(page_id, materialized_path)` pairs. Returns
349/// `page_id → nearest restriction` (own or inherited from the closest
350/// restricted ancestor). Cost: two bounded queries total (all tenant
351/// restriction rows + the restricted pages' paths), then in-memory
352/// longest-prefix matching over the materialized paths.
353///
354/// Type-level restrictions are layered on separately by the caller (see
355/// [`type_restriction_for_type`]); this covers only stored page/subtree
356/// rows.
357pub async fn effective_restrictions_for(
358    pool: &rustango::sql::Pool,
359    pages: &[(i64, String)],
360) -> std::collections::HashMap<i64, PageViewRestriction> {
361    use rustango::sql::FetcherPool as _;
362    let mut out = std::collections::HashMap::new();
363    if pages.is_empty() {
364        return out;
365    }
366    let all: Vec<PageViewRestriction> = match PageViewRestriction::objects().fetch(pool).await {
367        Ok(rows) => rows,
368        Err(e) => return deny_every_page(pages, &e),
369    };
370    if all.is_empty() {
371        return out;
372    }
373    // Resolve each restricted page's materialized path so inheritance
374    // can be evaluated as a path-prefix test.
375    let restricted_ids: Vec<i64> = all.iter().map(|r| r.page_id).collect();
376    let restricted_pages: Vec<crate::page::Page> = {
377        use rustango::core::Column as _;
378        match crate::page::Page::objects()
379            .where_(crate::page::Page::id.is_in(restricted_ids.iter().copied()))
380            .fetch(pool)
381            .await
382        {
383            Ok(rows) => rows,
384            Err(e) => return deny_every_page(pages, &e),
385        }
386    };
387    let restriction_by_id: std::collections::HashMap<i64, &PageViewRestriction> =
388        all.iter().map(|r| (r.page_id, r)).collect();
389    // (path, page_id) for restricted pages, longest path first so the
390    // nearest ancestor wins the prefix match.
391    let mut restricted: Vec<(String, i64)> = restricted_pages
392        .iter()
393        .filter_map(|p| p.id.get().copied().map(|id| (p.path.clone(), id)))
394        .collect();
395    restricted.sort_by_key(|(path, _)| std::cmp::Reverse(path.len()));
396    for (pid, mpath) in pages {
397        for (rpath, rid) in &restricted {
398            if mpath.starts_with(rpath.as_str()) {
399                if let Some(r) = restriction_by_id.get(rid) {
400                    out.insert(*pid, (*r).clone());
401                }
402                break;
403            }
404        }
405    }
406    out
407}
408
409/// Resolve the type-level restriction for a page-type id, if the
410/// handler declares one. Used by menu filtering to hide type-gated
411/// pages; synthesizes a [`PageViewRestriction`] so callers share one
412/// predicate ([`viewer_satisfies`]).
413#[must_use]
414pub fn type_restriction_for_type(
415    page_type_id: i64,
416    type_name: &str,
417) -> Option<PageViewRestriction> {
418    let tvr = crate::page_type::find_handler(type_name)?.view_restriction()?;
419    Some(synthesize_restriction(page_type_id, &tvr))
420}
421
422/// Decide whether a viewer may *see* a restricted item, using
423/// pre-resolved viewer facts (so menu filtering avoids per-item
424/// queries). `is_authed` = a member/admin is signed in; `is_super` =
425/// superuser; `perm_set` = the viewer's permission codenames (from
426/// `user_permissions_pool`); `role_ids` = the viewer's role ids.
427///
428/// `Password` restrictions are treated as **visible** — password is
429/// identity-orthogonal, so the link shows and the guard prompts on
430/// click (matching the pre-#members behavior).
431#[must_use]
432pub fn viewer_satisfies(
433    restriction: &PageViewRestriction,
434    is_authed: bool,
435    is_super: bool,
436    perm_set: &std::collections::HashSet<String>,
437    role_ids: &std::collections::HashSet<i64>,
438) -> bool {
439    ViewerFacts {
440        is_authed,
441        is_super,
442        perm_set: perm_set.clone(),
443        role_ids: role_ids.clone(),
444    }
445    .satisfies(
446        restriction.parsed_kind(),
447        &restriction.parsed_groups(),
448        &restriction.parsed_codenames(),
449    )
450}
451
452/// A viewer's resolved access facts, independent of what is being
453/// guarded.
454///
455/// [`AccessContext`] holds these alongside the *page* restrictions, but
456/// media collections gate on exactly the same four things and had no way
457/// to reuse them — so `/api/v2/images/` listed assets that `/__media__/`
458/// refuses to serve. Splitting the facts out lets both ask the same
459/// question of the same viewer.
460#[derive(Debug, Clone, Default)]
461pub struct ViewerFacts {
462    pub is_authed: bool,
463    pub is_super: bool,
464    pub perm_set: std::collections::HashSet<String>,
465    pub role_ids: std::collections::HashSet<i64>,
466}
467
468impl ViewerFacts {
469    /// Does this viewer satisfy a restriction of `kind`?
470    ///
471    /// Takes the restriction decomposed rather than by type, because
472    /// pages and collections store the same three fields in two
473    /// different tables.
474    ///
475    /// `Password` returns `true`: a password gate is satisfied by a
476    /// cookie the guard checks at request time, not by who you are, so
477    /// hiding password-protected items from listings would be wrong —
478    /// the prompt is the point.
479    #[must_use]
480    pub fn satisfies(
481        &self,
482        kind: Option<RestrictionKind>,
483        groups: &[i64],
484        codenames: &[String],
485    ) -> bool {
486        if self.is_super {
487            return true;
488        }
489        match kind {
490            Some(RestrictionKind::Login) => self.is_authed,
491            Some(RestrictionKind::Groups) => groups.iter().any(|g| self.role_ids.contains(g)),
492            Some(RestrictionKind::Permission) => {
493                codenames.iter().any(|c| self.perm_set.contains(c))
494            }
495            Some(RestrictionKind::Password) => true,
496            // A kind this build can't read denies, as the serve path does.
497            None => false,
498        }
499    }
500}
501
502/// Resolve a viewer's permissions and roles.
503///
504/// `gated` lets the caller skip both lookups when nothing is restricted
505/// — the common case, and the reason a public site pays nothing for this
506/// machinery.
507pub async fn viewer_facts(
508    pool: &rustango::sql::Pool,
509    viewer: Option<&rustango::tenancy::auth::User>,
510    gated: bool,
511) -> ViewerFacts {
512    let is_super = viewer.is_some_and(|u| u.is_superuser);
513    let (perm_set, role_ids) = match viewer {
514        Some(u) if gated && !is_super => {
515            let uid = u.id.get().copied().unwrap_or_default();
516            let perms = rustango::tenancy::user_permissions_pool(uid, pool)
517                .await
518                .unwrap_or_default();
519            (
520                perms.into_iter().collect(),
521                viewer_role_ids(pool, uid).await,
522            )
523        }
524        _ => (
525            std::collections::HashSet::new(),
526            std::collections::HashSet::new(),
527        ),
528    };
529    ViewerFacts {
530        is_authed: viewer.is_some(),
531        is_super,
532        perm_set,
533        role_ids,
534    }
535}
536
537/// A resolve-once, in-memory oracle for "can this viewer see page X?".
538/// Built per render by [`access_context`] and reused for viewer-aware
539/// menu hiding **and** the `can_view` / `visible` Tera helpers (so a
540/// template can guard any hand-written page link or nested list with
541/// the same protection the built-in menus apply). Holds the viewer's
542/// resolved facts + every tenant view-restriction (page/subtree and
543/// per-type), so [`AccessContext::can_view`] answers with zero further
544/// queries.
545pub struct AccessContext {
546    is_authed: bool,
547    is_super: bool,
548    perm_set: std::collections::HashSet<String>,
549    role_ids: std::collections::HashSet<i64>,
550    /// `(materialized_path, restriction)` for every restricted page,
551    /// sorted longest-path-first so the nearest ancestor wins the
552    /// subtree-inheritance prefix match.
553    restricted: Vec<(String, PageViewRestriction)>,
554    /// `page_type_id → restriction` for every type whose handler
555    /// declares one (empty when nothing gates by type).
556    type_restrictions: std::collections::HashMap<i64, PageViewRestriction>,
557}
558
559impl AccessContext {
560    /// True when nothing is gated at all — callers can short-circuit to
561    /// "everything visible" without inspecting each page.
562    #[must_use]
563    pub fn is_unrestricted(&self) -> bool {
564        self.restricted.is_empty() && self.type_restrictions.is_empty()
565    }
566
567    /// True when some page type carries a view restriction.
568    #[must_use]
569    pub fn gates_by_type(&self) -> bool {
570        !self.type_restrictions.is_empty()
571    }
572
573    /// Can the viewer see the page with this materialized `path` +
574    /// `page_type_id`? A page/subtree restriction (nearest ancestor by
575    /// longest path prefix) wins; otherwise the page-type restriction
576    /// applies; otherwise the page is public.
577    #[must_use]
578    pub fn can_view(&self, path: &str, page_type_id: i64) -> bool {
579        let restriction = self
580            .restricted
581            .iter()
582            .find(|(rpath, _)| path.starts_with(rpath.as_str()))
583            .map(|(_, r)| r)
584            .or_else(|| self.type_restrictions.get(&page_type_id));
585        match restriction {
586            None => true,
587            Some(r) => viewer_satisfies(
588                r,
589                self.is_authed,
590                self.is_super,
591                &self.perm_set,
592                &self.role_ids,
593            ),
594        }
595    }
596}
597
598impl AccessContext {
599    /// What this viewer may not see, as SQL exclusions: the subtree path
600    /// prefixes and page type ids whose restriction it fails. Over-hides
601    /// rather than under-hides — a page the viewer could open under a
602    /// nested restriction it satisfies is still excluded with its denied
603    /// ancestor.
604    fn denied_scopes(&self) -> (Vec<String>, Vec<i64>) {
605        let satisfies =
606            |r| viewer_satisfies(r, self.is_authed, self.is_super, &self.perm_set, &self.role_ids);
607        let prefixes = self
608            .restricted
609            .iter()
610            .filter(|(_, r)| !satisfies(r))
611            .map(|(path, _)| path.clone())
612            .collect();
613        let types = self
614            .type_restrictions
615            .iter()
616            .filter(|(_, r)| !satisfies(r))
617            .map(|(tid, _)| *tid)
618            .collect();
619        (prefixes, types)
620    }
621
622    /// True when the viewer satisfies every restriction there is, so
623    /// [`Self::can_view`] answers true for any page and a listing can
624    /// count and page in SQL without checking each row.
625    pub(crate) fn denies_nothing(&self) -> bool {
626        let (prefixes, types) = self.denied_scopes();
627        prefixes.is_empty() && types.is_empty()
628    }
629}
630
631/// Narrow a page query to what an anonymous visitor may see.
632///
633/// For crawler-facing listings (feed, sitemap), which are cached and read
634/// without a session. The filter is in SQL so paging and counts stay
635/// right. Materialized paths hold only alphanumerics and `/`, so a
636/// prefix needs no LIKE escaping.
637pub async fn only_anonymous_visible(
638    pool: &rustango::sql::Pool,
639    mut qs: rustango::query::QuerySet<crate::page::Page>,
640) -> rustango::query::QuerySet<crate::page::Page> {
641    use rustango::core::Column as _;
642    let (prefixes, types) = access_context(pool, None).await.denied_scopes();
643    for prefix in prefixes {
644        qs = qs.where_(crate::page::Page::path.not_like(format!("{prefix}%")));
645    }
646    if !types.is_empty() {
647        qs = qs.where_(crate::page::Page::page_type_id.not_in(types));
648    }
649    qs
650}
651
652impl AccessContext {
653    /// Every path gated behind [`deny_restriction`]: superusers see
654    /// everything, everyone else nothing.
655    fn deny_all(is_super: bool) -> Self {
656        Self {
657            is_authed: false,
658            is_super,
659            perm_set: std::collections::HashSet::new(),
660            role_ids: std::collections::HashSet::new(),
661            restricted: vec![(String::new(), deny_restriction(0))],
662            type_restrictions: std::collections::HashMap::new(),
663        }
664    }
665}
666
667#[cfg(test)]
668impl AccessContext {
669    /// Test-only: a context that gates every page whose materialized
670    /// path starts with `deny_prefix` behind a `login` restriction (so an
671    /// anonymous viewer is denied, everything else public).
672    pub(crate) fn deny_prefix_for_test(deny_prefix: &str) -> Self {
673        use rustango::sql::Auto;
674        let r = PageViewRestriction {
675            id: Auto::Unset,
676            page_id: 0,
677            kind: RestrictionKind::Login.as_str().to_owned(),
678            password_hash: String::new(),
679            group_ids: serde_json::json!([]),
680            codenames: serde_json::json!([]),
681            created_at: Auto::Unset,
682            updated_at: Auto::Unset,
683        };
684        Self {
685            is_authed: false,
686            is_super: false,
687            perm_set: std::collections::HashSet::new(),
688            role_ids: std::collections::HashSet::new(),
689            restricted: vec![(deny_prefix.to_owned(), r)],
690            type_restrictions: std::collections::HashMap::new(),
691        }
692    }
693
694    /// Test-only: a context gating one page type behind a login.
695    pub(crate) fn deny_type_for_test(page_type_id: i64) -> Self {
696        let mut ctx = Self::deny_prefix_for_test("\u{0}");
697        let (_, r) = ctx.restricted.pop().expect("one restriction");
698        ctx.type_restrictions.insert(page_type_id, r);
699        ctx
700    }
701
702    /// Test-only: a context that gates nothing.
703    pub(crate) fn unrestricted_for_test() -> Self {
704        Self {
705            is_authed: false,
706            is_super: false,
707            perm_set: std::collections::HashSet::new(),
708            role_ids: std::collections::HashSet::new(),
709            restricted: Vec::new(),
710            type_restrictions: std::collections::HashMap::new(),
711        }
712    }
713}
714
715/// Build the per-render [`AccessContext`] for `viewer`: load every
716/// tenant restriction (+ the restricted pages' paths) and per-type
717/// restriction, and resolve the viewer's codenames + role ids. Bounded,
718/// fixed number of queries; the viewer lookups are skipped entirely when
719/// nothing is gated or the viewer is a superuser.
720///
721/// When the restrictions can't be read the context hides every page from
722/// everyone but superusers: a menu or search result must not list
723/// a gated page's title and URL because the lookup failed.
724pub async fn access_context(
725    pool: &rustango::sql::Pool,
726    viewer: Option<&rustango::tenancy::auth::User>,
727) -> AccessContext {
728    match try_access_context(pool, viewer).await {
729        Ok(ctx) => ctx,
730        Err(e) => {
731            tracing::warn!(
732                target: "rustango_cms::view_restriction",
733                error = %e,
734                "restriction lookup failed; hiding restricted listings"
735            );
736            AccessContext::deny_all(viewer.is_some_and(|u| u.is_superuser))
737        }
738    }
739}
740
741async fn try_access_context(
742    pool: &rustango::sql::Pool,
743    viewer: Option<&rustango::tenancy::auth::User>,
744) -> Result<AccessContext, rustango::sql::ExecError> {
745    use rustango::core::Column as _;
746    use rustango::sql::FetcherPool as _;
747    use std::collections::HashMap;
748
749    // Page/subtree restrictions + their materialized paths.
750    let all: Vec<PageViewRestriction> = PageViewRestriction::objects().fetch(pool).await?;
751    let restricted: Vec<(String, PageViewRestriction)> = if all.is_empty() {
752        Vec::new()
753    } else {
754        let ids: Vec<i64> = all.iter().map(|r| r.page_id).collect();
755        let pages: Vec<crate::page::Page> = crate::page::Page::objects()
756            .where_(crate::page::Page::id.is_in(ids.iter().copied()))
757            .fetch(pool)
758            .await?;
759        let path_by_id: HashMap<i64, String> = pages
760            .iter()
761            .filter_map(|p| p.id.get().copied().map(|id| (id, p.path.clone())))
762            .collect();
763        let mut v: Vec<(String, PageViewRestriction)> = all
764            .into_iter()
765            .filter_map(|r| path_by_id.get(&r.page_id).map(|p| (p.clone(), r)))
766            .collect();
767        v.sort_by_key(|(path, _)| std::cmp::Reverse(path.len()));
768        v
769    };
770
771    // Per-type restrictions (only when some handler gates by type).
772    let type_restrictions: HashMap<i64, PageViewRestriction> =
773        if crate::page_type::any_type_view_restriction() {
774            let type_rows: Vec<crate::PageType> = crate::PageType::objects().fetch(pool).await?;
775            type_rows
776                .into_iter()
777                .filter_map(|pt| {
778                    let tid = pt.id.get().copied()?;
779                    type_restriction_for_type(tid, &pt.type_name).map(|r| (tid, r))
780                })
781                .collect()
782        } else {
783            HashMap::new()
784        };
785
786    let gated = !restricted.is_empty() || !type_restrictions.is_empty();
787    let facts = viewer_facts(pool, viewer, gated).await;
788
789    Ok(AccessContext {
790        is_authed: facts.is_authed,
791        is_super: facts.is_super,
792        perm_set: facts.perm_set,
793        role_ids: facts.role_ids,
794        restricted,
795        type_restrictions,
796    })
797}
798
799/// A restriction nobody but a superuser satisfies: `groups` with no
800/// groups. Stands in for "unknown" when the real rows can't be read.
801fn deny_restriction(page_id: i64) -> PageViewRestriction {
802    PageViewRestriction {
803        id: Auto::Unset,
804        page_id,
805        kind: RestrictionKind::Groups.as_str().to_owned(),
806        password_hash: String::new(),
807        group_ids: serde_json::json!([]),
808        codenames: serde_json::json!([]),
809        created_at: Auto::Unset,
810        updated_at: Auto::Unset,
811    }
812}
813
814/// [`effective_restrictions_for`] when the restrictions can't be read:
815/// every page counts as restricted.
816fn deny_every_page(
817    pages: &[(i64, String)],
818    e: &rustango::sql::ExecError,
819) -> std::collections::HashMap<i64, PageViewRestriction> {
820    tracing::warn!(
821        target: "rustango_cms::view_restriction",
822        error = %e,
823        "restriction lookup failed; treating every listed page as restricted"
824    );
825    pages.iter().map(|(id, _)| (*id, deny_restriction(*id))).collect()
826}
827
828/// Given a batch of pages and a viewer, return the subset of page ids
829/// the viewer may **not** access — for viewer-aware menu hiding shared
830/// by `auto_menu` and the curated navigation resolver. `pages` are
831/// `(page_id, materialized_path, page_type_id)` triples. Thin wrapper
832/// over [`access_context`] + [`AccessContext::can_view`].
833pub async fn denied_page_ids(
834    pool: &rustango::sql::Pool,
835    viewer: Option<&rustango::tenancy::auth::User>,
836    pages: &[(i64, String, i64)],
837) -> std::collections::HashSet<i64> {
838    let mut denied = std::collections::HashSet::new();
839    if pages.is_empty() {
840        return denied;
841    }
842    let ctx = access_context(pool, viewer).await;
843    if ctx.is_unrestricted() {
844        return denied;
845    }
846    for (id, path, type_id) in pages {
847        if !ctx.can_view(path, *type_id) {
848            denied.insert(*id);
849        }
850    }
851    denied
852}
853
854/// The set of role ids a member/admin holds (for menu-hiding a legacy
855/// `groups` restriction).
856async fn viewer_role_ids(pool: &rustango::sql::Pool, uid: i64) -> std::collections::HashSet<i64> {
857    use rustango::core::Column as _;
858    use rustango::sql::FetcherPool as _;
859    let rows: Vec<rustango::tenancy::permissions::UserRole> =
860        rustango::tenancy::permissions::UserRole::objects()
861            .where_(rustango::tenancy::permissions::UserRole::user_id.eq(uid))
862            .fetch(pool)
863            .await
864            .unwrap_or_default();
865    rows.into_iter().map(|r| r.role_id).collect()
866}
867
868#[cfg(test)]
869mod tests {
870    use super::*;
871    use std::collections::HashSet;
872
873    fn restriction(
874        kind: RestrictionKind,
875        codenames: &[&str],
876        groups: &[i64],
877    ) -> PageViewRestriction {
878        use rustango::sql::Auto;
879        PageViewRestriction {
880            id: Auto::Unset,
881            page_id: 1,
882            kind: kind.as_str().to_owned(),
883            password_hash: String::new(),
884            group_ids: serde_json::json!(groups),
885            codenames: serde_json::json!(codenames),
886            created_at: Auto::Unset,
887            updated_at: Auto::Unset,
888        }
889    }
890
891    #[test]
892    fn kind_roundtrips_including_permission() {
893        for k in [
894            RestrictionKind::Password,
895            RestrictionKind::Login,
896            RestrictionKind::Groups,
897            RestrictionKind::Permission,
898        ] {
899            assert_eq!(RestrictionKind::parse(k.as_str()), Some(k));
900        }
901        assert_eq!(RestrictionKind::parse("bogus"), None);
902        assert_eq!(RestrictionKind::Permission.as_str(), "permission");
903    }
904
905    #[test]
906    fn parsed_codenames_reads_strings_only() {
907        let r = restriction(RestrictionKind::Permission, &["a", "b"], &[]);
908        assert_eq!(r.parsed_codenames(), vec!["a".to_owned(), "b".to_owned()]);
909        // A groups restriction (ints in group_ids) yields no codenames.
910        let g = restriction(RestrictionKind::Groups, &[], &[3, 4]);
911        assert!(g.parsed_codenames().is_empty());
912        assert_eq!(g.parsed_groups(), vec![3, 4]);
913    }
914
915    #[test]
916    fn viewer_satisfies_login_needs_auth() {
917        let r = restriction(RestrictionKind::Login, &[], &[]);
918        let (p, ro) = (HashSet::new(), HashSet::new());
919        assert!(!viewer_satisfies(&r, false, false, &p, &ro));
920        assert!(viewer_satisfies(&r, true, false, &p, &ro));
921    }
922
923    #[test]
924    fn viewer_satisfies_permission_needs_codename_or_super() {
925        let r = restriction(RestrictionKind::Permission, &["members.pro"], &[]);
926        let ro = HashSet::new();
927        // authed but lacks the codename → denied
928        assert!(!viewer_satisfies(&r, true, false, &HashSet::new(), &ro));
929        // holds the codename → allowed
930        let mut p = HashSet::new();
931        p.insert("members.pro".to_owned());
932        assert!(viewer_satisfies(&r, true, false, &p, &ro));
933        // superuser bypass, even anonymous perm set
934        assert!(viewer_satisfies(&r, false, true, &HashSet::new(), &ro));
935    }
936
937    #[test]
938    fn viewer_satisfies_groups_needs_role_or_super() {
939        let r = restriction(RestrictionKind::Groups, &[], &[7]);
940        let p = HashSet::new();
941        assert!(!viewer_satisfies(&r, true, false, &p, &HashSet::new()));
942        let mut roles = HashSet::new();
943        roles.insert(7);
944        assert!(viewer_satisfies(&r, true, false, &p, &roles));
945    }
946
947    #[test]
948    fn viewer_satisfies_password_stays_visible() {
949        // Password is identity-orthogonal — menu items stay visible and
950        // the guard prompts on click.
951        let r = restriction(RestrictionKind::Password, &[], &[]);
952        assert!(viewer_satisfies(
953            &r,
954            false,
955            false,
956            &HashSet::new(),
957            &HashSet::new()
958        ));
959    }
960
961    #[test]
962    fn access_context_can_view_prefix_and_unrestricted() {
963        // Subtree gate: the gated page + its descendants are denied to an
964        // anonymous viewer; siblings outside the subtree are visible.
965        let ctx = AccessContext::deny_prefix_for_test("0001/0002/");
966        assert!(!ctx.can_view("0001/0002/", 5)); // the gated page
967        assert!(!ctx.can_view("0001/0002/0007/", 5)); // a descendant
968        assert!(ctx.can_view("0001/0003/", 5)); // a sibling subtree
969        assert!(ctx.can_view("0001/", 4)); // the root
970        assert!(!ctx.is_unrestricted());
971
972        let open = AccessContext::unrestricted_for_test();
973        assert!(open.is_unrestricted());
974        assert!(open.can_view("0001/0002/", 5));
975    }
976
977    #[test]
978    fn type_view_restriction_constructors() {
979        let l = TypeViewRestriction::login();
980        assert_eq!(l.kind, RestrictionKind::Login);
981        assert!(l.codenames.is_empty());
982        let p = TypeViewRestriction::permission(["members.pro", "members.access"]);
983        assert_eq!(p.kind, RestrictionKind::Permission);
984        assert_eq!(
985            p.codenames,
986            vec!["members.pro".to_owned(), "members.access".to_owned()]
987        );
988    }
989}