plexus-auth-core 0.3.4

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
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
//! 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.
//!
//! - ONE-6: a membership may also be held on an **address** — `/dyn` (the
//!   methods of the activation `dyn`, or with `/dyn.connect` one method) or
//!   `/dyn.*` (`dyn` and everything mounted beneath it). `self` is `*`: the
//!   service being called. A scope being written goes through
//!   [`ScopeRef::parse_checked`].
//!
//! # Activation scopes and data scopes are separate (ONE-6)
//!
//! 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". An address scope answers one question — may this caller
//! make this call at this address (the **door**) — and never stands for
//! data: it is never among the scopes a [`Reach`] holds, never satisfies a
//! data target, and never makes a read "held anywhere". The gate owns
//! addresses: it is told the call as one [`DispatchedCall`] (its literal
//! address and its grant) and never asks a [`Resolve`] about one.
//!
//! What an address scope does, by the three shapes the gate knows:
//!
//! | the method's shape | asked through | an address scope covering the call | a data scope | `*` |
//! |---|---|---|---|---|
//! | `everywhere` (acts on the whole activation: `dyn.connect`, `auth.role_set`) | [`Gate::check_everywhere_at`] | **admits** (the door) | never (KEEL-31) | admits |
//! | a declared target (`tickets.get --id KILN-3`) | [`Gate::check`] with the target | **nothing** | admits when in the target's chain | admits |
//! | no target (`tickets.list`, `dyn.peers`, `ui.versions`) | [`Gate::check`] with none | **nothing** | admits, reach = the data scopes | admits, reach `[*]` |
//! | a call into an untyped peer slot (`dyn.peer.shop.items.list`) — no data chain on this service | [`Gate::check_everywhere_at`] (build 2) | **admits** (the door) | never | admits |
//!
//! **"No target" is ambiguous**: it is a read over data (`tickets.list`)
//! or a method with no data at all (`dyn.peers`, `ui.versions`), and the
//! gate cannot tell which. The safe default is the data reading: an address
//! scope counts for nothing there, so a caller who holds a grant only on
//! addresses is refused — not admitted with an empty reach, which a method
//! that forgets to filter by its reach would read as "no restriction", and
//! which would make "held on an address" a second meaning of "held
//! nowhere". So `operator on /dyn` cannot call `dyn.peers` until it is
//! declared activation-scoped. What builds 2–3 need instead of a new word
//! here: (a) the dispatcher sends `everywhere` methods and untyped peer-slot
//! calls through [`Gate::check_everywhere_at`]; (b) a schema-level way to
//! say "this targetless method touches no data" — reusing `everywhere`
//! (decided at the door alone; a data-scoped holder refused) is enough for
//! `dyn.peers`-like methods, or a macro word if a targetless method must
//! stay open to data holders *and* address holders; (c) the in-method
//! backstops that ask [`Reach::is_everywhere`] on whole-service methods move
//! to [`Reach::holds_activation`].
//!
//! A ceiling layer is read the same way: its entries on addresses count at
//! the door, its entries on data scopes (and `*`) count for data. A layer
//! with only address entries allows no data; a layer with only data entries
//! opens no door.
//!
//! [`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 service; a service 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.
///
/// ONE-6: two kinds of name are not the service's.
///
/// - A name that begins with `/` is an address scope (`/dyn`, `/dyn.*`,
///   [`ScopeRef::parse_checked`]), which the gate decides by the call's
///   address alone ([`CallAddress`], [`DispatchedCall`]). It is never a data
///   scope: a service whose own data scopes began with `/` loses them (as of
///   0.3.4), and a [`Resolve`] chain that names one has it dropped.
/// - The name `self` is reserved: written through
///   [`ScopeRef::parse_checked`] it is `*`; held as a raw `Named("self")`
///   (stored through the lenient [`ScopeRef::parse`] or serde) it holds
///   nothing at all — never a data scope, never `*`. A [`Resolve`] chain that
///   names it has it dropped too.
///
/// An address scope never stands for data: it opens the door of the calls
/// it covers and holds nothing else (the module's "Activation scopes and
/// data scopes are separate"; the rules are `Gate::as_data` and
/// `Gate::opens`).
///
/// 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.
    ///
    /// Lenient, as the wire is: it refuses nothing and reads `self` as a
    /// name, which the gate then holds on nothing. **A scope being written —
    /// a membership granted (`auth.grant`, `members.grant`), a role or a
    /// team's grant stored, a ceiling minted into a session — must go
    /// through [`ScopeRef::parse_checked`]**, which reads `self` as `*` and
    /// refuses a malformed address, so neither is stored to mean nothing.
    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)
    }

    /// ONE-6: a scope as a grant writes it, checked — what a membership or
    /// a ceiling may be held on:
    ///
    /// - `*` or `self` → [`ScopeRef::Everywhere`]: the root of the service
    ///   being called (`self` never means the caller);
    /// - `/a.b` or `/a.b.*` → an address scope, kept as written (see
    ///   [`CallAddress`] for the forms and what each covers); refused unless
    ///   every segment is one or more of `A–Z a–z 0–9 _ -`, so `/`, `//`,
    ///   `/*`, `/a.`, `/.a`, `/a..b`, `/a.*.b`, and any `*`, `@`, space or
    ///   non-ASCII character inside one are refused;
    /// - anything else non-empty, with no space around it → a data scope,
    ///   the service's own name.
    ///
    /// [`ScopeRef::parse`] stays as it was (lenient, the wire's): it never
    /// reads `self` as `*`. A malformed address it lets through is held on
    /// nothing — the gate reads every scope that begins with `/` as an
    /// address scope or as nothing, never as a data scope.
    pub fn parse_checked(text: &str) -> Result<Self, AddressError> {
        match text {
            "*" | "self" => Ok(Self::Everywhere),
            t if t.starts_with('/') => match address_form(t) {
                Some(_) => Ok(Self::Named(t.to_string())),
                None => Err(AddressError(format!(
                    "`{t}` is not an address scope: `/` then dotted segments of A-Z a-z 0-9 _ -, \
                     optionally ending `.*`"
                ))),
            },
            t if t.is_empty() || t.trim() != t => Err(AddressError(format!("`{t}` is not a scope"))),
            t => Ok(Self::Named(t.to_string())),
        }
    }

    /// ONE-6: whether this is an address scope — a name beginning with `/`.
    /// Well formed or not: one that is not covers nothing.
    pub fn is_address(&self) -> bool {
        matches!(self, Self::Named(n) if n.starts_with('/'))
    }

    /// A service's own name: neither `*`, nor an address, nor the reserved
    /// `self`.
    fn is_data(&self) -> bool {
        matches!(self, Self::Named(n) if !n.starts_with('/') && n != "self")
    }

    /// ONE-6: whether this scope covers the call at `at` *as an address*:
    /// `*` covers every call; `/P` the methods of the activation `P` and
    /// the method `P` itself; `/P.*` the address `P` and everything under
    /// it. A data scope, or a malformed address, covers none.
    pub fn covers_address(&self, at: &CallAddress) -> bool {
        match self {
            Self::Everywhere => true,
            Self::Named(n) => match address_form(n) {
                Some((p, true)) => at.path() == p || at.path().strip_prefix(p).is_some_and(|rest| rest.starts_with('.')),
                Some((p, false)) => p == at.activation() || p == at.path(),
                None => false,
            },
        }
    }
}

// ---------------------------------------------------------------------------
// Addresses (ONE-6)
// ---------------------------------------------------------------------------

/// ONE-6: why an address, or a scope written as one, was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddressError(pub String);

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

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

/// One segment of an address: one or more of `A–Z a–z 0–9 _ -`. Compared
/// byte for byte, so case matters (`/Dyn` is not `/dyn`).
fn segment_ok(segment: &str) -> bool {
    !segment.is_empty() && segment.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

/// One or more segments joined by single dots.
fn path_ok(path: &str) -> bool {
    path.split('.').all(segment_ok)
}

/// An address scope's path and whether it is the subtree form (`/P.*`);
/// `None` when `scope` is not a well-formed address scope.
fn address_form(scope: &str) -> Option<(&str, bool)> {
    let body = scope.strip_prefix('/')?;
    let (path, subtree) = match body.strip_suffix(".*") {
        Some(p) => (p, true),
        None => (body, false),
    };
    path_ok(path).then_some((path, subtree))
}

/// ONE-6: the literal address of one call — the activation it is
/// dispatched to and the method, named apart. The gate is told it by
/// whoever dispatches (plexus-core), from the path it routes, never from a
/// parameter; a service's [`Resolve`] is never asked about an address.
///
/// **A method of X, or a child of X.** A dotted path alone does not say
/// which of its dots separates the activation from the method, so the
/// gate is told: the activation is one or more segments, the method is
/// exactly one. `dyn.connect` is the method `connect` of the activation
/// `dyn`; `dyn.peer.shop.items.list` is the method `list` of the activation
/// `dyn.peer.shop.items` — mounted under `dyn`, not of it. Since a method
/// may not hold a dot, a path has one way to be told and no other: a
/// caller that split it anywhere but at its last dot is refused here.
///
/// **What an address scope covers** ([`ScopeRef::covers_address`]):
///
/// | held on | covers the call at `A.m` when |
/// |---|---|
/// | `*`, `self` | always |
/// | `/P` | `P` is `A` (a method of that activation) or `P` is `A.m` (that one method) |
/// | `/P.*` | `A.m` is `P` or begins with `P.` (`P` and all beneath it) |
///
/// So `operator on /dyn` reaches `dyn.connect` and not
/// `dyn.peer.shop.items.list`; `operator on /dyn.*` reaches both;
/// `operator on /dyn.peer.shop.*` reaches the peer `shop` alone.
///
/// **`/P` names a method and an activation alike.** `/dyn.connect` covers
/// the method `dyn.connect` *and* every method of an activation mounted at
/// `dyn.connect`, should one exist. An address cannot tell them apart; a
/// service that mounts a child under a method's name gives both to whoever
/// holds `/P`.
///
/// **The contract a dispatcher relies on.** What is refused here: an empty
/// segment, a method holding a dot, and any byte outside `A–Z a–z 0–9 _ -`
/// (so `*`, `@`, `{`, `/`, a space, non-ASCII). What cannot be refused
/// here: a key that holds a dot, joined into the activation's path
/// (`dyn.peer.github.repos.alice.app.v2.issues`) — it reads as two
/// segments, and `/…alice.app.*` would cover the repository `app.v2`. A
/// dispatcher builds the address from its routed segments with
/// [`CallAddress::of_segments`], which refuses a segment holding a dot,
/// and never joins or splits a key itself. An address that cannot be built
/// is no address: the call is decided as told none, where an address scope
/// holds nothing — never on a shorter address that would parse.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CallAddress {
    /// `activation.method`.
    path: String,
    /// Where the method begins, less the dot: `activation.len()`.
    dot: usize,
}

impl CallAddress {
    /// The call of `method` on the activation at `activation`
    /// (`CallAddress::new("dyn.peer.shop.items", "list")`). Refused unless
    /// `activation` is dotted segments and `method` is one segment, each of
    /// `A–Z a–z 0–9 _ -`.
    pub fn new(activation: &str, method: &str) -> Result<Self, AddressError> {
        if !path_ok(activation) {
            return Err(AddressError(format!("`{activation}` is not an activation's address")));
        }
        if !segment_ok(method) {
            return Err(AddressError(format!("`{method}` is not a method's name (one segment, no dot)")));
        }
        Ok(Self { path: format!("{activation}.{method}"), dot: activation.len() })
    }

    /// The call of `method` on the activation whose path is `activation`,
    /// segment by segment as routed (`["dyn", "peer", "shop", "items"]`,
    /// `"list"`). Each is one segment: one holding a dot (a key `app.v2`)
    /// is refused, never split.
    pub fn of_segments(activation: &[&str], method: &str) -> Result<Self, AddressError> {
        match activation.iter().find(|s| !segment_ok(s)) {
            Some(bad) => Err(AddressError(format!("`{bad}` is not one segment of an address"))),
            None if activation.is_empty() => Err(AddressError("an activation's address has a segment".into())),
            None => Self::new(&activation.join("."), method),
        }
    }

    /// The activation's address: `dyn`, `dyn.peer.shop.items`.
    pub fn activation(&self) -> &str {
        &self.path[..self.dot]
    }

    /// The method's name: `connect`.
    pub fn method(&self) -> &str {
        &self.path[self.dot + 1..]
    }

    /// The whole address, as dispatched: `dyn.connect`.
    pub fn path(&self) -> &str {
        &self.path
    }
}

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

/// ONE-6: one call as dispatched — its literal address and the grant that
/// address dispatches to, as one value. The door
/// ([`Gate::check_everywhere_at`]) takes this and nothing else, and decides
/// its grant: an address scope covering the address admits that grant only.
///
/// The dispatcher builds it **once, at dispatch, from the routed entry**:
/// the address from the path it routed, the grant from the same entry (the
/// method's own, a schema-named one, or a slot's such as `dyn.{peer}`). The
/// gate never compares the two as strings — a grant's name may differ from
/// its path.
///
/// **A check inside a call** — a method's own `required(…)`, a seam asking
/// the gate, a store's per-aspect check, any second grant — is asked with
/// [`Gate::check`] / [`Gate::check_everywhere`], told no address: an address
/// scope holds nothing there. Only the reach the door gave carries its
/// address, and only for its own grant ([`Reach::current`] re-asks with
/// both; [`Reach::allows`] answers data, which an address never holds).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DispatchedCall {
    at: CallAddress,
    grant: Grant,
}

impl DispatchedCall {
    /// The call at `at`, which dispatches to `grant`.
    pub fn new(at: CallAddress, grant: Grant) -> Self {
        Self { at, grant }
    }

    /// Its address.
    pub fn at(&self) -> &CallAddress {
        &self.at
    }

    /// The grant its address dispatches to.
    pub fn grant(&self) -> &Grant {
        &self.grant
    }
}

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 service without a gate
/// hands every method [`Reach::everywhere`], which allows everything.
#[derive(Clone)]
pub struct Reach {
    /// PERF.115-49: borrowed for the two constant answers (everywhere,
    /// nowhere), so a service without a gate allocates nothing for them.
    held_on: std::borrow::Cow<'static, [ScopeRef]>,
    live: Option<Live>,
}

#[derive(Clone)]
struct Live {
    gate: Gate,
    caller: Option<AuthContext>,
    grant: Grant,
    /// KEEL-31: the reach of a method that acts on the whole service — asked
    /// again by [`Gate::check_everywhere`], so it lasts only while the grant
    /// is held on `*`.
    everywhere: bool,
    /// ONE-6: the dispatched call whose door admitted it — set only on a
    /// whole-service reach [`Gate::check_everywhere_at`] gave, and asked
    /// again at the same door.
    call: Option<DispatchedCall>,
}

impl Live {
    /// The gate's answer now, by the rule this reach was given by.
    fn now(&self) -> Result<Reach, Refusal> {
        self.now_on(None)
    }

    /// The gate's answer now, for `target` (a whole-service reach ignores
    /// it, as it always has).
    fn now_on(&self, target: Option<&str>) -> Result<Reach, Refusal> {
        match self.everywhere {
            true => self.gate.everywhere_in(self.caller.as_ref(), &self.grant, self.call.as_ref()),
            false => self.gate.check_in(self.caller.as_ref(), &self.grant, target),
        }
    }
}

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 service without a gate (login
    /// off), as today.
    pub fn everywhere() -> Self {
        static EVERYWHERE: [ScopeRef; 1] = [ScopeRef::Everywhere];
        Self { held_on: std::borrow::Cow::Borrowed(&EVERYWHERE), live: None }
    }

    /// RETURNS-47: nothing — the reach of a call made for no one (a child
    /// under the `anonymous` forward policy, or one whose caller cannot be
    /// read). Covers and allows nothing, and names no grant.
    pub fn nowhere() -> Self {
        Self { held_on: std::borrow::Cow::Borrowed(&[]), live: None }
    }

    /// Whether the grant is held on `*`. ONE-6: only a real `*` (or
    /// `self`) — never an address scope, which holds no data.
    pub fn is_everywhere(&self) -> bool {
        self.held_on.iter().any(ScopeRef::is_everywhere)
    }

    /// ONE-6: whether the grant is held for the whole of this call's
    /// activation — the door: on `*`, or, for a reach
    /// [`Gate::check_everywhere_at`] gave, on an address scope covering the
    /// call. Never because of a data scope. An in-method backstop on a
    /// whole-service method asks this (an `operator on /dyn` holds
    /// `dyn.connect`'s activation); one that means "holds every data scope"
    /// asks [`Reach::is_everywhere`], which this never widens. Without a
    /// gate: true, as `is_everywhere` is.
    pub fn holds_activation(&self) -> bool {
        self.is_everywhere() || self.live.as_ref().is_some_and(|l| l.everywhere && l.call.is_some())
    }

    /// 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
    }

    /// PERF.115-49: the caller this reach was decided for — the context the
    /// gate was asked about, which it keeps to ask again; `None` for an
    /// anonymous caller and for a reach no gate made ([`Reach::everywhere`],
    /// [`Reach::nowhere`]). Lets a holder of the reach read that caller
    /// rather than keep a second copy of it.
    pub fn caller(&self) -> Option<&AuthContext> {
        self.live.as_ref().and_then(|l| l.caller.as_ref())
    }

    /// The grant this reach is for; `None` on a service 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. KEEL-31: a whole-service
    /// method's reach allows a target only while the grant is held on `*`.
    /// ONE-6: a whole-service reach admitted at a door
    /// ([`Gate::check_everywhere_at`]) allows a target only while the door
    /// still admits *and* the target's data chain does (`*` or a data scope
    /// holding the grant) — an address scope never allows data.
    pub fn allows(&self, target: &str) -> bool {
        match &self.live {
            None => self.is_everywhere(),
            Some(l) if l.everywhere && l.call.is_none() => l.now().is_ok(),
            Some(l) if l.everywhere => match l.now() {
                Ok(now) => now.is_everywhere() || l.gate.check_in(l.caller.as_ref(), &l.grant, Some(target)).is_ok(),
                Err(_) => false,
            },
            Some(l) => l.now_on(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.now().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.now(),
        }
    }

    /// 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()
    }
}

/// KEEL-59 (N2): see [`GrantsGeneration::on_move`].
static ON_MOVE: std::sync::OnceLock<fn(u64)> = std::sync::OnceLock::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;
        // KEEL-59 (N2): told before any subscriber wakes, in the task that
        // moved it, so the call that made the move knows it was its own.
        if let Some(told) = ON_MOVE.get() {
            told(n);
        }
        self.tx.send_replace(n);
        n
    }

    /// KEEL-59 (N2): `told(generation)` is called, in the moving task, with
    /// every generation a [`bump`](Self::bump) makes — before anything
    /// subscribed to it wakes. Set once per process (plexus-core sets it,
    /// so the call whose own write moved the grants is not ended by that
    /// move); a later call is ignored.
    pub fn on_move(told: fn(u64)) {
        let _ = ON_MOVE.set(told);
    }

    /// [`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(());
        }
        self.alive_named(caller)
    }

    /// [`Gate::alive`] for a caller whose principal was just read (PERF.115-49:
    /// [`Gate::check`] has it from [`Gate::caller_of`], and does not parse it
    /// again).
    fn alive_named(&self, caller: &AuthContext) -> Result<(), String> {
        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))
    }

    /// ONE-6: what the service's [`Resolve`] says of `name`, with every
    /// scope that is not the service's own dropped — an address, or the
    /// reserved `self`. The gate owns addresses: a resolver's answer can
    /// never put one in a chain. Dropping only narrows — the chain loses a
    /// scope and gains none — and a chain is otherwise read as before, so a
    /// caller holding `*` is answered as it always was even when the
    /// target's own value begins with `/` (a resolver that echoes its
    /// target, as plexus-login's does).
    fn chain_of(&self, name: &str) -> Option<Vec<ScopeRef>> {
        let mut chain = self.inner.resolve.chain(name)?;
        chain.retain(|s| s.is_everywhere() || s.is_data());
        Some(chain)
    }

    /// ONE-6 (F1): the address of the door being asked about, in a check
    /// of `grant` — the dispatched call's, and only when `grant` is the
    /// grant that call dispatches to. Any other grant is asked as if no call
    /// were told. The pair is compared whole, as the dispatcher built it;
    /// never a grant's name against a path.
    fn address_for<'c>(call: Option<&'c DispatchedCall>, grant: &Grant) -> Option<&'c CallAddress> {
        call.filter(|c| c.grant() == grant).map(DispatchedCall::at)
    }

    /// **ONE-6, the rule for data** (owner, 2026-11-11: "activation and
    /// data scopes are separate"): what a held scope (a membership's, a
    /// ceiling entry's) stands for among the data scopes a call is decided
    /// on and a reach holds. `*` is `*`; a data scope is itself; an address
    /// scope — and the reserved `self` held raw — is nothing. An address
    /// scope never stands for data.
    fn as_data(scope: &ScopeRef) -> Option<&ScopeRef> {
        (scope.is_everywhere() || scope.is_data()).then_some(scope)
    }

    /// **ONE-6, the rule for the door**: whether a held scope opens the
    /// door of the call at `at` — `*`, or an address scope covering it. A
    /// data scope never does (KEEL-31).
    fn opens(scope: &ScopeRef, at: &CallAddress) -> bool {
        scope.is_everywhere() || (scope.is_address() && scope.covers_address(at))
    }

    /// Whether `inner` lies within `outer` (or is it). Both are data
    /// scopes or `*` ([`Gate::as_data`]); anything else is within nothing.
    fn within(&self, inner: &ScopeRef, outer: &ScopeRef) -> bool {
        if outer.is_everywhere() {
            return true;
        }
        if !inner.is_data() || !outer.is_data() {
            return false;
        }
        if inner == outer {
            return true;
        }
        match inner {
            ScopeRef::Named(name) => self.chain_of(name).is_some_and(|c| c.contains(outer)),
            ScopeRef::Everywhere => false,
        }
    }

    /// 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`,
    /// among data scopes ([`Gate::as_data`]): 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)).filter_map(|(_, scope)| Self::as_data(scope).cloned()),
        );
        for layer in layers {
            if acc.is_empty() {
                break;
            }
            let allowed = Self::normal(
                layer
                    .0
                    .iter()
                    .filter(|(rg, _)| self.entry_allows(rg, grant))
                    .filter_map(|(_, s)| Self::as_data(s).cloned()),
            );
            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. ONE-6: data scopes only — an
    /// address scope is never among them.
    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`.
    ///
    /// ONE-6: decided on data scopes and `*` alone. An address scope never
    /// counts here — not for a target, and not as "held anywhere" for a
    /// read with no target: it opens a door ([`Gate::check_everywhere_at`])
    /// and holds no data. A caller holding a grant only on addresses is
    /// refused here, as one holding it nowhere is.
    pub fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<Reach, Refusal> {
        self.check_in(caller, grant, target)
    }

    /// The data check.
    fn check_in(&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_named(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.chain_of(t) {
                None => (false, ScopeRef::named(t)),
                Some(chain) => {
                    let in_chain =
                        |s: &ScopeRef| Self::as_data(s).is_some_and(|d| d.is_everywhere() || chain.contains(d));
                    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: held_on.into(), live: Some(self.live(caller, grant, None, false)) })
        } else {
            Err(Refusal::MissingGrant { grant: grant.clone(), scope, roles: self.roles_listing(grant), held_on })
        }
    }

    /// The live part of a reach: this gate, the caller, the grant, the rule
    /// it is asked again by, and the door's call (if a door admitted it).
    fn live(&self, caller: Option<&AuthContext>, grant: &Grant, call: Option<&DispatchedCall>, everywhere: bool) -> Live {
        Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone(), everywhere, call: call.cloned() }
    }

    /// KEEL-31: the check for a method that acts on the whole service (it
    /// names no target because its target is everything: a key rotated, a
    /// process spawned, a peer connected). Allowed only where the grant is
    /// held on `*` — by a role held on `*` that lists it, and every ceiling
    /// layer allowing it on `*` — never because it is held on some scope. A
    /// scoped `admin`, or a session minted `admin@X`, is refused, naming `*`.
    /// The reach is `[*]` and stays live by this same rule.
    pub fn check_everywhere(&self, caller: Option<&AuthContext>, grant: &Grant) -> Result<Reach, Refusal> {
        self.everywhere_in(caller, grant, None)
    }

    /// ONE-6: **the door** — [`Gate::check_everywhere`] of the dispatched
    /// `call`, for its own grant: may this caller make this call at this
    /// address. Admitted where a role listing the grant is held on a scope
    /// that opens the call's door — `*` (`self`), the activation's address
    /// (`/dyn` for `dyn.connect`), the method's own (`/dyn.connect`), or a
    /// subtree above it (`/dyn.*`) — and every ceiling layer has an entry
    /// allowing the grant on such a scope. A data scope never opens a door
    /// (KEEL-31), nor an address that does not cover the call (`/ui`,
    /// `/dyn.peer.shop.*`). A refusal names the activation's address.
    ///
    /// The reach says what was admitted apart from what data is held:
    /// [`Reach::holds_activation`] is true; [`Reach::held_on`] is the
    /// caller's data scopes for the grant, as [`Gate::check`] reads them —
    /// `[*]` for a holder of `*`, `[]` for one who holds only addresses — so
    /// [`Reach::is_everywhere`] is true only for a real `*`. It stays live
    /// by this same rule, at the same door.
    pub fn check_everywhere_at(&self, caller: Option<&AuthContext>, call: &DispatchedCall) -> Result<Reach, Refusal> {
        self.everywhere_in(caller, call.grant(), Some(call))
    }

    /// The whole-service check of `grant`: on `*` alone (no call), or at
    /// the dispatched call's door.
    fn everywhere_in(
        &self,
        caller: Option<&AuthContext>,
        grant: &Grant,
        call: Option<&DispatchedCall>,
    ) -> Result<Reach, Refusal> {
        match Self::address_for(call, grant) {
            None => self.on_everywhere(caller, grant),
            Some(at) => self.at_door(caller, grant, call, at),
        }
    }

    /// KEEL-31's rule, as it was: the grant held on `*`.
    fn on_everywhere(&self, caller: Option<&AuthContext>, grant: &Grant) -> Result<Reach, Refusal> {
        let reach = match self.check_in(caller, grant, None) {
            Ok(reach) => reach,
            Err(Refusal::MissingGrant { grant, roles, held_on, .. }) => {
                return Err(Refusal::MissingGrant { grant, scope: ScopeRef::Everywhere, roles, held_on })
            }
            Err(other) => return Err(other),
        };
        if !reach.is_everywhere() {
            return Err(Refusal::MissingGrant {
                grant: grant.clone(),
                scope: ScopeRef::Everywhere,
                roles: self.roles_listing(grant),
                held_on: reach.held_on.into_owned(),
            });
        }
        // PERF.115-49: the check's own live part (this gate, this caller,
        // this grant), kept by the rule of `*` — not a second copy of each.
        let live = reach.live.map(|live| Live { everywhere: true, ..live });
        Ok(Reach { held_on: reach.held_on, live })
    }

    /// The door of the call at `at`: a membership opening it lists the
    /// grant, and every ceiling layer has an entry opening it that allows
    /// the grant ([`Gate::opens`]).
    fn at_door(
        &self,
        caller: Option<&AuthContext>,
        grant: &Grant,
        call: Option<&DispatchedCall>,
        at: &CallAddress,
    ) -> Result<Reach, Refusal> {
        let Some((principal, layers)) = Self::caller_of(caller) else {
            return Err(Refusal::Unauthenticated);
        };
        if let Some(ctx) = caller {
            self.alive_named(ctx).map_err(|reason| Refusal::Ended { reason })?;
        }
        let held = self.inner.memberships.held(&principal);
        let by_membership = held.iter().any(|m| Self::opens(&m.scope, at) && self.lists(&m.role, grant));
        let by_ceiling =
            layers.iter().all(|layer| layer.0.iter().any(|(rg, s)| Self::opens(s, at) && self.entry_allows(rg, grant)));
        let held_on = self.held_on_in(held.iter().map(|m| (&m.role, &m.scope)), &layers, grant);
        if by_membership && by_ceiling {
            Ok(Reach { held_on: held_on.into(), live: Some(self.live(caller, grant, call, true)) })
        } else {
            Err(Refusal::MissingGrant {
                grant: grant.clone(),
                scope: ScopeRef::named(format!("/{}", at.activation())),
                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_in(caller, grant, None).unwrap_or_else(|_| Reach {
            held_on: std::borrow::Cow::Borrowed(&[]),
            live: Some(self.live(caller, grant, None, false)),
        })
    }
}

// ---------------------------------------------------------------------------
// 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");
    }

    /// KEEL-31 (the review's probe, KEEL-28): `admin` held on one ticket is
    /// admitted to a method with no target by [`Gate::check`] — held
    /// somewhere — and refused by [`Gate::check_everywhere`], naming `*`; so
    /// is a session minted narrower than `*`. Held on `*`, it is allowed,
    /// and its reach stays live by the same rule.
    #[test]
    fn a_whole_service_method_needs_its_grant_on_everywhere() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "admin", "MENGER-5");
        m.grant(BOB, "admin", "*");
        let gate = gate(&m);
        let grow = g("dyn.grow");
        assert_eq!(gate.check(Some(&who(ADA)), &grow, None).unwrap().held_on(), [ScopeRef::named("MENGER-5")]);
        match gate.check_everywhere(Some(&who(ADA)), &grow) {
            Err(Refusal::MissingGrant { scope, held_on, .. }) => {
                assert_eq!(scope, ScopeRef::Everywhere);
                assert_eq!(held_on, [ScopeRef::named("MENGER-5")]);
            }
            other => panic!("a scoped admin: {other:?}"),
        }
        let reach = gate.check_everywhere(Some(&who(BOB)), &grow).unwrap();
        assert!(reach.is_everywhere());
        for ceiling in [serde_json::json!(["admin@MENGER-5"]), serde_json::json!(["viewer@*"]), serde_json::json!("admin@*")] {
            let capped = with_ceiling(BOB, ceiling.clone());
            assert!(gate.check_everywhere(Some(&capped), &grow).is_err(), "ceiling {ceiling}");
        }
        assert!(gate.check_everywhere(Some(&with_ceiling(BOB, serde_json::json!(["dyn.grow@*"]))), &grow).is_ok());
        assert!(gate.check_everywhere(Some(&with_ceiling(ADA, serde_json::json!(["admin@*"]))), &grow).is_err(), "a ceiling never widens");
        assert_eq!(gate.check_everywhere(None, &grow).err(), Some(Refusal::Unauthenticated));
        // Live: narrowed to a scope while it runs, the reach is gone.
        m.revoke_all();
        m.grant(BOB, "admin", "MENGER");
        assert!(reach.current().is_none());
        assert!(reach.recheck().is_err());
        assert!(!reach.allows("MENGER-1"));
    }

    /// ONE-6 (review F1): inside the gate too, a dispatched call opens its
    /// door only for the grant it dispatches to — any other grant asked
    /// "at" it is decided as told no call (on `*` alone).
    #[test]
    fn a_dispatched_call_opens_its_door_for_its_own_grant_only() {
        let m = Arc::new(Members::default());
        m.grant(ADA, "admin", "/dyn.connect");
        let gate = gate(&m);
        let connect = DispatchedCall::new(CallAddress::new("dyn", "connect").unwrap(), g("dyn.connect"));
        assert!(gate.everywhere_in(Some(&who(ADA)), &g("dyn.connect"), Some(&connect)).is_ok());
        assert!(gate.everywhere_in(Some(&who(ADA)), &g("dyn.disconnect"), Some(&connect)).is_err());
        assert!(gate.everywhere_in(Some(&who(ADA)), &g("auth.grant"), Some(&connect)).is_err());
    }
}