1use std::collections::{BTreeMap, BTreeSet};
39use std::fmt;
40use std::sync::Arc;
41
42use serde::{Deserialize, Deserializer, Serialize, Serializer};
43
44use crate::audit::RoleName;
45use crate::auth::AuthContext;
46use crate::identity::Principal;
47
48pub const ADMIN: &str = "admin";
51
52pub const CEILING_KEY: &str = "ceiling";
57
58#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
65#[serde(transparent)]
66pub struct Grant(String);
67
68impl Grant {
69 pub fn new(path: impl Into<String>) -> Self {
72 Self(path.into())
73 }
74
75 pub fn of(activation: &str, method: &str) -> Self {
77 Self(format!("{activation}.{method}"))
78 }
79
80 pub fn as_str(&self) -> &str {
82 &self.0
83 }
84}
85
86impl fmt::Display for Grant {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 f.write_str(&self.0)
89 }
90}
91
92#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
102pub enum ScopeRef {
103 Everywhere,
105 Named(String),
107}
108
109impl ScopeRef {
110 pub fn parse(text: &str) -> Self {
112 match text.trim() {
113 "*" => Self::Everywhere,
114 other => Self::Named(other.to_string()),
115 }
116 }
117
118 pub fn named(name: impl Into<String>) -> Self {
120 Self::Named(name.into())
121 }
122
123 pub fn as_str(&self) -> &str {
125 match self {
126 Self::Everywhere => "*",
127 Self::Named(n) => n,
128 }
129 }
130
131 pub fn is_everywhere(&self) -> bool {
133 matches!(self, Self::Everywhere)
134 }
135}
136
137impl fmt::Display for ScopeRef {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.write_str(self.as_str())
140 }
141}
142
143impl Serialize for ScopeRef {
144 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
145 s.serialize_str(self.as_str())
146 }
147}
148
149impl<'de> Deserialize<'de> for ScopeRef {
150 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
151 let s = String::deserialize(d)?;
152 Ok(Self::parse(&s))
153 }
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
162pub enum GrantSet {
163 All,
165 Listed(BTreeSet<Grant>),
167}
168
169impl GrantSet {
170 pub fn contains(&self, grant: &Grant) -> bool {
172 match self {
173 Self::All => true,
174 Self::Listed(set) => set.contains(grant),
175 }
176 }
177
178 pub fn listed<I, G>(grants: I) -> Self
180 where
181 I: IntoIterator<Item = G>,
182 G: Into<String>,
183 {
184 Self::Listed(grants.into_iter().map(|g| Grant::new(g)).collect())
185 }
186}
187
188#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
191pub enum RoleOrGrant {
192 Role(RoleName),
193 Grant(Grant),
194}
195
196impl RoleOrGrant {
197 pub fn parse(text: &str) -> Self {
199 let t = text.trim();
200 if t.contains('.') {
201 Self::Grant(Grant::new(t))
202 } else {
203 Self::Role(RoleName::new(t))
204 }
205 }
206}
207
208impl fmt::Display for RoleOrGrant {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 match self {
211 Self::Role(r) => write!(f, "{r}"),
212 Self::Grant(g) => write!(f, "{g}"),
213 }
214 }
215}
216
217#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct Membership {
220 pub principal: Principal,
221 pub role: RoleName,
222 pub scope: ScopeRef,
223}
224
225#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
230pub struct Ceiling(pub Vec<(RoleOrGrant, ScopeRef)>);
231
232#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct CeilingError(pub String);
235
236impl fmt::Display for CeilingError {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 f.write_str(&self.0)
239 }
240}
241
242impl std::error::Error for CeilingError {}
243
244impl Ceiling {
245 pub fn entry(text: &str) -> Result<(RoleOrGrant, ScopeRef), CeilingError> {
247 let (left, scope) = text
248 .trim()
249 .split_once('@')
250 .ok_or_else(|| CeilingError(format!("`{}` is not role@SCOPE or grant@SCOPE", text.trim())))?;
251 if left.trim().is_empty() || scope.trim().is_empty() {
252 return Err(CeilingError(format!("`{}` is not role@SCOPE or grant@SCOPE", text.trim())));
253 }
254 Ok((RoleOrGrant::parse(left), ScopeRef::parse(scope)))
255 }
256
257 pub fn parse<I, S>(entries: I) -> Result<Self, CeilingError>
259 where
260 I: IntoIterator<Item = S>,
261 S: AsRef<str>,
262 {
263 entries
264 .into_iter()
265 .map(|e| Self::entry(e.as_ref()))
266 .collect::<Result<Vec<_>, _>>()
267 .map(Ceiling)
268 }
269
270 pub fn text(&self) -> Vec<String> {
272 self.0.iter().map(|(rg, s)| format!("{rg}@{s}")).collect()
273 }
274
275 pub fn layers_of(ctx: &AuthContext) -> Result<Vec<Ceiling>, CeilingError> {
280 let Some(v) = ctx.metadata.get(CEILING_KEY) else {
281 return Ok(Vec::new());
282 };
283 let unreadable = || CeilingError("this session's ceiling cannot be read: sign in again".into());
284 let items = v.as_array().ok_or_else(unreadable)?;
285 if items.iter().all(|i| i.is_string()) {
286 let texts: Vec<&str> = items.iter().filter_map(|i| i.as_str()).collect();
287 return Ok(vec![Self::parse(texts).map_err(|_| unreadable())?]);
288 }
289 items
290 .iter()
291 .map(|layer| {
292 let entries = layer.as_array().ok_or_else(unreadable)?;
293 let texts = entries
294 .iter()
295 .map(|e| e.as_str().ok_or_else(unreadable))
296 .collect::<Result<Vec<_>, _>>()?;
297 Self::parse(texts).map_err(|_| unreadable())
298 })
299 .collect()
300 }
301}
302
303#[derive(Debug, Clone, PartialEq, Eq, Hash)]
314pub struct Fingerprint {
315 held: Vec<(RoleName, ScopeRef)>,
317 layers: Vec<Ceiling>,
320}
321
322pub trait Memberships: Send + Sync {
329 fn held(&self, who: &Principal) -> Vec<Membership>;
330
331 fn own_held(&self, who: &Principal) -> Vec<Membership> {
337 self.held(who)
338 }
339}
340
341pub trait Roles: Send + Sync {
344 fn grants(&self, role: &RoleName) -> Option<GrantSet>;
347
348 fn names(&self) -> Vec<RoleName> {
352 Vec::new()
353 }
354}
355
356pub trait Resolve: Send + Sync {
358 fn chain(&self, target: &str) -> Option<Vec<ScopeRef>>;
370}
371
372#[derive(Debug, Clone, PartialEq, Eq)]
378pub enum RoleTableError {
379 UnknownRole { role: String, includes: String },
383}
384
385impl fmt::Display for RoleTableError {
386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387 match self {
388 Self::UnknownRole { role, includes } => write!(
389 f,
390 "role {role} includes {includes}, which is not defined before it"
391 ),
392 }
393 }
394}
395
396impl std::error::Error for RoleTableError {}
397
398#[derive(Debug, Clone, Default)]
413pub struct RoleTable {
414 roles: BTreeMap<RoleName, GrantSet>,
415}
416
417impl RoleTable {
418 pub fn new() -> Self {
420 Self::default()
421 }
422
423 pub fn define<I, S>(mut self, role: &str, entries: I) -> Result<Self, RoleTableError>
428 where
429 I: IntoIterator<Item = S>,
430 S: AsRef<str>,
431 {
432 let name = RoleName::new(role);
433 let mut set = match self.roles.remove(&name) {
434 Some(GrantSet::Listed(s)) => s,
435 Some(GrantSet::All) => {
436 self.roles.insert(name, GrantSet::All);
437 return Ok(self);
438 }
439 None => BTreeSet::new(),
440 };
441 let mut all = name.as_str() == ADMIN;
442 for entry in entries {
443 let e = entry.as_ref().trim();
444 if e.contains('.') {
445 set.insert(Grant::new(e));
446 continue;
447 }
448 if e == ADMIN {
449 all = true;
450 continue;
451 }
452 match self.roles.get(&RoleName::new(e)) {
453 Some(GrantSet::All) => all = true,
454 Some(GrantSet::Listed(inc)) => set.extend(inc.iter().cloned()),
455 None => {
456 return Err(RoleTableError::UnknownRole { role: role.to_string(), includes: e.to_string() })
457 }
458 }
459 }
460 self.roles.insert(name, if all { GrantSet::All } else { GrantSet::Listed(set) });
461 Ok(self)
462 }
463
464 pub fn set(&mut self, role: &str, grants: GrantSet) {
466 self.roles.insert(RoleName::new(role), grants);
467 }
468
469 pub fn from_lists<'a, I, G>(lists: I) -> Self
472 where
473 I: IntoIterator<Item = (&'a str, G)>,
474 G: IntoIterator,
475 G::Item: AsRef<str>,
476 {
477 let mut table = Self::new();
478 for (role, grants) in lists {
479 let name = RoleName::new(role);
480 let grants: Vec<Grant> = grants.into_iter().map(|g| Grant::new(g.as_ref().trim())).collect();
481 match table.roles.entry(name) {
482 std::collections::btree_map::Entry::Occupied(mut o) => {
483 if let GrantSet::Listed(s) = o.get_mut() {
484 s.extend(grants);
485 }
486 }
487 std::collections::btree_map::Entry::Vacant(v) => {
488 v.insert(if role == ADMIN { GrantSet::All } else { GrantSet::Listed(grants.into_iter().collect()) });
489 }
490 }
491 }
492 table
493 }
494}
495
496impl Roles for RoleTable {
497 fn grants(&self, role: &RoleName) -> Option<GrantSet> {
498 if role.as_str() == ADMIN {
499 return Some(GrantSet::All);
500 }
501 self.roles.get(role).cloned()
502 }
503
504 fn names(&self) -> Vec<RoleName> {
505 self.roles.keys().cloned().collect()
506 }
507}
508
509#[derive(Debug, Clone, PartialEq, Eq)]
515pub enum Refusal {
516 Unauthenticated,
518 MissingGrant {
520 grant: Grant,
522 scope: ScopeRef,
525 roles: Vec<RoleName>,
527 held_on: Vec<ScopeRef>,
529 },
530 Ended {
533 reason: String,
536 },
537}
538
539impl fmt::Display for Refusal {
540 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541 match self {
542 Self::Unauthenticated => f.write_str("sign in first"),
543 Self::Ended { reason } => f.write_str(reason),
544 Self::MissingGrant { grant, scope, .. } => write!(f, "needs {grant} on {scope}"),
545 }
546 }
547}
548
549impl std::error::Error for Refusal {}
550
551#[derive(Clone)]
565pub struct Reach {
566 held_on: Vec<ScopeRef>,
567 live: Option<Live>,
568}
569
570#[derive(Clone)]
571struct Live {
572 gate: Gate,
573 caller: Option<AuthContext>,
574 grant: Grant,
575}
576
577impl fmt::Debug for Reach {
578 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579 f.debug_struct("Reach")
580 .field("held_on", &self.held_on)
581 .field("grant", &self.live.as_ref().map(|l| l.grant.as_str()))
582 .finish()
583 }
584}
585
586impl PartialEq for Reach {
587 fn eq(&self, other: &Self) -> bool {
590 self.held_on == other.held_on && self.grant() == other.grant()
591 }
592}
593
594impl Reach {
595 pub fn everywhere() -> Self {
598 Self { held_on: vec![ScopeRef::Everywhere], live: None }
599 }
600
601 pub fn nowhere() -> Self {
605 Self { held_on: Vec::new(), live: None }
606 }
607
608 pub fn is_everywhere(&self) -> bool {
610 self.held_on.iter().any(ScopeRef::is_everywhere)
611 }
612
613 pub fn is_empty(&self) -> bool {
616 self.held_on.is_empty()
617 }
618
619 pub fn held_on(&self) -> &[ScopeRef] {
621 &self.held_on
622 }
623
624 pub fn grant(&self) -> Option<&Grant> {
626 self.live.as_ref().map(|l| &l.grant)
627 }
628
629 pub fn generation(&self) -> Option<&GrantsGeneration> {
634 self.live.as_ref().map(|l| l.gate.generation())
635 }
636
637 pub fn allows(&self, target: &str) -> bool {
640 match &self.live {
641 None => self.is_everywhere(),
642 Some(l) => l.gate.check(l.caller.as_ref(), &l.grant, Some(target)).is_ok(),
643 }
644 }
645
646 pub fn current(&self) -> Option<Reach> {
649 match &self.live {
650 None => Some(self.clone()),
651 Some(l) => l.gate.check(l.caller.as_ref(), &l.grant, None).ok(),
652 }
653 }
654
655 pub fn recheck(&self) -> Result<Reach, Refusal> {
664 match &self.live {
665 None => Ok(self.clone()),
666 Some(l) => l.gate.check(l.caller.as_ref(), &l.grant, None),
667 }
668 }
669
670 pub fn covers(&self, chain: &[ScopeRef]) -> bool {
674 self.is_everywhere() || self.held_on.iter().any(|s| chain.contains(s))
675 }
676}
677
678pub trait Liveness: Send + Sync {
688 fn alive(&self, caller: &AuthContext) -> Result<(), String>;
690}
691
692struct GateInner {
693 memberships: Arc<dyn Memberships>,
694 roles: Arc<dyn Roles>,
695 resolve: Arc<dyn Resolve>,
696 liveness: Option<Arc<dyn Liveness>>,
697 generation: GrantsGeneration,
698}
699
700#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
703pub enum GrantsMove {
704 Grant,
706 Revoke,
708 RoleEdit,
710 TeamAdd,
712 TeamRemove,
714 SignOut,
716}
717
718#[derive(Clone)]
730pub struct GrantsGeneration {
731 now: Arc<std::sync::atomic::AtomicU64>,
732 tx: Arc<tokio::sync::watch::Sender<u64>>,
733}
734
735impl fmt::Debug for GrantsGeneration {
736 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
737 f.debug_tuple("GrantsGeneration").field(&self.current()).finish()
738 }
739}
740
741impl Default for GrantsGeneration {
742 fn default() -> Self {
743 Self::new()
744 }
745}
746
747impl GrantsGeneration {
748 pub fn new() -> Self {
750 Self { now: Arc::new(std::sync::atomic::AtomicU64::new(0)), tx: Arc::new(tokio::sync::watch::channel(0).0) }
751 }
752
753 pub fn bump(&self) -> u64 {
756 let n = self.now.fetch_add(1, std::sync::atomic::Ordering::AcqRel) + 1;
757 self.tx.send_replace(n);
758 n
759 }
760
761 pub fn moved(&self, why: GrantsMove) -> u64 {
764 let _ = why;
765 self.bump()
766 }
767
768 pub fn current(&self) -> u64 {
770 self.now.load(std::sync::atomic::Ordering::Acquire)
771 }
772
773 pub fn raise_to(&self, n: u64) {
776 let was = self.now.fetch_max(n, std::sync::atomic::Ordering::AcqRel);
777 if n > was {
778 self.tx.send_replace(self.current());
779 }
780 }
781
782 pub fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
784 self.tx.subscribe()
785 }
786}
787
788#[derive(Clone)]
793pub struct Gate {
794 inner: Arc<GateInner>,
795}
796
797impl fmt::Debug for Gate {
798 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
799 f.write_str("Gate")
800 }
801}
802
803impl Gate {
804 pub fn new(memberships: Arc<dyn Memberships>, roles: Arc<dyn Roles>, resolve: Arc<dyn Resolve>) -> Self {
806 Self { inner: Arc::new(GateInner { memberships, roles, resolve, liveness: None, generation: GrantsGeneration::new() }) }
807 }
808
809 pub fn with_generation(self, generation: GrantsGeneration) -> Self {
813 let i = &self.inner;
814 Self {
815 inner: Arc::new(GateInner {
816 memberships: i.memberships.clone(),
817 roles: i.roles.clone(),
818 resolve: i.resolve.clone(),
819 liveness: i.liveness.clone(),
820 generation,
821 }),
822 }
823 }
824
825 pub fn generation(&self) -> &GrantsGeneration {
827 &self.inner.generation
828 }
829
830 pub fn moved(&self, why: GrantsMove) -> u64 {
834 self.inner.generation.moved(why)
835 }
836
837 pub fn with_liveness(self, liveness: Arc<dyn Liveness>) -> Self {
841 let i = &self.inner;
842 Self {
843 inner: Arc::new(GateInner {
844 memberships: i.memberships.clone(),
845 roles: i.roles.clone(),
846 resolve: i.resolve.clone(),
847 liveness: Some(liveness),
848 generation: i.generation.clone(),
849 }),
850 }
851 }
852
853 pub fn alive(&self, caller: &AuthContext) -> Result<(), String> {
857 if caller.principal().is_none() {
858 return Ok(());
859 }
860 if caller.expired() {
861 return Err("your sign-in has expired: sign in again".into());
862 }
863 match &self.inner.liveness {
864 Some(l) => l.alive(caller),
865 None => Ok(()),
866 }
867 }
868
869 pub fn lists(&self, role: &RoleName, grant: &Grant) -> bool {
871 role.as_str() == ADMIN || self.inner.roles.grants(role).is_some_and(|g| g.contains(grant))
872 }
873
874 pub fn roles_listing(&self, grant: &Grant) -> Vec<RoleName> {
876 let mut out: Vec<RoleName> = self
877 .inner
878 .roles
879 .names()
880 .into_iter()
881 .filter(|r| r.as_str() != ADMIN && self.lists(r, grant))
882 .collect();
883 out.push(RoleName::new(ADMIN));
884 out
885 }
886
887 fn entry_allows(&self, entry: &RoleOrGrant, grant: &Grant) -> bool {
889 match entry {
890 RoleOrGrant::Grant(g) => g == grant,
891 RoleOrGrant::Role(r) => self.lists(r, grant),
892 }
893 }
894
895 fn caller_of(caller: Option<&AuthContext>) -> Option<(Principal, Vec<Ceiling>)> {
898 let ctx = caller?;
899 let principal = ctx.principal()?;
900 let layers = Ceiling::layers_of(ctx).unwrap_or_else(|_| vec![Ceiling::default()]);
901 Some((principal, layers))
902 }
903
904 fn within(&self, inner: &ScopeRef, outer: &ScopeRef) -> bool {
906 if outer.is_everywhere() || inner == outer {
907 return true;
908 }
909 match inner {
910 ScopeRef::Everywhere => false,
911 ScopeRef::Named(name) => self.inner.resolve.chain(name).is_some_and(|c| c.contains(outer)),
912 }
913 }
914
915 fn meet(&self, a: Vec<ScopeRef>, b: Vec<ScopeRef>) -> Vec<ScopeRef> {
918 if a.iter().any(ScopeRef::is_everywhere) {
919 return b;
920 }
921 if b.iter().any(ScopeRef::is_everywhere) {
922 return a;
923 }
924 let mut out = BTreeSet::new();
925 for x in &a {
926 for y in &b {
927 if self.within(x, y) {
928 out.insert(x.clone());
929 } else if self.within(y, x) {
930 out.insert(y.clone());
931 }
932 }
933 }
934 out.into_iter().collect()
935 }
936
937 fn normal(scopes: impl IntoIterator<Item = ScopeRef>) -> Vec<ScopeRef> {
939 let set: BTreeSet<ScopeRef> = scopes.into_iter().collect();
940 if set.contains(&ScopeRef::Everywhere) {
941 vec![ScopeRef::Everywhere]
942 } else {
943 set.into_iter().collect()
944 }
945 }
946
947 fn held_on_for(&self, principal: &Principal, layers: &[Ceiling], grant: &Grant) -> Vec<ScopeRef> {
948 let held = self.inner.memberships.held(principal);
949 self.held_on_in(held.iter().map(|m| (&m.role, &m.scope)), layers, grant)
950 }
951
952 fn held_on_in<'a>(
956 &self,
957 held: impl Iterator<Item = (&'a RoleName, &'a ScopeRef)>,
958 layers: &[Ceiling],
959 grant: &Grant,
960 ) -> Vec<ScopeRef> {
961 let mut acc = Self::normal(held.filter(|(role, _)| self.lists(role, grant)).map(|(_, scope)| scope.clone()));
962 for layer in layers {
963 if acc.is_empty() {
964 break;
965 }
966 let allowed = Self::normal(
967 layer.0.iter().filter(|(rg, _)| self.entry_allows(rg, grant)).map(|(_, s)| s.clone()),
968 );
969 acc = self.meet(acc, allowed);
970 }
971 acc
972 }
973
974 pub fn held_on(&self, caller: &AuthContext, grant: &Grant) -> Vec<ScopeRef> {
978 match Self::caller_of(Some(caller)) {
979 Some((p, layers)) => self.held_on_for(&p, &layers, grant),
980 None => Vec::new(),
981 }
982 }
983
984 pub fn fingerprint(&self, caller: &AuthContext) -> Option<Fingerprint> {
989 let (principal, layers) = Self::caller_of(Some(caller))?;
990 let mut held: Vec<(RoleName, ScopeRef)> =
991 self.inner.memberships.held(&principal).into_iter().map(|m| (m.role, m.scope)).collect();
992 held.sort();
993 held.dedup();
994 Some(Fingerprint { held, layers })
995 }
996
997 pub fn held_on_by(&self, who: &Fingerprint, grant: &Grant) -> Vec<ScopeRef> {
1002 self.held_on_in(who.held.iter().map(|(r, s)| (r, s)), &who.layers, grant)
1003 }
1004
1005 pub fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<Reach, Refusal> {
1014 let Some((principal, layers)) = Self::caller_of(caller) else {
1015 return Err(Refusal::Unauthenticated);
1016 };
1017 if let Some(ctx) = caller {
1018 self.alive(ctx).map_err(|reason| Refusal::Ended { reason })?;
1019 }
1020 let held_on = self.held_on_for(&principal, &layers, grant);
1021 let (allowed, scope) = match target {
1022 None => (!held_on.is_empty(), ScopeRef::Everywhere),
1023 Some(t) => match self.inner.resolve.chain(t) {
1024 None => (false, ScopeRef::named(t)),
1025 Some(chain) => {
1026 let in_chain = |s: &ScopeRef| s.is_everywhere() || chain.contains(s);
1027 let by_membership = self
1028 .inner
1029 .memberships
1030 .held(&principal)
1031 .iter()
1032 .any(|m| in_chain(&m.scope) && self.lists(&m.role, grant));
1033 let by_ceiling = layers
1034 .iter()
1035 .all(|layer| layer.0.iter().any(|(rg, s)| in_chain(s) && self.entry_allows(rg, grant)));
1036 let scope = chain.first().cloned().unwrap_or_else(|| ScopeRef::named(t));
1037 (by_membership && by_ceiling, scope)
1038 }
1039 },
1040 };
1041 if allowed {
1042 Ok(Reach {
1043 held_on,
1044 live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone() }),
1045 })
1046 } else {
1047 Err(Refusal::MissingGrant { grant: grant.clone(), scope, roles: self.roles_listing(grant), held_on })
1048 }
1049 }
1050
1051 pub fn reach_of_public(&self, caller: Option<&AuthContext>, grant: &Grant) -> Reach {
1055 self.check(caller, grant, None).unwrap_or_else(|_| Reach {
1056 held_on: Vec::new(),
1057 live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone() }),
1058 })
1059 }
1060}
1061
1062#[cfg(test)]
1067mod tests {
1068 use super::*;
1069 use std::sync::Mutex;
1070
1071 const ADA: &str = "key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
1072 const BOB: &str = "key:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
1073
1074 #[derive(Default)]
1076 struct Members(Mutex<Vec<Membership>>);
1077 impl Members {
1078 fn grant(&self, who: &str, role: &str, scope: &str) {
1079 self.0.lock().unwrap().push(Membership {
1080 principal: who.parse().unwrap(),
1081 role: RoleName::new(role),
1082 scope: ScopeRef::parse(scope),
1083 });
1084 }
1085 fn revoke_all(&self) {
1086 self.0.lock().unwrap().clear();
1087 }
1088 }
1089 impl Memberships for Members {
1090 fn held(&self, who: &Principal) -> Vec<Membership> {
1091 self.0.lock().unwrap().iter().filter(|m| &m.principal == who).cloned().collect()
1092 }
1093 }
1094
1095 struct Shortcodes;
1098 impl Resolve for Shortcodes {
1099 fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
1100 let code = target.split_once('-').map(|(c, _)| c).unwrap_or(target);
1101 let mut chain = Vec::new();
1102 if target.contains('-') {
1103 chain.push(ScopeRef::named(target));
1104 }
1105 match code {
1106 "MENGER" | "IDENTITY" => {
1107 chain.push(ScopeRef::named(code));
1108 chain.push(ScopeRef::named("PLEXUS"));
1109 }
1110 "PLEXUS" => chain.push(ScopeRef::named("PLEXUS")),
1111 _ => return None,
1112 }
1113 chain.push(ScopeRef::Everywhere);
1114 Some(chain)
1115 }
1116 }
1117
1118 fn roles() -> RoleTable {
1119 RoleTable::new()
1120 .define("viewer", ["tickets.get", "tickets.list"])
1121 .unwrap()
1122 .define("editor", ["viewer", "tickets.set_status"])
1123 .unwrap()
1124 }
1125
1126 fn gate(members: &Arc<Members>) -> Gate {
1127 Gate::new(members.clone(), Arc::new(roles()), Arc::new(Shortcodes))
1128 }
1129
1130 fn who(p: &str) -> AuthContext {
1131 AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::Value::Null)
1132 }
1133
1134 fn with_ceiling(p: &str, ceiling: serde_json::Value) -> AuthContext {
1135 AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::json!({ CEILING_KEY: ceiling }))
1136 }
1137
1138 fn g(s: &str) -> Grant {
1139 Grant::new(s)
1140 }
1141
1142 #[test]
1143 fn a_grant_no_role_lists_is_refused_to_all_but_admin() {
1144 let m = Arc::new(Members::default());
1145 m.grant(ADA, "editor", "*");
1146 m.grant(BOB, "admin", "MENGER");
1147 let gate = gate(&m);
1148 let err = gate.check(Some(&who(ADA)), &g("members.grant"), Some("MENGER-1")).unwrap_err();
1149 assert_eq!(
1150 err,
1151 Refusal::MissingGrant {
1152 grant: g("members.grant"),
1153 scope: ScopeRef::named("MENGER-1"),
1154 roles: vec![RoleName::new("admin")],
1155 held_on: vec![],
1156 }
1157 );
1158 assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("MENGER-1")).is_ok());
1159 assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("IDENTITY-1")).is_err());
1161 }
1162
1163 #[test]
1164 fn held_on_a_scope_allows_targets_in_its_chain_only() {
1165 let m = Arc::new(Members::default());
1166 m.grant(ADA, "editor", "MENGER");
1167 let gate = gate(&m);
1168 let reach = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("MENGER-12")).unwrap();
1169 assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER")]);
1170 let err = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-1")).unwrap_err();
1171 assert_eq!(
1172 err,
1173 Refusal::MissingGrant {
1174 grant: g("tickets.set_status"),
1175 scope: ScopeRef::named("IDENTITY-1"),
1176 roles: vec![RoleName::new("editor"), RoleName::new("admin")],
1177 held_on: vec![ScopeRef::named("MENGER")],
1178 }
1179 );
1180 assert_eq!(err.to_string(), "needs tickets.set_status on IDENTITY-1");
1181 assert!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("NOPE-1")).is_err());
1183 }
1184
1185 #[test]
1186 fn held_on_everywhere_allows_any_target_and_reach_is_everywhere() {
1187 let m = Arc::new(Members::default());
1188 m.grant(ADA, "viewer", "*");
1189 m.grant(ADA, "viewer", "MENGER");
1190 let gate = gate(&m);
1191 let reach = gate.check(Some(&who(ADA)), &g("tickets.get"), Some("IDENTITY-3")).unwrap();
1192 assert!(reach.is_everywhere());
1193 assert_eq!(reach.held_on(), &[ScopeRef::Everywhere]);
1194 assert!(gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap().is_everywhere());
1195 assert!(gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-3")).is_err());
1197 }
1198
1199 #[test]
1200 fn without_a_target_held_anywhere_suffices_and_reach_says_where() {
1201 let m = Arc::new(Members::default());
1202 m.grant(ADA, "viewer", "MENGER");
1203 m.grant(ADA, "viewer", "IDENTITY");
1204 let gate = gate(&m);
1205 let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
1206 assert_eq!(reach.held_on(), &[ScopeRef::named("IDENTITY"), ScopeRef::named("MENGER")]);
1207 assert!(reach.allows("MENGER-4"));
1208 assert!(!reach.allows("PLEXUS-1"));
1209 let err = gate.check(Some(&who(BOB)), &g("tickets.list"), None).unwrap_err();
1210 assert!(matches!(err, Refusal::MissingGrant { ref scope, .. } if scope.is_everywhere()));
1211 }
1212
1213 #[test]
1214 fn a_ceiling_narrows_the_membership() {
1215 let m = Arc::new(Members::default());
1216 m.grant(ADA, "editor", "MENGER");
1217 let gate = gate(&m);
1218 let narrowed = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
1219 assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-12")).is_ok());
1220 assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-13")).is_err());
1221 let reach = gate.check(Some(&narrowed), &g("tickets.list"), None).unwrap();
1223 assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER-12")]);
1224 let only_get = with_ceiling(ADA, serde_json::json!([["tickets.get@*"]]));
1226 assert!(gate.check(Some(&only_get), &g("tickets.get"), Some("MENGER-1")).is_ok());
1227 let err = gate.check(Some(&only_get), &g("tickets.set_status"), Some("MENGER-1")).unwrap_err();
1228 assert!(matches!(err, Refusal::MissingGrant { ref held_on, .. } if held_on.is_empty()));
1229 let layered = with_ceiling(ADA, serde_json::json!([["editor@*"], ["viewer@MENGER"]]));
1231 assert!(gate.check(Some(&layered), &g("tickets.get"), Some("MENGER-1")).is_ok());
1232 assert!(gate.check(Some(&layered), &g("tickets.set_status"), Some("MENGER-1")).is_err());
1233 let wider = with_ceiling(ADA, serde_json::json!(["editor@IDENTITY"]));
1235 assert!(gate.check(Some(&wider), &g("tickets.get"), Some("IDENTITY-1")).is_err());
1236 let bad = with_ceiling(ADA, serde_json::json!("editor@*"));
1238 assert!(gate.check(Some(&bad), &g("tickets.get"), Some("MENGER-1")).is_err());
1239 }
1240
1241 #[test]
1242 fn role_inclusion_flattens_and_must_name_an_earlier_role() {
1243 let r = roles();
1244 let editor = r.grants(&RoleName::new("editor")).unwrap();
1245 assert!(editor.contains(&g("tickets.get")) && editor.contains(&g("tickets.set_status")));
1246 let viewer = r.grants(&RoleName::new("viewer")).unwrap();
1247 assert!(!viewer.contains(&g("tickets.set_status")));
1248 assert_eq!(
1249 RoleTable::new().define("editor", ["viewer"]).unwrap_err(),
1250 RoleTableError::UnknownRole { role: "editor".into(), includes: "viewer".into() }
1251 );
1252 assert_eq!(r.grants(&RoleName::new("admin")), Some(GrantSet::All));
1254 let merged = RoleTable::from_lists([("editor", vec!["tickets.get"]), ("editor", vec!["comments.add"])]);
1256 let e = merged.grants(&RoleName::new("editor")).unwrap();
1257 assert!(e.contains(&g("tickets.get")) && e.contains(&g("comments.add")));
1258 }
1259
1260 #[test]
1261 fn anonymous_is_unauthenticated() {
1262 let m = Arc::new(Members::default());
1263 let gate = gate(&m);
1264 assert_eq!(gate.check(None, &g("tickets.get"), Some("MENGER-1")).unwrap_err(), Refusal::Unauthenticated);
1265 assert_eq!(
1266 gate.check(Some(&AuthContext::anonymous()), &g("tickets.list"), None).unwrap_err(),
1267 Refusal::Unauthenticated
1268 );
1269 assert!(gate.reach_of_public(None, &g("auth.login")).is_empty());
1271 }
1272
1273 #[test]
1274 fn a_live_reach_follows_grants_as_they_stand() {
1275 let m = Arc::new(Members::default());
1276 m.grant(ADA, "viewer", "MENGER");
1277 let gate = gate(&m);
1278 let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
1279 assert!(reach.allows("MENGER-1"));
1280 assert!(reach.current().is_some());
1281 m.revoke_all();
1282 assert!(!reach.allows("MENGER-1"));
1283 assert!(reach.current().is_none());
1284 assert!(Reach::everywhere().allows("ANY-1") && Reach::everywhere().current().is_some());
1286 }
1287
1288 #[test]
1289 fn scope_refs_and_ceilings_round_trip() {
1290 assert_eq!(serde_json::to_string(&ScopeRef::Everywhere).unwrap(), "\"*\"");
1291 assert_eq!(serde_json::from_str::<ScopeRef>("\"MENGER\"").unwrap(), ScopeRef::named("MENGER"));
1292 let c = Ceiling::parse(["editor@MENGER-12", "tickets.get@*"]).unwrap();
1293 assert_eq!(c.0[0], (RoleOrGrant::Role(RoleName::new("editor")), ScopeRef::named("MENGER-12")));
1294 assert_eq!(c.0[1], (RoleOrGrant::Grant(g("tickets.get")), ScopeRef::Everywhere));
1295 assert_eq!(c.text(), vec!["editor@MENGER-12", "tickets.get@*"]);
1296 assert!(Ceiling::parse(["editor"]).is_err());
1297 }
1298
1299 #[derive(Default)]
1301 struct Switch(std::sync::atomic::AtomicBool);
1302 impl Liveness for Switch {
1303 fn alive(&self, _: &AuthContext) -> Result<(), String> {
1304 if self.0.load(std::sync::atomic::Ordering::SeqCst) {
1305 Err("you have signed out: sign in again".into())
1306 } else {
1307 Ok(())
1308 }
1309 }
1310 }
1311
1312 #[test]
1315 fn a_session_that_ended_holds_nothing() {
1316 let m = Arc::new(Members::default());
1317 m.grant(ADA, "admin", "*");
1318 let out = Arc::new(Switch::default());
1319 let gate = gate(&m).with_liveness(out.clone());
1320 let reach = gate.check(Some(&who(ADA)), &g("auth.grant"), None).expect("admin before sign-out");
1321 assert!(reach.allows("MENGER-1"));
1322 out.0.store(true, std::sync::atomic::Ordering::SeqCst);
1323 let ended = Refusal::Ended { reason: "you have signed out: sign in again".into() };
1324 assert_eq!(gate.check(Some(&who(ADA)), &g("auth.grant"), None).unwrap_err(), ended);
1325 assert_eq!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("MENGER-1")).unwrap_err(), ended);
1326 assert!(!reach.allows("MENGER-1"), "a stream's next event sees it");
1327 assert!(reach.current().is_none());
1328 assert!(gate.reach_of_public(Some(&who(ADA)), &g("auth.grant")).is_empty());
1329 assert_eq!(gate.check(None, &g("auth.grant"), None).unwrap_err(), Refusal::Unauthenticated);
1331 }
1332
1333 #[test]
1336 fn an_expired_sign_in_holds_nothing() {
1337 let m = Arc::new(Members::default());
1338 m.grant(ADA, "admin", "*");
1339 let gate = gate(&m);
1340 let past = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": 1 }));
1341 assert!(matches!(gate.check(Some(&past), &g("auth.grant"), None), Err(Refusal::Ended { .. })));
1342 let future = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": i64::MAX }));
1343 assert!(gate.check(Some(&future), &g("auth.grant"), None).is_ok());
1344 }
1345
1346 #[test]
1351 fn a_fingerprint_is_what_the_answers_read() {
1352 let m = Arc::new(Members::default());
1353 m.grant(ADA, "viewer", "IDENTITY");
1354 m.grant(ADA, "editor", "MENGER");
1355 m.grant(BOB, "editor", "MENGER");
1356 m.grant(BOB, "viewer", "IDENTITY");
1357 m.grant(BOB, "editor", "MENGER");
1358 let gate = gate(&m);
1359 let (ada, bob) = (gate.fingerprint(&who(ADA)).unwrap(), gate.fingerprint(&who(BOB)).unwrap());
1360 assert_eq!(ada, bob, "the same holdings, in another order and once more: one fingerprint");
1361 assert_eq!(gate.fingerprint(&AuthContext::anonymous()), None);
1362 let narrow = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
1363 let narrowed = gate.fingerprint(&narrow).unwrap();
1364 assert_ne!(narrowed, ada, "a ceiling: another fingerprint");
1365 let unreadable = gate.fingerprint(&with_ceiling(ADA, serde_json::json!("editor@*"))).unwrap();
1366 assert_ne!(unreadable, ada, "an unreadable ceiling allows nothing: not the unbounded caller's");
1367 for (ctx, fp) in [(&who(ADA), &ada), (&narrow, &narrowed), (&with_ceiling(ADA, serde_json::json!("editor@*")), &unreadable)] {
1368 for grant in ["tickets.get", "tickets.set_status", "tickets.delete", "members.grant"] {
1369 assert_eq!(gate.held_on_by(fp, &g(grant)), gate.held_on(ctx, &g(grant)), "{grant}");
1370 }
1371 }
1372 assert_eq!(gate.held_on_by(&narrowed, &g("tickets.get")), vec![ScopeRef::named("MENGER-12")]);
1373 m.revoke_all();
1374 assert_ne!(gate.fingerprint(&who(ADA)).unwrap(), ada, "a revoke: another fingerprint");
1375 }
1376}