1use 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
49pub const HOST_CALL: &str = "_host.call";
51pub const HOST_CALL_UNSUB: &str = "_host.call_unsub";
53
54#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
57pub struct Consented {
58 pub method: String,
60 pub scopes: Vec<String>,
62}
63
64pub(super) struct Under {
67 auth: Option<AuthContext>,
68 reach: Reach,
69 service: WeakService,
70 ended: watch::Sender<Option<String>>,
72 minted: Option<Minted>,
74}
75
76tokio::task_local! {
77 static PRESENTED: crate::plexus::peer_token::PeerClaims;
79}
80
81pub(super) fn presented() -> Option<crate::plexus::peer_token::PeerClaims> {
86 PRESENTED.try_with(Clone::clone).ok()
87}
88
89#[derive(Clone)]
91pub(super) struct Minted {
92 pub token: String,
93 pub claims: crate::plexus::peer_token::PeerClaims,
94}
95
96pub(super) struct Upcalls {
99 host: Mutex<Option<WeakService>>,
100 under: Mutex<HashMap<String, Arc<Under>>>,
101 pub made: AtomicU64,
103 proofs: crate::plexus::peer_token::ProofCache,
105 needs: Mutex<Option<Arc<[String]>>>,
108 consent: Mutex<Option<Arc<[Consented]>>>,
112 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 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 pub(super) fn set_consent(&self, consent: Option<Vec<Consented>>) {
131 *self.consent.lock().unwrap() = consent.map(Into::into);
132 }
133
134 pub(super) fn consent(&self) -> Option<Arc<[Consented]>> {
136 self.consent.lock().unwrap().clone()
137 }
138
139 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 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 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 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 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 pub(super) fn open_now(&self) -> usize {
229 self.under.lock().unwrap().len()
230 }
231}
232
233pub(super) struct UnderGuard {
236 up: Arc<Upcalls>,
237 id: String,
238 under: Arc<Under>,
239}
240
241impl UnderGuard {
242 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
262fn 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
292fn 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
310fn 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
328fn 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
335fn refusal(id: &Value, e: &PlexusError) -> Value {
337 let mut error = serde_json::to_value(plexus_error_to_jsonrpc(e)).unwrap_or_default();
338 error["message"] = json!(e.to_string());
341 json!({ "jsonrpc": "2.0", "id": id, "error": error })
342}
343
344#[derive(Default)]
347pub(super) struct Served {
348 next: AtomicU64,
349 open: Mutex<HashMap<u64, tokio::task::AbortHandle>>,
350}
351
352impl Served {
353 pub(super) fn abort_all(&self) {
355 for (_, h) in self.open.lock().unwrap().drain() {
356 h.abort();
357 }
358 }
359}
360
361pub(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 let presented = target.clone();
378 let under_id = params.get("under").and_then(Value::as_str).map(str::to_string);
379 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 if let Some(m) = &under.minted {
399 if let Err(e) = presented_ok(up, m, ¶ms, &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 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 send(json!({ "jsonrpc": "2.0", "id": id, "result": sid }));
449 let (out, served2, name) = (out.clone(), Arc::clone(served), name.to_string());
450 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 Under(Arc<Under>, Option<Vec<String>>),
463 Schema(WeakService),
464 Standard(WeakService, Option<AuthContext>),
467}
468
469async 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 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 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 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 #[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 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 #[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 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 #[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 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 #[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}