use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use futures::StreamExt;
use plexus_auth_core::grants::{Reach, CEILING_KEY};
use serde_json::{json, Value};
use tokio::sync::{mpsc, watch};
use super::link::meta;
use crate::plexus::auth::AuthContext;
use crate::plexus::service_scope::{self, WeakService};
use crate::plexus::types::PlexusStreamItem;
use crate::plexus::{parent, plexus_error_to_jsonrpc, PlexusError};
pub const HOST_CALL: &str = "_host.call";
pub const HOST_CALL_UNSUB: &str = "_host.call_unsub";
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Consented {
pub method: String,
pub scopes: Vec<String>,
}
pub(super) struct Under {
auth: Option<AuthContext>,
reach: Reach,
service: WeakService,
ended: watch::Sender<Option<String>>,
minted: Option<Minted>,
}
tokio::task_local! {
static PRESENTED: crate::plexus::peer_token::PeerClaims;
}
pub(super) fn presented() -> Option<crate::plexus::peer_token::PeerClaims> {
PRESENTED.try_with(Clone::clone).ok()
}
#[derive(Clone)]
pub(super) struct Minted {
pub token: String,
pub claims: crate::plexus::peer_token::PeerClaims,
}
pub(super) struct Upcalls {
host: Mutex<Option<WeakService>>,
under: Mutex<HashMap<String, Arc<Under>>>,
pub made: AtomicU64,
proofs: crate::plexus::peer_token::ProofCache,
needs: Mutex<Option<Arc<[String]>>>,
consent: Mutex<Option<Arc<[Consented]>>>,
legacy: bool,
}
impl Upcalls {
pub(super) fn new(host: Option<WeakService>, legacy: bool) -> Arc<Self> {
Arc::new(Self { host: Mutex::new(host), under: Mutex::default(), made: AtomicU64::new(0), proofs: Default::default(), needs: Mutex::default(), consent: Mutex::default(), legacy })
}
pub(super) fn set_needs(&self, needs: Option<&[crate::plexus::schema::Need]>) {
*self.needs.lock().unwrap() = needs.map(|n| n.iter().map(|n| n.method.clone()).collect::<Vec<_>>().into());
}
pub(super) fn set_consent(&self, consent: Option<Vec<Consented>>) {
*self.consent.lock().unwrap() = consent.map(Into::into);
}
pub(super) fn consent(&self) -> Option<Arc<[Consented]>> {
self.consent.lock().unwrap().clone()
}
fn allows(&self, method: &str) -> Result<Option<Vec<String>>, (PlexusError, String)> {
if parent::is_standard(method) {
return Ok(None);
}
let declared = match self.needs.lock().unwrap().as_ref() {
Some(needs) => needs.iter().any(|n| n == method),
None if self.legacy => return Ok(None),
None => false,
};
if !declared {
let e = parent::not_needed(method);
let said = e.to_string();
return Err((e, said));
}
match self.consent.lock().unwrap().as_ref() {
None => Ok(Some(vec!["*".into()])),
Some(c) => match c.iter().find(|c| c.method == method) {
Some(c) => Ok(Some(c.scopes.clone())),
None => Err((
parent::not_needed(method),
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"),
)),
},
}
}
fn host(&self) -> Option<WeakService> {
let mut h = self.host.lock().unwrap();
if h.as_ref().and_then(WeakService::upgrade).is_none() {
if let Some(now) = service_scope::current() {
*h = Some(now);
}
}
h.clone()
}
pub(super) fn open(self: &Arc<Self>, id: &str, auth: Option<&AuthContext>, reach: &Reach, minted: Option<Minted>) -> Option<UnderGuard> {
let service = service_scope::current().or_else(|| self.host())?;
let (ended, _) = watch::channel(None);
let under = Arc::new(Under { auth: auth.cloned(), reach: reach.clone(), service, ended, minted });
self.under.lock().unwrap().insert(id.to_string(), Arc::clone(&under));
Some(UnderGuard { up: Arc::clone(self), id: id.to_string(), under })
}
pub(super) fn need_grants(&self, service: &crate::plexus::DynamicHub) -> Vec<(String, Vec<String>)> {
let needs = self.needs.lock().unwrap().clone().unwrap_or_else(|| Vec::<String>::new().into());
let consent = self.consent.lock().unwrap().clone();
needs
.iter()
.filter_map(|m| {
let scopes = match &consent {
None => vec!["*".to_string()],
Some(c) => c.iter().find(|c| &c.method == m)?.scopes.clone(),
};
Some((service.grant_at(m)?, scopes))
})
.collect()
}
pub(super) fn end_all(&self, why: &str) {
let open: Vec<Arc<Under>> = self.under.lock().unwrap().drain().map(|(_, u)| u).collect();
for u in open {
u.ended.send_if_modified(|e| {
if e.is_none() {
*e = Some(why.to_string());
true
} else {
false
}
});
}
}
pub(super) fn open_now(&self) -> usize {
self.under.lock().unwrap().len()
}
}
pub(super) struct UnderGuard {
up: Arc<Upcalls>,
id: String,
under: Arc<Under>,
}
impl UnderGuard {
pub(super) fn end(&self, why: &str) {
self.up.under.lock().unwrap().remove(&self.id);
self.under.ended.send_if_modified(|e| {
if e.is_none() {
*e = Some(why.to_string());
true
} else {
false
}
});
}
}
impl Drop for UnderGuard {
fn drop(&mut self) {
self.end("it ended");
}
}
fn narrowed(auth: &AuthContext, reach: &Reach, grant: Option<&str>) -> AuthContext {
if reach.is_everywhere() && grant.is_none() {
return auth.clone();
}
let mut ctx = auth.clone();
let mut layers: Vec<Value> = match ctx.metadata.get(CEILING_KEY) {
Some(Value::Array(items)) if items.iter().all(Value::is_string) => vec![Value::Array(items.clone())],
Some(Value::Array(items)) => items.clone(),
Some(other) => vec![other.clone()],
None => Vec::new(),
};
let what = grant.unwrap_or(plexus_auth_core::grants::ADMIN);
let scopes: Vec<String> = if reach.is_everywhere() { vec!["*".into()] } else { reach.held_on().iter().map(|s| s.to_string()).collect() };
layers.push(Value::Array(scopes.iter().map(|s| json!(format!("{what}@{s}"))).collect()));
if !ctx.metadata.is_object() {
ctx.metadata = json!({});
}
ctx.metadata[CEILING_KEY] = Value::Array(layers);
ctx
}
fn presented_ok(up: &Upcalls, m: &Minted, params: &Value, method: &str, under: &str) -> Result<(), String> {
if let Some(t) = params.get("token").and_then(Value::as_str) {
if t != m.token {
return Err("the token presented is not the one minted for this call".into());
}
}
if m.claims.cnf.is_none() {
return Ok(());
}
let proof = params.get("proof").and_then(Value::as_str).ok_or_else(|| {
"a call back under a key-bound token carries a proof of possession (`proof`): none was sent".to_string()
})?;
crate::plexus::peer_token::check_proof(proof, &m.token, &m.claims, method, under, crate::plexus::peer_token::now(), &up.proofs)
.map_err(|e| format!("the call back's {e}"))
}
fn consented(auth: &AuthContext, grant: &str, scopes: &[String]) -> AuthContext {
let mut ctx = auth.clone();
let mut layers: Vec<Value> = match ctx.metadata.get(CEILING_KEY) {
Some(Value::Array(items)) if items.iter().all(Value::is_string) => vec![Value::Array(items.clone())],
Some(Value::Array(items)) => items.clone(),
Some(other) => vec![other.clone()],
None => Vec::new(),
};
layers.push(Value::Array(scopes.iter().map(|s| json!(format!("{grant}@{s}"))).collect()));
if !ctx.metadata.is_object() {
ctx.metadata = json!({});
}
ctx.metadata[CEILING_KEY] = Value::Array(layers);
ctx
}
fn refusal_said(id: &Value, e: &PlexusError, said: &str) -> Value {
let mut r = refusal(id, e);
r["error"]["message"] = json!(said);
r
}
fn refusal(id: &Value, e: &PlexusError) -> Value {
let mut error = serde_json::to_value(plexus_error_to_jsonrpc(e)).unwrap_or_default();
error["message"] = json!(e.to_string());
json!({ "jsonrpc": "2.0", "id": id, "error": error })
}
#[derive(Default)]
pub(super) struct Served {
next: AtomicU64,
open: Mutex<HashMap<u64, tokio::task::AbortHandle>>,
}
impl Served {
pub(super) fn abort_all(&self) {
for (_, h) in self.open.lock().unwrap().drain() {
h.abort();
}
}
}
pub(super) fn on_request(up: &Arc<Upcalls>, served: &Arc<Served>, out: &mpsc::UnboundedSender<Vec<u8>>, name: &str, id: Value, method: &str, params: Value) {
let send = |v: Value| {
let _ = out.send(serde_json::to_vec(&v).unwrap_or_default());
};
if method == HOST_CALL_UNSUB {
let held = params.get(0).and_then(Value::as_u64).and_then(|sid| served.open.lock().unwrap().remove(&sid));
let stopped = held.map(|h| h.abort()).is_some();
return send(json!({ "jsonrpc": "2.0", "id": id, "result": stopped }));
}
let Some(mut target) = params.get("method").and_then(Value::as_str).map(str::to_string) else {
return send(refusal(&id, &PlexusError::invalid_params("`_host.call` names the `method` it calls")));
};
let args = params.get("params").cloned().unwrap_or_else(|| json!({}));
let presented = target.clone();
let under_id = params.get("under").and_then(Value::as_str).map(str::to_string);
let need = match up.allows(&target) {
Ok(need) => need,
Err((e, said)) => return send(refusal_said(&id, &e, &said)),
};
let standard = matches!(target.as_str(), parent::HOST_WHOAMI | parent::HOST_LOG | parent::HOST_NOTIFY);
if target == parent::HOST_SCHEMA {
if let Some(svc) = up.host().and_then(|h| h.upgrade()) {
target = format!("{}.schema", svc.runtime_namespace());
}
}
let route = match &under_id {
Some(u) => match up.under.lock().unwrap().get(u).cloned() {
Some(under) => {
if let Some(m) = &under.minted {
if let Err(e) = presented_ok(up, m, ¶ms, &presented, u) {
return send(refusal_said(&id, &PlexusError::Unauthenticated(e.clone()), &e));
}
}
if standard {
Route::Standard(under.service.clone(), under.auth.clone())
} else {
let need = match (&under.minted, need, under.service.upgrade()) {
(Some(m), Some(_), Some(svc)) => {
let held = svc.grant_at(&target).map(|g| m.claims.scopes_for(&g)).unwrap_or_default();
if held.is_empty() {
let e = parent::not_needed(&target);
return send(refusal_said(&id, &e, &format!("`{target}` is not within the scope of the token minted for this call")));
}
Some(held)
}
(_, n, _) => n,
};
Route::Under(under, need)
}
}
None => {
return send(refusal(&id, &PlexusError::Unauthenticated(format!(
"no call `{u}` is open into this child: a child calls its service only under a call it is serving, while it is open"
))))
}
},
None => {
let schema = target.ends_with(".schema");
match (schema || standard, up.host()) {
(true, Some(host)) if standard => Route::Standard(host, None),
(true, Some(host)) => Route::Schema(host),
(true, None) => {
return send(refusal(&id, &PlexusError::Unauthenticated(
"this child's service is not known yet: it is learned with the first call forwarded to it".into(),
)))
}
(false, _) => {
return send(refusal(&id, &PlexusError::Unauthenticated(format!(
"`{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`"
))))
}
}
}
};
up.made.fetch_add(1, Ordering::Relaxed);
let sid = served.next.fetch_add(1, Ordering::Relaxed) + 1;
send(json!({ "jsonrpc": "2.0", "id": id, "result": sid }));
let (out, served2, name) = (out.clone(), Arc::clone(served), name.to_string());
let mut open = served.open.lock().unwrap();
let task = tokio::spawn(async move {
pump(route, &out, sid, &name, &target, args).await;
served2.open.lock().unwrap().remove(&sid);
});
open.insert(sid, task.abort_handle());
}
enum Route {
Under(Arc<Under>, Option<Vec<String>>),
Schema(WeakService),
Standard(WeakService, Option<AuthContext>),
}
async fn pump(route: Route, out: &mpsc::UnboundedSender<Vec<u8>>, sid: u64, name: &str, target: &str, args: Value) {
let item = |i: &PlexusStreamItem| {
let frame = json!({ "jsonrpc": "2.0", "method": HOST_CALL, "params": { "subscription": sid, "result": i } });
let _ = out.send(serde_json::to_vec(&frame).unwrap_or_default());
};
let gone = || PlexusStreamItem::error(meta(name), plexus_client::RemoteError::Unauthenticated, false);
let ended_item = |why: &str| {
let mut e = gone();
if let PlexusStreamItem::Error { message, .. } = &mut e {
*message = format!("the call this was made under has ended ({why})");
}
e
};
let (under, service) = match &route {
Route::Under(u, _) => (Some(Arc::clone(u)), u.service.upgrade()),
Route::Schema(s) | Route::Standard(s, _) => (None, s.upgrade()),
};
let Some(service) = service else {
let mut e = gone();
if let PlexusStreamItem::Error { message, .. } = &mut e {
*message = "the service this child is mounted in has gone".into();
}
return item(&e);
};
if let Route::Standard(_, caller) = &route {
for i in parent::standard_answer(&service, name, target, &args, caller.as_ref()).unwrap_or_default() {
item(&i);
}
return;
}
let need = match &route {
Route::Under(_, n) => n.clone(),
_ => None,
};
let routed = match &under {
Some(u) => {
let grant = need.as_ref().and_then(|_| service.grant_at(target));
let auth = u.auth.as_ref().map(|a| narrowed(a, &u.reach, grant.as_deref()));
let auth = match (auth, &grant, &need) {
(Some(a), Some(g), Some(scopes)) if !scopes.iter().any(|s| s == "*") => Some(consented(&a, g, scopes)),
(a, _, _) => a,
};
match &u.minted {
Some(m) => PRESENTED.scope(m.claims.clone(), service.route_with_ctx(target, args, auth.as_ref(), None)).await,
None => service.route_with_ctx(target, args, auth.as_ref(), None).await,
}
}
None => service.schema_for_child(target, args).await,
};
let mut stream = match routed {
Ok(s) => s,
Err(e) => {
let v = crate::plexus::error_item(service.runtime_namespace(), &e);
let frame = json!({ "jsonrpc": "2.0", "method": HOST_CALL, "params": { "subscription": sid, "result": v } });
let _ = out.send(serde_json::to_vec(&frame).unwrap_or_default());
return;
}
};
let Some(under) = under else {
while let Some(i) = stream.next().await {
item(&i);
}
return;
};
let mut ended = under.ended.subscribe();
if let Some(why) = ended.borrow().clone() {
return item(&ended_item(&why));
}
let mut moved = under.reach.generation().map(|g| g.subscribe());
loop {
tokio::select! {
next = stream.next() => match next {
Some(i) => {
let terminal = matches!(i, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. });
item(&i);
if terminal {
return;
}
}
None => return,
},
_ = ended.changed() => {
let why = ended.borrow().clone().unwrap_or_default();
return item(&ended_item(&why));
}
changed = async { match moved.as_mut() { Some(m) => m.changed().await, None => std::future::pending().await } } => {
if changed.is_err() {
moved = None;
} else if under.reach.current().is_none() {
return item(&ended_item("its grant was revoked"));
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use plexus_auth_core::grants::{Gate, Membership, Memberships, Resolve, RoleTable, ScopeRef};
#[test]
fn a_call_back_is_narrowed_to_the_forwarded_calls_scopes() {
struct Held;
impl Memberships for Held {
fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
vec![Membership { principal: who.clone(), role: plexus_auth_core::RoleName::new("viewer"), scope: ScopeRef::Everywhere }]
}
}
struct Chain;
impl Resolve for Chain {
fn chain(&self, t: &str) -> Option<Vec<ScopeRef>> {
Some(vec![ScopeRef::named(t), ScopeRef::Everywhere])
}
}
let roles = RoleTable::from_lists([("viewer", ["a.get", "b.get"])]);
let gate = Gate::new(Arc::new(Held), Arc::new(roles), Arc::new(Chain));
let who = AuthContext::for_principal(&"key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".parse().unwrap(), "s", vec![], Value::Null);
let wide = gate.check(Some(&who), &plexus_auth_core::grants::Grant::new("a.get"), None).unwrap();
assert_eq!(narrowed(&who, &wide, None).metadata, who.metadata, "held everywhere: nothing added");
let mut n = who.clone();
n.metadata[CEILING_KEY] = json!([["admin@X"]]);
let narrow = n.clone();
let g = plexus_auth_core::grants::Grant::new("b.get");
assert!(gate.check(Some(&narrow), &g, Some("X")).is_ok());
assert!(gate.check(Some(&narrow), &g, Some("Y")).is_err());
let layered = narrowed(&n, &gate.check(Some(&n), &plexus_auth_core::grants::Grant::new("a.get"), None).unwrap(), None);
assert_eq!(layered.metadata[CEILING_KEY].as_array().unwrap().len(), 2, "{:?}", layered.metadata);
assert!(gate.check(Some(&layered), &g, Some("Y")).is_err());
}
#[test]
fn a_need_is_held_to_its_consent() {
let up = Upcalls::new(None, false);
let need = |m: &str| crate::plexus::schema::Need { method: m.into(), hash: String::new() };
up.set_needs(Some(&[need("shop.items"), need("shop.orders")]));
assert_eq!(up.allows("shop.items").unwrap(), Some(vec!["*".to_string()]), "no consent kept: declared is enough");
assert!(up.allows("shop.secret").is_err(), "undeclared");
assert_eq!(up.allows(parent::HOST_WHOAMI).unwrap(), None, "the standard four need nothing");
up.set_consent(Some(vec![Consented { method: "shop.items".into(), scopes: vec!["MENGER".into()] }]));
assert_eq!(up.allows("shop.items").unwrap(), Some(vec!["MENGER".to_string()]));
let (e, said) = up.allows("shop.orders").unwrap_err();
assert!(said.contains("consented"), "{said}");
assert!(e.to_string().contains("shop.orders"));
up.set_consent(Some(vec![]));
assert!(up.allows("shop.items").is_err(), "an empty consent: nothing upward");
let who = AuthContext::for_principal(&"key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".parse().unwrap(), "s", vec![], Value::Null);
let c = consented(&who, "shop.items", &["MENGER".to_string()]);
assert_eq!(c.metadata[CEILING_KEY], json!([["shop.items@MENGER"]]));
}
#[test]
fn a_call_back_under_a_bound_token_needs_its_proof() {
use crate::plexus::peer_token::{prove, MintRequest, PeerKey, TokenIssuer};
let (host, child, thief) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
let issuer = TokenIssuer::new(host);
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 };
let (token, claims) = issuer.mint(req(Some(child.kid().into()))).unwrap();
let m = Minted { token: token.clone(), claims };
let up = Upcalls::new(None, false);
let no_proof = presented_ok(&up, &m, &json!({}), "shop.items", "u1").unwrap_err();
assert!(no_proof.contains("proof"), "{no_proof}");
let good = json!({ "token": token, "proof": prove(&child, &token, "shop.items", "u1") });
assert_eq!(presented_ok(&up, &m, &good, "shop.items", "u1"), Ok(()));
assert!(presented_ok(&up, &m, &good, "shop.items", "u1").is_err(), "a proof is used once");
let stolen = json!({ "proof": prove(&thief, &token, "shop.items", "u1") });
assert!(presented_ok(&up, &m, &stolen, "shop.items", "u1").unwrap_err().contains("another key"));
let other_method = json!({ "proof": prove(&child, &token, "shop.items", "u1") });
assert!(presented_ok(&up, &m, &other_method, "auth.grant", "u1").is_err());
let other_token = json!({ "token": "a.b.c", "proof": prove(&child, &token, "shop.items", "u1") });
assert!(presented_ok(&up, &m, &other_token, "shop.items", "u1").unwrap_err().contains("not the one"));
let (token, claims) = issuer.mint(req(None)).unwrap();
assert_eq!(presented_ok(&up, &Minted { token, claims }, &json!({}), "shop.items", "u1"), Ok(()));
}
#[tokio::test]
async fn revoking_ends_every_call_back() {
let up = Upcalls::new(None, false);
let svc = crate::plexus::DynamicHub::new("svc");
let reach = plexus_auth_core::grants::Reach::everywhere();
let guard = crate::plexus::service_scope::scope(svc.downgrade(), async { up.open("c1", None, &reach, None) }).await.expect("opened");
let mut ended = guard.under.ended.subscribe();
assert_eq!(up.open_now(), 1);
up.end_all("revoked: compromised");
assert_eq!(up.open_now(), 0);
ended.changed().await.unwrap();
assert_eq!(ended.borrow().as_deref(), Some("revoked: compromised"));
}
}