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