plexus-auth-core 0.2.2

Sealed-type primitives for the Plexus auth framework: AuthContext, VerifiedUser, Principal.
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
//! AUTH-2: **grants, roles, memberships, ceilings — and the gate** that asks
//! them on every call.
//!
//! The model (AUTH-1, owner 2026-10-10: "every method should be its own grant
//! inherently and require a role to have it explicitly listed if not admin
//! role"):
//!
//! - A [`Grant`] is the right to call one method: `<activation>.<method>`
//!   (`tickets.set_status`). Inherent — every method has exactly one and
//!   nothing declares it.
//! - A role is a named, explicit list of grants ([`GrantSet::Listed`]); the
//!   built-in [`ADMIN`] role alone holds every grant ([`GrantSet::All`]).
//!   [`RoleTable`] is an in-memory [`Roles`] in which a role may list
//!   another role (inclusion), flattened as it is defined.
//! - A [`Membership`] says a principal holds a role on a scope
//!   ([`ScopeRef::Named`]) or everywhere ([`ScopeRef::Everywhere`], `*`).
//! - A *target* is the param that locates the resource a call acts on; the
//!   service's [`Resolve`] maps its value to the scopes it lives in,
//!   innermost first (`MENGER-12` → `[MENGER, *]`).
//! - A [`Ceiling`] is a session's upper bound (IDENTITY-40): `role@SCOPE` or
//!   `grant@SCOPE` entries. A session may carry several layers; every layer
//!   must allow a check, as the memberships must.
//!
//! [`Gate::check`] answers one call: allowed — with the [`Reach`] the method
//! answers from — or a [`Refusal`] that names what was needed. Everything is
//! answered from memory: the three service traits are synchronous and must
//! not do I/O.
//!
//! # Relation to R-5's [`ScopeRegistry`](crate::ScopeRegistry)
//!
//! R-5's registry maps *token-claimed roles* to dotted capability scopes and
//! knows nothing of where a role is held. The grant model keeps its words —
//! a grant is exactly R-5's implicit `<activation>.<method>` scope, and
//! [`RoleName`] is the same type — and adds the *where*: memberships on
//! scopes, targets resolved through a chain, ceilings. Both gates can be
//! configured on one hub; a hub with neither dispatches as before.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::audit::RoleName;
use crate::auth::AuthContext;
use crate::identity::Principal;

/// The built-in role that holds every grant. No other role holds anything it
/// does not list.
pub const ADMIN: &str = "admin";

/// The metadata key a session's ceiling rides under (IDENTITY-42's
/// `menger_session` sessions write it): either a list of `role@SCOPE` /
/// `grant@SCOPE` strings (one layer) or a list of such lists (layers, every
/// one of which must allow a check).
pub const CEILING_KEY: &str = "ceiling";

// ---------------------------------------------------------------------------
// Grant
// ---------------------------------------------------------------------------

/// The right to call one method: `<activation>.<method>`, e.g.
/// `tickets.set_status`. Every method has exactly one; nothing declares it.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Grant(String);

impl Grant {
    /// Wrap a dotted method path as a grant. Unvalidated, as wire-decoded
    /// values are.
    pub fn new(path: impl Into<String>) -> Self {
        Self(path.into())
    }

    /// The grant of `method` on `activation`: `<activation>.<method>`.
    pub fn of(activation: &str, method: &str) -> Self {
        Self(format!("{activation}.{method}"))
    }

    /// The dotted path.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Grant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

// ---------------------------------------------------------------------------
// ScopeRef
// ---------------------------------------------------------------------------

/// Where a role is held: everywhere (`*`) or one named scope (`MENGER`).
/// What a name means — a shortcode, a tenant, a project — is the service's;
/// the gate only compares names and asks [`Resolve::chain`] how they nest.
///
/// On the wire, a plain string: `"*"` or the name.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ScopeRef {
    /// `*`: every scope.
    Everywhere,
    /// One named scope, and whatever the service nests under it.
    Named(String),
}

impl ScopeRef {
    /// `"*"` → [`ScopeRef::Everywhere`]; anything else (trimmed) → named.
    pub fn parse(text: &str) -> Self {
        match text.trim() {
            "*" => Self::Everywhere,
            other => Self::Named(other.to_string()),
        }
    }

    /// A named scope.
    pub fn named(name: impl Into<String>) -> Self {
        Self::Named(name.into())
    }

    /// `"*"` or the name.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Everywhere => "*",
            Self::Named(n) => n,
        }
    }

    /// Whether this is `*`.
    pub fn is_everywhere(&self) -> bool {
        matches!(self, Self::Everywhere)
    }
}

impl fmt::Display for ScopeRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for ScopeRef {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for ScopeRef {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        Ok(Self::parse(&s))
    }
}

// ---------------------------------------------------------------------------
// GrantSet, RoleOrGrant, Membership, Ceiling
// ---------------------------------------------------------------------------

/// What a role holds: every grant ([`ADMIN`]) or exactly those it lists.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GrantSet {
    /// Every grant — the admin role, and only it by default.
    All,
    /// Exactly these grants.
    Listed(BTreeSet<Grant>),
}

impl GrantSet {
    /// Whether the set holds `grant`.
    pub fn contains(&self, grant: &Grant) -> bool {
        match self {
            Self::All => true,
            Self::Listed(set) => set.contains(grant),
        }
    }

    /// A listed set from anything that names grants.
    pub fn listed<I, G>(grants: I) -> Self
    where
        I: IntoIterator<Item = G>,
        G: Into<String>,
    {
        Self::Listed(grants.into_iter().map(|g| Grant::new(g)).collect())
    }
}

/// One ceiling entry's left side: a role (`editor`) or a single grant
/// (`tickets.get`). A dotted name is a grant; a bare one is a role.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum RoleOrGrant {
    Role(RoleName),
    Grant(Grant),
}

impl RoleOrGrant {
    /// A dotted name is a grant, a bare one a role.
    pub fn parse(text: &str) -> Self {
        let t = text.trim();
        if t.contains('.') {
            Self::Grant(Grant::new(t))
        } else {
            Self::Role(RoleName::new(t))
        }
    }
}

impl fmt::Display for RoleOrGrant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Role(r) => write!(f, "{r}"),
            Self::Grant(g) => write!(f, "{g}"),
        }
    }
}

/// A principal holds a role on a scope: `key:ac79… is editor on MENGER`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Membership {
    pub principal: Principal,
    pub role: RoleName,
    pub scope: ScopeRef,
}

/// A session's upper bound (IDENTITY-40): `(role or grant, scope)` entries,
/// spelled `editor@MENGER-12`, `tickets.get@*`. A check passes a ceiling
/// when some entry's scope is in the target's chain and the entry allows the
/// grant (the grant itself, or a role listing it).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Ceiling(pub Vec<(RoleOrGrant, ScopeRef)>);

/// Why a ceiling could not be read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CeilingError(pub String);

impl fmt::Display for CeilingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for CeilingError {}

impl Ceiling {
    /// One `role@SCOPE` or `grant@SCOPE` entry.
    pub fn entry(text: &str) -> Result<(RoleOrGrant, ScopeRef), CeilingError> {
        let (left, scope) = text
            .trim()
            .split_once('@')
            .ok_or_else(|| CeilingError(format!("`{}` is not role@SCOPE or grant@SCOPE", text.trim())))?;
        if left.trim().is_empty() || scope.trim().is_empty() {
            return Err(CeilingError(format!("`{}` is not role@SCOPE or grant@SCOPE", text.trim())));
        }
        Ok((RoleOrGrant::parse(left), ScopeRef::parse(scope)))
    }

    /// A ceiling from its entries' text.
    pub fn parse<I, S>(entries: I) -> Result<Self, CeilingError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        entries
            .into_iter()
            .map(|e| Self::entry(e.as_ref()))
            .collect::<Result<Vec<_>, _>>()
            .map(Ceiling)
    }

    /// The entries as the wire says them: `role@SCOPE` each.
    pub fn text(&self) -> Vec<String> {
        self.0.iter().map(|(rg, s)| format!("{rg}@{s}")).collect()
    }

    /// The ceilings an identity's metadata carries under [`CEILING_KEY`]:
    /// none → `[]`; a list of strings → one layer; a list of lists → one
    /// layer each. Anything else is an error, and a caller whose ceiling
    /// cannot be read must be refused, never widened.
    pub fn layers_of(ctx: &AuthContext) -> Result<Vec<Ceiling>, CeilingError> {
        let Some(v) = ctx.metadata.get(CEILING_KEY) else {
            return Ok(Vec::new());
        };
        let unreadable = || CeilingError("this session's ceiling cannot be read: sign in again".into());
        let items = v.as_array().ok_or_else(unreadable)?;
        if items.iter().all(|i| i.is_string()) {
            let texts: Vec<&str> = items.iter().filter_map(|i| i.as_str()).collect();
            return Ok(vec![Self::parse(texts).map_err(|_| unreadable())?]);
        }
        items
            .iter()
            .map(|layer| {
                let entries = layer.as_array().ok_or_else(unreadable)?;
                let texts = entries
                    .iter()
                    .map(|e| e.as_str().ok_or_else(unreadable))
                    .collect::<Result<Vec<_>, _>>()?;
                Self::parse(texts).map_err(|_| unreadable())
            })
            .collect()
    }
}

/// PERF-15: everything [`Gate::held_on`] reads of one signed-in caller,
/// besides the grants generation — what its principal holds (each
/// membership's role and scope, as a set) and its session's ceiling layers.
/// Two callers with equal fingerprints hold the same grants on the same
/// scopes, whoever they are: at one generation the gate answers them alike.
/// So a service keeps what a caller may see (its view, AUTH-4) by it —
/// one entry shared by every caller holding the same, dropped when the
/// generation moves. Compared whole, never by a digest: two fingerprints are
/// one key only when they are equal. [`Gate::fingerprint`] takes one,
/// [`Gate::held_on_by`] answers from it.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Fingerprint {
    /// (role, scope) of each membership, sorted, each once.
    held: Vec<(RoleName, ScopeRef)>,
    /// The session's ceiling, as [`Ceiling::layers_of`] reads it (an
    /// unreadable one is one empty layer, as the gate reads it).
    layers: Vec<Ceiling>,
}

// ---------------------------------------------------------------------------
// What a service supplies
// ---------------------------------------------------------------------------

/// Who holds which role where (menger: its members table, cached). Answered
/// from memory: no I/O on a call.
pub trait Memberships: Send + Sync {
    fn held(&self, who: &Principal) -> Vec<Membership>;

    /// What `who` holds of its own — without a membership the service
    /// gives every signed-in principal (menger's `everyone` grant). It
    /// decides whether `who` is still waiting for an admin (`auth.waiting`,
    /// `auth.signup`); the gate reads [`Memberships::held`]. The default is
    /// `held`: a service with no such grant has nothing to leave out.
    fn own_held(&self, who: &Principal) -> Vec<Membership> {
        self.held(who)
    }
}

/// Role → grants (defaults declared in code, edits as data). Answered from
/// memory. [`ADMIN`] holds every grant whatever this answers.
pub trait Roles: Send + Sync {
    /// What `role` holds; `None` for a role this service does not know
    /// (it holds nothing).
    fn grants(&self, role: &RoleName) -> Option<GrantSet>;

    /// Every role this service knows, so a refusal can name the roles that
    /// list a grant. The default knows none (a refusal then names only
    /// [`ADMIN`]).
    fn names(&self) -> Vec<RoleName> {
        Vec::new()
    }
}

/// Where a target lives. Answered from memory.
pub trait Resolve: Send + Sync {
    /// The scopes a target lives in, innermost first, ending in
    /// [`ScopeRef::Everywhere`]: `"MENGER-12"` → `[MENGER-12, MENGER, *]`
    /// (or, for a service whose memberships are per shortcode,
    /// `[MENGER, *]`). `None`: the value locates nothing — the call is
    /// refused.
    ///
    /// The gate also asks it about **scope names** (a membership's or a
    /// ceiling's): `chain("MENGER")` → `[MENGER, PLEXUS, *]`, to tell which
    /// of two scopes lies within the other when it narrows a reach by a
    /// ceiling. A service that cannot answer for a name returns `None`, and
    /// two different names are then taken as disjoint.
    fn chain(&self, target: &str) -> Option<Vec<ScopeRef>>;
}

// ---------------------------------------------------------------------------
// RoleTable — an in-memory Roles with inclusion
// ---------------------------------------------------------------------------

/// Why [`RoleTable::define`] refused a role.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RoleTableError {
    /// An entry named a role that is not (yet) defined. A role may only
    /// include roles defined before it, which is what keeps inclusion
    /// acyclic.
    UnknownRole { role: String, includes: String },
}

impl fmt::Display for RoleTableError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownRole { role, includes } => write!(
                f,
                "role {role} includes {includes}, which is not defined before it"
            ),
        }
    }
}

impl std::error::Error for RoleTableError {}

/// An in-memory [`Roles`]: each role an explicit list of grants, where an
/// entry may also name an earlier role (inclusion, flattened when defined).
/// [`ADMIN`] is built in.
///
/// ```
/// use plexus_auth_core::grants::{Grant, RoleTable, Roles};
/// use plexus_auth_core::RoleName;
///
/// let roles = RoleTable::new()
///     .define("viewer", ["tickets.get", "tickets.list"]).unwrap()
///     .define("editor", ["viewer", "tickets.set_status"]).unwrap();
/// let editor = roles.grants(&RoleName::new("editor")).unwrap();
/// assert!(editor.contains(&Grant::new("tickets.get")));
/// ```
#[derive(Debug, Clone, Default)]
pub struct RoleTable {
    roles: BTreeMap<RoleName, GrantSet>,
}

impl RoleTable {
    /// The table with only the built-in [`ADMIN`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Define (or extend) `role`: each entry a grant (dotted) or an earlier
    /// role (bare), whose grants are included. Defining a role again adds to
    /// it, which is how several activations' defaults for one role name
    /// merge.
    pub fn define<I, S>(mut self, role: &str, entries: I) -> Result<Self, RoleTableError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let name = RoleName::new(role);
        let mut set = match self.roles.remove(&name) {
            Some(GrantSet::Listed(s)) => s,
            Some(GrantSet::All) => {
                self.roles.insert(name, GrantSet::All);
                return Ok(self);
            }
            None => BTreeSet::new(),
        };
        let mut all = name.as_str() == ADMIN;
        for entry in entries {
            let e = entry.as_ref().trim();
            if e.contains('.') {
                set.insert(Grant::new(e));
                continue;
            }
            if e == ADMIN {
                all = true;
                continue;
            }
            match self.roles.get(&RoleName::new(e)) {
                Some(GrantSet::All) => all = true,
                Some(GrantSet::Listed(inc)) => set.extend(inc.iter().cloned()),
                None => {
                    return Err(RoleTableError::UnknownRole { role: role.to_string(), includes: e.to_string() })
                }
            }
        }
        self.roles.insert(name, if all { GrantSet::All } else { GrantSet::Listed(set) });
        Ok(self)
    }

    /// Replace `role`'s grants outright (an admin's edit: the store wins).
    pub fn set(&mut self, role: &str, grants: GrantSet) {
        self.roles.insert(RoleName::new(role), grants);
    }

    /// A table from already-flat lists (`role → [grant, …]`), as a schema's
    /// `roles` carries them; lists for one role name merge.
    pub fn from_lists<'a, I, G>(lists: I) -> Self
    where
        I: IntoIterator<Item = (&'a str, G)>,
        G: IntoIterator,
        G::Item: AsRef<str>,
    {
        let mut table = Self::new();
        for (role, grants) in lists {
            let name = RoleName::new(role);
            let grants: Vec<Grant> = grants.into_iter().map(|g| Grant::new(g.as_ref().trim())).collect();
            match table.roles.entry(name) {
                std::collections::btree_map::Entry::Occupied(mut o) => {
                    if let GrantSet::Listed(s) = o.get_mut() {
                        s.extend(grants);
                    }
                }
                std::collections::btree_map::Entry::Vacant(v) => {
                    v.insert(if role == ADMIN { GrantSet::All } else { GrantSet::Listed(grants.into_iter().collect()) });
                }
            }
        }
        table
    }
}

impl Roles for RoleTable {
    fn grants(&self, role: &RoleName) -> Option<GrantSet> {
        if role.as_str() == ADMIN {
            return Some(GrantSet::All);
        }
        self.roles.get(role).cloned()
    }

    fn names(&self) -> Vec<RoleName> {
        self.roles.keys().cloned().collect()
    }
}

// ---------------------------------------------------------------------------
// Refusal
// ---------------------------------------------------------------------------

/// Why the gate refused a call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Refusal {
    /// No principal: only `public` methods are reachable anonymously.
    Unauthenticated,
    /// The caller does not hold `grant` on `scope` (within its ceiling).
    MissingGrant {
        /// The grant the call needed.
        grant: Grant,
        /// Where it was needed: the target's innermost scope, or `*` for a
        /// method without a target (held anywhere would have done).
        scope: ScopeRef,
        /// The roles that list the grant ([`ADMIN`] last).
        roles: Vec<RoleName>,
        /// Where the caller does hold it (within its ceiling).
        held_on: Vec<ScopeRef>,
    },
    /// AUTH-11: the caller signed in, but that sign-in no longer stands
    /// (signed out, expired, revoked) — it proves no one.
    Ended {
        /// Why, in words for the caller ("you have signed out: sign in
        /// again").
        reason: String,
    },
}

impl fmt::Display for Refusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unauthenticated => f.write_str("sign in first"),
            Self::Ended { reason } => f.write_str(reason),
            Self::MissingGrant { grant, scope, .. } => write!(f, "needs {grant} on {scope}"),
        }
    }
}

impl std::error::Error for Refusal {}

// ---------------------------------------------------------------------------
// Reach
// ---------------------------------------------------------------------------

/// Where a call may act: the scopes the caller holds the method's grant on
/// (within its ceiling), handed to the method beside `auth`. A read without a
/// target (`list`, `watch`) answers only from these.
///
/// A reach is **live** when it came from a gate: [`Reach::allows`] and
/// [`Reach::current`] ask the gate again, as memberships, roles and the
/// ceiling stand *now* — so a stream checks each event (IDENTITY-37: a role
/// revoked reaches an open stream at its next event). A hub without a gate
/// hands every method [`Reach::everywhere`], which allows everything.
#[derive(Clone)]
pub struct Reach {
    held_on: Vec<ScopeRef>,
    live: Option<Live>,
}

#[derive(Clone)]
struct Live {
    gate: Gate,
    caller: Option<AuthContext>,
    grant: Grant,
}

impl fmt::Debug for Reach {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Reach")
            .field("held_on", &self.held_on)
            .field("grant", &self.live.as_ref().map(|l| l.grant.as_str()))
            .finish()
    }
}

impl PartialEq for Reach {
    /// Two reaches are equal when they hold the same scopes for the same
    /// grant (the gate behind them is not compared).
    fn eq(&self, other: &Self) -> bool {
        self.held_on == other.held_on && self.grant() == other.grant()
    }
}

impl Reach {
    /// Everything — what a method receives on a hub without a gate (login
    /// off), as today.
    pub fn everywhere() -> Self {
        Self { held_on: vec![ScopeRef::Everywhere], live: None }
    }

    /// Whether the grant is held on `*`.
    pub fn is_everywhere(&self) -> bool {
        self.held_on.iter().any(ScopeRef::is_everywhere)
    }

    /// Whether the grant is held nowhere (a `public` method called by a
    /// caller who holds no role listing it).
    pub fn is_empty(&self) -> bool {
        self.held_on.is_empty()
    }

    /// The scopes the grant is held on; `[*]` when everywhere.
    pub fn held_on(&self) -> &[ScopeRef] {
        &self.held_on
    }

    /// The grant this reach is for; `None` on a hub without a gate.
    pub fn grant(&self) -> Option<&Grant> {
        self.live.as_ref().map(|l| &l.grant)
    }

    /// POLYGLOT-5: the grants generation of the gate this reach came from
    /// (BIDIR-8) — a call held open elsewhere (a child service's stream)
    /// asks [`Reach::current`] again only when it moved. `None` without a
    /// gate.
    pub fn generation(&self) -> Option<&GrantsGeneration> {
        self.live.as_ref().map(|l| l.gate.generation())
    }

    /// Whether the call may act on `target` — asked of the gate as it
    /// stands now. Without a gate: always.
    pub fn allows(&self, target: &str) -> bool {
        match &self.live {
            None => self.is_everywhere(),
            Some(l) => l.gate.check(l.caller.as_ref(), &l.grant, Some(target)).is_ok(),
        }
    }

    /// The reach as it stands now: `None` once the grant is held nowhere (a
    /// stream should end). Without a gate: unchanged.
    pub fn current(&self) -> Option<Reach> {
        match &self.live {
            None => Some(self.clone()),
            Some(l) => l.gate.check(l.caller.as_ref(), &l.grant, None).ok(),
        }
    }

    /// FRAME-5: [`Reach::current`] with the gate's refusal kept — `Err`
    /// says why the grant is held nowhere now: [`Refusal::Ended`] when the
    /// sign-in no longer stands (signed out, expired, revoked session),
    /// [`Refusal::MissingGrant`] when the grants moved away,
    /// [`Refusal::Unauthenticated`] when the caller proves no one. A held
    /// open call that must say *why* it ends (a watch's typed reason) asks
    /// this; one that only needs to know whether asks `current`. Without a
    /// gate: unchanged.
    pub fn recheck(&self) -> Result<Reach, Refusal> {
        match &self.live {
            None => Ok(self.clone()),
            Some(l) => l.gate.check(l.caller.as_ref(), &l.grant, None),
        }
    }

    /// Whether the reach covers a target whose chain is `chain` (as
    /// [`Resolve::chain`] gives it), by this snapshot — no new question to
    /// the gate. Prefer [`Reach::allows`] where the answer must be current.
    pub fn covers(&self, chain: &[ScopeRef]) -> bool {
        self.is_everywhere() || self.held_on.iter().any(|s| chain.contains(s))
    }
}

// ---------------------------------------------------------------------------
// Gate
// ---------------------------------------------------------------------------

/// AUTH-11: whether a signed-in caller's sign-in still stands — the
/// service's session table, asked by [`Gate::check`] on every call (and so
/// on every [`Reach::allows`] / [`Reach::current`] a stream makes). A
/// signed-out or revoked session proves no one, whatever its principal
/// holds. Memory only, like the other service traits.
pub trait Liveness: Send + Sync {
    /// `Err`: why the sign-in no longer stands, in words for the caller.
    fn alive(&self, caller: &AuthContext) -> Result<(), String>;
}

struct GateInner {
    memberships: Arc<dyn Memberships>,
    roles: Arc<dyn Roles>,
    resolve: Arc<dyn Resolve>,
    liveness: Option<Arc<dyn Liveness>>,
    generation: GrantsGeneration,
}

/// BIDIR-8: what moved the grants generation ([`Gate::moved`]) — every
/// write that could change an answer the gate gave.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GrantsMove {
    /// A membership added.
    Grant,
    /// A membership removed.
    Revoke,
    /// A role's grants edited.
    RoleEdit,
    /// A principal added to a team (it holds the team's grants).
    TeamAdd,
    /// A principal removed from a team.
    TeamRemove,
    /// A sign-in ended: signed out, or its session revoked.
    SignOut,
}

/// BIDIR-8 (BIDIR-5's finding): the **grants generation** — a count every
/// write that could change one of the gate's answers moves
/// ([`GrantsMove`]). It is the gate's: whoever holds an answer across time
/// (a duplex call's caller, a watch) records the generation it was decided
/// at and asks the gate again only when it has moved — once per move, never
/// per item. Cheap to clone (two `Arc`s, one count); a read is one atomic
/// load; a move wakes every [`subscribe`](GrantsGeneration::subscribe)r.
///
/// A service shares one across its gates with [`Gate::with_generation`]
/// (menger: the gate in front of its calls, the access layer's and the store's count are
/// one).
#[derive(Clone)]
pub struct GrantsGeneration {
    now: Arc<std::sync::atomic::AtomicU64>,
    tx: Arc<tokio::sync::watch::Sender<u64>>,
}

impl fmt::Debug for GrantsGeneration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("GrantsGeneration").field(&self.current()).finish()
    }
}

impl Default for GrantsGeneration {
    fn default() -> Self {
        Self::new()
    }
}

impl GrantsGeneration {
    /// A count at 0.
    pub fn new() -> Self {
        Self { now: Arc::new(std::sync::atomic::AtomicU64::new(0)), tx: Arc::new(tokio::sync::watch::channel(0).0) }
    }

    /// Something that could change an answer moved: +1, and every
    /// subscriber woken. Answers the generation now.
    pub fn bump(&self) -> u64 {
        let n = self.now.fetch_add(1, std::sync::atomic::Ordering::AcqRel) + 1;
        self.tx.send_replace(n);
        n
    }

    /// [`bump`](Self::bump), naming what moved (for the reader; the count
    /// is one either way).
    pub fn moved(&self, why: GrantsMove) -> u64 {
        let _ = why;
        self.bump()
    }

    /// The generation now (one atomic load).
    pub fn current(&self) -> u64 {
        self.now.load(std::sync::atomic::Ordering::Acquire)
    }

    /// At least `n` — a service that counted before it shared this handle
    /// carries its count over. Never back: a smaller `n` changes nothing.
    pub fn raise_to(&self, n: u64) {
        let was = self.now.fetch_max(n, std::sync::atomic::Ordering::AcqRel);
        if n > was {
            self.tx.send_replace(self.current());
        }
    }

    /// What wakes a holder when the generation moves.
    pub fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
        self.tx.subscribe()
    }
}

/// The one rule in front of every call: the method's grant, held through a
/// role on the target's scope, within the session's ceiling. Default deny.
/// Cheap to clone (one `Arc`); cheap to ask (memory only), so a stream may
/// ask per event.
#[derive(Clone)]
pub struct Gate {
    inner: Arc<GateInner>,
}

impl fmt::Debug for Gate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Gate")
    }
}

impl Gate {
    /// A gate over a service's memberships, roles and resolver.
    pub fn new(memberships: Arc<dyn Memberships>, roles: Arc<dyn Roles>, resolve: Arc<dyn Resolve>) -> Self {
        Self { inner: Arc::new(GateInner { memberships, roles, resolve, liveness: None, generation: GrantsGeneration::new() }) }
    }

    /// BIDIR-8: this gate, counting its moves in `generation` — the
    /// service's one ([`GrantsGeneration`]), shared by every gate it builds.
    /// Without it a gate counts alone, from 0.
    pub fn with_generation(self, generation: GrantsGeneration) -> Self {
        let i = &self.inner;
        Self {
            inner: Arc::new(GateInner {
                memberships: i.memberships.clone(),
                roles: i.roles.clone(),
                resolve: i.resolve.clone(),
                liveness: i.liveness.clone(),
                generation,
            }),
        }
    }

    /// BIDIR-8: the grants generation this gate's answers are decided at.
    pub fn generation(&self) -> &GrantsGeneration {
        &self.inner.generation
    }

    /// BIDIR-8: a write that could change this gate's answers happened
    /// (the service wrote it — the gate keeps no memberships of its own):
    /// the generation moves once. Answers the generation now.
    pub fn moved(&self, why: GrantsMove) -> u64 {
        self.inner.generation.moved(why)
    }

    /// AUTH-11: this gate, asking `liveness` whether a caller's sign-in
    /// still stands before every check. Without it the gate still refuses
    /// a caller past its `expires_at` stamp ([`AuthContext::expired`]).
    pub fn with_liveness(self, liveness: Arc<dyn Liveness>) -> Self {
        let i = &self.inner;
        Self {
            inner: Arc::new(GateInner {
                memberships: i.memberships.clone(),
                roles: i.roles.clone(),
                resolve: i.resolve.clone(),
                liveness: Some(liveness),
                generation: i.generation.clone(),
            }),
        }
    }

    /// AUTH-11: whether `caller`'s sign-in still stands: not past its
    /// `expires_at`, and live by the service's [`Liveness`]. An anonymous
    /// context has no sign-in to end: `Ok`.
    pub fn alive(&self, caller: &AuthContext) -> Result<(), String> {
        if caller.principal().is_none() {
            return Ok(());
        }
        if caller.expired() {
            return Err("your sign-in has expired: sign in again".into());
        }
        match &self.inner.liveness {
            Some(l) => l.alive(caller),
            None => Ok(()),
        }
    }

    /// Whether `role` lists `grant` ([`ADMIN`] lists every grant).
    pub fn lists(&self, role: &RoleName, grant: &Grant) -> bool {
        role.as_str() == ADMIN || self.inner.roles.grants(role).is_some_and(|g| g.contains(grant))
    }

    /// The roles that list `grant`, [`ADMIN`] last.
    pub fn roles_listing(&self, grant: &Grant) -> Vec<RoleName> {
        let mut out: Vec<RoleName> = self
            .inner
            .roles
            .names()
            .into_iter()
            .filter(|r| r.as_str() != ADMIN && self.lists(r, grant))
            .collect();
        out.push(RoleName::new(ADMIN));
        out
    }

    /// Whether a ceiling entry allows `grant`.
    fn entry_allows(&self, entry: &RoleOrGrant, grant: &Grant) -> bool {
        match entry {
            RoleOrGrant::Grant(g) => g == grant,
            RoleOrGrant::Role(r) => self.lists(r, grant),
        }
    }

    /// The caller's principal and ceiling layers; `None` when anonymous. An
    /// unreadable ceiling becomes one empty layer — it allows nothing.
    fn caller_of(caller: Option<&AuthContext>) -> Option<(Principal, Vec<Ceiling>)> {
        let ctx = caller?;
        let principal = ctx.principal()?;
        let layers = Ceiling::layers_of(ctx).unwrap_or_else(|_| vec![Ceiling::default()]);
        Some((principal, layers))
    }

    /// Whether `inner` lies within `outer` (or is it).
    fn within(&self, inner: &ScopeRef, outer: &ScopeRef) -> bool {
        if outer.is_everywhere() || inner == outer {
            return true;
        }
        match inner {
            ScopeRef::Everywhere => false,
            ScopeRef::Named(name) => self.inner.resolve.chain(name).is_some_and(|c| c.contains(outer)),
        }
    }

    /// The scopes both `a` and `b` reach: where one lies within the other,
    /// the inner one.
    fn meet(&self, a: Vec<ScopeRef>, b: Vec<ScopeRef>) -> Vec<ScopeRef> {
        if a.iter().any(ScopeRef::is_everywhere) {
            return b;
        }
        if b.iter().any(ScopeRef::is_everywhere) {
            return a;
        }
        let mut out = BTreeSet::new();
        for x in &a {
            for y in &b {
                if self.within(x, y) {
                    out.insert(x.clone());
                } else if self.within(y, x) {
                    out.insert(y.clone());
                }
            }
        }
        out.into_iter().collect()
    }

    /// Collapse to `[*]` when `*` is among them; dedupe, ordered.
    fn normal(scopes: impl IntoIterator<Item = ScopeRef>) -> Vec<ScopeRef> {
        let set: BTreeSet<ScopeRef> = scopes.into_iter().collect();
        if set.contains(&ScopeRef::Everywhere) {
            vec![ScopeRef::Everywhere]
        } else {
            set.into_iter().collect()
        }
    }

    fn held_on_for(&self, principal: &Principal, layers: &[Ceiling], grant: &Grant) -> Vec<ScopeRef> {
        let held = self.inner.memberships.held(principal);
        self.held_on_in(held.iter().map(|m| (&m.role, &m.scope)), layers, grant)
    }

    /// Where `held` (role, scope pairs) holds `grant` within `layers`: what
    /// [`Gate::held_on`] answers from the memberships and
    /// [`Gate::held_on_by`] from a [`Fingerprint`] — one rule.
    fn held_on_in<'a>(
        &self,
        held: impl Iterator<Item = (&'a RoleName, &'a ScopeRef)>,
        layers: &[Ceiling],
        grant: &Grant,
    ) -> Vec<ScopeRef> {
        let mut acc = Self::normal(held.filter(|(role, _)| self.lists(role, grant)).map(|(_, scope)| scope.clone()));
        for layer in layers {
            if acc.is_empty() {
                break;
            }
            let allowed = Self::normal(
                layer.0.iter().filter(|(rg, _)| self.entry_allows(rg, grant)).map(|(_, s)| s.clone()),
            );
            acc = self.meet(acc, allowed);
        }
        acc
    }

    /// Where the caller holds `grant`, within its ceiling: `[*]` when
    /// everywhere, `[]` when nowhere (and for an anonymous caller). What a
    /// method without a target answers from.
    pub fn held_on(&self, caller: &AuthContext, grant: &Grant) -> Vec<ScopeRef> {
        match Self::caller_of(Some(caller)) {
            Some((p, layers)) => self.held_on_for(&p, &layers, grant),
            None => Vec::new(),
        }
    }

    /// PERF-15: what this gate's answers about `caller` read, besides the
    /// grants generation — its principal's memberships and its session's
    /// ceiling ([`Fingerprint`]); `None` when it is anonymous. The
    /// memberships are read now, from memory.
    pub fn fingerprint(&self, caller: &AuthContext) -> Option<Fingerprint> {
        let (principal, layers) = Self::caller_of(Some(caller))?;
        let mut held: Vec<(RoleName, ScopeRef)> =
            self.inner.memberships.held(&principal).into_iter().map(|m| (m.role, m.scope)).collect();
        held.sort();
        held.dedup();
        Some(Fingerprint { held, layers })
    }

    /// PERF-15: [`Gate::held_on`] for whoever has `who` — read from the
    /// fingerprint instead of the memberships, by the same rule, so a view
    /// built from it is exactly the one built from any caller it was taken
    /// of.
    pub fn held_on_by(&self, who: &Fingerprint, grant: &Grant) -> Vec<ScopeRef> {
        self.held_on_in(who.held.iter().map(|(r, s)| (r, s)), &who.layers, grant)
    }

    /// Allowed when the grant is listed by a role held on a scope in the
    /// target's chain — or anywhere, for a call with no target — and every
    /// ceiling layer allows it the same way. The [`Reach`] is live (it asks
    /// this gate again on [`Reach::allows`] / [`Reach::current`]).
    ///
    /// AUTH-11: first, the caller's sign-in must still stand
    /// ([`Gate::alive`]) — a signed-out session holds nothing, so a socket
    /// that signed out cannot go on to call `auth.grant`.
    pub fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<Reach, Refusal> {
        let Some((principal, layers)) = Self::caller_of(caller) else {
            return Err(Refusal::Unauthenticated);
        };
        if let Some(ctx) = caller {
            self.alive(ctx).map_err(|reason| Refusal::Ended { reason })?;
        }
        let held_on = self.held_on_for(&principal, &layers, grant);
        let (allowed, scope) = match target {
            None => (!held_on.is_empty(), ScopeRef::Everywhere),
            Some(t) => match self.inner.resolve.chain(t) {
                None => (false, ScopeRef::named(t)),
                Some(chain) => {
                    let in_chain = |s: &ScopeRef| s.is_everywhere() || chain.contains(s);
                    let by_membership = self
                        .inner
                        .memberships
                        .held(&principal)
                        .iter()
                        .any(|m| in_chain(&m.scope) && self.lists(&m.role, grant));
                    let by_ceiling = layers
                        .iter()
                        .all(|layer| layer.0.iter().any(|(rg, s)| in_chain(s) && self.entry_allows(rg, grant)));
                    let scope = chain.first().cloned().unwrap_or_else(|| ScopeRef::named(t));
                    (by_membership && by_ceiling, scope)
                }
            },
        };
        if allowed {
            Ok(Reach {
                held_on,
                live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone() }),
            })
        } else {
            Err(Refusal::MissingGrant { grant: grant.clone(), scope, roles: self.roles_listing(grant), held_on })
        }
    }

    /// The reach of a `public` method: what [`Gate::check`] would allow
    /// without a target, or an empty (still live) reach when the caller holds
    /// the grant nowhere or is anonymous. A public method is never refused.
    pub fn reach_of_public(&self, caller: Option<&AuthContext>, grant: &Grant) -> Reach {
        self.check(caller, grant, None).unwrap_or_else(|_| Reach {
            held_on: Vec::new(),
            live: Some(Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone() }),
        })
    }
}

// ---------------------------------------------------------------------------
// Tests — the gate's decision table
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    const ADA: &str = "key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    const BOB: &str = "key:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";

    /// Memberships as a mutable table, so a test can revoke one.
    #[derive(Default)]
    struct Members(Mutex<Vec<Membership>>);
    impl Members {
        fn grant(&self, who: &str, role: &str, scope: &str) {
            self.0.lock().unwrap().push(Membership {
                principal: who.parse().unwrap(),
                role: RoleName::new(role),
                scope: ScopeRef::parse(scope),
            });
        }
        fn revoke_all(&self) {
            self.0.lock().unwrap().clear();
        }
    }
    impl Memberships for Members {
        fn held(&self, who: &Principal) -> Vec<Membership> {
            self.0.lock().unwrap().iter().filter(|m| &m.principal == who).cloned().collect()
        }
    }

    /// menger-shaped: a ticket `CODE-n` lives in itself, then `CODE`;
    /// MENGER and IDENTITY are disjoint, both hosted under PLEXUS.
    struct Shortcodes;
    impl Resolve for Shortcodes {
        fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
            let code = target.split_once('-').map(|(c, _)| c).unwrap_or(target);
            let mut chain = Vec::new();
            if target.contains('-') {
                chain.push(ScopeRef::named(target));
            }
            match code {
                "MENGER" | "IDENTITY" => {
                    chain.push(ScopeRef::named(code));
                    chain.push(ScopeRef::named("PLEXUS"));
                }
                "PLEXUS" => chain.push(ScopeRef::named("PLEXUS")),
                _ => return None,
            }
            chain.push(ScopeRef::Everywhere);
            Some(chain)
        }
    }

    fn roles() -> RoleTable {
        RoleTable::new()
            .define("viewer", ["tickets.get", "tickets.list"])
            .unwrap()
            .define("editor", ["viewer", "tickets.set_status"])
            .unwrap()
    }

    fn gate(members: &Arc<Members>) -> Gate {
        Gate::new(members.clone(), Arc::new(roles()), Arc::new(Shortcodes))
    }

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

    fn with_ceiling(p: &str, ceiling: serde_json::Value) -> AuthContext {
        AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::json!({ CEILING_KEY: ceiling }))
    }

    fn g(s: &str) -> Grant {
        Grant::new(s)
    }

    #[test]
    fn a_grant_no_role_lists_is_refused_to_all_but_admin() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "editor", "*");
        m.grant(BOB, "admin", "MENGER");
        let gate = gate(&m);
        let err = gate.check(Some(&who(ADA)), &g("members.grant"), Some("MENGER-1")).unwrap_err();
        assert_eq!(
            err,
            Refusal::MissingGrant {
                grant: g("members.grant"),
                scope: ScopeRef::named("MENGER-1"),
                roles: vec![RoleName::new("admin")],
                held_on: vec![],
            }
        );
        assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("MENGER-1")).is_ok());
        // admin on MENGER is not admin on IDENTITY.
        assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("IDENTITY-1")).is_err());
    }

    #[test]
    fn held_on_a_scope_allows_targets_in_its_chain_only() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "editor", "MENGER");
        let gate = gate(&m);
        let reach = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("MENGER-12")).unwrap();
        assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER")]);
        let err = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-1")).unwrap_err();
        assert_eq!(
            err,
            Refusal::MissingGrant {
                grant: g("tickets.set_status"),
                scope: ScopeRef::named("IDENTITY-1"),
                roles: vec![RoleName::new("editor"), RoleName::new("admin")],
                held_on: vec![ScopeRef::named("MENGER")],
            }
        );
        assert_eq!(err.to_string(), "needs tickets.set_status on IDENTITY-1");
        // A target nothing resolves is refused.
        assert!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("NOPE-1")).is_err());
    }

    #[test]
    fn held_on_everywhere_allows_any_target_and_reach_is_everywhere() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "viewer", "*");
        m.grant(ADA, "viewer", "MENGER");
        let gate = gate(&m);
        let reach = gate.check(Some(&who(ADA)), &g("tickets.get"), Some("IDENTITY-3")).unwrap();
        assert!(reach.is_everywhere());
        assert_eq!(reach.held_on(), &[ScopeRef::Everywhere]);
        assert!(gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap().is_everywhere());
        // viewer does not list set_status, wherever it is held.
        assert!(gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-3")).is_err());
    }

    #[test]
    fn without_a_target_held_anywhere_suffices_and_reach_says_where() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "viewer", "MENGER");
        m.grant(ADA, "viewer", "IDENTITY");
        let gate = gate(&m);
        let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
        assert_eq!(reach.held_on(), &[ScopeRef::named("IDENTITY"), ScopeRef::named("MENGER")]);
        assert!(reach.allows("MENGER-4"));
        assert!(!reach.allows("PLEXUS-1"));
        let err = gate.check(Some(&who(BOB)), &g("tickets.list"), None).unwrap_err();
        assert!(matches!(err, Refusal::MissingGrant { ref scope, .. } if scope.is_everywhere()));
    }

    #[test]
    fn a_ceiling_narrows_the_membership() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "editor", "MENGER");
        let gate = gate(&m);
        let narrowed = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
        assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-12")).is_ok());
        assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-13")).is_err());
        // The reach of a target-less read is the meet: MENGER-12, inside MENGER.
        let reach = gate.check(Some(&narrowed), &g("tickets.list"), None).unwrap();
        assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER-12")]);
        // A grant-entry ceiling: only tickets.get, anywhere the membership allows.
        let only_get = with_ceiling(ADA, serde_json::json!([["tickets.get@*"]]));
        assert!(gate.check(Some(&only_get), &g("tickets.get"), Some("MENGER-1")).is_ok());
        let err = gate.check(Some(&only_get), &g("tickets.set_status"), Some("MENGER-1")).unwrap_err();
        assert!(matches!(err, Refusal::MissingGrant { ref held_on, .. } if held_on.is_empty()));
        // Two layers: both must allow.
        let layered = with_ceiling(ADA, serde_json::json!([["editor@*"], ["viewer@MENGER"]]));
        assert!(gate.check(Some(&layered), &g("tickets.get"), Some("MENGER-1")).is_ok());
        assert!(gate.check(Some(&layered), &g("tickets.set_status"), Some("MENGER-1")).is_err());
        // A ceiling never widens: editor@IDENTITY grants nothing there.
        let wider = with_ceiling(ADA, serde_json::json!(["editor@IDENTITY"]));
        assert!(gate.check(Some(&wider), &g("tickets.get"), Some("IDENTITY-1")).is_err());
        // An unreadable ceiling allows nothing.
        let bad = with_ceiling(ADA, serde_json::json!("editor@*"));
        assert!(gate.check(Some(&bad), &g("tickets.get"), Some("MENGER-1")).is_err());
    }

    #[test]
    fn role_inclusion_flattens_and_must_name_an_earlier_role() {
        let r = roles();
        let editor = r.grants(&RoleName::new("editor")).unwrap();
        assert!(editor.contains(&g("tickets.get")) && editor.contains(&g("tickets.set_status")));
        let viewer = r.grants(&RoleName::new("viewer")).unwrap();
        assert!(!viewer.contains(&g("tickets.set_status")));
        assert_eq!(
            RoleTable::new().define("editor", ["viewer"]).unwrap_err(),
            RoleTableError::UnknownRole { role: "editor".into(), includes: "viewer".into() }
        );
        // admin is built in: holds every grant, whatever the table says.
        assert_eq!(r.grants(&RoleName::new("admin")), Some(GrantSet::All));
        // from_lists merges one role's lists from several activations.
        let merged = RoleTable::from_lists([("editor", vec!["tickets.get"]), ("editor", vec!["comments.add"])]);
        let e = merged.grants(&RoleName::new("editor")).unwrap();
        assert!(e.contains(&g("tickets.get")) && e.contains(&g("comments.add")));
    }

    #[test]
    fn anonymous_is_unauthenticated() {
        let m = Arc::new(Members::default());
        let gate = gate(&m);
        assert_eq!(gate.check(None, &g("tickets.get"), Some("MENGER-1")).unwrap_err(), Refusal::Unauthenticated);
        assert_eq!(
            gate.check(Some(&AuthContext::anonymous()), &g("tickets.list"), None).unwrap_err(),
            Refusal::Unauthenticated
        );
        // A public method's reach for an anonymous caller: empty, never refused.
        assert!(gate.reach_of_public(None, &g("auth.login")).is_empty());
    }

    #[test]
    fn a_live_reach_follows_grants_as_they_stand() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "viewer", "MENGER");
        let gate = gate(&m);
        let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
        assert!(reach.allows("MENGER-1"));
        assert!(reach.current().is_some());
        m.revoke_all();
        assert!(!reach.allows("MENGER-1"));
        assert!(reach.current().is_none());
        // Without a gate, everything.
        assert!(Reach::everywhere().allows("ANY-1") && Reach::everywhere().current().is_some());
    }

    #[test]
    fn scope_refs_and_ceilings_round_trip() {
        assert_eq!(serde_json::to_string(&ScopeRef::Everywhere).unwrap(), "\"*\"");
        assert_eq!(serde_json::from_str::<ScopeRef>("\"MENGER\"").unwrap(), ScopeRef::named("MENGER"));
        let c = Ceiling::parse(["editor@MENGER-12", "tickets.get@*"]).unwrap();
        assert_eq!(c.0[0], (RoleOrGrant::Role(RoleName::new("editor")), ScopeRef::named("MENGER-12")));
        assert_eq!(c.0[1], (RoleOrGrant::Grant(g("tickets.get")), ScopeRef::Everywhere));
        assert_eq!(c.text(), vec!["editor@MENGER-12", "tickets.get@*"]);
        assert!(Ceiling::parse(["editor"]).is_err());
    }

    /// A session table with one switch: signed out or not.
    #[derive(Default)]
    struct Switch(std::sync::atomic::AtomicBool);
    impl Liveness for Switch {
        fn alive(&self, _: &AuthContext) -> Result<(), String> {
            if self.0.load(std::sync::atomic::Ordering::SeqCst) {
                Err("you have signed out: sign in again".into())
            } else {
                Ok(())
            }
        }
    }

    /// AUTH-11: a signed-out session holds nothing — not even admin on `*`
    /// — and a live reach taken before the sign-out ends with it.
    #[test]
    fn a_session_that_ended_holds_nothing() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "admin", "*");
        let out = Arc::new(Switch::default());
        let gate = gate(&m).with_liveness(out.clone());
        let reach = gate.check(Some(&who(ADA)), &g("auth.grant"), None).expect("admin before sign-out");
        assert!(reach.allows("MENGER-1"));
        out.0.store(true, std::sync::atomic::Ordering::SeqCst);
        let ended = Refusal::Ended { reason: "you have signed out: sign in again".into() };
        assert_eq!(gate.check(Some(&who(ADA)), &g("auth.grant"), None).unwrap_err(), ended);
        assert_eq!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("MENGER-1")).unwrap_err(), ended);
        assert!(!reach.allows("MENGER-1"), "a stream's next event sees it");
        assert!(reach.current().is_none());
        assert!(gate.reach_of_public(Some(&who(ADA)), &g("auth.grant")).is_empty());
        // Anonymous is not "ended": still plain Unauthenticated.
        assert_eq!(gate.check(None, &g("auth.grant"), None).unwrap_err(), Refusal::Unauthenticated);
    }

    /// AUTH-11: past its `expires_at` stamp, a sign-in is over even with
    /// no liveness hook.
    #[test]
    fn an_expired_sign_in_holds_nothing() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "admin", "*");
        let gate = gate(&m);
        let past = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": 1 }));
        assert!(matches!(gate.check(Some(&past), &g("auth.grant"), None), Err(Refusal::Ended { .. })));
        let future = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": i64::MAX }));
        assert!(gate.check(Some(&future), &g("auth.grant"), None).is_ok());
    }

    /// PERF-15: a fingerprint is what the gate's answers read of a caller —
    /// equal for two principals holding the same, different when a
    /// membership or the ceiling differs, `None` when anonymous — and
    /// `held_on_by` answers from it exactly what `held_on` answers.
    #[test]
    fn a_fingerprint_is_what_the_answers_read() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "viewer", "IDENTITY");
        m.grant(ADA, "editor", "MENGER");
        m.grant(BOB, "editor", "MENGER");
        m.grant(BOB, "viewer", "IDENTITY");
        m.grant(BOB, "editor", "MENGER");
        let gate = gate(&m);
        let (ada, bob) = (gate.fingerprint(&who(ADA)).unwrap(), gate.fingerprint(&who(BOB)).unwrap());
        assert_eq!(ada, bob, "the same holdings, in another order and once more: one fingerprint");
        assert_eq!(gate.fingerprint(&AuthContext::anonymous()), None);
        let narrow = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
        let narrowed = gate.fingerprint(&narrow).unwrap();
        assert_ne!(narrowed, ada, "a ceiling: another fingerprint");
        let unreadable = gate.fingerprint(&with_ceiling(ADA, serde_json::json!("editor@*"))).unwrap();
        assert_ne!(unreadable, ada, "an unreadable ceiling allows nothing: not the unbounded caller's");
        for (ctx, fp) in [(&who(ADA), &ada), (&narrow, &narrowed), (&with_ceiling(ADA, serde_json::json!("editor@*")), &unreadable)] {
            for grant in ["tickets.get", "tickets.set_status", "tickets.delete", "members.grant"] {
                assert_eq!(gate.held_on_by(fp, &g(grant)), gate.held_on(ctx, &g(grant)), "{grant}");
            }
        }
        assert_eq!(gate.held_on_by(&narrowed, &g("tickets.get")), vec![ScopeRef::named("MENGER-12")]);
        m.revoke_all();
        assert_ne!(gate.fingerprint(&who(ADA)).unwrap(), ada, "a revoke: another fingerprint");
    }
}