Skip to main content

plexus_core/
call.rs

1//! RETURNS-47 · the call's context: who is calling, as the gate admitted
2//! them, how far the call reaches, and the hop it came through.
3//!
4//! A method reaches its caller through the call it runs in, never through
5//! its signature, so a method of a hand-written trait (whose signature is
6//! the same for every implementation) reaches it the same way an inherent
7//! method does:
8//!
9//! ```ignore
10//! #[plexus_macros::activation]
11//! impl forge::Forge for GitHub {
12//!     async fn repos(&self) -> Vec<Repo> {
13//!         let Ok(caller) = plexus_core::call::caller() else { return vec![] };   // fail closed
14//!         self.repos_within(caller.reach()).await
15//!     }
16//! }
17//! ```
18//!
19//! - **Typed and verified.** [`caller()`] answers the [`AuthContext`] the
20//!   service's gate admitted (after AUTH-11's liveness: a sign-in that ended
21//!   is anonymous here, as at the gate) and the [`Reach`] it answered for the
22//!   call. A service's own verifier turns it into its own verified user, as
23//!   `#[from_auth]` does (`VerifiedUser::current(&self.access).await?`).
24//!   Nothing outside this crate builds one: a [`DynamicHub`] sets it as it
25//!   dispatches.
26//! - **Fail closed.** Outside a call there is no caller: [`caller()`],
27//!   [`hop()`] and [`crate::plexus::current_reach`] are errors, never a
28//!   default. A service without a gate dispatches every call with
29//!   [`Reach::everywhere`] — what no gate has always meant — said by the
30//!   dispatch, not assumed by the reader.
31//! - **Through a hop.** In a child service reached through the seam
32//!   ([`crate::plexus::remote_child::serve_child`]), the call's context is
33//!   the hop's (spec/12: the acting service, the caller it acts for, the
34//!   gate's verdict as a ceiling, the call id): [`hop()`] answers it, and
35//!   [`Hop::allows`] bounds a read by it. [`caller()`] there is an error:
36//!   no gate of this process admitted anyone, and the hop is not a
37//!   credential.
38//! - **With the call's stream.** The context goes with the stream the call
39//!   answers: each poll of it runs inside the context ([`InCall`]), so a
40//!   method's stream body reads [`caller()`] as its first line does.
41//! - **Across spawned work, only when handed.** A task the method spawns
42//!   does not inherit the context: it carries it only when handed it
43//!   explicitly, [`scope`]`(`[`context()`]`?, fut)`. Nothing inherits a
44//!   caller by accident.
45//!
46//! `#[plexus_macros::from_auth]` stays for inherent methods: the dispatch
47//! hands it the same identity it puts here.
48//!
49//! [`DynamicHub`]: crate::plexus::DynamicHub
50
51use std::fmt;
52use std::future::Future;
53use std::pin::Pin;
54use std::any::Any;
55use std::sync::{Arc, Mutex, OnceLock};
56use std::task::{Context, Poll};
57
58use futures::Stream;
59use plexus_auth_core::grants::{Gate, Grant, Reach, ScopeRef};
60use serde::{Deserialize, Serialize};
61
62use crate::plexus::{AuthContext, PlexusError};
63
64tokio::task_local! {
65    static CALL: CallContext;
66}
67
68/// The context of one call: the caller as the gate admitted them and the
69/// reach it answered — or, in a child, the hop the call came through.
70/// Cheap to clone. Built only by the dispatch (and the child seam), never by
71/// hand; a method gets it with [`context()`], to hand to work it spawns.
72#[derive(Clone)]
73pub struct CallContext(Arc<Inner>);
74
75struct Inner {
76    auth: Option<AuthContext>,
77    reach: OnceLock<Reach>,
78    /// An introspection call's reach, asked of the gate only if something
79    /// reads it (PERF-15: an introspection answer looks no role up).
80    deferred: Option<(Arc<Gate>, Grant)>,
81    hop: Option<Hop>,
82    /// What a trait-impl method's verifier answered for this call
83    /// (`#[plexus_macros::from_auth(…)]` on the method): [`verified`]. Shared
84    /// by a context narrowed from this one (`with_reach`: the same call);
85    /// another caller's context (`with_auth`, `ungated`) starts its own.
86    verified: Verified,
87    /// NEST-11: in a child, its link back to the service that forwarded the
88    /// call (`remote_child::host`).
89    host: Option<Arc<dyn Any + Send + Sync>>,
90}
91
92type Verified = Arc<Mutex<Option<Arc<dyn Any + Send + Sync>>>>;
93
94impl Inner {
95    fn with(auth: Option<AuthContext>, reach: Option<Reach>, deferred: Option<(Arc<Gate>, Grant)>, hop: Option<Hop>) -> Self {
96        let cell = OnceLock::new();
97        if let Some(r) = reach {
98            let _ = cell.set(r);
99        }
100        Inner { auth, reach: cell, deferred, hop, verified: Verified::default(), host: None }
101    }
102}
103
104impl fmt::Debug for CallContext {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        f.debug_struct("CallContext")
107            .field("principal", &self.0.auth.as_ref().and_then(|a| a.principal()).map(|p| p.to_string()))
108            .field("reach", &self.0.reach.get())
109            .field("hop", &self.0.hop)
110            .finish()
111    }
112}
113
114impl CallContext {
115    /// A call a service's dispatch admitted: `auth` the identity that
116    /// stands (none: anonymous), `reach` what the gate answered — or
117    /// [`Reach::everywhere`] on a service without a gate.
118    pub(crate) fn admitted(auth: Option<&AuthContext>, reach: Reach) -> Self {
119        Self(Arc::new(Inner::with(auth.cloned(), Some(reach), None, None)))
120    }
121
122    /// An introspection call a gated service let through (AUTH-4): its
123    /// reach is the caller's for the path, as the gate answers a public
124    /// method's — asked only when read.
125    pub(crate) fn introspection(auth: Option<&AuthContext>, gate: Arc<Gate>, grant: Grant) -> Self {
126        Self(Arc::new(Inner::with(auth.cloned(), None, Some((gate, grant)), None)))
127    }
128
129    /// A call that came through the child seam (owner, 2026-11-04: children
130    /// receive auth): its caller is the one the hop names — `for`'s far end,
131    /// as an `AuthContext` whose session is the hop's call id; anonymous when
132    /// `for` is empty — and its reach the hop's ceiling (`limit.held_on` for
133    /// `limit.grant`, as a gate of the hop alone answers it), never wider;
134    /// nowhere when no gate decided (`limit: null`) or `for` cannot be read. The hop is
135    /// believed as the transport delivered it (`remote_child::serve_child_on`
136    /// takes it only from a sender it trusts).
137    // PLEXUS-45: the child seam is native-only; on wasm32 nothing takes a hop.
138    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
139    pub(crate) fn through_hop(hop: Hop) -> Self {
140        // `for` names someone this cannot read: anonymous, and no ceiling —
141        // the verdict was for a caller this child cannot name.
142        let unreadable = hop.caller().is_some_and(|p| p.parse::<plexus_auth_core::identity::Principal>().is_err());
143        let auth = hop.caller().and_then(|p| p.parse::<plexus_auth_core::identity::Principal>().ok()).map(|p| {
144            AuthContext::for_principal(&p, format!("hop:{}", hop.call), Vec::new(), serde_json::json!({ "hop_principal": hop.principal }))
145        });
146        let reach = match &hop.limit {
147            Some(l) if !unreadable => ceiling_reach(auth.as_ref(), &l.grant, &hop.held_on()),
148            _ => Reach::nowhere(),
149        };
150        Self(Arc::new(Inner::with(auth, Some(reach), None, Some(hop))))
151    }
152
153    /// NEST-11: [`CallContext::through_hop`], with the link back to the
154    /// service that forwarded the call.
155    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
156    pub(crate) fn through_hop_with(hop: Hop, host: Arc<dyn Any + Send + Sync>) -> Self {
157        let mut ctx = Self::through_hop(hop);
158        if let Some(inner) = Arc::get_mut(&mut ctx.0) {
159            inner.host = Some(host);
160        }
161        ctx
162    }
163
164    /// NEST-11: the link back to the service that forwarded this call, in a
165    /// child.
166    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
167    pub(crate) fn host_link(&self) -> Option<&Arc<dyn Any + Send + Sync>> {
168        self.0.host.as_ref()
169    }
170
171    /// The context of a call routed into an in-process child, under its
172    /// forward policy: `callee` the context the policy derived (none, or
173    /// one no longer signed in, is anonymous); the call's reach kept when
174    /// the policy keeps the caller's identity, nowhere when it does not; the
175    /// hop kept as the caller is (none under `anonymous`); the verified
176    /// value the child's own (another caller).
177    pub(crate) fn for_child(&self, callee: Option<&AuthContext>, keeps_identity: bool) -> Self {
178        let auth = callee.filter(|a| a.is_authenticated()).cloned();
179        // The reach and the hop follow the caller: kept with its identity
180        // (`same_service`, `identity_only`, `pass_through`), none under
181        // `anonymous` — `hop()` there errors, as outside a hop.
182        let (reach, hop) = if keeps_identity {
183            (self.reach().cloned().unwrap_or_else(Reach::nowhere), self.0.hop.clone())
184        } else {
185            (Reach::nowhere(), None)
186        };
187        let mut inner = Inner::with(auth, Some(reach), None, hop);
188        inner.host = self.0.host.clone().filter(|_| keeps_identity);
189        Self(Arc::new(inner))
190    }
191
192    /// This context with its identity replaced: a call routed from inside
193    /// another, through a service with no gate of its own.
194    pub(crate) fn with_auth(&self, auth: Option<&AuthContext>) -> Self {
195        let mut inner = Inner::with(auth.cloned(), self.0.reach.get().cloned(), self.0.deferred.clone(), self.0.hop.clone());
196        inner.host = self.0.host.clone();
197        Self(Arc::new(inner))
198    }
199
200    /// This context with its reach replaced: the same call, so the same
201    /// verified value (the same slot, set once for both).
202    pub(crate) fn with_reach(&self, reach: Reach) -> Self {
203        let mut inner = Inner::with(self.0.auth.clone(), Some(reach), None, self.0.hop.clone());
204        inner.verified = Arc::clone(&self.0.verified);
205        inner.host = self.0.host.clone();
206        Self(Arc::new(inner))
207    }
208
209    /// The identity the gate admitted (in a child, the one the hop names, or
210    /// the one its forward policy derived); `None` for an anonymous call.
211    pub fn auth(&self) -> Option<&AuthContext> {
212        self.0.auth.as_ref()
213    }
214
215    /// The reach the gate answered (in a child through the seam, the hop's
216    /// ceiling).
217    pub fn reach(&self) -> Option<&Reach> {
218        if let Some(reach) = self.0.reach.get() {
219            return Some(reach);
220        }
221        let (gate, grant) = self.0.deferred.as_ref()?;
222        Some(self.0.reach.get_or_init(|| gate.reach_of_public(self.0.auth.as_ref(), grant)))
223    }
224
225    /// The hop the call came through, in a child.
226    pub fn hop(&self) -> Option<&Hop> {
227        self.0.hop.as_ref()
228    }
229
230    /// The caller this context names: an error for a call that came
231    /// through a hop (no gate of this process admitted anyone).
232    pub fn caller(&self) -> Result<Caller, CallError> {
233        match self.reach() {
234            Some(_) => Ok(Caller(self.clone())),
235            None => Err(CallError::ThroughHop),
236        }
237    }
238}
239
240/// The caller of the call being run, as the service's gate admitted them:
241/// [`caller()`].
242#[derive(Clone, Debug)]
243pub struct Caller(CallContext);
244
245impl Caller {
246    /// The identity the gate admitted; `None` for an anonymous caller (a
247    /// `public` method, or a sign-in that has ended).
248    pub fn auth(&self) -> Option<&AuthContext> {
249        self.0.auth()
250    }
251
252    /// The identity, signed in — `Unauthenticated` for an anonymous caller,
253    /// as `#[from_auth]` refuses one.
254    pub fn signed_in(&self) -> Result<&AuthContext, PlexusError> {
255        self.0
256            .auth()
257            .ok_or_else(|| PlexusError::Unauthenticated("This method requires authentication".to_string()))
258    }
259
260    /// What the gate answered for the call: where its grant is held.
261    pub fn reach(&self) -> &Reach {
262        self.0.reach().expect("a caller is made only from a context with a reach")
263    }
264
265    /// The whole context, to hand to work the method spawns ([`scope`]).
266    pub fn context(&self) -> &CallContext {
267        &self.0
268    }
269}
270
271/// Why there is no caller (or no hop) to answer. Fail closed: each is an
272/// error, never a default; as a [`PlexusError`] it is `Unauthenticated`.
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274pub enum CallError {
275    /// Not inside a call: no dispatch set a context here — a task spawned
276    /// without one handed to it ([`scope`]), or code run outside any call.
277    OutsideCall,
278    /// Inside a call that came through a hop: no gate of this process
279    /// admitted a caller; read [`hop()`].
280    ThroughHop,
281    /// Inside a call that did not come through a hop: there is none to read.
282    NoHop,
283    /// Inside a call whose method declared no verifier, or one that answered
284    /// another type than the one asked for.
285    NotVerified,
286    /// The call's verified value is already set: it is set once, by the
287    /// method's verifier, and never replaced.
288    AlreadyVerified,
289}
290
291impl fmt::Display for CallError {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        f.write_str(match self {
294            CallError::OutsideCall => {
295                "no caller: this runs outside a call (a spawned task carries one only when handed it, plexus_core::call::scope)"
296            }
297            CallError::ThroughHop => "no caller admitted here: this call came through a hop (read plexus_core::call::hop)",
298            CallError::NoHop => "no hop: this call did not come through the child seam",
299            CallError::AlreadyVerified => "the call's verified value is set once, by its verifier, and is set",
300            CallError::NotVerified => {
301                "nothing verified: the method declares no `#[plexus_macros::from_auth(…)]` answering this type"
302            }
303        })
304    }
305}
306
307impl std::error::Error for CallError {}
308
309impl From<CallError> for PlexusError {
310    fn from(e: CallError) -> Self {
311        PlexusError::Unauthenticated(e.to_string())
312    }
313}
314
315/// The caller of the call this runs in, as the gate admitted them, with the
316/// reach it answered. An error outside a call, and in a child (read
317/// [`hop()`] there).
318pub fn caller() -> Result<Caller, CallError> {
319    CALL.try_with(CallContext::caller).unwrap_or(Err(CallError::OutsideCall))
320}
321
322/// The hop the call this runs in came through (spec/12), in a child reached
323/// through the seam. An error outside a call, and in a call that did not
324/// come through a hop.
325pub fn hop() -> Result<Hop, CallError> {
326    CALL.try_with(|c| c.hop().cloned().ok_or(CallError::NoHop)).unwrap_or(Err(CallError::OutsideCall))
327}
328
329/// The whole context of the call this runs in — to hand to a task it
330/// spawns, [`scope`]`(context()?, fut)`. An error outside a call.
331pub fn context() -> Result<CallContext, CallError> {
332    CALL.try_with(CallContext::clone).map_err(|_| CallError::OutsideCall)
333}
334
335/// What the method's verifier answered for this call: on `impl Trait for
336/// Type`, `#[plexus_macros::from_auth(self.access.verify)]` on the method
337/// runs the verifier before the body — its error the call's refusal, out of
338/// band and typed, as a `#[from_auth]` parameter's is — and keeps its value
339/// here for the body. An error outside a call, and when the method declared
340/// no verifier of type `T`.
341pub fn verified<T: Clone + Send + Sync + 'static>() -> Result<T, CallError> {
342    let ctx = context()?;
343    let held = ctx.0.verified.lock().unwrap_or_else(|p| p.into_inner()).clone();
344    held.and_then(|v| v.downcast_ref::<T>().cloned()).ok_or(CallError::NotVerified)
345}
346
347/// The macro's half of [`verified`]: keep a verifier's answer on the call.
348/// Set once per call: the dispatch sets it before the body runs, so a second
349/// set — by any code inside the call — is refused (`AlreadyVerified`) and
350/// the verifier's value stands.
351#[doc(hidden)]
352pub fn __keep_verified<T: Send + Sync + 'static>(value: T) -> Result<(), CallError> {
353    let ctx = context()?;
354    let mut held = ctx.0.verified.lock().unwrap_or_else(|p| p.into_inner());
355    if held.is_some() {
356        return Err(CallError::AlreadyVerified);
357    }
358    *held = Some(Arc::new(value));
359    Ok(())
360}
361
362/// Dispatch a call to one activation as a service with no gate dispatches
363/// it: in a context admitting `auth` everywhere — said here, by the caller of
364/// this function, never assumed by the method. The leaf path of a bridge that
365/// serves a single activation (plexus-transport's REST and MCP bridges call
366/// `Activation::call` straight, outside any context, where a method that
367/// needs its caller is refused). Inside a call already, that call's reach
368/// and hop are kept, with this call's identity.
369pub async fn ungated<A: crate::plexus::Activation + ?Sized>(
370    activation: &A,
371    method: &str,
372    params: serde_json::Value,
373    auth: Option<&AuthContext>,
374    raw_ctx: Option<&crate::request::RawRequestContext>,
375) -> Result<crate::plexus::PlexusStream, PlexusError> {
376    let ctx = match context() {
377        Ok(outer) => outer.with_auth(auth),
378        Err(_) => CallContext::admitted(auth, Reach::everywhere()),
379    };
380    let stream = scope(ctx.clone(), activation.call(method, params, auth, raw_ctx)).await?;
381    Ok(Box::pin(InCall::new(ctx, stream)))
382}
383
384/// A test's way into a call (feature `test-util`, never default): a
385/// verifier that reads [`caller()`] or `current_reach()`, tested without a
386/// service. Nothing but a test builds a caller by hand.
387#[cfg(feature = "test-util")]
388pub mod test {
389    use super::{scope, CallContext};
390    use crate::plexus::AuthContext;
391    use plexus_auth_core::grants::Reach;
392    use std::future::Future;
393
394    /// Run `fut` inside a call admitted for `auth` (none: anonymous) with
395    /// `reach`, as a service's dispatch would run it.
396    pub async fn in_call<F: Future>(auth: Option<&AuthContext>, reach: Reach, fut: F) -> F::Output {
397        scope(CallContext::admitted(auth, reach), fut).await
398    }
399}
400
401/// Run `fut` inside `ctx`: how a task a method spawns carries its caller.
402pub fn scope<F: Future>(ctx: CallContext, fut: F) -> impl Future<Output = F::Output> {
403    CALL.scope(ctx, fut)
404}
405
406pin_project_lite::pin_project! {
407    /// A stream polled inside a call's context: what the dispatch hands its
408    /// caller, so a method's stream reads [`caller()`] as its first line
409    /// does.
410    pub struct InCall<S> {
411        ctx: CallContext,
412        #[pin]
413        inner: S,
414    }
415}
416
417impl<S> InCall<S> {
418    /// `inner`, each poll of it inside `ctx`.
419    pub fn new(ctx: CallContext, inner: S) -> Self {
420        Self { ctx, inner }
421    }
422}
423
424impl<S: Stream> Stream for InCall<S> {
425    type Item = S::Item;
426
427    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
428        let this = self.project();
429        let inner = this.inner;
430        CALL.sync_scope(this.ctx.clone(), || inner.poll_next(cx))
431    }
432
433    fn size_hint(&self) -> (usize, Option<usize>) {
434        self.inner.size_hint()
435    }
436}
437
438/// spec/12's hop, as a child reads it: who acts, for whom, within what.
439/// `for` grants nothing; `limit` is a ceiling, never a grant.
440#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
441pub struct Hop {
442    /// Who acts: the service that forwarded the call.
443    pub principal: String,
444    /// On whose behalf, nearest first; `[]` when the service calls for
445    /// itself or its caller is anonymous.
446    #[serde(rename = "for", default)]
447    pub for_: Vec<String>,
448    /// The service gate's verdict, in this child's terms; `None` when no
449    /// gate decided.
450    #[serde(default)]
451    pub limit: Option<HopLimit>,
452    /// The hop's id for this call, to join the two logs.
453    #[serde(default)]
454    pub call: String,
455}
456
457/// The near side's decision, as a ceiling (spec/12 `limit`).
458#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
459pub struct HopLimit {
460    /// The grant the service's gate checked (`{ns}.<method>`).
461    pub grant: String,
462    /// The scopes it admitted the caller on for it (`["*"]`, `["MENGER"]`).
463    #[serde(default)]
464    pub held_on: Vec<String>,
465}
466
467impl Hop {
468    /// The caller the hop acts for — the far end of `for` — or `None`
469    /// when it acts for itself or for an anonymous caller.
470    pub fn caller(&self) -> Option<&str> {
471        self.for_.last().map(String::as_str)
472    }
473
474    /// The grant the near side checked, if a gate decided.
475    pub fn grant(&self) -> Option<&str> {
476        self.limit.as_ref().map(|l| l.grant.as_str())
477    }
478
479    /// The ceiling: the scopes the near side admitted the caller on. Empty
480    /// when no gate decided — and then nothing is within it (fail closed).
481    pub fn held_on(&self) -> Vec<ScopeRef> {
482        self.limit.as_ref().map(|l| l.held_on.iter().map(|s| ScopeRef::parse(s)).collect()).unwrap_or_default()
483    }
484
485    /// Whether a target whose scope chain is `chain` is within the ceiling:
486    /// held on `*`, or on a scope of the chain. `false` when no gate decided,
487    /// and when the hop names no readable caller (`for` empty, or not a
488    /// principal) — the ceiling was the near side's verdict for a caller,
489    /// and there is none here: this agrees with `caller()?.reach()`, which
490    /// is nowhere then.
491    pub fn allows(&self, chain: &[ScopeRef]) -> bool {
492        let readable = self.caller().is_some_and(|p| p.parse::<plexus_auth_core::identity::Principal>().is_ok());
493        readable && self.held_on().iter().any(|s| s.is_everywhere() || chain.contains(s))
494    }
495
496    /// [`Hop::allows`] for one named scope.
497    pub fn allows_scope(&self, scope: &str) -> bool {
498        self.allows(&[ScopeRef::parse(scope)])
499    }
500}
501
502/// The reach a hop's ceiling gives its caller: what a gate of the hop alone
503/// answers — the caller holds one role, listing `grant` alone, on each scope
504/// of `held_on`, and a target resolves to itself and `*` (the child cannot
505/// resolve the service's scopes) — so it names `grant`, covers exactly
506/// `held_on`, and allows a target by name only on `*`. An anonymous caller
507/// holds nothing. RETURNS-47: no public constructor makes a reach from a
508/// list of scopes; this one is the seam's, built from a hop it took.
509#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
510fn ceiling_reach(caller: Option<&AuthContext>, grant: &str, held_on: &[ScopeRef]) -> Reach {
511    use plexus_auth_core::grants::{Gate, Membership, Memberships, Resolve, RoleTable};
512    struct Held(Vec<Membership>);
513    impl Memberships for Held {
514        fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
515            self.0.iter().filter(|m| &m.principal == who).cloned().collect()
516        }
517    }
518    struct Itself;
519    impl Resolve for Itself {
520        fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
521            Some(vec![ScopeRef::named(target), ScopeRef::Everywhere])
522        }
523    }
524    const ROLE: &str = "hop";
525    let grant = Grant::new(grant.to_string());
526    let held: Vec<Membership> = match caller.and_then(|a| a.principal()) {
527        Some(p) => held_on
528            .iter()
529            .map(|s| Membership { principal: p.clone(), role: plexus_auth_core::RoleName::new(ROLE), scope: s.clone() })
530            .collect(),
531        None => Vec::new(),
532    };
533    let roles = RoleTable::from_lists([(ROLE, [grant.as_str()])]);
534    let gate = Gate::new(std::sync::Arc::new(Held(held)), std::sync::Arc::new(roles), std::sync::Arc::new(Itself));
535    gate.reach_of_public(caller, &grant)
536}