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 revoked: Mutex<Option<String>>,
120 schemas: Mutex<Arc<[String]>>,
123}
124
125#[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 pub(super) fn set_schemas(&self, paths: &[String]) {
143 *self.schemas.lock().unwrap() = paths.to_vec().into();
144 }
145
146 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 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 pub(super) fn set_consent(&self, consent: Option<Vec<Consented>>) {
198 *self.consent.lock().unwrap() = consent.map(Into::into);
199 }
200
201 pub(super) fn consent(&self) -> Option<Arc<[Consented]>> {
203 self.consent.lock().unwrap().clone()
204 }
205
206 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 pub(super) fn revoked(&self) -> Option<String> {
215 self.revoked.lock().unwrap().clone()
216 }
217
218 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 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 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 pub(super) fn open(self: &Arc<Self>, id: &str, auth: Option<&AuthContext>, reach: &Reach, minted: Option<Minted>) -> Option<UnderGuard> {
299 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 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 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 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 pub(super) fn open_now(&self) -> usize {
354 self.under.lock().unwrap().len()
355 }
356}
357
358fn 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
380pub(super) struct UnderGuard {
383 up: Arc<Upcalls>,
384 id: String,
385 under: Arc<Under>,
386}
387
388impl UnderGuard {
389 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
409fn 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
439fn 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
457fn 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
475fn 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
482fn refusal(id: &Value, e: &PlexusError) -> Value {
484 let mut error = serde_json::to_value(plexus_error_to_jsonrpc(e)).unwrap_or_default();
485 error["message"] = json!(e.to_string());
488 json!({ "jsonrpc": "2.0", "id": id, "error": error })
489}
490
491#[derive(Default)]
494pub(super) struct Served {
495 next: AtomicU64,
496 open: Mutex<HashMap<u64, tokio::task::AbortHandle>>,
497}
498
499impl Served {
500 pub(super) fn abort_all(&self) {
502 for (_, h) in self.open.lock().unwrap().drain() {
503 h.abort();
504 }
505 }
506}
507
508pub(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 let presented = target.clone();
525 let under_id = params.get("under").and_then(Value::as_str).map(str::to_string);
526 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 if let Some(m) = &under.minted {
547 if let Err(e) = presented_ok(up, m, ¶ms, &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 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 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 send(json!({ "jsonrpc": "2.0", "id": id, "result": sid }));
611 let (out, served2, name) = (out.clone(), Arc::clone(served), name.to_string());
612 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 Under(Arc<Under>, Option<Vec<String>>),
625 Schema(WeakService),
626 Standard(WeakService, Option<AuthContext>),
629}
630
631async 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 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 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 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 #[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 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 #[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 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 #[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 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 #[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 #[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 #[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}