Skip to main content

plexus_auth_core/
grants.rs

1//! AUTH-2: **grants, roles, memberships, ceilings — and the gate** that asks
2//! them on every call.
3//!
4//! The model (AUTH-1, owner 2026-10-10: "every method should be its own grant
5//! inherently and require a role to have it explicitly listed if not admin
6//! role"):
7//!
8//! - A [`Grant`] is the right to call one method: `<activation>.<method>`
9//!   (`tickets.set_status`). Inherent — every method has exactly one and
10//!   nothing declares it.
11//! - A role is a named, explicit list of grants ([`GrantSet::Listed`]); the
12//!   built-in [`ADMIN`] role alone holds every grant ([`GrantSet::All`]).
13//!   [`RoleTable`] is an in-memory [`Roles`] in which a role may list
14//!   another role (inclusion), flattened as it is defined.
15//! - A [`Membership`] says a principal holds a role on a scope
16//!   ([`ScopeRef::Named`]) or everywhere ([`ScopeRef::Everywhere`], `*`).
17//! - A *target* is the param that locates the resource a call acts on; the
18//!   service's [`Resolve`] maps its value to the scopes it lives in,
19//!   innermost first (`MENGER-12` → `[MENGER, *]`).
20//! - A [`Ceiling`] is a session's upper bound (IDENTITY-40): `role@SCOPE` or
21//!   `grant@SCOPE` entries. A session may carry several layers; every layer
22//!   must allow a check, as the memberships must.
23//!
24//! [`Gate::check`] answers one call: allowed — with the [`Reach`] the method
25//! answers from — or a [`Refusal`] that names what was needed. Everything is
26//! answered from memory: the three service traits are synchronous and must
27//! not do I/O.
28//!
29//! # Relation to R-5's [`ScopeRegistry`](crate::ScopeRegistry)
30//!
31//! R-5's registry maps *token-claimed roles* to dotted capability scopes and
32//! knows nothing of where a role is held. The grant model keeps its words —
33//! a grant is exactly R-5's implicit `<activation>.<method>` scope, and
34//! [`RoleName`] is the same type — and adds the *where*: memberships on
35//! scopes, targets resolved through a chain, ceilings. Both gates can be
36//! configured on one hub; a hub with neither dispatches as before.
37
38use 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
48/// The built-in role that holds every grant. No other role holds anything it
49/// does not list.
50pub const ADMIN: &str = "admin";
51
52/// The metadata key a session's ceiling rides under (IDENTITY-42's
53/// `menger_session` sessions write it): either a list of `role@SCOPE` /
54/// `grant@SCOPE` strings (one layer) or a list of such lists (layers, every
55/// one of which must allow a check).
56pub const CEILING_KEY: &str = "ceiling";
57
58// ---------------------------------------------------------------------------
59// Grant
60// ---------------------------------------------------------------------------
61
62/// The right to call one method: `<activation>.<method>`, e.g.
63/// `tickets.set_status`. Every method has exactly one; nothing declares it.
64#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
65#[serde(transparent)]
66pub struct Grant(String);
67
68impl Grant {
69    /// Wrap a dotted method path as a grant. Unvalidated, as wire-decoded
70    /// values are.
71    pub fn new(path: impl Into<String>) -> Self {
72        Self(path.into())
73    }
74
75    /// The grant of `method` on `activation`: `<activation>.<method>`.
76    pub fn of(activation: &str, method: &str) -> Self {
77        Self(format!("{activation}.{method}"))
78    }
79
80    /// The dotted path.
81    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// ---------------------------------------------------------------------------
93// ScopeRef
94// ---------------------------------------------------------------------------
95
96/// Where a role is held: everywhere (`*`) or one named scope (`MENGER`).
97/// What a name means — a shortcode, a tenant, a project — is the service's;
98/// the gate only compares names and asks [`Resolve::chain`] how they nest.
99///
100/// On the wire, a plain string: `"*"` or the name.
101#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
102pub enum ScopeRef {
103    /// `*`: every scope.
104    Everywhere,
105    /// One named scope, and whatever the service nests under it.
106    Named(String),
107}
108
109impl ScopeRef {
110    /// `"*"` → [`ScopeRef::Everywhere`]; anything else (trimmed) → named.
111    pub fn parse(text: &str) -> Self {
112        match text.trim() {
113            "*" => Self::Everywhere,
114            other => Self::Named(other.to_string()),
115        }
116    }
117
118    /// A named scope.
119    pub fn named(name: impl Into<String>) -> Self {
120        Self::Named(name.into())
121    }
122
123    /// `"*"` or the name.
124    pub fn as_str(&self) -> &str {
125        match self {
126            Self::Everywhere => "*",
127            Self::Named(n) => n,
128        }
129    }
130
131    /// Whether this is `*`.
132    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// ---------------------------------------------------------------------------
157// GrantSet, RoleOrGrant, Membership, Ceiling
158// ---------------------------------------------------------------------------
159
160/// What a role holds: every grant ([`ADMIN`]) or exactly those it lists.
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub enum GrantSet {
163    /// Every grant — the admin role, and only it by default.
164    All,
165    /// Exactly these grants.
166    Listed(BTreeSet<Grant>),
167}
168
169impl GrantSet {
170    /// Whether the set holds `grant`.
171    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    /// A listed set from anything that names grants.
179    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/// One ceiling entry's left side: a role (`editor`) or a single grant
189/// (`tickets.get`). A dotted name is a grant; a bare one is a role.
190#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
191pub enum RoleOrGrant {
192    Role(RoleName),
193    Grant(Grant),
194}
195
196impl RoleOrGrant {
197    /// A dotted name is a grant, a bare one a role.
198    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/// A principal holds a role on a scope: `key:ac79… is editor on MENGER`.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct Membership {
220    pub principal: Principal,
221    pub role: RoleName,
222    pub scope: ScopeRef,
223}
224
225/// A session's upper bound (IDENTITY-40): `(role or grant, scope)` entries,
226/// spelled `editor@MENGER-12`, `tickets.get@*`. A check passes a ceiling
227/// when some entry's scope is in the target's chain and the entry allows the
228/// grant (the grant itself, or a role listing it).
229#[derive(Debug, Clone, PartialEq, Eq, Default)]
230pub struct Ceiling(pub Vec<(RoleOrGrant, ScopeRef)>);
231
232/// Why a ceiling could not be read.
233#[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    /// One `role@SCOPE` or `grant@SCOPE` entry.
246    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    /// A ceiling from its entries' text.
258    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    /// The entries as the wire says them: `role@SCOPE` each.
271    pub fn text(&self) -> Vec<String> {
272        self.0.iter().map(|(rg, s)| format!("{rg}@{s}")).collect()
273    }
274
275    /// The ceilings an identity's metadata carries under [`CEILING_KEY`]:
276    /// none → `[]`; a list of strings → one layer; a list of lists → one
277    /// layer each. Anything else is an error, and a caller whose ceiling
278    /// cannot be read must be refused, never widened.
279    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// ---------------------------------------------------------------------------
304// What a service supplies
305// ---------------------------------------------------------------------------
306
307/// Who holds which role where (menger: its members table, cached). Answered
308/// from memory: no I/O on a call.
309pub trait Memberships: Send + Sync {
310    fn held(&self, who: &Principal) -> Vec<Membership>;
311}
312
313/// Role → grants (defaults declared in code, edits as data). Answered from
314/// memory. [`ADMIN`] holds every grant whatever this answers.
315pub trait Roles: Send + Sync {
316    /// What `role` holds; `None` for a role this service does not know
317    /// (it holds nothing).
318    fn grants(&self, role: &RoleName) -> Option<GrantSet>;
319
320    /// Every role this service knows, so a refusal can name the roles that
321    /// list a grant. The default knows none (a refusal then names only
322    /// [`ADMIN`]).
323    fn names(&self) -> Vec<RoleName> {
324        Vec::new()
325    }
326}
327
328/// Where a target lives. Answered from memory.
329pub trait Resolve: Send + Sync {
330    /// The scopes a target lives in, innermost first, ending in
331    /// [`ScopeRef::Everywhere`]: `"MENGER-12"` → `[MENGER-12, MENGER, *]`
332    /// (or, for a service whose memberships are per shortcode,
333    /// `[MENGER, *]`). `None`: the value locates nothing — the call is
334    /// refused.
335    ///
336    /// The gate also asks it about **scope names** (a membership's or a
337    /// ceiling's): `chain("MENGER")` → `[MENGER, PLEXUS, *]`, to tell which
338    /// of two scopes lies within the other when it narrows a reach by a
339    /// ceiling. A service that cannot answer for a name returns `None`, and
340    /// two different names are then taken as disjoint.
341    fn chain(&self, target: &str) -> Option<Vec<ScopeRef>>;
342}
343
344// ---------------------------------------------------------------------------
345// RoleTable — an in-memory Roles with inclusion
346// ---------------------------------------------------------------------------
347
348/// Why [`RoleTable::define`] refused a role.
349#[derive(Debug, Clone, PartialEq, Eq)]
350pub enum RoleTableError {
351    /// An entry named a role that is not (yet) defined. A role may only
352    /// include roles defined before it, which is what keeps inclusion
353    /// acyclic.
354    UnknownRole { role: String, includes: String },
355}
356
357impl fmt::Display for RoleTableError {
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        match self {
360            Self::UnknownRole { role, includes } => write!(
361                f,
362                "role {role} includes {includes}, which is not defined before it"
363            ),
364        }
365    }
366}
367
368impl std::error::Error for RoleTableError {}
369
370/// An in-memory [`Roles`]: each role an explicit list of grants, where an
371/// entry may also name an earlier role (inclusion, flattened when defined).
372/// [`ADMIN`] is built in.
373///
374/// ```
375/// use plexus_auth_core::grants::{Grant, RoleTable, Roles};
376/// use plexus_auth_core::RoleName;
377///
378/// let roles = RoleTable::new()
379///     .define("viewer", ["tickets.get", "tickets.list"]).unwrap()
380///     .define("editor", ["viewer", "tickets.set_status"]).unwrap();
381/// let editor = roles.grants(&RoleName::new("editor")).unwrap();
382/// assert!(editor.contains(&Grant::new("tickets.get")));
383/// ```
384#[derive(Debug, Clone, Default)]
385pub struct RoleTable {
386    roles: BTreeMap<RoleName, GrantSet>,
387}
388
389impl RoleTable {
390    /// The table with only the built-in [`ADMIN`].
391    pub fn new() -> Self {
392        Self::default()
393    }
394
395    /// Define (or extend) `role`: each entry a grant (dotted) or an earlier
396    /// role (bare), whose grants are included. Defining a role again adds to
397    /// it, which is how several activations' defaults for one role name
398    /// merge.
399    pub fn define<I, S>(mut self, role: &str, entries: I) -> Result<Self, RoleTableError>
400    where
401        I: IntoIterator<Item = S>,
402        S: AsRef<str>,
403    {
404        let name = RoleName::new(role);
405        let mut set = match self.roles.remove(&name) {
406            Some(GrantSet::Listed(s)) => s,
407            Some(GrantSet::All) => {
408                self.roles.insert(name, GrantSet::All);
409                return Ok(self);
410            }
411            None => BTreeSet::new(),
412        };
413        let mut all = name.as_str() == ADMIN;
414        for entry in entries {
415            let e = entry.as_ref().trim();
416            if e.contains('.') {
417                set.insert(Grant::new(e));
418                continue;
419            }
420            if e == ADMIN {
421                all = true;
422                continue;
423            }
424            match self.roles.get(&RoleName::new(e)) {
425                Some(GrantSet::All) => all = true,
426                Some(GrantSet::Listed(inc)) => set.extend(inc.iter().cloned()),
427                None => {
428                    return Err(RoleTableError::UnknownRole { role: role.to_string(), includes: e.to_string() })
429                }
430            }
431        }
432        self.roles.insert(name, if all { GrantSet::All } else { GrantSet::Listed(set) });
433        Ok(self)
434    }
435
436    /// Replace `role`'s grants outright (an admin's edit: the store wins).
437    pub fn set(&mut self, role: &str, grants: GrantSet) {
438        self.roles.insert(RoleName::new(role), grants);
439    }
440
441    /// A table from already-flat lists (`role → [grant, …]`), as a schema's
442    /// `roles` carries them; lists for one role name merge.
443    pub fn from_lists<'a, I, G>(lists: I) -> Self
444    where
445        I: IntoIterator<Item = (&'a str, G)>,
446        G: IntoIterator,
447        G::Item: AsRef<str>,
448    {
449        let mut table = Self::new();
450        for (role, grants) in lists {
451            let name = RoleName::new(role);
452            let grants: Vec<Grant> = grants.into_iter().map(|g| Grant::new(g.as_ref().trim())).collect();
453            match table.roles.entry(name) {
454                std::collections::btree_map::Entry::Occupied(mut o) => {
455                    if let GrantSet::Listed(s) = o.get_mut() {
456                        s.extend(grants);
457                    }
458                }
459                std::collections::btree_map::Entry::Vacant(v) => {
460                    v.insert(if role == ADMIN { GrantSet::All } else { GrantSet::Listed(grants.into_iter().collect()) });
461                }
462            }
463        }
464        table
465    }
466}
467
468impl Roles for RoleTable {
469    fn grants(&self, role: &RoleName) -> Option<GrantSet> {
470        if role.as_str() == ADMIN {
471            return Some(GrantSet::All);
472        }
473        self.roles.get(role).cloned()
474    }
475
476    fn names(&self) -> Vec<RoleName> {
477        self.roles.keys().cloned().collect()
478    }
479}
480
481// ---------------------------------------------------------------------------
482// Refusal
483// ---------------------------------------------------------------------------
484
485/// Why the gate refused a call.
486#[derive(Debug, Clone, PartialEq, Eq)]
487pub enum Refusal {
488    /// No principal: only `public` methods are reachable anonymously.
489    Unauthenticated,
490    /// The caller does not hold `grant` on `scope` (within its ceiling).
491    MissingGrant {
492        /// The grant the call needed.
493        grant: Grant,
494        /// Where it was needed: the target's innermost scope, or `*` for a
495        /// method without a target (held anywhere would have done).
496        scope: ScopeRef,
497        /// The roles that list the grant ([`ADMIN`] last).
498        roles: Vec<RoleName>,
499        /// Where the caller does hold it (within its ceiling).
500        held_on: Vec<ScopeRef>,
501    },
502    /// AUTH-11: the caller signed in, but that sign-in no longer stands
503    /// (signed out, expired, revoked) — it proves no one.
504    Ended {
505        /// Why, in words for the caller ("you have signed out: sign in
506        /// again").
507        reason: String,
508    },
509}
510
511impl fmt::Display for Refusal {
512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513        match self {
514            Self::Unauthenticated => f.write_str("sign in first"),
515            Self::Ended { reason } => f.write_str(reason),
516            Self::MissingGrant { grant, scope, .. } => write!(f, "needs {grant} on {scope}"),
517        }
518    }
519}
520
521impl std::error::Error for Refusal {}
522
523// ---------------------------------------------------------------------------
524// Reach
525// ---------------------------------------------------------------------------
526
527/// Where a call may act: the scopes the caller holds the method's grant on
528/// (within its ceiling), handed to the method beside `auth`. A read without a
529/// target (`list`, `watch`) answers only from these.
530///
531/// A reach is **live** when it came from a gate: [`Reach::allows`] and
532/// [`Reach::current`] ask the gate again, as memberships, roles and the
533/// ceiling stand *now* — so a stream checks each event (IDENTITY-37: a role
534/// revoked reaches an open stream at its next event). A hub without a gate
535/// hands every method [`Reach::everywhere`], which allows everything.
536#[derive(Clone)]
537pub struct Reach {
538    held_on: Vec<ScopeRef>,
539    live: Option<Live>,
540}
541
542#[derive(Clone)]
543struct Live {
544    gate: Gate,
545    caller: Option<AuthContext>,
546    grant: Grant,
547}
548
549impl fmt::Debug for Reach {
550    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551        f.debug_struct("Reach")
552            .field("held_on", &self.held_on)
553            .field("grant", &self.live.as_ref().map(|l| l.grant.as_str()))
554            .finish()
555    }
556}
557
558impl PartialEq for Reach {
559    /// Two reaches are equal when they hold the same scopes for the same
560    /// grant (the gate behind them is not compared).
561    fn eq(&self, other: &Self) -> bool {
562        self.held_on == other.held_on && self.grant() == other.grant()
563    }
564}
565
566impl Reach {
567    /// Everything — what a method receives on a hub without a gate (login
568    /// off), as today.
569    pub fn everywhere() -> Self {
570        Self { held_on: vec![ScopeRef::Everywhere], live: None }
571    }
572
573    /// Whether the grant is held on `*`.
574    pub fn is_everywhere(&self) -> bool {
575        self.held_on.iter().any(ScopeRef::is_everywhere)
576    }
577
578    /// Whether the grant is held nowhere (a `public` method called by a
579    /// caller who holds no role listing it).
580    pub fn is_empty(&self) -> bool {
581        self.held_on.is_empty()
582    }
583
584    /// The scopes the grant is held on; `[*]` when everywhere.
585    pub fn held_on(&self) -> &[ScopeRef] {
586        &self.held_on
587    }
588
589    /// The grant this reach is for; `None` on a hub without a gate.
590    pub fn grant(&self) -> Option<&Grant> {
591        self.live.as_ref().map(|l| &l.grant)
592    }
593
594    /// Whether the call may act on `target` — asked of the gate as it
595    /// stands now. Without a gate: always.
596    pub fn allows(&self, target: &str) -> bool {
597        match &self.live {
598            None => self.is_everywhere(),
599            Some(l) => l.gate.check(l.caller.as_ref(), &l.grant, Some(target)).is_ok(),
600        }
601    }
602
603    /// The reach as it stands now: `None` once the grant is held nowhere (a
604    /// stream should end). Without a gate: unchanged.
605    pub fn current(&self) -> Option<Reach> {
606        match &self.live {
607            None => Some(self.clone()),
608            Some(l) => l.gate.check(l.caller.as_ref(), &l.grant, None).ok(),
609        }
610    }
611
612    /// Whether the reach covers a target whose chain is `chain` (as
613    /// [`Resolve::chain`] gives it), by this snapshot — no new question to
614    /// the gate. Prefer [`Reach::allows`] where the answer must be current.
615    pub fn covers(&self, chain: &[ScopeRef]) -> bool {
616        self.is_everywhere() || self.held_on.iter().any(|s| chain.contains(s))
617    }
618}
619
620// ---------------------------------------------------------------------------
621// Gate
622// ---------------------------------------------------------------------------
623
624/// AUTH-11: whether a signed-in caller's sign-in still stands — the
625/// service's session table, asked by [`Gate::check`] on every call (and so
626/// on every [`Reach::allows`] / [`Reach::current`] a stream makes). A
627/// signed-out or revoked session proves no one, whatever its principal
628/// holds. Memory only, like the other service traits.
629pub trait Liveness: Send + Sync {
630    /// `Err`: why the sign-in no longer stands, in words for the caller.
631    fn alive(&self, caller: &AuthContext) -> Result<(), String>;
632}
633
634struct GateInner {
635    memberships: Arc<dyn Memberships>,
636    roles: Arc<dyn Roles>,
637    resolve: Arc<dyn Resolve>,
638    liveness: Option<Arc<dyn Liveness>>,
639}
640
641/// The one rule in front of every call: the method's grant, held through a
642/// role on the target's scope, within the session's ceiling. Default deny.
643/// Cheap to clone (one `Arc`); cheap to ask (memory only), so a stream may
644/// ask per event.
645#[derive(Clone)]
646pub struct Gate {
647    inner: Arc<GateInner>,
648}
649
650impl fmt::Debug for Gate {
651    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652        f.write_str("Gate")
653    }
654}
655
656impl Gate {
657    /// A gate over a service's memberships, roles and resolver.
658    pub fn new(memberships: Arc<dyn Memberships>, roles: Arc<dyn Roles>, resolve: Arc<dyn Resolve>) -> Self {
659        Self { inner: Arc::new(GateInner { memberships, roles, resolve, liveness: None }) }
660    }
661
662    /// AUTH-11: this gate, asking `liveness` whether a caller's sign-in
663    /// still stands before every check. Without it the gate still refuses
664    /// a caller past its `expires_at` stamp ([`AuthContext::expired`]).
665    pub fn with_liveness(self, liveness: Arc<dyn Liveness>) -> Self {
666        let i = &self.inner;
667        Self {
668            inner: Arc::new(GateInner {
669                memberships: i.memberships.clone(),
670                roles: i.roles.clone(),
671                resolve: i.resolve.clone(),
672                liveness: Some(liveness),
673            }),
674        }
675    }
676
677    /// AUTH-11: whether `caller`'s sign-in still stands: not past its
678    /// `expires_at`, and live by the service's [`Liveness`]. An anonymous
679    /// context has no sign-in to end: `Ok`.
680    pub fn alive(&self, caller: &AuthContext) -> Result<(), String> {
681        if caller.principal().is_none() {
682            return Ok(());
683        }
684        if caller.expired() {
685            return Err("your sign-in has expired: sign in again".into());
686        }
687        match &self.inner.liveness {
688            Some(l) => l.alive(caller),
689            None => Ok(()),
690        }
691    }
692
693    /// Whether `role` lists `grant` ([`ADMIN`] lists every grant).
694    pub fn lists(&self, role: &RoleName, grant: &Grant) -> bool {
695        role.as_str() == ADMIN || self.inner.roles.grants(role).is_some_and(|g| g.contains(grant))
696    }
697
698    /// The roles that list `grant`, [`ADMIN`] last.
699    pub fn roles_listing(&self, grant: &Grant) -> Vec<RoleName> {
700        let mut out: Vec<RoleName> = self
701            .inner
702            .roles
703            .names()
704            .into_iter()
705            .filter(|r| r.as_str() != ADMIN && self.lists(r, grant))
706            .collect();
707        out.push(RoleName::new(ADMIN));
708        out
709    }
710
711    /// Whether a ceiling entry allows `grant`.
712    fn entry_allows(&self, entry: &RoleOrGrant, grant: &Grant) -> bool {
713        match entry {
714            RoleOrGrant::Grant(g) => g == grant,
715            RoleOrGrant::Role(r) => self.lists(r, grant),
716        }
717    }
718
719    /// The caller's principal and ceiling layers; `None` when anonymous. An
720    /// unreadable ceiling becomes one empty layer — it allows nothing.
721    fn caller_of(caller: Option<&AuthContext>) -> Option<(Principal, Vec<Ceiling>)> {
722        let ctx = caller?;
723        let principal = ctx.principal()?;
724        let layers = Ceiling::layers_of(ctx).unwrap_or_else(|_| vec![Ceiling::default()]);
725        Some((principal, layers))
726    }
727
728    /// Whether `inner` lies within `outer` (or is it).
729    fn within(&self, inner: &ScopeRef, outer: &ScopeRef) -> bool {
730        if outer.is_everywhere() || inner == outer {
731            return true;
732        }
733        match inner {
734            ScopeRef::Everywhere => false,
735            ScopeRef::Named(name) => self.inner.resolve.chain(name).is_some_and(|c| c.contains(outer)),
736        }
737    }
738
739    /// The scopes both `a` and `b` reach: where one lies within the other,
740    /// the inner one.
741    fn meet(&self, a: Vec<ScopeRef>, b: Vec<ScopeRef>) -> Vec<ScopeRef> {
742        if a.iter().any(ScopeRef::is_everywhere) {
743            return b;
744        }
745        if b.iter().any(ScopeRef::is_everywhere) {
746            return a;
747        }
748        let mut out = BTreeSet::new();
749        for x in &a {
750            for y in &b {
751                if self.within(x, y) {
752                    out.insert(x.clone());
753                } else if self.within(y, x) {
754                    out.insert(y.clone());
755                }
756            }
757        }
758        out.into_iter().collect()
759    }
760
761    /// Collapse to `[*]` when `*` is among them; dedupe, ordered.
762    fn normal(scopes: impl IntoIterator<Item = ScopeRef>) -> Vec<ScopeRef> {
763        let set: BTreeSet<ScopeRef> = scopes.into_iter().collect();
764        if set.contains(&ScopeRef::Everywhere) {
765            vec![ScopeRef::Everywhere]
766        } else {
767            set.into_iter().collect()
768        }
769    }
770
771    fn held_on_for(&self, principal: &Principal, layers: &[Ceiling], grant: &Grant) -> Vec<ScopeRef> {
772        let mut acc = Self::normal(
773            self.inner
774                .memberships
775                .held(principal)
776                .into_iter()
777                .filter(|m| self.lists(&m.role, grant))
778                .map(|m| m.scope),
779        );
780        for layer in layers {
781            if acc.is_empty() {
782                break;
783            }
784            let allowed = Self::normal(
785                layer.0.iter().filter(|(rg, _)| self.entry_allows(rg, grant)).map(|(_, s)| s.clone()),
786            );
787            acc = self.meet(acc, allowed);
788        }
789        acc
790    }
791
792    /// Where the caller holds `grant`, within its ceiling: `[*]` when
793    /// everywhere, `[]` when nowhere (and for an anonymous caller). What a
794    /// method without a target answers from.
795    pub fn held_on(&self, caller: &AuthContext, grant: &Grant) -> Vec<ScopeRef> {
796        match Self::caller_of(Some(caller)) {
797            Some((p, layers)) => self.held_on_for(&p, &layers, grant),
798            None => Vec::new(),
799        }
800    }
801
802    /// Allowed when the grant is listed by a role held on a scope in the
803    /// target's chain — or anywhere, for a call with no target — and every
804    /// ceiling layer allows it the same way. The [`Reach`] is live (it asks
805    /// this gate again on [`Reach::allows`] / [`Reach::current`]).
806    ///
807    /// AUTH-11: first, the caller's sign-in must still stand
808    /// ([`Gate::alive`]) — a signed-out session holds nothing, so a socket
809    /// that signed out cannot go on to call `auth.grant`.
810    pub fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<Reach, Refusal> {
811        let Some((principal, layers)) = Self::caller_of(caller) else {
812            return Err(Refusal::Unauthenticated);
813        };
814        if let Some(ctx) = caller {
815            self.alive(ctx).map_err(|reason| Refusal::Ended { reason })?;
816        }
817        let held_on = self.held_on_for(&principal, &layers, grant);
818        let (allowed, scope) = match target {
819            None => (!held_on.is_empty(), ScopeRef::Everywhere),
820            Some(t) => match self.inner.resolve.chain(t) {
821                None => (false, ScopeRef::named(t)),
822                Some(chain) => {
823                    let in_chain = |s: &ScopeRef| s.is_everywhere() || chain.contains(s);
824                    let by_membership = self
825                        .inner
826                        .memberships
827                        .held(&principal)
828                        .iter()
829                        .any(|m| in_chain(&m.scope) && self.lists(&m.role, grant));
830                    let by_ceiling = layers
831                        .iter()
832                        .all(|layer| layer.0.iter().any(|(rg, s)| in_chain(s) && self.entry_allows(rg, grant)));
833                    let scope = chain.first().cloned().unwrap_or_else(|| ScopeRef::named(t));
834                    (by_membership && by_ceiling, scope)
835                }
836            },
837        };
838        if allowed {
839            Ok(Reach {
840                held_on,
841                live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone() }),
842            })
843        } else {
844            Err(Refusal::MissingGrant { grant: grant.clone(), scope, roles: self.roles_listing(grant), held_on })
845        }
846    }
847
848    /// The reach of a `public` method: what [`Gate::check`] would allow
849    /// without a target, or an empty (still live) reach when the caller holds
850    /// the grant nowhere or is anonymous. A public method is never refused.
851    pub fn reach_of_public(&self, caller: Option<&AuthContext>, grant: &Grant) -> Reach {
852        self.check(caller, grant, None).unwrap_or_else(|_| Reach {
853            held_on: Vec::new(),
854            live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone() }),
855        })
856    }
857}
858
859// ---------------------------------------------------------------------------
860// Tests — the gate's decision table
861// ---------------------------------------------------------------------------
862
863#[cfg(test)]
864mod tests {
865    use super::*;
866    use std::sync::Mutex;
867
868    const ADA: &str = "key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
869    const BOB: &str = "key:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
870
871    /// Memberships as a mutable table, so a test can revoke one.
872    #[derive(Default)]
873    struct Members(Mutex<Vec<Membership>>);
874    impl Members {
875        fn grant(&self, who: &str, role: &str, scope: &str) {
876            self.0.lock().unwrap().push(Membership {
877                principal: who.parse().unwrap(),
878                role: RoleName::new(role),
879                scope: ScopeRef::parse(scope),
880            });
881        }
882        fn revoke_all(&self) {
883            self.0.lock().unwrap().clear();
884        }
885    }
886    impl Memberships for Members {
887        fn held(&self, who: &Principal) -> Vec<Membership> {
888            self.0.lock().unwrap().iter().filter(|m| &m.principal == who).cloned().collect()
889        }
890    }
891
892    /// menger-shaped: a ticket `CODE-n` lives in itself, then `CODE`;
893    /// MENGER and IDENTITY are disjoint, both hosted under PLEXUS.
894    struct Shortcodes;
895    impl Resolve for Shortcodes {
896        fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
897            let code = target.split_once('-').map(|(c, _)| c).unwrap_or(target);
898            let mut chain = Vec::new();
899            if target.contains('-') {
900                chain.push(ScopeRef::named(target));
901            }
902            match code {
903                "MENGER" | "IDENTITY" => {
904                    chain.push(ScopeRef::named(code));
905                    chain.push(ScopeRef::named("PLEXUS"));
906                }
907                "PLEXUS" => chain.push(ScopeRef::named("PLEXUS")),
908                _ => return None,
909            }
910            chain.push(ScopeRef::Everywhere);
911            Some(chain)
912        }
913    }
914
915    fn roles() -> RoleTable {
916        RoleTable::new()
917            .define("viewer", ["tickets.get", "tickets.list"])
918            .unwrap()
919            .define("editor", ["viewer", "tickets.set_status"])
920            .unwrap()
921    }
922
923    fn gate(members: &Arc<Members>) -> Gate {
924        Gate::new(members.clone(), Arc::new(roles()), Arc::new(Shortcodes))
925    }
926
927    fn who(p: &str) -> AuthContext {
928        AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::Value::Null)
929    }
930
931    fn with_ceiling(p: &str, ceiling: serde_json::Value) -> AuthContext {
932        AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::json!({ CEILING_KEY: ceiling }))
933    }
934
935    fn g(s: &str) -> Grant {
936        Grant::new(s)
937    }
938
939    #[test]
940    fn a_grant_no_role_lists_is_refused_to_all_but_admin() {
941        let m = Arc::new(Members::default());
942        m.grant(ADA, "editor", "*");
943        m.grant(BOB, "admin", "MENGER");
944        let gate = gate(&m);
945        let err = gate.check(Some(&who(ADA)), &g("members.grant"), Some("MENGER-1")).unwrap_err();
946        assert_eq!(
947            err,
948            Refusal::MissingGrant {
949                grant: g("members.grant"),
950                scope: ScopeRef::named("MENGER-1"),
951                roles: vec![RoleName::new("admin")],
952                held_on: vec![],
953            }
954        );
955        assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("MENGER-1")).is_ok());
956        // admin on MENGER is not admin on IDENTITY.
957        assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("IDENTITY-1")).is_err());
958    }
959
960    #[test]
961    fn held_on_a_scope_allows_targets_in_its_chain_only() {
962        let m = Arc::new(Members::default());
963        m.grant(ADA, "editor", "MENGER");
964        let gate = gate(&m);
965        let reach = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("MENGER-12")).unwrap();
966        assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER")]);
967        let err = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-1")).unwrap_err();
968        assert_eq!(
969            err,
970            Refusal::MissingGrant {
971                grant: g("tickets.set_status"),
972                scope: ScopeRef::named("IDENTITY-1"),
973                roles: vec![RoleName::new("editor"), RoleName::new("admin")],
974                held_on: vec![ScopeRef::named("MENGER")],
975            }
976        );
977        assert_eq!(err.to_string(), "needs tickets.set_status on IDENTITY-1");
978        // A target nothing resolves is refused.
979        assert!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("NOPE-1")).is_err());
980    }
981
982    #[test]
983    fn held_on_everywhere_allows_any_target_and_reach_is_everywhere() {
984        let m = Arc::new(Members::default());
985        m.grant(ADA, "viewer", "*");
986        m.grant(ADA, "viewer", "MENGER");
987        let gate = gate(&m);
988        let reach = gate.check(Some(&who(ADA)), &g("tickets.get"), Some("IDENTITY-3")).unwrap();
989        assert!(reach.is_everywhere());
990        assert_eq!(reach.held_on(), &[ScopeRef::Everywhere]);
991        assert!(gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap().is_everywhere());
992        // viewer does not list set_status, wherever it is held.
993        assert!(gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-3")).is_err());
994    }
995
996    #[test]
997    fn without_a_target_held_anywhere_suffices_and_reach_says_where() {
998        let m = Arc::new(Members::default());
999        m.grant(ADA, "viewer", "MENGER");
1000        m.grant(ADA, "viewer", "IDENTITY");
1001        let gate = gate(&m);
1002        let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
1003        assert_eq!(reach.held_on(), &[ScopeRef::named("IDENTITY"), ScopeRef::named("MENGER")]);
1004        assert!(reach.allows("MENGER-4"));
1005        assert!(!reach.allows("PLEXUS-1"));
1006        let err = gate.check(Some(&who(BOB)), &g("tickets.list"), None).unwrap_err();
1007        assert!(matches!(err, Refusal::MissingGrant { ref scope, .. } if scope.is_everywhere()));
1008    }
1009
1010    #[test]
1011    fn a_ceiling_narrows_the_membership() {
1012        let m = Arc::new(Members::default());
1013        m.grant(ADA, "editor", "MENGER");
1014        let gate = gate(&m);
1015        let narrowed = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
1016        assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-12")).is_ok());
1017        assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-13")).is_err());
1018        // The reach of a target-less read is the meet: MENGER-12, inside MENGER.
1019        let reach = gate.check(Some(&narrowed), &g("tickets.list"), None).unwrap();
1020        assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER-12")]);
1021        // A grant-entry ceiling: only tickets.get, anywhere the membership allows.
1022        let only_get = with_ceiling(ADA, serde_json::json!([["tickets.get@*"]]));
1023        assert!(gate.check(Some(&only_get), &g("tickets.get"), Some("MENGER-1")).is_ok());
1024        let err = gate.check(Some(&only_get), &g("tickets.set_status"), Some("MENGER-1")).unwrap_err();
1025        assert!(matches!(err, Refusal::MissingGrant { ref held_on, .. } if held_on.is_empty()));
1026        // Two layers: both must allow.
1027        let layered = with_ceiling(ADA, serde_json::json!([["editor@*"], ["viewer@MENGER"]]));
1028        assert!(gate.check(Some(&layered), &g("tickets.get"), Some("MENGER-1")).is_ok());
1029        assert!(gate.check(Some(&layered), &g("tickets.set_status"), Some("MENGER-1")).is_err());
1030        // A ceiling never widens: editor@IDENTITY grants nothing there.
1031        let wider = with_ceiling(ADA, serde_json::json!(["editor@IDENTITY"]));
1032        assert!(gate.check(Some(&wider), &g("tickets.get"), Some("IDENTITY-1")).is_err());
1033        // An unreadable ceiling allows nothing.
1034        let bad = with_ceiling(ADA, serde_json::json!("editor@*"));
1035        assert!(gate.check(Some(&bad), &g("tickets.get"), Some("MENGER-1")).is_err());
1036    }
1037
1038    #[test]
1039    fn role_inclusion_flattens_and_must_name_an_earlier_role() {
1040        let r = roles();
1041        let editor = r.grants(&RoleName::new("editor")).unwrap();
1042        assert!(editor.contains(&g("tickets.get")) && editor.contains(&g("tickets.set_status")));
1043        let viewer = r.grants(&RoleName::new("viewer")).unwrap();
1044        assert!(!viewer.contains(&g("tickets.set_status")));
1045        assert_eq!(
1046            RoleTable::new().define("editor", ["viewer"]).unwrap_err(),
1047            RoleTableError::UnknownRole { role: "editor".into(), includes: "viewer".into() }
1048        );
1049        // admin is built in: holds every grant, whatever the table says.
1050        assert_eq!(r.grants(&RoleName::new("admin")), Some(GrantSet::All));
1051        // from_lists merges one role's lists from several activations.
1052        let merged = RoleTable::from_lists([("editor", vec!["tickets.get"]), ("editor", vec!["comments.add"])]);
1053        let e = merged.grants(&RoleName::new("editor")).unwrap();
1054        assert!(e.contains(&g("tickets.get")) && e.contains(&g("comments.add")));
1055    }
1056
1057    #[test]
1058    fn anonymous_is_unauthenticated() {
1059        let m = Arc::new(Members::default());
1060        let gate = gate(&m);
1061        assert_eq!(gate.check(None, &g("tickets.get"), Some("MENGER-1")).unwrap_err(), Refusal::Unauthenticated);
1062        assert_eq!(
1063            gate.check(Some(&AuthContext::anonymous()), &g("tickets.list"), None).unwrap_err(),
1064            Refusal::Unauthenticated
1065        );
1066        // A public method's reach for an anonymous caller: empty, never refused.
1067        assert!(gate.reach_of_public(None, &g("auth.login")).is_empty());
1068    }
1069
1070    #[test]
1071    fn a_live_reach_follows_grants_as_they_stand() {
1072        let m = Arc::new(Members::default());
1073        m.grant(ADA, "viewer", "MENGER");
1074        let gate = gate(&m);
1075        let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
1076        assert!(reach.allows("MENGER-1"));
1077        assert!(reach.current().is_some());
1078        m.revoke_all();
1079        assert!(!reach.allows("MENGER-1"));
1080        assert!(reach.current().is_none());
1081        // Without a gate, everything.
1082        assert!(Reach::everywhere().allows("ANY-1") && Reach::everywhere().current().is_some());
1083    }
1084
1085    #[test]
1086    fn scope_refs_and_ceilings_round_trip() {
1087        assert_eq!(serde_json::to_string(&ScopeRef::Everywhere).unwrap(), "\"*\"");
1088        assert_eq!(serde_json::from_str::<ScopeRef>("\"MENGER\"").unwrap(), ScopeRef::named("MENGER"));
1089        let c = Ceiling::parse(["editor@MENGER-12", "tickets.get@*"]).unwrap();
1090        assert_eq!(c.0[0], (RoleOrGrant::Role(RoleName::new("editor")), ScopeRef::named("MENGER-12")));
1091        assert_eq!(c.0[1], (RoleOrGrant::Grant(g("tickets.get")), ScopeRef::Everywhere));
1092        assert_eq!(c.text(), vec!["editor@MENGER-12", "tickets.get@*"]);
1093        assert!(Ceiling::parse(["editor"]).is_err());
1094    }
1095
1096    /// A session table with one switch: signed out or not.
1097    #[derive(Default)]
1098    struct Switch(std::sync::atomic::AtomicBool);
1099    impl Liveness for Switch {
1100        fn alive(&self, _: &AuthContext) -> Result<(), String> {
1101            if self.0.load(std::sync::atomic::Ordering::SeqCst) {
1102                Err("you have signed out: sign in again".into())
1103            } else {
1104                Ok(())
1105            }
1106        }
1107    }
1108
1109    /// AUTH-11: a signed-out session holds nothing — not even admin on `*`
1110    /// — and a live reach taken before the sign-out ends with it.
1111    #[test]
1112    fn a_session_that_ended_holds_nothing() {
1113        let m = Arc::new(Members::default());
1114        m.grant(ADA, "admin", "*");
1115        let out = Arc::new(Switch::default());
1116        let gate = gate(&m).with_liveness(out.clone());
1117        let reach = gate.check(Some(&who(ADA)), &g("auth.grant"), None).expect("admin before sign-out");
1118        assert!(reach.allows("MENGER-1"));
1119        out.0.store(true, std::sync::atomic::Ordering::SeqCst);
1120        let ended = Refusal::Ended { reason: "you have signed out: sign in again".into() };
1121        assert_eq!(gate.check(Some(&who(ADA)), &g("auth.grant"), None).unwrap_err(), ended);
1122        assert_eq!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("MENGER-1")).unwrap_err(), ended);
1123        assert!(!reach.allows("MENGER-1"), "a stream's next event sees it");
1124        assert!(reach.current().is_none());
1125        assert!(gate.reach_of_public(Some(&who(ADA)), &g("auth.grant")).is_empty());
1126        // Anonymous is not "ended": still plain Unauthenticated.
1127        assert_eq!(gate.check(None, &g("auth.grant"), None).unwrap_err(), Refusal::Unauthenticated);
1128    }
1129
1130    /// AUTH-11: past its `expires_at` stamp, a sign-in is over even with
1131    /// no liveness hook.
1132    #[test]
1133    fn an_expired_sign_in_holds_nothing() {
1134        let m = Arc::new(Members::default());
1135        m.grant(ADA, "admin", "*");
1136        let gate = gate(&m);
1137        let past = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": 1 }));
1138        assert!(matches!(gate.check(Some(&past), &g("auth.grant"), None), Err(Refusal::Ended { .. })));
1139        let future = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": i64::MAX }));
1140        assert!(gate.check(Some(&future), &g("auth.grant"), None).is_ok());
1141    }
1142}