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/// How much one call may take in (BIDIR-1: "every item that flows has a
99/// limit"). Beside the transport's per-connection call count, which counts a
100/// duplex call as one call.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct CallCeiling {
103    /// Credit granted with the call's answer: items the caller may send
104    /// before the callee grants more.
105    pub credit: u64,
106    /// Input items over the call's life.
107    pub max_items: u64,
108    /// Input bytes over the call's life (each item as its JSON).
109    pub max_bytes: u64,
110}
111
112impl Default for CallCeiling {
113    fn default() -> Self {
114        Self { credit: 64, max_items: 1_000_000, max_bytes: 64 * 1024 * 1024 }
115    }
116}
117
118/// BIDIR-8: which call a refusal was about — the connection it runs on and
119/// its subscription there (the slot BIDIR-6 keys a duplex call by).
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
121pub struct CallRef {
122    /// The connection, as the transport numbers it.
123    pub conn: u64,
124    /// The call's subscription on that connection.
125    pub subscription: u64,
126}
127
128/// BIDIR-8: every typed refusal the gate makes over a duplex call — its
129/// `error_kind` on the wire, and the `reason` of its audit record
130/// ([`AuditRecordKind::DuplexRefused`](crate::audit::AuditRecordKind::DuplexRefused)).
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
132#[serde(rename_all = "snake_case")]
133pub enum DuplexRefusalCode {
134    /// The grant gate refused: at open, at a re-verify, or an answer by grant.
135    Forbidden,
136    /// No one proved, a sign-in ended (signed out, revoked) or expired.
137    Unauthenticated,
138    /// The connection's calls are all open (`too_many_calls {max}`).
139    TooManyCalls,
140    /// A frame or an answer from a connection that is not the call's.
141    NotThisCall,
142    /// An input item past the credit granted (`past_credit {seq, credit}`).
143    PastCredit,
144    /// Past the call's ceiling of items or bytes (`too_much_input {limit, max}`).
145    TooMuchInput,
146    /// A question that needs a person's answer, answered by an agent.
147    PersonRequired,
148    /// A frame or an answer after the input half closed.
149    InputClosed,
150}
151
152impl DuplexRefusalCode {
153    /// The `error_kind` it goes on the wire as.
154    pub fn as_str(&self) -> &'static str {
155        match self {
156            Self::Forbidden => "forbidden",
157            Self::Unauthenticated => "unauthenticated",
158            Self::TooManyCalls => "too_many_calls",
159            Self::NotThisCall => "not_this_call",
160            Self::PastCredit => "past_credit",
161            Self::TooMuchInput => "too_much_input",
162            Self::PersonRequired => "person_required",
163            Self::InputClosed => "input_closed",
164        }
165    }
166}
167
168/// The metadata key naming whom a hop acts for (IDENTITY-2's `for`;
169/// RFC 8693's actor chain, read the other way): a list, nearest caller
170/// first. It is attribution only — it grants nothing.
171pub const FOR_KEY: &str = "for";
172
173/// BIDIR-1 `forward` = identity: the context a call carries across a hop.
174///
175/// - the principal is the **hop** (`hop`: the calling service's own identity on
176///   the far side — its key, its session there);
177/// - the caller is named under [`FOR_KEY`] (its principal, then whomever it
178///   was itself acting for) and grants nothing;
179/// - the hop's own ceilings and the caller's are kept, and the hop's **verdict** — the scopes
180///   it admitted the caller on — is one more ceiling layer
181///   (`admin@<scope>` each: any grant, only there), so the far side can
182///   only narrow: the smaller of the two;
183/// - nothing of the caller's credential crosses: not its session id, not
184///   its metadata (tokens, session keys, proofs, its own ceilings).
185///
186/// The far side decides again, with its own gate, for the hop.
187pub fn hop_identity(hop: &AuthContext, caller: &AuthContext, verdict: &[ScopeRef]) -> AuthContext {
188    let mut meta = Map::new();
189    for key in [PRINCIPAL_CLAIM, crate::auth::EXPIRES_AT_KEY] {
190        if let Some(v) = hop.metadata.get(key) {
191            meta.insert(key.into(), v.clone());
192        }
193    }
194    let mut chain = vec![Value::String(caller.principal().map(|p| p.to_string()).unwrap_or_else(|| "anonymous".into()))];
195    if let Some(Value::Array(earlier)) = caller.metadata.get(FOR_KEY) {
196        chain.extend(earlier.iter().cloned());
197    }
198    meta.insert(FOR_KEY.into(), Value::Array(chain));
199    // Ceilings are bounds, not credentials: the hop's own and the caller's
200    // (one it carried across an earlier hop included) both stay, so a chain
201    // only ever narrows. One that cannot be read is kept as written, and
202    // the far side's gate refuses it, never widens it.
203    let layers_of = |ctx: &AuthContext| -> Vec<Value> {
204        match ctx.metadata.get(CEILING_KEY) {
205            Some(Value::Array(items)) if items.iter().all(Value::is_string) => vec![Value::Array(items.clone())],
206            Some(Value::Array(items)) => items.clone(),
207            Some(other) => vec![other.clone()],
208            None => Vec::new(),
209        }
210    };
211    let mut layers = layers_of(hop);
212    layers.extend(layers_of(caller));
213    layers.push(Value::Array(verdict.iter().map(|s| json!(format!("{}@{s}", crate::grants::ADMIN))).collect()));
214    meta.insert(CEILING_KEY.into(), Value::Array(layers));
215    AuthContext::new(hop.user_id.clone(), hop.session_id.clone(), hop.roles.clone(), Value::Object(meta))
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn answerer_reads_its_declaration() {
224        assert_eq!(Answerer::parse("caller"), Ok(Answerer::Caller));
225        assert_eq!(Answerer::parse(" person "), Ok(Answerer::Person));
226        assert_eq!(Answerer::parse("grant:runs.approve"), Ok(Answerer::Grant("runs.approve".into())));
227        assert!(Answerer::parse("grant:approve").is_err());
228        assert!(Answerer::parse("anyone").is_err());
229        assert_eq!(Answerer::default(), Answerer::Caller);
230        // BIDIR-8: the schema's spelling round-trips; the default is absent.
231        for a in [Answerer::Caller, Answerer::Person, Answerer::Grant("runs.approve".into())] {
232            assert_eq!(Answerer::of_schema(a.declared().as_deref()), Ok(a.clone()));
233        }
234        assert_eq!(Answerer::Caller.declared(), None);
235        assert!(Answerer::of_schema(Some("anyone")).unwrap_err().contains("`person`"));
236    }
237}