Skip to main content

plexus_core/plexus/
duplex_gate.rs

1//! BIDIR-8 (BIDIR-5's rule, made a library) — the gate over a duplex call.
2//!
3//! A duplex call is params, then an input half and an output half
4//! (BIDIR-1). [`DuplexGate::open`] decides it as the grant gate decides any
5//! call — once, the method's grant on its target, within the ceiling — and
6//! takes the call's place on its connection ([`CallCounter`]: in a server,
7//! plexus-transport's `ConnectionCalls`, one per connection, a duplex call
8//! counted as one call). The [`DuplexCall`] it answers holds the caller and
9//! admits each input frame **without asking the gate**:
10//!
11//! | when | the gate does | refusal (`error_kind`) | ends the call? |
12//! |---|---|---|---|
13//! | open | [`Gate::check`] once | `forbidden {grant, scope, roles, held_on}` / `unauthenticated` | never opens |
14//! | open, past the connection's calls | count it as any call | `too_many_calls {max}` | never opens |
15//! | an input frame from another connection | compare connection ids | `not_this_call` (to the sender) | no |
16//! | an input frame past credit | compare `seq` with the credit granted | `past_credit {seq, credit}` | yes |
17//! | an input frame past the call's ceiling | count items and bytes | `too_much_input {limit, max}` | yes |
18//! | the gate's grants generation moves (grant, revoke, role edit, team, sign-out) | [`Gate::check`] once per call | `forbidden` / `unauthenticated` | yes, items after it dropped |
19//! | the sign-in's expiry | the call's own timer: the caller proves no one | `unauthenticated` | yes |
20//! | a question answered | [`Answerer`]: own connection; a person; or a grant on the target ([`Gate::check`] once per answer) | `not_this_call` / `person_required` / `forbidden` | no |
21//!
22//! A frame's admission is: the half is open, the frame is the call's own
23//! connection's, the gate's generation is the one last verified (one atomic
24//! load), the frame is within credit and the ceiling. So a revoke reaches
25//! every open call at the generation's move — [`DuplexCall::input`] selects
26//! on it, so a quiet call ends then too — and no item ever costs a gate
27//! check. The generation is the gate's own ([`Gate::generation`],
28//! plexus-auth-core): every service that keeps a gate keeps one, and moves
29//! it with [`Gate::moved`] wherever it writes a grant.
30//!
31//! Every typed refusal is one audit record
32//! ([`AuditRecordKind::DuplexRefused`](plexus_auth_core::audit::AuditRecordKind::DuplexRefused)),
33//! built only when it happens and offered to a bounded [`AuditQueue`] that
34//! never waits ([`DuplexGate::with_audit`]): an admitted frame allocates
35//! nothing.
36//!
37//! BIDIR-6's call slot, keyed by `(connection, subscription)`, holds the
38//! [`DuplexCall`] and feeds [`DuplexCall::input`] the frames of one
39//! `{ns}.input {subscription, seq, items}` each.
40
41use 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;
47/// The gate's terms for a duplex call (plexus-auth-core), re-exported so a
48/// caller of this module needs no second import.
49pub 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/// A connection, as the transport numbers it.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub struct ConnId(pub u64);
61
62impl From<ConnId> for CallRef {
63    /// A call on `conn` with no subscription named (0) — a test's, or a
64    /// caller that keys calls by connection alone.
65    fn from(conn: ConnId) -> Self {
66        CallRef { conn: conn.0, subscription: 0 }
67    }
68}
69
70/// A call's place on its connection, held for as long as the call is open
71/// and given back when dropped — whatever the counter keeps behind it.
72pub struct CallPlace(#[allow(dead_code)] Box<dyn Send + Sync>);
73
74impl CallPlace {
75    /// A place that gives itself back when `held` is dropped.
76    pub fn new(held: impl Send + Sync + 'static) -> Self {
77        Self(Box::new(held))
78    }
79}
80
81/// The calls open on one connection, as whoever counts them keeps them —
82/// plexus-transport's `ConnectionCalls` in a server (BIDIR-8: the count is
83/// the transport's, so no service writes it). A duplex call is one call.
84pub trait CallCounter: Send + Sync {
85    /// A place for one more call, or the most there may be (`too_many_calls
86    /// {max}`).
87    fn take_place(&self) -> Result<CallPlace, usize>;
88}
89
90/// The wall clock, in unix seconds: when a sign-in expires.
91pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
92
93fn wall_clock() -> i64 {
94    chrono::Utc::now().timestamp()
95}
96
97/// Why the gate refused a duplex call, a frame or an answer — each typed on
98/// the wire as an error item with its `error_kind`.
99#[derive(Debug, Clone)]
100pub enum DuplexRefusal {
101    /// The grant gate's own refusal (`forbidden`, `unauthenticated`).
102    Gate(PlexusError),
103    TooManyCalls { max: usize },
104    NotThisCall,
105    PastCredit { seq: u64, credit: u64 },
106    TooMuchInput { limit: &'static str, max: u64 },
107    PersonRequired,
108    /// The input half is already closed (a frame after the end).
109    InputClosed,
110}
111
112impl DuplexRefusal {
113    /// The `error_kind` it goes on the wire as.
114    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    /// The refusal's code: its audit `reason` (a gate refusal other than
125    /// `unauthenticated` is `forbidden`).
126    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    /// Whether it ends the call's input half (else it refuses one frame or
140    /// one answer to its sender, and the call runs on).
141    pub fn ends_input(&self) -> bool {
142        !matches!(self, Self::NotThisCall | Self::PersonRequired)
143    }
144
145    /// The gate's own refusal, when it is one.
146    pub fn into_plexus(self) -> Option<PlexusError> {
147        match self {
148            Self::Gate(e) => Some(e),
149            _ => None,
150        }
151    }
152
153    /// The error item: a gate refusal exactly as `{ns}.call` sends one;
154    /// the rest `{"type":"error","error_kind":…, <facts>, "message"}`.
155    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/// One input frame as the transport hands it over: which connection sent
174/// it, its `seq`, the item, and its size on the wire.
175#[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    /// A frame whose size is its item's JSON (a transport has the raw
185    /// length already).
186    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/// The gate over duplex calls: a [`Gate`] (and its grants generation, which
193/// says when to ask it again), the audit, and the clock expiry is read by.
194#[derive(Clone)]
195pub struct DuplexGate {
196    gate: Gate,
197    checks: Arc<AtomicU64>,
198    audit: Option<AuditQueue>,
199    clock: Clock,
200}
201
202impl DuplexGate {
203    /// The gate over duplex calls in front of `gate`; re-verifies when
204    /// `gate`'s generation ([`Gate::generation`]) moves.
205    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    /// Every typed refusal to `audit` (one record each, never waiting).
210    pub fn with_audit(mut self, audit: AuditQueue) -> Self {
211        self.audit = Some(audit);
212        self
213    }
214
215    /// When a sign-in expires is read by `clock` (unix seconds; a test's).
216    pub fn with_clock(mut self, clock: Clock) -> Self {
217        self.clock = clock;
218        self
219    }
220
221    /// The grant gate it asks (its [`Gate::generation`], [`Gate::moved`]).
222    pub fn gate(&self) -> &Gate {
223        &self.gate
224    }
225
226    /// How many times the gate has been asked through this one.
227    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    /// The refusal, audited: one record, built here and only here.
237    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    /// Open a duplex call: the gate first (a refusal takes no place), then
245    /// the call's place on its connection. `at` is the call — its
246    /// connection and subscription (a [`ConnId`] alone is subscription 0).
247    #[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        // Subscribe before deciding: a move after the check is a wake.
260        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
290/// One open duplex call, holding its caller (the module docs).
291pub 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    /// Which call this is: its connection and subscription.
311    pub fn call(&self) -> CallRef {
312        self.at
313    }
314
315    /// Who may answer its questions.
316    pub fn answer_by(&self) -> &Answerer {
317        &self.answer_by
318    }
319
320    /// Why its input half closed, once it has.
321    pub fn closed(&self) -> Option<&DuplexRefusal> {
322        self.closed.as_ref()
323    }
324
325    /// The callee grants `n` more items (the `credit { n }` output item).
326    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    /// The caller, verified again (the generation moved): one gate check.
341    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    /// The sign-in's expiry came: the caller proves no one now (the gate
353    /// would say the same — [`Gate::alive`] refuses a context past its
354    /// `expires_at`), so no check is asked. The input half closes.
355    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    /// Admit one input frame — no gate check unless the generation moved.
360    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    /// May `who`, on connection `from`, answer a question this call asked?
385    /// By the method's [`Answerer`]; a refusal is audited as `who`'s.
386    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    /// The handler's input: the frames as they come, each admitted; the
406    /// generation and the sign-in's expiry selected beside them, so a quiet
407    /// call ends at a revoke. A frame from another connection is refused to
408    /// its sender on `refused` and the call runs on; any other refusal is
409    /// the stream's last item, and what follows is never read (dropped).
410    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                        // Already verified at this generation (a frame
439                        // found the move first): nothing to ask again.
440                        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}