1use std::sync::atomic::{AtomicU64, Ordering};
44use std::sync::Arc;
45
46use futures::stream::{Stream, StreamExt};
47use plexus_auth_core::audit::{AuditQueue, AuditRecord};
48use plexus_auth_core::duplex::is_person;
49pub use plexus_auth_core::duplex::{Answerer, CallCeiling, CallRef, DuplexRefusalCode};
52pub use plexus_auth_core::grants::{GrantsGeneration, GrantsMove};
53use plexus_auth_core::grants::{Gate, Grant, Membership, Memberships, Resolve, RoleTable, ScopeRef};
54use serde_json::{json, Value};
55use tokio::sync::{mpsc, watch};
56
57use super::auth::AuthContext;
58use super::context::PlexusContext;
59use super::plexus::{error_item, PlexusError};
60use super::types::{spec_code, spec_fields, PlexusStreamItem, StreamMetadata};
61use super::RemoteError;
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
65pub struct ConnId(pub u64);
66
67impl From<ConnId> for CallRef {
68 fn from(conn: ConnId) -> Self {
71 CallRef { conn: conn.0, subscription: 0 }
72 }
73}
74
75pub struct CallPlace(#[allow(dead_code)] Box<dyn Send + Sync>);
78
79impl CallPlace {
80 pub fn new(held: impl Send + Sync + 'static) -> Self {
82 Self(Box::new(held))
83 }
84}
85
86pub trait CallCounter: Send + Sync {
90 fn take_place(&self) -> Result<CallPlace, usize>;
93}
94
95pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
97
98fn wall_clock() -> i64 {
99 chrono::Utc::now().timestamp()
100}
101
102#[derive(Debug, Clone)]
105pub enum DuplexRefusal {
106 Gate(PlexusError),
108 TooManyCalls { max: usize },
109 NotThisCall,
110 PastCredit { seq: u64, credit: u64 },
111 TooMuchInput { limit: &'static str, max: u64 },
112 PersonRequired,
113 InputClosed,
115 OutOfSequence { seq: u64, expected: u64 },
117 InvalidInput { seq: u64, message: String },
119}
120
121impl DuplexRefusal {
122 pub fn kind(&self) -> &'static str {
124 match self {
125 Self::Gate(PlexusError::Forbidden { .. }) => "forbidden",
126 Self::Gate(PlexusError::Unauthenticated(_)) => "unauthenticated",
127 Self::Gate(PlexusError::InvalidParams { .. }) => "invalid_params",
128 Self::Gate(_) => "error",
129 other => other.code().as_str(),
130 }
131 }
132
133 pub fn code(&self) -> DuplexRefusalCode {
136 match self {
137 Self::Gate(PlexusError::Unauthenticated(_)) => DuplexRefusalCode::Unauthenticated,
138 Self::Gate(_) => DuplexRefusalCode::Forbidden,
139 Self::TooManyCalls { .. } => DuplexRefusalCode::TooManyCalls,
140 Self::NotThisCall => DuplexRefusalCode::NotThisCall,
141 Self::PastCredit { .. } => DuplexRefusalCode::PastCredit,
142 Self::TooMuchInput { .. } => DuplexRefusalCode::TooMuchInput,
143 Self::PersonRequired => DuplexRefusalCode::PersonRequired,
144 Self::InputClosed => DuplexRefusalCode::InputClosed,
145 Self::OutOfSequence { .. } => DuplexRefusalCode::OutOfSequence,
146 Self::InvalidInput { .. } => DuplexRefusalCode::InvalidInput,
147 }
148 }
149
150 pub fn ends_input(&self) -> bool {
153 !matches!(self, Self::NotThisCall | Self::PersonRequired)
154 }
155
156 pub fn into_plexus(self) -> Option<PlexusError> {
158 match self {
159 Self::Gate(e) => Some(e),
160 _ => None,
161 }
162 }
163
164 pub fn to_item(&self, ns: &str) -> Value {
168 let (message, facts) = match self {
169 Self::Gate(e) => return error_item(ns, e),
170 Self::TooManyCalls { max } => (format!("too many calls open on this connection (at most {max})"), json!({ "max": max })),
171 Self::NotThisCall => ("this call is not yours: input and answers come from the connection that opened it".into(), json!({})),
172 Self::PastCredit { seq, credit } => (format!("item {seq} is past the credit granted ({credit})"), json!({ "seq": seq, "credit": credit })),
173 Self::TooMuchInput { limit, max } => (format!("this call takes at most {max} {limit} of input"), json!({ "limit": limit, "max": max })),
174 Self::PersonRequired => ("this question needs a person's answer".into(), json!({})),
175 Self::InputClosed => ("the input half is closed".into(), json!({})),
176 Self::OutOfSequence { seq, expected } => (format!("input frame {seq} is out of sequence: {expected} comes next"), json!({ "seq": seq, "expected": expected })),
177 Self::InvalidInput { seq, message } => (format!("an item of input frame {seq} is not this method's input: {message}"), json!({ "seq": seq })),
178 };
179 let Value::Object(facts) = facts else { unreachable!("facts are an object") };
180 let metadata = StreamMetadata::new(vec![ns.into()], PlexusContext::hash());
181 let error = match self {
184 Self::TooManyCalls { max } => RemoteError::TooManyCalls { max: *max as u64, child: None },
185 _ => RemoteError::Other(plexus_client::OtherError { kind: self.kind().to_string(), fields: facts }),
186 };
187 let item = PlexusStreamItem::Error {
188 metadata,
189 message,
190 code: Some(spec_code(&error)),
191 recoverable: false,
192 fields: spec_fields(&error),
193 error,
194 };
195 serde_json::to_value(&item).unwrap_or(Value::Null)
196 }
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub enum Overrun {
205 Credit,
207 Sequence { expected: u64 },
209 Empty,
211}
212
213#[derive(Debug, Clone)]
217pub struct InputFrame<I = Value> {
218 pub from: ConnId,
219 pub seq: u64,
220 pub item: I,
221 pub items: u64,
223 pub bytes: u64,
224 pub overrun: Option<Overrun>,
226}
227
228impl InputFrame {
229 pub fn new(from: ConnId, seq: u64, item: Value) -> Self {
232 let bytes = serde_json::to_vec(&item).map(|v| v.len() as u64).unwrap_or(0);
233 Self { from, seq, item, items: 1, bytes, overrun: None }
234 }
235}
236
237#[derive(Debug, Clone)]
241pub struct CreditLine(Arc<AtomicU64>);
242
243impl CreditLine {
244 pub fn grant(&self, n: u64) {
246 let _ = self.0.fetch_update(Ordering::AcqRel, Ordering::Acquire, |c| Some(c.saturating_add(n)));
247 }
248
249 pub fn granted(&self) -> u64 {
251 self.0.load(Ordering::Acquire)
252 }
253}
254
255struct Nobody;
258
259impl Memberships for Nobody {
260 fn held(&self, _who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
261 Vec::new()
262 }
263}
264
265impl Resolve for Nobody {
266 fn chain(&self, _target: &str) -> Option<Vec<ScopeRef>> {
267 None
268 }
269}
270
271#[derive(Clone)]
274pub struct DuplexGate {
275 gate: Gate,
276 checks: Arc<AtomicU64>,
277 audit: Option<AuditQueue>,
278 clock: Clock,
279}
280
281impl DuplexGate {
282 pub fn new(gate: Gate) -> Self {
285 Self { gate, checks: Arc::new(AtomicU64::new(0)), audit: None, clock: Arc::new(wall_clock) }
286 }
287
288 pub fn ungated() -> Self {
293 Self::new(Gate::new(Arc::new(Nobody), Arc::new(RoleTable::new()), Arc::new(Nobody)))
294 }
295
296 pub fn with_audit(mut self, audit: AuditQueue) -> Self {
298 self.audit = Some(audit);
299 self
300 }
301
302 pub fn with_clock(mut self, clock: Clock) -> Self {
304 self.clock = clock;
305 self
306 }
307
308 pub fn gate(&self) -> &Gate {
310 &self.gate
311 }
312
313 pub fn gate_checks(&self) -> u64 {
315 self.checks.load(Ordering::Relaxed)
316 }
317
318 fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<(), DuplexRefusal> {
319 self.checks.fetch_add(1, Ordering::Relaxed);
320 self.gate.check(caller, grant, target).map(drop).map_err(|r| DuplexRefusal::Gate(r.into()))
321 }
322
323 fn audited(&self, call: CallRef, who: Option<&AuthContext>, grant: &Grant, why: DuplexRefusal) -> DuplexRefusal {
325 if let Some(q) = &self.audit {
326 q.offer(AuditRecord::duplex_refused(call, why.code(), who, grant.as_str()));
327 }
328 why
329 }
330
331 #[allow(clippy::too_many_arguments)]
335 pub fn open(
336 &self,
337 at: impl Into<CallRef>,
338 calls: &dyn CallCounter,
339 caller: Option<Arc<AuthContext>>,
340 grant: &str,
341 target: Option<&str>,
342 ceiling: CallCeiling,
343 answer_by: Answerer,
344 ) -> Result<DuplexCall, DuplexRefusal> {
345 let at = at.into();
346 let mut moves = self.gate.generation().subscribe();
348 let seen = *moves.borrow_and_update();
349 let grant = Grant::new(grant);
350 if let Err(e) = self.check(caller.as_deref(), &grant, target) {
351 return Err(self.audited(at, caller.as_deref(), &grant, e));
352 }
353 let targets = target.map(str::to_string).into_iter().collect();
354 self.opened(at, calls, caller, grant, targets, seen, moves, true, ceiling, answer_by)
355 }
356
357 #[allow(clippy::too_many_arguments)]
365 pub fn admitted(
366 &self,
367 at: impl Into<CallRef>,
368 calls: &dyn CallCounter,
369 caller: Option<Arc<AuthContext>>,
370 grant: &str,
371 targets: Vec<String>,
372 seen: u64,
373 recheck: bool,
374 ceiling: CallCeiling,
375 answer_by: Answerer,
376 ) -> Result<DuplexCall, DuplexRefusal> {
377 let mut moves = self.gate.generation().subscribe();
378 moves.mark_changed();
379 self.opened(at.into(), calls, caller, Grant::new(grant), targets, seen, moves, recheck, ceiling, answer_by)
380 }
381
382 #[allow(clippy::too_many_arguments)]
383 fn opened(
384 &self,
385 at: CallRef,
386 calls: &dyn CallCounter,
387 caller: Option<Arc<AuthContext>>,
388 grant: Grant,
389 targets: Vec<String>,
390 seen: u64,
391 moves: watch::Receiver<u64>,
392 recheck: bool,
393 ceiling: CallCeiling,
394 answer_by: Answerer,
395 ) -> Result<DuplexCall, DuplexRefusal> {
396 let place = match calls.take_place() {
397 Ok(p) => p,
398 Err(max) => return Err(self.audited(at, caller.as_deref(), &grant, DuplexRefusal::TooManyCalls { max })),
399 };
400 Ok(DuplexCall {
401 dg: self.clone(),
402 conn: ConnId(at.conn),
403 at,
404 caller,
405 grant,
406 targets,
407 recheck,
408 seen,
409 moves,
410 ceiling,
411 credit: CreditLine(Arc::new(AtomicU64::new(ceiling.credit))),
412 items: 0,
413 bytes: 0,
414 closed: None,
415 answer_by,
416 _place: place,
417 })
418 }
419}
420
421pub struct DuplexCall {
423 dg: DuplexGate,
424 conn: ConnId,
425 at: CallRef,
426 caller: Option<Arc<AuthContext>>,
427 grant: Grant,
428 targets: Vec<String>,
429 recheck: bool,
430 seen: u64,
431 moves: watch::Receiver<u64>,
432 ceiling: CallCeiling,
433 credit: CreditLine,
434 items: u64,
435 bytes: u64,
436 closed: Option<DuplexRefusal>,
437 answer_by: Answerer,
438 _place: CallPlace,
439}
440
441impl DuplexCall {
442 pub fn call(&self) -> CallRef {
444 self.at
445 }
446
447 pub fn answer_by(&self) -> &Answerer {
449 &self.answer_by
450 }
451
452 pub fn closed(&self) -> Option<&DuplexRefusal> {
454 self.closed.as_ref()
455 }
456
457 pub fn grant_credit(&mut self, n: u64) {
459 self.credit.grant(n);
460 }
461
462 pub fn credit_line(&self) -> CreditLine {
465 self.credit.clone()
466 }
467
468 fn refuse(&self, why: DuplexRefusal) -> DuplexRefusal {
469 self.dg.audited(self.at, self.caller.as_deref(), &self.grant, why)
470 }
471
472 fn close(&mut self, why: DuplexRefusal) -> DuplexRefusal {
473 let why = self.refuse(why);
474 self.closed = Some(why.clone());
475 why
476 }
477
478 pub fn reverify(&mut self) -> Result<(), DuplexRefusal> {
480 let now = self.dg.gate.generation().current();
481 let asked = if !self.recheck {
482 Ok(())
483 } else if self.targets.is_empty() {
484 self.dg.check(self.caller.as_deref(), &self.grant, None)
485 } else {
486 self.targets.iter().try_for_each(|t| self.dg.check(self.caller.as_deref(), &self.grant, Some(t)))
487 };
488 match asked {
489 Ok(()) => {
490 self.seen = now;
491 Ok(())
492 }
493 Err(e) => Err(self.close(e)),
494 }
495 }
496
497 pub fn expire(&mut self) -> DuplexRefusal {
501 self.close(DuplexRefusal::Gate(PlexusError::Unauthenticated("your sign-in has expired: sign in again".into())))
502 }
503
504 pub fn admit<I>(&mut self, f: &InputFrame<I>) -> Result<(), DuplexRefusal> {
506 if self.closed.is_some() {
507 return Err(self.refuse(DuplexRefusal::InputClosed));
508 }
509 if f.from != self.conn {
510 return Err(self.refuse(DuplexRefusal::NotThisCall));
511 }
512 if self.dg.gate.generation().current() != self.seen {
513 self.reverify()?;
514 }
515 let credit = self.credit.granted();
516 match f.overrun {
517 None => {}
518 Some(Overrun::Credit) => return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit })),
519 Some(Overrun::Sequence { expected }) => return Err(self.close(DuplexRefusal::OutOfSequence { seq: f.seq, expected })),
520 Some(Overrun::Empty) => return Err(self.close(DuplexRefusal::InvalidInput { seq: f.seq, message: "an input frame with no items".into() })),
521 }
522 if f.items == 0 {
523 return Err(self.close(DuplexRefusal::InvalidInput { seq: f.seq, message: "an input frame with no items".into() }));
524 }
525 if self.items.saturating_add(f.items) > credit {
526 return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit }));
527 }
528 if self.items.saturating_add(f.items) > self.ceiling.max_items {
529 return Err(self.close(DuplexRefusal::TooMuchInput { limit: "items", max: self.ceiling.max_items }));
530 }
531 if self.bytes.saturating_add(f.bytes) > self.ceiling.max_bytes {
532 return Err(self.close(DuplexRefusal::TooMuchInput { limit: "bytes", max: self.ceiling.max_bytes }));
533 }
534 self.items = self.items.saturating_add(f.items);
535 self.bytes = self.bytes.saturating_add(f.bytes);
536 Ok(())
537 }
538
539 pub fn answer(&self, from: ConnId, who: Option<&AuthContext>) -> Result<(), DuplexRefusal> {
542 let refused = |why| Err(self.dg.audited(self.at, who, &self.grant, why));
543 if self.closed.is_some() {
544 return refused(DuplexRefusal::InputClosed);
545 }
546 match &self.answer_by {
547 Answerer::Caller if from == self.conn => Ok(()),
548 Answerer::Person if from == self.conn => match who {
549 Some(w) if is_person(w) => Ok(()),
550 _ => refused(DuplexRefusal::PersonRequired),
551 },
552 Answerer::Caller | Answerer::Person => refused(DuplexRefusal::NotThisCall),
553 Answerer::Grant(g) => match self.dg.check(who, &Grant::new(g.clone()), self.targets.first().map(String::as_str)) {
554 Ok(()) => Ok(()),
555 Err(e) => refused(e),
556 },
557 }
558 }
559
560 pub fn input<S, I>(mut self, frames: S, refused: mpsc::UnboundedSender<(ConnId, Value)>) -> impl Stream<Item = Result<I, DuplexRefusal>> + Send + 'static
566 where
567 S: Stream<Item = InputFrame<I>> + Send + 'static,
568 I: Send + 'static,
569 {
570 let ns = self.grant.as_str().split('.').next().unwrap_or("").to_string();
571 let expires = self
572 .caller
573 .as_ref()
574 .and_then(|c| c.metadata.get(plexus_auth_core::auth::EXPIRES_AT_KEY))
575 .and_then(Value::as_i64);
576 let now = (self.dg.clock)();
577 async_stream::stream! {
578 let frames = frames;
579 futures::pin_mut!(frames);
580 let expiry = async move {
581 match expires {
582 Some(at) => {
583 let secs = at.saturating_sub(now).max(0) as u64;
584 tokio::time::sleep(std::time::Duration::from_secs(secs)).await
585 }
586 None => std::future::pending().await,
587 }
588 };
589 futures::pin_mut!(expiry);
590 loop {
591 tokio::select! {
592 biased;
593 moved = self.moves.changed() => {
594 if moved.is_err() || self.dg.gate.generation().current() == self.seen { continue; }
597 if let Err(e) = self.reverify() { yield Err(e); break; }
598 }
599 () = &mut expiry => {
600 yield Err(self.expire());
601 break;
602 }
603 f = frames.next() => match f {
604 None => break,
605 Some(f) => match self.admit(&f) {
606 Ok(()) => yield Ok(f.item),
607 Err(e) if !e.ends_input() => { let _ = refused.send((f.from, e.to_item(&ns))); }
608 Err(e) => { yield Err(e); break; }
609 },
610 },
611 }
612 }
613 }
614 }
615}