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
623pub async fn only_anonymous_visible(
630 pool: &rustango::sql::Pool,
631 mut qs: rustango::query::QuerySet<crate::page::Page>,
632) -> rustango::query::QuerySet<crate::page::Page> {
633 use rustango::core::Column as _;
634 let (prefixes, types) = access_context(pool, None).await.denied_scopes();
635 for prefix in prefixes {
636 qs = qs.where_(crate::page::Page::path.not_like(format!("{prefix}%")));
637 }
638 if !types.is_empty() {
639 qs = qs.where_(crate::page::Page::page_type_id.not_in(types));
640 }
641 qs
642}
643
644impl AccessContext {
645 fn deny_all(is_super: bool) -> Self {
648 Self {
649 is_authed: false,
650 is_super,
651 perm_set: std::collections::HashSet::new(),
652 role_ids: std::collections::HashSet::new(),
653 restricted: vec![(String::new(), deny_restriction(0))],
654 type_restrictions: std::collections::HashMap::new(),
655 }
656 }
657}
658
659#[cfg(test)]
660impl AccessContext {
661 pub(crate) fn deny_prefix_for_test(deny_prefix: &str) -> Self {
665 use rustango::sql::Auto;
666 let r = PageViewRestriction {
667 id: Auto::Unset,
668 page_id: 0,
669 kind: RestrictionKind::Login.as_str().to_owned(),
670 password_hash: String::new(),
671 group_ids: serde_json::json!([]),
672 codenames: serde_json::json!([]),
673 created_at: Auto::Unset,
674 updated_at: Auto::Unset,
675 };
676 Self {
677 is_authed: false,
678 is_super: false,
679 perm_set: std::collections::HashSet::new(),
680 role_ids: std::collections::HashSet::new(),
681 restricted: vec![(deny_prefix.to_owned(), r)],
682 type_restrictions: std::collections::HashMap::new(),
683 }
684 }
685
686 pub(crate) fn deny_type_for_test(page_type_id: i64) -> Self {
688 let mut ctx = Self::deny_prefix_for_test("\u{0}");
689 let (_, r) = ctx.restricted.pop().expect("one restriction");
690 ctx.type_restrictions.insert(page_type_id, r);
691 ctx
692 }
693
694 pub(crate) fn unrestricted_for_test() -> Self {
696 Self {
697 is_authed: false,
698 is_super: false,
699 perm_set: std::collections::HashSet::new(),
700 role_ids: std::collections::HashSet::new(),
701 restricted: Vec::new(),
702 type_restrictions: std::collections::HashMap::new(),
703 }
704 }
705}
706
707pub async fn access_context(
717 pool: &rustango::sql::Pool,
718 viewer: Option<&rustango::tenancy::auth::User>,
719) -> AccessContext {
720 match try_access_context(pool, viewer).await {
721 Ok(ctx) => ctx,
722 Err(e) => {
723 tracing::warn!(
724 target: "rustango_cms::view_restriction",
725 error = %e,
726 "restriction lookup failed; hiding restricted listings"
727 );
728 AccessContext::deny_all(viewer.is_some_and(|u| u.is_superuser))
729 }
730 }
731}
732
733async fn try_access_context(
734 pool: &rustango::sql::Pool,
735 viewer: Option<&rustango::tenancy::auth::User>,
736) -> Result<AccessContext, rustango::sql::ExecError> {
737 use rustango::core::Column as _;
738 use rustango::sql::FetcherPool as _;
739 use std::collections::HashMap;
740
741 let all: Vec<PageViewRestriction> = PageViewRestriction::objects().fetch(pool).await?;
743 let restricted: Vec<(String, PageViewRestriction)> = if all.is_empty() {
744 Vec::new()
745 } else {
746 let ids: Vec<i64> = all.iter().map(|r| r.page_id).collect();
747 let pages: Vec<crate::page::Page> = crate::page::Page::objects()
748 .where_(crate::page::Page::id.is_in(ids.iter().copied()))
749 .fetch(pool)
750 .await?;
751 let path_by_id: HashMap<i64, String> = pages
752 .iter()
753 .filter_map(|p| p.id.get().copied().map(|id| (id, p.path.clone())))
754 .collect();
755 let mut v: Vec<(String, PageViewRestriction)> = all
756 .into_iter()
757 .filter_map(|r| path_by_id.get(&r.page_id).map(|p| (p.clone(), r)))
758 .collect();
759 v.sort_by_key(|(path, _)| std::cmp::Reverse(path.len()));
760 v
761 };
762
763 let type_restrictions: HashMap<i64, PageViewRestriction> =
765 if crate::page_type::any_type_view_restriction() {
766 let type_rows: Vec<crate::PageType> = crate::PageType::objects().fetch(pool).await?;
767 type_rows
768 .into_iter()
769 .filter_map(|pt| {
770 let tid = pt.id.get().copied()?;
771 type_restriction_for_type(tid, &pt.type_name).map(|r| (tid, r))
772 })
773 .collect()
774 } else {
775 HashMap::new()
776 };
777
778 let gated = !restricted.is_empty() || !type_restrictions.is_empty();
779 let facts = viewer_facts(pool, viewer, gated).await;
780
781 Ok(AccessContext {
782 is_authed: facts.is_authed,
783 is_super: facts.is_super,
784 perm_set: facts.perm_set,
785 role_ids: facts.role_ids,
786 restricted,
787 type_restrictions,
788 })
789}
790
791fn deny_restriction(page_id: i64) -> PageViewRestriction {
794 PageViewRestriction {
795 id: Auto::Unset,
796 page_id,
797 kind: RestrictionKind::Groups.as_str().to_owned(),
798 password_hash: String::new(),
799 group_ids: serde_json::json!([]),
800 codenames: serde_json::json!([]),
801 created_at: Auto::Unset,
802 updated_at: Auto::Unset,
803 }
804}
805
806fn deny_every_page(
809 pages: &[(i64, String)],
810 e: &rustango::sql::ExecError,
811) -> std::collections::HashMap<i64, PageViewRestriction> {
812 tracing::warn!(
813 target: "rustango_cms::view_restriction",
814 error = %e,
815 "restriction lookup failed; treating every listed page as restricted"
816 );
817 pages.iter().map(|(id, _)| (*id, deny_restriction(*id))).collect()
818}
819
820pub async fn denied_page_ids(
826 pool: &rustango::sql::Pool,
827 viewer: Option<&rustango::tenancy::auth::User>,
828 pages: &[(i64, String, i64)],
829) -> std::collections::HashSet<i64> {
830 let mut denied = std::collections::HashSet::new();
831 if pages.is_empty() {
832 return denied;
833 }
834 let ctx = access_context(pool, viewer).await;
835 if ctx.is_unrestricted() {
836 return denied;
837 }
838 for (id, path, type_id) in pages {
839 if !ctx.can_view(path, *type_id) {
840 denied.insert(*id);
841 }
842 }
843 denied
844}
845
846async fn viewer_role_ids(pool: &rustango::sql::Pool, uid: i64) -> std::collections::HashSet<i64> {
849 use rustango::core::Column as _;
850 use rustango::sql::FetcherPool as _;
851 let rows: Vec<rustango::tenancy::permissions::UserRole> =
852 rustango::tenancy::permissions::UserRole::objects()
853 .where_(rustango::tenancy::permissions::UserRole::user_id.eq(uid))
854 .fetch(pool)
855 .await
856 .unwrap_or_default();
857 rows.into_iter().map(|r| r.role_id).collect()
858}
859
860#[cfg(test)]
861mod tests {
862 use super::*;
863 use std::collections::HashSet;
864
865 fn restriction(
866 kind: RestrictionKind,
867 codenames: &[&str],
868 groups: &[i64],
869 ) -> PageViewRestriction {
870 use rustango::sql::Auto;
871 PageViewRestriction {
872 id: Auto::Unset,
873 page_id: 1,
874 kind: kind.as_str().to_owned(),
875 password_hash: String::new(),
876 group_ids: serde_json::json!(groups),
877 codenames: serde_json::json!(codenames),
878 created_at: Auto::Unset,
879 updated_at: Auto::Unset,
880 }
881 }
882
883 #[test]
884 fn kind_roundtrips_including_permission() {
885 for k in [
886 RestrictionKind::Password,
887 RestrictionKind::Login,
888 RestrictionKind::Groups,
889 RestrictionKind::Permission,
890 ] {
891 assert_eq!(RestrictionKind::parse(k.as_str()), Some(k));
892 }
893 assert_eq!(RestrictionKind::parse("bogus"), None);
894 assert_eq!(RestrictionKind::Permission.as_str(), "permission");
895 }
896
897 #[test]
898 fn parsed_codenames_reads_strings_only() {
899 let r = restriction(RestrictionKind::Permission, &["a", "b"], &[]);
900 assert_eq!(r.parsed_codenames(), vec!["a".to_owned(), "b".to_owned()]);
901 let g = restriction(RestrictionKind::Groups, &[], &[3, 4]);
903 assert!(g.parsed_codenames().is_empty());
904 assert_eq!(g.parsed_groups(), vec![3, 4]);
905 }
906
907 #[test]
908 fn viewer_satisfies_login_needs_auth() {
909 let r = restriction(RestrictionKind::Login, &[], &[]);
910 let (p, ro) = (HashSet::new(), HashSet::new());
911 assert!(!viewer_satisfies(&r, false, false, &p, &ro));
912 assert!(viewer_satisfies(&r, true, false, &p, &ro));
913 }
914
915 #[test]
916 fn viewer_satisfies_permission_needs_codename_or_super() {
917 let r = restriction(RestrictionKind::Permission, &["members.pro"], &[]);
918 let ro = HashSet::new();
919 assert!(!viewer_satisfies(&r, true, false, &HashSet::new(), &ro));
921 let mut p = HashSet::new();
923 p.insert("members.pro".to_owned());
924 assert!(viewer_satisfies(&r, true, false, &p, &ro));
925 assert!(viewer_satisfies(&r, false, true, &HashSet::new(), &ro));
927 }
928
929 #[test]
930 fn viewer_satisfies_groups_needs_role_or_super() {
931 let r = restriction(RestrictionKind::Groups, &[], &[7]);
932 let p = HashSet::new();
933 assert!(!viewer_satisfies(&r, true, false, &p, &HashSet::new()));
934 let mut roles = HashSet::new();
935 roles.insert(7);
936 assert!(viewer_satisfies(&r, true, false, &p, &roles));
937 }
938
939 #[test]
940 fn viewer_satisfies_password_stays_visible() {
941 let r = restriction(RestrictionKind::Password, &[], &[]);
944 assert!(viewer_satisfies(
945 &r,
946 false,
947 false,
948 &HashSet::new(),
949 &HashSet::new()
950 ));
951 }
952
953 #[test]
954 fn access_context_can_view_prefix_and_unrestricted() {
955 let ctx = AccessContext::deny_prefix_for_test("0001/0002/");
958 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());
963
964 let open = AccessContext::unrestricted_for_test();
965 assert!(open.is_unrestricted());
966 assert!(open.can_view("0001/0002/", 5));
967 }
968
969 #[test]
970 fn type_view_restriction_constructors() {
971 let l = TypeViewRestriction::login();
972 assert_eq!(l.kind, RestrictionKind::Login);
973 assert!(l.codenames.is_empty());
974 let p = TypeViewRestriction::permission(["members.pro", "members.access"]);
975 assert_eq!(p.kind, RestrictionKind::Permission);
976 assert_eq!(
977 p.codenames,
978 vec!["members.pro".to_owned(), "members.access".to_owned()]
979 );
980 }
981}