Skip to main content

plexus_core/plexus/
grant_gate.rs

1//! AUTH-2 — the grant gate in dispatch: default deny, every method.
2//!
3//! A [`DynamicHub`](super::DynamicHub) given a gate
4//! ([`DynamicHub::with_gate`](super::DynamicHub::with_gate)) asks it before
5//! routing every call: the method's grant (its schema's `grant`, else
6//! `<activation>.<method>`), held through a role on the scope its target
7//! resolves to (its schema's `target` param, read from the call's params),
8//! within the session's ceiling. A service without a gate never enters this
9//! module and dispatches exactly as before.
10//!
11//! # Decision table (gate set)
12//!
13//! | call | anonymous | signed in |
14//! |---|---|---|
15//! | `public` method | runs (empty reach) | runs (its reach) |
16//! | introspection: `<ns>.schema`, the service's `hash` / `hashes` / `schema` / `ir` | runs | runs |
17//! | method with a `target`, value present | `Unauthenticated` | allowed iff a role held on a scope in the value's chain lists the grant, and every ceiling layer allows it there |
18//! | method without a target (or the target param absent / null) | `Unauthenticated` | allowed iff the grant is held anywhere (within the ceiling) |
19//! | method no schema describes (a nested child path) | `Unauthenticated` | as "without a target", grant = the dotted path |
20//! | a signed-in grant (AUTH-5: `auth.whoami`, `auth.logout`, `auth.requires`) | `Unauthenticated` | runs (its reach), whatever the roles or ceiling |
21//!
22//! A target whose value is a list is checked element by element; every
23//! element must be allowed.
24//!
25//! AUTH-13: before any of this, `params` must be an object (or absent):
26//! the gate reads a target by name, and a bare value (`"MENGER-1"`, `[…]`)
27//! names none — it would be decided as "held anywhere" while the method
28//! deserialized it into its only parameter. A target that is neither a
29//! scalar nor a list of scalars is refused too. Both are `InvalidParams`
30//! (`error_kind: invalid_params`), whoever calls. Introspection stays open here: what it answers
31//! is the caller's view (AUTH-4, [`super::view`]) — `_info` and every
32//! `schema` answered per caller; this gate decides calls, not what is listed.
33//!
34//! # How a method receives its [`Reach`]
35//!
36//! The gate's answer — where the grant is held — rides into the method as
37//! [`Reach`]: the dispatch runs the routed call inside a task-local scope,
38//! and `#[plexus_macros::method]` hands a method that declares a `reach:
39//! Reach` parameter (stripped from the schema, like `auth`) the value of
40//! [`current_reach`]. Outside a gated dispatch, [`current_reach`] is
41//! [`Reach::everywhere`] — what a service without a gate has always meant. The
42//! reach is live: [`Reach::allows`] / [`Reach::current`] ask the gate again
43//! as it stands, which is how a stream checks each event (IDENTITY-37).
44
45use plexus_auth_core::grants::{Gate, Grant, Reach, Refusal};
46use serde_json::Value;
47
48use super::auth::AuthContext;
49use super::plexus::{AuthzDenyReason, PlexusError};
50use super::scope_gate::MethodGateInfo;
51
52tokio::task_local! {
53    static CURRENT_REACH: Reach;
54}
55
56/// The reach of the call being dispatched: what the gate answered for its
57/// grant. [`Reach::everywhere`] when no gate decided this call (a service
58/// without a gate, or a call that did not come through a gated dispatch).
59///
60/// `#[plexus_macros::method]` calls this for a method that declares a
61/// `reach: Reach` parameter, before the method's stream is built — read it
62/// there, not from inside a stream, which runs outside the dispatch's scope.
63pub fn current_reach() -> Reach {
64    CURRENT_REACH.try_with(Reach::clone).unwrap_or_else(|_| Reach::everywhere())
65}
66
67/// Run `fut` with `reach` as the [`current_reach`].
68pub async fn with_reach<F: std::future::Future>(reach: Reach, fut: F) -> F::Output {
69    CURRENT_REACH.scope(reach, fut).await
70}
71
72/// What the gate decided for a call that may proceed: run it under this
73/// reach, or (introspection) without one.
74pub(crate) enum Admit {
75    Reach(Reach),
76    Open,
77}
78
79impl From<Refusal> for PlexusError {
80    fn from(r: Refusal) -> Self {
81        match r {
82            Refusal::Unauthenticated => {
83                PlexusError::Unauthenticated("sign in first: this method is not public".into())
84            }
85            Refusal::MissingGrant { grant, scope, roles, held_on } => PlexusError::Forbidden {
86                reason: AuthzDenyReason::MissingGrant { grant, scope, roles, held_on },
87            },
88            Refusal::Ended { reason } => PlexusError::Unauthenticated(reason),
89        }
90    }
91}
92
93/// AUTH-11: the identity a call acts as — `auth` while its sign-in stands
94/// ([`Gate::alive`]); once it has ended (signed out, expired, revoked),
95/// nobody: the call is decided and dispatched as anonymous, and the second
96/// value says why. A socket that signed out sees the anonymous view and
97/// reaches only the `public` methods — not `auth.grant`.
98pub(crate) fn standing<'a>(gate: &Gate, auth: Option<&'a AuthContext>) -> (Option<&'a AuthContext>, Option<String>) {
99    match auth.map(|a| gate.alive(a)) {
100        Some(Err(reason)) => (None, Some(reason)),
101        _ => (auth, None),
102    }
103}
104
105/// AUTH-11: an anonymous refusal of a sign-in that ended says so, rather
106/// than "sign in first".
107pub(crate) fn say_ended(e: PlexusError, ended: Option<&str>) -> PlexusError {
108    match (e, ended) {
109        (PlexusError::Unauthenticated(_), Some(reason)) => PlexusError::Unauthenticated(reason.to_string()),
110        (e, _) => e,
111    }
112}
113
114/// The target values a call names: `None` when the param is absent or
115/// null; one string per element when it is a list. AUTH-13: a value the
116/// gate cannot read as a scope — an object, or a list holding anything but
117/// scalars — is refused, never skipped (skipped, it would be decided as
118/// "no target": held anywhere).
119pub(crate) fn target_values(params: &Value, param: &str) -> Result<Option<Vec<String>>, PlexusError> {
120    let Some(v) = params.get(param) else { return Ok(None) };
121    let one = |v: &Value| match v {
122        Value::String(s) => Some(s.clone()),
123        Value::Number(n) => Some(n.to_string()),
124        Value::Bool(b) => Some(b.to_string()),
125        _ => None,
126    };
127    let unreadable = || {
128        PlexusError::malformed_param(param, "names what this call acts on: a string, or a list of strings")
129    };
130    match v {
131        Value::Null => Ok(None),
132        Value::Array(items) => items.iter().map(|i| one(i).ok_or_else(unreadable)).collect::<Result<_, _>>().map(Some),
133        other => one(other).map(|s| Some(vec![s])).ok_or_else(unreadable),
134    }
135}
136
137/// AUTH-13: under a gate, a call's params are an object (or absent). A
138/// bare value names no target, so the gate would decide it as "held
139/// anywhere" — while a method of one parameter would take it as that
140/// parameter.
141fn params_shape(params: &Value) -> Result<(), PlexusError> {
142    match params {
143        Value::Object(_) | Value::Null => Ok(()),
144        _ => Err(PlexusError::invalid_params(
145            "params must be an object naming each parameter, e.g. {\"id\": \"…\"}: a gated method takes no bare value",
146        )),
147    }
148}
149
150/// Decide one call. `full_path` is the dotted method as dispatched;
151/// `service_ns` the service's own namespace.
152pub(crate) fn decide(
153    gate: &Gate,
154    service_ns: &str,
155    full_path: &str,
156    info: Option<&MethodGateInfo>,
157    params: &Value,
158    auth: Option<&AuthContext>,
159    signed_in_grants: &std::collections::BTreeSet<String>,
160) -> Result<Admit, PlexusError> {
161    params_shape(params)?;
162    let (ns, method) = full_path.split_once('.').unwrap_or((full_path, ""));
163    let introspection = method == "schema"
164        || method.ends_with(".schema")
165        || (ns == service_ns && matches!(method, "hash" | "hashes" | "ir"));
166    if introspection {
167        return Ok(Admit::Open);
168    }
169    let grant = Grant::new(info.and_then(|i| i.grant.clone()).unwrap_or_else(|| full_path.to_string()));
170    if info.is_some_and(|i| i.public) {
171        return Ok(Admit::Reach(gate.reach_of_public(auth, &grant)));
172    }
173    // AUTH-5: what every signed-in caller reaches (`auth.whoami`,
174    // `auth.logout`, `auth.requires`) — whatever its roles or ceiling, but
175    // never anonymously.
176    if signed_in_grants.contains(grant.as_str()) {
177        if auth.and_then(|a| a.principal()).is_none() {
178            return Err(Refusal::Unauthenticated.into());
179        }
180        return Ok(Admit::Reach(gate.reach_of_public(auth, &grant)));
181    }
182    let targets = match info.and_then(|i| i.target.as_deref()) {
183        Some(param) => target_values(params, param)?,
184        None => None,
185    };
186    match targets {
187        None => Ok(Admit::Reach(gate.check(auth, &grant, None)?)),
188        Some(values) if values.is_empty() => Ok(Admit::Reach(gate.check(auth, &grant, None)?)),
189        Some(values) => {
190            let mut reach = None;
191            for v in &values {
192                reach = Some(gate.check(auth, &grant, Some(v))?);
193            }
194            Ok(Admit::Reach(reach.expect("non-empty")))
195        }
196    }
197}
198
199/// A refusal as a client reads it back from an error stream item — the
200/// typed view of the `forbidden` shape [`super::types::spec_fields`] writes.
201#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
202pub struct ForbiddenItem {
203    pub grant: String,
204    pub scope: String,
205    #[serde(default)]
206    pub roles: Vec<String>,
207    #[serde(default)]
208    pub held_on: Vec<String>,
209    pub message: String,
210}
211
212impl ForbiddenItem {
213    /// The refusal an error item carries, when it is a missing grant.
214    pub fn from_item(item: &Value) -> Option<Self> {
215        if item.get("type")?.as_str()? != "error" || item.get("error_kind")?.as_str()? != "forbidden" {
216            return None;
217        }
218        item.get("grant")?;
219        serde_json::from_value(item.clone()).ok()
220    }
221}