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