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: std::borrow::Cow<'static, [ScopeRef]>,
569 live: Option<Live>,
570}
571
572#[derive(Clone)]
573struct Live {
574 gate: Gate,
575 caller: Option<AuthContext>,
576 grant: Grant,
577 everywhere: bool,
581}
582
583impl Live {
584 fn now(&self) -> Result<Reach, Refusal> {
586 match self.everywhere {
587 true => self.gate.check_everywhere(self.caller.as_ref(), &self.grant),
588 false => self.gate.check(self.caller.as_ref(), &self.grant, None),
589 }
590 }
591}
592
593impl fmt::Debug for Reach {
594 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
595 f.debug_struct("Reach")
596 .field("held_on", &self.held_on)
597 .field("grant", &self.live.as_ref().map(|l| l.grant.as_str()))
598 .finish()
599 }
600}
601
602impl PartialEq for Reach {
603 fn eq(&self, other: &Self) -> bool {
606 self.held_on == other.held_on && self.grant() == other.grant()
607 }
608}
609
610impl Reach {
611 pub fn everywhere() -> Self {
614 static EVERYWHERE: [ScopeRef; 1] = [ScopeRef::Everywhere];
615 Self { held_on: std::borrow::Cow::Borrowed(&EVERYWHERE), live: None }
616 }
617
618 pub fn nowhere() -> Self {
622 Self { held_on: std::borrow::Cow::Borrowed(&[]), live: None }
623 }
624
625 pub fn is_everywhere(&self) -> bool {
627 self.held_on.iter().any(ScopeRef::is_everywhere)
628 }
629
630 pub fn is_empty(&self) -> bool {
633 self.held_on.is_empty()
634 }
635
636 pub fn held_on(&self) -> &[ScopeRef] {
638 &self.held_on
639 }
640
641 pub fn caller(&self) -> Option<&AuthContext> {
647 self.live.as_ref().and_then(|l| l.caller.as_ref())
648 }
649
650 pub fn grant(&self) -> Option<&Grant> {
652 self.live.as_ref().map(|l| &l.grant)
653 }
654
655 pub fn generation(&self) -> Option<&GrantsGeneration> {
660 self.live.as_ref().map(|l| l.gate.generation())
661 }
662
663 pub fn allows(&self, target: &str) -> bool {
667 match &self.live {
668 None => self.is_everywhere(),
669 Some(l) if l.everywhere => l.now().is_ok(),
670 Some(l) => l.gate.check(l.caller.as_ref(), &l.grant, Some(target)).is_ok(),
671 }
672 }
673
674 pub fn current(&self) -> Option<Reach> {
677 match &self.live {
678 None => Some(self.clone()),
679 Some(l) => l.now().ok(),
680 }
681 }
682
683 pub fn recheck(&self) -> Result<Reach, Refusal> {
692 match &self.live {
693 None => Ok(self.clone()),
694 Some(l) => l.now(),
695 }
696 }
697
698 pub fn covers(&self, chain: &[ScopeRef]) -> bool {
702 self.is_everywhere() || self.held_on.iter().any(|s| chain.contains(s))
703 }
704}
705
706pub trait Liveness: Send + Sync {
716 fn alive(&self, caller: &AuthContext) -> Result<(), String>;
718}
719
720struct GateInner {
721 memberships: Arc<dyn Memberships>,
722 roles: Arc<dyn Roles>,
723 resolve: Arc<dyn Resolve>,
724 liveness: Option<Arc<dyn Liveness>>,
725 generation: GrantsGeneration,
726}
727
728#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
731pub enum GrantsMove {
732 Grant,
734 Revoke,
736 RoleEdit,
738 TeamAdd,
740 TeamRemove,
742 SignOut,
744}
745
746#[derive(Clone)]
758pub struct GrantsGeneration {
759 now: Arc<std::sync::atomic::AtomicU64>,
760 tx: Arc<tokio::sync::watch::Sender<u64>>,
761}
762
763impl fmt::Debug for GrantsGeneration {
764 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
765 f.debug_tuple("GrantsGeneration").field(&self.current()).finish()
766 }
767}
768
769impl Default for GrantsGeneration {
770 fn default() -> Self {
771 Self::new()
772 }
773}
774
775impl GrantsGeneration {
776 pub fn new() -> Self {
778 Self { now: Arc::new(std::sync::atomic::AtomicU64::new(0)), tx: Arc::new(tokio::sync::watch::channel(0).0) }
779 }
780
781 pub fn bump(&self) -> u64 {
784 let n = self.now.fetch_add(1, std::sync::atomic::Ordering::AcqRel) + 1;
785 self.tx.send_replace(n);
786 n
787 }
788
789 pub fn moved(&self, why: GrantsMove) -> u64 {
792 let _ = why;
793 self.bump()
794 }
795
796 pub fn current(&self) -> u64 {
798 self.now.load(std::sync::atomic::Ordering::Acquire)
799 }
800
801 pub fn raise_to(&self, n: u64) {
804 let was = self.now.fetch_max(n, std::sync::atomic::Ordering::AcqRel);
805 if n > was {
806 self.tx.send_replace(self.current());
807 }
808 }
809
810 pub fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
812 self.tx.subscribe()
813 }
814}
815
816#[derive(Clone)]
821pub struct Gate {
822 inner: Arc<GateInner>,
823}
824
825impl fmt::Debug for Gate {
826 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
827 f.write_str("Gate")
828 }
829}
830
831impl Gate {
832 pub fn new(memberships: Arc<dyn Memberships>, roles: Arc<dyn Roles>, resolve: Arc<dyn Resolve>) -> Self {
834 Self { inner: Arc::new(GateInner { memberships, roles, resolve, liveness: None, generation: GrantsGeneration::new() }) }
835 }
836
837 pub fn with_generation(self, generation: GrantsGeneration) -> 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: i.liveness.clone(),
848 generation,
849 }),
850 }
851 }
852
853 pub fn generation(&self) -> &GrantsGeneration {
855 &self.inner.generation
856 }
857
858 pub fn moved(&self, why: GrantsMove) -> u64 {
862 self.inner.generation.moved(why)
863 }
864
865 pub fn with_liveness(self, liveness: Arc<dyn Liveness>) -> Self {
869 let i = &self.inner;
870 Self {
871 inner: Arc::new(GateInner {
872 memberships: i.memberships.clone(),
873 roles: i.roles.clone(),
874 resolve: i.resolve.clone(),
875 liveness: Some(liveness),
876 generation: i.generation.clone(),
877 }),
878 }
879 }
880
881 pub fn alive(&self, caller: &AuthContext) -> Result<(), String> {
885 if caller.principal().is_none() {
886 return Ok(());
887 }
888 self.alive_named(caller)
889 }
890
891 fn alive_named(&self, caller: &AuthContext) -> Result<(), String> {
895 if caller.expired() {
896 return Err("your sign-in has expired: sign in again".into());
897 }
898 match &self.inner.liveness {
899 Some(l) => l.alive(caller),
900 None => Ok(()),
901 }
902 }
903
904 pub fn lists(&self, role: &RoleName, grant: &Grant) -> bool {
906 role.as_str() == ADMIN || self.inner.roles.grants(role).is_some_and(|g| g.contains(grant))
907 }
908
909 pub fn roles_listing(&self, grant: &Grant) -> Vec<RoleName> {
911 let mut out: Vec<RoleName> = self
912 .inner
913 .roles
914 .names()
915 .into_iter()
916 .filter(|r| r.as_str() != ADMIN && self.lists(r, grant))
917 .collect();
918 out.push(RoleName::new(ADMIN));
919 out
920 }
921
922 fn entry_allows(&self, entry: &RoleOrGrant, grant: &Grant) -> bool {
924 match entry {
925 RoleOrGrant::Grant(g) => g == grant,
926 RoleOrGrant::Role(r) => self.lists(r, grant),
927 }
928 }
929
930 fn caller_of(caller: Option<&AuthContext>) -> Option<(Principal, Vec<Ceiling>)> {
933 let ctx = caller?;
934 let principal = ctx.principal()?;
935 let layers = Ceiling::layers_of(ctx).unwrap_or_else(|_| vec![Ceiling::default()]);
936 Some((principal, layers))
937 }
938
939 fn within(&self, inner: &ScopeRef, outer: &ScopeRef) -> bool {
941 if outer.is_everywhere() || inner == outer {
942 return true;
943 }
944 match inner {
945 ScopeRef::Everywhere => false,
946 ScopeRef::Named(name) => self.inner.resolve.chain(name).is_some_and(|c| c.contains(outer)),
947 }
948 }
949
950 fn meet(&self, a: Vec<ScopeRef>, b: Vec<ScopeRef>) -> Vec<ScopeRef> {
953 if a.iter().any(ScopeRef::is_everywhere) {
954 return b;
955 }
956 if b.iter().any(ScopeRef::is_everywhere) {
957 return a;
958 }
959 let mut out = BTreeSet::new();
960 for x in &a {
961 for y in &b {
962 if self.within(x, y) {
963 out.insert(x.clone());
964 } else if self.within(y, x) {
965 out.insert(y.clone());
966 }
967 }
968 }
969 out.into_iter().collect()
970 }
971
972 fn normal(scopes: impl IntoIterator<Item = ScopeRef>) -> Vec<ScopeRef> {
974 let set: BTreeSet<ScopeRef> = scopes.into_iter().collect();
975 if set.contains(&ScopeRef::Everywhere) {
976 vec![ScopeRef::Everywhere]
977 } else {
978 set.into_iter().collect()
979 }
980 }
981
982 fn held_on_for(&self, principal: &Principal, layers: &[Ceiling], grant: &Grant) -> Vec<ScopeRef> {
983 let held = self.inner.memberships.held(principal);
984 self.held_on_in(held.iter().map(|m| (&m.role, &m.scope)), layers, grant)
985 }
986
987 fn held_on_in<'a>(
991 &self,
992 held: impl Iterator<Item = (&'a RoleName, &'a ScopeRef)>,
993 layers: &[Ceiling],
994 grant: &Grant,
995 ) -> Vec<ScopeRef> {
996 let mut acc = Self::normal(held.filter(|(role, _)| self.lists(role, grant)).map(|(_, scope)| scope.clone()));
997 for layer in layers {
998 if acc.is_empty() {
999 break;
1000 }
1001 let allowed = Self::normal(
1002 layer.0.iter().filter(|(rg, _)| self.entry_allows(rg, grant)).map(|(_, s)| s.clone()),
1003 );
1004 acc = self.meet(acc, allowed);
1005 }
1006 acc
1007 }
1008
1009 pub fn held_on(&self, caller: &AuthContext, grant: &Grant) -> Vec<ScopeRef> {
1013 match Self::caller_of(Some(caller)) {
1014 Some((p, layers)) => self.held_on_for(&p, &layers, grant),
1015 None => Vec::new(),
1016 }
1017 }
1018
1019 pub fn fingerprint(&self, caller: &AuthContext) -> Option<Fingerprint> {
1024 let (principal, layers) = Self::caller_of(Some(caller))?;
1025 let mut held: Vec<(RoleName, ScopeRef)> =
1026 self.inner.memberships.held(&principal).into_iter().map(|m| (m.role, m.scope)).collect();
1027 held.sort();
1028 held.dedup();
1029 Some(Fingerprint { held, layers })
1030 }
1031
1032 pub fn held_on_by(&self, who: &Fingerprint, grant: &Grant) -> Vec<ScopeRef> {
1037 self.held_on_in(who.held.iter().map(|(r, s)| (r, s)), &who.layers, grant)
1038 }
1039
1040 pub fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<Reach, Refusal> {
1049 let Some((principal, layers)) = Self::caller_of(caller) else {
1050 return Err(Refusal::Unauthenticated);
1051 };
1052 if let Some(ctx) = caller {
1053 self.alive_named(ctx).map_err(|reason| Refusal::Ended { reason })?;
1054 }
1055 let held_on = self.held_on_for(&principal, &layers, grant);
1056 let (allowed, scope) = match target {
1057 None => (!held_on.is_empty(), ScopeRef::Everywhere),
1058 Some(t) => match self.inner.resolve.chain(t) {
1059 None => (false, ScopeRef::named(t)),
1060 Some(chain) => {
1061 let in_chain = |s: &ScopeRef| s.is_everywhere() || chain.contains(s);
1062 let by_membership = self
1063 .inner
1064 .memberships
1065 .held(&principal)
1066 .iter()
1067 .any(|m| in_chain(&m.scope) && self.lists(&m.role, grant));
1068 let by_ceiling = layers
1069 .iter()
1070 .all(|layer| layer.0.iter().any(|(rg, s)| in_chain(s) && self.entry_allows(rg, grant)));
1071 let scope = chain.first().cloned().unwrap_or_else(|| ScopeRef::named(t));
1072 (by_membership && by_ceiling, scope)
1073 }
1074 },
1075 };
1076 if allowed {
1077 Ok(Reach {
1078 held_on: held_on.into(),
1079 live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone(), everywhere: false }),
1080 })
1081 } else {
1082 Err(Refusal::MissingGrant { grant: grant.clone(), scope, roles: self.roles_listing(grant), held_on })
1083 }
1084 }
1085
1086 pub fn check_everywhere(&self, caller: Option<&AuthContext>, grant: &Grant) -> Result<Reach, Refusal> {
1094 let reach = match self.check(caller, grant, None) {
1095 Ok(reach) => reach,
1096 Err(Refusal::MissingGrant { grant, roles, held_on, .. }) => {
1097 return Err(Refusal::MissingGrant { grant, scope: ScopeRef::Everywhere, roles, held_on })
1098 }
1099 Err(other) => return Err(other),
1100 };
1101 if !reach.is_everywhere() {
1102 return Err(Refusal::MissingGrant {
1103 grant: grant.clone(),
1104 scope: ScopeRef::Everywhere,
1105 roles: self.roles_listing(grant),
1106 held_on: reach.held_on.into_owned(),
1107 });
1108 }
1109 let live = reach.live.map(|live| Live { everywhere: true, ..live });
1112 Ok(Reach { held_on: reach.held_on, live })
1113 }
1114
1115 pub fn reach_of_public(&self, caller: Option<&AuthContext>, grant: &Grant) -> Reach {
1119 self.check(caller, grant, None).unwrap_or_else(|_| Reach {
1120 held_on: std::borrow::Cow::Borrowed(&[]),
1121 live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone(), everywhere: false }),
1122 })
1123 }
1124}
1125
1126#[cfg(test)]
1131mod tests {
1132 use super::*;
1133 use std::sync::Mutex;
1134
1135 const ADA: &str = "key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
1136 const BOB: &str = "key:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
1137
1138 #[derive(Default)]
1140 struct Members(Mutex<Vec<Membership>>);
1141 impl Members {
1142 fn grant(&self, who: &str, role: &str, scope: &str) {
1143 self.0.lock().unwrap().push(Membership {
1144 principal: who.parse().unwrap(),
1145 role: RoleName::new(role),
1146 scope: ScopeRef::parse(scope),
1147 });
1148 }
1149 fn revoke_all(&self) {
1150 self.0.lock().unwrap().clear();
1151 }
1152 }
1153 impl Memberships for Members {
1154 fn held(&self, who: &Principal) -> Vec<Membership> {
1155 self.0.lock().unwrap().iter().filter(|m| &m.principal == who).cloned().collect()
1156 }
1157 }
1158
1159 struct Shortcodes;
1162 impl Resolve for Shortcodes {
1163 fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
1164 let code = target.split_once('-').map(|(c, _)| c).unwrap_or(target);
1165 let mut chain = Vec::new();
1166 if target.contains('-') {
1167 chain.push(ScopeRef::named(target));
1168 }
1169 match code {
1170 "MENGER" | "IDENTITY" => {
1171 chain.push(ScopeRef::named(code));
1172 chain.push(ScopeRef::named("PLEXUS"));
1173 }
1174 "PLEXUS" => chain.push(ScopeRef::named("PLEXUS")),
1175 _ => return None,
1176 }
1177 chain.push(ScopeRef::Everywhere);
1178 Some(chain)
1179 }
1180 }
1181
1182 fn roles() -> RoleTable {
1183 RoleTable::new()
1184 .define("viewer", ["tickets.get", "tickets.list"])
1185 .unwrap()
1186 .define("editor", ["viewer", "tickets.set_status"])
1187 .unwrap()
1188 }
1189
1190 fn gate(members: &Arc<Members>) -> Gate {
1191 Gate::new(members.clone(), Arc::new(roles()), Arc::new(Shortcodes))
1192 }
1193
1194 fn who(p: &str) -> AuthContext {
1195 AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::Value::Null)
1196 }
1197
1198 fn with_ceiling(p: &str, ceiling: serde_json::Value) -> AuthContext {
1199 AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::json!({ CEILING_KEY: ceiling }))
1200 }
1201
1202 fn g(s: &str) -> Grant {
1203 Grant::new(s)
1204 }
1205
1206 #[test]
1207 fn a_grant_no_role_lists_is_refused_to_all_but_admin() {
1208 let m = Arc::new(Members::default());
1209 m.grant(ADA, "editor", "*");
1210 m.grant(BOB, "admin", "MENGER");
1211 let gate = gate(&m);
1212 let err = gate.check(Some(&who(ADA)), &g("members.grant"), Some("MENGER-1")).unwrap_err();
1213 assert_eq!(
1214 err,
1215 Refusal::MissingGrant {
1216 grant: g("members.grant"),
1217 scope: ScopeRef::named("MENGER-1"),
1218 roles: vec![RoleName::new("admin")],
1219 held_on: vec![],
1220 }
1221 );
1222 assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("MENGER-1")).is_ok());
1223 assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("IDENTITY-1")).is_err());
1225 }
1226
1227 #[test]
1228 fn held_on_a_scope_allows_targets_in_its_chain_only() {
1229 let m = Arc::new(Members::default());
1230 m.grant(ADA, "editor", "MENGER");
1231 let gate = gate(&m);
1232 let reach = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("MENGER-12")).unwrap();
1233 assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER")]);
1234 let err = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-1")).unwrap_err();
1235 assert_eq!(
1236 err,
1237 Refusal::MissingGrant {
1238 grant: g("tickets.set_status"),
1239 scope: ScopeRef::named("IDENTITY-1"),
1240 roles: vec![RoleName::new("editor"), RoleName::new("admin")],
1241 held_on: vec![ScopeRef::named("MENGER")],
1242 }
1243 );
1244 assert_eq!(err.to_string(), "needs tickets.set_status on IDENTITY-1");
1245 assert!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("NOPE-1")).is_err());
1247 }
1248
1249 #[test]
1250 fn held_on_everywhere_allows_any_target_and_reach_is_everywhere() {
1251 let m = Arc::new(Members::default());
1252 m.grant(ADA, "viewer", "*");
1253 m.grant(ADA, "viewer", "MENGER");
1254 let gate = gate(&m);
1255 let reach = gate.check(Some(&who(ADA)), &g("tickets.get"), Some("IDENTITY-3")).unwrap();
1256 assert!(reach.is_everywhere());
1257 assert_eq!(reach.held_on(), &[ScopeRef::Everywhere]);
1258 assert!(gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap().is_everywhere());
1259 assert!(gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-3")).is_err());
1261 }
1262
1263 #[test]
1264 fn without_a_target_held_anywhere_suffices_and_reach_says_where() {
1265 let m = Arc::new(Members::default());
1266 m.grant(ADA, "viewer", "MENGER");
1267 m.grant(ADA, "viewer", "IDENTITY");
1268 let gate = gate(&m);
1269 let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
1270 assert_eq!(reach.held_on(), &[ScopeRef::named("IDENTITY"), ScopeRef::named("MENGER")]);
1271 assert!(reach.allows("MENGER-4"));
1272 assert!(!reach.allows("PLEXUS-1"));
1273 let err = gate.check(Some(&who(BOB)), &g("tickets.list"), None).unwrap_err();
1274 assert!(matches!(err, Refusal::MissingGrant { ref scope, .. } if scope.is_everywhere()));
1275 }
1276
1277 #[test]
1278 fn a_ceiling_narrows_the_membership() {
1279 let m = Arc::new(Members::default());
1280 m.grant(ADA, "editor", "MENGER");
1281 let gate = gate(&m);
1282 let narrowed = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
1283 assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-12")).is_ok());
1284 assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-13")).is_err());
1285 let reach = gate.check(Some(&narrowed), &g("tickets.list"), None).unwrap();
1287 assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER-12")]);
1288 let only_get = with_ceiling(ADA, serde_json::json!([["tickets.get@*"]]));
1290 assert!(gate.check(Some(&only_get), &g("tickets.get"), Some("MENGER-1")).is_ok());
1291 let err = gate.check(Some(&only_get), &g("tickets.set_status"), Some("MENGER-1")).unwrap_err();
1292 assert!(matches!(err, Refusal::MissingGrant { ref held_on, .. } if held_on.is_empty()));
1293 let layered = with_ceiling(ADA, serde_json::json!([["editor@*"], ["viewer@MENGER"]]));
1295 assert!(gate.check(Some(&layered), &g("tickets.get"), Some("MENGER-1")).is_ok());
1296 assert!(gate.check(Some(&layered), &g("tickets.set_status"), Some("MENGER-1")).is_err());
1297 let wider = with_ceiling(ADA, serde_json::json!(["editor@IDENTITY"]));
1299 assert!(gate.check(Some(&wider), &g("tickets.get"), Some("IDENTITY-1")).is_err());
1300 let bad = with_ceiling(ADA, serde_json::json!("editor@*"));
1302 assert!(gate.check(Some(&bad), &g("tickets.get"), Some("MENGER-1")).is_err());
1303 }
1304
1305 #[test]
1306 fn role_inclusion_flattens_and_must_name_an_earlier_role() {
1307 let r = roles();
1308 let editor = r.grants(&RoleName::new("editor")).unwrap();
1309 assert!(editor.contains(&g("tickets.get")) && editor.contains(&g("tickets.set_status")));
1310 let viewer = r.grants(&RoleName::new("viewer")).unwrap();
1311 assert!(!viewer.contains(&g("tickets.set_status")));
1312 assert_eq!(
1313 RoleTable::new().define("editor", ["viewer"]).unwrap_err(),
1314 RoleTableError::UnknownRole { role: "editor".into(), includes: "viewer".into() }
1315 );
1316 assert_eq!(r.grants(&RoleName::new("admin")), Some(GrantSet::All));
1318 let merged = RoleTable::from_lists([("editor", vec!["tickets.get"]), ("editor", vec!["comments.add"])]);
1320 let e = merged.grants(&RoleName::new("editor")).unwrap();
1321 assert!(e.contains(&g("tickets.get")) && e.contains(&g("comments.add")));
1322 }
1323
1324 #[test]
1325 fn anonymous_is_unauthenticated() {
1326 let m = Arc::new(Members::default());
1327 let gate = gate(&m);
1328 assert_eq!(gate.check(None, &g("tickets.get"), Some("MENGER-1")).unwrap_err(), Refusal::Unauthenticated);
1329 assert_eq!(
1330 gate.check(Some(&AuthContext::anonymous()), &g("tickets.list"), None).unwrap_err(),
1331 Refusal::Unauthenticated
1332 );
1333 assert!(gate.reach_of_public(None, &g("auth.login")).is_empty());
1335 }
1336
1337 #[test]
1338 fn a_live_reach_follows_grants_as_they_stand() {
1339 let m = Arc::new(Members::default());
1340 m.grant(ADA, "viewer", "MENGER");
1341 let gate = gate(&m);
1342 let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
1343 assert!(reach.allows("MENGER-1"));
1344 assert!(reach.current().is_some());
1345 m.revoke_all();
1346 assert!(!reach.allows("MENGER-1"));
1347 assert!(reach.current().is_none());
1348 assert!(Reach::everywhere().allows("ANY-1") && Reach::everywhere().current().is_some());
1350 }
1351
1352 #[test]
1353 fn scope_refs_and_ceilings_round_trip() {
1354 assert_eq!(serde_json::to_string(&ScopeRef::Everywhere).unwrap(), "\"*\"");
1355 assert_eq!(serde_json::from_str::<ScopeRef>("\"MENGER\"").unwrap(), ScopeRef::named("MENGER"));
1356 let c = Ceiling::parse(["editor@MENGER-12", "tickets.get@*"]).unwrap();
1357 assert_eq!(c.0[0], (RoleOrGrant::Role(RoleName::new("editor")), ScopeRef::named("MENGER-12")));
1358 assert_eq!(c.0[1], (RoleOrGrant::Grant(g("tickets.get")), ScopeRef::Everywhere));
1359 assert_eq!(c.text(), vec!["editor@MENGER-12", "tickets.get@*"]);
1360 assert!(Ceiling::parse(["editor"]).is_err());
1361 }
1362
1363 #[derive(Default)]
1365 struct Switch(std::sync::atomic::AtomicBool);
1366 impl Liveness for Switch {
1367 fn alive(&self, _: &AuthContext) -> Result<(), String> {
1368 if self.0.load(std::sync::atomic::Ordering::SeqCst) {
1369 Err("you have signed out: sign in again".into())
1370 } else {
1371 Ok(())
1372 }
1373 }
1374 }
1375
1376 #[test]
1379 fn a_session_that_ended_holds_nothing() {
1380 let m = Arc::new(Members::default());
1381 m.grant(ADA, "admin", "*");
1382 let out = Arc::new(Switch::default());
1383 let gate = gate(&m).with_liveness(out.clone());
1384 let reach = gate.check(Some(&who(ADA)), &g("auth.grant"), None).expect("admin before sign-out");
1385 assert!(reach.allows("MENGER-1"));
1386 out.0.store(true, std::sync::atomic::Ordering::SeqCst);
1387 let ended = Refusal::Ended { reason: "you have signed out: sign in again".into() };
1388 assert_eq!(gate.check(Some(&who(ADA)), &g("auth.grant"), None).unwrap_err(), ended);
1389 assert_eq!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("MENGER-1")).unwrap_err(), ended);
1390 assert!(!reach.allows("MENGER-1"), "a stream's next event sees it");
1391 assert!(reach.current().is_none());
1392 assert!(gate.reach_of_public(Some(&who(ADA)), &g("auth.grant")).is_empty());
1393 assert_eq!(gate.check(None, &g("auth.grant"), None).unwrap_err(), Refusal::Unauthenticated);
1395 }
1396
1397 #[test]
1400 fn an_expired_sign_in_holds_nothing() {
1401 let m = Arc::new(Members::default());
1402 m.grant(ADA, "admin", "*");
1403 let gate = gate(&m);
1404 let past = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": 1 }));
1405 assert!(matches!(gate.check(Some(&past), &g("auth.grant"), None), Err(Refusal::Ended { .. })));
1406 let future = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": i64::MAX }));
1407 assert!(gate.check(Some(&future), &g("auth.grant"), None).is_ok());
1408 }
1409
1410 #[test]
1415 fn a_fingerprint_is_what_the_answers_read() {
1416 let m = Arc::new(Members::default());
1417 m.grant(ADA, "viewer", "IDENTITY");
1418 m.grant(ADA, "editor", "MENGER");
1419 m.grant(BOB, "editor", "MENGER");
1420 m.grant(BOB, "viewer", "IDENTITY");
1421 m.grant(BOB, "editor", "MENGER");
1422 let gate = gate(&m);
1423 let (ada, bob) = (gate.fingerprint(&who(ADA)).unwrap(), gate.fingerprint(&who(BOB)).unwrap());
1424 assert_eq!(ada, bob, "the same holdings, in another order and once more: one fingerprint");
1425 assert_eq!(gate.fingerprint(&AuthContext::anonymous()), None);
1426 let narrow = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
1427 let narrowed = gate.fingerprint(&narrow).unwrap();
1428 assert_ne!(narrowed, ada, "a ceiling: another fingerprint");
1429 let unreadable = gate.fingerprint(&with_ceiling(ADA, serde_json::json!("editor@*"))).unwrap();
1430 assert_ne!(unreadable, ada, "an unreadable ceiling allows nothing: not the unbounded caller's");
1431 for (ctx, fp) in [(&who(ADA), &ada), (&narrow, &narrowed), (&with_ceiling(ADA, serde_json::json!("editor@*")), &unreadable)] {
1432 for grant in ["tickets.get", "tickets.set_status", "tickets.delete", "members.grant"] {
1433 assert_eq!(gate.held_on_by(fp, &g(grant)), gate.held_on(ctx, &g(grant)), "{grant}");
1434 }
1435 }
1436 assert_eq!(gate.held_on_by(&narrowed, &g("tickets.get")), vec![ScopeRef::named("MENGER-12")]);
1437 m.revoke_all();
1438 assert_ne!(gate.fingerprint(&who(ADA)).unwrap(), ada, "a revoke: another fingerprint");
1439 }
1440
1441 #[test]
1447 fn a_whole_service_method_needs_its_grant_on_everywhere() {
1448 let m = Arc::new(Members::default());
1449 m.grant(ADA, "admin", "MENGER-5");
1450 m.grant(BOB, "admin", "*");
1451 let gate = gate(&m);
1452 let grow = g("dyn.grow");
1453 assert_eq!(gate.check(Some(&who(ADA)), &grow, None).unwrap().held_on(), [ScopeRef::named("MENGER-5")]);
1454 match gate.check_everywhere(Some(&who(ADA)), &grow) {
1455 Err(Refusal::MissingGrant { scope, held_on, .. }) => {
1456 assert_eq!(scope, ScopeRef::Everywhere);
1457 assert_eq!(held_on, [ScopeRef::named("MENGER-5")]);
1458 }
1459 other => panic!("a scoped admin: {other:?}"),
1460 }
1461 let reach = gate.check_everywhere(Some(&who(BOB)), &grow).unwrap();
1462 assert!(reach.is_everywhere());
1463 for ceiling in [serde_json::json!(["admin@MENGER-5"]), serde_json::json!(["viewer@*"]), serde_json::json!("admin@*")] {
1464 let capped = with_ceiling(BOB, ceiling.clone());
1465 assert!(gate.check_everywhere(Some(&capped), &grow).is_err(), "ceiling {ceiling}");
1466 }
1467 assert!(gate.check_everywhere(Some(&with_ceiling(BOB, serde_json::json!(["dyn.grow@*"]))), &grow).is_ok());
1468 assert!(gate.check_everywhere(Some(&with_ceiling(ADA, serde_json::json!(["admin@*"]))), &grow).is_err(), "a ceiling never widens");
1469 assert_eq!(gate.check_everywhere(None, &grow).err(), Some(Refusal::Unauthenticated));
1470 m.revoke_all();
1472 m.grant(BOB, "admin", "MENGER");
1473 assert!(reach.current().is_none());
1474 assert!(reach.recheck().is_err());
1475 assert!(!reach.allows("MENGER-1"));
1476 }
1477}