Skip to main content

plexus_core/plexus/remote_child/
upcall.rs

1//! NEST-11 · a child calls its service back, under a call it serves.
2//!
3//! While the service has a call open into a child, the child may open calls
4//! of its own into the service on the same connection (spec/14: either side
5//! opens a call), each naming the forwarded call it acts under:
6//!
7//! ```json
8//! ← {"jsonrpc":"2.0","id":1,"method":"_host.call","params":{"method":"weather.forecast","params":{"city":"lisbon"},"under":"3e1e8fa8-…"}}
9//! → {"jsonrpc":"2.0","id":1,"result":1}
10//! → {"jsonrpc":"2.0","method":"_host.call","params":{"subscription":1,"result":{"type":"data",…}}}
11//! → {"jsonrpc":"2.0","method":"_host.call","params":{"subscription":1,"result":{"type":"done",…}}}
12//! ← {"jsonrpc":"2.0","id":2,"method":"_host.call_unsub","params":[1]}
13//! ```
14//!
15//! `under` is the forwarded call's `hop.call`. The service routes the call
16//! through its own routing and gate — [`DynamicHub::route_with_ctx`], as
17//! any caller's — **as that call's caller** (`hop.for`'s far end, the
18//! identity its own gate admitted), **within that call's reach**: one more
19//! ceiling layer, `admin@<scope>` for each scope the forwarded call was
20//! admitted on (BIDIR-5's `hop_identity` rule: the far side only ever
21//! narrows). A call refused by the gate is the subscription id, then one
22//! `error` item (as `{ns}.call` answers it). When the forwarded call ends
23//! (its last item, its caller letting go, the connection going) or its grant
24//! is revoked (the grants generation moves and its reach is held nowhere),
25//! every call made under it ends with one `error` item. A call naming no
26//! live forwarded call is refused at the JSON-RPC layer, `unauthenticated`,
27//! naming why — with one exception: outside any call a child may ask its
28//! service for a **schema** (`<path>.schema`), answered from the service's
29//! whole description, so it can learn, at its start, the shape of what it
30//! will call.
31//!
32//! [`DynamicHub::route_with_ctx`]: crate::plexus::DynamicHub::route_with_ctx
33
34use std::collections::HashMap;
35use std::sync::atomic::{AtomicU64, Ordering};
36use std::sync::{Arc, Mutex};
37
38use futures::StreamExt;
39use plexus_auth_core::grants::{Reach, CEILING_KEY};
40use serde_json::{json, Value};
41use tokio::sync::{mpsc, watch};
42
43use super::link::meta;
44use crate::plexus::auth::AuthContext;
45use crate::plexus::service_scope::{self, WeakService};
46use crate::plexus::types::PlexusStreamItem;
47use crate::plexus::{parent, plexus_error_to_jsonrpc, PlexusError};
48
49/// The method a child opens a call into its service with.
50pub const HOST_CALL: &str = "_host.call";
51/// The method a child lets go of such a call with (`[sid]`).
52pub const HOST_CALL_UNSUB: &str = "_host.call_unsub";
53
54/// DYNAUTH-5: one of a child's needs an admin consented to, and where:
55/// `scopes` `["*"]` anywhere its caller reaches, else only on those.
56#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
57pub struct Consented {
58    /// The need, by its path from the service (`shop.items`).
59    pub method: String,
60    /// The scopes it may be called on (`["*"]`, `["MENGER"]`).
61    pub scopes: Vec<String>,
62}
63
64/// One forwarded call open into the child: whom it acts for, within what,
65/// and in which service.
66pub(super) struct Under {
67    auth: Option<AuthContext>,
68    reach: Reach,
69    service: WeakService,
70    /// `Some(why)` once the forwarded call has ended.
71    ended: watch::Sender<Option<String>>,
72    /// DYNAUTH-12: the token minted for the forwarded call, if one was.
73    minted: Option<Minted>,
74    /// ONE-7: the door the forwarded call was admitted at, as a ceiling
75    /// entry for exactly it (`dyn.{peer}@/dyn.peer.shop.items.list`): what a
76    /// call back made under it holds beyond the call's data — that one
77    /// door, never `*`.
78    door: Option<String>,
79}
80
81tokio::task_local! {
82    /// DYNAUTH-6: the token a call back is made under, while it is routed.
83    static PRESENTED: crate::plexus::peer_token::PeerClaims;
84}
85
86/// DYNAUTH-6: the token a call back was made under, while that call back
87/// is routed — so a call it reaches into another child is an exchange
88/// (RFC 8693: the same `sub`, the presenter in `act`, a scope never wider),
89/// not a fresh mint.
90pub(super) fn presented() -> Option<crate::plexus::peer_token::PeerClaims> {
91    PRESENTED.try_with(Clone::clone).ok()
92}
93
94/// DYNAUTH-12: a token minted for one forwarded call, and what it says.
95#[derive(Clone)]
96pub(super) struct Minted {
97    pub token: String,
98    pub claims: crate::plexus::peer_token::PeerClaims,
99}
100
101/// What a mount keeps for its child's calls back: the service it is in and
102/// the forwarded calls open now, by their hop's `call` id.
103pub(super) struct Upcalls {
104    host: Mutex<Option<WeakService>>,
105    under: Mutex<HashMap<String, Arc<Under>>>,
106    /// Calls the child made back, in all.
107    pub made: AtomicU64,
108    /// DYNAUTH-12: the proofs of possession seen, each once.
109    proofs: crate::plexus::peer_token::ProofCache,
110    /// NEST-16: the methods the child's schema says it needs (`None`: it
111    /// declares none), set when it is mounted.
112    needs: Mutex<Option<Arc<[String]>>>,
113    /// DYNAUTH-5: what an admin consented to of those needs, each on the
114    /// scopes it may be called on (`None`: no consent is kept for this
115    /// mount — a declared need is enough, as NEST-16 has it).
116    consent: Mutex<Option<Arc<[Consented]>>>,
117    /// NEST-16: NEST-11's broad rule for a child that declares no needs —
118    /// anything its caller could reach ([`ChildOptions::legacy_upcalls`]).
119    ///
120    /// [`ChildOptions::legacy_upcalls`]: super::ChildOptions::legacy_upcalls
121    legacy: bool,
122    /// DYNAUTH-7: revoked, and why: no call is forwarded, no token minted,
123    /// and (KEEL-19) nothing is decided for it — no call back, no exchange.
124    revoked: Mutex<Option<String>>,
125    /// KEEL-32: the paths whose schemas it may read outside any call before
126    /// its needs are known ([`super::ChildOptions::schemas`]).
127    schemas: Mutex<Arc<[String]>>,
128}
129
130/// KEEL-19: what [`Upcalls::decide`] answers for a need: the scopes it is
131/// consented on now (`["*"]` anywhere), and, decided under a token, the
132/// scopes both that token holds its grant on and the consent holds now
133/// (KEEL-20's first row: a consent narrowed while a call is open narrows
134/// the next call back made under it).
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub(super) struct Decided {
137    pub consented: Vec<String>,
138    pub held: Option<Vec<String>>,
139}
140
141impl Upcalls {
142    pub(super) fn new(host: Option<WeakService>, legacy: bool) -> Arc<Self> {
143        Arc::new(Self { host: Mutex::new(host), under: Mutex::default(), made: AtomicU64::new(0), proofs: Default::default(), needs: Mutex::default(), consent: Mutex::default(), legacy, revoked: Mutex::default(), schemas: Mutex::new(Arc::from(Vec::new())) })
144    }
145
146    /// KEEL-32: see [`super::ChildOptions::schemas`].
147    pub(super) fn set_schemas(&self, paths: &[String]) {
148        *self.schemas.lock().unwrap() = paths.to_vec().into();
149    }
150
151    /// KEEL-32 · a schema the child asks for **outside any call**, answered
152    /// as the child — never as the service with everything, or anyone's
153    /// view but its own. `path` is the bare path (`weather.weather`,
154    /// `dyn.peer.w`), `crosses_slot` whether reaching it looks a name up in
155    /// a dynamic or peer slot. Answered when it is:
156    ///
157    /// - at or above one of its needs, declared and consented
158    ///   ([`Upcalls::decide`]'s rule): the shape of what it may call;
159    /// - at, above or below a path it was mounted to read
160    ///   ([`super::ChildOptions::schemas`]) — what it grows from at its
161    ///   start, before its needs are known;
162    /// - for a child under the legacy rule that declares no needs, a
163    ///   static path (no slot lookup on its way), as NEST-11 had it.
164    ///
165    /// A revoked child is answered nothing; anything else is not found —
166    /// never routed, so no dynamic child or peer is looked up for it.
167    pub(super) fn may_read_schema(&self, path: &str, crosses_slot: bool) -> Result<(), (PlexusError, String)> {
168        if let Some(why) = self.revoked() {
169            return Err((PlexusError::Unauthenticated(format!("this child is revoked ({why})")), format!("this child is revoked ({why}): it is answered no schema")));
170        }
171        let at_or_above = |n: &str| n == path || n.starts_with(&format!("{path}."));
172        let at_above_or_below = |s: &str| at_or_above(s) || path.starts_with(&format!("{s}."));
173        if self.schemas.lock().unwrap().iter().any(|s| at_above_or_below(s)) {
174            return Ok(());
175        }
176        let needs = self.needs.lock().unwrap().clone();
177        if let Some(needs) = &needs {
178            let consent = self.consent.lock().unwrap().clone();
179            let consented = |n: &String| consent.as_ref().is_none_or(|c| c.iter().any(|c| &c.method == n));
180            if needs.iter().filter(|n| consented(n)).any(|n| at_or_above(n)) {
181                return Ok(());
182            }
183        } else if self.legacy && !crosses_slot {
184            return Ok(());
185        }
186        let (ns, rest) = path.split_once('.').unwrap_or((path, ""));
187        let e = if rest.is_empty() {
188            PlexusError::ActivationNotFound(ns.to_string())
189        } else {
190            PlexusError::MethodNotFound { activation: ns.to_string(), method: rest.to_string() }
191        };
192        let said = format!("`{path}.schema` is not among what this child needs or was mounted to read: not found");
193        Err((e, said))
194    }
195
196    /// NEST-16: what the mounted child's schema says it needs.
197    pub(super) fn set_needs(&self, needs: Option<&[crate::plexus::schema::Need]>) {
198        *self.needs.lock().unwrap() = needs.map(|n| n.iter().map(|n| n.method.clone()).collect::<Vec<_>>().into());
199    }
200
201    /// DYNAUTH-5: what an admin consented to (`None`: no consent kept).
202    pub(super) fn set_consent(&self, consent: Option<Vec<Consented>>) {
203        *self.consent.lock().unwrap() = consent.map(Into::into);
204    }
205
206    /// DYNAUTH-5: the consent kept now.
207    pub(super) fn consent(&self) -> Option<Arc<[Consented]>> {
208        self.consent.lock().unwrap().clone()
209    }
210
211    /// DYNAUTH-7: revoke: no call back is decided from now, and every one
212    /// open ends saying why.
213    pub(super) fn revoke(&self, why: &str) {
214        *self.revoked.lock().unwrap() = Some(why.to_string());
215        self.end_all(&format!("revoked: {why}"));
216    }
217
218    /// DYNAUTH-7: why the child is revoked, if it is.
219    pub(super) fn revoked(&self) -> Option<String> {
220        self.revoked.lock().unwrap().clone()
221    }
222
223    /// KEEL-19 · **the one decision** of what this child may reach of its
224    /// service — a call back's ([`on_request`]) and an exchange's
225    /// ([`super::RemoteChild::may_exchange`]) alike: the standard interface
226    /// (`Ok(None)`), or a need — declared, consented, and the child not
227    /// revoked — and, under `token` (the token its call was made under, and
228    /// the service that names the need's grant), only where that token holds
229    /// the need's grant. `Err` the refusal, typed and said.
230    pub(super) fn decide(&self, method: &str, token: Option<(&crate::plexus::DynamicHub, &crate::plexus::peer_token::PeerClaims)>) -> Result<Option<Decided>, (PlexusError, String)> {
231        if parent::is_standard(method) {
232            return Ok(None);
233        }
234        if let Some(why) = self.revoked() {
235            return Err((PlexusError::Unauthenticated(format!("this child is revoked ({why})")), format!("this child is revoked ({why}): nothing it asks is decided for it")));
236        }
237        let Some(consented) = self.allows(method)? else { return Ok(None) };
238        let held = match token {
239            None => None,
240            Some((svc, claims)) => {
241                let held = svc.grant_at(method).map(|g| claims.scopes_for(&g)).unwrap_or_default();
242                if held.is_empty() {
243                    let e = parent::not_needed(method);
244                    return Err((e, format!("`{method}` is not within the scope of the token minted for this call")));
245                }
246                let both = intersect(&held, &consented);
247                if both.is_empty() {
248                    let e = parent::not_needed(method);
249                    return Err((e, format!("`{method}` is consented on {consented:?} now, and the token holds it on {held:?}: nowhere both")));
250                }
251                Some(both)
252            }
253        };
254        Ok(Some(Decided { consented, held }))
255    }
256
257    /// NEST-16: may the child call `method` up — the standard interface, a
258    /// need, or anything under the legacy rule for a child that declares
259    /// none. DYNAUTH-5: a need must also be consented, when consent is
260    /// kept. `Ok(Some(scopes))` for a need (routed under its own grant,
261    /// only on `scopes` — `["*"]` anywhere), `Ok(None)` for the rest;
262    /// `Err` the refusal, said.
263    fn allows(&self, method: &str) -> Result<Option<Vec<String>>, (PlexusError, String)> {
264        if parent::is_standard(method) {
265            return Ok(None);
266        }
267        let declared = match self.needs.lock().unwrap().as_ref() {
268            Some(needs) => needs.iter().any(|n| n == method),
269            None if self.legacy => return Ok(None),
270            None => false,
271        };
272        if !declared {
273            let e = parent::not_needed(method);
274            let said = e.to_string();
275            return Err((e, said));
276        }
277        match self.consent.lock().unwrap().as_ref() {
278            None => Ok(Some(vec!["*".into()])),
279            Some(c) => match c.iter().find(|c| c.method == method) {
280                Some(c) => Ok(Some(c.scopes.clone())),
281                None => Err((
282                    parent::not_needed(method),
283                    format!("`{method}` is among this child's needs, but no admin has consented to it (dyn.consent): a declared need is a request, not a grant"),
284                )),
285            },
286        }
287    }
288
289    /// The service the child is in: the one given, else the one a call was
290    /// routed in when it was first seen.
291    pub(super) fn host(&self) -> Option<WeakService> {
292        let mut h = self.host.lock().unwrap();
293        if h.as_ref().and_then(WeakService::upgrade).is_none() {
294            if let Some(now) = service_scope::current() {
295                *h = Some(now);
296            }
297        }
298        h.clone()
299    }
300
301    /// A forwarded call opens: the child may call back under `id` until the
302    /// guard is dropped (or [`UnderGuard::end`]ed).
303    pub(super) fn open(self: &Arc<Self>, id: &str, auth: Option<&AuthContext>, reach: &Reach, minted: Option<Minted>, door: Option<plexus_auth_core::grants::DispatchedCall>) -> Option<UnderGuard> {
304        // The service is learned here, with the first call forwarded (a
305        // schema the child asks outside any call is answered by it).
306        let known = self.host();
307        let service = service_scope::current().or(known)?;
308        let (ended, _) = watch::channel(None);
309        let door = door.map(|d| format!("{}@/{}", d.grant(), d.at().path()));
310        let under = Arc::new(Under { auth: auth.cloned(), reach: reach.clone(), service, ended, minted, door });
311        {
312            // KEEL-19: a revoked child is opened nothing to call back under —
313            // asked under the lock `revoke`'s `end_all` drains, after the
314            // mark is set, so an open either sees the mark or is drained.
315            let mut open = self.under.lock().unwrap();
316            if self.revoked().is_some() {
317                return None;
318            }
319            open.insert(id.to_string(), Arc::clone(&under));
320        }
321        Some(UnderGuard { up: Arc::clone(self), id: id.to_string(), under })
322    }
323
324    /// DYNAUTH-12: the needs a token minted now may hold, each by the grant
325    /// the service holds a call to it to and the scopes it is consented on
326    /// (`["*"]` without consent kept).
327    pub(super) fn need_grants(&self, service: &crate::plexus::DynamicHub) -> Vec<(String, Vec<String>)> {
328        let needs = self.needs.lock().unwrap().clone().unwrap_or_else(|| Vec::<String>::new().into());
329        let consent = self.consent.lock().unwrap().clone();
330        needs
331            .iter()
332            .filter_map(|m| {
333                let scopes = match &consent {
334                    None => vec!["*".to_string()],
335                    Some(c) => c.iter().find(|c| &c.method == m)?.scopes.clone(),
336                };
337                Some((service.grant_at(m)?, scopes))
338            })
339            .collect()
340    }
341
342    /// DYNAUTH-7: every forwarded call open now ends for the child's calls
343    /// back — each made under one ends with one error item, saying `why`.
344    pub(super) fn end_all(&self, why: &str) {
345        let open: Vec<Arc<Under>> = self.under.lock().unwrap().drain().map(|(_, u)| u).collect();
346        for u in open {
347            u.ended.send_if_modified(|e| {
348                if e.is_none() {
349                    *e = Some(why.to_string());
350                    true
351                } else {
352                    false
353                }
354            });
355        }
356    }
357
358    /// How many forwarded calls the child may call back under now.
359    pub(super) fn open_now(&self) -> usize {
360        self.under.lock().unwrap().len()
361    }
362}
363
364/// Each scope both `a` and `b` hold, the narrower of each pair (`*` holds
365/// every scope).
366fn intersect(a: &[String], b: &[String]) -> Vec<String> {
367    let within = |inner: &str, outer: &str| outer == "*" || inner == outer;
368    let mut out: Vec<String> = Vec::new();
369    for x in a {
370        for y in b {
371            let s = if within(x, y) {
372                x
373            } else if within(y, x) {
374                y
375            } else {
376                continue;
377            };
378            if !out.contains(s) {
379                out.push(s.clone());
380            }
381        }
382    }
383    out
384}
385
386/// A forwarded call's standing for the child's calls back: dropped, the
387/// calls made under it end.
388pub(super) struct UnderGuard {
389    up: Arc<Upcalls>,
390    id: String,
391    under: Arc<Under>,
392}
393
394impl UnderGuard {
395    /// The forwarded call has ended, and why.
396    pub(super) fn end(&self, why: &str) {
397        self.up.under.lock().unwrap().remove(&self.id);
398        self.under.ended.send_if_modified(|e| {
399            if e.is_none() {
400                *e = Some(why.to_string());
401                true
402            } else {
403                false
404            }
405        });
406    }
407}
408
409impl Drop for UnderGuard {
410    fn drop(&mut self) {
411        self.end("it ended");
412    }
413}
414
415/// `auth`, its reach narrowed to `reach`'s scopes: one more ceiling layer,
416/// `admin@<scope>` each — none when `reach` holds everywhere. DYNAUTH-6:
417/// `admin@X` in a ceiling layer is not the admin role: it reads "any grant,
418/// only on X" (the gate's `admin` lists every grant), so it narrows by
419/// *where* only — the outer bound, kept for a child under the legacy rule.
420/// What a child may *do* is the need's own grant (below) and its token's
421/// scope. NEST-16 (TM-1): for a need, the layer is its own grant on
422/// each of those scopes (`shop.items@*` when everywhere), so the call back
423/// reaches that method and nothing else, whatever the caller holds.
424///
425/// ONE-7: a forwarded call admitted at a door (`door`: its grant at its
426/// address, `dyn.{peer}@/dyn.peer.shop.items.list`) adds that entry to the
427/// layer — the door of that one call, for its own grant, never `*` — so a
428/// call back under it reaches the data the caller holds the grant on, and
429/// that door, and nothing else: `operator on /dyn.*` calling into a peer
430/// does not hand the peer `dyn.connect`.
431fn narrowed(auth: &AuthContext, reach: &Reach, grant: Option<&str>, door: Option<&str>) -> AuthContext {
432    if reach.is_everywhere() && grant.is_none() {
433        return auth.clone();
434    }
435    let mut ctx = auth.clone();
436    let mut layers: Vec<Value> = match ctx.metadata.get(CEILING_KEY) {
437        Some(Value::Array(items)) if items.iter().all(Value::is_string) => vec![Value::Array(items.clone())],
438        Some(Value::Array(items)) => items.clone(),
439        Some(other) => vec![other.clone()],
440        None => Vec::new(),
441    };
442    let what = grant.unwrap_or(plexus_auth_core::grants::ADMIN);
443    let scopes: Vec<String> = if reach.is_everywhere() { vec!["*".into()] } else { reach.held_on().iter().map(|s| s.to_string()).collect() };
444    let mut layer: Vec<Value> = scopes.iter().map(|s| json!(format!("{what}@{s}"))).collect();
445    layer.extend(door.filter(|_| !reach.is_everywhere()).map(|d| json!(d)));
446    layers.push(Value::Array(layer));
447    if !ctx.metadata.is_object() {
448        ctx.metadata = json!({});
449    }
450    ctx.metadata[CEILING_KEY] = Value::Array(layers);
451    ctx
452}
453
454/// DYNAUTH-12: the token and proof a keyed child presents with a call
455/// back, checked against the token minted for the call it names.
456fn presented_ok(up: &Upcalls, m: &Minted, params: &Value, method: &str, under: &str) -> Result<(), String> {
457    if let Some(t) = params.get("token").and_then(Value::as_str) {
458        if t != m.token {
459            return Err("the token presented is not the one minted for this call".into());
460        }
461    }
462    if m.claims.cnf.is_none() {
463        return Ok(());
464    }
465    let proof = params.get("proof").and_then(Value::as_str).ok_or_else(|| {
466        "a call back under a key-bound token carries a proof of possession (`proof`): none was sent".to_string()
467    })?;
468    crate::plexus::peer_token::check_proof(proof, &m.token, &m.claims, method, under, crate::plexus::peer_token::now(), &up.proofs)
469        .map_err(|e| format!("the call back's {e}"))
470}
471
472/// DYNAUTH-5: `auth` with one more ceiling layer, `grant@<scope>` for each
473/// consented scope — a need consented on `MENGER` reaches only there.
474fn consented(auth: &AuthContext, grant: &str, scopes: &[String]) -> AuthContext {
475    let mut ctx = auth.clone();
476    let mut layers: Vec<Value> = match ctx.metadata.get(CEILING_KEY) {
477        Some(Value::Array(items)) if items.iter().all(Value::is_string) => vec![Value::Array(items.clone())],
478        Some(Value::Array(items)) => items.clone(),
479        Some(other) => vec![other.clone()],
480        None => Vec::new(),
481    };
482    layers.push(Value::Array(scopes.iter().map(|s| json!(format!("{grant}@{s}"))).collect()));
483    if !ctx.metadata.is_object() {
484        ctx.metadata = json!({});
485    }
486    ctx.metadata[CEILING_KEY] = Value::Array(layers);
487    ctx
488}
489
490/// A refusal at the JSON-RPC layer, typed, said in its own words.
491fn refusal_said(id: &Value, e: &PlexusError, said: &str) -> Value {
492    let mut r = refusal(id, e);
493    r["error"]["message"] = json!(said);
494    r
495}
496
497/// A refusal at the JSON-RPC layer, typed.
498fn refusal(id: &Value, e: &PlexusError) -> Value {
499    let mut error = serde_json::to_value(plexus_error_to_jsonrpc(e)).unwrap_or_default();
500    // The reason in words, as the error item says it (the typed `data`
501    // carries the kind).
502    error["message"] = json!(e.to_string());
503    json!({ "jsonrpc": "2.0", "id": id, "error": error })
504}
505
506/// The calls a connection serves its child, by the subscription id this
507/// side minted.
508#[derive(Default)]
509pub(super) struct Served {
510    next: AtomicU64,
511    open: Mutex<HashMap<u64, tokio::task::AbortHandle>>,
512}
513
514impl Served {
515    /// The connection went: every call it served ends.
516    pub(super) fn abort_all(&self) {
517        for (_, h) in self.open.lock().unwrap().drain() {
518            h.abort();
519        }
520    }
521}
522
523/// A request from the child: `_host.call` (opens) or `_host.call_unsub`
524/// (lets go). `out` is the connection's writer.
525pub(super) fn on_request(up: &Arc<Upcalls>, served: &Arc<Served>, out: &mpsc::UnboundedSender<Vec<u8>>, name: &str, id: Value, method: &str, params: Value) {
526    let send = |v: Value| {
527        let _ = out.send(serde_json::to_vec(&v).unwrap_or_default());
528    };
529    if method == HOST_CALL_UNSUB {
530        let held = params.get(0).and_then(Value::as_u64).and_then(|sid| served.open.lock().unwrap().remove(&sid));
531        let stopped = held.map(|h| h.abort()).is_some();
532        return send(json!({ "jsonrpc": "2.0", "id": id, "result": stopped }));
533    }
534    let Some(mut target) = params.get("method").and_then(Value::as_str).map(str::to_string) else {
535        return send(refusal(&id, &PlexusError::invalid_params("`_host.call` names the `method` it calls")));
536    };
537    let args = params.get("params").cloned().unwrap_or_else(|| json!({}));
538    // DYNAUTH-12: the method as the child asked it (what its proof names).
539    let presented = target.clone();
540    let under_id = params.get("under").and_then(Value::as_str).map(str::to_string);
541    // NEST-16: the standard upward interface, the child's needs, or (a
542    // child that declares none, under the legacy option) NEST-11's rule.
543    // KEEL-19: decided by the one function an exchange is decided by.
544    let need = match up.decide(&target, None) {
545        Ok(need) => need.map(|d| d.consented),
546        Err((e, said)) => return send(refusal_said(&id, &e, &said)),
547    };
548    let standard = matches!(target.as_str(), parent::HOST_WHOAMI | parent::HOST_LOG | parent::HOST_NOTIFY);
549    if target == parent::HOST_SCHEMA {
550        if let Some(svc) = up.host().and_then(|h| h.upgrade()) {
551            target = format!("{}.schema", svc.runtime_namespace());
552        }
553    }
554    let route = match &under_id {
555        Some(u) => match up.under.lock().unwrap().get(u).cloned() {
556            Some(under) => {
557                // DYNAUTH-12: under a call whose token is bound to the
558                // child's key, every call back carries a proof of
559                // possession by that key, for this method and call (a
560                // child on the service's own pipe needs none, D3).
561                if let Some(m) = &under.minted {
562                    if let Err(e) = presented_ok(up, m, &params, &presented, u) {
563                        return send(refusal_said(&id, &PlexusError::Unauthenticated(e.clone()), &e));
564                    }
565                }
566                if standard {
567                    Route::Standard(under.service.clone(), under.auth.clone())
568                } else {
569                    // DYNAUTH-12: a need is held to the token's scope too.
570                    let need = match (&under.minted, need, under.service.upgrade()) {
571                        (Some(m), Some(_), Some(svc)) => match up.decide(&target, Some((&svc, &m.claims))) {
572                            Ok(d) => d.and_then(|d| d.held),
573                            Err((e, said)) => return send(refusal_said(&id, &e, &said)),
574                        },
575                        (_, n, _) => n,
576                    };
577                    Route::Under(under, need)
578                }
579            }
580            None => {
581                return send(refusal(&id, &PlexusError::Unauthenticated(format!(
582                    "no call `{u}` is open into this child: a child calls its service only under a call it is serving, while it is open"
583                ))))
584            }
585        },
586        None => {
587            let schema = target.ends_with(".schema");
588            match (schema || standard, up.host()) {
589                (true, Some(host)) if standard => Route::Standard(host, None),
590                (true, Some(host)) => {
591                    // KEEL-32: answered as the child — its needs, what it
592                    // was mounted to read — or not found, never routed.
593                    if let Some(svc) = host.upgrade() {
594                        let own = format!("{}.schema", svc.runtime_namespace());
595                        if target == own {
596                            if let Some(why) = up.revoked() {
597                                let e = PlexusError::Unauthenticated(format!("this child is revoked ({why})"));
598                                return send(refusal(&id, &e));
599                            }
600                        } else {
601                            let path = svc.bare_schema_path(&target);
602                            if let Err((e, said)) = up.may_read_schema(&path, svc.crosses_slot(&path)) {
603                                return send(refusal_said(&id, &e, &said));
604                            }
605                        }
606                    }
607                    Route::Schema(host)
608                }
609                (true, None) => {
610                    return send(refusal(&id, &PlexusError::Unauthenticated(
611                        "this child's service is not known yet: it is learned with the first call forwarded to it".into(),
612                    )))
613                }
614                (false, _) => {
615                    return send(refusal(&id, &PlexusError::Unauthenticated(format!(
616                        "`{target}` names no call it acts under (`under`): a child calls its service only under a call it is serving; outside one it may ask only for a schema, or call `host.log` and `host.notify`"
617                    ))))
618                }
619            }
620        }
621    };
622    up.made.fetch_add(1, Ordering::Relaxed);
623    let sid = served.next.fetch_add(1, Ordering::Relaxed) + 1;
624    // spec/02: the subscription id before any of its items.
625    send(json!({ "jsonrpc": "2.0", "id": id, "result": sid }));
626    let (out, served2, name) = (out.clone(), Arc::clone(served), name.to_string());
627    // Registered before it can end, so its end always finds it.
628    let mut open = served.open.lock().unwrap();
629    let task = tokio::spawn(async move {
630        pump(route, &out, sid, &name, &target, args).await;
631        served2.open.lock().unwrap().remove(&sid);
632    });
633    open.insert(sid, task.abort_handle());
634}
635
636enum Route {
637    /// A call under a forwarded call; `Some(scopes)`: one of the child's
638    /// needs, consented on those scopes (DYNAUTH-5).
639    Under(Arc<Under>, Option<Vec<String>>),
640    Schema(WeakService),
641    /// NEST-16: `host.whoami`, `host.log` or `host.notify`, answered by the
642    /// service itself, for the caller of the call it is made under.
643    Standard(WeakService, Option<AuthContext>),
644}
645
646/// One call the child made: routed, its items written back under `sid`
647/// until the last — or until the call it was made under ends.
648async fn pump(route: Route, out: &mpsc::UnboundedSender<Vec<u8>>, sid: u64, name: &str, target: &str, args: Value) {
649    let item = |i: &PlexusStreamItem| {
650        let frame = json!({ "jsonrpc": "2.0", "method": HOST_CALL, "params": { "subscription": sid, "result": i } });
651        let _ = out.send(serde_json::to_vec(&frame).unwrap_or_default());
652    };
653    let gone = || PlexusStreamItem::error(meta(name), plexus_client::RemoteError::Unauthenticated, false);
654    let ended_item = |why: &str| {
655        let mut e = gone();
656        if let PlexusStreamItem::Error { message, .. } = &mut e {
657            *message = format!("the call this was made under has ended ({why})");
658        }
659        e
660    };
661    let (under, service) = match &route {
662        Route::Under(u, _) => (Some(Arc::clone(u)), u.service.upgrade()),
663        Route::Schema(s) | Route::Standard(s, _) => (None, s.upgrade()),
664    };
665    let Some(service) = service else {
666        let mut e = gone();
667        if let PlexusStreamItem::Error { message, .. } = &mut e {
668            *message = "the service this child is mounted in has gone".into();
669        }
670        return item(&e);
671    };
672    if let Route::Standard(_, caller) = &route {
673        for i in parent::standard_answer(&service, name, target, &args, caller.as_ref()).unwrap_or_default() {
674            item(&i);
675        }
676        return;
677    }
678    let need = match &route {
679        Route::Under(_, n) => n.clone(),
680        _ => None,
681    };
682    let routed = match &under {
683        Some(u) => {
684            // TM-1: a need is routed under its own grant as one more ceiling;
685            // DYNAUTH-5: and only on the scopes it was consented on.
686            let grant = need.as_ref().and_then(|_| service.grant_at(target));
687            let auth = u.auth.as_ref().map(|a| narrowed(a, &u.reach, grant.as_deref(), u.door.as_deref()));
688            let auth = match (auth, &grant, &need) {
689                (Some(a), Some(g), Some(scopes)) if !scopes.iter().any(|s| s == "*") => Some(consented(&a, g, scopes)),
690                (a, _, _) => a,
691            };
692            // DYNAUTH-6: a call it reaches into another child is minted as
693            // an exchange of the token this call back was made under.
694            match &u.minted {
695                Some(m) => PRESENTED.scope(m.claims.clone(), service.route_with_ctx(target, args, auth.as_ref(), None)).await,
696                None => service.route_with_ctx(target, args, auth.as_ref(), None).await,
697            }
698        }
699        None => service.schema_for_child(target, args).await,
700    };
701    let mut stream = match routed {
702        Ok(s) => s,
703        Err(e) => {
704            let v = crate::plexus::error_item(service.runtime_namespace(), &e);
705            let frame = json!({ "jsonrpc": "2.0", "method": HOST_CALL, "params": { "subscription": sid, "result": v } });
706            let _ = out.send(serde_json::to_vec(&frame).unwrap_or_default());
707            return;
708        }
709    };
710    let Some(under) = under else {
711        while let Some(i) = stream.next().await {
712            item(&i);
713        }
714        return;
715    };
716    let mut ended = under.ended.subscribe();
717    if let Some(why) = ended.borrow().clone() {
718        return item(&ended_item(&why));
719    }
720    // The forwarded call's grant, asked again when the grants move.
721    let mut moved = under.reach.generation().map(|g| g.subscribe());
722    loop {
723        tokio::select! {
724            next = stream.next() => match next {
725                Some(i) => {
726                    let terminal = matches!(i, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. });
727                    item(&i);
728                    if terminal {
729                        return;
730                    }
731                }
732                None => return,
733            },
734            _ = ended.changed() => {
735                let why = ended.borrow().clone().unwrap_or_default();
736                return item(&ended_item(&why));
737            }
738            changed = async { match moved.as_mut() { Some(m) => m.changed().await, None => std::future::pending().await } } => {
739                if changed.is_err() {
740                    moved = None;
741                } else if under.reach.current().is_none() {
742                    return item(&ended_item("its grant was revoked"));
743                }
744            }
745        }
746    }
747}
748
749#[cfg(test)]
750mod tests {
751    use super::*;
752    use plexus_auth_core::grants::{Gate, Membership, Memberships, Resolve, RoleTable, ScopeRef};
753
754    /// The narrowed caller holds what it held, only where the call reached.
755    #[test]
756    fn a_call_back_is_narrowed_to_the_forwarded_calls_scopes() {
757        struct Held;
758        impl Memberships for Held {
759            fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
760                vec![Membership { principal: who.clone(), role: plexus_auth_core::RoleName::new("viewer"), scope: ScopeRef::Everywhere }]
761            }
762        }
763        struct Chain;
764        impl Resolve for Chain {
765            fn chain(&self, t: &str) -> Option<Vec<ScopeRef>> {
766                Some(vec![ScopeRef::named(t), ScopeRef::Everywhere])
767            }
768        }
769        let roles = RoleTable::from_lists([("viewer", ["a.get", "b.get"])]);
770        let gate = Gate::new(Arc::new(Held), Arc::new(roles), Arc::new(Chain));
771        let who = AuthContext::for_principal(&"key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".parse().unwrap(), "s", vec![], Value::Null);
772        let wide = gate.check(Some(&who), &plexus_auth_core::grants::Grant::new("a.get"), None).unwrap();
773        assert_eq!(narrowed(&who, &wide, None, None).metadata, who.metadata, "held everywhere: nothing added");
774        // A reach held on `X` alone: the call back reaches `b.get` on X, not on Y.
775        let mut n = who.clone();
776        n.metadata[CEILING_KEY] = json!([["admin@X"]]);
777        let narrow = n.clone();
778        let g = plexus_auth_core::grants::Grant::new("b.get");
779        assert!(gate.check(Some(&narrow), &g, Some("X")).is_ok());
780        assert!(gate.check(Some(&narrow), &g, Some("Y")).is_err());
781        let layered = narrowed(&n, &gate.check(Some(&n), &plexus_auth_core::grants::Grant::new("a.get"), None).unwrap(), None, None);
782        assert_eq!(layered.metadata[CEILING_KEY].as_array().unwrap().len(), 2, "{:?}", layered.metadata);
783        assert!(gate.check(Some(&layered), &g, Some("Y")).is_err());
784    }
785
786    /// DYNAUTH-5: a declared need is called only once consented, and only
787    /// on its consented scopes; without consent kept, NEST-16's rule.
788    #[test]
789    fn a_need_is_held_to_its_consent() {
790        let up = Upcalls::new(None, false);
791        let need = |m: &str| crate::plexus::schema::Need { method: m.into(), hash: String::new() };
792        up.set_needs(Some(&[need("shop.items"), need("shop.orders")]));
793        assert_eq!(up.allows("shop.items").unwrap(), Some(vec!["*".to_string()]), "no consent kept: declared is enough");
794        assert!(up.allows("shop.secret").is_err(), "undeclared");
795        assert_eq!(up.allows(parent::HOST_WHOAMI).unwrap(), None, "the standard four need nothing");
796        up.set_consent(Some(vec![Consented { method: "shop.items".into(), scopes: vec!["MENGER".into()] }]));
797        assert_eq!(up.allows("shop.items").unwrap(), Some(vec!["MENGER".to_string()]));
798        let (e, said) = up.allows("shop.orders").unwrap_err();
799        assert!(said.contains("consented"), "{said}");
800        assert!(e.to_string().contains("shop.orders"));
801        up.set_consent(Some(vec![]));
802        assert!(up.allows("shop.items").is_err(), "an empty consent: nothing upward");
803        // The consented scope is one more ceiling layer.
804        let who = AuthContext::for_principal(&"key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".parse().unwrap(), "s", vec![], Value::Null);
805        let c = consented(&who, "shop.items", &["MENGER".to_string()]);
806        assert_eq!(c.metadata[CEILING_KEY], json!([["shop.items@MENGER"]]));
807    }
808
809    /// DYNAUTH-12: a keyed child's call back carries a proof by its key,
810    /// for this method and call; a pipe child's needs none.
811    #[test]
812    fn a_call_back_under_a_bound_token_needs_its_proof() {
813        use crate::plexus::peer_token::{prove, MintRequest, PeerKey, TokenIssuer};
814        let (host, child, thief) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
815        let issuer = TokenIssuer::new(host);
816        let req = |peer_key: Option<String>| MintRequest { sub: "key:x".into(), peer_key, name: "w".into(), scope: vec![], call: "u1".into(), method: "w.m".into(), presented: None };
817        let (token, claims) = issuer.mint(req(Some(child.kid().into()))).unwrap();
818        let m = Minted { token: token.clone(), claims };
819        let up = Upcalls::new(None, false);
820        let no_proof = presented_ok(&up, &m, &json!({}), "shop.items", "u1").unwrap_err();
821        assert!(no_proof.contains("proof"), "{no_proof}");
822        let good = json!({ "token": token, "proof": prove(&child, &token, "shop.items", "u1") });
823        assert_eq!(presented_ok(&up, &m, &good, "shop.items", "u1"), Ok(()));
824        assert!(presented_ok(&up, &m, &good, "shop.items", "u1").is_err(), "a proof is used once");
825        let stolen = json!({ "proof": prove(&thief, &token, "shop.items", "u1") });
826        assert!(presented_ok(&up, &m, &stolen, "shop.items", "u1").unwrap_err().contains("another key"));
827        let other_method = json!({ "proof": prove(&child, &token, "shop.items", "u1") });
828        assert!(presented_ok(&up, &m, &other_method, "auth.grant", "u1").is_err());
829        let other_token = json!({ "token": "a.b.c", "proof": prove(&child, &token, "shop.items", "u1") });
830        assert!(presented_ok(&up, &m, &other_token, "shop.items", "u1").unwrap_err().contains("not the one"));
831        // A pipe's token: bound to no key, no proof asked.
832        let (token, claims) = issuer.mint(req(None)).unwrap();
833        assert_eq!(presented_ok(&up, &Minted { token, claims }, &json!({}), "shop.items", "u1"), Ok(()));
834    }
835
836    /// KEEL-19: the one decision — a need declared and consented is decided;
837    /// once the child is revoked, nothing but the standard interface is.
838    #[test]
839    fn a_revoked_child_is_decided_nothing() {
840        let up = Upcalls::new(None, false);
841        let need = |m: &str| crate::plexus::schema::Need { method: m.into(), hash: String::new() };
842        up.set_needs(Some(&[need("dyn.peer.b.forecast")]));
843        up.set_consent(Some(vec![Consented { method: "dyn.peer.b.forecast".into(), scopes: vec!["*".into()] }]));
844        assert_eq!(up.decide("dyn.peer.b.forecast", None).unwrap(), Some(Decided { consented: vec!["*".into()], held: None }));
845        up.revoke("compromised");
846        let (_, said) = up.decide("dyn.peer.b.forecast", None).unwrap_err();
847        assert!(said.contains("revoked (compromised)"), "{said}");
848        assert_eq!(up.decide(parent::HOST_WHOAMI, None).unwrap(), None, "the standard interface is not this ticket's");
849    }
850
851    /// KEEL-19 (KEEL-22's first row): once revoked, nothing is opened to call
852    /// back under — whatever `forward` awaited before it asked.
853    #[tokio::test]
854    async fn a_revoked_child_is_opened_nothing() {
855        let up = Upcalls::new(None, false);
856        let svc = crate::plexus::DynamicHub::new("svc");
857        let reach = plexus_auth_core::grants::Reach::everywhere();
858        let open = |id: &'static str| crate::plexus::service_scope::scope(svc.downgrade(), { let up = Arc::clone(&up); let reach = reach.clone(); async move { up.open(id, None, &reach, None, None) } });
859        assert!(open("c1").await.is_some());
860        up.revoke("compromised");
861        assert!(open("c2").await.is_none(), "opened after the revoke");
862        assert_eq!(up.open_now(), 0);
863    }
864
865    /// DYNAUTH-7: a revoked child's calls back end, each saying why.
866    #[tokio::test]
867    async fn revoking_ends_every_call_back() {
868        let up = Upcalls::new(None, false);
869        let svc = crate::plexus::DynamicHub::new("svc");
870        let reach = plexus_auth_core::grants::Reach::everywhere();
871        let guard = crate::plexus::service_scope::scope(svc.downgrade(), async { up.open("c1", None, &reach, None, None) }).await.expect("opened");
872        let mut ended = guard.under.ended.subscribe();
873        assert_eq!(up.open_now(), 1);
874        up.end_all("revoked: compromised");
875        assert_eq!(up.open_now(), 0);
876        ended.changed().await.unwrap();
877        assert_eq!(ended.borrow().as_deref(), Some("revoked: compromised"));
878    }
879}