use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use futures::stream::{Stream, StreamExt};
use plexus_auth_core::audit::{AuditQueue, AuditRecord};
use plexus_auth_core::duplex::is_person;
pub use plexus_auth_core::duplex::{Answerer, CallCeiling, CallRef, DuplexRefusalCode};
pub use plexus_auth_core::grants::{GrantsGeneration, GrantsMove};
use plexus_auth_core::grants::{Gate, Grant, Membership, Memberships, Resolve, RoleTable, ScopeRef};
use serde_json::{json, Value};
use tokio::sync::{mpsc, watch};
use super::auth::AuthContext;
use super::context::PlexusContext;
use super::plexus::{error_item, PlexusError};
use super::types::{spec_code, spec_fields, PlexusStreamItem, StreamMetadata};
use super::RemoteError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ConnId(pub u64);
impl From<ConnId> for CallRef {
fn from(conn: ConnId) -> Self {
CallRef { conn: conn.0, subscription: 0 }
}
}
pub struct CallPlace(#[allow(dead_code)] Box<dyn Send + Sync>);
impl CallPlace {
pub fn new(held: impl Send + Sync + 'static) -> Self {
Self(Box::new(held))
}
}
pub trait CallCounter: Send + Sync {
fn take_place(&self) -> Result<CallPlace, usize>;
}
pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
fn wall_clock() -> i64 {
chrono::Utc::now().timestamp()
}
#[derive(Debug, Clone)]
pub enum DuplexRefusal {
Gate(PlexusError),
TooManyCalls { max: usize },
NotThisCall,
PastCredit { seq: u64, credit: u64 },
TooMuchInput { limit: &'static str, max: u64 },
PersonRequired,
InputClosed,
OutOfSequence { seq: u64, expected: u64 },
InvalidInput { seq: u64, message: String },
}
impl DuplexRefusal {
pub fn kind(&self) -> &'static str {
match self {
Self::Gate(PlexusError::Forbidden { .. }) => "forbidden",
Self::Gate(PlexusError::Unauthenticated(_)) => "unauthenticated",
Self::Gate(PlexusError::InvalidParams { .. }) => "invalid_params",
Self::Gate(_) => "error",
other => other.code().as_str(),
}
}
pub fn code(&self) -> DuplexRefusalCode {
match self {
Self::Gate(PlexusError::Unauthenticated(_)) => DuplexRefusalCode::Unauthenticated,
Self::Gate(_) => DuplexRefusalCode::Forbidden,
Self::TooManyCalls { .. } => DuplexRefusalCode::TooManyCalls,
Self::NotThisCall => DuplexRefusalCode::NotThisCall,
Self::PastCredit { .. } => DuplexRefusalCode::PastCredit,
Self::TooMuchInput { .. } => DuplexRefusalCode::TooMuchInput,
Self::PersonRequired => DuplexRefusalCode::PersonRequired,
Self::InputClosed => DuplexRefusalCode::InputClosed,
Self::OutOfSequence { .. } => DuplexRefusalCode::OutOfSequence,
Self::InvalidInput { .. } => DuplexRefusalCode::InvalidInput,
}
}
pub fn ends_input(&self) -> bool {
!matches!(self, Self::NotThisCall | Self::PersonRequired)
}
pub fn into_plexus(self) -> Option<PlexusError> {
match self {
Self::Gate(e) => Some(e),
_ => None,
}
}
pub fn to_item(&self, ns: &str) -> Value {
let (message, facts) = match self {
Self::Gate(e) => return error_item(ns, e),
Self::TooManyCalls { max } => (format!("too many calls open on this connection (at most {max})"), json!({ "max": max })),
Self::NotThisCall => ("this call is not yours: input and answers come from the connection that opened it".into(), json!({})),
Self::PastCredit { seq, credit } => (format!("item {seq} is past the credit granted ({credit})"), json!({ "seq": seq, "credit": credit })),
Self::TooMuchInput { limit, max } => (format!("this call takes at most {max} {limit} of input"), json!({ "limit": limit, "max": max })),
Self::PersonRequired => ("this question needs a person's answer".into(), json!({})),
Self::InputClosed => ("the input half is closed".into(), json!({})),
Self::OutOfSequence { seq, expected } => (format!("input frame {seq} is out of sequence: {expected} comes next"), json!({ "seq": seq, "expected": expected })),
Self::InvalidInput { seq, message } => (format!("an item of input frame {seq} is not this method's input: {message}"), json!({ "seq": seq })),
};
let Value::Object(facts) = facts else { unreachable!("facts are an object") };
let metadata = StreamMetadata::new(vec![ns.into()], PlexusContext::hash());
let error = match self {
Self::TooManyCalls { max } => RemoteError::TooManyCalls { max: *max as u64, child: None },
_ => RemoteError::Other(plexus_client::OtherError { kind: self.kind().to_string(), fields: facts }),
};
let item = PlexusStreamItem::Error {
metadata,
message,
code: Some(spec_code(&error)),
recoverable: false,
fields: spec_fields(&error),
error,
};
serde_json::to_value(&item).unwrap_or(Value::Null)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Overrun {
Credit,
Sequence { expected: u64 },
Empty,
}
#[derive(Debug, Clone)]
pub struct InputFrame<I = Value> {
pub from: ConnId,
pub seq: u64,
pub item: I,
pub items: u64,
pub bytes: u64,
pub overrun: Option<Overrun>,
}
impl InputFrame {
pub fn new(from: ConnId, seq: u64, item: Value) -> Self {
let bytes = serde_json::to_vec(&item).map(|v| v.len() as u64).unwrap_or(0);
Self { from, seq, item, items: 1, bytes, overrun: None }
}
}
#[derive(Debug, Clone)]
pub struct CreditLine(Arc<AtomicU64>);
impl CreditLine {
pub fn grant(&self, n: u64) {
let _ = self.0.fetch_update(Ordering::AcqRel, Ordering::Acquire, |c| Some(c.saturating_add(n)));
}
pub fn granted(&self) -> u64 {
self.0.load(Ordering::Acquire)
}
}
struct Nobody;
impl Memberships for Nobody {
fn held(&self, _who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
Vec::new()
}
}
impl Resolve for Nobody {
fn chain(&self, _target: &str) -> Option<Vec<ScopeRef>> {
None
}
}
#[derive(Clone)]
pub struct DuplexGate {
gate: Gate,
checks: Arc<AtomicU64>,
audit: Option<AuditQueue>,
clock: Clock,
}
impl DuplexGate {
pub fn new(gate: Gate) -> Self {
Self { gate, checks: Arc::new(AtomicU64::new(0)), audit: None, clock: Arc::new(wall_clock) }
}
pub fn ungated() -> Self {
Self::new(Gate::new(Arc::new(Nobody), Arc::new(RoleTable::new()), Arc::new(Nobody)))
}
pub fn with_audit(mut self, audit: AuditQueue) -> Self {
self.audit = Some(audit);
self
}
pub fn with_clock(mut self, clock: Clock) -> Self {
self.clock = clock;
self
}
pub fn gate(&self) -> &Gate {
&self.gate
}
pub fn gate_checks(&self) -> u64 {
self.checks.load(Ordering::Relaxed)
}
fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<(), DuplexRefusal> {
self.checks.fetch_add(1, Ordering::Relaxed);
self.gate.check(caller, grant, target).map(drop).map_err(|r| DuplexRefusal::Gate(r.into()))
}
fn audited(&self, call: CallRef, who: Option<&AuthContext>, grant: &Grant, why: DuplexRefusal) -> DuplexRefusal {
if let Some(q) = &self.audit {
q.offer(AuditRecord::duplex_refused(call, why.code(), who, grant.as_str()));
}
why
}
#[allow(clippy::too_many_arguments)]
pub fn open(
&self,
at: impl Into<CallRef>,
calls: &dyn CallCounter,
caller: Option<Arc<AuthContext>>,
grant: &str,
target: Option<&str>,
ceiling: CallCeiling,
answer_by: Answerer,
) -> Result<DuplexCall, DuplexRefusal> {
let at = at.into();
let mut moves = self.gate.generation().subscribe();
let seen = *moves.borrow_and_update();
let grant = Grant::new(grant);
if let Err(e) = self.check(caller.as_deref(), &grant, target) {
return Err(self.audited(at, caller.as_deref(), &grant, e));
}
let targets = target.map(str::to_string).into_iter().collect();
self.opened(at, calls, caller, grant, targets, seen, moves, true, ceiling, answer_by)
}
#[allow(clippy::too_many_arguments)]
pub fn admitted(
&self,
at: impl Into<CallRef>,
calls: &dyn CallCounter,
caller: Option<Arc<AuthContext>>,
grant: &str,
targets: Vec<String>,
seen: u64,
recheck: bool,
ceiling: CallCeiling,
answer_by: Answerer,
) -> Result<DuplexCall, DuplexRefusal> {
let mut moves = self.gate.generation().subscribe();
moves.mark_changed();
self.opened(at.into(), calls, caller, Grant::new(grant), targets, seen, moves, recheck, ceiling, answer_by)
}
#[allow(clippy::too_many_arguments)]
fn opened(
&self,
at: CallRef,
calls: &dyn CallCounter,
caller: Option<Arc<AuthContext>>,
grant: Grant,
targets: Vec<String>,
seen: u64,
moves: watch::Receiver<u64>,
recheck: bool,
ceiling: CallCeiling,
answer_by: Answerer,
) -> Result<DuplexCall, DuplexRefusal> {
let place = match calls.take_place() {
Ok(p) => p,
Err(max) => return Err(self.audited(at, caller.as_deref(), &grant, DuplexRefusal::TooManyCalls { max })),
};
Ok(DuplexCall {
dg: self.clone(),
conn: ConnId(at.conn),
at,
caller,
grant,
targets,
recheck,
seen,
moves,
ceiling,
credit: CreditLine(Arc::new(AtomicU64::new(ceiling.credit))),
items: 0,
bytes: 0,
closed: None,
answer_by,
_place: place,
})
}
}
pub struct DuplexCall {
dg: DuplexGate,
conn: ConnId,
at: CallRef,
caller: Option<Arc<AuthContext>>,
grant: Grant,
targets: Vec<String>,
recheck: bool,
seen: u64,
moves: watch::Receiver<u64>,
ceiling: CallCeiling,
credit: CreditLine,
items: u64,
bytes: u64,
closed: Option<DuplexRefusal>,
answer_by: Answerer,
_place: CallPlace,
}
impl DuplexCall {
pub fn call(&self) -> CallRef {
self.at
}
pub fn answer_by(&self) -> &Answerer {
&self.answer_by
}
pub fn closed(&self) -> Option<&DuplexRefusal> {
self.closed.as_ref()
}
pub fn grant_credit(&mut self, n: u64) {
self.credit.grant(n);
}
pub fn credit_line(&self) -> CreditLine {
self.credit.clone()
}
fn refuse(&self, why: DuplexRefusal) -> DuplexRefusal {
self.dg.audited(self.at, self.caller.as_deref(), &self.grant, why)
}
fn close(&mut self, why: DuplexRefusal) -> DuplexRefusal {
let why = self.refuse(why);
self.closed = Some(why.clone());
why
}
pub fn reverify(&mut self) -> Result<(), DuplexRefusal> {
let now = self.dg.gate.generation().current();
let asked = if !self.recheck {
Ok(())
} else if self.targets.is_empty() {
self.dg.check(self.caller.as_deref(), &self.grant, None)
} else {
self.targets.iter().try_for_each(|t| self.dg.check(self.caller.as_deref(), &self.grant, Some(t)))
};
match asked {
Ok(()) => {
self.seen = now;
Ok(())
}
Err(e) => Err(self.close(e)),
}
}
pub fn expire(&mut self) -> DuplexRefusal {
self.close(DuplexRefusal::Gate(PlexusError::Unauthenticated("your sign-in has expired: sign in again".into())))
}
pub fn admit<I>(&mut self, f: &InputFrame<I>) -> Result<(), DuplexRefusal> {
if self.closed.is_some() {
return Err(self.refuse(DuplexRefusal::InputClosed));
}
if f.from != self.conn {
return Err(self.refuse(DuplexRefusal::NotThisCall));
}
if self.dg.gate.generation().current() != self.seen {
self.reverify()?;
}
let credit = self.credit.granted();
match f.overrun {
None => {}
Some(Overrun::Credit) => return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit })),
Some(Overrun::Sequence { expected }) => return Err(self.close(DuplexRefusal::OutOfSequence { seq: f.seq, expected })),
Some(Overrun::Empty) => return Err(self.close(DuplexRefusal::InvalidInput { seq: f.seq, message: "an input frame with no items".into() })),
}
if f.items == 0 {
return Err(self.close(DuplexRefusal::InvalidInput { seq: f.seq, message: "an input frame with no items".into() }));
}
if self.items.saturating_add(f.items) > credit {
return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit }));
}
if self.items.saturating_add(f.items) > self.ceiling.max_items {
return Err(self.close(DuplexRefusal::TooMuchInput { limit: "items", max: self.ceiling.max_items }));
}
if self.bytes.saturating_add(f.bytes) > self.ceiling.max_bytes {
return Err(self.close(DuplexRefusal::TooMuchInput { limit: "bytes", max: self.ceiling.max_bytes }));
}
self.items = self.items.saturating_add(f.items);
self.bytes = self.bytes.saturating_add(f.bytes);
Ok(())
}
pub fn answer(&self, from: ConnId, who: Option<&AuthContext>) -> Result<(), DuplexRefusal> {
let refused = |why| Err(self.dg.audited(self.at, who, &self.grant, why));
if self.closed.is_some() {
return refused(DuplexRefusal::InputClosed);
}
match &self.answer_by {
Answerer::Caller if from == self.conn => Ok(()),
Answerer::Person if from == self.conn => match who {
Some(w) if is_person(w) => Ok(()),
_ => refused(DuplexRefusal::PersonRequired),
},
Answerer::Caller | Answerer::Person => refused(DuplexRefusal::NotThisCall),
Answerer::Grant(g) => match self.dg.check(who, &Grant::new(g.clone()), self.targets.first().map(String::as_str)) {
Ok(()) => Ok(()),
Err(e) => refused(e),
},
}
}
pub fn input<S, I>(mut self, frames: S, refused: mpsc::UnboundedSender<(ConnId, Value)>) -> impl Stream<Item = Result<I, DuplexRefusal>> + Send + 'static
where
S: Stream<Item = InputFrame<I>> + Send + 'static,
I: Send + 'static,
{
let ns = self.grant.as_str().split('.').next().unwrap_or("").to_string();
let expires = self
.caller
.as_ref()
.and_then(|c| c.metadata.get(plexus_auth_core::auth::EXPIRES_AT_KEY))
.and_then(Value::as_i64);
let now = (self.dg.clock)();
async_stream::stream! {
let frames = frames;
futures::pin_mut!(frames);
let expiry = async move {
match expires {
Some(at) => {
let secs = at.saturating_sub(now).max(0) as u64;
crate::rt::sleep(std::time::Duration::from_secs(secs)).await
}
None => std::future::pending().await,
}
};
futures::pin_mut!(expiry);
loop {
tokio::select! {
biased;
moved = self.moves.changed() => {
if moved.is_err() || self.dg.gate.generation().current() == self.seen { continue; }
if let Err(e) = self.reverify() { yield Err(e); break; }
}
() = &mut expiry => {
yield Err(self.expire());
break;
}
f = frames.next() => match f {
None => break,
Some(f) => match self.admit(&f) {
Ok(()) => yield Ok(f.item),
Err(e) if !e.ends_input() => { let _ = refused.send((f.from, e.to_item(&ns))); }
Err(e) => { yield Err(e); break; }
},
},
}
}
}
}
}