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 recheck(&self, reach: &plexus_auth_core::grants::Reach, targets: &[String]) -> Result<(), DuplexRefusal> {
328 self.checks.fetch_add(1, Ordering::Relaxed);
329 super::held::redecide(&self.gate, reach, targets).map_err(|r| DuplexRefusal::Gate(r.into()))
330 }
331
332 fn audited(&self, call: CallRef, who: Option<&AuthContext>, grant: &Grant, why: DuplexRefusal) -> DuplexRefusal {
334 if let Some(q) = &self.audit {
335 q.offer(AuditRecord::duplex_refused(call, why.code(), who, grant.as_str()));
336 }
337 why
338 }
339
340 #[allow(clippy::too_many_arguments)]
344 pub fn open(
345 &self,
346 at: impl Into<CallRef>,
347 calls: &dyn CallCounter,
348 caller: Option<Arc<AuthContext>>,
349 grant: &str,
350 target: Option<&str>,
351 ceiling: CallCeiling,
352 answer_by: Answerer,
353 ) -> Result<DuplexCall, DuplexRefusal> {
354 let at = at.into();
355 let mut moves = self.gate.generation().subscribe();
357 let seen = *moves.borrow_and_update();
358 let grant = Grant::new(grant);
359 if let Err(e) = self.check(caller.as_deref(), &grant, target) {
360 return Err(self.audited(at, caller.as_deref(), &grant, e));
361 }
362 let targets = target.map(str::to_string).into_iter().collect();
363 self.opened(at, calls, caller, grant, targets, seen, moves, true, ceiling, answer_by)
364 }
365
366 #[allow(clippy::too_many_arguments)]
374 pub fn admitted(
375 &self,
376 at: impl Into<CallRef>,
377 calls: &dyn CallCounter,
378 caller: Option<Arc<AuthContext>>,
379 grant: &str,
380 targets: Vec<String>,
381 seen: u64,
382 recheck: bool,
383 ceiling: CallCeiling,
384 answer_by: Answerer,
385 ) -> Result<DuplexCall, DuplexRefusal> {
386 let mut moves = self.gate.generation().subscribe();
387 moves.mark_changed();
388 let grant = Grant::new(grant);
389 let ctx = crate::call::context().ok();
394 let decided = ctx.as_ref().and_then(|c| c.reach().cloned()).filter(|r| r.grant() == Some(&grant));
395 let mut call = self.opened(at.into(), calls, caller, grant, targets, seen, moves, recheck, ceiling, answer_by)?;
401 call.decided = decided;
402 Ok(call)
403 }
404
405 #[allow(clippy::too_many_arguments)]
406 fn opened(
407 &self,
408 at: CallRef,
409 calls: &dyn CallCounter,
410 caller: Option<Arc<AuthContext>>,
411 grant: Grant,
412 targets: Vec<String>,
413 seen: u64,
414 moves: watch::Receiver<u64>,
415 recheck: bool,
416 ceiling: CallCeiling,
417 answer_by: Answerer,
418 ) -> Result<DuplexCall, DuplexRefusal> {
419 let place = match calls.take_place() {
420 Ok(p) => p,
421 Err(max) => return Err(self.audited(at, caller.as_deref(), &grant, DuplexRefusal::TooManyCalls { max })),
422 };
423 Ok(DuplexCall {
424 dg: self.clone(),
425 conn: ConnId(at.conn),
426 at,
427 caller,
428 grant,
429 targets,
430 recheck,
431 seen,
432 moves,
433 ceiling,
434 credit: CreditLine(Arc::new(AtomicU64::new(ceiling.credit))),
435 items: 0,
436 bytes: 0,
437 closed: None,
438 answer_by,
439 decided: None,
440 _place: place,
441 })
442 }
443}
444
445pub struct DuplexCall {
447 dg: DuplexGate,
448 conn: ConnId,
449 at: CallRef,
450 caller: Option<Arc<AuthContext>>,
451 grant: Grant,
452 targets: Vec<String>,
453 recheck: bool,
454 seen: u64,
455 moves: watch::Receiver<u64>,
456 ceiling: CallCeiling,
457 credit: CreditLine,
458 items: u64,
459 bytes: u64,
460 closed: Option<DuplexRefusal>,
461 answer_by: Answerer,
462 decided: Option<plexus_auth_core::grants::Reach>,
465 _place: CallPlace,
466}
467
468impl DuplexCall {
469 pub fn call(&self) -> CallRef {
471 self.at
472 }
473
474 pub fn answer_by(&self) -> &Answerer {
476 &self.answer_by
477 }
478
479 pub fn closed(&self) -> Option<&DuplexRefusal> {
481 self.closed.as_ref()
482 }
483
484 pub fn grant_credit(&mut self, n: u64) {
486 self.credit.grant(n);
487 }
488
489 pub fn credit_line(&self) -> CreditLine {
492 self.credit.clone()
493 }
494
495 fn refuse(&self, why: DuplexRefusal) -> DuplexRefusal {
496 self.dg.audited(self.at, self.caller.as_deref(), &self.grant, why)
497 }
498
499 fn close(&mut self, why: DuplexRefusal) -> DuplexRefusal {
500 let why = self.refuse(why);
501 self.closed = Some(why.clone());
502 why
503 }
504
505 pub fn reverify(&mut self) -> Result<(), DuplexRefusal> {
507 let now = self.dg.gate.generation().current();
508 let asked = if !self.recheck {
509 Ok(())
510 } else if let Some(reach) = &self.decided {
511 self.dg.recheck(reach, &self.targets)
512 } else if self.targets.is_empty() {
513 self.dg.check(self.caller.as_deref(), &self.grant, None)
514 } else {
515 self.targets.iter().try_for_each(|t| self.dg.check(self.caller.as_deref(), &self.grant, Some(t)))
516 };
517 match asked {
518 Ok(()) => {
519 self.seen = now;
520 Ok(())
521 }
522 Err(e) => Err(self.close(e)),
523 }
524 }
525
526 pub fn expire(&mut self) -> DuplexRefusal {
530 self.close(DuplexRefusal::Gate(PlexusError::Unauthenticated("your sign-in has expired: sign in again".into())))
531 }
532
533 pub fn admit<I>(&mut self, f: &InputFrame<I>) -> Result<(), DuplexRefusal> {
535 if self.closed.is_some() {
536 return Err(self.refuse(DuplexRefusal::InputClosed));
537 }
538 if f.from != self.conn {
539 return Err(self.refuse(DuplexRefusal::NotThisCall));
540 }
541 if self.dg.gate.generation().current() != self.seen {
542 self.reverify()?;
543 }
544 let credit = self.credit.granted();
545 match f.overrun {
546 None => {}
547 Some(Overrun::Credit) => return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit })),
548 Some(Overrun::Sequence { expected }) => return Err(self.close(DuplexRefusal::OutOfSequence { seq: f.seq, expected })),
549 Some(Overrun::Empty) => return Err(self.close(DuplexRefusal::InvalidInput { seq: f.seq, message: "an input frame with no items".into() })),
550 }
551 if f.items == 0 {
552 return Err(self.close(DuplexRefusal::InvalidInput { seq: f.seq, message: "an input frame with no items".into() }));
553 }
554 if self.items.saturating_add(f.items) > credit {
555 return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit }));
556 }
557 if self.items.saturating_add(f.items) > self.ceiling.max_items {
558 return Err(self.close(DuplexRefusal::TooMuchInput { limit: "items", max: self.ceiling.max_items }));
559 }
560 if self.bytes.saturating_add(f.bytes) > self.ceiling.max_bytes {
561 return Err(self.close(DuplexRefusal::TooMuchInput { limit: "bytes", max: self.ceiling.max_bytes }));
562 }
563 self.items = self.items.saturating_add(f.items);
564 self.bytes = self.bytes.saturating_add(f.bytes);
565 Ok(())
566 }
567
568 pub fn answer(&self, from: ConnId, who: Option<&AuthContext>) -> Result<(), DuplexRefusal> {
571 let refused = |why| Err(self.dg.audited(self.at, who, &self.grant, why));
572 if self.closed.is_some() {
573 return refused(DuplexRefusal::InputClosed);
574 }
575 match &self.answer_by {
576 Answerer::Caller if from == self.conn => Ok(()),
577 Answerer::Person if from == self.conn => match who {
578 Some(w) if is_person(w) => Ok(()),
579 _ => refused(DuplexRefusal::PersonRequired),
580 },
581 Answerer::Caller | Answerer::Person => refused(DuplexRefusal::NotThisCall),
582 Answerer::Grant(g) => match self.dg.check(who, &Grant::new(g.clone()), self.targets.first().map(String::as_str)) {
583 Ok(()) => Ok(()),
584 Err(e) => refused(e),
585 },
586 }
587 }
588
589 pub fn input<S, I>(mut self, frames: S, refused: mpsc::UnboundedSender<(ConnId, Value)>) -> impl Stream<Item = Result<I, DuplexRefusal>> + Send + 'static
595 where
596 S: Stream<Item = InputFrame<I>> + Send + 'static,
597 I: Send + 'static,
598 {
599 let ns = self.grant.as_str().split('.').next().unwrap_or("").to_string();
600 let expires = self
601 .caller
602 .as_ref()
603 .and_then(|c| c.metadata.get(plexus_auth_core::auth::EXPIRES_AT_KEY))
604 .and_then(Value::as_i64);
605 let now = (self.dg.clock)();
606 async_stream::stream! {
607 let frames = frames;
608 futures::pin_mut!(frames);
609 let expiry = async move {
610 match expires {
611 Some(at) => {
612 let secs = at.saturating_sub(now).max(0) as u64;
613 crate::rt::sleep(std::time::Duration::from_secs(secs)).await
614 }
615 None => std::future::pending().await,
616 }
617 };
618 futures::pin_mut!(expiry);
619 loop {
620 tokio::select! {
621 biased;
622 moved = self.moves.changed() => {
623 if moved.is_err() || self.dg.gate.generation().current() == self.seen { continue; }
626 if let Err(e) = self.reverify() { yield Err(e); break; }
627 }
628 () = &mut expiry => {
629 yield Err(self.expire());
630 break;
631 }
632 f = frames.next() => match f {
633 None => break,
634 Some(f) => match self.admit(&f) {
635 Ok(()) => yield Ok(f.item),
636 Err(e) if !e.ends_input() => { let _ = refused.send((f.from, e.to_item(&ns))); }
637 Err(e) => { yield Err(e); break; }
638 },
639 },
640 }
641 }
642 }
643 }
644}