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};
use serde_json::{json, Value};
use tokio::sync::{mpsc, watch};
use super::auth::AuthContext;
use super::plexus::{error_item, PlexusError};
#[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,
}
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,
}
}
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!({})),
};
let mut item = json!({ "type": "error", "error_kind": self.kind(), "message": message, "recoverable": false });
if let (Some(o), Value::Object(f)) = (item.as_object_mut(), facts) {
o.extend(f);
}
item
}
}
#[derive(Debug, Clone)]
pub struct InputFrame {
pub from: ConnId,
pub seq: u64,
pub item: Value,
pub bytes: u64,
}
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, bytes }
}
}
#[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 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 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,
target: target.map(str::to_string),
seen,
moves,
ceiling,
credit: 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,
target: Option<String>,
seen: u64,
moves: watch::Receiver<u64>,
ceiling: CallCeiling,
credit: u64,
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 = self.credit.saturating_add(n);
}
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();
match self.dg.check(self.caller.as_deref(), &self.grant, self.target.as_deref()) {
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(&mut self, f: &InputFrame) -> 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()?;
}
if f.seq >= self.credit {
return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit: self.credit }));
}
if self.items + 1 > self.ceiling.max_items {
return Err(self.close(DuplexRefusal::TooMuchInput { limit: "items", max: self.ceiling.max_items }));
}
if self.bytes + f.bytes > self.ceiling.max_bytes {
return Err(self.close(DuplexRefusal::TooMuchInput { limit: "bytes", max: self.ceiling.max_bytes }));
}
self.items += 1;
self.bytes += 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.target.as_deref()) {
Ok(()) => Ok(()),
Err(e) => refused(e),
},
}
}
pub fn input<S>(mut self, frames: S, refused: mpsc::UnboundedSender<(ConnId, Value)>) -> impl Stream<Item = Result<Value, DuplexRefusal>> + Send + 'static
where
S: Stream<Item = InputFrame> + 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;
tokio::time::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; }
},
},
}
}
}
}
}