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::{DispatchedCall, 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    /// PERF.115-49: the caller is the one the gate decided `reach` for
78    /// ([`Reach::caller`]), read there rather than kept twice; `auth` is
79    /// then `None`.
80    auth_in_reach: bool,
81    reach: ReachCell,
82    /// Boxed (PERF.115-49): only a call through the child seam has one, and
83    /// inline it was 144 of every context's bytes.
84    hop: Option<Box<Hop>>,
85    /// What a trait-impl method's verifier answered for this call
86    /// (`#[plexus_macros::from_auth(…)]` on the method): [`verified`]. Shared
87    /// by a context narrowed from this one (`with_reach`: the same call);
88    /// another caller's context (`with_auth`, `ungated`) starts its own.
89    verified: OnceLock<Verified>,
90    /// NEST-11: in a child, its link back to the service that forwarded the
91    /// call (`remote_child::host`).
92    host: Option<Arc<dyn Any + Send + Sync>>,
93    /// ONE-7: the call whose door admitted this one — its address and grant,
94    /// as the dispatcher built them — when a door did (an address scope, or
95    /// `*`, at [`plexus_auth_core::grants::Gate::check_everywhere_at`]). What
96    /// a hop carries across for exactly this call (`limit.door`) and the
97    /// call-back ceiling names.
98    door: Option<DispatchedCall>,
99    /// ONE-7 (review M1): when the door is the method's own — its grant the
100    /// call's own path ([`crate::plexus::grant_gate::door_is_own`]), or, in a
101    /// child, a hop that said so (`limit.door_own`) — and not a slot's whole
102    /// grant above it, the grant's shape: the door's grant, a `{…}` segment
103    /// where any one name stands (a typed slot's `solar.{planet}.wipe`; a
104    /// peer's literal grant with its name's segment open,
105    /// `dyn.peer.{peer}.wipe`). Only an own door runs a whole-activation
106    /// method.
107    door_shape: Option<String>,
108    /// KEEL-59: [`HOLDS_ITSELF`] — the method the dispatch held this call
109    /// for said it follows its own reach ([`follows_its_reach`]), so the
110    /// dispatch's hold ([`crate::plexus::held`]) does not end it; and
111    /// [`ROUTED`] — the dispatch has its stream, so a context derived from
112    /// this one from now is a callee's, not the dispatched method's.
113    hold: std::sync::atomic::AtomicU8,
114    /// KEEL-59 (I1): the context this one was derived from while the call
115    /// was still being routed to its method (`for_child` — a path into an
116    /// in-process child — `with_auth`, `with_reach`), so the dispatched
117    /// method's claim reaches the context the dispatch holds. A context
118    /// derived once the call is routed — a callee the method calls, an
119    /// ungated service it reaches — has none: its claim is its own.
120    up: Option<CallContext>,
121    /// KEEL-59 (N4): whether a [`follows_its_reach`] claim made here reaches
122    /// `up`: not across a call routed through a service with no gate of its
123    /// own (`with_auth`) — a callee the method's body calls — only along the
124    /// dispatched call's own path (`for_child`, `with_reach`).
125    claim_up: bool,
126    /// KEEL-59 (N3): calls into a peer opened in this call whose peer was cut
127    /// off and whose end (`child_unavailable`) is not yet taken: while any
128    /// is, a grants move the cut-off made is not asked about this call.
129    peer_ends: std::sync::atomic::AtomicU32,
130    /// KEEL-59 (N2): the grants generations this call's own writes made, the
131    /// last run of them with nothing between (`own_from..=own_to`; 0: none)
132    /// — those moves are not asked about it.
133    own_from: std::sync::atomic::AtomicU64,
134    own_to: std::sync::atomic::AtomicU64,
135}
136
137/// [`Inner::hold`]: the dispatched method follows its own reach.
138const HOLDS_ITSELF: u8 = 1;
139/// [`Inner::hold`]: the dispatch has the call's stream (the call is routed).
140const ROUTED: u8 = 2;
141
142type Verified = Arc<Mutex<Option<Arc<dyn Any + Send + Sync>>>>;
143
144/// PERF.115-49: the call's reach — known when the context is made (every
145/// call the dispatch admits: no `Once` to set it through), or an
146/// introspection call's, asked of the gate only if something reads it
147/// (PERF-15: an introspection answer looks no role up).
148enum ReachCell {
149    Known(Reach),
150    Deferred(Arc<Gate>, Grant, OnceLock<Reach>),
151}
152
153impl Inner {
154    fn with(auth: Option<AuthContext>, reach: ReachCell, hop: Option<Box<Hop>>) -> Self {
155        Inner { auth, auth_in_reach: false, reach, hop, verified: OnceLock::new(), host: None, door: None, door_shape: None, hold: std::sync::atomic::AtomicU8::new(0), up: None, claim_up: true, peer_ends: std::sync::atomic::AtomicU32::new(0), own_from: std::sync::atomic::AtomicU64::new(0), own_to: std::sync::atomic::AtomicU64::new(0) }
156    }
157
158    /// The call's verified slot, made when first set or shared (PERF.115-49:
159    /// a call whose method has no verifier allocates none).
160    fn verified(&self) -> &Verified {
161        self.verified.get_or_init(Verified::default)
162    }
163}
164
165impl fmt::Debug for CallContext {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.debug_struct("CallContext")
168            .field("principal", &self.auth().and_then(|a| a.principal()).map(|p| p.to_string()))
169            .field("reach", &self.reach())
170            .field("hop", &self.0.hop)
171            .finish()
172    }
173}
174
175impl CallContext {
176    /// A call a service's dispatch admitted: `auth` the identity that
177    /// stands (none: anonymous), `reach` what the gate answered — or
178    /// [`Reach::everywhere`] on a service without a gate.
179    pub(crate) fn admitted(auth: Option<&AuthContext>, reach: Reach) -> Self {
180        Self(Arc::new(Inner::with(auth.cloned(), ReachCell::Known(reach), None)))
181    }
182
183    /// PERF.115-49: a call a gated service's dispatch admitted on the
184    /// gate's `reach` — whose caller is the identity that stands, the one
185    /// the gate was asked about ([`Reach::caller`]), so the context reads it
186    /// from the reach rather than cloning it again. Only for a reach the
187    /// gate answered for this call's own caller.
188    pub(crate) fn admitted_by_gate(auth: Option<&AuthContext>, reach: Reach) -> Self {
189        debug_assert_eq!(
190            reach.caller().map(|a| (&a.user_id, &a.session_id)),
191            auth.map(|a| (&a.user_id, &a.session_id)),
192            "a gate's reach names the caller it was decided for"
193        );
194        let mut inner = Inner::with(None, ReachCell::Known(reach), None);
195        inner.auth_in_reach = true;
196        Self(Arc::new(inner))
197    }
198
199    /// ONE-7: this context, admitted at the door of `call` — made by the
200    /// dispatch alone, right after the gate answered, for the call it decided.
201    ///
202    /// `peer_slot`: the untyped peer slot's grant (`dyn.{peer}`) the path
203    /// went through, when it did — the peer's name's segment is then open in
204    /// the door's shape (an in-process peer's namespace is not its name).
205    pub(crate) fn at_door(mut self, call: DispatchedCall, peer_slot: Option<&str>) -> Self {
206        match Arc::get_mut(&mut self.0) {
207            Some(inner) => {
208                inner.door_shape = crate::plexus::grant_gate::door_is_own(&call).then(|| crate::plexus::grant_gate::door_shape(&call, peer_slot));
209                inner.door = Some(call);
210            }
211            None => debug_assert!(false, "a context is given its door as it is made"),
212        }
213        self
214    }
215
216    /// ONE-7: the call whose door admitted this one, if a door did.
217    pub(crate) fn door(&self) -> Option<&DispatchedCall> {
218        self.0.door.as_ref()
219    }
220
221    /// ONE-7 (review M1): whether the door that admitted this call is the
222    /// method's own, not a slot's whole grant above it.
223    pub(crate) fn door_own(&self) -> bool {
224        self.0.door.is_some() && self.0.door_shape.is_some()
225    }
226
227    /// The shape of an own door's grant ([`CallContext::door_own`]).
228    fn door_shape(&self) -> Option<&str> {
229        self.0.door.as_ref().and(self.0.door_shape.as_deref())
230    }
231
232    /// An introspection call a gated service let through (AUTH-4): its
233    /// reach is the caller's for the path, as the gate answers a public
234    /// method's — asked only when read.
235    pub(crate) fn introspection(auth: Option<&AuthContext>, gate: Arc<Gate>, grant: Grant) -> Self {
236        Self(Arc::new(Inner::with(auth.cloned(), ReachCell::Deferred(gate, grant, OnceLock::new()), None)))
237    }
238
239    /// A call that came through the child seam (owner, 2026-11-04: children
240    /// receive auth): its caller is the one the hop names — `for`'s far end,
241    /// as an `AuthContext` whose session is the hop's call id; anonymous when
242    /// `for` is empty — and its reach the hop's ceiling (`limit.held_on` for
243    /// `limit.grant`, as a gate of the hop alone answers it), never wider;
244    /// nowhere when no gate decided (`limit: null`) or `for` cannot be read. The hop is
245    /// believed as the transport delivered it (`remote_child::serve_child_on`
246    /// takes it only from a sender it trusts).
247    // PLEXUS-45: the child seam is native-only; on wasm32 nothing takes a hop.
248    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
249    ///
250    /// ONE-7: `door` — the hop's `limit.door`, checked by the seam to name
251    /// exactly the call being served (`/{target}`) — is the door the near
252    /// side admitted it at: the reach is then that door's, for `limit.grant`
253    /// at this call's address alone (and `limit.held_on`'s data, as
254    /// before), so [`Reach::holds_activation`] is true and no data is held
255    /// by it. Never `*`.
256    ///
257    /// `own` — the hop's `limit.door_own` — says the near side admitted it
258    /// at the method's own grant there, not a slot's whole grant: only then
259    /// does the door run a whole-activation method here (review M1).
260    pub(crate) fn through_hop(hop: Hop, door: Option<&DispatchedCall>, own: bool) -> Self {
261        // `for` names someone this cannot read: anonymous, and no ceiling —
262        // the verdict was for a caller this child cannot name.
263        let unreadable = hop.caller().is_some_and(|p| p.parse::<plexus_auth_core::identity::Principal>().is_err());
264        let auth = hop.caller().and_then(|p| p.parse::<plexus_auth_core::identity::Principal>().ok()).map(|p| {
265            AuthContext::for_principal(&p, format!("hop:{}", hop.call), Vec::new(), serde_json::json!({ "hop_principal": hop.principal }))
266        });
267        let door = door.filter(|d| hop.limit.as_ref().is_some_and(|l| d.grant().as_str() == l.grant));
268        let reach = match &hop.limit {
269            Some(l) if !unreadable => ceiling_reach(auth.as_ref(), &l.grant, &hop.held_on(), door),
270            _ => Reach::nowhere(),
271        };
272        let admitted_at = door.filter(|_| crate::plexus::grant_gate::is_door(&reach)).cloned();
273        let mut inner = Inner::with(auth, ReachCell::Known(reach), Some(Box::new(hop)));
274        inner.door_shape = admitted_at.as_ref().filter(|_| own).map(|d| d.grant().to_string());
275        inner.door = admitted_at;
276        Self(Arc::new(inner))
277    }
278
279    /// NEST-11: [`CallContext::through_hop`], with the link back to the
280    /// service that forwarded the call.
281    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
282    pub(crate) fn through_hop_with(hop: Hop, door: Option<&DispatchedCall>, own: bool, host: Arc<dyn Any + Send + Sync>) -> Self {
283        let mut ctx = Self::through_hop(hop, door, own);
284        if let Some(inner) = Arc::get_mut(&mut ctx.0) {
285            inner.host = Some(host);
286        }
287        ctx
288    }
289
290    /// NEST-11: the link back to the service that forwarded this call, in a
291    /// child.
292    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
293    pub(crate) fn host_link(&self) -> Option<&Arc<dyn Any + Send + Sync>> {
294        self.0.host.as_ref()
295    }
296
297    /// The context of a call routed into an in-process child, under its
298    /// forward policy: `callee` the context the policy derived (none, or
299    /// one no longer signed in, is anonymous); the call's reach kept when
300    /// the policy keeps the caller's identity, nowhere when it does not; the
301    /// hop kept as the caller is (none under `anonymous`); the verified
302    /// value the child's own (another caller).
303    pub(crate) fn for_child(&self, callee: Option<&AuthContext>, keeps_identity: bool) -> Self {
304        let auth = callee.filter(|a| a.is_authenticated()).cloned();
305        // The reach and the hop follow the caller: kept with its identity
306        // (`same_service`, `identity_only`, `pass_through`), none under
307        // `anonymous` — `hop()` there errors, as outside a hop.
308        let (reach, hop) = if keeps_identity {
309            (self.reach().cloned().unwrap_or_else(Reach::nowhere), self.0.hop.clone())
310        } else {
311            (Reach::nowhere(), None)
312        };
313        let mut inner = Inner::with(auth, ReachCell::Known(reach), hop);
314        inner.host = self.0.host.clone().filter(|_| keeps_identity);
315        // ONE-7: the same call, so the same door — with the reach it is kept with.
316        inner.door = self.0.door.clone().filter(|_| keeps_identity);
317        inner.door_shape = self.0.door_shape.clone();
318        inner.up = self.routing().then(|| self.clone());
319        Self(Arc::new(inner))
320    }
321
322    /// This context with its identity replaced: a call routed from inside
323    /// another, through a service with no gate of its own.
324    pub(crate) fn with_auth(&self, auth: Option<&AuthContext>) -> Self {
325        let reach = match &self.0.reach {
326            ReachCell::Known(r) => ReachCell::Known(r.clone()),
327            ReachCell::Deferred(_, _, cell) if cell.get().is_some() => ReachCell::Known(cell.get().unwrap().clone()),
328            ReachCell::Deferred(gate, grant, _) => ReachCell::Deferred(gate.clone(), grant.clone(), OnceLock::new()),
329        };
330        let mut inner = Inner::with(auth.cloned(), reach, self.0.hop.clone());
331        inner.host = self.0.host.clone();
332        inner.door = self.0.door.clone();
333        inner.door_shape = self.0.door_shape.clone();
334        inner.up = self.routing().then(|| self.clone());
335        // N4: a service with no gate reached from inside a call is the
336        // body's callee: its claim to follow its reach is its own.
337        inner.claim_up = false;
338        Self(Arc::new(inner))
339    }
340
341    /// This context with its reach replaced: the same call, so the same
342    /// verified value (the same slot, set once for both).
343    pub(crate) fn with_reach(&self, reach: Reach) -> Self {
344        // ONE-7: the door stays only with a door reach (`with_reach` takes
345        // one only for the call's own grant).
346        let door = self.0.door.clone().filter(|_| crate::plexus::grant_gate::is_door(&reach));
347        let mut inner = Inner::with(self.auth().cloned(), ReachCell::Known(reach), self.0.hop.clone());
348        inner.verified = OnceLock::from(Arc::clone(self.0.verified()));
349        inner.host = self.0.host.clone();
350        inner.door = door;
351        inner.door_shape = self.0.door_shape.clone();
352        inner.up = self.routing().then(|| self.clone());
353        Self(Arc::new(inner))
354    }
355
356    /// The identity the gate admitted (in a child, the one the hop names, or
357    /// the one its forward policy derived); `None` for an anonymous call.
358    pub fn auth(&self) -> Option<&AuthContext> {
359        match (self.0.auth_in_reach, &self.0.reach) {
360            (true, ReachCell::Known(reach)) => reach.caller(),
361            _ => self.0.auth.as_ref(),
362        }
363    }
364
365    /// The reach the gate answered (in a child through the seam, the hop's
366    /// ceiling).
367    pub fn reach(&self) -> Option<&Reach> {
368        Some(match &self.0.reach {
369            ReachCell::Known(reach) => reach,
370            ReachCell::Deferred(gate, grant, cell) => cell.get_or_init(|| gate.reach_of_public(self.0.auth.as_ref(), grant)),
371        })
372    }
373
374    /// The hop the call came through, in a child.
375    pub fn hop(&self) -> Option<&Hop> {
376        self.0.hop.as_deref()
377    }
378
379    /// KEEL-59: the dispatched method answers for its own reach from now
380    /// ([`follows_its_reach`]): said on this context and every one it was
381    /// derived from while the call was routed — the dispatched method's own
382    /// chain, never a callee's (I1).
383    pub(crate) fn hold_itself(&self) {
384        let mut at = Some(self);
385        while let Some(ctx) = at {
386            ctx.0.hold.fetch_or(HOLDS_ITSELF, std::sync::atomic::Ordering::AcqRel);
387            at = ctx.0.up.as_ref().filter(|_| ctx.0.claim_up);
388        }
389    }
390
391    /// KEEL-59: whether the dispatched method answers for its own reach.
392    pub(crate) fn holds_itself(&self) -> bool {
393        self.0.hold.load(std::sync::atomic::Ordering::Acquire) & HOLDS_ITSELF != 0
394    }
395
396    /// KEEL-59 (N3): a call into a peer opened in this call had its peer
397    /// cut off — its end is on its way — said on this context and those it
398    /// was derived from while routed, so a grants move the cut-off made (a
399    /// peer leaving takes its grants with it) leaves the call its own end,
400    /// not a `forbidden` for a name that went. Undone by
401    /// [`Self::peer_end_taken`] once that call is let go.
402    pub(crate) fn peer_ended(&self) {
403        let mut at = Some(self);
404        while let Some(ctx) = at {
405            ctx.0.peer_ends.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
406            at = ctx.0.up.as_ref();
407        }
408    }
409
410    /// KEEL-59 (N3): the call into the cut-off peer is let go (its end taken,
411    /// or dropped): this call is asked again at the next move as usual.
412    pub(crate) fn peer_end_taken(&self) {
413        let mut at = Some(self);
414        while let Some(ctx) = at {
415            let _ = ctx.0.peer_ends.fetch_update(std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire, |n| n.checked_sub(1));
416            at = ctx.0.up.as_ref();
417        }
418    }
419
420    /// KEEL-59: whether a call into a cut-off peer has its end on its way.
421    pub(crate) fn ended_by_peer(&self) -> bool {
422        self.0.peer_ends.load(std::sync::atomic::Ordering::Acquire) != 0
423    }
424
425    /// KEEL-59 (N2): this call's own write moved the grants to `generation`
426    /// (said by plexus-auth-core in the moving task): said on this context
427    /// and those it was derived from while routed.
428    fn moved_by_itself(&self, generation: u64) {
429        use std::sync::atomic::Ordering::{Acquire, Release};
430        let mut at = Some(self);
431        while let Some(ctx) = at {
432            // A move right after its own last one extends the run; any other
433            // starts a new one (a move made between is not its own). The
434            // run's start is written before its end is, so a reader never
435            // pairs a new end with an old start.
436            if ctx.0.own_to.load(Acquire) != generation.wrapping_sub(1) {
437                ctx.0.own_from.store(generation, Release);
438            }
439            ctx.0.own_to.store(generation, Release);
440            at = ctx.0.up.as_ref();
441        }
442    }
443
444    /// KEEL-59 (N2): whether every move from `seen` to `now` was this call's
445    /// own write: then it is not asked about them. A later move, or one
446    /// made between by anything else, is asked as usual — it is never a way
447    /// to stay alive past someone else's revoke.
448    pub(crate) fn own_move(&self, seen: u64, now: u64) -> bool {
449        use std::sync::atomic::Ordering::Acquire;
450        self.0.own_to.load(Acquire) == now && self.0.own_from.load(Acquire) <= seen.wrapping_add(1) && now > seen
451    }
452
453    /// KEEL-59: the dispatch has this call's stream: what is derived from
454    /// it from now is a callee's context.
455    pub(crate) fn routed(&self) {
456        self.0.hold.fetch_or(ROUTED, std::sync::atomic::Ordering::AcqRel);
457    }
458
459    /// Whether the call this context is in is still being routed to its
460    /// method: none of the contexts it was derived from while routing has
461    /// been marked routed.
462    pub(crate) fn routing(&self) -> bool {
463        let mut at = Some(self);
464        while let Some(ctx) = at {
465            if ctx.0.hold.load(std::sync::atomic::Ordering::Acquire) & ROUTED != 0 {
466                return false;
467            }
468            at = ctx.0.up.as_ref();
469        }
470        true
471    }
472
473    /// The caller this context names: an error for a call that came
474    /// through a hop (no gate of this process admitted anyone).
475    pub fn caller(&self) -> Result<Caller, CallError> {
476        match self.reach() {
477            Some(_) => Ok(Caller(self.clone())),
478            None => Err(CallError::ThroughHop),
479        }
480    }
481}
482
483/// The caller of the call being run, as the service's gate admitted them:
484/// [`caller()`].
485#[derive(Clone, Debug)]
486pub struct Caller(CallContext);
487
488impl Caller {
489    /// The identity the gate admitted; `None` for an anonymous caller (a
490    /// `public` method, or a sign-in that has ended).
491    pub fn auth(&self) -> Option<&AuthContext> {
492        self.0.auth()
493    }
494
495    /// The identity, signed in — `Unauthenticated` for an anonymous caller,
496    /// as `#[from_auth]` refuses one.
497    pub fn signed_in(&self) -> Result<&AuthContext, PlexusError> {
498        self.0
499            .auth()
500            .ok_or_else(|| PlexusError::Unauthenticated("This method requires authentication".to_string()))
501    }
502
503    /// What the gate answered for the call: where its grant is held.
504    pub fn reach(&self) -> &Reach {
505        self.0.reach().expect("a caller is made only from a context with a reach")
506    }
507
508    /// The whole context, to hand to work the method spawns ([`scope`]).
509    pub fn context(&self) -> &CallContext {
510        &self.0
511    }
512}
513
514/// Why there is no caller (or no hop) to answer. Fail closed: each is an
515/// error, never a default; as a [`PlexusError`] it is `Unauthenticated`.
516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
517pub enum CallError {
518    /// Not inside a call: no dispatch set a context here — a task spawned
519    /// without one handed to it ([`scope`]), or code run outside any call.
520    OutsideCall,
521    /// Inside a call that came through a hop: no gate of this process
522    /// admitted a caller; read [`hop()`].
523    ThroughHop,
524    /// Inside a call that did not come through a hop: there is none to read.
525    NoHop,
526    /// Inside a call whose method declared no verifier, or one that answered
527    /// another type than the one asked for.
528    NotVerified,
529    /// The call's verified value is already set: it is set once, by the
530    /// method's verifier, and never replaced.
531    AlreadyVerified,
532}
533
534impl fmt::Display for CallError {
535    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
536        f.write_str(match self {
537            CallError::OutsideCall => {
538                "no caller: this runs outside a call (a spawned task carries one only when handed it, plexus_core::call::scope)"
539            }
540            CallError::ThroughHop => "no caller admitted here: this call came through a hop (read plexus_core::call::hop)",
541            CallError::NoHop => "no hop: this call did not come through the child seam",
542            CallError::AlreadyVerified => "the call's verified value is set once, by its verifier, and is set",
543            CallError::NotVerified => {
544                "nothing verified: the method declares no `#[plexus_macros::from_auth(…)]` answering this type"
545            }
546        })
547    }
548}
549
550impl std::error::Error for CallError {}
551
552impl From<CallError> for PlexusError {
553    fn from(e: CallError) -> Self {
554        PlexusError::Unauthenticated(e.to_string())
555    }
556}
557
558/// The caller of the call this runs in, as the gate admitted them, with the
559/// reach it answered. An error outside a call, and in a child (read
560/// [`hop()`] there).
561pub fn caller() -> Result<Caller, CallError> {
562    CALL.try_with(CallContext::caller).unwrap_or(Err(CallError::OutsideCall))
563}
564
565/// The hop the call this runs in came through (spec/12), in a child reached
566/// through the seam. An error outside a call, and in a call that did not
567/// come through a hop.
568pub fn hop() -> Result<Hop, CallError> {
569    CALL.try_with(|c| c.hop().cloned().ok_or(CallError::NoHop)).unwrap_or(Err(CallError::OutsideCall))
570}
571
572/// KEEL-59: the call this runs in answers for its own reach when the
573/// grants move, so the dispatch does not end it.
574///
575/// A call a gated service admitted is held to that admission while it runs
576/// ([`crate::plexus::held`]): when the grants generation moves (a grant or
577/// a revoke, a role edited, a team changed, a sign-out), it is decided again
578/// by the rule it was admitted by, and one that no longer holds — or whose
579/// reach lost a scope it had — ends with one `forbidden` (or
580/// `unauthenticated`) item. A method that already follows its reach as it
581/// moves — a `watch` that asks [`plexus_auth_core::grants::Reach::recheck`]
582/// at each move and re-scopes in place, saying what entered and what left,
583/// and ends itself when the grant is held nowhere — calls this once, and
584/// the dispatch leaves the call to it. It is the method's word that it ends
585/// itself when nothing is held: a method that calls this and goes on
586/// answering from a reach it no longer has leaks it, as one that ignores
587/// its reach always could.
588///
589/// An error outside a call.
590pub fn follows_its_reach() -> Result<(), CallError> {
591    CALL.try_with(CallContext::hold_itself).map_err(|_| CallError::OutsideCall)
592}
593
594/// KEEL-59 (N2): plexus-auth-core tells, in the moving task, every grants
595/// generation a bump makes; the call that made it marks it its own. Set once.
596pub(crate) fn hook_moves() {
597    static HOOKED: std::sync::Once = std::sync::Once::new();
598    HOOKED.call_once(|| {
599        plexus_auth_core::grants::GrantsGeneration::on_move(|generation| {
600            let _ = CALL.try_with(|c| c.moved_by_itself(generation));
601        });
602    });
603}
604
605/// The whole context of the call this runs in — to hand to a task it
606/// spawns, [`scope`]`(context()?, fut)`. An error outside a call.
607pub fn context() -> Result<CallContext, CallError> {
608    CALL.try_with(CallContext::clone).map_err(|_| CallError::OutsideCall)
609}
610
611/// KEEL-31: may the call this runs in run `grant`, a method that acts on
612/// the whole service (`#[plexus_macros::method(everywhere)]`)? Only when
613/// the reach it was admitted with is held on `*`: a gated service's verdict
614/// (the gate decided it on `*` — or, through an untyped slot, on the slot's
615/// grant, which must then be held on `*`), the hop's ceiling in a child
616/// reached through the seam (`limit.held_on` naming `*`), or a service
617/// without a gate (its dispatch admits everywhere). The macro calls it
618/// before such a method runs, wherever it is called from, so neither a
619/// near side that decided on a slot nor an older near side lets a scoped
620/// holder through. Outside any call — code calling the activation
621/// directly, with no dispatch and no hop — it allows, as before: no gate
622/// decided anything to consult.
623///
624/// ONE-7: or when the call was admitted at its own door — decided from
625/// the door the dispatch recorded ([`CallContext::door`]: the address and
626/// the grant it was admitted at), never from grant names (review M1). The
627/// door must be the method's own: its grant the call's own path, segment
628/// for segment (`dyn.connect` at `dyn.connect`, a typed slot's
629/// `solar.{planet}.wipe` at `solar.mars.wipe`, a peer's literal
630/// `dyn.peer.vault.wipe` held at `/dyn.peer.vault.*` or `/dyn.*`), or in a
631/// child a hop that said so (`limit.door_own`); and its address must end in
632/// `grant` itself (`….vault.wipe` for `vault.wipe`; a `{slot}` segment
633/// stands for the namespace there), so a method one call's body runs
634/// in-process is not run on that call's door. An untyped peer slot's whole
635/// grant (`dyn.{peer}`) held at a peer's address opens the peer's ordinary
636/// methods and no whole-activation one: those need the method's own grant
637/// at its address (a role listing it, or admin), or `*`.
638pub fn admits_everywhere(grant: &str) -> Result<(), PlexusError> {
639    let Ok(ctx) = context() else { return Ok(()) };
640    let held_on = match ctx.reach() {
641        Some(r) if r.is_everywhere() => return Ok(()),
642        Some(r) if r.holds_activation() && own_door_of(&ctx, r, grant) => return Ok(()),
643        Some(r) => r.held_on().to_vec(),
644        None => Vec::new(),
645    };
646    Err(PlexusError::Forbidden {
647        reason: crate::plexus::AuthzDenyReason::MissingGrant {
648            grant: Grant::new(grant),
649            scope: plexus_auth_core::grants::ScopeRef::Everywhere,
650            roles: Vec::new(),
651            held_on,
652        },
653    })
654}
655
656/// ONE-7 (review M1): whether the call's recorded door is `grant`'s own
657/// (`<namespace>.<method>`, as the macro says it): the method's own grant
658/// ([`CallContext::door_own`]), the reach's, at an address ending in the
659/// namespace and the method — a `{slot}` segment of the door's grant
660/// standing for the namespace in its place.
661fn own_door_of(ctx: &CallContext, reach: &Reach, grant: &str) -> bool {
662    let Some(call) = ctx.door() else { return false };
663    if reach.grant() != Some(call.grant()) {
664        return false;
665    }
666    let Some(shape) = ctx.door_shape() else { return false };
667    let path: Vec<&str> = call.at().path().split('.').collect();
668    let held: Vec<&str> = shape.split('.').collect();
669    let named: Vec<&str> = grant.split('.').collect();
670    let Some((method, ns)) = named.split_last() else { return false };
671    if ns.is_empty() || path.len() < named.len() || path.last() != Some(method) {
672        return false;
673    }
674    let from = path.len() - named.len();
675    ns.iter().enumerate().all(|(i, n)| {
676        let at = from + i;
677        path[at] == *n || held.get(at).is_some_and(|g| crate::plexus::grant_gate::is_slot_segment(g))
678    })
679}
680
681/// What the method's verifier answered for this call: on `impl Trait for
682/// Type`, `#[plexus_macros::from_auth(self.access.verify)]` on the method
683/// runs the verifier before the body — its error the call's refusal, out of
684/// band and typed, as a `#[from_auth]` parameter's is — and keeps its value
685/// here for the body. An error outside a call, and when the method declared
686/// no verifier of type `T`.
687pub fn verified<T: Clone + Send + Sync + 'static>() -> Result<T, CallError> {
688    let ctx = context()?;
689    let Some(slot) = ctx.0.verified.get() else { return Err(CallError::NotVerified) };
690    let held = slot.lock().unwrap_or_else(|p| p.into_inner()).clone();
691    held.and_then(|v| v.downcast_ref::<T>().cloned()).ok_or(CallError::NotVerified)
692}
693
694/// The macro's half of [`verified`]: keep a verifier's answer on the call.
695/// Set once per call: the dispatch sets it before the body runs, so a second
696/// set — by any code inside the call — is refused (`AlreadyVerified`) and
697/// the verifier's value stands.
698#[doc(hidden)]
699pub fn __keep_verified<T: Send + Sync + 'static>(value: T) -> Result<(), CallError> {
700    let ctx = context()?;
701    let mut held = ctx.0.verified().lock().unwrap_or_else(|p| p.into_inner());
702    if held.is_some() {
703        return Err(CallError::AlreadyVerified);
704    }
705    *held = Some(Arc::new(value));
706    Ok(())
707}
708
709/// Dispatch a call to one activation as a service with no gate dispatches
710/// it: in a context admitting `auth` everywhere — said here, by the caller of
711/// this function, never assumed by the method. The leaf path of a bridge that
712/// serves a single activation (plexus-transport's REST and MCP bridges call
713/// `Activation::call` straight, outside any context, where a method that
714/// needs its caller is refused). Inside a call already, that call's reach
715/// and hop are kept, with this call's identity.
716pub async fn ungated<A: crate::plexus::Activation + ?Sized>(
717    activation: &A,
718    method: &str,
719    params: serde_json::Value,
720    auth: Option<&AuthContext>,
721    raw_ctx: Option<&crate::request::RawRequestContext>,
722) -> Result<crate::plexus::PlexusStream, PlexusError> {
723    let ctx = match context() {
724        Ok(outer) => outer.with_auth(auth),
725        Err(_) => CallContext::admitted(auth, Reach::everywhere()),
726    };
727    let stream = scope(ctx.clone(), activation.call(method, params, auth, raw_ctx)).await?;
728    Ok(Box::pin(InCall::new(ctx, stream)))
729}
730
731/// A test's way into a call (feature `test-util`, never default): a
732/// verifier that reads [`caller()`] or `current_reach()`, tested without a
733/// service. Nothing but a test builds a caller by hand.
734#[cfg(feature = "test-util")]
735pub mod test {
736    use super::{scope, CallContext};
737    use crate::plexus::AuthContext;
738    use plexus_auth_core::grants::Reach;
739    use std::future::Future;
740
741    /// Run `fut` inside a call admitted for `auth` (none: anonymous) with
742    /// `reach`, as a service's dispatch would run it.
743    pub async fn in_call<F: Future>(auth: Option<&AuthContext>, reach: Reach, fut: F) -> F::Output {
744        scope(CallContext::admitted(auth, reach), fut).await
745    }
746}
747
748/// Run `fut` inside `ctx`: how a task a method spawns carries its caller.
749pub fn scope<F: Future>(ctx: CallContext, fut: F) -> impl Future<Output = F::Output> {
750    CALL.scope(ctx, fut)
751}
752
753pin_project_lite::pin_project! {
754    /// A stream polled inside a call's context: what the dispatch hands its
755    /// caller, so a method's stream reads [`caller()`] as its first line
756    /// does.
757    pub struct InCall<S> {
758        ctx: CallContext,
759        #[pin]
760        inner: S,
761    }
762}
763
764impl<S> InCall<S> {
765    /// `inner`, each poll of it inside `ctx`.
766    pub fn new(ctx: CallContext, inner: S) -> Self {
767        Self { ctx, inner }
768    }
769}
770
771/// KEEL-59: poll `stream` once inside `ctx`, as [`InCall`] does.
772pub(crate) fn poll_in<S: Stream + Unpin + ?Sized>(ctx: &CallContext, stream: &mut S, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
773    CALL.sync_scope(ctx.clone(), || Pin::new(stream).poll_next(cx))
774}
775
776impl<S: Stream> Stream for InCall<S> {
777    type Item = S::Item;
778
779    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
780        let this = self.project();
781        let inner = this.inner;
782        CALL.sync_scope(this.ctx.clone(), || inner.poll_next(cx))
783    }
784
785    fn size_hint(&self) -> (usize, Option<usize>) {
786        self.inner.size_hint()
787    }
788}
789
790/// spec/12's hop, as a child reads it: who acts, for whom, within what.
791/// `for` grants nothing; `limit` is a ceiling, never a grant.
792#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
793pub struct Hop {
794    /// Who acts: the service that forwarded the call.
795    pub principal: String,
796    /// On whose behalf, nearest first; `[]` when the service calls for
797    /// itself or its caller is anonymous.
798    #[serde(rename = "for", default)]
799    pub for_: Vec<String>,
800    /// The service gate's verdict, in this child's terms; `None` when no
801    /// gate decided.
802    #[serde(default)]
803    pub limit: Option<HopLimit>,
804    /// The hop's id for this call, to join the two logs.
805    #[serde(default)]
806    pub call: String,
807    /// DYNAUTH-12: the peer token the service minted for this one call
808    /// (`plexus::peer_token`): addressed to this child, bound to its key,
809    /// naming `call` and the method. A child that verifies
810    /// (`ServeChild::tokens`) checks the hop by it, and (KEEL-19) believes
811    /// it only from whoever the token's `cnf` names: the service's own
812    /// connection for a token it forwards, or the presenter, with its proof
813    /// (the hop's `proof`, beside the token), for one exchanged
814    /// (`dyn.exchange`). Never logged.
815    #[serde(default, skip_serializing_if = "Option::is_none")]
816    pub token: Option<String>,
817}
818
819// DYNAUTH-12: a hop's token is never shown.
820impl std::fmt::Debug for Hop {
821    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
822        f.debug_struct("Hop")
823            .field("principal", &self.principal)
824            .field("for_", &self.for_)
825            .field("limit", &self.limit)
826            .field("call", &self.call)
827            .field("token", &self.token.as_ref().map(|_| "…"))
828            .finish()
829    }
830}
831
832/// The near side's decision, as a ceiling (spec/12 `limit`).
833#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
834pub struct HopLimit {
835    /// The grant the service's gate checked (`{ns}.<method>`).
836    pub grant: String,
837    /// The scopes it admitted the caller on for it (`["*"]`, `["MENGER"]`).
838    #[serde(default)]
839    pub held_on: Vec<String>,
840}
841
842impl Hop {
843    /// The caller the hop acts for — the far end of `for` — or `None`
844    /// when it acts for itself or for an anonymous caller.
845    pub fn caller(&self) -> Option<&str> {
846        self.for_.last().map(String::as_str)
847    }
848
849    /// The grant the near side checked, if a gate decided.
850    pub fn grant(&self) -> Option<&str> {
851        self.limit.as_ref().map(|l| l.grant.as_str())
852    }
853
854    /// The ceiling: the scopes the near side admitted the caller on. Empty
855    /// when no gate decided — and then nothing is within it (fail closed).
856    pub fn held_on(&self) -> Vec<ScopeRef> {
857        self.limit.as_ref().map(|l| l.held_on.iter().map(|s| ScopeRef::parse(s)).collect()).unwrap_or_default()
858    }
859
860    /// Whether a target whose scope chain is `chain` is within the ceiling:
861    /// held on `*`, or on a scope of the chain. `false` when no gate decided,
862    /// and when the hop names no readable caller (`for` empty, or not a
863    /// principal) — the ceiling was the near side's verdict for a caller,
864    /// and there is none here: this agrees with `caller()?.reach()`, which
865    /// is nowhere then.
866    pub fn allows(&self, chain: &[ScopeRef]) -> bool {
867        let readable = self.caller().is_some_and(|p| p.parse::<plexus_auth_core::identity::Principal>().is_ok());
868        readable && self.held_on().iter().any(|s| s.is_everywhere() || chain.contains(s))
869    }
870
871    /// [`Hop::allows`] for one named scope.
872    pub fn allows_scope(&self, scope: &str) -> bool {
873        self.allows(&[ScopeRef::parse(scope)])
874    }
875}
876
877/// The reach a hop's ceiling gives its caller: what a gate of the hop alone
878/// answers — the caller holds one role, listing `grant` alone, on each scope
879/// of `held_on`, and a target resolves to itself and `*` (the child cannot
880/// resolve the service's scopes) — so it names `grant`, covers exactly
881/// `held_on`, and allows a target by name only on `*`. An anonymous caller
882/// holds nothing. RETURNS-47: no public constructor makes a reach from a
883/// list of scopes; this one is the seam's, built from a hop it took.
884///
885/// ONE-7: with `door` (the hop's `limit.door`, for this call), the role is
886/// held on the call's own address too, and the reach is the gate's answer at
887/// that door ([`Gate::check_everywhere_at`]): it holds the activation for
888/// this call and `grant` alone, and no data beyond `held_on`.
889#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
890fn ceiling_reach(caller: Option<&AuthContext>, grant: &str, held_on: &[ScopeRef], door: Option<&DispatchedCall>) -> Reach {
891    use plexus_auth_core::grants::{Gate, Membership, Memberships, Resolve, RoleTable};
892    struct Held(Vec<Membership>);
893    impl Memberships for Held {
894        fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
895            self.0.iter().filter(|m| &m.principal == who).cloned().collect()
896        }
897    }
898    struct Itself;
899    impl Resolve for Itself {
900        fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
901            Some(vec![ScopeRef::named(target), ScopeRef::Everywhere])
902        }
903    }
904    const ROLE: &str = "hop";
905    let grant = Grant::new(grant.to_string());
906    let door = door.filter(|d| d.grant() == &grant);
907    let at = door.map(|d| ScopeRef::named(format!("/{}", d.at().path())));
908    let held: Vec<Membership> = match caller.and_then(|a| a.principal()) {
909        Some(p) => held_on
910            .iter()
911            .chain(at.iter())
912            .map(|s| Membership { principal: p.clone(), role: plexus_auth_core::RoleName::new(ROLE), scope: s.clone() })
913            .collect(),
914        None => Vec::new(),
915    };
916    let roles = RoleTable::from_lists([(ROLE, [grant.as_str()])]);
917    let gate = Gate::new(std::sync::Arc::new(Held(held)), std::sync::Arc::new(roles), std::sync::Arc::new(Itself));
918    match door {
919        Some(call) => gate.check_everywhere_at(caller, call).unwrap_or_else(|_| gate.reach_of_public(caller, &grant)),
920        None => gate.reach_of_public(caller, &grant),
921    }
922}