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}
118
119impl Upcalls {
120    pub(super) fn new(host: Option<WeakService>, legacy: bool) -> Arc<Self> {
121        Arc::new(Self { host: Mutex::new(host), under: Mutex::default(), made: AtomicU64::new(0), proofs: Default::default(), needs: Mutex::default(), consent: Mutex::default(), legacy })
122    }
123
124    /// NEST-16: what the mounted child's schema says it needs.
125    pub(super) fn set_needs(&self, needs: Option<&[crate::plexus::schema::Need]>) {
126        *self.needs.lock().unwrap() = needs.map(|n| n.iter().map(|n| n.method.clone()).collect::<Vec<_>>().into());
127    }
128
129    /// DYNAUTH-5: what an admin consented to (`None`: no consent kept).
130    pub(super) fn set_consent(&self, consent: Option<Vec<Consented>>) {
131        *self.consent.lock().unwrap() = consent.map(Into::into);
132    }
133
134    /// DYNAUTH-5: the consent kept now.
135    pub(super) fn consent(&self) -> Option<Arc<[Consented]>> {
136        self.consent.lock().unwrap().clone()
137    }
138
139    /// NEST-16: may the child call `method` up — the standard interface, a
140    /// need, or anything under the legacy rule for a child that declares
141    /// none. DYNAUTH-5: a need must also be consented, when consent is
142    /// kept. `Ok(Some(scopes))` for a need (routed under its own grant,
143    /// only on `scopes` — `["*"]` anywhere), `Ok(None)` for the rest;
144    /// `Err` the refusal, said.
145    fn allows(&self, method: &str) -> Result<Option<Vec<String>>, (PlexusError, String)> {
146        if parent::is_standard(method) {
147            return Ok(None);
148        }
149        let declared = match self.needs.lock().unwrap().as_ref() {
150            Some(needs) => needs.iter().any(|n| n == method),
151            None if self.legacy => return Ok(None),
152            None => false,
153        };
154        if !declared {
155            let e = parent::not_needed(method);
156            let said = e.to_string();
157            return Err((e, said));
158        }
159        match self.consent.lock().unwrap().as_ref() {
160            None => Ok(Some(vec!["*".into()])),
161            Some(c) => match c.iter().find(|c| c.method == method) {
162                Some(c) => Ok(Some(c.scopes.clone())),
163                None => Err((
164                    parent::not_needed(method),
165                    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"),
166                )),
167            },
168        }
169    }
170
171    /// The service the child is in: the one given, else the one a call was
172    /// routed in when it was first seen.
173    fn host(&self) -> Option<WeakService> {
174        let mut h = self.host.lock().unwrap();
175        if h.as_ref().and_then(WeakService::upgrade).is_none() {
176            if let Some(now) = service_scope::current() {
177                *h = Some(now);
178            }
179        }
180        h.clone()
181    }
182
183    /// A forwarded call opens: the child may call back under `id` until the
184    /// guard is dropped (or [`UnderGuard::end`]ed).
185    pub(super) fn open(self: &Arc<Self>, id: &str, auth: Option<&AuthContext>, reach: &Reach, minted: Option<Minted>) -> Option<UnderGuard> {
186        let service = service_scope::current().or_else(|| self.host())?;
187        let (ended, _) = watch::channel(None);
188        let under = Arc::new(Under { auth: auth.cloned(), reach: reach.clone(), service, ended, minted });
189        self.under.lock().unwrap().insert(id.to_string(), Arc::clone(&under));
190        Some(UnderGuard { up: Arc::clone(self), id: id.to_string(), under })
191    }
192
193    /// DYNAUTH-12: the needs a token minted now may hold, each by the grant
194    /// the service holds a call to it to and the scopes it is consented on
195    /// (`["*"]` without consent kept).
196    pub(super) fn need_grants(&self, service: &crate::plexus::DynamicHub) -> Vec<(String, Vec<String>)> {
197        let needs = self.needs.lock().unwrap().clone().unwrap_or_else(|| Vec::<String>::new().into());
198        let consent = self.consent.lock().unwrap().clone();
199        needs
200            .iter()
201            .filter_map(|m| {
202                let scopes = match &consent {
203                    None => vec!["*".to_string()],
204                    Some(c) => c.iter().find(|c| &c.method == m)?.scopes.clone(),
205                };
206                Some((service.grant_at(m)?, scopes))
207            })
208            .collect()
209    }
210
211    /// DYNAUTH-7: every forwarded call open now ends for the child's calls
212    /// back — each made under one ends with one error item, saying `why`.
213    pub(super) fn end_all(&self, why: &str) {
214        let open: Vec<Arc<Under>> = self.under.lock().unwrap().drain().map(|(_, u)| u).collect();
215        for u in open {
216            u.ended.send_if_modified(|e| {
217                if e.is_none() {
218                    *e = Some(why.to_string());
219                    true
220                } else {
221                    false
222                }
223            });
224        }
225    }
226
227    /// How many forwarded calls the child may call back under now.
228    pub(super) fn open_now(&self) -> usize {
229        self.under.lock().unwrap().len()
230    }
231}
232
233/// A forwarded call's standing for the child's calls back: dropped, the
234/// calls made under it end.
235pub(super) struct UnderGuard {
236    up: Arc<Upcalls>,
237    id: String,
238    under: Arc<Under>,
239}
240
241impl UnderGuard {
242    /// The forwarded call has ended, and why.
243    pub(super) fn end(&self, why: &str) {
244        self.up.under.lock().unwrap().remove(&self.id);
245        self.under.ended.send_if_modified(|e| {
246            if e.is_none() {
247                *e = Some(why.to_string());
248                true
249            } else {
250                false
251            }
252        });
253    }
254}
255
256impl Drop for UnderGuard {
257    fn drop(&mut self) {
258        self.end("it ended");
259    }
260}
261
262/// `auth`, its reach narrowed to `reach`'s scopes: one more ceiling layer,
263/// `admin@<scope>` each — none when `reach` holds everywhere. DYNAUTH-6:
264/// `admin@X` in a ceiling layer is not the admin role: it reads "any grant,
265/// only on X" (the gate's `admin` lists every grant), so it narrows by
266/// *where* only — the outer bound, kept for a child under the legacy rule.
267/// What a child may *do* is the need's own grant (below) and its token's
268/// scope. NEST-16 (TM-1): for a need, the layer is its own grant on
269/// each of those scopes (`shop.items@*` when everywhere), so the call back
270/// reaches that method and nothing else, whatever the caller holds.
271fn narrowed(auth: &AuthContext, reach: &Reach, grant: Option<&str>) -> AuthContext {
272    if reach.is_everywhere() && grant.is_none() {
273        return auth.clone();
274    }
275    let mut ctx = auth.clone();
276    let mut layers: Vec<Value> = match ctx.metadata.get(CEILING_KEY) {
277        Some(Value::Array(items)) if items.iter().all(Value::is_string) => vec![Value::Array(items.clone())],
278        Some(Value::Array(items)) => items.clone(),
279        Some(other) => vec![other.clone()],
280        None => Vec::new(),
281    };
282    let what = grant.unwrap_or(plexus_auth_core::grants::ADMIN);
283    let scopes: Vec<String> = if reach.is_everywhere() { vec!["*".into()] } else { reach.held_on().iter().map(|s| s.to_string()).collect() };
284    layers.push(Value::Array(scopes.iter().map(|s| json!(format!("{what}@{s}"))).collect()));
285    if !ctx.metadata.is_object() {
286        ctx.metadata = json!({});
287    }
288    ctx.metadata[CEILING_KEY] = Value::Array(layers);
289    ctx
290}
291
292/// DYNAUTH-12: the token and proof a keyed child presents with a call
293/// back, checked against the token minted for the call it names.
294fn presented_ok(up: &Upcalls, m: &Minted, params: &Value, method: &str, under: &str) -> Result<(), String> {
295    if let Some(t) = params.get("token").and_then(Value::as_str) {
296        if t != m.token {
297            return Err("the token presented is not the one minted for this call".into());
298        }
299    }
300    if m.claims.cnf.is_none() {
301        return Ok(());
302    }
303    let proof = params.get("proof").and_then(Value::as_str).ok_or_else(|| {
304        "a call back under a key-bound token carries a proof of possession (`proof`): none was sent".to_string()
305    })?;
306    crate::plexus::peer_token::check_proof(proof, &m.token, &m.claims, method, under, crate::plexus::peer_token::now(), &up.proofs)
307        .map_err(|e| format!("the call back's {e}"))
308}
309
310/// DYNAUTH-5: `auth` with one more ceiling layer, `grant@<scope>` for each
311/// consented scope — a need consented on `MENGER` reaches only there.
312fn consented(auth: &AuthContext, grant: &str, scopes: &[String]) -> AuthContext {
313    let mut ctx = auth.clone();
314    let mut layers: Vec<Value> = match ctx.metadata.get(CEILING_KEY) {
315        Some(Value::Array(items)) if items.iter().all(Value::is_string) => vec![Value::Array(items.clone())],
316        Some(Value::Array(items)) => items.clone(),
317        Some(other) => vec![other.clone()],
318        None => Vec::new(),
319    };
320    layers.push(Value::Array(scopes.iter().map(|s| json!(format!("{grant}@{s}"))).collect()));
321    if !ctx.metadata.is_object() {
322        ctx.metadata = json!({});
323    }
324    ctx.metadata[CEILING_KEY] = Value::Array(layers);
325    ctx
326}
327
328/// A refusal at the JSON-RPC layer, typed, said in its own words.
329fn refusal_said(id: &Value, e: &PlexusError, said: &str) -> Value {
330    let mut r = refusal(id, e);
331    r["error"]["message"] = json!(said);
332    r
333}
334
335/// A refusal at the JSON-RPC layer, typed.
336fn refusal(id: &Value, e: &PlexusError) -> Value {
337    let mut error = serde_json::to_value(plexus_error_to_jsonrpc(e)).unwrap_or_default();
338    // The reason in words, as the error item says it (the typed `data`
339    // carries the kind).
340    error["message"] = json!(e.to_string());
341    json!({ "jsonrpc": "2.0", "id": id, "error": error })
342}
343
344/// The calls a connection serves its child, by the subscription id this
345/// side minted.
346#[derive(Default)]
347pub(super) struct Served {
348    next: AtomicU64,
349    open: Mutex<HashMap<u64, tokio::task::AbortHandle>>,
350}
351
352impl Served {
353    /// The connection went: every call it served ends.
354    pub(super) fn abort_all(&self) {
355        for (_, h) in self.open.lock().unwrap().drain() {
356            h.abort();
357        }
358    }
359}
360
361/// A request from the child: `_host.call` (opens) or `_host.call_unsub`
362/// (lets go). `out` is the connection's writer.
363pub(super) fn on_request(up: &Arc<Upcalls>, served: &Arc<Served>, out: &mpsc::UnboundedSender<Vec<u8>>, name: &str, id: Value, method: &str, params: Value) {
364    let send = |v: Value| {
365        let _ = out.send(serde_json::to_vec(&v).unwrap_or_default());
366    };
367    if method == HOST_CALL_UNSUB {
368        let held = params.get(0).and_then(Value::as_u64).and_then(|sid| served.open.lock().unwrap().remove(&sid));
369        let stopped = held.map(|h| h.abort()).is_some();
370        return send(json!({ "jsonrpc": "2.0", "id": id, "result": stopped }));
371    }
372    let Some(mut target) = params.get("method").and_then(Value::as_str).map(str::to_string) else {
373        return send(refusal(&id, &PlexusError::invalid_params("`_host.call` names the `method` it calls")));
374    };
375    let args = params.get("params").cloned().unwrap_or_else(|| json!({}));
376    // DYNAUTH-12: the method as the child asked it (what its proof names).
377    let presented = target.clone();
378    let under_id = params.get("under").and_then(Value::as_str).map(str::to_string);
379    // NEST-16: the standard upward interface, the child's needs, or (a
380    // child that declares none, under the legacy option) NEST-11's rule.
381    let need = match up.allows(&target) {
382        Ok(need) => need,
383        Err((e, said)) => return send(refusal_said(&id, &e, &said)),
384    };
385    let standard = matches!(target.as_str(), parent::HOST_WHOAMI | parent::HOST_LOG | parent::HOST_NOTIFY);
386    if target == parent::HOST_SCHEMA {
387        if let Some(svc) = up.host().and_then(|h| h.upgrade()) {
388            target = format!("{}.schema", svc.runtime_namespace());
389        }
390    }
391    let route = match &under_id {
392        Some(u) => match up.under.lock().unwrap().get(u).cloned() {
393            Some(under) => {
394                // DYNAUTH-12: under a call whose token is bound to the
395                // child's key, every call back carries a proof of
396                // possession by that key, for this method and call (a
397                // child on the service's own pipe needs none, D3).
398                if let Some(m) = &under.minted {
399                    if let Err(e) = presented_ok(up, m, &params, &presented, u) {
400                        return send(refusal_said(&id, &PlexusError::Unauthenticated(e.clone()), &e));
401                    }
402                }
403                if standard {
404                    Route::Standard(under.service.clone(), under.auth.clone())
405                } else {
406                    // DYNAUTH-12: a need is held to the token's scope too.
407                    let need = match (&under.minted, need, under.service.upgrade()) {
408                        (Some(m), Some(_), Some(svc)) => {
409                            let held = svc.grant_at(&target).map(|g| m.claims.scopes_for(&g)).unwrap_or_default();
410                            if held.is_empty() {
411                                let e = parent::not_needed(&target);
412                                return send(refusal_said(&id, &e, &format!("`{target}` is not within the scope of the token minted for this call")));
413                            }
414                            Some(held)
415                        }
416                        (_, n, _) => n,
417                    };
418                    Route::Under(under, need)
419                }
420            }
421            None => {
422                return send(refusal(&id, &PlexusError::Unauthenticated(format!(
423                    "no call `{u}` is open into this child: a child calls its service only under a call it is serving, while it is open"
424                ))))
425            }
426        },
427        None => {
428            let schema = target.ends_with(".schema");
429            match (schema || standard, up.host()) {
430                (true, Some(host)) if standard => Route::Standard(host, None),
431                (true, Some(host)) => Route::Schema(host),
432                (true, None) => {
433                    return send(refusal(&id, &PlexusError::Unauthenticated(
434                        "this child's service is not known yet: it is learned with the first call forwarded to it".into(),
435                    )))
436                }
437                (false, _) => {
438                    return send(refusal(&id, &PlexusError::Unauthenticated(format!(
439                        "`{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`"
440                    ))))
441                }
442            }
443        }
444    };
445    up.made.fetch_add(1, Ordering::Relaxed);
446    let sid = served.next.fetch_add(1, Ordering::Relaxed) + 1;
447    // spec/02: the subscription id before any of its items.
448    send(json!({ "jsonrpc": "2.0", "id": id, "result": sid }));
449    let (out, served2, name) = (out.clone(), Arc::clone(served), name.to_string());
450    // Registered before it can end, so its end always finds it.
451    let mut open = served.open.lock().unwrap();
452    let task = tokio::spawn(async move {
453        pump(route, &out, sid, &name, &target, args).await;
454        served2.open.lock().unwrap().remove(&sid);
455    });
456    open.insert(sid, task.abort_handle());
457}
458
459enum Route {
460    /// A call under a forwarded call; `Some(scopes)`: one of the child's
461    /// needs, consented on those scopes (DYNAUTH-5).
462    Under(Arc<Under>, Option<Vec<String>>),
463    Schema(WeakService),
464    /// NEST-16: `host.whoami`, `host.log` or `host.notify`, answered by the
465    /// service itself, for the caller of the call it is made under.
466    Standard(WeakService, Option<AuthContext>),
467}
468
469/// One call the child made: routed, its items written back under `sid`
470/// until the last — or until the call it was made under ends.
471async fn pump(route: Route, out: &mpsc::UnboundedSender<Vec<u8>>, sid: u64, name: &str, target: &str, args: Value) {
472    let item = |i: &PlexusStreamItem| {
473        let frame = json!({ "jsonrpc": "2.0", "method": HOST_CALL, "params": { "subscription": sid, "result": i } });
474        let _ = out.send(serde_json::to_vec(&frame).unwrap_or_default());
475    };
476    let gone = || PlexusStreamItem::error(meta(name), plexus_client::RemoteError::Unauthenticated, false);
477    let ended_item = |why: &str| {
478        let mut e = gone();
479        if let PlexusStreamItem::Error { message, .. } = &mut e {
480            *message = format!("the call this was made under has ended ({why})");
481        }
482        e
483    };
484    let (under, service) = match &route {
485        Route::Under(u, _) => (Some(Arc::clone(u)), u.service.upgrade()),
486        Route::Schema(s) | Route::Standard(s, _) => (None, s.upgrade()),
487    };
488    let Some(service) = service else {
489        let mut e = gone();
490        if let PlexusStreamItem::Error { message, .. } = &mut e {
491            *message = "the service this child is mounted in has gone".into();
492        }
493        return item(&e);
494    };
495    if let Route::Standard(_, caller) = &route {
496        for i in parent::standard_answer(&service, name, target, &args, caller.as_ref()).unwrap_or_default() {
497            item(&i);
498        }
499        return;
500    }
501    let need = match &route {
502        Route::Under(_, n) => n.clone(),
503        _ => None,
504    };
505    let routed = match &under {
506        Some(u) => {
507            // TM-1: a need is routed under its own grant as one more ceiling;
508            // DYNAUTH-5: and only on the scopes it was consented on.
509            let grant = need.as_ref().and_then(|_| service.grant_at(target));
510            let auth = u.auth.as_ref().map(|a| narrowed(a, &u.reach, grant.as_deref()));
511            let auth = match (auth, &grant, &need) {
512                (Some(a), Some(g), Some(scopes)) if !scopes.iter().any(|s| s == "*") => Some(consented(&a, g, scopes)),
513                (a, _, _) => a,
514            };
515            // DYNAUTH-6: a call it reaches into another child is minted as
516            // an exchange of the token this call back was made under.
517            match &u.minted {
518                Some(m) => PRESENTED.scope(m.claims.clone(), service.route_with_ctx(target, args, auth.as_ref(), None)).await,
519                None => service.route_with_ctx(target, args, auth.as_ref(), None).await,
520            }
521        }
522        None => service.schema_for_child(target, args).await,
523    };
524    let mut stream = match routed {
525        Ok(s) => s,
526        Err(e) => {
527            let v = crate::plexus::error_item(service.runtime_namespace(), &e);
528            let frame = json!({ "jsonrpc": "2.0", "method": HOST_CALL, "params": { "subscription": sid, "result": v } });
529            let _ = out.send(serde_json::to_vec(&frame).unwrap_or_default());
530            return;
531        }
532    };
533    let Some(under) = under else {
534        while let Some(i) = stream.next().await {
535            item(&i);
536        }
537        return;
538    };
539    let mut ended = under.ended.subscribe();
540    if let Some(why) = ended.borrow().clone() {
541        return item(&ended_item(&why));
542    }
543    // The forwarded call's grant, asked again when the grants move.
544    let mut moved = under.reach.generation().map(|g| g.subscribe());
545    loop {
546        tokio::select! {
547            next = stream.next() => match next {
548                Some(i) => {
549                    let terminal = matches!(i, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. });
550                    item(&i);
551                    if terminal {
552                        return;
553                    }
554                }
555                None => return,
556            },
557            _ = ended.changed() => {
558                let why = ended.borrow().clone().unwrap_or_default();
559                return item(&ended_item(&why));
560            }
561            changed = async { match moved.as_mut() { Some(m) => m.changed().await, None => std::future::pending().await } } => {
562                if changed.is_err() {
563                    moved = None;
564                } else if under.reach.current().is_none() {
565                    return item(&ended_item("its grant was revoked"));
566                }
567            }
568        }
569    }
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575    use plexus_auth_core::grants::{Gate, Membership, Memberships, Resolve, RoleTable, ScopeRef};
576
577    /// The narrowed caller holds what it held, only where the call reached.
578    #[test]
579    fn a_call_back_is_narrowed_to_the_forwarded_calls_scopes() {
580        struct Held;
581        impl Memberships for Held {
582            fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
583                vec![Membership { principal: who.clone(), role: plexus_auth_core::RoleName::new("viewer"), scope: ScopeRef::Everywhere }]
584            }
585        }
586        struct Chain;
587        impl Resolve for Chain {
588            fn chain(&self, t: &str) -> Option<Vec<ScopeRef>> {
589                Some(vec![ScopeRef::named(t), ScopeRef::Everywhere])
590            }
591        }
592        let roles = RoleTable::from_lists([("viewer", ["a.get", "b.get"])]);
593        let gate = Gate::new(Arc::new(Held), Arc::new(roles), Arc::new(Chain));
594        let who = AuthContext::for_principal(&"key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".parse().unwrap(), "s", vec![], Value::Null);
595        let wide = gate.check(Some(&who), &plexus_auth_core::grants::Grant::new("a.get"), None).unwrap();
596        assert_eq!(narrowed(&who, &wide, None).metadata, who.metadata, "held everywhere: nothing added");
597        // A reach held on `X` alone: the call back reaches `b.get` on X, not on Y.
598        let mut n = who.clone();
599        n.metadata[CEILING_KEY] = json!([["admin@X"]]);
600        let narrow = n.clone();
601        let g = plexus_auth_core::grants::Grant::new("b.get");
602        assert!(gate.check(Some(&narrow), &g, Some("X")).is_ok());
603        assert!(gate.check(Some(&narrow), &g, Some("Y")).is_err());
604        let layered = narrowed(&n, &gate.check(Some(&n), &plexus_auth_core::grants::Grant::new("a.get"), None).unwrap(), None);
605        assert_eq!(layered.metadata[CEILING_KEY].as_array().unwrap().len(), 2, "{:?}", layered.metadata);
606        assert!(gate.check(Some(&layered), &g, Some("Y")).is_err());
607    }
608
609    /// DYNAUTH-5: a declared need is called only once consented, and only
610    /// on its consented scopes; without consent kept, NEST-16's rule.
611    #[test]
612    fn a_need_is_held_to_its_consent() {
613        let up = Upcalls::new(None, false);
614        let need = |m: &str| crate::plexus::schema::Need { method: m.into(), hash: String::new() };
615        up.set_needs(Some(&[need("shop.items"), need("shop.orders")]));
616        assert_eq!(up.allows("shop.items").unwrap(), Some(vec!["*".to_string()]), "no consent kept: declared is enough");
617        assert!(up.allows("shop.secret").is_err(), "undeclared");
618        assert_eq!(up.allows(parent::HOST_WHOAMI).unwrap(), None, "the standard four need nothing");
619        up.set_consent(Some(vec![Consented { method: "shop.items".into(), scopes: vec!["MENGER".into()] }]));
620        assert_eq!(up.allows("shop.items").unwrap(), Some(vec!["MENGER".to_string()]));
621        let (e, said) = up.allows("shop.orders").unwrap_err();
622        assert!(said.contains("consented"), "{said}");
623        assert!(e.to_string().contains("shop.orders"));
624        up.set_consent(Some(vec![]));
625        assert!(up.allows("shop.items").is_err(), "an empty consent: nothing upward");
626        // The consented scope is one more ceiling layer.
627        let who = AuthContext::for_principal(&"key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".parse().unwrap(), "s", vec![], Value::Null);
628        let c = consented(&who, "shop.items", &["MENGER".to_string()]);
629        assert_eq!(c.metadata[CEILING_KEY], json!([["shop.items@MENGER"]]));
630    }
631
632    /// DYNAUTH-12: a keyed child's call back carries a proof by its key,
633    /// for this method and call; a pipe child's needs none.
634    #[test]
635    fn a_call_back_under_a_bound_token_needs_its_proof() {
636        use crate::plexus::peer_token::{prove, MintRequest, PeerKey, TokenIssuer};
637        let (host, child, thief) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
638        let issuer = TokenIssuer::new(host);
639        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 };
640        let (token, claims) = issuer.mint(req(Some(child.kid().into()))).unwrap();
641        let m = Minted { token: token.clone(), claims };
642        let up = Upcalls::new(None, false);
643        let no_proof = presented_ok(&up, &m, &json!({}), "shop.items", "u1").unwrap_err();
644        assert!(no_proof.contains("proof"), "{no_proof}");
645        let good = json!({ "token": token, "proof": prove(&child, &token, "shop.items", "u1") });
646        assert_eq!(presented_ok(&up, &m, &good, "shop.items", "u1"), Ok(()));
647        assert!(presented_ok(&up, &m, &good, "shop.items", "u1").is_err(), "a proof is used once");
648        let stolen = json!({ "proof": prove(&thief, &token, "shop.items", "u1") });
649        assert!(presented_ok(&up, &m, &stolen, "shop.items", "u1").unwrap_err().contains("another key"));
650        let other_method = json!({ "proof": prove(&child, &token, "shop.items", "u1") });
651        assert!(presented_ok(&up, &m, &other_method, "auth.grant", "u1").is_err());
652        let other_token = json!({ "token": "a.b.c", "proof": prove(&child, &token, "shop.items", "u1") });
653        assert!(presented_ok(&up, &m, &other_token, "shop.items", "u1").unwrap_err().contains("not the one"));
654        // A pipe's token: bound to no key, no proof asked.
655        let (token, claims) = issuer.mint(req(None)).unwrap();
656        assert_eq!(presented_ok(&up, &Minted { token, claims }, &json!({}), "shop.items", "u1"), Ok(()));
657    }
658
659    /// DYNAUTH-7: a revoked child's calls back end, each saying why.
660    #[tokio::test]
661    async fn revoking_ends_every_call_back() {
662        let up = Upcalls::new(None, false);
663        let svc = crate::plexus::DynamicHub::new("svc");
664        let reach = plexus_auth_core::grants::Reach::everywhere();
665        let guard = crate::plexus::service_scope::scope(svc.downgrade(), async { up.open("c1", None, &reach, None) }).await.expect("opened");
666        let mut ended = guard.under.ended.subscribe();
667        assert_eq!(up.open_now(), 1);
668        up.end_all("revoked: compromised");
669        assert_eq!(up.open_now(), 0);
670        ended.changed().await.unwrap();
671        assert_eq!(ended.borrow().as_deref(), Some("revoked: compromised"));
672    }
673}