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 door: Option<String>,
79}
80
81tokio::task_local! {
82 static PRESENTED: crate::plexus::peer_token::PeerClaims;
84}
85
86pub(super) fn presented() -> Option<crate::plexus::peer_token::PeerClaims> {
91 PRESENTED.try_with(Clone::clone).ok()
92}
93
94#[derive(Clone)]
96pub(super) struct Minted {
97 pub token: String,
98 pub claims: crate::plexus::peer_token::PeerClaims,
99}
100
101pub(super) struct Upcalls {
104 host: Mutex<Option<WeakService>>,
105 under: Mutex<HashMap<String, Arc<Under>>>,
106 pub made: AtomicU64,
108 proofs: crate::plexus::peer_token::ProofCache,
110 needs: Mutex<Option<Arc<[String]>>>,
113 consent: Mutex<Option<Arc<[Consented]>>>,
117 legacy: bool,
122 revoked: Mutex<Option<String>>,
125 schemas: Mutex<Arc<[String]>>,
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
136pub(super) struct Decided {
137 pub consented: Vec<String>,
138 pub held: Option<Vec<String>>,
139}
140
141impl Upcalls {
142 pub(super) fn new(host: Option<WeakService>, legacy: bool) -> Arc<Self> {
143 Arc::new(Self { host: Mutex::new(host), under: Mutex::default(), made: AtomicU64::new(0), proofs: Default::default(), needs: Mutex::default(), consent: Mutex::default(), legacy, revoked: Mutex::default(), schemas: Mutex::new(Arc::from(Vec::new())) })
144 }
145
146 pub(super) fn set_schemas(&self, paths: &[String]) {
148 *self.schemas.lock().unwrap() = paths.to_vec().into();
149 }
150
151 pub(super) fn may_read_schema(&self, path: &str, crosses_slot: bool) -> Result<(), (PlexusError, String)> {
168 if let Some(why) = self.revoked() {
169 return Err((PlexusError::Unauthenticated(format!("this child is revoked ({why})")), format!("this child is revoked ({why}): it is answered no schema")));
170 }
171 let at_or_above = |n: &str| n == path || n.starts_with(&format!("{path}."));
172 let at_above_or_below = |s: &str| at_or_above(s) || path.starts_with(&format!("{s}."));
173 if self.schemas.lock().unwrap().iter().any(|s| at_above_or_below(s)) {
174 return Ok(());
175 }
176 let needs = self.needs.lock().unwrap().clone();
177 if let Some(needs) = &needs {
178 let consent = self.consent.lock().unwrap().clone();
179 let consented = |n: &String| consent.as_ref().is_none_or(|c| c.iter().any(|c| &c.method == n));
180 if needs.iter().filter(|n| consented(n)).any(|n| at_or_above(n)) {
181 return Ok(());
182 }
183 } else if self.legacy && !crosses_slot {
184 return Ok(());
185 }
186 let (ns, rest) = path.split_once('.').unwrap_or((path, ""));
187 let e = if rest.is_empty() {
188 PlexusError::ActivationNotFound(ns.to_string())
189 } else {
190 PlexusError::MethodNotFound { activation: ns.to_string(), method: rest.to_string() }
191 };
192 let said = format!("`{path}.schema` is not among what this child needs or was mounted to read: not found");
193 Err((e, said))
194 }
195
196 pub(super) fn set_needs(&self, needs: Option<&[crate::plexus::schema::Need]>) {
198 *self.needs.lock().unwrap() = needs.map(|n| n.iter().map(|n| n.method.clone()).collect::<Vec<_>>().into());
199 }
200
201 pub(super) fn set_consent(&self, consent: Option<Vec<Consented>>) {
203 *self.consent.lock().unwrap() = consent.map(Into::into);
204 }
205
206 pub(super) fn consent(&self) -> Option<Arc<[Consented]>> {
208 self.consent.lock().unwrap().clone()
209 }
210
211 pub(super) fn revoke(&self, why: &str) {
214 *self.revoked.lock().unwrap() = Some(why.to_string());
215 self.end_all(&format!("revoked: {why}"));
216 }
217
218 pub(super) fn revoked(&self) -> Option<String> {
220 self.revoked.lock().unwrap().clone()
221 }
222
223 pub(super) fn decide(&self, method: &str, token: Option<(&crate::plexus::DynamicHub, &crate::plexus::peer_token::PeerClaims)>) -> Result<Option<Decided>, (PlexusError, String)> {
231 if parent::is_standard(method) {
232 return Ok(None);
233 }
234 if let Some(why) = self.revoked() {
235 return Err((PlexusError::Unauthenticated(format!("this child is revoked ({why})")), format!("this child is revoked ({why}): nothing it asks is decided for it")));
236 }
237 let Some(consented) = self.allows(method)? else { return Ok(None) };
238 let held = match token {
239 None => None,
240 Some((svc, claims)) => {
241 let held = svc.grant_at(method).map(|g| claims.scopes_for(&g)).unwrap_or_default();
242 if held.is_empty() {
243 let e = parent::not_needed(method);
244 return Err((e, format!("`{method}` is not within the scope of the token minted for this call")));
245 }
246 let both = intersect(&held, &consented);
247 if both.is_empty() {
248 let e = parent::not_needed(method);
249 return Err((e, format!("`{method}` is consented on {consented:?} now, and the token holds it on {held:?}: nowhere both")));
250 }
251 Some(both)
252 }
253 };
254 Ok(Some(Decided { consented, held }))
255 }
256
257 fn allows(&self, method: &str) -> Result<Option<Vec<String>>, (PlexusError, String)> {
264 if parent::is_standard(method) {
265 return Ok(None);
266 }
267 let declared = match self.needs.lock().unwrap().as_ref() {
268 Some(needs) => needs.iter().any(|n| n == method),
269 None if self.legacy => return Ok(None),
270 None => false,
271 };
272 if !declared {
273 let e = parent::not_needed(method);
274 let said = e.to_string();
275 return Err((e, said));
276 }
277 match self.consent.lock().unwrap().as_ref() {
278 None => Ok(Some(vec!["*".into()])),
279 Some(c) => match c.iter().find(|c| c.method == method) {
280 Some(c) => Ok(Some(c.scopes.clone())),
281 None => Err((
282 parent::not_needed(method),
283 format!("`{method}` is among this child's needs, but no admin has consented to it (dyn.consent): a declared need is a request, not a grant"),
284 )),
285 },
286 }
287 }
288
289 pub(super) fn host(&self) -> Option<WeakService> {
292 let mut h = self.host.lock().unwrap();
293 if h.as_ref().and_then(WeakService::upgrade).is_none() {
294 if let Some(now) = service_scope::current() {
295 *h = Some(now);
296 }
297 }
298 h.clone()
299 }
300
301 pub(super) fn open(self: &Arc<Self>, id: &str, auth: Option<&AuthContext>, reach: &Reach, minted: Option<Minted>, door: Option<plexus_auth_core::grants::DispatchedCall>) -> Option<UnderGuard> {
304 let known = self.host();
307 let service = service_scope::current().or(known)?;
308 let (ended, _) = watch::channel(None);
309 let door = door.map(|d| format!("{}@/{}", d.grant(), d.at().path()));
310 let under = Arc::new(Under { auth: auth.cloned(), reach: reach.clone(), service, ended, minted, door });
311 {
312 let mut open = self.under.lock().unwrap();
316 if self.revoked().is_some() {
317 return None;
318 }
319 open.insert(id.to_string(), Arc::clone(&under));
320 }
321 Some(UnderGuard { up: Arc::clone(self), id: id.to_string(), under })
322 }
323
324 pub(super) fn need_grants(&self, service: &crate::plexus::DynamicHub) -> Vec<(String, Vec<String>)> {
328 let needs = self.needs.lock().unwrap().clone().unwrap_or_else(|| Vec::<String>::new().into());
329 let consent = self.consent.lock().unwrap().clone();
330 needs
331 .iter()
332 .filter_map(|m| {
333 let scopes = match &consent {
334 None => vec!["*".to_string()],
335 Some(c) => c.iter().find(|c| &c.method == m)?.scopes.clone(),
336 };
337 Some((service.grant_at(m)?, scopes))
338 })
339 .collect()
340 }
341
342 pub(super) fn end_all(&self, why: &str) {
345 let open: Vec<Arc<Under>> = self.under.lock().unwrap().drain().map(|(_, u)| u).collect();
346 for u in open {
347 u.ended.send_if_modified(|e| {
348 if e.is_none() {
349 *e = Some(why.to_string());
350 true
351 } else {
352 false
353 }
354 });
355 }
356 }
357
358 pub(super) fn open_now(&self) -> usize {
360 self.under.lock().unwrap().len()
361 }
362}
363
364fn intersect(a: &[String], b: &[String]) -> Vec<String> {
367 let within = |inner: &str, outer: &str| outer == "*" || inner == outer;
368 let mut out: Vec<String> = Vec::new();
369 for x in a {
370 for y in b {
371 let s = if within(x, y) {
372 x
373 } else if within(y, x) {
374 y
375 } else {
376 continue;
377 };
378 if !out.contains(s) {
379 out.push(s.clone());
380 }
381 }
382 }
383 out
384}
385
386pub(super) struct UnderGuard {
389 up: Arc<Upcalls>,
390 id: String,
391 under: Arc<Under>,
392}
393
394impl UnderGuard {
395 pub(super) fn end(&self, why: &str) {
397 self.up.under.lock().unwrap().remove(&self.id);
398 self.under.ended.send_if_modified(|e| {
399 if e.is_none() {
400 *e = Some(why.to_string());
401 true
402 } else {
403 false
404 }
405 });
406 }
407}
408
409impl Drop for UnderGuard {
410 fn drop(&mut self) {
411 self.end("it ended");
412 }
413}
414
415fn narrowed(auth: &AuthContext, reach: &Reach, grant: Option<&str>, door: Option<&str>) -> AuthContext {
432 if reach.is_everywhere() && grant.is_none() {
433 return auth.clone();
434 }
435 let mut ctx = auth.clone();
436 let mut layers: Vec<Value> = match ctx.metadata.get(CEILING_KEY) {
437 Some(Value::Array(items)) if items.iter().all(Value::is_string) => vec![Value::Array(items.clone())],
438 Some(Value::Array(items)) => items.clone(),
439 Some(other) => vec![other.clone()],
440 None => Vec::new(),
441 };
442 let what = grant.unwrap_or(plexus_auth_core::grants::ADMIN);
443 let scopes: Vec<String> = if reach.is_everywhere() { vec!["*".into()] } else { reach.held_on().iter().map(|s| s.to_string()).collect() };
444 let mut layer: Vec<Value> = scopes.iter().map(|s| json!(format!("{what}@{s}"))).collect();
445 layer.extend(door.filter(|_| !reach.is_everywhere()).map(|d| json!(d)));
446 layers.push(Value::Array(layer));
447 if !ctx.metadata.is_object() {
448 ctx.metadata = json!({});
449 }
450 ctx.metadata[CEILING_KEY] = Value::Array(layers);
451 ctx
452}
453
454fn presented_ok(up: &Upcalls, m: &Minted, params: &Value, method: &str, under: &str) -> Result<(), String> {
457 if let Some(t) = params.get("token").and_then(Value::as_str) {
458 if t != m.token {
459 return Err("the token presented is not the one minted for this call".into());
460 }
461 }
462 if m.claims.cnf.is_none() {
463 return Ok(());
464 }
465 let proof = params.get("proof").and_then(Value::as_str).ok_or_else(|| {
466 "a call back under a key-bound token carries a proof of possession (`proof`): none was sent".to_string()
467 })?;
468 crate::plexus::peer_token::check_proof(proof, &m.token, &m.claims, method, under, crate::plexus::peer_token::now(), &up.proofs)
469 .map_err(|e| format!("the call back's {e}"))
470}
471
472fn consented(auth: &AuthContext, grant: &str, scopes: &[String]) -> AuthContext {
475 let mut ctx = auth.clone();
476 let mut layers: Vec<Value> = match ctx.metadata.get(CEILING_KEY) {
477 Some(Value::Array(items)) if items.iter().all(Value::is_string) => vec![Value::Array(items.clone())],
478 Some(Value::Array(items)) => items.clone(),
479 Some(other) => vec![other.clone()],
480 None => Vec::new(),
481 };
482 layers.push(Value::Array(scopes.iter().map(|s| json!(format!("{grant}@{s}"))).collect()));
483 if !ctx.metadata.is_object() {
484 ctx.metadata = json!({});
485 }
486 ctx.metadata[CEILING_KEY] = Value::Array(layers);
487 ctx
488}
489
490fn refusal_said(id: &Value, e: &PlexusError, said: &str) -> Value {
492 let mut r = refusal(id, e);
493 r["error"]["message"] = json!(said);
494 r
495}
496
497fn refusal(id: &Value, e: &PlexusError) -> Value {
499 let mut error = serde_json::to_value(plexus_error_to_jsonrpc(e)).unwrap_or_default();
500 error["message"] = json!(e.to_string());
503 json!({ "jsonrpc": "2.0", "id": id, "error": error })
504}
505
506#[derive(Default)]
509pub(super) struct Served {
510 next: AtomicU64,
511 open: Mutex<HashMap<u64, tokio::task::AbortHandle>>,
512}
513
514impl Served {
515 pub(super) fn abort_all(&self) {
517 for (_, h) in self.open.lock().unwrap().drain() {
518 h.abort();
519 }
520 }
521}
522
523pub(super) fn on_request(up: &Arc<Upcalls>, served: &Arc<Served>, out: &mpsc::UnboundedSender<Vec<u8>>, name: &str, id: Value, method: &str, params: Value) {
526 let send = |v: Value| {
527 let _ = out.send(serde_json::to_vec(&v).unwrap_or_default());
528 };
529 if method == HOST_CALL_UNSUB {
530 let held = params.get(0).and_then(Value::as_u64).and_then(|sid| served.open.lock().unwrap().remove(&sid));
531 let stopped = held.map(|h| h.abort()).is_some();
532 return send(json!({ "jsonrpc": "2.0", "id": id, "result": stopped }));
533 }
534 let Some(mut target) = params.get("method").and_then(Value::as_str).map(str::to_string) else {
535 return send(refusal(&id, &PlexusError::invalid_params("`_host.call` names the `method` it calls")));
536 };
537 let args = params.get("params").cloned().unwrap_or_else(|| json!({}));
538 let presented = target.clone();
540 let under_id = params.get("under").and_then(Value::as_str).map(str::to_string);
541 let need = match up.decide(&target, None) {
545 Ok(need) => need.map(|d| d.consented),
546 Err((e, said)) => return send(refusal_said(&id, &e, &said)),
547 };
548 let standard = matches!(target.as_str(), parent::HOST_WHOAMI | parent::HOST_LOG | parent::HOST_NOTIFY);
549 if target == parent::HOST_SCHEMA {
550 if let Some(svc) = up.host().and_then(|h| h.upgrade()) {
551 target = format!("{}.schema", svc.runtime_namespace());
552 }
553 }
554 let route = match &under_id {
555 Some(u) => match up.under.lock().unwrap().get(u).cloned() {
556 Some(under) => {
557 if let Some(m) = &under.minted {
562 if let Err(e) = presented_ok(up, m, ¶ms, &presented, u) {
563 return send(refusal_said(&id, &PlexusError::Unauthenticated(e.clone()), &e));
564 }
565 }
566 if standard {
567 Route::Standard(under.service.clone(), under.auth.clone())
568 } else {
569 let need = match (&under.minted, need, under.service.upgrade()) {
571 (Some(m), Some(_), Some(svc)) => match up.decide(&target, Some((&svc, &m.claims))) {
572 Ok(d) => d.and_then(|d| d.held),
573 Err((e, said)) => return send(refusal_said(&id, &e, &said)),
574 },
575 (_, n, _) => n,
576 };
577 Route::Under(under, need)
578 }
579 }
580 None => {
581 return send(refusal(&id, &PlexusError::Unauthenticated(format!(
582 "no call `{u}` is open into this child: a child calls its service only under a call it is serving, while it is open"
583 ))))
584 }
585 },
586 None => {
587 let schema = target.ends_with(".schema");
588 match (schema || standard, up.host()) {
589 (true, Some(host)) if standard => Route::Standard(host, None),
590 (true, Some(host)) => {
591 if let Some(svc) = host.upgrade() {
594 let own = format!("{}.schema", svc.runtime_namespace());
595 if target == own {
596 if let Some(why) = up.revoked() {
597 let e = PlexusError::Unauthenticated(format!("this child is revoked ({why})"));
598 return send(refusal(&id, &e));
599 }
600 } else {
601 let path = svc.bare_schema_path(&target);
602 if let Err((e, said)) = up.may_read_schema(&path, svc.crosses_slot(&path)) {
603 return send(refusal_said(&id, &e, &said));
604 }
605 }
606 }
607 Route::Schema(host)
608 }
609 (true, None) => {
610 return send(refusal(&id, &PlexusError::Unauthenticated(
611 "this child's service is not known yet: it is learned with the first call forwarded to it".into(),
612 )))
613 }
614 (false, _) => {
615 return send(refusal(&id, &PlexusError::Unauthenticated(format!(
616 "`{target}` names no call it acts under (`under`): a child calls its service only under a call it is serving; outside one it may ask only for a schema, or call `host.log` and `host.notify`"
617 ))))
618 }
619 }
620 }
621 };
622 up.made.fetch_add(1, Ordering::Relaxed);
623 let sid = served.next.fetch_add(1, Ordering::Relaxed) + 1;
624 send(json!({ "jsonrpc": "2.0", "id": id, "result": sid }));
626 let (out, served2, name) = (out.clone(), Arc::clone(served), name.to_string());
627 let mut open = served.open.lock().unwrap();
629 let task = tokio::spawn(async move {
630 pump(route, &out, sid, &name, &target, args).await;
631 served2.open.lock().unwrap().remove(&sid);
632 });
633 open.insert(sid, task.abort_handle());
634}
635
636enum Route {
637 Under(Arc<Under>, Option<Vec<String>>),
640 Schema(WeakService),
641 Standard(WeakService, Option<AuthContext>),
644}
645
646async fn pump(route: Route, out: &mpsc::UnboundedSender<Vec<u8>>, sid: u64, name: &str, target: &str, args: Value) {
649 let item = |i: &PlexusStreamItem| {
650 let frame = json!({ "jsonrpc": "2.0", "method": HOST_CALL, "params": { "subscription": sid, "result": i } });
651 let _ = out.send(serde_json::to_vec(&frame).unwrap_or_default());
652 };
653 let gone = || PlexusStreamItem::error(meta(name), plexus_client::RemoteError::Unauthenticated, false);
654 let ended_item = |why: &str| {
655 let mut e = gone();
656 if let PlexusStreamItem::Error { message, .. } = &mut e {
657 *message = format!("the call this was made under has ended ({why})");
658 }
659 e
660 };
661 let (under, service) = match &route {
662 Route::Under(u, _) => (Some(Arc::clone(u)), u.service.upgrade()),
663 Route::Schema(s) | Route::Standard(s, _) => (None, s.upgrade()),
664 };
665 let Some(service) = service else {
666 let mut e = gone();
667 if let PlexusStreamItem::Error { message, .. } = &mut e {
668 *message = "the service this child is mounted in has gone".into();
669 }
670 return item(&e);
671 };
672 if let Route::Standard(_, caller) = &route {
673 for i in parent::standard_answer(&service, name, target, &args, caller.as_ref()).unwrap_or_default() {
674 item(&i);
675 }
676 return;
677 }
678 let need = match &route {
679 Route::Under(_, n) => n.clone(),
680 _ => None,
681 };
682 let routed = match &under {
683 Some(u) => {
684 let grant = need.as_ref().and_then(|_| service.grant_at(target));
687 let auth = u.auth.as_ref().map(|a| narrowed(a, &u.reach, grant.as_deref(), u.door.as_deref()));
688 let auth = match (auth, &grant, &need) {
689 (Some(a), Some(g), Some(scopes)) if !scopes.iter().any(|s| s == "*") => Some(consented(&a, g, scopes)),
690 (a, _, _) => a,
691 };
692 match &u.minted {
695 Some(m) => PRESENTED.scope(m.claims.clone(), service.route_with_ctx(target, args, auth.as_ref(), None)).await,
696 None => service.route_with_ctx(target, args, auth.as_ref(), None).await,
697 }
698 }
699 None => service.schema_for_child(target, args).await,
700 };
701 let mut stream = match routed {
702 Ok(s) => s,
703 Err(e) => {
704 let v = crate::plexus::error_item(service.runtime_namespace(), &e);
705 let frame = json!({ "jsonrpc": "2.0", "method": HOST_CALL, "params": { "subscription": sid, "result": v } });
706 let _ = out.send(serde_json::to_vec(&frame).unwrap_or_default());
707 return;
708 }
709 };
710 let Some(under) = under else {
711 while let Some(i) = stream.next().await {
712 item(&i);
713 }
714 return;
715 };
716 let mut ended = under.ended.subscribe();
717 if let Some(why) = ended.borrow().clone() {
718 return item(&ended_item(&why));
719 }
720 let mut moved = under.reach.generation().map(|g| g.subscribe());
722 loop {
723 tokio::select! {
724 next = stream.next() => match next {
725 Some(i) => {
726 let terminal = matches!(i, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. });
727 item(&i);
728 if terminal {
729 return;
730 }
731 }
732 None => return,
733 },
734 _ = ended.changed() => {
735 let why = ended.borrow().clone().unwrap_or_default();
736 return item(&ended_item(&why));
737 }
738 changed = async { match moved.as_mut() { Some(m) => m.changed().await, None => std::future::pending().await } } => {
739 if changed.is_err() {
740 moved = None;
741 } else if under.reach.current().is_none() {
742 return item(&ended_item("its grant was revoked"));
743 }
744 }
745 }
746 }
747}
748
749#[cfg(test)]
750mod tests {
751 use super::*;
752 use plexus_auth_core::grants::{Gate, Membership, Memberships, Resolve, RoleTable, ScopeRef};
753
754 #[test]
756 fn a_call_back_is_narrowed_to_the_forwarded_calls_scopes() {
757 struct Held;
758 impl Memberships for Held {
759 fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
760 vec![Membership { principal: who.clone(), role: plexus_auth_core::RoleName::new("viewer"), scope: ScopeRef::Everywhere }]
761 }
762 }
763 struct Chain;
764 impl Resolve for Chain {
765 fn chain(&self, t: &str) -> Option<Vec<ScopeRef>> {
766 Some(vec![ScopeRef::named(t), ScopeRef::Everywhere])
767 }
768 }
769 let roles = RoleTable::from_lists([("viewer", ["a.get", "b.get"])]);
770 let gate = Gate::new(Arc::new(Held), Arc::new(roles), Arc::new(Chain));
771 let who = AuthContext::for_principal(&"key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".parse().unwrap(), "s", vec![], Value::Null);
772 let wide = gate.check(Some(&who), &plexus_auth_core::grants::Grant::new("a.get"), None).unwrap();
773 assert_eq!(narrowed(&who, &wide, None, None).metadata, who.metadata, "held everywhere: nothing added");
774 let mut n = who.clone();
776 n.metadata[CEILING_KEY] = json!([["admin@X"]]);
777 let narrow = n.clone();
778 let g = plexus_auth_core::grants::Grant::new("b.get");
779 assert!(gate.check(Some(&narrow), &g, Some("X")).is_ok());
780 assert!(gate.check(Some(&narrow), &g, Some("Y")).is_err());
781 let layered = narrowed(&n, &gate.check(Some(&n), &plexus_auth_core::grants::Grant::new("a.get"), None).unwrap(), None, None);
782 assert_eq!(layered.metadata[CEILING_KEY].as_array().unwrap().len(), 2, "{:?}", layered.metadata);
783 assert!(gate.check(Some(&layered), &g, Some("Y")).is_err());
784 }
785
786 #[test]
789 fn a_need_is_held_to_its_consent() {
790 let up = Upcalls::new(None, false);
791 let need = |m: &str| crate::plexus::schema::Need { method: m.into(), hash: String::new() };
792 up.set_needs(Some(&[need("shop.items"), need("shop.orders")]));
793 assert_eq!(up.allows("shop.items").unwrap(), Some(vec!["*".to_string()]), "no consent kept: declared is enough");
794 assert!(up.allows("shop.secret").is_err(), "undeclared");
795 assert_eq!(up.allows(parent::HOST_WHOAMI).unwrap(), None, "the standard four need nothing");
796 up.set_consent(Some(vec![Consented { method: "shop.items".into(), scopes: vec!["MENGER".into()] }]));
797 assert_eq!(up.allows("shop.items").unwrap(), Some(vec!["MENGER".to_string()]));
798 let (e, said) = up.allows("shop.orders").unwrap_err();
799 assert!(said.contains("consented"), "{said}");
800 assert!(e.to_string().contains("shop.orders"));
801 up.set_consent(Some(vec![]));
802 assert!(up.allows("shop.items").is_err(), "an empty consent: nothing upward");
803 let who = AuthContext::for_principal(&"key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".parse().unwrap(), "s", vec![], Value::Null);
805 let c = consented(&who, "shop.items", &["MENGER".to_string()]);
806 assert_eq!(c.metadata[CEILING_KEY], json!([["shop.items@MENGER"]]));
807 }
808
809 #[test]
812 fn a_call_back_under_a_bound_token_needs_its_proof() {
813 use crate::plexus::peer_token::{prove, MintRequest, PeerKey, TokenIssuer};
814 let (host, child, thief) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
815 let issuer = TokenIssuer::new(host);
816 let req = |peer_key: Option<String>| MintRequest { sub: "key:x".into(), peer_key, name: "w".into(), scope: vec![], call: "u1".into(), method: "w.m".into(), presented: None };
817 let (token, claims) = issuer.mint(req(Some(child.kid().into()))).unwrap();
818 let m = Minted { token: token.clone(), claims };
819 let up = Upcalls::new(None, false);
820 let no_proof = presented_ok(&up, &m, &json!({}), "shop.items", "u1").unwrap_err();
821 assert!(no_proof.contains("proof"), "{no_proof}");
822 let good = json!({ "token": token, "proof": prove(&child, &token, "shop.items", "u1") });
823 assert_eq!(presented_ok(&up, &m, &good, "shop.items", "u1"), Ok(()));
824 assert!(presented_ok(&up, &m, &good, "shop.items", "u1").is_err(), "a proof is used once");
825 let stolen = json!({ "proof": prove(&thief, &token, "shop.items", "u1") });
826 assert!(presented_ok(&up, &m, &stolen, "shop.items", "u1").unwrap_err().contains("another key"));
827 let other_method = json!({ "proof": prove(&child, &token, "shop.items", "u1") });
828 assert!(presented_ok(&up, &m, &other_method, "auth.grant", "u1").is_err());
829 let other_token = json!({ "token": "a.b.c", "proof": prove(&child, &token, "shop.items", "u1") });
830 assert!(presented_ok(&up, &m, &other_token, "shop.items", "u1").unwrap_err().contains("not the one"));
831 let (token, claims) = issuer.mint(req(None)).unwrap();
833 assert_eq!(presented_ok(&up, &Minted { token, claims }, &json!({}), "shop.items", "u1"), Ok(()));
834 }
835
836 #[test]
839 fn a_revoked_child_is_decided_nothing() {
840 let up = Upcalls::new(None, false);
841 let need = |m: &str| crate::plexus::schema::Need { method: m.into(), hash: String::new() };
842 up.set_needs(Some(&[need("dyn.peer.b.forecast")]));
843 up.set_consent(Some(vec![Consented { method: "dyn.peer.b.forecast".into(), scopes: vec!["*".into()] }]));
844 assert_eq!(up.decide("dyn.peer.b.forecast", None).unwrap(), Some(Decided { consented: vec!["*".into()], held: None }));
845 up.revoke("compromised");
846 let (_, said) = up.decide("dyn.peer.b.forecast", None).unwrap_err();
847 assert!(said.contains("revoked (compromised)"), "{said}");
848 assert_eq!(up.decide(parent::HOST_WHOAMI, None).unwrap(), None, "the standard interface is not this ticket's");
849 }
850
851 #[tokio::test]
854 async fn a_revoked_child_is_opened_nothing() {
855 let up = Upcalls::new(None, false);
856 let svc = crate::plexus::DynamicHub::new("svc");
857 let reach = plexus_auth_core::grants::Reach::everywhere();
858 let open = |id: &'static str| crate::plexus::service_scope::scope(svc.downgrade(), { let up = Arc::clone(&up); let reach = reach.clone(); async move { up.open(id, None, &reach, None, None) } });
859 assert!(open("c1").await.is_some());
860 up.revoke("compromised");
861 assert!(open("c2").await.is_none(), "opened after the revoke");
862 assert_eq!(up.open_now(), 0);
863 }
864
865 #[tokio::test]
867 async fn revoking_ends_every_call_back() {
868 let up = Upcalls::new(None, false);
869 let svc = crate::plexus::DynamicHub::new("svc");
870 let reach = plexus_auth_core::grants::Reach::everywhere();
871 let guard = crate::plexus::service_scope::scope(svc.downgrade(), async { up.open("c1", None, &reach, None, None) }).await.expect("opened");
872 let mut ended = guard.under.ended.subscribe();
873 assert_eq!(up.open_now(), 1);
874 up.end_all("revoked: compromised");
875 assert_eq!(up.open_now(), 0);
876 ended.changed().await.unwrap();
877 assert_eq!(ended.borrow().as_deref(), Some("revoked: compromised"));
878 }
879}