use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::any::Any;
use std::sync::{Arc, Mutex, OnceLock};
use std::task::{Context, Poll};
use futures::Stream;
use plexus_auth_core::grants::{Gate, Grant, Reach, ScopeRef};
use serde::{Deserialize, Serialize};
use crate::plexus::{AuthContext, PlexusError};
tokio::task_local! {
static CALL: CallContext;
}
#[derive(Clone)]
pub struct CallContext(Arc<Inner>);
struct Inner {
auth: Option<AuthContext>,
reach: OnceLock<Reach>,
deferred: Option<(Arc<Gate>, Grant)>,
hop: Option<Hop>,
verified: Verified,
host: Option<Arc<dyn Any + Send + Sync>>,
}
type Verified = Arc<Mutex<Option<Arc<dyn Any + Send + Sync>>>>;
impl Inner {
fn with(auth: Option<AuthContext>, reach: Option<Reach>, deferred: Option<(Arc<Gate>, Grant)>, hop: Option<Hop>) -> Self {
let cell = OnceLock::new();
if let Some(r) = reach {
let _ = cell.set(r);
}
Inner { auth, reach: cell, deferred, hop, verified: Verified::default(), host: None }
}
}
impl fmt::Debug for CallContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CallContext")
.field("principal", &self.0.auth.as_ref().and_then(|a| a.principal()).map(|p| p.to_string()))
.field("reach", &self.0.reach.get())
.field("hop", &self.0.hop)
.finish()
}
}
impl CallContext {
pub(crate) fn admitted(auth: Option<&AuthContext>, reach: Reach) -> Self {
Self(Arc::new(Inner::with(auth.cloned(), Some(reach), None, None)))
}
pub(crate) fn introspection(auth: Option<&AuthContext>, gate: Arc<Gate>, grant: Grant) -> Self {
Self(Arc::new(Inner::with(auth.cloned(), None, Some((gate, grant)), None)))
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn through_hop(hop: Hop) -> Self {
let unreadable = hop.caller().is_some_and(|p| p.parse::<plexus_auth_core::identity::Principal>().is_err());
let auth = hop.caller().and_then(|p| p.parse::<plexus_auth_core::identity::Principal>().ok()).map(|p| {
AuthContext::for_principal(&p, format!("hop:{}", hop.call), Vec::new(), serde_json::json!({ "hop_principal": hop.principal }))
});
let reach = match &hop.limit {
Some(l) if !unreadable => ceiling_reach(auth.as_ref(), &l.grant, &hop.held_on()),
_ => Reach::nowhere(),
};
Self(Arc::new(Inner::with(auth, Some(reach), None, Some(hop))))
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn through_hop_with(hop: Hop, host: Arc<dyn Any + Send + Sync>) -> Self {
let mut ctx = Self::through_hop(hop);
if let Some(inner) = Arc::get_mut(&mut ctx.0) {
inner.host = Some(host);
}
ctx
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn host_link(&self) -> Option<&Arc<dyn Any + Send + Sync>> {
self.0.host.as_ref()
}
pub(crate) fn for_child(&self, callee: Option<&AuthContext>, keeps_identity: bool) -> Self {
let auth = callee.filter(|a| a.is_authenticated()).cloned();
let (reach, hop) = if keeps_identity {
(self.reach().cloned().unwrap_or_else(Reach::nowhere), self.0.hop.clone())
} else {
(Reach::nowhere(), None)
};
let mut inner = Inner::with(auth, Some(reach), None, hop);
inner.host = self.0.host.clone().filter(|_| keeps_identity);
Self(Arc::new(inner))
}
pub(crate) fn with_auth(&self, auth: Option<&AuthContext>) -> Self {
let mut inner = Inner::with(auth.cloned(), self.0.reach.get().cloned(), self.0.deferred.clone(), self.0.hop.clone());
inner.host = self.0.host.clone();
Self(Arc::new(inner))
}
pub(crate) fn with_reach(&self, reach: Reach) -> Self {
let mut inner = Inner::with(self.0.auth.clone(), Some(reach), None, self.0.hop.clone());
inner.verified = Arc::clone(&self.0.verified);
inner.host = self.0.host.clone();
Self(Arc::new(inner))
}
pub fn auth(&self) -> Option<&AuthContext> {
self.0.auth.as_ref()
}
pub fn reach(&self) -> Option<&Reach> {
if let Some(reach) = self.0.reach.get() {
return Some(reach);
}
let (gate, grant) = self.0.deferred.as_ref()?;
Some(self.0.reach.get_or_init(|| gate.reach_of_public(self.0.auth.as_ref(), grant)))
}
pub fn hop(&self) -> Option<&Hop> {
self.0.hop.as_ref()
}
pub fn caller(&self) -> Result<Caller, CallError> {
match self.reach() {
Some(_) => Ok(Caller(self.clone())),
None => Err(CallError::ThroughHop),
}
}
}
#[derive(Clone, Debug)]
pub struct Caller(CallContext);
impl Caller {
pub fn auth(&self) -> Option<&AuthContext> {
self.0.auth()
}
pub fn signed_in(&self) -> Result<&AuthContext, PlexusError> {
self.0
.auth()
.ok_or_else(|| PlexusError::Unauthenticated("This method requires authentication".to_string()))
}
pub fn reach(&self) -> &Reach {
self.0.reach().expect("a caller is made only from a context with a reach")
}
pub fn context(&self) -> &CallContext {
&self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallError {
OutsideCall,
ThroughHop,
NoHop,
NotVerified,
AlreadyVerified,
}
impl fmt::Display for CallError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
CallError::OutsideCall => {
"no caller: this runs outside a call (a spawned task carries one only when handed it, plexus_core::call::scope)"
}
CallError::ThroughHop => "no caller admitted here: this call came through a hop (read plexus_core::call::hop)",
CallError::NoHop => "no hop: this call did not come through the child seam",
CallError::AlreadyVerified => "the call's verified value is set once, by its verifier, and is set",
CallError::NotVerified => {
"nothing verified: the method declares no `#[plexus_macros::from_auth(…)]` answering this type"
}
})
}
}
impl std::error::Error for CallError {}
impl From<CallError> for PlexusError {
fn from(e: CallError) -> Self {
PlexusError::Unauthenticated(e.to_string())
}
}
pub fn caller() -> Result<Caller, CallError> {
CALL.try_with(CallContext::caller).unwrap_or(Err(CallError::OutsideCall))
}
pub fn hop() -> Result<Hop, CallError> {
CALL.try_with(|c| c.hop().cloned().ok_or(CallError::NoHop)).unwrap_or(Err(CallError::OutsideCall))
}
pub fn context() -> Result<CallContext, CallError> {
CALL.try_with(CallContext::clone).map_err(|_| CallError::OutsideCall)
}
pub fn verified<T: Clone + Send + Sync + 'static>() -> Result<T, CallError> {
let ctx = context()?;
let held = ctx.0.verified.lock().unwrap_or_else(|p| p.into_inner()).clone();
held.and_then(|v| v.downcast_ref::<T>().cloned()).ok_or(CallError::NotVerified)
}
#[doc(hidden)]
pub fn __keep_verified<T: Send + Sync + 'static>(value: T) -> Result<(), CallError> {
let ctx = context()?;
let mut held = ctx.0.verified.lock().unwrap_or_else(|p| p.into_inner());
if held.is_some() {
return Err(CallError::AlreadyVerified);
}
*held = Some(Arc::new(value));
Ok(())
}
pub async fn ungated<A: crate::plexus::Activation + ?Sized>(
activation: &A,
method: &str,
params: serde_json::Value,
auth: Option<&AuthContext>,
raw_ctx: Option<&crate::request::RawRequestContext>,
) -> Result<crate::plexus::PlexusStream, PlexusError> {
let ctx = match context() {
Ok(outer) => outer.with_auth(auth),
Err(_) => CallContext::admitted(auth, Reach::everywhere()),
};
let stream = scope(ctx.clone(), activation.call(method, params, auth, raw_ctx)).await?;
Ok(Box::pin(InCall::new(ctx, stream)))
}
#[cfg(feature = "test-util")]
pub mod test {
use super::{scope, CallContext};
use crate::plexus::AuthContext;
use plexus_auth_core::grants::Reach;
use std::future::Future;
pub async fn in_call<F: Future>(auth: Option<&AuthContext>, reach: Reach, fut: F) -> F::Output {
scope(CallContext::admitted(auth, reach), fut).await
}
}
pub fn scope<F: Future>(ctx: CallContext, fut: F) -> impl Future<Output = F::Output> {
CALL.scope(ctx, fut)
}
pin_project_lite::pin_project! {
pub struct InCall<S> {
ctx: CallContext,
#[pin]
inner: S,
}
}
impl<S> InCall<S> {
pub fn new(ctx: CallContext, inner: S) -> Self {
Self { ctx, inner }
}
}
impl<S: Stream> Stream for InCall<S> {
type Item = S::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
let this = self.project();
let inner = this.inner;
CALL.sync_scope(this.ctx.clone(), || inner.poll_next(cx))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Hop {
pub principal: String,
#[serde(rename = "for", default)]
pub for_: Vec<String>,
#[serde(default)]
pub limit: Option<HopLimit>,
#[serde(default)]
pub call: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
}
impl std::fmt::Debug for Hop {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Hop")
.field("principal", &self.principal)
.field("for_", &self.for_)
.field("limit", &self.limit)
.field("call", &self.call)
.field("token", &self.token.as_ref().map(|_| "…"))
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HopLimit {
pub grant: String,
#[serde(default)]
pub held_on: Vec<String>,
}
impl Hop {
pub fn caller(&self) -> Option<&str> {
self.for_.last().map(String::as_str)
}
pub fn grant(&self) -> Option<&str> {
self.limit.as_ref().map(|l| l.grant.as_str())
}
pub fn held_on(&self) -> Vec<ScopeRef> {
self.limit.as_ref().map(|l| l.held_on.iter().map(|s| ScopeRef::parse(s)).collect()).unwrap_or_default()
}
pub fn allows(&self, chain: &[ScopeRef]) -> bool {
let readable = self.caller().is_some_and(|p| p.parse::<plexus_auth_core::identity::Principal>().is_ok());
readable && self.held_on().iter().any(|s| s.is_everywhere() || chain.contains(s))
}
pub fn allows_scope(&self, scope: &str) -> bool {
self.allows(&[ScopeRef::parse(scope)])
}
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn ceiling_reach(caller: Option<&AuthContext>, grant: &str, held_on: &[ScopeRef]) -> Reach {
use plexus_auth_core::grants::{Gate, Membership, Memberships, Resolve, RoleTable};
struct Held(Vec<Membership>);
impl Memberships for Held {
fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
self.0.iter().filter(|m| &m.principal == who).cloned().collect()
}
}
struct Itself;
impl Resolve for Itself {
fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
Some(vec![ScopeRef::named(target), ScopeRef::Everywhere])
}
}
const ROLE: &str = "hop";
let grant = Grant::new(grant.to_string());
let held: Vec<Membership> = match caller.and_then(|a| a.principal()) {
Some(p) => held_on
.iter()
.map(|s| Membership { principal: p.clone(), role: plexus_auth_core::RoleName::new(ROLE), scope: s.clone() })
.collect(),
None => Vec::new(),
};
let roles = RoleTable::from_lists([(ROLE, [grant.as_str()])]);
let gate = Gate::new(std::sync::Arc::new(Held(held)), std::sync::Arc::new(roles), std::sync::Arc::new(Itself));
gate.reach_of_public(caller, &grant)
}