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