Skip to main content

plexus_core/plexus/
auth_memory.rs

1//! AUTH-5 — a **reference, in-memory** implementation of what a service
2//! supplies the `auth` activation: [`MemoryRoles`] ([`RoleStore`]),
3//! [`MemoryMemberships`] ([`MembershipStore`]) and [`MemoryAuthBackend`]
4//! ([`AuthBackend`], and a [`SessionValidator`] for the tokens it mints).
5//!
6//! For tests, and as the shape a Plexus service starts from: a real service
7//! keeps the same answers in its own store (menger: its members table and
8//! sessions, AUTH-7) — reads from memory, writes through.
9//!
10//! The backend's flows:
11//!
12//! - **browser** — `login {browser: {redirect}}` keeps a state for the
13//!   loopback `redirect` (only `http://127.0.0.1:…` / `http://localhost:…`)
14//!   and answers `{login_url: "<login_url>?cli=1&state=…", state}`. The
15//!   service's web sign-in, once the person is through, calls
16//!   [`MemoryAuthBackend::complete_browser`], which mints a one-time code
17//!   (good for a minute) and gives the URL to send the browser back to.
18//!   `login {code: {code, state}}` trades it for a session.
19//! - **password** — users added with [`MemoryAuthBackend::with_user`].
20//! - **session** — on a connection that is someone: a session for the same
21//!   principal (and agent), its ceiling layered on the caller's.
22//!
23//! Tokens are `mgs_<32 hex>`; [`SessionValidator::validate`] takes the bare
24//! token, `Bearer <token>`, or a `Cookie` header holding `access_token=…`.
25
26use std::collections::HashMap;
27use std::sync::{Mutex, RwLock};
28use std::time::{SystemTime, UNIX_EPOCH};
29
30use async_trait::async_trait;
31
32use plexus_auth_core::grants::{Ceiling, GrantSet, Membership, Memberships, RoleTable, Roles, ScopeRef, CEILING_KEY};
33use plexus_auth_core::identity::Principal;
34use plexus_auth_core::{RoleName, SessionValidator};
35
36use super::auth::AuthContext;
37use super::auth_activation::{
38    AuthBackend, AuthFailure, LoginAnswer, LoginFlow, MembershipStore, Provider, ProviderKind, RoleStore, Session,
39    SignupAnswer, StoreError, Waiting,
40};
41
42fn now() -> i64 {
43    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
44}
45
46fn fresh(prefix: &str) -> String {
47    format!("{prefix}{}", uuid::Uuid::new_v4().simple())
48}
49
50// ===========================================================================
51// Roles
52// ===========================================================================
53
54/// An editable [`RoleTable`]: the activations' declared defaults, an admin's
55/// edits replacing a role outright.
56#[derive(Debug, Default)]
57pub struct MemoryRoles {
58    table: RwLock<RoleTable>,
59}
60
61impl MemoryRoles {
62    pub fn new(table: RoleTable) -> Self {
63        Self { table: RwLock::new(table) }
64    }
65
66    /// Seeded from [`DynamicHub::declared_roles`](super::DynamicHub::declared_roles)
67    /// — every activation's `roles(...)`, merged by name.
68    pub fn from_declared(declared: &std::collections::BTreeMap<String, Vec<String>>) -> Self {
69        Self::new(RoleTable::from_lists(declared.iter().map(|(r, g)| (r.as_str(), g.iter().map(String::as_str)))))
70    }
71
72    /// Add the declared defaults of roles this table does not hold yet —
73    /// a role already defined (or edited) keeps what it has. For a hub
74    /// built before its roles are known:
75    /// `roles.seed(&hub.declared_roles())` after
76    /// [`DynamicHub::with_auth`](super::DynamicHub::with_auth).
77    pub fn seed(&self, declared: &std::collections::BTreeMap<String, Vec<String>>) {
78        let mut table = self.table.write().unwrap_or_else(|p| p.into_inner());
79        let known = table.names();
80        for (role, grants) in declared {
81            if role == plexus_auth_core::grants::ADMIN || known.iter().any(|k| k.as_str() == role) {
82                continue;
83            }
84            table.set(role, GrantSet::listed(grants.iter().cloned()));
85        }
86    }
87}
88
89impl Roles for MemoryRoles {
90    fn grants(&self, role: &RoleName) -> Option<GrantSet> {
91        self.table.read().unwrap_or_else(|p| p.into_inner()).grants(role)
92    }
93
94    fn names(&self) -> Vec<RoleName> {
95        self.table.read().unwrap_or_else(|p| p.into_inner()).names()
96    }
97}
98
99#[async_trait]
100impl RoleStore for MemoryRoles {
101    async fn set(&self, role: &RoleName, grants: GrantSet) -> Result<(), StoreError> {
102        self.table.write().unwrap_or_else(|p| p.into_inner()).set(role.as_str(), grants);
103        Ok(())
104    }
105}
106
107// ===========================================================================
108// Memberships
109// ===========================================================================
110
111/// Memberships as a list.
112#[derive(Debug, Default)]
113pub struct MemoryMemberships {
114    rows: RwLock<Vec<Membership>>,
115}
116
117impl MemoryMemberships {
118    pub fn new() -> Self {
119        Self::default()
120    }
121
122    /// Add `principal` as `role` on `scope` (`*` or a name). Panics on a
123    /// principal that does not parse — a fixture's mistake.
124    pub fn with(self, principal: &str, role: &str, scope: &str) -> Self {
125        self.rows.write().unwrap_or_else(|p| p.into_inner()).push(Membership {
126            principal: principal.parse().expect("a principal"),
127            role: RoleName::new(role),
128            scope: ScopeRef::parse(scope),
129        });
130        self
131    }
132
133    /// Every membership.
134    pub fn all(&self) -> Vec<Membership> {
135        self.rows.read().unwrap_or_else(|p| p.into_inner()).clone()
136    }
137}
138
139impl Memberships for MemoryMemberships {
140    fn held(&self, who: &Principal) -> Vec<Membership> {
141        self.rows.read().unwrap_or_else(|p| p.into_inner()).iter().filter(|m| &m.principal == who).cloned().collect()
142    }
143}
144
145#[async_trait]
146impl MembershipStore for MemoryMemberships {
147    async fn grant(&self, membership: Membership) -> Result<(), StoreError> {
148        let mut rows = self.rows.write().unwrap_or_else(|p| p.into_inner());
149        if !rows.contains(&membership) {
150            rows.push(membership);
151        }
152        Ok(())
153    }
154
155    async fn revoke(
156        &self,
157        principal: &Principal,
158        role: Option<&RoleName>,
159        scope: &ScopeRef,
160    ) -> Result<Vec<RoleName>, StoreError> {
161        let mut rows = self.rows.write().unwrap_or_else(|p| p.into_inner());
162        let mut removed = Vec::new();
163        rows.retain(|m| {
164            let hit = &m.principal == principal && &m.scope == scope && role.is_none_or(|r| &m.role == r);
165            if hit {
166                removed.push(m.role.clone());
167            }
168            !hit
169        });
170        Ok(removed)
171    }
172}
173
174// ===========================================================================
175// Backend
176// ===========================================================================
177
178#[derive(Debug, Clone)]
179struct User {
180    password: String,
181    principal: Principal,
182    name: Option<String>,
183}
184
185#[derive(Debug, Clone)]
186struct SessionRec {
187    id: String,
188    principal: Principal,
189    name: Option<String>,
190    agent: Option<String>,
191    expires_at: i64,
192    layers: Vec<Vec<String>>,
193}
194
195#[derive(Debug, Clone)]
196struct Code {
197    state: String,
198    principal: Principal,
199    name: Option<String>,
200    issued: i64,
201}
202
203#[derive(Debug, Default)]
204struct State {
205    users: HashMap<String, User>,
206    sessions: HashMap<String, SessionRec>,
207    /// state → the loopback redirect it was started for
208    pending: HashMap<String, String>,
209    codes: HashMap<String, Code>,
210    waiting: Vec<Waiting>,
211}
212
213/// An in-memory [`AuthBackend`] and [`SessionValidator`]. See the module
214/// docs for its flows.
215#[derive(Debug)]
216pub struct MemoryAuthBackend {
217    login_url: String,
218    providers: Vec<Provider>,
219    default_ttl: u64,
220    state: Mutex<State>,
221}
222
223/// How long a browser flow's code is good for.
224pub const CODE_TTL_SECS: i64 = 60;
225
226impl MemoryAuthBackend {
227    /// A backend whose browser sign-in page is `login_url` (the service's
228    /// own, e.g. `http://127.0.0.1:4456/login`). Offers a `browser` and a
229    /// `key` provider; [`Self::with_user`] adds `password`.
230    pub fn new(login_url: impl Into<String>) -> Self {
231        Self {
232            login_url: login_url.into(),
233            providers: vec![
234                Provider { name: "browser".into(), kind: ProviderKind::Browser, label: Some("Sign in with the browser".into()) },
235                Provider { name: "key".into(), kind: ProviderKind::Key, label: Some("An agent's key".into()) },
236            ],
237            default_ttl: 12 * 3600,
238            state: Mutex::new(State::default()),
239        }
240    }
241
242    /// Replace the providers offered.
243    pub fn with_providers(mut self, providers: Vec<Provider>) -> Self {
244        self.providers = providers;
245        self
246    }
247
248    /// A password user: `username` / `password` sign in as `principal`.
249    pub fn with_user(self, username: &str, password: &str, principal: &str, name: Option<&str>) -> Self {
250        {
251            let mut st = self.state.lock().unwrap_or_else(|p| p.into_inner());
252            st.users.insert(
253                username.into(),
254                User { password: password.into(), principal: principal.parse().expect("a principal"), name: name.map(Into::into) },
255            );
256        }
257        if !self.providers.iter().any(|p| p.kind == ProviderKind::Password) {
258            let mut me = self;
259            me.providers.push(Provider { name: "password".into(), kind: ProviderKind::Password, label: None });
260            return me;
261        }
262        self
263    }
264
265    /// The service's web sign-in, once the person behind `state` is through:
266    /// a one-time code for that state, and the loopback URL to send the
267    /// browser back to (`<redirect>?code=…&state=…`).
268    pub fn complete_browser(&self, state: &str, principal: &str, name: Option<&str>) -> Result<(String, String), AuthFailure> {
269        let principal: Principal = principal.parse().map_err(|e| AuthFailure::new(format!("{e}")))?;
270        let mut st = self.state.lock().unwrap_or_else(|p| p.into_inner());
271        let redirect = st.pending.remove(state).ok_or_else(|| AuthFailure::new("no sign-in waits on this state"))?;
272        let code = fresh("c_");
273        st.codes.insert(code.clone(), Code { state: state.into(), principal, name: name.map(Into::into), issued: now() });
274        let sep = if redirect.contains('?') { '&' } else { '?' };
275        Ok((format!("{redirect}{sep}code={code}&state={state}"), code))
276    }
277
278    /// Mint a session (also what a service's own web login would call).
279    pub fn mint(
280        &self,
281        principal: &Principal,
282        name: Option<String>,
283        agent: Option<String>,
284        ttl_secs: Option<u64>,
285        layers: Vec<Vec<String>>,
286    ) -> Session {
287        let token = fresh("mgs_");
288        let expires_at = now() + ttl_secs.unwrap_or(self.default_ttl) as i64;
289        let rec = SessionRec {
290            id: fresh("sess_"),
291            principal: principal.clone(),
292            name: name.clone(),
293            agent: agent.clone(),
294            expires_at,
295            layers: layers.clone(),
296        };
297        self.state.lock().unwrap_or_else(|p| p.into_inner()).sessions.insert(token.clone(), rec);
298        Session {
299            token,
300            principal: principal.to_string(),
301            agent,
302            name,
303            expires_at,
304            ceiling: layers.last().cloned().unwrap_or_default(),
305        }
306    }
307
308    /// The identity a token stands for, while it lasts.
309    pub fn context_of(&self, token: &str) -> Option<AuthContext> {
310        let st = self.state.lock().unwrap_or_else(|p| p.into_inner());
311        let rec = st.sessions.get(token)?;
312        if rec.expires_at <= now() {
313            return None;
314        }
315        let mut meta = serde_json::Map::new();
316        if let Some(n) = &rec.name {
317            meta.insert("name".into(), n.clone().into());
318        }
319        if let Some(a) = &rec.agent {
320            meta.insert("agent".into(), a.clone().into());
321        }
322        if !rec.layers.is_empty() {
323            meta.insert(CEILING_KEY.into(), serde_json::json!(rec.layers));
324        }
325        meta.insert("expires_at".into(), rec.expires_at.into());
326        Some(AuthContext::for_principal(&rec.principal, rec.id.clone(), vec![], serde_json::Value::Object(meta)))
327    }
328
329    /// The token a credential carries: bare, `Bearer …`, or a cookie
330    /// header's `access_token=…`.
331    fn token_in(credential: &str) -> Option<&str> {
332        let c = credential.trim();
333        if let Some(t) = c.strip_prefix("Bearer ") {
334            return Some(t.trim());
335        }
336        if c.starts_with("mgs_") && !c.contains(';') && !c.contains('=') {
337            return Some(c);
338        }
339        c.split(';').filter_map(|kv| kv.trim().split_once('=')).find(|(k, _)| *k == "access_token").map(|(_, v)| v.trim())
340    }
341}
342
343/// The ceiling layers a caller's session already carries, as text.
344fn layers_of(ctx: &AuthContext) -> Result<Vec<Vec<String>>, AuthFailure> {
345    Ceiling::layers_of(ctx).map(|ls| ls.iter().map(|l| l.text()).collect()).map_err(|e| AuthFailure::new(e.to_string()))
346}
347
348#[async_trait]
349impl AuthBackend for MemoryAuthBackend {
350    fn providers(&self) -> Vec<Provider> {
351        self.providers.clone()
352    }
353
354    async fn login(&self, caller: Option<&AuthContext>, flow: LoginFlow) -> Result<LoginAnswer, AuthFailure> {
355        match flow {
356            LoginFlow::Browser { redirect } => {
357                let loopback = ["http://127.0.0.1:", "http://localhost:", "http://[::1]:"];
358                if !loopback.iter().any(|p| redirect.starts_with(p)) {
359                    return Err(AuthFailure::new("the redirect must be a loopback address (http://127.0.0.1:PORT/…)"));
360                }
361                let state = fresh("s_");
362                self.state.lock().unwrap_or_else(|p| p.into_inner()).pending.insert(state.clone(), redirect);
363                let sep = if self.login_url.contains('?') { '&' } else { '?' };
364                Ok(LoginAnswer::LoginUrl { url: format!("{}{sep}cli=1&state={state}", self.login_url), state })
365            }
366            LoginFlow::Code { code, state } => {
367                let found = self.state.lock().unwrap_or_else(|p| p.into_inner()).codes.remove(&code);
368                let Some(c) = found else { return Err(AuthFailure::new("the code is not good (used, or never issued)")) };
369                if c.state != state {
370                    return Err(AuthFailure::new("the code is not good for this state"));
371                }
372                if now() - c.issued > CODE_TTL_SECS {
373                    return Err(AuthFailure::new("the code has expired: sign in again"));
374                }
375                Ok(LoginAnswer::Session(self.mint(&c.principal, c.name, None, None, Vec::new())))
376            }
377            LoginFlow::Password { username, password } => {
378                let user = self.state.lock().unwrap_or_else(|p| p.into_inner()).users.get(&username).cloned();
379                match user {
380                    Some(u) if u.password == password => {
381                        Ok(LoginAnswer::Session(self.mint(&u.principal, u.name, None, None, Vec::new())))
382                    }
383                    _ => Err(AuthFailure::new("wrong username or password")),
384                }
385            }
386            LoginFlow::Session { ttl_secs, ceiling } => {
387                let ctx = caller.ok_or_else(|| AuthFailure::new("a session needs a connection that is someone"))?;
388                let principal = ctx.principal().ok_or_else(|| AuthFailure::new("a session needs a connection that is someone"))?;
389                let mut layers = layers_of(ctx)?;
390                if let Some(entries) = ceiling.filter(|c| !c.is_empty()) {
391                    let parsed = Ceiling::parse(&entries).map_err(|e| AuthFailure::new(e.to_string()))?;
392                    layers.push(parsed.text());
393                }
394                // Never outlive the session it was asked on.
395                let ttl = match ctx.metadata.get("expires_at").and_then(|v| v.as_i64()) {
396                    Some(end) => {
397                        let left = (end - now()).max(0) as u64;
398                        Some(ttl_secs.unwrap_or(self.default_ttl).min(left))
399                    }
400                    None => ttl_secs,
401                };
402                let name = ctx.get_metadata_string("name");
403                let agent = ctx.get_metadata_string("agent");
404                Ok(LoginAnswer::Session(self.mint(&principal, name, agent, ttl, layers)))
405            }
406        }
407    }
408
409    async fn signup(&self, caller: Option<&AuthContext>, _via: Option<String>) -> Result<SignupAnswer, AuthFailure> {
410        match caller.and_then(|c| c.principal()) {
411            None => Err(AuthFailure::new("sign in first (auth.login): signup asks for access for who you are")),
412            Some(_) => Err(AuthFailure::new("you already hold a role here")),
413        }
414    }
415
416    async fn ask_access(&self, caller: &AuthContext, via: Option<String>) -> Result<Waiting, AuthFailure> {
417        let principal = caller.principal().ok_or_else(|| AuthFailure::new("sign in first"))?;
418        let text = principal.to_string();
419        let mut st = self.state.lock().unwrap_or_else(|p| p.into_inner());
420        if let Some(w) = st.waiting.iter().find(|w| w.principal == text) {
421            return Ok(w.clone());
422        }
423        let provider = via.or_else(|| text.split_once(':').map(|(k, _)| k.to_string()));
424        let w = Waiting {
425            principal: text,
426            name: caller.get_metadata_string("name").or_else(|| caller.get_metadata_string("agent")),
427            provider,
428            since: now(),
429        };
430        st.waiting.push(w.clone());
431        Ok(w)
432    }
433
434    fn waiting(&self) -> Vec<Waiting> {
435        self.state.lock().unwrap_or_else(|p| p.into_inner()).waiting.clone()
436    }
437
438    async fn logout(&self, caller: &AuthContext) -> Result<(), AuthFailure> {
439        let mut st = self.state.lock().unwrap_or_else(|p| p.into_inner());
440        st.sessions.retain(|_, rec| rec.id != caller.session_id);
441        Ok(())
442    }
443
444    fn alive(&self, caller: &AuthContext) -> Result<(), String> {
445        self.session_alive(caller)
446    }
447}
448
449impl MemoryAuthBackend {
450    /// AUTH-11: a caller whose session this backend minted stands while
451    /// that session does; any other identity (a key proof) has none to end.
452    fn session_alive(&self, caller: &AuthContext) -> Result<(), String> {
453        if !caller.session_id.starts_with("sess_") {
454            return Ok(());
455        }
456        let st = self.state.lock().unwrap_or_else(|p| p.into_inner());
457        match st.sessions.values().find(|rec| rec.id == caller.session_id) {
458            Some(rec) if rec.expires_at > now() => Ok(()),
459            Some(_) => Err("your sign-in has expired: sign in again".into()),
460            None => Err("you have signed out: sign in again".into()),
461        }
462    }
463}
464
465#[async_trait]
466impl SessionValidator for MemoryAuthBackend {
467    async fn validate(&self, credential: &str) -> Option<AuthContext> {
468        self.context_of(Self::token_in(credential)?)
469    }
470
471    fn alive(&self, ctx: &AuthContext) -> Result<(), String> {
472        self.session_alive(ctx)
473    }
474}