Skip to main content

plexus_core/plexus/
auth_activation.rs

1//! AUTH-5 — **the `auth` activation**: one auth surface in every gated
2//! Plexus hub. Sign in, sign up, who am I, what does this need, and the
3//! admin's roles and memberships.
4//!
5//! A service turns login on with [`DynamicHub::with_auth`], handing it an
6//! [`AuthSetup`]: what only the service knows —
7//!
8//! - an [`AuthBackend`]: its providers, its login flows (the browser start
9//!   and finish, a password, a session minted on a key-proved or signed-in
10//!   connection), signup and the waiting list, logout;
11//! - an editable [`RoleStore`] (role → grants: defaults from the
12//!   activations' `roles(...)`, an admin's edits win) and
13//!   [`MembershipStore`] (who holds which role where);
14//! - its scope [`Resolve`]r.
15//!
16//! The hub builds the [`Gate`] from those same stores (so an edit reaches
17//! the next call and the next view), mounts this activation, and the rest
18//! the activation answers itself from the gate and the stores:
19//!
20//! | method | who | answers |
21//! |---|---|---|
22//! | `providers`, `login`, `signup` | anyone (`public`) | the door |
23//! | `whoami`, `logout`, `requires` | any signed-in caller (whatever its roles or ceiling) | `whoami`, `logged_out`, `requires` |
24//! | `roles` | whoever holds `auth.roles` (admin) | one `role` per role |
25//! | `role_set` | admin on `*` | the role as it now stands |
26//! | `grant`, `revoke` | whoever holds them on the scope (`target = "scope"`) | `granted` / `revoked` |
27//! | `waiting` | admin on `*` | one `waiting` per principal asking |
28//!
29//! A refusal the gate makes is AUTH-2's typed error item; one this
30//! activation makes (`role_set`, `waiting` short of `*`) is an in-band
31//! `{type: "error", error_kind: "forbidden", grant, scope, roles,
32//! held_on, message}` event — the same fields.
33//!
34//! [`super::auth_memory`] has a reference in-memory implementation of every
35//! trait here, for tests and as a starting point.
36//!
37//! [`DynamicHub::with_auth`]: super::DynamicHub::with_auth
38
39use std::collections::{BTreeMap, BTreeSet};
40use std::fmt;
41use std::sync::{Arc, RwLock};
42
43use async_stream::stream;
44use async_trait::async_trait;
45use futures::Stream;
46use schemars::JsonSchema;
47use serde::{Deserialize, Serialize};
48
49use plexus_auth_core::grants::{
50    Ceiling, Gate, Grant, GrantSet, Liveness, Membership, Memberships, Reach, Resolve, Roles, ScopeRef, ADMIN,
51};
52use plexus_auth_core::identity::Principal;
53use plexus_auth_core::RoleName;
54
55use super::auth::AuthContext;
56use super::auth_params as param;
57use super::schema::{MethodRole, PluginSchema};
58
59/// The grants every signed-in caller reaches, whatever its roles or its
60/// session's ceiling: asking who it is, signing out, and asking what a
61/// method needs. Never anonymously.
62pub const SIGNED_IN_GRANTS: [&str; 3] = ["auth.whoami", "auth.logout", "auth.requires"];
63
64// ===========================================================================
65// Wire types
66// ===========================================================================
67
68/// How a provider signs someone in.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
70#[serde(rename_all = "snake_case")]
71pub enum ProviderKind {
72    /// A person, through the browser (OIDC, WorkOS, …): `login {flow:
73    /// {browser}}` then `{code}`.
74    Browser,
75    /// A username and password (`login {flow: {password}}`).
76    Password,
77    /// An agent's key: a proof at the upgrade, then `login {flow: {session}}`.
78    Key,
79}
80
81/// One way in this server offers.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
83pub struct Provider {
84    /// Its name (`workos`, `plexus-idp`, `key`).
85    pub name: String,
86    pub kind: ProviderKind,
87    /// A human label, when it has one.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub label: Option<String>,
90}
91
92/// How a caller signs in (`auth.login {flow: …}`). On the wire, externally
93/// tagged: `{"browser": {"redirect": …}}`, `{"code": {"code", "state"}}`,
94/// `{"password": {"username", "password"}}`, `{"session": {"ttl_secs",
95/// "ceiling"}}`.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
97#[serde(rename_all = "snake_case")]
98pub enum LoginFlow {
99    /// A person, from a client with a browser: answered with the URL to
100    /// open (`login_url {url, state}`); the browser comes back to
101    /// `redirect` (a loopback address the client listens on) with a
102    /// one-time code.
103    Browser { redirect: String },
104    /// The browser came back: trade the code for a session. Single-use,
105    /// bound to the state.
106    Code { code: String, state: String },
107    /// Where a provider takes a password.
108    Password { username: String, password: String },
109    /// A session on a connection that is already someone — a key proof at
110    /// the upgrade (IDENTITY-40), or a session — bounded by `ceiling`
111    /// (`role@SCOPE` / `grant@SCOPE` entries) and lasting `ttl_secs`.
112    Session {
113        #[serde(default)]
114        ttl_secs: Option<u64>,
115        #[serde(default)]
116        ceiling: Option<Vec<String>>,
117    },
118}
119
120/// A session a backend minted.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
122pub struct Session {
123    /// The bearer token (`Authorization: Bearer …`, or the service's cookie).
124    pub token: String,
125    /// Who it is: `key:…`, `oidc:workos/user_…`, `idp:…`.
126    pub principal: String,
127    /// The agent id, for an agent's session.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub agent: Option<String>,
130    /// A display name, when the provider gives one.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub name: Option<String>,
133    /// Unix seconds.
134    pub expires_at: i64,
135    /// The session's ceiling, `role@SCOPE` / `grant@SCOPE`; empty: none.
136    #[serde(default)]
137    pub ceiling: Vec<String>,
138}
139
140/// Someone asking for access.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
142pub struct Waiting {
143    pub principal: String,
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub name: Option<String>,
146    /// The way they came in (`key`, `workos`, …).
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub provider: Option<String>,
149    /// Unix seconds: when they first asked.
150    pub since: i64,
151}
152
153/// What `login` answers.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub enum LoginAnswer {
156    /// Open this URL; the browser comes back with a code for this state.
157    LoginUrl { url: String, state: String },
158    Session(Session),
159}
160
161/// What `signup` answers when the backend decides it.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum SignupAnswer {
164    Waiting(Waiting),
165    LoginUrl { url: String, state: String },
166    Session(Session),
167}
168
169/// Why a backend would not: said to the caller as an in-band error.
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct AuthFailure(pub String);
172
173impl AuthFailure {
174    pub fn new(message: impl Into<String>) -> Self {
175        Self(message.into())
176    }
177}
178
179impl fmt::Display for AuthFailure {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        f.write_str(&self.0)
182    }
183}
184
185impl std::error::Error for AuthFailure {}
186
187/// Why a store would not write.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct StoreError(pub String);
190
191impl StoreError {
192    pub fn new(message: impl Into<String>) -> Self {
193        Self(message.into())
194    }
195}
196
197impl fmt::Display for StoreError {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        f.write_str(&self.0)
200    }
201}
202
203impl std::error::Error for StoreError {}
204
205/// A membership as `whoami` says it.
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
207pub struct MembershipEntry {
208    pub role: String,
209    pub scope: String,
210}
211
212/// Every event the `auth` activation sends (`{"type": …}`).
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
214#[serde(tag = "type", rename_all = "snake_case")]
215pub enum AuthEvent {
216    /// `providers`: one way in.
217    Provider {
218        name: String,
219        kind: ProviderKind,
220        #[serde(default, skip_serializing_if = "Option::is_none")]
221        label: Option<String>,
222    },
223    /// `login {browser}` / `signup`: open this URL.
224    LoginUrl { url: String, state: String },
225    /// `login`: signed in.
226    Session {
227        token: String,
228        principal: String,
229        #[serde(default, skip_serializing_if = "Option::is_none")]
230        agent: Option<String>,
231        #[serde(default, skip_serializing_if = "Option::is_none")]
232        name: Option<String>,
233        expires_at: i64,
234        #[serde(default)]
235        ceiling: Vec<String>,
236    },
237    /// `signup` (asking for access) / `waiting` (an admin's list).
238    Waiting {
239        principal: String,
240        #[serde(default, skip_serializing_if = "Option::is_none")]
241        name: Option<String>,
242        #[serde(default, skip_serializing_if = "Option::is_none")]
243        provider: Option<String>,
244        since: i64,
245    },
246    /// `whoami`.
247    Whoami {
248        principal: String,
249        #[serde(default, skip_serializing_if = "Option::is_none")]
250        name: Option<String>,
251        #[serde(default, skip_serializing_if = "Option::is_none")]
252        agent: Option<String>,
253        memberships: Vec<MembershipEntry>,
254        ceiling: Vec<String>,
255    },
256    /// `logout`.
257    LoggedOut { principal: String },
258    /// `requires {method}`: its grant, its target, the roles that list it.
259    Requires {
260        method: String,
261        grant: String,
262        #[serde(default, skip_serializing_if = "Option::is_none")]
263        target: Option<String>,
264        roles: Vec<String>,
265        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
266        public: bool,
267    },
268    /// `roles` / `role_set`: a role and its grants (`all`: every grant —
269    /// admin).
270    Role {
271        role: String,
272        grants: Vec<String>,
273        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
274        all: bool,
275    },
276    /// `grant`.
277    Granted { principal: String, role: String, scope: String },
278    /// `revoke`: the roles it removed there.
279    Revoked { principal: String, scope: String, roles: Vec<String> },
280    /// Anything refused or failed. A refusal (`error_kind: "forbidden"`)
281    /// carries AUTH-2's fields.
282    Error {
283        message: String,
284        #[serde(default, skip_serializing_if = "Option::is_none")]
285        error_kind: Option<String>,
286        #[serde(default, skip_serializing_if = "Option::is_none")]
287        grant: Option<String>,
288        #[serde(default, skip_serializing_if = "Option::is_none")]
289        scope: Option<String>,
290        #[serde(default, skip_serializing_if = "Option::is_none")]
291        roles: Option<Vec<String>>,
292        #[serde(default, skip_serializing_if = "Option::is_none")]
293        held_on: Option<Vec<String>>,
294    },
295}
296
297impl AuthEvent {
298    fn error(message: impl Into<String>) -> Self {
299        Self::Error { message: message.into(), error_kind: None, grant: None, scope: None, roles: None, held_on: None }
300    }
301}
302
303/// MACRO-13: `AuthClient` implements the `Auth` trait; a client failure is
304/// the in-band error, the last item of its stream.
305impl plexus_client::FromClientError for AuthEvent {
306    fn from_client_error(error: plexus_client::ClientError) -> Self {
307        Self::error(error.to_string())
308    }
309}
310
311impl From<Session> for AuthEvent {
312    fn from(s: Session) -> Self {
313        Self::Session {
314            token: s.token,
315            principal: s.principal,
316            agent: s.agent,
317            name: s.name,
318            expires_at: s.expires_at,
319            ceiling: s.ceiling,
320        }
321    }
322}
323
324impl From<Waiting> for AuthEvent {
325    fn from(w: Waiting) -> Self {
326        Self::Waiting { principal: w.principal, name: w.name, provider: w.provider, since: w.since }
327    }
328}
329
330// ===========================================================================
331// What a service supplies
332// ===========================================================================
333
334/// What only the service knows about signing in. Async: a backend may talk
335/// to its identity provider. (The gate's own questions — [`Memberships`],
336/// [`Roles`], [`Resolve`] — stay synchronous and from memory.)
337#[async_trait]
338pub trait AuthBackend: Send + Sync + 'static {
339    /// The ways in this server offers (`auth.providers`).
340    fn providers(&self) -> Vec<Provider>;
341
342    /// Sign in by `flow` (`auth.login`). `caller` is the connection's
343    /// identity, if any: a [`LoginFlow::Session`] needs one (a key proof at
344    /// the upgrade, or a session) and must not widen it — the new
345    /// session's ceiling lies within the caller's (layer it). The browser
346    /// flow's start and finish, the code's single use and expiry, and the
347    /// session's minting are the backend's.
348    async fn login(&self, caller: Option<&AuthContext>, flow: LoginFlow) -> Result<LoginAnswer, AuthFailure>;
349
350    /// `auth.signup` where the activation's own rule does not decide it:
351    /// an anonymous caller (create an account — or refuse: sign in first),
352    /// or one who already holds a membership. (A signed-in caller holding
353    /// none is put on the waiting list by [`AuthBackend::ask_access`].)
354    async fn signup(&self, caller: Option<&AuthContext>, via: Option<String>) -> Result<SignupAnswer, AuthFailure>;
355
356    /// Put a signed-in caller who holds no membership on the waiting list
357    /// (asking again keeps the first `since`).
358    async fn ask_access(&self, caller: &AuthContext, via: Option<String>) -> Result<Waiting, AuthFailure>;
359
360    /// Everyone who has asked for access. The activation shows an admin
361    /// only those still holding no membership.
362    fn waiting(&self) -> Vec<Waiting>;
363
364    /// End the caller's session (`auth.logout`). A connection with no
365    /// session to end (a bare key proof) is not an error.
366    async fn logout(&self, caller: &AuthContext) -> Result<(), AuthFailure>;
367
368    /// AUTH-11: whether a signed-in caller's sign-in still stands — its
369    /// session not signed out, revoked or expired. The gate asks it before
370    /// every call it decides (`auth.*` included), so a sign-in that ended
371    /// holds nothing from its next call on. `Err`: why not, in words for
372    /// the caller. Memory only: it is asked on every call. (The gate
373    /// refuses a caller past its `expires_at` stamp before asking.)
374    fn alive(&self, caller: &AuthContext) -> Result<(), String>;
375}
376
377/// AUTH-11: the backend as the gate's [`Liveness`].
378struct BackendLiveness(Arc<dyn AuthBackend>);
379
380impl Liveness for BackendLiveness {
381    fn alive(&self, caller: &AuthContext) -> Result<(), String> {
382        self.0.alive(caller)
383    }
384}
385
386/// [`Roles`] an admin can edit (`auth.role_set`). The gate reads the same
387/// store, so an edit reaches the next call and the next view.
388#[async_trait]
389pub trait RoleStore: Roles + 'static {
390    /// Replace `role`'s grants. Never called for [`ADMIN`].
391    async fn set(&self, role: &RoleName, grants: GrantSet) -> Result<(), StoreError>;
392}
393
394/// [`Memberships`] an admin can edit (`auth.grant`, `auth.revoke`).
395#[async_trait]
396pub trait MembershipStore: Memberships + 'static {
397    /// Add a membership (holding it already is not an error).
398    async fn grant(&self, membership: Membership) -> Result<(), StoreError>;
399
400    /// Remove `principal`'s memberships on `scope` — the one role named, or
401    /// every role there. Answers the roles removed.
402    async fn revoke(
403        &self,
404        principal: &Principal,
405        role: Option<&RoleName>,
406        scope: &ScopeRef,
407    ) -> Result<Vec<RoleName>, StoreError>;
408}
409
410/// What [`DynamicHub::with_auth`](super::DynamicHub::with_auth) takes.
411#[derive(Clone)]
412pub struct AuthSetup {
413    pub backend: Arc<dyn AuthBackend>,
414    pub roles: Arc<dyn RoleStore>,
415    pub memberships: Arc<dyn MembershipStore>,
416    pub resolve: Arc<dyn Resolve>,
417}
418
419impl AuthSetup {
420    pub fn new(
421        backend: Arc<dyn AuthBackend>,
422        roles: Arc<dyn RoleStore>,
423        memberships: Arc<dyn MembershipStore>,
424        resolve: Arc<dyn Resolve>,
425    ) -> Self {
426        Self { backend, roles, memberships, resolve }
427    }
428}
429
430// ===========================================================================
431// The catalog: what each method requires
432// ===========================================================================
433
434/// What one method requires, as `auth.requires` says it.
435#[derive(Debug, Clone, PartialEq, Eq)]
436pub struct Requirement {
437    pub grant: String,
438    pub target: Option<String>,
439    pub public: bool,
440}
441
442/// Every method of the hub by grant — fed as activations register.
443#[derive(Clone, Default)]
444pub struct Catalog(Arc<RwLock<BTreeMap<String, Requirement>>>);
445
446impl Catalog {
447    /// Add an activation's methods (not its auto-generated `schema`, which
448    /// is introspection, nor its child routes).
449    pub(crate) fn add(&self, schema: &PluginSchema) {
450        let mut map = self.0.write().unwrap_or_else(|p| p.into_inner());
451        for m in &schema.methods {
452            if (m.name == "schema" && m.hash == "auto_schema") || !matches!(m.role, MethodRole::Rpc) {
453                continue;
454            }
455            let grant = m.grant_or(&schema.namespace);
456            map.insert(grant.clone(), Requirement { grant, target: m.target.clone(), public: m.public });
457        }
458    }
459
460    /// The requirement of `method` (`tickets.set_status`).
461    pub fn get(&self, method: &str) -> Option<Requirement> {
462        self.0.read().unwrap_or_else(|p| p.into_inner()).get(method).cloned()
463    }
464
465    /// Whether `grant` names a method of this hub.
466    pub fn knows(&self, grant: &str) -> bool {
467        self.0.read().unwrap_or_else(|p| p.into_inner()).contains_key(grant)
468    }
469}
470
471// ===========================================================================
472// The activation
473// ===========================================================================
474
475/// The `auth` activation. Mounted by
476/// [`DynamicHub::with_auth`](super::DynamicHub::with_auth); see the module
477/// docs.
478#[derive(Clone)]
479pub struct AuthActivation {
480    inner: Arc<AuthInner>,
481}
482
483struct AuthInner {
484    backend: Arc<dyn AuthBackend>,
485    roles: Arc<dyn RoleStore>,
486    memberships: Arc<dyn MembershipStore>,
487    gate: Gate,
488    catalog: Catalog,
489}
490
491/// The service's resolver, and `*` → `[*]` (a membership on everywhere is
492/// granted and revoked like any other scope).
493struct WithEverywhere(Arc<dyn Resolve>);
494
495impl Resolve for WithEverywhere {
496    fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
497        if target.trim() == "*" {
498            return Some(vec![ScopeRef::Everywhere]);
499        }
500        self.0.chain(target)
501    }
502}
503
504impl AuthActivation {
505    /// The activation and the gate over the same stores.
506    pub(crate) fn mount(setup: AuthSetup, catalog: Catalog) -> (Self, Gate) {
507        let memberships: Arc<dyn Memberships> = setup.memberships.clone();
508        let roles: Arc<dyn Roles> = setup.roles.clone();
509        let gate = Gate::new(memberships, roles, Arc::new(WithEverywhere(setup.resolve)))
510            .with_liveness(Arc::new(BackendLiveness(setup.backend.clone())));
511        let auth = Self {
512            inner: Arc::new(AuthInner {
513                backend: setup.backend,
514                roles: setup.roles,
515                memberships: setup.memberships,
516                gate: gate.clone(),
517                catalog,
518            }),
519        };
520        (auth, gate)
521    }
522}
523
524fn principal_of(ctx: &AuthContext) -> Option<Principal> {
525    ctx.principal()
526}
527
528fn meta(ctx: &AuthContext, key: &str) -> Option<String> {
529    ctx.get_metadata_string(key).filter(|s| !s.is_empty())
530}
531
532/// An in-band refusal: `grant` is needed on `*`.
533fn needs_everywhere(gate: &Gate, grant: &str, reach: &Reach) -> AuthEvent {
534    let g = Grant::new(grant);
535    AuthEvent::Error {
536        message: format!("needs {grant} on *"),
537        error_kind: Some("forbidden".into()),
538        grant: Some(grant.into()),
539        scope: Some("*".into()),
540        roles: Some(gate.roles_listing(&g).iter().map(|r| r.as_str().to_string()).collect()),
541        held_on: Some(reach.held_on().iter().map(|s| s.as_str().to_string()).collect()),
542    }
543}
544
545fn role_event(role: &RoleName, grants: Option<GrantSet>) -> AuthEvent {
546    match grants {
547        Some(GrantSet::All) => AuthEvent::Role { role: role.as_str().into(), grants: Vec::new(), all: true },
548        Some(GrantSet::Listed(set)) => AuthEvent::Role {
549            role: role.as_str().into(),
550            grants: set.iter().map(|g| g.as_str().to_string()).collect(),
551            all: false,
552        },
553        None => AuthEvent::Role { role: role.as_str().into(), grants: Vec::new(), all: false },
554    }
555}
556
557#[plexus_macros::activation(
558    version = "1.0.0",
559    description = "Sign in, who am I, what does this need",
560    roles(member = ["whoami", "logout", "requires"]),
561    // MACRO-12: every parameter is a type (`super::auth_params`); a bare
562    // string parameter does not compile here.
563    typed_params,
564)]
565impl AuthActivation {
566    /// The ways in this server offers.
567    #[plexus_macros::method(public, group = "sign in", description = "The ways in this server offers")]
568    async fn providers(&self) -> impl Stream<Item = AuthEvent> + Send + 'static {
569        let providers = self.inner.backend.providers();
570        stream! {
571            for p in providers {
572                yield AuthEvent::Provider { name: p.name, kind: p.kind, label: p.label };
573            }
574        }
575    }
576
577    /// Sign in — a person through the browser (`{browser: {redirect}}`,
578    /// then `{code: {code, state}}`), a password, or an agent's session on
579    /// a key-proved connection (`{session: {ttl_secs, ceiling}}`).
580    #[plexus_macros::method(
581        public,
582        group = "sign in",
583        description = "Sign in — a person through the browser, an agent with its key",
584        params(flow = "browser {redirect} | code {code, state} | password {username, password} | session {ttl_secs?, ceiling?}")
585    )]
586    async fn login(&self, auth: Option<&AuthContext>, flow: LoginFlow) -> impl Stream<Item = AuthEvent> + Send + 'static {
587        let inner = self.inner.clone();
588        let caller = auth.cloned();
589        stream! {
590            if let LoginFlow::Session { ceiling: Some(entries), .. } = &flow {
591                if let Err(e) = Ceiling::parse(entries) {
592                    yield AuthEvent::error(format!("ceiling: {e}"));
593                    return;
594                }
595            }
596            if matches!(flow, LoginFlow::Session { .. }) && caller.as_ref().and_then(principal_of).is_none() {
597                yield AuthEvent::error("a session needs a connection that is someone: a key proof at the upgrade, or a session");
598                return;
599            }
600            match inner.backend.login(caller.as_ref(), flow).await {
601                Ok(LoginAnswer::LoginUrl { url, state }) => yield AuthEvent::LoginUrl { url, state },
602                Ok(LoginAnswer::Session(s)) => yield s.into(),
603                Err(e) => yield AuthEvent::error(e.0),
604            }
605        }
606    }
607
608    /// Create an account, or ask for access: a signed-in caller holding no
609    /// membership of its own ([`Memberships::own_held`]) joins the waiting
610    /// list for an admin.
611    #[plexus_macros::method(
612        public,
613        group = "sign in",
614        description = "Create an account, or ask for access",
615        params(via = "The provider to sign up through, where the server offers several")
616    )]
617    async fn signup(&self, auth: Option<&AuthContext>, via: Option<param::ProviderName>) -> impl Stream<Item = AuthEvent> + Send + 'static {
618        let inner = self.inner.clone();
619        let caller = auth.cloned();
620        let via = via.map(param::ProviderName::into_string);
621        stream! {
622            let holds_none = caller
623                .as_ref()
624                .and_then(principal_of)
625                .map(|p| inner.memberships.own_held(&p).is_empty());
626            let answer = match (holds_none, caller.as_ref()) {
627                (Some(true), Some(ctx)) => inner.backend.ask_access(ctx, via).await.map(SignupAnswer::Waiting),
628                _ => inner.backend.signup(caller.as_ref(), via).await,
629            };
630            match answer {
631                Ok(SignupAnswer::Waiting(w)) => yield w.into(),
632                Ok(SignupAnswer::LoginUrl { url, state }) => yield AuthEvent::LoginUrl { url, state },
633                Ok(SignupAnswer::Session(s)) => yield s.into(),
634                Err(e) => yield AuthEvent::error(e.0),
635            }
636        }
637    }
638
639    /// Who this connection is: principal, name, the roles it holds where,
640    /// and its session's ceiling.
641    #[plexus_macros::method(group = "you", description = "Who you are: principal, roles held where, ceiling")]
642    async fn whoami(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
643        let inner = self.inner.clone();
644        let ctx = auth.clone();
645        stream! {
646            let Some(p) = principal_of(&ctx) else {
647                yield AuthEvent::error("sign in first");
648                return;
649            };
650            let memberships = inner
651                .memberships
652                .held(&p)
653                .into_iter()
654                .map(|m| MembershipEntry { role: m.role.as_str().into(), scope: m.scope.as_str().into() })
655                .collect();
656            let ceiling = Ceiling::layers_of(&ctx)
657                .map(|layers| layers.iter().flat_map(|l| l.text()).collect())
658                .unwrap_or_default();
659            yield AuthEvent::Whoami {
660                principal: p.to_string(),
661                name: meta(&ctx, "name"),
662                agent: meta(&ctx, "agent"),
663                memberships,
664                ceiling,
665            };
666        }
667    }
668
669    /// End this session.
670    #[plexus_macros::method(group = "you", description = "Sign out: end this session")]
671    async fn logout(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
672        let inner = self.inner.clone();
673        let ctx = auth.clone();
674        stream! {
675            let principal = principal_of(&ctx).map(|p| p.to_string()).unwrap_or_default();
676            match inner.backend.logout(&ctx).await {
677                Ok(()) => yield AuthEvent::LoggedOut { principal },
678                Err(e) => yield AuthEvent::error(e.0),
679            }
680        }
681    }
682
683    /// What a method needs: its grant, its target and the roles that list
684    /// it.
685    #[plexus_macros::method(
686        group = "you",
687        description = "What a method needs: its grant, target, and the roles that list it",
688        params(method = "The method, as <activation>.<method>: tickets.set_status"),
689        example(note = "what changing a ticket's status needs", params = r#"{"method": "tickets.set_status"}"#)
690    )]
691    async fn requires(&self, auth: &AuthContext, method: param::MethodPath) -> impl Stream<Item = AuthEvent> + Send + 'static {
692        let _ = auth;
693        let inner = self.inner.clone();
694        stream! {
695            match inner.catalog.get(method.as_str()) {
696                None => yield AuthEvent::error(format!("no method {method} here")),
697                Some(req) => {
698                    let roles = inner.gate.roles_listing(&Grant::new(req.grant.clone()));
699                    yield AuthEvent::Requires {
700                        method: method.into_string(),
701                        grant: req.grant,
702                        target: req.target,
703                        roles: roles.iter().map(|r| r.as_str().to_string()).collect(),
704                        public: req.public,
705                    };
706                }
707            }
708        }
709    }
710
711    /// Every role and the grants it lists (admin: every grant).
712    #[plexus_macros::method(group = "admin", description = "Every role and the grants it lists")]
713    async fn roles(&self, auth: &AuthContext) -> impl Stream<Item = AuthEvent> + Send + 'static {
714        let _ = auth;
715        let inner = self.inner.clone();
716        stream! {
717            let admin = RoleName::new(ADMIN);
718            yield role_event(&admin, Some(GrantSet::All));
719            let names: BTreeSet<RoleName> = inner.roles.names().into_iter().filter(|r| r.as_str() != ADMIN).collect();
720            for r in names {
721                let grants = inner.roles.grants(&r);
722                yield role_event(&r, grants);
723            }
724        }
725    }
726
727    /// Set a role's grants (admin on `*`). Each entry a grant
728    /// (`tickets.get`) or an existing role whose grants it includes.
729    #[plexus_macros::method(
730        group = "admin",
731        description = "Set a role's grants (admin on *)",
732        params(role = "The role (not admin)", grants = "Grants (tickets.get) or roles to include")
733    )]
734    async fn role_set(&self, auth: &AuthContext, reach: Reach, role: param::RoleName, grants: Vec<param::GrantName>) -> impl Stream<Item = AuthEvent> + Send + 'static {
735        let _ = auth;
736        let inner = self.inner.clone();
737        stream! {
738            if !reach.is_everywhere() {
739                yield needs_everywhere(&inner.gate, "auth.role_set", &reach);
740                return;
741            }
742            // The name's shape (one word, no `.` or `@`) is `param::RoleName`'s,
743            // refused as InvalidParams before this runs.
744            if role.as_str() == ADMIN {
745                yield AuthEvent::error("admin holds every grant; it is not edited");
746                return;
747            }
748            let mut set: BTreeSet<Grant> = BTreeSet::new();
749            for entry in grants.iter() {
750                let entry = entry.as_str();
751                if entry.contains('.') {
752                    if !inner.catalog.knows(entry) {
753                        yield AuthEvent::error(format!("no method {entry} here"));
754                        return;
755                    }
756                    set.insert(Grant::new(entry));
757                } else {
758                    match inner.roles.grants(&RoleName::new(entry)) {
759                        Some(GrantSet::Listed(included)) => set.extend(included),
760                        Some(GrantSet::All) => {
761                            yield AuthEvent::error(format!("{entry} holds every grant; a role cannot include it"));
762                            return;
763                        }
764                        None => {
765                            yield AuthEvent::error(format!("no role {entry} to include"));
766                            return;
767                        }
768                    }
769                }
770            }
771            let name = role.role();
772            if let Err(e) = inner.roles.set(&name, GrantSet::Listed(set)).await {
773                yield AuthEvent::error(e.0);
774                return;
775            }
776            let now = inner.roles.grants(&name);
777            yield role_event(&name, now);
778        }
779    }
780
781    /// Give `principal` `role` on `scope` (whoever holds `auth.grant` on
782    /// the scope: admin there).
783    #[plexus_macros::method(
784        target = "scope",
785        group = "admin",
786        description = "Give a principal a role on a scope",
787        params(principal = "key:…, oidc:…/…, idp:…", role = "The role", scope = "Where: a scope name, or *"),
788        example(note = "make a person an editor on MENGER", params = r#"{"principal": "oidc:workos/user_01M4", "role": "editor", "scope": "MENGER"}"#),
789        example(note = "make an agent's key an admin everywhere", params = r#"{"principal": "key:ac79e0d1f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d", "role": "admin", "scope": "*"}"#)
790    )]
791    async fn grant(&self, auth: &AuthContext, principal: param::Principal, role: param::RoleName, scope: param::ScopeName) -> impl Stream<Item = AuthEvent> + Send + 'static {
792        let _ = auth;
793        let inner = self.inner.clone();
794        stream! {
795            let who: Principal = principal.principal();
796            let role_name = role.role();
797            if role_name.as_str() != ADMIN && inner.roles.grants(&role_name).is_none() {
798                yield AuthEvent::error(format!("no role {role} here"));
799                return;
800            }
801            let scope_ref = scope.scope();
802            let m = Membership { principal: who.clone(), role: role_name.clone(), scope: scope_ref.clone() };
803            match inner.memberships.grant(m).await {
804                Ok(()) => yield AuthEvent::Granted {
805                    principal: who.to_string(),
806                    role: role_name.as_str().into(),
807                    scope: scope_ref.as_str().into(),
808                },
809                Err(e) => yield AuthEvent::error(e.0),
810            }
811        }
812    }
813
814    /// Take `principal`'s role (or every role) on `scope` away.
815    #[plexus_macros::method(
816        target = "scope",
817        group = "admin",
818        description = "Take a principal's role on a scope away",
819        params(principal = "key:…, oidc:…/…, idp:…", role = "The role; absent: every role there", scope = "Where: a scope name, or *")
820    )]
821    async fn revoke(&self, auth: &AuthContext, principal: param::Principal, role: Option<param::RoleName>, scope: param::ScopeName) -> impl Stream<Item = AuthEvent> + Send + 'static {
822        let _ = auth;
823        let inner = self.inner.clone();
824        stream! {
825            let who: Principal = principal.principal();
826            let scope_ref = scope.scope();
827            let role_name = role.as_ref().map(param::RoleName::role);
828            match inner.memberships.revoke(&who, role_name.as_ref(), &scope_ref).await {
829                Ok(removed) => yield AuthEvent::Revoked {
830                    principal: who.to_string(),
831                    scope: scope_ref.as_str().into(),
832                    roles: removed.iter().map(|r| r.as_str().to_string()).collect(),
833                },
834                Err(e) => yield AuthEvent::error(e.0),
835            }
836        }
837    }
838
839    /// Who signed up or asked for access and holds nothing of its own yet
840    /// ([`Memberships::own_held`]; admin on `*`).
841    #[plexus_macros::method(group = "admin", description = "Who asked for access and holds nothing yet (admin on *)")]
842    async fn waiting(&self, auth: &AuthContext, reach: Reach) -> impl Stream<Item = AuthEvent> + Send + 'static {
843        let _ = auth;
844        let inner = self.inner.clone();
845        stream! {
846            if !reach.is_everywhere() {
847                yield needs_everywhere(&inner.gate, "auth.waiting", &reach);
848                return;
849            }
850            for w in inner.backend.waiting() {
851                let still = w
852                    .principal
853                    .parse::<Principal>()
854                    .map(|p| inner.memberships.own_held(&p).is_empty())
855                    .unwrap_or(true);
856                if still {
857                    yield w.into();
858                }
859            }
860        }
861    }
862}