1use 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 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#[derive(Debug, Clone)]
77pub struct TypeViewRestriction {
78 pub kind: RestrictionKind,
79 pub codenames: Vec<String>,
80}
81
82impl TypeViewRestriction {
83 #[must_use]
85 pub fn login() -> Self {
86 Self {
87 kind: RestrictionKind::Login,
88 codenames: Vec::new(),
89 }
90 }
91
92 #[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 #[rustango(fk = "cms_page", on = "id", index)]
123 pub page_id: i64,
124
125 #[rustango(max_length = 16, index)]
127 pub kind: String,
128
129 #[rustango(max_length = 255)]
131 pub password_hash: String,
132
133 pub group_ids: serde_json::Value,
136
137 #[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 #[must_use]
153 pub fn parsed_kind(&self) -> Option<RestrictionKind> {
154 RestrictionKind::parse(&self.kind)
155 }
156
157 #[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 #[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
182pub 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
199pub 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 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 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 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 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
273pub 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
299async 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
319fn 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
328fn 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
344pub 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 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 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#[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#[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#[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 #[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 None => false,
498 }
499 }
500}
501
502pub 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
537pub 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 restricted: Vec<(String, PageViewRestriction)>,
554 type_restrictions: std::collections::HashMap<i64, PageViewRestriction>,
557}
558
559impl AccessContext {
560 #[must_use]
563 pub fn is_unrestricted(&self) -> bool {
564 self.restricted.is_empty() && self.type_restrictions.is_empty()
565 }
566
567 #[must_use]
569 pub fn gates_by_type(&self) -> bool {
570 !self.type_restrictions.is_empty()
571 }
572
573 #[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 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 pub(crate) fn denies_nothing(&self) -> bool {
626 let (prefixes, types) = self.denied_scopes();
627 prefixes.is_empty() && types.is_empty()
628 }
629}
630
631pub 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 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 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 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 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
715pub 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 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 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
799fn 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
814fn 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
828pub 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
854async 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 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 assert!(!viewer_satisfies(&r, true, false, &HashSet::new(), &ro));
929 let mut p = HashSet::new();
931 p.insert("members.pro".to_owned());
932 assert!(viewer_satisfies(&r, true, false, &p, &ro));
933 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 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 let ctx = AccessContext::deny_prefix_for_test("0001/0002/");
966 assert!(!ctx.can_view("0001/0002/", 5)); assert!(!ctx.can_view("0001/0002/0007/", 5)); assert!(ctx.can_view("0001/0003/", 5)); assert!(ctx.can_view("0001/", 4)); 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}