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