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