1use std::sync::atomic::{AtomicU64, Ordering};
42use std::sync::Arc;
43
44use futures::stream::{Stream, StreamExt};
45use plexus_auth_core::audit::{AuditQueue, AuditRecord};
46use plexus_auth_core::duplex::is_person;
47pub use plexus_auth_core::duplex::{Answerer, CallCeiling, CallRef, DuplexRefusalCode};
50pub use plexus_auth_core::grants::{GrantsGeneration, GrantsMove};
51use plexus_auth_core::grants::{Gate, Grant};
52use serde_json::{json, Value};
53use tokio::sync::{mpsc, watch};
54
55use super::auth::AuthContext;
56use super::plexus::{error_item, PlexusError};
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub struct ConnId(pub u64);
61
62impl From<ConnId> for CallRef {
63 fn from(conn: ConnId) -> Self {
66 CallRef { conn: conn.0, subscription: 0 }
67 }
68}
69
70pub struct CallPlace(#[allow(dead_code)] Box<dyn Send + Sync>);
73
74impl CallPlace {
75 pub fn new(held: impl Send + Sync + 'static) -> Self {
77 Self(Box::new(held))
78 }
79}
80
81pub trait CallCounter: Send + Sync {
85 fn take_place(&self) -> Result<CallPlace, usize>;
88}
89
90pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
92
93fn wall_clock() -> i64 {
94 chrono::Utc::now().timestamp()
95}
96
97#[derive(Debug, Clone)]
100pub enum DuplexRefusal {
101 Gate(PlexusError),
103 TooManyCalls { max: usize },
104 NotThisCall,
105 PastCredit { seq: u64, credit: u64 },
106 TooMuchInput { limit: &'static str, max: u64 },
107 PersonRequired,
108 InputClosed,
110}
111
112impl DuplexRefusal {
113 pub fn kind(&self) -> &'static str {
115 match self {
116 Self::Gate(PlexusError::Forbidden { .. }) => "forbidden",
117 Self::Gate(PlexusError::Unauthenticated(_)) => "unauthenticated",
118 Self::Gate(PlexusError::InvalidParams(_)) => "invalid_params",
119 Self::Gate(_) => "error",
120 other => other.code().as_str(),
121 }
122 }
123
124 pub fn code(&self) -> DuplexRefusalCode {
127 match self {
128 Self::Gate(PlexusError::Unauthenticated(_)) => DuplexRefusalCode::Unauthenticated,
129 Self::Gate(_) => DuplexRefusalCode::Forbidden,
130 Self::TooManyCalls { .. } => DuplexRefusalCode::TooManyCalls,
131 Self::NotThisCall => DuplexRefusalCode::NotThisCall,
132 Self::PastCredit { .. } => DuplexRefusalCode::PastCredit,
133 Self::TooMuchInput { .. } => DuplexRefusalCode::TooMuchInput,
134 Self::PersonRequired => DuplexRefusalCode::PersonRequired,
135 Self::InputClosed => DuplexRefusalCode::InputClosed,
136 }
137 }
138
139 pub fn ends_input(&self) -> bool {
142 !matches!(self, Self::NotThisCall | Self::PersonRequired)
143 }
144
145 pub fn into_plexus(self) -> Option<PlexusError> {
147 match self {
148 Self::Gate(e) => Some(e),
149 _ => None,
150 }
151 }
152
153 pub fn to_item(&self, ns: &str) -> Value {
156 let (message, facts) = match self {
157 Self::Gate(e) => return error_item(ns, e),
158 Self::TooManyCalls { max } => (format!("too many calls open on this connection (at most {max})"), json!({ "max": max })),
159 Self::NotThisCall => ("this call is not yours: input and answers come from the connection that opened it".into(), json!({})),
160 Self::PastCredit { seq, credit } => (format!("item {seq} is past the credit granted ({credit})"), json!({ "seq": seq, "credit": credit })),
161 Self::TooMuchInput { limit, max } => (format!("this call takes at most {max} {limit} of input"), json!({ "limit": limit, "max": max })),
162 Self::PersonRequired => ("this question needs a person's answer".into(), json!({})),
163 Self::InputClosed => ("the input half is closed".into(), json!({})),
164 };
165 let mut item = json!({ "type": "error", "error_kind": self.kind(), "message": message, "recoverable": false });
166 if let (Some(o), Value::Object(f)) = (item.as_object_mut(), facts) {
167 o.extend(f);
168 }
169 item
170 }
171}
172
173#[derive(Debug, Clone)]
176pub struct InputFrame {
177 pub from: ConnId,
178 pub seq: u64,
179 pub item: Value,
180 pub bytes: u64,
181}
182
183impl InputFrame {
184 pub fn new(from: ConnId, seq: u64, item: Value) -> Self {
187 let bytes = serde_json::to_vec(&item).map(|v| v.len() as u64).unwrap_or(0);
188 Self { from, seq, item, bytes }
189 }
190}
191
192#[derive(Clone)]
195pub struct DuplexGate {
196 gate: Gate,
197 checks: Arc<AtomicU64>,
198 audit: Option<AuditQueue>,
199 clock: Clock,
200}
201
202impl DuplexGate {
203 pub fn new(gate: Gate) -> Self {
206 Self { gate, checks: Arc::new(AtomicU64::new(0)), audit: None, clock: Arc::new(wall_clock) }
207 }
208
209 pub fn with_audit(mut self, audit: AuditQueue) -> Self {
211 self.audit = Some(audit);
212 self
213 }
214
215 pub fn with_clock(mut self, clock: Clock) -> Self {
217 self.clock = clock;
218 self
219 }
220
221 pub fn gate(&self) -> &Gate {
223 &self.gate
224 }
225
226 pub fn gate_checks(&self) -> u64 {
228 self.checks.load(Ordering::Relaxed)
229 }
230
231 fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<(), DuplexRefusal> {
232 self.checks.fetch_add(1, Ordering::Relaxed);
233 self.gate.check(caller, grant, target).map(drop).map_err(|r| DuplexRefusal::Gate(r.into()))
234 }
235
236 fn audited(&self, call: CallRef, who: Option<&AuthContext>, grant: &Grant, why: DuplexRefusal) -> DuplexRefusal {
238 if let Some(q) = &self.audit {
239 q.offer(AuditRecord::duplex_refused(call, why.code(), who, grant.as_str()));
240 }
241 why
242 }
243
244 #[allow(clippy::too_many_arguments)]
248 pub fn open(
249 &self,
250 at: impl Into<CallRef>,
251 calls: &dyn CallCounter,
252 caller: Option<Arc<AuthContext>>,
253 grant: &str,
254 target: Option<&str>,
255 ceiling: CallCeiling,
256 answer_by: Answerer,
257 ) -> Result<DuplexCall, DuplexRefusal> {
258 let at = at.into();
259 let mut moves = self.gate.generation().subscribe();
261 let seen = *moves.borrow_and_update();
262 let grant = Grant::new(grant);
263 if let Err(e) = self.check(caller.as_deref(), &grant, target) {
264 return Err(self.audited(at, caller.as_deref(), &grant, e));
265 }
266 let place = match calls.take_place() {
267 Ok(p) => p,
268 Err(max) => return Err(self.audited(at, caller.as_deref(), &grant, DuplexRefusal::TooManyCalls { max })),
269 };
270 Ok(DuplexCall {
271 dg: self.clone(),
272 conn: ConnId(at.conn),
273 at,
274 caller,
275 grant,
276 target: target.map(str::to_string),
277 seen,
278 moves,
279 ceiling,
280 credit: ceiling.credit,
281 items: 0,
282 bytes: 0,
283 closed: None,
284 answer_by,
285 _place: place,
286 })
287 }
288}
289
290pub struct DuplexCall {
292 dg: DuplexGate,
293 conn: ConnId,
294 at: CallRef,
295 caller: Option<Arc<AuthContext>>,
296 grant: Grant,
297 target: Option<String>,
298 seen: u64,
299 moves: watch::Receiver<u64>,
300 ceiling: CallCeiling,
301 credit: u64,
302 items: u64,
303 bytes: u64,
304 closed: Option<DuplexRefusal>,
305 answer_by: Answerer,
306 _place: CallPlace,
307}
308
309impl DuplexCall {
310 pub fn call(&self) -> CallRef {
312 self.at
313 }
314
315 pub fn answer_by(&self) -> &Answerer {
317 &self.answer_by
318 }
319
320 pub fn closed(&self) -> Option<&DuplexRefusal> {
322 self.closed.as_ref()
323 }
324
325 pub fn grant_credit(&mut self, n: u64) {
327 self.credit = self.credit.saturating_add(n);
328 }
329
330 fn refuse(&self, why: DuplexRefusal) -> DuplexRefusal {
331 self.dg.audited(self.at, self.caller.as_deref(), &self.grant, why)
332 }
333
334 fn close(&mut self, why: DuplexRefusal) -> DuplexRefusal {
335 let why = self.refuse(why);
336 self.closed = Some(why.clone());
337 why
338 }
339
340 pub fn reverify(&mut self) -> Result<(), DuplexRefusal> {
342 let now = self.dg.gate.generation().current();
343 match self.dg.check(self.caller.as_deref(), &self.grant, self.target.as_deref()) {
344 Ok(()) => {
345 self.seen = now;
346 Ok(())
347 }
348 Err(e) => Err(self.close(e)),
349 }
350 }
351
352 pub fn expire(&mut self) -> DuplexRefusal {
356 self.close(DuplexRefusal::Gate(PlexusError::Unauthenticated("your sign-in has expired: sign in again".into())))
357 }
358
359 pub fn admit(&mut self, f: &InputFrame) -> Result<(), DuplexRefusal> {
361 if self.closed.is_some() {
362 return Err(self.refuse(DuplexRefusal::InputClosed));
363 }
364 if f.from != self.conn {
365 return Err(self.refuse(DuplexRefusal::NotThisCall));
366 }
367 if self.dg.gate.generation().current() != self.seen {
368 self.reverify()?;
369 }
370 if f.seq >= self.credit {
371 return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit: self.credit }));
372 }
373 if self.items + 1 > self.ceiling.max_items {
374 return Err(self.close(DuplexRefusal::TooMuchInput { limit: "items", max: self.ceiling.max_items }));
375 }
376 if self.bytes + f.bytes > self.ceiling.max_bytes {
377 return Err(self.close(DuplexRefusal::TooMuchInput { limit: "bytes", max: self.ceiling.max_bytes }));
378 }
379 self.items += 1;
380 self.bytes += f.bytes;
381 Ok(())
382 }
383
384 pub fn answer(&self, from: ConnId, who: Option<&AuthContext>) -> Result<(), DuplexRefusal> {
387 let refused = |why| Err(self.dg.audited(self.at, who, &self.grant, why));
388 if self.closed.is_some() {
389 return refused(DuplexRefusal::InputClosed);
390 }
391 match &self.answer_by {
392 Answerer::Caller if from == self.conn => Ok(()),
393 Answerer::Person if from == self.conn => match who {
394 Some(w) if is_person(w) => Ok(()),
395 _ => refused(DuplexRefusal::PersonRequired),
396 },
397 Answerer::Caller | Answerer::Person => refused(DuplexRefusal::NotThisCall),
398 Answerer::Grant(g) => match self.dg.check(who, &Grant::new(g.clone()), self.target.as_deref()) {
399 Ok(()) => Ok(()),
400 Err(e) => refused(e),
401 },
402 }
403 }
404
405 pub fn input<S>(mut self, frames: S, refused: mpsc::UnboundedSender<(ConnId, Value)>) -> impl Stream<Item = Result<Value, DuplexRefusal>> + Send + 'static
411 where
412 S: Stream<Item = InputFrame> + Send + 'static,
413 {
414 let ns = self.grant.as_str().split('.').next().unwrap_or("").to_string();
415 let expires = self
416 .caller
417 .as_ref()
418 .and_then(|c| c.metadata.get(plexus_auth_core::auth::EXPIRES_AT_KEY))
419 .and_then(Value::as_i64);
420 let now = (self.dg.clock)();
421 async_stream::stream! {
422 let frames = frames;
423 futures::pin_mut!(frames);
424 let expiry = async move {
425 match expires {
426 Some(at) => {
427 let secs = at.saturating_sub(now).max(0) as u64;
428 tokio::time::sleep(std::time::Duration::from_secs(secs)).await
429 }
430 None => std::future::pending().await,
431 }
432 };
433 futures::pin_mut!(expiry);
434 loop {
435 tokio::select! {
436 biased;
437 moved = self.moves.changed() => {
438 if moved.is_err() || self.dg.gate.generation().current() == self.seen { continue; }
441 if let Err(e) = self.reverify() { yield Err(e); break; }
442 }
443 () = &mut expiry => {
444 yield Err(self.expire());
445 break;
446 }
447 f = frames.next() => match f {
448 None => break,
449 Some(f) => match self.admit(&f) {
450 Ok(()) => yield Ok(f.item),
451 Err(e) if !e.ends_input() => { let _ = refused.send((f.from, e.to_item(&ns))); }
452 Err(e) => { yield Err(e); break; }
453 },
454 },
455 }
456 }
457 }
458 }
459}