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 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 and no slot holds (KEEL-54) | `Unauthenticated` | grant = the dotted path, held on `*` alone (as `everywhere`) — never "held anywhere" |
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//! KEEL-54: every row is decided on the path the service routes —
27//! [`DynamicHub::call_path`](super::DynamicHub), the caller's spelling read
28//! once (`svc.vault.get` is `vault.get`) — and the router runs the call only
29//! under a reach made for that path's own grant.
30//!
31//! # The door (ONE-7)
32//!
33//! Owner, 2026-11-11: "activation and data scopes are separate. we can only
34//! generally handle activation scopes. data scopes must be handled by the
35//! application". A role may be held on an **address** (`/dyn`, `/dyn.*`,
36//! `/dyn.peer.shop.*`; plexus-auth-core 0.3.4) — never data. The gate passes
37//! the address of the call it dispatches only for the two shapes that touch
38//! no data of this service, and decides them at the **door**
39//! ([`Gate::check_everywhere_at`]):
40//!
41//! | the routed entry | decided by | an address scope covering the call | a data scope | `*` |
42//! |---|---|---|---|---|
43//! | a method marked `everywhere`, no target (`dyn.connect`, `auth.role_set`) | the door | admits | never (KEEL-31) | admits |
44//! | a call into an untyped peer slot (`dyn.peer.shop.items.list`, slot grant `dyn.{peer}`) | the door | admits | **never** (KEEL-44) | admits |
45//! | a method with a declared target | [`Gate::check`] on the target, as before | nothing | its chain | admits |
46//! | a method with no target | [`Gate::check`], "held anywhere", as before | nothing | admits | admits |
47//! | a method marked `everywhere` **and** a target (mis-declared) | `*` alone (KEEL-31), told no address | nothing | never | admits |
48//! | a literal path through a slot (consent's `callers`, KEEL-31's literal grant) | as before: [`Gate::check`] / `*` | nothing | as before | admits |
49//!
50//! The dispatcher makes **one** [`DispatchedCall`] per dispatch, here
51//! ([`dispatched`]): its address from the literal routed path, split at
52//! every dot ([`CallAddress::of_segments`]), its grant the routed entry's.
53//! A path whose address cannot be built — a segment outside `A–Z a–z 0–9 _
54//! -`, an empty one, or one at or under a name that is both a method and a
55//! child ([`named_twice`]) — has no address, and its door is decided on `*`
56//! alone, never on a shorter address and never as "held anywhere".
57//!
58//! A call the door admitted carries the door into a remote child for exactly
59//! that call ([`crate::call::Door`]; plexus-wire spec/12 `limit.door`).
60//!
61//! AUTH-13: before any of this, `params` must be an object (or absent):
62//! the gate reads a target by name, and a bare value (`"MENGER-1"`, `[…]`)
63//! names none — it would be decided as "held anywhere" while the method
64//! deserialized it into its only parameter. A target that is neither a
65//! scalar nor a list of scalars is refused too. Both are `InvalidParams`
66//! (`error_kind: invalid_params`), whoever calls. Introspection stays open here: what it answers
67//! is the caller's view (AUTH-4, [`super::view`]) — `_info` and every
68//! `schema` answered per caller; this gate decides calls, not what is listed.
69//!
70//! # How a method receives its [`Reach`]
71//!
72//! The gate's answer — where the grant is held — rides into the method as
73//! [`Reach`]: the dispatch runs the routed call inside its context
74//! ([`crate::call`], RETURNS-47) — the stream it answers included — and
75//! `#[plexus_macros::method]` hands a method that declares a `reach: Reach`
76//! parameter (stripped from the schema, like `auth`) the value of
77//! [`current_reach`]. A service without a gate dispatches with
78//! [`Reach::everywhere`], said by its dispatch; outside a call
79//! [`current_reach`] is an error, never everything (RETURNS-47: it fell back
80//! to everywhere). The reach is live: [`Reach::allows`] / [`Reach::current`]
81//! ask the gate again as it stands, which is how a stream checks each event
82//! (IDENTITY-37).
83
84use plexus_auth_core::grants::{CallAddress, DispatchedCall, Gate, Grant, Reach, Refusal};
85use serde_json::Value;
86
87use super::auth::AuthContext;
88use super::plexus::{AuthzDenyReason, PlexusError};
89use super::scope_gate::MethodGateInfo;
90
91/// The reach of the call being dispatched: what the gate answered for its
92/// grant — [`Reach::everywhere`] on a service without a gate, which its
93/// dispatch says. RETURNS-47: **fail closed** — outside a call (code no
94/// dispatch runs, a task spawned without its context handed to it,
95/// [`crate::call::scope`]), and in a call that came through a hop (its
96/// bound is [`crate::call::Hop::allows`]), it is an error
97/// (`Unauthenticated`), never everything.
98///
99/// `#[plexus_macros::method]` calls this for a method that declares a
100/// `reach: Reach` parameter, before the method's stream is built; the
101/// stream runs in the call's context too, so reading it there answers the
102/// same.
103pub fn current_reach() -> Result<Reach, PlexusError> {
104    let ctx = crate::call::context()?;
105    ctx.reach().cloned().ok_or_else(|| crate::call::CallError::ThroughHop.into())
106}
107
108/// Run `fut` with `reach` as the [`current_reach`] of the call it runs in:
109/// it narrows that call's reach, never widens it and never creates a call.
110/// RETURNS-47: refused (`Unauthenticated`) outside a call, and when `reach`
111/// holds a scope the call's does not (unless the call's is everywhere) —
112/// it used to build an anonymous caller by hand. A test enters a call with
113/// `plexus_core::call::test::in_call` (feature `test-util`).
114///
115/// ONE-7 (ONE-6 review round 2, L1): and on the door — a reach that holds
116/// the activation ([`Reach::holds_activation`]) is taken only where the
117/// call's does too, and a door reach (the activation held at an address, not
118/// on `*`) only for the call's own grant: a door is one call's, never handed
119/// to work inside another.
120pub async fn with_reach<F: std::future::Future>(reach: Reach, fut: F) -> Result<F::Output, PlexusError> {
121    let ctx = crate::call::context()?;
122    let current = ctx.reach().ok_or(crate::call::CallError::ThroughHop)?;
123    if let Err(why) = narrows(current, &reach) {
124        return Err(PlexusError::Unauthenticated(why.into()));
125    }
126    Ok(crate::call::scope(ctx.with_reach(reach), fut).await)
127}
128
129/// [`with_reach`]'s rule: `Ok` when `reach` is within `current`.
130fn narrows(current: &Reach, reach: &Reach) -> Result<(), &'static str> {
131    let within = current.is_everywhere() || reach.held_on().iter().all(|s| current.held_on().contains(s));
132    if !within {
133        return Err("with_reach narrows a call's reach; it holds a scope the call does not");
134    }
135    if reach.holds_activation() && !current.holds_activation() {
136        return Err("with_reach narrows a call's reach; it holds the activation, and the call does not");
137    }
138    if is_door(reach) && reach.grant() != current.grant() {
139        return Err("with_reach narrows a call's reach; it is the door of another grant than the call's");
140    }
141    Ok(())
142}
143
144/// ONE-7: whether `reach` holds its activation at a door — on an address,
145/// not on `*`.
146pub(crate) fn is_door(reach: &Reach) -> bool {
147    reach.holds_activation() && !reach.is_everywhere()
148}
149
150/// ONE-7 (review M1): whether the door `call` was admitted at is the
151/// method's own — its grant names the call's own path, segment for segment
152/// (a `{slot}` segment standing for the one name in its place: a typed
153/// slot's `solar.{planet}.wipe` at `solar.mars.wipe`) — and not a slot's
154/// whole grant above it (`dyn.{peer}` at `dyn.peer.vault.wipe`). Only an
155/// own door runs a whole-activation method ([`crate::call::admits_everywhere`]);
156/// a slot's opens the peer's ordinary methods and nothing more.
157pub(crate) fn door_is_own(call: &DispatchedCall) -> bool {
158    let path = call.at().path();
159    let grant = call.grant().as_str();
160    path.split('.').count() == grant.split('.').count()
161        && path.split('.').zip(grant.split('.')).all(|(p, g)| p == g || is_slot_segment(g))
162}
163
164/// The shape of an own door's grant (`call`'s, [`door_is_own`]): the grant,
165/// and — through an untyped peer slot (`peer_slot`, `dyn.{peer}`) — the
166/// peer's name's segment open: `dyn.peer.{peer}.wipe` for the literal
167/// `dyn.peer.vault.wipe`.
168pub(crate) fn door_shape(call: &DispatchedCall, peer_slot: Option<&str>) -> String {
169    let grant = call.grant().as_str();
170    let Some(slot) = peer_slot else { return grant.to_string() };
171    let at = slot.split('.').count();
172    grant
173        .split('.')
174        .enumerate()
175        .map(|(i, s)| if i == at { "{peer}" } else { s })
176        .collect::<Vec<_>>()
177        .join(".")
178}
179
180/// A grant's segment that stands for any one name (`{planet}`).
181pub(crate) fn is_slot_segment(segment: &str) -> bool {
182    segment.len() > 2 && segment.starts_with('{') && segment.ends_with('}')
183}
184
185/// What the gate decided for a call that may proceed: run it under this
186/// reach — with the call the door admitted it at, if a door did (ONE-7) —
187/// or (introspection) without one.
188///
189/// KEEL-59: and what the call is held to while it runs
190/// ([`super::held`]): `Some(targets)` — every target the decision checked,
191/// none for a call without one — is asked again when the grants generation
192/// moves; `None` (a `public` method, a grant every signed-in caller holds)
193/// is never asked again.
194pub(crate) enum Admit {
195    Reach(Reach, Option<DispatchedCall>, Option<Vec<String>>),
196    Open,
197}
198
199/// ONE-7 · **the one place a [`DispatchedCall`] is made**: the call at the
200/// literal routed `path` (`dyn.peer.shop.items.list`), its address split at
201/// every dot ([`CallAddress::of_segments`]: the activation every segment but
202/// the last, the method the last), paired with `grant`, the grant of the
203/// entry the path was routed to. `None` when no address can be built — a
204/// segment `of_segments` refuses (empty, `*`, `@`, `{`, a space, non-ASCII),
205/// a path of one segment, or a path at or under a name its activation uses
206/// for a method and a child alike (`ambiguous`, [`named_twice`]): that call
207/// is decided as told no address — never on a shorter one.
208///
209/// A key cannot hold a dot here: every router of the path (this service's,
210/// a child's, a peer's) splits it at every dot, so a dot in a key is two
211/// segments everywhere, and an address scope deeper than a peer's name
212/// covers what that peer routes beneath it.
213pub(crate) fn dispatched(path: &str, grant: &Grant, ambiguous: &std::collections::HashSet<String>) -> Option<DispatchedCall> {
214    let segments: Vec<&str> = path.split('.').collect();
215    let (method, activation) = segments.split_last()?;
216    let at = CallAddress::of_segments(activation, method).ok()?;
217    let mut prefix = String::with_capacity(path.len());
218    for (i, s) in segments.iter().enumerate() {
219        if i > 0 {
220            prefix.push('.');
221        }
222        prefix.push_str(s);
223        if i > 0 && ambiguous.contains(&prefix) {
224            return None;
225        }
226    }
227    Some(DispatchedCall::new(at, grant.clone()))
228}
229
230/// ONE-7: the names `schema` gives both a method and a child (a static
231/// child, a dynamic child's slot, a peer slot) — `/P` would cover both, so
232/// such a name is refused at registration and has no address at dispatch.
233pub fn named_twice(schema: &super::schema::PluginSchema) -> Vec<String> {
234    use super::schema::MethodRole;
235    let child = |r: &MethodRole| matches!(r, MethodRole::StaticChild | MethodRole::DynamicChild { .. } | MethodRole::Peer { .. });
236    let mut twice: Vec<String> = schema
237        .methods
238        .iter()
239        .filter(|m| matches!(m.role, MethodRole::Rpc) && schema.methods.iter().any(|c| c.name == m.name && child(&c.role)))
240        .map(|m| m.name.clone())
241        .collect();
242    twice.sort();
243    twice.dedup();
244    twice
245}
246
247impl From<Refusal> for PlexusError {
248    fn from(r: Refusal) -> Self {
249        match r {
250            Refusal::Unauthenticated => {
251                PlexusError::Unauthenticated("sign in first: this method is not public".into())
252            }
253            Refusal::MissingGrant { grant, scope, roles, held_on } => PlexusError::Forbidden {
254                reason: AuthzDenyReason::MissingGrant { grant, scope, roles, held_on },
255            },
256            Refusal::Ended { reason } => PlexusError::Unauthenticated(reason),
257        }
258    }
259}
260
261/// AUTH-11: the identity a call acts as — `auth` while its sign-in stands
262/// ([`Gate::alive`]); once it has ended (signed out, expired, revoked),
263/// nobody: the call is decided and dispatched as anonymous, and the second
264/// value says why. A socket that signed out sees the anonymous view and
265/// reaches only the `public` methods — not `auth.grant`.
266pub(crate) fn standing<'a>(gate: &Gate, auth: Option<&'a AuthContext>) -> (Option<&'a AuthContext>, Option<String>) {
267    match auth.map(|a| gate.alive(a)) {
268        Some(Err(reason)) => (None, Some(reason)),
269        _ => (auth, None),
270    }
271}
272
273/// AUTH-11: an anonymous refusal of a sign-in that ended says so, rather
274/// than "sign in first".
275pub(crate) fn say_ended(e: PlexusError, ended: Option<&str>) -> PlexusError {
276    match (e, ended) {
277        (PlexusError::Unauthenticated(_), Some(reason)) => PlexusError::Unauthenticated(reason.to_string()),
278        (e, _) => e,
279    }
280}
281
282/// The target values a call names: `None` when the param is absent or
283/// null; one string per element when it is a list. AUTH-13: a value the
284/// gate cannot read as a scope — an object, or a list holding anything but
285/// scalars — is refused, never skipped (skipped, it would be decided as
286/// "no target": held anywhere).
287pub(crate) fn target_values(params: &Value, param: &str) -> Result<Option<Vec<String>>, PlexusError> {
288    let Some(v) = params.get(param) else { return Ok(None) };
289    let one = |v: &Value| match v {
290        Value::String(s) => Some(s.clone()),
291        Value::Number(n) => Some(n.to_string()),
292        Value::Bool(b) => Some(b.to_string()),
293        _ => None,
294    };
295    let unreadable = || {
296        PlexusError::malformed_param(param, "names what this call acts on: a string, or a list of strings")
297    };
298    match v {
299        Value::Null => Ok(None),
300        Value::Array(items) => items.iter().map(|i| one(i).ok_or_else(unreadable)).collect::<Result<_, _>>().map(Some),
301        other => one(other).map(|s| Some(vec![s])).ok_or_else(unreadable),
302    }
303}
304
305/// AUTH-13: under a gate, a call's params are an object (or absent). A
306/// bare value names no target, so the gate would decide it as "held
307/// anywhere" — while a method of one parameter would take it as that
308/// parameter.
309fn params_shape(params: &Value) -> Result<(), PlexusError> {
310    match params {
311        Value::Object(_) | Value::Null => Ok(()),
312        _ => Err(PlexusError::invalid_params(
313            "params must be an object naming each parameter, e.g. {\"id\": \"…\"}: a gated method takes no bare value",
314        )),
315    }
316}
317
318/// ONE-7: a door's refusal as KEEL-31's says it — needed at `*` — whatever
319/// address the gate names (plexus-auth-core names the activation's, `/dyn`):
320/// the refusal a client reads for a whole-service method stays one shape,
321/// and `held_on` (the data held) as it was. Only the scope's name changes.
322fn said_at_everywhere(r: Refusal) -> Refusal {
323    match r {
324        Refusal::MissingGrant { grant, roles, held_on, .. } => {
325            Refusal::MissingGrant { grant, scope: plexus_auth_core::grants::ScopeRef::Everywhere, roles, held_on }
326        }
327        other => other,
328    }
329}
330
331/// ONE-7 · **which entries the door decides** — the one rule, applied when
332/// the gate's index is built ([`MethodGateInfo::door`]): a method marked
333/// `everywhere` that declares no target, and an untyped peer slot. A method
334/// that declares a target is never decided at the door, whatever else it
335/// says: its target is checked ([`Gate::check`]), or, marked `everywhere`
336/// as well, it is held to `*` alone (KEEL-31), told no address.
337pub(crate) fn door_shaped(everywhere: bool, target: Option<&str>, untyped_peer_slot: bool) -> bool {
338    match target {
339        Some(_) => false,
340        None => everywhere || untyped_peer_slot,
341    }
342}
343
344/// Decide one call. `full_path` is the dotted method as dispatched;
345/// `service_ns` the service's own namespace; `ambiguous` the paths that name
346/// a method and a child alike ([`dispatched`]).
347#[allow(clippy::too_many_arguments)]
348pub(crate) fn decide(
349    gate: &Gate,
350    service_ns: &str,
351    full_path: &str,
352    info: Option<&MethodGateInfo>,
353    params: &Value,
354    auth: Option<&AuthContext>,
355    signed_in_grants: &std::collections::BTreeSet<String>,
356    ambiguous: &std::collections::HashSet<String>,
357) -> Result<Admit, PlexusError> {
358    params_shape(params)?;
359    let (ns, method) = full_path.split_once('.').unwrap_or((full_path, ""));
360    let introspection = method == "schema"
361        || method.ends_with(".schema")
362        || (ns == service_ns && matches!(method, "hash" | "hashes" | "ir"));
363    if introspection {
364        return Ok(Admit::Open);
365    }
366    let grant = Grant::new(info.and_then(|i| i.grant.clone()).unwrap_or_else(|| full_path.to_string()));
367    // ONE-7: a method that acts on the whole activation, or a call into an
368    // untyped peer slot, is decided at the door of the call dispatched —
369    // an address scope covering it, or `*` — and never on a data scope.
370    // No address: `*` alone (KEEL-31's rule), never "held anywhere".
371    if info.is_some_and(|i| i.door) {
372        return Ok(match dispatched(full_path, &grant, ambiguous) {
373            Some(call) => Admit::Reach(gate.check_everywhere_at(auth, &call).map_err(said_at_everywhere)?, Some(call), Some(Vec::new())),
374            None => Admit::Reach(gate.check_everywhere(auth, &grant)?, None, Some(Vec::new())),
375        });
376    }
377    // KEEL-31: a method that acts on the whole service is decided on `*`,
378    // whatever else it says — the rule is the gate's, not the method's.
379    if info.is_some_and(|i| i.everywhere) {
380        return Ok(Admit::Reach(gate.check_everywhere(auth, &grant)?, None, Some(Vec::new())));
381    }
382    if info.is_some_and(|i| i.public) {
383        return Ok(Admit::Reach(gate.reach_of_public(auth, &grant), None, None));
384    }
385    // AUTH-5: what every signed-in caller reaches (`auth.whoami`,
386    // `auth.logout`, `auth.requires`) — whatever its roles or ceiling, but
387    // never anonymously.
388    if signed_in_grants.contains(grant.as_str()) {
389        if auth.and_then(|a| a.principal()).is_none() {
390            return Err(Refusal::Unauthenticated.into());
391        }
392        return Ok(Admit::Reach(gate.reach_of_public(auth, &grant), None, None));
393    }
394    let targets = match info.and_then(|i| i.target.as_deref()) {
395        Some(param) => target_values(params, param)?,
396        None => None,
397    };
398    match targets {
399        None => Ok(Admit::Reach(gate.check(auth, &grant, None)?, None, Some(Vec::new()))),
400        Some(values) if values.is_empty() => Ok(Admit::Reach(gate.check(auth, &grant, None)?, None, Some(values))),
401        Some(values) => {
402            let mut reach = None;
403            for v in &values {
404                reach = Some(gate.check(auth, &grant, Some(v))?);
405            }
406            // KEEL-59: the targets it was decided on, kept with the call
407            // (moved, not copied) to be asked again on a move.
408            Ok(Admit::Reach(reach.expect("non-empty"), None, Some(values)))
409        }
410    }
411}
412
413/// KEEL-31: a backstop that does not depend on the macro — each of
414/// `methods` in `schema` is marked `everywhere`, or why not. A service
415/// whose own whole-service methods lost the mark (built with a macro that
416/// dropped the word) refuses to start rather than admit a scoped holder.
417pub fn require_everywhere(schema: &super::schema::PluginSchema, methods: &[&str]) -> Result<(), String> {
418    let unmarked: Vec<&str> = methods
419        .iter()
420        .copied()
421        .filter(|name| !schema.methods.iter().any(|m| m.name == *name && m.everywhere))
422        .collect();
423    if unmarked.is_empty() {
424        return Ok(());
425    }
426    Err(format!(
427        "{}: {} act on the whole service and must be marked `everywhere` in its schema; they are not — \
428         built with a plexus-macros that does not know the word (it needs 0.11.1 or later)",
429        schema.namespace,
430        unmarked.iter().map(|m| format!("{}.{m}", schema.namespace)).collect::<Vec<_>>().join(", "),
431    ))
432}
433
434/// A refusal as a client reads it back from an error stream item — the
435/// typed view of the `forbidden` shape [`super::types::spec_fields`] writes.
436#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
437pub struct ForbiddenItem {
438    pub grant: String,
439    pub scope: String,
440    #[serde(default)]
441    pub roles: Vec<String>,
442    #[serde(default)]
443    pub held_on: Vec<String>,
444    pub message: String,
445}
446
447impl ForbiddenItem {
448    /// The refusal an error item carries, when it is a missing grant.
449    pub fn from_item(item: &Value) -> Option<Self> {
450        if item.get("type")?.as_str()? != "error" || item.get("error_kind")?.as_str()? != "forbidden" {
451            return None;
452        }
453        item.get("grant")?;
454        serde_json::from_value(item.clone()).ok()
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    //! ONE-7: the routing to the door, shape by shape — an operator held on
461    //! `/ops` alone, and an admin of the data scope `KILN`.
462    use super::*;
463    use plexus_auth_core::grants::{Membership, Memberships, Resolve, RoleTable, ScopeRef};
464    use serde_json::json;
465    use std::collections::{BTreeSet, HashSet};
466    use std::sync::Arc;
467
468    const OPERATOR: &str = "key:0101010101010101010101010101010101010101010101010101010101010101";
469    const KILN_ADMIN: &str = "key:0303030303030303030303030303030303030303030303030303030303030303";
470    const GARDENER: &str = "key:0202020202020202020202020202020202020202020202020202020202020202";
471
472    struct Held;
473    impl Memberships for Held {
474        fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
475            let at = |role: &str, scope: &str| Membership { principal: who.clone(), role: plexus_auth_core::RoleName::new(role), scope: ScopeRef::parse(scope) };
476            match who.to_string().as_str() {
477                OPERATOR => vec![at("operator", "/ops")],
478                KILN_ADMIN => vec![at("admin", "KILN")],
479                GARDENER => vec![at("operator", "/ops.*")],
480                _ => vec![],
481            }
482        }
483    }
484    struct Kiln;
485    impl Resolve for Kiln {
486        fn chain(&self, t: &str) -> Option<Vec<ScopeRef>> {
487            Some(vec![ScopeRef::named(t.split('-').next().unwrap_or(t)), ScopeRef::Everywhere])
488        }
489    }
490
491    fn gate() -> Gate {
492        let roles = RoleTable::from_lists([("operator", ["ops.grow", "ops.get", "ops.misdeclared", "ops.tally", "ops.{peer}", "ops.{box}", "ops.{planet}.wipe", "ops.peer.shop.wipe"])]);
493        Gate::new(Arc::new(Held), Arc::new(roles), Arc::new(Kiln))
494    }
495
496    fn who(p: &str) -> AuthContext {
497        AuthContext::for_principal(&p.parse().unwrap(), "s", vec![], Value::Null)
498    }
499
500    fn info(grant: &str, everywhere: bool, target: Option<&str>, peer_slot: bool) -> MethodGateInfo {
501        MethodGateInfo {
502            grant: Some(grant.into()),
503            everywhere,
504            target: target.map(str::to_string),
505            door: door_shaped(everywhere, target, peer_slot),
506            ..Default::default()
507        }
508    }
509
510    /// Admitted, and whether at a door.
511    fn decided(caller: &str, path: &str, info: &MethodGateInfo, params: Value) -> Result<bool, PlexusError> {
512        match decide(&gate(), "svc", path, Some(info), &params, Some(&who(caller)), &BTreeSet::new(), &HashSet::new())? {
513            Admit::Reach(_, door, _) => Ok(door.is_some()),
514            Admit::Open => Ok(false),
515        }
516    }
517
518    #[test]
519    fn a_whole_activation_method_is_decided_at_its_door() {
520        let grow = info("ops.grow", true, None, false);
521        assert_eq!(decided(OPERATOR, "ops.grow", &grow, json!({})).unwrap(), true);
522        assert!(matches!(decided(KILN_ADMIN, "ops.grow", &grow, json!({})), Err(PlexusError::Forbidden { .. })), "KEEL-31");
523    }
524
525    #[test]
526    fn an_untyped_peer_slot_is_decided_at_the_peer_s_door() {
527        let peer = info("ops.{peer}", false, None, true);
528        assert_eq!(decided(OPERATOR, "ops.peer.shop.look", &peer, json!({})).ok(), None, "`/ops` is ops' own: no prefix rule");
529        assert!(matches!(decided(KILN_ADMIN, "ops.peer.shop.look", &peer, json!({})), Err(PlexusError::Forbidden { .. })), "KEEL-44");
530    }
531
532    #[test]
533    fn a_data_method_is_decided_on_its_target_never_at_a_door() {
534        let get = info("ops.get", false, Some("id"), false);
535        assert!(decided(OPERATOR, "ops.get", &get, json!({ "id": "KILN-3" })).is_err(), "an address holds no data");
536        assert_eq!(decided(KILN_ADMIN, "ops.get", &get, json!({ "id": "KILN-3" })).unwrap(), false);
537        let tally = info("ops.tally", false, None, false);
538        assert!(decided(OPERATOR, "ops.tally", &tally, json!({})).is_err(), "no target: held anywhere, on data");
539        assert_eq!(decided(KILN_ADMIN, "ops.tally", &tally, json!({})).unwrap(), false);
540    }
541
542    /// A method marked `everywhere` that also declares a target is decided
543    /// on `*` alone (KEEL-31) — the door would never check its target.
544    #[test]
545    fn a_misdeclared_data_method_is_not_reachable_through_the_door() {
546        let bad = info("ops.misdeclared", true, Some("id"), false);
547        assert!(!bad.door);
548        assert!(matches!(decided(OPERATOR, "ops.misdeclared", &bad, json!({ "id": "KILN-3" })), Err(PlexusError::Forbidden { .. })));
549        assert!(matches!(decided(KILN_ADMIN, "ops.misdeclared", &bad, json!({ "id": "KILN-3" })), Err(PlexusError::Forbidden { .. })));
550    }
551
552    /// An opaque dynamic child is this service's own: held anywhere, as before.
553    #[test]
554    fn a_dynamic_child_slot_is_held_anywhere_as_before() {
555        let boxes = info("ops.{box}", false, None, false);
556        assert!(!boxes.door);
557        assert!(decided(OPERATOR, "ops.b1.look", &boxes, json!({})).is_err());
558        assert_eq!(decided(KILN_ADMIN, "ops.b1.look", &boxes, json!({})).unwrap(), false);
559    }
560
561    #[test]
562    fn a_call_is_dispatched_from_its_literal_path() {
563        let none = HashSet::new();
564        let g = Grant::new("ops.{peer}");
565        let call = dispatched("ops.peer.shop.items.list", &g, &none).unwrap();
566        assert_eq!((call.at().activation(), call.at().method(), call.grant()), ("ops.peer.shop.items", "list", &g));
567        for bad in ["ops", "ops..x", "ops.sh*p.x", "ops.sh p.x", "ops.{peer}.x", ""] {
568            assert!(dispatched(bad, &g, &none).is_none(), "{bad}");
569        }
570        let ambiguous: HashSet<String> = ["ops.peer".to_string()].into();
571        assert!(dispatched("ops.peer", &g, &ambiguous).is_none(), "a name both a method and a child");
572        assert!(dispatched("ops.peer.shop.look", &g, &ambiguous).is_none(), "and everything under it");
573        assert!(dispatched("ops.peers", &g, &ambiguous).is_some());
574    }
575
576    #[test]
577    fn a_name_given_twice_is_found() {
578        use crate::plexus::schema::{MethodRole, MethodSchema, PluginSchema};
579        let mut s = PluginSchema::leaf("dyn", "1", "d", vec![MethodSchema::new("peers", "d", "h")]);
580        s.methods.push(MethodSchema::new("peer", "d", "h"));
581        s.methods.push(MethodSchema::new("peer", "d", "h").with_role(MethodRole::Peer { list_method: None, search_method: None, interface: None }));
582        assert_eq!(named_twice(&s), ["peer"]);
583    }
584
585    /// Review M1: the backstop decides from the door the dispatch recorded.
586    /// Run inside a call admitted at it, `grant` (as the macro names it)
587    /// passes only for the door's own method: not another method's of the
588    /// same name run in-process (`x.grow` on `ops.grow`'s door), not one
589    /// on a slot's whole grant (`ops.{peer}` at a peer's address).
590    #[test]
591    fn the_backstop_takes_only_the_methods_own_door() {
592        let ran = |caller: &str, path: &str, info: &MethodGateInfo, peer_slot: Option<&str>, grant: &str| -> bool {
593            let auth = who(caller);
594            let Ok(Admit::Reach(reach, Some(call), _)) = decide(&gate(), "svc", path, Some(info), &json!({}), Some(&auth), &BTreeSet::new(), &HashSet::new()) else {
595                panic!("{path}: not admitted at a door");
596            };
597            let ctx = crate::call::CallContext::admitted_by_gate(Some(&auth), reach).at_door(call, peer_slot);
598            futures::executor::block_on(crate::call::scope(ctx, async { crate::call::admits_everywhere(grant) })).is_ok()
599        };
600        let grow = info("ops.grow", true, None, false);
601        assert!(ran(OPERATOR, "ops.grow", &grow, None, "ops.grow"));
602        assert!(!ran(OPERATOR, "ops.grow", &grow, None, "x.grow"), "another activation's `grow`, in process");
603        assert!(!ran(OPERATOR, "ops.grow", &grow, None, "ops.tally"));
604        // A typed slot's own grant: its `{planet}` stands for the namespace there.
605        let wipe = info("ops.{planet}.wipe", true, None, false);
606        assert!(ran(GARDENER, "ops.mars.wipe", &wipe, None, "planet.wipe"));
607        assert!(!ran(GARDENER, "ops.mars.wipe", &wipe, None, "planet.look"));
608        // The slot's whole grant at a peer's address: ordinary methods only.
609        let slot = info("ops.{peer}", false, None, true);
610        assert!(!ran(GARDENER, "ops.peer.shop.wipe", &slot, Some("ops.{peer}"), "shop.wipe"));
611        assert!(!ran(GARDENER, "ops.peer.shop.wipe", &slot, Some("ops.{peer}"), "leaf.wipe"));
612        // The peer's literal grant there: its own door — the peer's name open
613        // (an in-process peer's namespace is not its name).
614        let literal = MethodGateInfo { door: true, ..Default::default() };
615        assert!(ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "shop.wipe"));
616        assert!(ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "leaf.wipe"));
617        assert!(!ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "leaf.look"));
618        // Without the slot said, the literal door's namespace is the peer's name.
619        assert!(!ran(GARDENER, "ops.peer.shop.wipe", &literal, None, "leaf.wipe"));
620    }
621}