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