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