Skip to main content

plexus_auth_core/
duplex.rs

1//! BIDIR-5 / BIDIR-8 — the gate's rules for a duplex call, in this crate's terms.
2//!
3//! A duplex call is params, then an input half and an output half
4//! (BIDIR-1). The gate decides it at open exactly as it decides any call
5//! ([`Gate::check`](crate::grants::Gate::check): the method's grant on its
6//! target, within the ceiling). What this module adds is what a duplex call
7//! needs beyond that, each as data a method or a service declares — no rule is
8//! written in an application:
9//!
10//! | when | the gate does | in these terms |
11//! |---|---|---|
12//! | the call opens | [`Gate::check`](crate::grants::Gate::check), once; the call holds the caller and the [`Reach`](crate::grants::Reach) | a grant |
13//! | an input frame arrives | no gate check: the frame's connection is the call's, the half is open, the grants generation is the one last verified, the frame is within credit and the [`CallCeiling`] | [`InputBy::Caller`], [`CallCeiling`] |
14//! | the grants generation moves, a sign-out, the expiry | the caller verified again, once per call; a refusal closes the input half with `forbidden` / `unauthenticated` | a grant |
15//! | a question is answered | [`Answerer`]: the caller's own connection; a person; or whoever holds a grant on the call's target | [`Answerer`] |
16//! | a call goes into a client or a service that dialed in | that peer's own gate, deciding for the principal on that connection — the other side of the call is a caller like any other | a grant on the peer |
17//! | a call crosses a hop | [`hop_identity`]: the hop is the principal, the caller is named `for` and grants nothing, the hop's verdict is a ceiling layer; the far side decides again | a ceiling |
18
19use serde::{Deserialize, Serialize};
20use serde_json::{json, Map, Value};
21
22use crate::auth::{AuthContext, PRINCIPAL_CLAIM};
23use crate::grants::{ScopeRef, CEILING_KEY};
24use crate::identity::Issuer;
25
26/// Who may send a call's input items. Only the caller, on the call's own
27/// connection: an input item carries no target of its own, so there is
28/// nothing another principal could be checked against. (A wider sender is
29/// a second call, gated as one.)
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
31pub enum InputBy {
32    /// The connection that opened the call (`#[method(input_by = "caller")]`,
33    /// the default and only form).
34    #[default]
35    Caller,
36}
37
38/// Who may answer a question a method asks mid-call — an output item that
39/// expects a reply (BIDIR-1 `mechanism`). The method declares it
40/// (`#[method(answer_by = "…")]`, BIDIR-1 `answerer`).
41#[derive(Debug, Clone, PartialEq, Eq, Default)]
42pub enum Answerer {
43    /// `caller` (default): the call's own connection, as the call's
44    /// principal — whatever kind it is.
45    #[default]
46    Caller,
47    /// `person`: the call's own connection, and its principal a person
48    /// ([`is_person`]); an agent's answer is refused `person_required`.
49    Person,
50    /// `grant:<g>`: any connection whose principal holds grant `g` on the
51    /// call's target (asked of the gate once, per answer) — the owner
52    /// approving a step an agent's call asks.
53    Grant(String),
54}
55
56/// BIDIR-8: the spellings `#[method(answer_by = "…")]` takes, for a
57/// refusal to name (the macro's compile error says the same three).
58pub const ANSWER_BY_SPELLINGS: &str = "`caller` (the default), `person`, or `grant:<activation.method>`";
59
60impl Answerer {
61    /// BIDIR-8: the declaration as written (`MethodSchema.answer_by`):
62    /// `None` for the default, so a method without one is unchanged.
63    pub fn declared(&self) -> Option<String> {
64        match self {
65            Self::Caller => None,
66            Self::Person => Some("person".into()),
67            Self::Grant(g) => Some(format!("grant:{g}")),
68        }
69    }
70
71    /// BIDIR-8: the answerer a schema names (`MethodSchema.answer_by`;
72    /// absent is the default). A spelling the macro would have refused is
73    /// an error, never a wider answerer.
74    pub fn of_schema(answer_by: Option<&str>) -> Result<Self, String> {
75        answer_by.map_or(Ok(Self::Caller), Self::parse)
76    }
77
78    /// Read a declaration: `caller`, `person` or `grant:<dotted.grant>`.
79    pub fn parse(text: &str) -> Result<Self, String> {
80        match text.trim() {
81            "caller" => Ok(Self::Caller),
82            "person" => Ok(Self::Person),
83            t => match t.strip_prefix("grant:") {
84                Some(g) if g.contains('.') && !g.contains(char::is_whitespace) => Ok(Self::Grant(g.to_string())),
85                _ => Err(format!("answer_by `{t}`: one of {ANSWER_BY_SPELLINGS}")),
86            },
87        }
88    }
89}
90
91/// A person, as the identity's issuer vouches: a sign-in through plexus-idp
92/// or an OIDC provider. A key, an API key or a nostr key is not (a nostr key
93/// may be a person's, but nothing vouches it — AUTH-35 grades that).
94pub fn is_person(ctx: &AuthContext) -> bool {
95    ctx.principal().is_some_and(|p| matches!(p.issuer(), Issuer::Idp | Issuer::Oidc))
96}
97
98/// The credit a method grants unless it says otherwise
99/// (`#[method(input_window = N)]`, BIDIR-6).
100pub const DEFAULT_INPUT_WINDOW: u64 = 64;
101
102/// The bytes one call may hold buffered unless it says otherwise
103/// (`#[method(input_max_buffered = N)]`, BIDIR-6).
104pub const DEFAULT_MAX_BUFFERED: u64 = 64 * 1024 * 1024;
105
106/// What one call may take in (BIDIR-1: "every item that flows has a limit").
107/// Beside the transport's per-connection call count, which counts a duplex
108/// call as one call.
109///
110/// BIDIR-6, the owner's decision: nothing limits what has *passed through* a
111/// call unless its method opts in (64 MiB is 56 minutes of 16 kHz PCM). What a
112/// call costs is what it holds, so what is bounded is what it holds: `credit`
113/// items, and past `max_buffered` bytes no more credit until the handler
114/// drains below it. An obedient client is slowed, never ended (owner,
115/// 2026-11-02).
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub struct CallCeiling {
118    /// Credit granted with the call's answer: items the caller may send
119    /// before the callee grants more, and so the items it can hold. The
120    /// callee's window, not a policy: it moves as the handler consumes.
121    pub credit: u64,
122    /// Input items over the call's life. `u64::MAX` (the default): no limit.
123    pub max_items: u64,
124    /// Input bytes over the call's life (each item as its JSON). `u64::MAX`
125    /// (the default): no limit.
126    pub max_bytes: u64,
127    /// Input bytes held at once (received and not yet consumed) past which
128    /// the callee grants no credit until it drains below them. Not a refusal:
129    /// a client within its credit may still land up to a window's items.
130    pub max_buffered: u64,
131}
132
133impl Default for CallCeiling {
134    fn default() -> Self {
135        Self { credit: DEFAULT_INPUT_WINDOW, max_items: u64::MAX, max_bytes: u64::MAX, max_buffered: DEFAULT_MAX_BUFFERED }
136    }
137}
138
139/// BIDIR-8: which call a refusal was about — the connection it runs on and
140/// its subscription there (the slot BIDIR-6 keys a duplex call by).
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
142pub struct CallRef {
143    /// The connection, as the transport numbers it.
144    pub conn: u64,
145    /// The call's subscription on that connection.
146    pub subscription: u64,
147}
148
149/// BIDIR-8: every typed refusal the gate makes over a duplex call — its
150/// `error_kind` on the wire, and the `reason` of its audit record
151/// ([`AuditRecordKind::DuplexRefused`](crate::audit::AuditRecordKind::DuplexRefused)).
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
153#[serde(rename_all = "snake_case")]
154pub enum DuplexRefusalCode {
155    /// The grant gate refused: at open, at a re-verify, or an answer by grant.
156    Forbidden,
157    /// No one proved, a sign-in ended (signed out, revoked) or expired.
158    Unauthenticated,
159    /// The connection's calls are all open (`too_many_calls {max}`).
160    TooManyCalls,
161    /// A frame or an answer from a connection that is not the call's.
162    NotThisCall,
163    /// An input item past the credit granted (`past_credit {seq, credit}`).
164    PastCredit,
165    /// Past the ceiling a method opted into (`too_much_input {limit, max}`,
166    /// `limit` `items` or `bytes`).
167    TooMuchInput,
168    /// A question that needs a person's answer, answered by an agent.
169    PersonRequired,
170    /// A frame or an answer after the input half closed.
171    InputClosed,
172    /// A frame out of sequence on a socket, which delivers in order: a broken
173    /// client (`out_of_sequence {seq, expected}`).
174    OutOfSequence,
175    /// An input item that does not decode as the method's type
176    /// (`invalid_input {seq}`).
177    InvalidInput,
178}
179
180impl DuplexRefusalCode {
181    /// The `error_kind` it goes on the wire as.
182    pub fn as_str(&self) -> &'static str {
183        match self {
184            Self::Forbidden => "forbidden",
185            Self::Unauthenticated => "unauthenticated",
186            Self::TooManyCalls => "too_many_calls",
187            Self::NotThisCall => "not_this_call",
188            Self::PastCredit => "past_credit",
189            Self::TooMuchInput => "too_much_input",
190            Self::PersonRequired => "person_required",
191            Self::InputClosed => "input_closed",
192            Self::OutOfSequence => "out_of_sequence",
193            Self::InvalidInput => "invalid_input",
194        }
195    }
196}
197
198/// The metadata key naming whom a hop acts for (IDENTITY-2's `for`;
199/// RFC 8693's actor chain, read the other way): a list, nearest caller
200/// first. It is attribution only — it grants nothing.
201pub const FOR_KEY: &str = "for";
202
203/// BIDIR-1 `forward` = identity: the context a call carries across a hop.
204///
205/// - the principal is the **hop** (`hop`: the calling service's own identity on
206///   the far side — its key, its session there);
207/// - the caller is named under [`FOR_KEY`] (its principal, then whomever it
208///   was itself acting for) and grants nothing;
209/// - the hop's own ceilings and the caller's are kept, and the hop's **verdict** — the scopes
210///   it admitted the caller on — is one more ceiling layer
211///   (`admin@<scope>` each: any grant, only there), so the far side can
212///   only narrow: the smaller of the two;
213/// - nothing of the caller's credential crosses: not its session id, not
214///   its metadata (tokens, session keys, proofs, its own ceilings).
215///
216/// The far side decides again, with its own gate, for the hop.
217pub fn hop_identity(hop: &AuthContext, caller: &AuthContext, verdict: &[ScopeRef]) -> AuthContext {
218    let mut meta = Map::new();
219    for key in [PRINCIPAL_CLAIM, crate::auth::EXPIRES_AT_KEY] {
220        if let Some(v) = hop.metadata.get(key) {
221            meta.insert(key.into(), v.clone());
222        }
223    }
224    let mut chain = vec![Value::String(caller.principal().map(|p| p.to_string()).unwrap_or_else(|| "anonymous".into()))];
225    if let Some(Value::Array(earlier)) = caller.metadata.get(FOR_KEY) {
226        chain.extend(earlier.iter().cloned());
227    }
228    meta.insert(FOR_KEY.into(), Value::Array(chain));
229    // Ceilings are bounds, not credentials: the hop's own and the caller's
230    // (one it carried across an earlier hop included) both stay, so a chain
231    // only ever narrows. One that cannot be read is kept as written, and
232    // the far side's gate refuses it, never widens it.
233    let layers_of = |ctx: &AuthContext| -> Vec<Value> {
234        match ctx.metadata.get(CEILING_KEY) {
235            Some(Value::Array(items)) if items.iter().all(Value::is_string) => vec![Value::Array(items.clone())],
236            Some(Value::Array(items)) => items.clone(),
237            Some(other) => vec![other.clone()],
238            None => Vec::new(),
239        }
240    };
241    let mut layers = layers_of(hop);
242    layers.extend(layers_of(caller));
243    layers.push(Value::Array(verdict.iter().map(|s| json!(format!("{}@{s}", crate::grants::ADMIN))).collect()));
244    meta.insert(CEILING_KEY.into(), Value::Array(layers));
245    AuthContext::new(hop.user_id.clone(), hop.session_id.clone(), hop.roles.clone(), Value::Object(meta))
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    /// BIDIR-6: nothing ends a call for what has passed through it unless
253    /// its method opted in; what it holds is what is bounded.
254    #[test]
255    fn a_call_has_no_lifetime_ceiling_by_default() {
256        let c = CallCeiling::default();
257        assert_eq!((c.max_items, c.max_bytes), (u64::MAX, u64::MAX));
258        assert_eq!((c.credit, c.max_buffered), (DEFAULT_INPUT_WINDOW, DEFAULT_MAX_BUFFERED));
259    }
260
261    #[test]
262    fn answerer_reads_its_declaration() {
263        assert_eq!(Answerer::parse("caller"), Ok(Answerer::Caller));
264        assert_eq!(Answerer::parse(" person "), Ok(Answerer::Person));
265        assert_eq!(Answerer::parse("grant:runs.approve"), Ok(Answerer::Grant("runs.approve".into())));
266        assert!(Answerer::parse("grant:approve").is_err());
267        assert!(Answerer::parse("anyone").is_err());
268        assert_eq!(Answerer::default(), Answerer::Caller);
269        // BIDIR-8: the schema's spelling round-trips; the default is absent.
270        for a in [Answerer::Caller, Answerer::Person, Answerer::Grant("runs.approve".into())] {
271            assert_eq!(Answerer::of_schema(a.declared().as_deref()), Ok(a.clone()));
272        }
273        assert_eq!(Answerer::Caller.declared(), None);
274        assert!(Answerer::of_schema(Some("anyone")).unwrap_err().contains("`person`"));
275    }
276}