plexus-core 0.11.3

Core infrastructure for Plexus RPC: Activation trait, DynamicHub, schemas
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! AUTH-2 — the grant gate in dispatch: default deny, every method.
//!
//! A [`DynamicHub`](super::DynamicHub) given a gate
//! ([`DynamicHub::with_gate`](super::DynamicHub::with_gate)) asks it before
//! routing every call: the method's grant (its schema's `grant`, else
//! `<activation>.<method>`), held through a role on the scope its target
//! resolves to (its schema's `target` param, read from the call's params),
//! within the session's ceiling. A service without a gate never enters this
//! module and dispatches exactly as before.
//!
//! # Decision table (gate set)
//!
//! | call | anonymous | signed in |
//! |---|---|---|
//! | `public` method | runs (empty reach) | runs (its reach) |
//! | introspection: `<ns>.schema`, the service's `hash` / `hashes` / `schema` / `ir` | runs | runs |
//! | method with a `target`, value present | `Unauthenticated` | allowed iff a role held on a scope in the value's chain lists the grant, and every ceiling layer allows it there |
//! | method that acts `everywhere` (KEEL-31) | `Unauthenticated` | allowed iff a role held on `*` lists the grant, and every ceiling layer allows it on `*` — held on a scope is refused, naming `*` |
//! | method without a target (or the target param absent / null) | `Unauthenticated` | allowed iff the grant is held anywhere (within the ceiling) |
//! | method no schema describes and no slot holds (KEEL-54) | `Unauthenticated` | grant = the dotted path, held on `*` alone (as `everywhere`) — never "held anywhere" |
//! | a signed-in grant (AUTH-5: `auth.whoami`, `auth.logout`, `auth.requires`) | `Unauthenticated` | runs (its reach), whatever the roles or ceiling |
//!
//! A target whose value is a list is checked element by element; every
//! element must be allowed.
//!
//! KEEL-54: every row is decided on the path the service routes —
//! [`DynamicHub::call_path`](super::DynamicHub), the caller's spelling read
//! once (`svc.vault.get` is `vault.get`) — and the router runs the call only
//! under a reach made for that path's own grant.
//!
//! # The door (ONE-7)
//!
//! Owner, 2026-11-11: "activation and data scopes are separate. we can only
//! generally handle activation scopes. data scopes must be handled by the
//! application". A role may be held on an **address** (`/dyn`, `/dyn.*`,
//! `/dyn.peer.shop.*`; plexus-auth-core 0.3.4) — never data. The gate passes
//! the address of the call it dispatches only for the two shapes that touch
//! no data of this service, and decides them at the **door**
//! ([`Gate::check_everywhere_at`]):
//!
//! | the routed entry | decided by | an address scope covering the call | a data scope | `*` |
//! |---|---|---|---|---|
//! | a method marked `everywhere`, no target (`dyn.connect`, `auth.role_set`) | the door | admits | never (KEEL-31) | admits |
//! | a call into an untyped peer slot (`dyn.peer.shop.items.list`, slot grant `dyn.{peer}`) | the door | admits | **never** (KEEL-44) | admits |
//! | a method with a declared target | [`Gate::check`] on the target, as before | nothing | its chain | admits |
//! | a method with no target | [`Gate::check`], "held anywhere", as before | nothing | admits | admits |
//! | a method marked `everywhere` **and** a target (mis-declared) | `*` alone (KEEL-31), told no address | nothing | never | admits |
//! | a literal path through a slot (consent's `callers`, KEEL-31's literal grant) | as before: [`Gate::check`] / `*` | nothing | as before | admits |
//!
//! The dispatcher makes **one** [`DispatchedCall`] per dispatch, here
//! ([`dispatched`]): its address from the literal routed path, split at
//! every dot ([`CallAddress::of_segments`]), its grant the routed entry's.
//! A path whose address cannot be built — a segment outside `A–Z a–z 0–9 _
//! -`, an empty one, or one at or under a name that is both a method and a
//! child ([`named_twice`]) — has no address, and its door is decided on `*`
//! alone, never on a shorter address and never as "held anywhere".
//!
//! A call the door admitted carries the door into a remote child for exactly
//! that call ([`crate::call::Door`]; plexus-wire spec/12 `limit.door`).
//!
//! AUTH-13: before any of this, `params` must be an object (or absent):
//! the gate reads a target by name, and a bare value (`"MENGER-1"`, `[…]`)
//! names none — it would be decided as "held anywhere" while the method
//! deserialized it into its only parameter. A target that is neither a
//! scalar nor a list of scalars is refused too. Both are `InvalidParams`
//! (`error_kind: invalid_params`), whoever calls. Introspection stays open here: what it answers
//! is the caller's view (AUTH-4, [`super::view`]) — `_info` and every
//! `schema` answered per caller; this gate decides calls, not what is listed.
//!
//! # How a method receives its [`Reach`]
//!
//! The gate's answer — where the grant is held — rides into the method as
//! [`Reach`]: the dispatch runs the routed call inside its context
//! ([`crate::call`], RETURNS-47) — the stream it answers included — and
//! `#[plexus_macros::method]` hands a method that declares a `reach: Reach`
//! parameter (stripped from the schema, like `auth`) the value of
//! [`current_reach`]. A service without a gate dispatches with
//! [`Reach::everywhere`], said by its dispatch; outside a call
//! [`current_reach`] is an error, never everything (RETURNS-47: it fell back
//! to everywhere). The reach is live: [`Reach::allows`] / [`Reach::current`]
//! ask the gate again as it stands, which is how a stream checks each event
//! (IDENTITY-37).

use plexus_auth_core::grants::{CallAddress, DispatchedCall, Gate, Grant, Reach, Refusal};
use serde_json::Value;

use super::auth::AuthContext;
use super::plexus::{AuthzDenyReason, PlexusError};
use super::scope_gate::MethodGateInfo;

/// The reach of the call being dispatched: what the gate answered for its
/// grant — [`Reach::everywhere`] on a service without a gate, which its
/// dispatch says. RETURNS-47: **fail closed** — outside a call (code no
/// dispatch runs, a task spawned without its context handed to it,
/// [`crate::call::scope`]), and in a call that came through a hop (its
/// bound is [`crate::call::Hop::allows`]), it is an error
/// (`Unauthenticated`), never everything.
///
/// `#[plexus_macros::method]` calls this for a method that declares a
/// `reach: Reach` parameter, before the method's stream is built; the
/// stream runs in the call's context too, so reading it there answers the
/// same.
pub fn current_reach() -> Result<Reach, PlexusError> {
    let ctx = crate::call::context()?;
    ctx.reach().cloned().ok_or_else(|| crate::call::CallError::ThroughHop.into())
}

/// Run `fut` with `reach` as the [`current_reach`] of the call it runs in:
/// it narrows that call's reach, never widens it and never creates a call.
/// RETURNS-47: refused (`Unauthenticated`) outside a call, and when `reach`
/// holds a scope the call's does not (unless the call's is everywhere) —
/// it used to build an anonymous caller by hand. A test enters a call with
/// `plexus_core::call::test::in_call` (feature `test-util`).
///
/// ONE-7 (ONE-6 review round 2, L1): and on the door — a reach that holds
/// the activation ([`Reach::holds_activation`]) is taken only where the
/// call's does too, and a door reach (the activation held at an address, not
/// on `*`) only for the call's own grant: a door is one call's, never handed
/// to work inside another.
pub async fn with_reach<F: std::future::Future>(reach: Reach, fut: F) -> Result<F::Output, PlexusError> {
    let ctx = crate::call::context()?;
    let current = ctx.reach().ok_or(crate::call::CallError::ThroughHop)?;
    if let Err(why) = narrows(current, &reach) {
        return Err(PlexusError::Unauthenticated(why.into()));
    }
    Ok(crate::call::scope(ctx.with_reach(reach), fut).await)
}

/// [`with_reach`]'s rule: `Ok` when `reach` is within `current`.
fn narrows(current: &Reach, reach: &Reach) -> Result<(), &'static str> {
    let within = current.is_everywhere() || reach.held_on().iter().all(|s| current.held_on().contains(s));
    if !within {
        return Err("with_reach narrows a call's reach; it holds a scope the call does not");
    }
    if reach.holds_activation() && !current.holds_activation() {
        return Err("with_reach narrows a call's reach; it holds the activation, and the call does not");
    }
    if is_door(reach) && reach.grant() != current.grant() {
        return Err("with_reach narrows a call's reach; it is the door of another grant than the call's");
    }
    Ok(())
}

/// ONE-7: whether `reach` holds its activation at a door — on an address,
/// not on `*`.
pub(crate) fn is_door(reach: &Reach) -> bool {
    reach.holds_activation() && !reach.is_everywhere()
}

/// ONE-7 (review M1): whether the door `call` was admitted at is the
/// method's own — its grant names the call's own path, segment for segment
/// (a `{slot}` segment standing for the one name in its place: a typed
/// slot's `solar.{planet}.wipe` at `solar.mars.wipe`) — and not a slot's
/// whole grant above it (`dyn.{peer}` at `dyn.peer.vault.wipe`). Only an
/// own door runs a whole-activation method ([`crate::call::admits_everywhere`]);
/// a slot's opens the peer's ordinary methods and nothing more.
pub(crate) fn door_is_own(call: &DispatchedCall) -> bool {
    let path = call.at().path();
    let grant = call.grant().as_str();
    path.split('.').count() == grant.split('.').count()
        && path.split('.').zip(grant.split('.')).all(|(p, g)| p == g || is_slot_segment(g))
}

/// The shape of an own door's grant (`call`'s, [`door_is_own`]): the grant,
/// and — through an untyped peer slot (`peer_slot`, `dyn.{peer}`) — the
/// peer's name's segment open: `dyn.peer.{peer}.wipe` for the literal
/// `dyn.peer.vault.wipe`.
pub(crate) fn door_shape(call: &DispatchedCall, peer_slot: Option<&str>) -> String {
    let grant = call.grant().as_str();
    let Some(slot) = peer_slot else { return grant.to_string() };
    let at = slot.split('.').count();
    grant
        .split('.')
        .enumerate()
        .map(|(i, s)| if i == at { "{peer}" } else { s })
        .collect::<Vec<_>>()
        .join(".")
}

/// A grant's segment that stands for any one name (`{planet}`).
pub(crate) fn is_slot_segment(segment: &str) -> bool {
    segment.len() > 2 && segment.starts_with('{') && segment.ends_with('}')
}

/// What the gate decided for a call that may proceed: run it under this
/// reach — with the call the door admitted it at, if a door did (ONE-7) —
/// or (introspection) without one.
///
/// KEEL-59: and what the call is held to while it runs
/// ([`super::held`]): `Some(targets)` — every target the decision checked,
/// none for a call without one — is asked again when the grants generation
/// moves; `None` (a `public` method, a grant every signed-in caller holds)
/// is never asked again.
pub(crate) enum Admit {
    Reach(Reach, Option<DispatchedCall>, Option<Vec<String>>),
    Open,
}

/// ONE-7 · **the one place a [`DispatchedCall`] is made**: the call at the
/// literal routed `path` (`dyn.peer.shop.items.list`), its address split at
/// every dot ([`CallAddress::of_segments`]: the activation every segment but
/// the last, the method the last), paired with `grant`, the grant of the
/// entry the path was routed to. `None` when no address can be built — a
/// segment `of_segments` refuses (empty, `*`, `@`, `{`, a space, non-ASCII),
/// a path of one segment, or a path at or under a name its activation uses
/// for a method and a child alike (`ambiguous`, [`named_twice`]): that call
/// is decided as told no address — never on a shorter one.
///
/// A key cannot hold a dot here: every router of the path (this service's,
/// a child's, a peer's) splits it at every dot, so a dot in a key is two
/// segments everywhere, and an address scope deeper than a peer's name
/// covers what that peer routes beneath it.
pub(crate) fn dispatched(path: &str, grant: &Grant, ambiguous: &std::collections::HashSet<String>) -> Option<DispatchedCall> {
    let segments: Vec<&str> = path.split('.').collect();
    let (method, activation) = segments.split_last()?;
    let at = CallAddress::of_segments(activation, method).ok()?;
    let mut prefix = String::with_capacity(path.len());
    for (i, s) in segments.iter().enumerate() {
        if i > 0 {
            prefix.push('.');
        }
        prefix.push_str(s);
        if i > 0 && ambiguous.contains(&prefix) {
            return None;
        }
    }
    Some(DispatchedCall::new(at, grant.clone()))
}

/// ONE-7: the names `schema` gives both a method and a child (a static
/// child, a dynamic child's slot, a peer slot) — `/P` would cover both, so
/// such a name is refused at registration and has no address at dispatch.
pub fn named_twice(schema: &super::schema::PluginSchema) -> Vec<String> {
    use super::schema::MethodRole;
    let child = |r: &MethodRole| matches!(r, MethodRole::StaticChild | MethodRole::DynamicChild { .. } | MethodRole::Peer { .. });
    let mut twice: Vec<String> = schema
        .methods
        .iter()
        .filter(|m| matches!(m.role, MethodRole::Rpc) && schema.methods.iter().any(|c| c.name == m.name && child(&c.role)))
        .map(|m| m.name.clone())
        .collect();
    twice.sort();
    twice.dedup();
    twice
}

impl From<Refusal> for PlexusError {
    fn from(r: Refusal) -> Self {
        match r {
            Refusal::Unauthenticated => {
                PlexusError::Unauthenticated("sign in first: this method is not public".into())
            }
            Refusal::MissingGrant { grant, scope, roles, held_on } => PlexusError::Forbidden {
                reason: AuthzDenyReason::MissingGrant { grant, scope, roles, held_on },
            },
            Refusal::Ended { reason } => PlexusError::Unauthenticated(reason),
        }
    }
}

/// AUTH-11: the identity a call acts as — `auth` while its sign-in stands
/// ([`Gate::alive`]); once it has ended (signed out, expired, revoked),
/// nobody: the call is decided and dispatched as anonymous, and the second
/// value says why. A socket that signed out sees the anonymous view and
/// reaches only the `public` methods — not `auth.grant`.
pub(crate) fn standing<'a>(gate: &Gate, auth: Option<&'a AuthContext>) -> (Option<&'a AuthContext>, Option<String>) {
    match auth.map(|a| gate.alive(a)) {
        Some(Err(reason)) => (None, Some(reason)),
        _ => (auth, None),
    }
}

/// AUTH-11: an anonymous refusal of a sign-in that ended says so, rather
/// than "sign in first".
pub(crate) fn say_ended(e: PlexusError, ended: Option<&str>) -> PlexusError {
    match (e, ended) {
        (PlexusError::Unauthenticated(_), Some(reason)) => PlexusError::Unauthenticated(reason.to_string()),
        (e, _) => e,
    }
}

/// The target values a call names: `None` when the param is absent or
/// null; one string per element when it is a list. AUTH-13: a value the
/// gate cannot read as a scope — an object, or a list holding anything but
/// scalars — is refused, never skipped (skipped, it would be decided as
/// "no target": held anywhere).
pub(crate) fn target_values(params: &Value, param: &str) -> Result<Option<Vec<String>>, PlexusError> {
    let Some(v) = params.get(param) else { return Ok(None) };
    let one = |v: &Value| match v {
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        Value::Bool(b) => Some(b.to_string()),
        _ => None,
    };
    let unreadable = || {
        PlexusError::malformed_param(param, "names what this call acts on: a string, or a list of strings")
    };
    match v {
        Value::Null => Ok(None),
        Value::Array(items) => items.iter().map(|i| one(i).ok_or_else(unreadable)).collect::<Result<_, _>>().map(Some),
        other => one(other).map(|s| Some(vec![s])).ok_or_else(unreadable),
    }
}

/// AUTH-13: under a gate, a call's params are an object (or absent). A
/// bare value names no target, so the gate would decide it as "held
/// anywhere" — while a method of one parameter would take it as that
/// parameter.
fn params_shape(params: &Value) -> Result<(), PlexusError> {
    match params {
        Value::Object(_) | Value::Null => Ok(()),
        _ => Err(PlexusError::invalid_params(
            "params must be an object naming each parameter, e.g. {\"id\": \"…\"}: a gated method takes no bare value",
        )),
    }
}

/// ONE-7: a door's refusal as KEEL-31's says it — needed at `*` — whatever
/// address the gate names (plexus-auth-core names the activation's, `/dyn`):
/// the refusal a client reads for a whole-service method stays one shape,
/// and `held_on` (the data held) as it was. Only the scope's name changes.
fn said_at_everywhere(r: Refusal) -> Refusal {
    match r {
        Refusal::MissingGrant { grant, roles, held_on, .. } => {
            Refusal::MissingGrant { grant, scope: plexus_auth_core::grants::ScopeRef::Everywhere, roles, held_on }
        }
        other => other,
    }
}

/// ONE-7 · **which entries the door decides** — the one rule, applied when
/// the gate's index is built ([`MethodGateInfo::door`]): a method marked
/// `everywhere` that declares no target, and an untyped peer slot. A method
/// that declares a target is never decided at the door, whatever else it
/// says: its target is checked ([`Gate::check`]), or, marked `everywhere`
/// as well, it is held to `*` alone (KEEL-31), told no address.
pub(crate) fn door_shaped(everywhere: bool, target: Option<&str>, untyped_peer_slot: bool) -> bool {
    match target {
        Some(_) => false,
        None => everywhere || untyped_peer_slot,
    }
}

/// Decide one call. `full_path` is the dotted method as dispatched;
/// `service_ns` the service's own namespace; `ambiguous` the paths that name
/// a method and a child alike ([`dispatched`]).
#[allow(clippy::too_many_arguments)]
pub(crate) fn decide(
    gate: &Gate,
    service_ns: &str,
    full_path: &str,
    info: Option<&MethodGateInfo>,
    params: &Value,
    auth: Option<&AuthContext>,
    signed_in_grants: &std::collections::BTreeSet<String>,
    ambiguous: &std::collections::HashSet<String>,
) -> Result<Admit, PlexusError> {
    params_shape(params)?;
    let (ns, method) = full_path.split_once('.').unwrap_or((full_path, ""));
    let introspection = method == "schema"
        || method.ends_with(".schema")
        || (ns == service_ns && matches!(method, "hash" | "hashes" | "ir"));
    if introspection {
        return Ok(Admit::Open);
    }
    let grant = Grant::new(info.and_then(|i| i.grant.clone()).unwrap_or_else(|| full_path.to_string()));
    // ONE-7: a method that acts on the whole activation, or a call into an
    // untyped peer slot, is decided at the door of the call dispatched —
    // an address scope covering it, or `*` — and never on a data scope.
    // No address: `*` alone (KEEL-31's rule), never "held anywhere".
    if info.is_some_and(|i| i.door) {
        return Ok(match dispatched(full_path, &grant, ambiguous) {
            Some(call) => Admit::Reach(gate.check_everywhere_at(auth, &call).map_err(said_at_everywhere)?, Some(call), Some(Vec::new())),
            None => Admit::Reach(gate.check_everywhere(auth, &grant)?, None, Some(Vec::new())),
        });
    }
    // KEEL-31: a method that acts on the whole service is decided on `*`,
    // whatever else it says — the rule is the gate's, not the method's.
    if info.is_some_and(|i| i.everywhere) {
        return Ok(Admit::Reach(gate.check_everywhere(auth, &grant)?, None, Some(Vec::new())));
    }
    if info.is_some_and(|i| i.public) {
        return Ok(Admit::Reach(gate.reach_of_public(auth, &grant), None, None));
    }
    // AUTH-5: what every signed-in caller reaches (`auth.whoami`,
    // `auth.logout`, `auth.requires`) — whatever its roles or ceiling, but
    // never anonymously.
    if signed_in_grants.contains(grant.as_str()) {
        if auth.and_then(|a| a.principal()).is_none() {
            return Err(Refusal::Unauthenticated.into());
        }
        return Ok(Admit::Reach(gate.reach_of_public(auth, &grant), None, None));
    }
    let targets = match info.and_then(|i| i.target.as_deref()) {
        Some(param) => target_values(params, param)?,
        None => None,
    };
    match targets {
        None => Ok(Admit::Reach(gate.check(auth, &grant, None)?, None, Some(Vec::new()))),
        Some(values) if values.is_empty() => Ok(Admit::Reach(gate.check(auth, &grant, None)?, None, Some(values))),
        Some(values) => {
            let mut reach = None;
            for v in &values {
                reach = Some(gate.check(auth, &grant, Some(v))?);
            }
            // KEEL-59: the targets it was decided on, kept with the call
            // (moved, not copied) to be asked again on a move.
            Ok(Admit::Reach(reach.expect("non-empty"), None, Some(values)))
        }
    }
}

/// KEEL-31: a backstop that does not depend on the macro — each of
/// `methods` in `schema` is marked `everywhere`, or why not. A service
/// whose own whole-service methods lost the mark (built with a macro that
/// dropped the word) refuses to start rather than admit a scoped holder.
pub fn require_everywhere(schema: &super::schema::PluginSchema, methods: &[&str]) -> Result<(), String> {
    let unmarked: Vec<&str> = methods
        .iter()
        .copied()
        .filter(|name| !schema.methods.iter().any(|m| m.name == *name && m.everywhere))
        .collect();
    if unmarked.is_empty() {
        return Ok(());
    }
    Err(format!(
        "{}: {} act on the whole service and must be marked `everywhere` in its schema; they are not — \
         built with a plexus-macros that does not know the word (it needs 0.11.1 or later)",
        schema.namespace,
        unmarked.iter().map(|m| format!("{}.{m}", schema.namespace)).collect::<Vec<_>>().join(", "),
    ))
}

/// A refusal as a client reads it back from an error stream item — the
/// typed view of the `forbidden` shape [`super::types::spec_fields`] writes.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ForbiddenItem {
    pub grant: String,
    pub scope: String,
    #[serde(default)]
    pub roles: Vec<String>,
    #[serde(default)]
    pub held_on: Vec<String>,
    pub message: String,
}

impl ForbiddenItem {
    /// The refusal an error item carries, when it is a missing grant.
    pub fn from_item(item: &Value) -> Option<Self> {
        if item.get("type")?.as_str()? != "error" || item.get("error_kind")?.as_str()? != "forbidden" {
            return None;
        }
        item.get("grant")?;
        serde_json::from_value(item.clone()).ok()
    }
}

#[cfg(test)]
mod tests {
    //! ONE-7: the routing to the door, shape by shape — an operator held on
    //! `/ops` alone, and an admin of the data scope `KILN`.
    use super::*;
    use plexus_auth_core::grants::{Membership, Memberships, Resolve, RoleTable, ScopeRef};
    use serde_json::json;
    use std::collections::{BTreeSet, HashSet};
    use std::sync::Arc;

    const OPERATOR: &str = "key:0101010101010101010101010101010101010101010101010101010101010101";
    const KILN_ADMIN: &str = "key:0303030303030303030303030303030303030303030303030303030303030303";
    const GARDENER: &str = "key:0202020202020202020202020202020202020202020202020202020202020202";

    struct Held;
    impl Memberships for Held {
        fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
            let at = |role: &str, scope: &str| Membership { principal: who.clone(), role: plexus_auth_core::RoleName::new(role), scope: ScopeRef::parse(scope) };
            match who.to_string().as_str() {
                OPERATOR => vec![at("operator", "/ops")],
                KILN_ADMIN => vec![at("admin", "KILN")],
                GARDENER => vec![at("operator", "/ops.*")],
                _ => vec![],
            }
        }
    }
    struct Kiln;
    impl Resolve for Kiln {
        fn chain(&self, t: &str) -> Option<Vec<ScopeRef>> {
            Some(vec![ScopeRef::named(t.split('-').next().unwrap_or(t)), ScopeRef::Everywhere])
        }
    }

    fn gate() -> Gate {
        let roles = RoleTable::from_lists([("operator", ["ops.grow", "ops.get", "ops.misdeclared", "ops.tally", "ops.{peer}", "ops.{box}", "ops.{planet}.wipe", "ops.peer.shop.wipe"])]);
        Gate::new(Arc::new(Held), Arc::new(roles), Arc::new(Kiln))
    }

    fn who(p: &str) -> AuthContext {
        AuthContext::for_principal(&p.parse().unwrap(), "s", vec![], Value::Null)
    }

    fn info(grant: &str, everywhere: bool, target: Option<&str>, peer_slot: bool) -> MethodGateInfo {
        MethodGateInfo {
            grant: Some(grant.into()),
            everywhere,
            target: target.map(str::to_string),
            door: door_shaped(everywhere, target, peer_slot),
            ..Default::default()
        }
    }

    /// Admitted, and whether at a door.
    fn decided(caller: &str, path: &str, info: &MethodGateInfo, params: Value) -> Result<bool, PlexusError> {
        match decide(&gate(), "svc", path, Some(info), &params, Some(&who(caller)), &BTreeSet::new(), &HashSet::new())? {
            Admit::Reach(_, door, _) => Ok(door.is_some()),
            Admit::Open => Ok(false),
        }
    }

    #[test]
    fn a_whole_activation_method_is_decided_at_its_door() {
        let grow = info("ops.grow", true, None, false);
        assert_eq!(decided(OPERATOR, "ops.grow", &grow, json!({})).unwrap(), true);
        assert!(matches!(decided(KILN_ADMIN, "ops.grow", &grow, json!({})), Err(PlexusError::Forbidden { .. })), "KEEL-31");
    }

    #[test]
    fn an_untyped_peer_slot_is_decided_at_the_peer_s_door() {
        let peer = info("ops.{peer}", false, None, true);
        assert_eq!(decided(OPERATOR, "ops.peer.shop.look", &peer, json!({})).ok(), None, "`/ops` is ops' own: no prefix rule");
        assert!(matches!(decided(KILN_ADMIN, "ops.peer.shop.look", &peer, json!({})), Err(PlexusError::Forbidden { .. })), "KEEL-44");
    }

    #[test]
    fn a_data_method_is_decided_on_its_target_never_at_a_door() {
        let get = info("ops.get", false, Some("id"), false);
        assert!(decided(OPERATOR, "ops.get", &get, json!({ "id": "KILN-3" })).is_err(), "an address holds no data");
        assert_eq!(decided(KILN_ADMIN, "ops.get", &get, json!({ "id": "KILN-3" })).unwrap(), false);
        let tally = info("ops.tally", false, None, false);
        assert!(decided(OPERATOR, "ops.tally", &tally, json!({})).is_err(), "no target: held anywhere, on data");
        assert_eq!(decided(KILN_ADMIN, "ops.tally", &tally, json!({})).unwrap(), false);
    }

    /// A method marked `everywhere` that also declares a target is decided
    /// on `*` alone (KEEL-31) — the door would never check its target.
    #[test]
    fn a_misdeclared_data_method_is_not_reachable_through_the_door() {
        let bad = info("ops.misdeclared", true, Some("id"), false);
        assert!(!bad.door);
        assert!(matches!(decided(OPERATOR, "ops.misdeclared", &bad, json!({ "id": "KILN-3" })), Err(PlexusError::Forbidden { .. })));
        assert!(matches!(decided(KILN_ADMIN, "ops.misdeclared", &bad, json!({ "id": "KILN-3" })), Err(PlexusError::Forbidden { .. })));
    }

    /// An opaque dynamic child is this service's own: held anywhere, as before.
    #[test]
    fn a_dynamic_child_slot_is_held_anywhere_as_before() {
        let boxes = info("ops.{box}", false, None, false);
        assert!(!boxes.door);
        assert!(decided(OPERATOR, "ops.b1.look", &boxes, json!({})).is_err());
        assert_eq!(decided(KILN_ADMIN, "ops.b1.look", &boxes, json!({})).unwrap(), false);
    }

    #[test]
    fn a_call_is_dispatched_from_its_literal_path() {
        let none = HashSet::new();
        let g = Grant::new("ops.{peer}");
        let call = dispatched("ops.peer.shop.items.list", &g, &none).unwrap();
        assert_eq!((call.at().activation(), call.at().method(), call.grant()), ("ops.peer.shop.items", "list", &g));
        for bad in ["ops", "ops..x", "ops.sh*p.x", "ops.sh p.x", "ops.{peer}.x", ""] {
            assert!(dispatched(bad, &g, &none).is_none(), "{bad}");
        }
        let ambiguous: HashSet<String> = ["ops.peer".to_string()].into();
        assert!(dispatched("ops.peer", &g, &ambiguous).is_none(), "a name both a method and a child");
        assert!(dispatched("ops.peer.shop.look", &g, &ambiguous).is_none(), "and everything under it");
        assert!(dispatched("ops.peers", &g, &ambiguous).is_some());
    }

    #[test]
    fn a_name_given_twice_is_found() {
        use crate::plexus::schema::{MethodRole, MethodSchema, PluginSchema};
        let mut s = PluginSchema::leaf("dyn", "1", "d", vec![MethodSchema::new("peers", "d", "h")]);
        s.methods.push(MethodSchema::new("peer", "d", "h"));
        s.methods.push(MethodSchema::new("peer", "d", "h").with_role(MethodRole::Peer { list_method: None, search_method: None, interface: None }));
        assert_eq!(named_twice(&s), ["peer"]);
    }

    /// Review M1: the backstop decides from the door the dispatch recorded.
    /// Run inside a call admitted at it, `grant` (as the macro names it)
    /// passes only for the door's own method: not another method's of the
    /// same name run in-process (`x.grow` on `ops.grow`'s door), not one
    /// on a slot's whole grant (`ops.{peer}` at a peer's address).
    #[test]
    fn the_backstop_takes_only_the_methods_own_door() {
        let ran = |caller: &str, path: &str, info: &MethodGateInfo, peer_slot: Option<&str>, grant: &str| -> bool {
            let auth = who(caller);
            let Ok(Admit::Reach(reach, Some(call), _)) = decide(&gate(), "svc", path, Some(info), &json!({}), Some(&auth), &BTreeSet::new(), &HashSet::new()) else {
                panic!("{path}: not admitted at a door");
            };
            let ctx = crate::call::CallContext::admitted_by_gate(Some(&auth), reach).at_door(call, peer_slot);
            futures::executor::block_on(crate::call::scope(ctx, async { crate::call::admits_everywhere(grant) })).is_ok()
        };
        let grow = info("ops.grow", true, None, false);
        assert!(ran(OPERATOR, "ops.grow", &grow, None, "ops.grow"));
        assert!(!ran(OPERATOR, "ops.grow", &grow, None, "x.grow"), "another activation's `grow`, in process");
        assert!(!ran(OPERATOR, "ops.grow", &grow, None, "ops.tally"));
        // A typed slot's own grant: its `{planet}` stands for the namespace there.
        let wipe = info("ops.{planet}.wipe", true, None, false);
        assert!(ran(GARDENER, "ops.mars.wipe", &wipe, None, "planet.wipe"));
        assert!(!ran(GARDENER, "ops.mars.wipe", &wipe, None, "planet.look"));
        // The slot's whole grant at a peer's address: ordinary methods only.
        let slot = info("ops.{peer}", false, None, true);
        assert!(!ran(GARDENER, "ops.peer.shop.wipe", &slot, Some("ops.{peer}"), "shop.wipe"));
        assert!(!ran(GARDENER, "ops.peer.shop.wipe", &slot, Some("ops.{peer}"), "leaf.wipe"));
        // The peer's literal grant there: its own door — the peer's name open
        // (an in-process peer's namespace is not its name).
        let literal = MethodGateInfo { door: true, ..Default::default() };
        assert!(ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "shop.wipe"));
        assert!(ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "leaf.wipe"));
        assert!(!ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "leaf.look"));
        // Without the slot said, the literal door's namespace is the peer's name.
        assert!(!ran(GARDENER, "ops.peer.shop.wipe", &literal, None, "leaf.wipe"));
    }
}