Skip to main content

plexus_core/
call.rs

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