zenkey-fleet 0.18.0

Fleet engine for keyspace-v2 Zenoh tooling: disciplined fan-in queries, liveliness roster, registry-slice sets, schema-aware decode, live key-tree monitoring — the shared core of zenctl and zengui
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
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
//! The ACL planner (RFC 09 §3, #392): an enrollment file plus, when given,
//! the registry in; the router's `access_control` block out — with every
//! rule naming the matrix row it instantiates and the fact it exists for,
//! every narrowing shown, and every refusal named.
//!
//! RFC 09 §3 has carried a complete recipe since v1.0 and it went undeployed
//! for a year, because writing it by hand is miserable and unverifiable.
//! Four facts shape it, and each one is a way a hand-written block fails
//! **silently and partially**:
//!
//! 1. Matching is keyexpr *inclusion*, and `**` never crosses a verbatim
//!    chunk there either — a host's `…/h-xxx/**` rule does not cover its
//!    `@rpc` replies, `@media` frames or `@blob` keys. One rule per plane.
//! 2. `*` in the origin position never covers `@catalog`; catalog access is
//!    its own rule (RFC 03 §4 D4).
//! 3. The config needs all three lists — `rules`, `subjects`, `policies`;
//!    rules alone are refused at router startup.
//! 4. Under `default_permission: "deny"`, *declarations* need allowing: a
//!    consumer that may not `declare_subscriber` receives nothing, a
//!    producer that may not `declare_queryable` serves nothing, and a query
//!    must be allowed *egress* toward the responder as well as ingress from
//!    the caller.
//!
//! And a fifth, from the reference deployment (2026-08-30), RFC 09 §3
//! fact 5 since v1.33: zenoh evaluates a consumer's declares and queries **on egress
//! toward the responding face, against that face's subject**. A host whose
//! grants are all own-origin (`…/h-xxx/**`) includes no wildcard-origin
//! selector, so a console's `…/v1/**` interest never reaches it, and a
//! peer-mode publisher with no matching interest publishes to nobody. The
//! fix is one shared, **egress-only** rule — [`INTEREST_PROP`] — allowing
//! declares and queries on the fleet's selectors, attached to every
//! publishing principal. It is security-neutral: puts and replies stay
//! ingress-checked. The same fact has a corollary: `**` cannot cross
//! `@catalog` any more than `@adv`, so `@catalog/**/@adv/**` needs spelling
//! out wherever the catalog runs the advanced tier.
//!
//! And a sixth (RFC 09 §3 fact 6, v1.38): **deny is by inclusion**, so
//! [`NO_REMOTE_ACTIONS`] binds only a caller who spells a write's key at
//! least as narrowly as the rule. A query on `…/v1/*/@rpc/**` — which the
//! console's own fleet grant includes — is not included by the literal, and
//! crosses to every queryable it intersects. The rule stays, as the second
//! lock on the door; the refusal of a broadcast write is the *server's*
//! (RFC 05 §2.1, `BringUp::serve_write`), and the rule's cite says so.
//!
//! Pure, like everything in [`crate::model`]: values in hand, no session.
//! [`plan_acl`] takes an *optional* registry and says what it could not
//! narrow without one rather than guessing (RFC 13 §3 O4); [`check_acl`]
//! compares a plan against a block somebody else read off a router's config
//! file; [`explain_acl`] answers "does this principal hold this grant, via
//! which rule, in which direction" over the plan alone, with inclusion
//! computed by `zenoh-keyexpr`. [`to_json5`] is the one rendering of the
//! plan that is not zenkey's — it is `zenohd`'s, field for field
//! `zenoh-config-1.10.0/src/lib.rs`.

use std::collections::{BTreeMap, BTreeSet};

use zenoh::key_expr::keyexpr;

use crate::model::registry::SliceSet;
use crate::report::{
    AclCheck, AclConfigDoc, AclDecision, AclDirection, AclDownsample, AclExplain, AclFinding,
    AclFindingKind, AclFlow, AclGrant, AclMessage, AclPermission, AclPlan, AclPolicy, AclRefusal,
    AclRegistryFacts, AclRule, AclSubject, AclWarning, AclWarningKind, Asked, Enrollment, FaceSpec,
    Judgement, LinkInterval, PrincipalSpec, Role,
};
use crate::{Error, Result};

/// The shared egress-only rule every publishing principal carries — the
/// fifth fact (module doc).
pub const INTEREST_PROP: &str = "interest-prop";
/// The shared deny on the write procedures — the console's
/// `no-remote-actions` row, narrowed by the registry when one was asked.
pub const NO_REMOTE_ACTIONS: &str = "no-remote-actions";
/// The convention's write-procedure leaf (RFC 09 §3, v1.4: a write is keyed
/// `…/set` so a rule can see the actuated resource) — the deny's shape when
/// no registry narrowed it.
pub const UNNARROWED_WRITE_LEAF: &str = "v1/*/@rpc/*/**/set";

/// What the caller decided about the enrollment's dangerous corners.
#[derive(Debug, Clone, Copy, Default)]
pub struct AclOptions {
    /// Admit `zid = "…"` subjects. Off by default: a ZID is not backed by
    /// authentication (zenoh's own config says so).
    pub allow_zid_subjects: bool,
}

// ── The matrix rows ───────────────────────────────────────────────────────

const DECLARES: [AclMessage; 4] = [
    AclMessage::DeclareSubscriber,
    AclMessage::DeclareLivelinessSubscriber,
    AclMessage::LivelinessQuery,
    AclMessage::Query,
];
const RECEIVES: [AclMessage; 4] = [
    AclMessage::Put,
    AclMessage::Delete,
    AclMessage::Reply,
    AclMessage::LivelinessToken,
];

fn wire(base: &str, rel: impl AsRef<str>) -> String {
    zenkey::grammar::with_base(base, rel)
}

/// The planes a consumer names, each spelled because `**` reaches none of
/// them from `v1/**` (fact 1) and `*` never reaches `@catalog` (fact 2).
struct Planes {
    media: bool,
    blob: bool,
    catalog_adv: bool,
}

fn fleet_exprs(base: &str, p: &Planes) -> Vec<String> {
    let mut out = vec![
        wire(base, "v1/**"),
        wire(base, "v1/@catalog/**"),
        wire(base, "v1/*/@rpc/**"),
        wire(base, "v1/@catalog/@rpc/**"),
    ];
    if p.blob {
        out.push(wire(base, "v1/*/@blob/**"));
    }
    if p.media {
        out.push(wire(base, "v1/*/@media/**"));
    }
    out.push(wire(base, "v1/**/@adv/**"));
    if p.catalog_adv {
        out.push(wire(base, "v1/@catalog/**/@adv/**"));
    }
    out
}

/// The `@adv` sidecar expressions, catalog sibling included when the
/// catalog runs the tier.
fn adv_exprs(base: &str, catalog_adv: bool) -> Vec<String> {
    let mut out = vec![wire(base, "v1/**/@adv/**")];
    if catalog_adv {
        out.push(wire(base, "v1/@catalog/**/@adv/**"));
    }
    out
}

fn rule(
    id: impl Into<String>,
    permission: AclPermission,
    flows: Option<&[AclFlow]>,
    messages: &[AclMessage],
    key_exprs: Vec<String>,
    purpose: &str,
    cite: &str,
) -> AclRule {
    AclRule {
        id: id.into(),
        permission,
        flows: flows.map(<[AclFlow]>::to_vec),
        messages: messages.to_vec(),
        key_exprs,
        purpose: purpose.into(),
        cite: cite.into(),
    }
}

const IN: &[AclFlow] = &[AclFlow::Ingress];
const OUT: &[AclFlow] = &[AclFlow::Egress];

/// A service origin's chunk without its `@`, for rule ids.
fn id_chunk(origin: &str) -> &str {
    origin.strip_prefix('@').unwrap_or(origin)
}

// ── The registry's part ───────────────────────────────────────────────────

fn registry_facts(slices: &SliceSet) -> AclRegistryFacts {
    let mut media_producers = Vec::new();
    let mut blob_producers = Vec::new();
    let mut write_procedures = Vec::new();
    let mut sensitive_procedures = Vec::new();
    for slice in slices.slices() {
        if slice.service_origin.is_none() {
            if !slice.media.is_empty() {
                media_producers.push(slice.name.clone());
            }
            if !slice.blob.is_empty() {
                blob_producers.push(slice.name.clone());
            }
        }
        for p in &slice.procedures {
            if p.kind
                .as_ref()
                .is_some_and(|k| k.is(&zenkey::slice::ProcedureKind::Write))
            {
                write_procedures.push(format!("{}/{}", slice.name, p.path));
                if p.sensitive == Some(true) {
                    sensitive_procedures.push(format!("{}/{}", slice.name, p.path));
                }
            }
        }
    }
    media_producers.sort();
    blob_producers.sort();
    write_procedures.sort();
    sensitive_procedures.sort();
    AclRegistryFacts {
        slices: slices.slices().len(),
        media_producers,
        blob_producers,
        write_procedures,
        sensitive_procedures,
    }
}

/// A registry path as a key expression: every `{var}` chunk is a `*`, and a
/// `{var...}` rest chunk (subjects only; refused on procedures) is a `**`.
fn procedure_pattern(path: &str) -> String {
    path.split('/')
        .map(|c| {
            if c.starts_with('{') && c.ends_with("...}") {
                "**"
            } else if c.starts_with('{') && c.ends_with('}') {
                "*"
            } else {
                c
            }
        })
        .collect::<Vec<_>>()
        .join("/")
}

/// Every declared write procedure's key expression, under the base.
fn write_exprs(base: &str, slices: &SliceSet) -> Vec<String> {
    procedure_exprs(base, slices, |p| {
        p.kind
            .as_ref()
            .is_some_and(|k| k.is(&zenkey::slice::ProcedureKind::Write))
    })
}

/// The `sensitive = true` writes (RFC 08 §2, v1.43), under the base.
fn sensitive_exprs(base: &str, slices: &SliceSet) -> Vec<String> {
    procedure_exprs(base, slices, |p| {
        p.sensitive == Some(true)
            && p.kind
                .as_ref()
                .is_some_and(|k| k.is(&zenkey::slice::ProcedureKind::Write))
    })
}

fn procedure_exprs(
    base: &str,
    slices: &SliceSet,
    keep: impl Fn(&zenkey::slice::ProcedureDecl) -> bool,
) -> Vec<String> {
    let mut out = BTreeSet::new();
    for slice in slices.slices() {
        let origin = slice
            .service_origin
            .as_ref()
            .map_or("*".to_string(), |o| o.token().to_string());
        for p in &slice.procedures {
            if keep(p) {
                out.insert(wire(
                    base,
                    format!(
                        "v1/{origin}/@rpc/{}/{}",
                        slice.name,
                        procedure_pattern(&p.path)
                    ),
                ));
            }
        }
    }
    out.into_iter().collect()
}

// ── The principals ────────────────────────────────────────────────────────

/// How a principal names itself in a refusal.
fn principal_name(index: usize, p: &PrincipalSpec) -> String {
    p.id.clone()
        .or_else(|| p.cn.clone())
        .or_else(|| p.user.clone())
        .or_else(|| p.zid.clone())
        .unwrap_or_else(|| format!("principal #{}", index + 1))
}

/// The refusal a principal's write grants earn whatever plan it is in: a
/// watch is read-only, and only a console takes a grant (RFC 09 §3).
fn grant_refusal(p: &PrincipalSpec) -> Option<String> {
    if p.remote_actions && p.role == Role::Watch {
        return Some(
            "a watch is read-only by definition; `remote_actions = true` wants a console".into(),
        );
    }
    if !p.writes.is_empty() && p.role != Role::Console {
        return Some(format!(
            "`writes` grants belong to a console; a {} {}",
            p.role.as_str(),
            if p.role == Role::Watch {
                "is read-only by definition"
            } else {
                "acts as itself and needs no grant"
            }
        ));
    }
    None
}

/// A host's origin: given, computed from its machine-id, or both in
/// agreement (RFC 06 §1).
fn host_origin(
    p: &PrincipalSpec,
    salt: Option<&str>,
) -> std::result::Result<String, (String, &'static str)> {
    let given = p.origin.as_deref();
    if let Some(o) = given
        && !zenkey::grammar::is_valid_host_origin(o)
    {
        return Err((
            format!("origin {o:?} is not an `h-<12 hex>` host origin"),
            "RFC 06 §1",
        ));
    }
    let Some(machine_id) = p.machine_id.as_deref() else {
        return given.map(str::to_string).ok_or((
            "a host needs `origin` or `machine_id` — nothing in the grammar binds a \
             transport identity to an origin, so the enrollment has to"
                .to_string(),
            "RFC 03 §4 D6",
        ));
    };
    let trimmed = machine_id.trim();
    if trimmed.len() != 32 || !trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err((
            format!("machine_id {machine_id:?} is not the 32 hex chars of /etc/machine-id"),
            "RFC 06 §1",
        ));
    }
    let Some(salt) = salt else {
        return Err((
            "machine_id needs the application's origin salt: set `[fleet] salt`".to_string(),
            "RFC 06 §1",
        ));
    };
    // The salt is an application *constant* by design (RFC 06 §1 "salt
    // scope"), and `OriginSalt` says so in its type. The enrollment's stands
    // in for one, and leaking it is what makes a runtime string into that
    // constant — once per plan, a few bytes, in a process that plans once.
    let salt: &'static str = Box::leak(salt.to_string().into_boxed_str());
    let computed = zenkey::origin::HostId::from_machine_id(trimmed, zenkey::OriginSalt::new(salt));
    let computed = computed.as_str().to_string();
    match given {
        Some(o) if o != computed => Err((
            format!(
                "origin {o:?} disagrees with the origin computed from machine_id under this \
                 salt, {computed:?} — one of the three is wrong, and a rule pinned to the \
                 wrong origin fails silently"
            ),
            "RFC 06 §1",
        )),
        _ => Ok(computed),
    }
}

/// A service principal's origin: the default for its role, or a verbatim
/// `@…` chunk it names.
fn service_origin(
    p: &PrincipalSpec,
    default: &str,
) -> std::result::Result<String, (String, &'static str)> {
    match p.origin.as_deref() {
        None => Ok(default.to_string()),
        Some(o) if zenkey::grammar::is_valid_verbatim_chunk(o) => Ok(o.to_string()),
        Some(o) => Err((
            format!("origin {o:?} is not a verbatim `@…` service origin"),
            "RFC 03 §1.2",
        )),
    }
}

fn warn(
    kind: AclWarningKind,
    principal: Option<&str>,
    cite: &str,
    text: impl Into<String>,
) -> AclWarning {
    AclWarning {
        kind,
        principal: principal.map(str::to_string),
        text: text.into(),
        cite: cite.into(),
    }
}

/// Rules keyed by id, in first-insertion order; a second identical push is
/// a no-op (two CNs enrolled for one origin share its rules).
#[derive(Default)]
struct Rules {
    order: Vec<String>,
    by_id: BTreeMap<String, AclRule>,
}

impl Rules {
    fn push(&mut self, r: AclRule) -> String {
        let id = r.id.clone();
        if !self.by_id.contains_key(&id) {
            self.order.push(id.clone());
            self.by_id.insert(id.clone(), r);
        }
        id
    }

    fn into_vec(self) -> Vec<AclRule> {
        let mut by_id = self.by_id;
        self.order
            .into_iter()
            .filter_map(|id| by_id.remove(&id))
            .collect()
    }
}

// ── The plan ──────────────────────────────────────────────────────────────

/// Plan the `access_control` block for an enrollment under `base`.
///
/// `slices`, when given, **narrows** the plan to what the fleet serves: a
/// host's `@media` and `@blob` rules exist only where some host producer
/// declares the plane, and `no-remote-actions` denies exactly the declared
/// `kind = "write"` procedures. Without one, the planes are what the
/// enrollment claims and the deny is the convention's `set` leaf — and the
/// plan says so (RFC 13 §3 O4).
///
/// A refused principal is left out of `subjects` and `policies` and named
/// in `refusals`; the plan is still emitted around it.
pub fn plan_acl(
    enrollment: &Enrollment,
    base: &str,
    slices: Option<&SliceSet>,
    opts: AclOptions,
) -> AclPlan {
    let mut rules = Rules::default();
    let mut subjects = Vec::new();
    let mut policies = Vec::new();
    let mut warnings = Vec::new();
    let mut refusals = Vec::new();

    let facts = slices.map(registry_facts);
    let catalog_adv = enrollment.fleet.catalog_adv;
    let salt = enrollment.fleet.salt.as_deref();

    // What the fleet serves, for the consumers' plane lists: without a
    // registry, everything the enrollment's hosts claim.
    let claimed_media = enrollment
        .principal
        .iter()
        .any(|p| p.role == Role::Host && p.media);
    let planes = match &facts {
        Some(f) => Planes {
            media: !f.media_producers.is_empty(),
            // `@blob` is served by any declarer; seeding is one host's
            // choice on top.
            blob: !f.blob_producers.is_empty(),
            catalog_adv,
        },
        None => Planes {
            media: claimed_media,
            // Without a registry the RFC row stands: every host serves
            // `@blob` (RFC 07 §2 makes it a plane every host may serve).
            blob: true,
            catalog_adv,
        },
    };

    // The write set the consumers are denied.
    let write_set: Vec<String> = match slices {
        Some(s) => {
            let exprs = write_exprs(base, s);
            if exprs.is_empty() {
                warnings.push(warn(
                    AclWarningKind::NoWriteProcedures,
                    None,
                    "RFC 09 §3",
                    "the registry declares no `kind = \"write\"` procedure, so the \
                     no-remote-actions deny is omitted — zenoh refuses a rule with no \
                     key expression",
                ));
            }
            exprs
        }
        None => {
            warnings.push(warn(
                AclWarningKind::WriteSetNotNarrowed,
                None,
                "RFC 13 §3 O4",
                format!(
                    "no registry asked: the planes are as the enrollment claims, and \
                     no-remote-actions denies the convention's write leaf {} rather than \
                     the declared write procedures — pass --registry <dir> to narrow both \
                     to what the fleet actually declares",
                    wire(base, UNNARROWED_WRITE_LEAF)
                ),
            ));
            vec![wire(base, UNNARROWED_WRITE_LEAF)]
        }
    };

    // The sensitive writes (RFC 08 §2, v1.43): denied to every principal,
    // `remote_actions` or not, until a grant names one. Unknown without a
    // registry, and an unknown set denies nothing extra — the unnarrowed
    // leaf already denies every write.
    let sensitive_set: Vec<String> = slices.map(|s| sensitive_exprs(base, s)).unwrap_or_default();
    let narrowed = slices.is_some();

    let interest_prop = || {
        rule(
            INTEREST_PROP,
            AclPermission::Allow,
            Some(OUT),
            &DECLARES,
            fleet_exprs(base, &planes),
            "interest-prop",
            "the fifth fact (reference deployment 2026-08-30): zenoh checks a consumer's \
             declares and queries on egress toward the responding face against that \
             face's subject, and own-origin grants include no wildcard-origin selector \
             — without this a peer-mode publisher publishes to nobody. Egress-only, \
             declares and queries only: puts and replies stay ingress-checked",
        )
    };

    let mut seen_ids = BTreeSet::new();
    let mut seen_cns = BTreeSet::new();
    let mut seen_users = BTreeSet::new();
    let mut seen_zids = BTreeSet::new();
    let mut hosts = 0usize;
    let mut consumers = 0usize;

    for (i, p) in enrollment.principal.iter().enumerate() {
        let name = principal_name(i, p);
        let mut refuse = |reason: String, cite: &str| {
            refusals.push(AclRefusal {
                principal: name.clone(),
                reason,
                cite: cite.into(),
            });
        };

        // The subject: who this is on the wire.
        let cn = p.cn.as_deref().filter(|s| !s.is_empty());
        let zid = p.zid.as_deref().filter(|s| !s.is_empty());
        let user = p.user.as_deref().filter(|s| !s.is_empty());
        if cn.is_none() && zid.is_none() && user.is_none() {
            refuse(
                "a principal needs a `cn` (the certificate common name) or a `user` (a zenoh \
                 usrpwd user name) — that is the enrollment"
                    .into(),
                "RFC 03 §4 D6",
            );
            continue;
        }
        if let Some(z) = zid
            && !opts.allow_zid_subjects
        {
            refuse(
                format!(
                    "zid {z:?} as a subject is refused: a ZID is not backed by an \
                     authentication mechanism and can only be trusted for ACL when a \
                     dedicated zenoh mechanism manages it (zenoh's own config says so); \
                     pass --allow-zid-subjects for a prototype, never a deployment"
                ),
                "zenoh-1.10.0/DEFAULT_CONFIG.json5",
            );
            continue;
        }
        if let Some(c) = cn
            && !seen_cns.insert(c.to_string())
        {
            refuse(
                format!("cn {c:?} is already enrolled — one transport identity, one principal"),
                "RFC 03 §4 D6",
            );
            continue;
        }
        if let Some(u) = user
            && !seen_users.insert(u.to_string())
        {
            refuse(
                format!("user {u:?} is already enrolled — one transport identity, one principal"),
                "RFC 03 §4 D6",
            );
            continue;
        }
        if let Some(z) = zid
            && !seen_zids.insert(z.to_string())
        {
            refuse(format!("zid {z:?} is already enrolled"), "RFC 03 §4 D6");
            continue;
        }
        let sid =
            p.id.clone()
                .or_else(|| cn.map(str::to_string))
                .or_else(|| user.map(str::to_string))
                .or_else(|| zid.map(str::to_string))
                .expect("cn, user or zid is present");
        if !seen_ids.insert(sid.clone()) {
            refuse(
                format!("subject id {sid:?} is already taken — give this principal an `id`"),
                "zenoh-config: subject ids are unique",
            );
            continue;
        }
        if let Some(z) = zid {
            warnings.push(warn(
                AclWarningKind::ZidSubject,
                Some(&sid),
                "zenoh-1.10.0/DEFAULT_CONFIG.json5",
                format!(
                    "subject {sid:?} is bound by zid {z:?}: prototyping only — a ZID is not \
                     backed by authentication and a peer can present any"
                ),
            ));
        }
        if let Some(reason) = grant_refusal(p) {
            refuse(reason, "RFC 09 §3");
            continue;
        }
        if p.role == Role::Link {
            refuse(
                "a link is a face, not a principal: it is selected by its transport and \
                 planned by `acl gen --face` from the registry's exposure markers"
                    .into(),
                "RFC 09 §4",
            );
            continue;
        }

        // The role's rules.
        let mut ids: Vec<String> = Vec::new();
        match p.role {
            Role::Host => {
                let origin = match host_origin(p, salt) {
                    Ok(o) => o,
                    Err((reason, cite)) => {
                        refuse(reason, cite);
                        continue;
                    }
                };
                hosts += 1;
                let o = origin.as_str();
                ids.push(rules.push(rule(
                    format!("host-data-{o}"),
                    AclPermission::Allow,
                    Some(IN),
                    &[
                        AclMessage::Put,
                        AclMessage::Delete,
                        AclMessage::LivelinessToken,
                    ],
                    vec![wire(base, format!("v1/{o}/**"))],
                    "host-data",
                    "RFC 09 §3 fact 1: the data classes and the alive tokens — and nothing \
                     under @rpc, @media or @blob, which `**` never reaches",
                )));
                // `@blob` rides host-serve where the plane is served at all.
                let mut serve = vec![wire(base, format!("v1/{o}/@rpc/**"))];
                if planes.blob {
                    serve.push(wire(base, format!("v1/{o}/@blob/**")));
                }
                ids.push(rules.push(rule(
                    format!("host-serve-{o}"),
                    AclPermission::Allow,
                    None,
                    &[
                        AclMessage::DeclareQueryable,
                        AclMessage::Reply,
                        AclMessage::Query,
                    ],
                    serve,
                    "host-serve",
                    "RFC 09 §3 facts 1 and 4: @rpc spelled explicitly because `**` will not \
                     cross it; declare_queryable allowed or the host serves nothing; query \
                     egress is the router forwarding calls to it",
                )));
                if p.media {
                    if planes.media {
                        ids.push(rules.push(rule(
                            format!("host-media-{o}"),
                            AclPermission::Allow,
                            Some(IN),
                            &[AclMessage::Put],
                            vec![wire(base, format!("v1/{o}/@media/**"))],
                            "host-media",
                            "RFC 09 §3 fact 1: the plane needs its own rule",
                        )));
                    } else {
                        warnings.push(warn(
                            AclWarningKind::PlaneNotDeclared,
                            Some(&sid),
                            "RFC 08 §2",
                            "media = true, but no host producer in the registry declares \
                             [[media]] — host-media omitted; the enrollment claims a plane \
                             the fleet does not serve",
                        ));
                    }
                }
                if p.blob_seed {
                    if planes.blob {
                        ids.push(rules.push(rule(
                            format!("host-blob-seed-{o}"),
                            AclPermission::Allow,
                            Some(IN),
                            &[AclMessage::Put],
                            vec![
                                wire(base, format!("v1/{o}/@blob/store/**")),
                                wire(base, format!("v1/{o}/@blob/tree/**")),
                            ],
                            "host-blob-seed",
                            "RFC 09 §3, RFC 07 §2: the sanctioned one-shot PUT path into the \
                             router content store — omit in deployments without one",
                        )));
                    } else {
                        warnings.push(warn(
                            AclWarningKind::PlaneNotDeclared,
                            Some(&sid),
                            "RFC 08 §2",
                            "blob_seed = true, but no host producer in the registry declares \
                             [[blob]] — host-blob-seed omitted",
                        ));
                    }
                }
                if p.adv {
                    ids.push(rules.push(rule(
                        format!("host-adv-{o}"),
                        AclPermission::Allow,
                        None,
                        &[
                            AclMessage::Put,
                            AclMessage::LivelinessToken,
                            AclMessage::DeclareQueryable,
                            AclMessage::Reply,
                            AclMessage::Query,
                        ],
                        vec![wire(base, format!("v1/{o}/**/@adv/**"))],
                        "host-adv",
                        "RFC 09 §3, RFC 04 §3.3: the sidecars live under a verbatim @adv \
                         suffix host-data's `**` cannot reach — omitting this when the tier \
                         is in use fails silently: empty seeds, dead recovery",
                    )));
                }
                ids.push(rules.push(interest_prop()));
            }
            Role::Catalog => {
                let origin = match service_origin(p, zenkey::grammar::SERVICE_CATALOG) {
                    Ok(o) => o,
                    Err((reason, cite)) => {
                        refuse(reason, cite);
                        continue;
                    }
                };
                consumers += 1;
                let o = origin.as_str();
                let c = id_chunk(o);
                let mut own = vec![
                    wire(base, format!("v1/{o}/**")),
                    wire(base, format!("v1/{o}/@rpc/**")),
                ];
                if catalog_adv {
                    own.push(wire(base, format!("v1/{o}/**/@adv/**")));
                }
                ids.push(rules.push(rule(
                    format!("catalog-own-{c}"),
                    AclPermission::Allow,
                    None,
                    &[
                        AclMessage::Put,
                        AclMessage::Delete,
                        AclMessage::LivelinessToken,
                        AclMessage::DeclareQueryable,
                        AclMessage::Reply,
                        AclMessage::Query,
                    ],
                    own,
                    "catalog-own",
                    "RFC 09 §3 fact 2: `*` never covers a verbatim origin, so the catalog's \
                     own keys are their own rule — @rpc and, on the advanced tier, @adv \
                     spelled beside them (fact 1)",
                )));
                let intake = if catalog_adv {
                    vec![wire(base, "v1/**"), wire(base, "v1/**/@adv/**")]
                } else {
                    vec![wire(base, "v1/**")]
                };
                ids.push(rules.push(rule(
                    format!("catalog-intake-declare-{c}"),
                    AclPermission::Allow,
                    Some(IN),
                    &DECLARES,
                    intake.clone(),
                    "catalog-intake-declare",
                    "RFC 09 §3 fact 4: the catalog DECLARES interest on ingress; split by flow \
                     from the receive half so it cannot ingress-publish any host's keys",
                )));
                ids.push(rules.push(rule(
                    format!("catalog-intake-recv-{c}"),
                    AclPermission::Allow,
                    Some(OUT),
                    &RECEIVES,
                    intake,
                    "catalog-intake-recv",
                    "RFC 09 §3: the catalog RECEIVES data and tokens on egress — a flowless \
                     rule here would let it tombstone any host's keys, defeating the \
                     per-host enrollment",
                )));
                ids.push(rules.push(interest_prop()));
            }
            Role::Console => {
                consumers += 1;
                ids.push(rules.push(rule(
                    "ops-sub",
                    AclPermission::Allow,
                    Some(IN),
                    &DECLARES,
                    fleet_exprs(base, &planes),
                    "ops-sub",
                    "RFC 09 §3 fact 4: every plane named, because a declare that is not \
                     allowed receives nothing and `**` reaches no verbatim plane (fact 1)",
                )));
                ids.push(rules.push(rule(
                    "ops-recv",
                    AclPermission::Allow,
                    Some(OUT),
                    &RECEIVES,
                    fleet_exprs(base, &planes),
                    "ops-recv",
                    "RFC 09 §3: what the console receives, on egress, over the same planes",
                )));
                if p.adv {
                    ids.push(rules.push(rule(
                        "ops-own-token",
                        AclPermission::Allow,
                        Some(IN),
                        &[AclMessage::LivelinessToken],
                        adv_exprs(base, catalog_adv),
                        "ops-own-token",
                        "RFC 09 §3: the console's own subscriber-detection token, confined to \
                         @adv — a broad ingress liveliness_token allow would let it forge \
                         any host's state/*/alive roster entry",
                    )));
                }
                for r in write_rules(
                    base,
                    &sid,
                    p,
                    &write_set,
                    &sensitive_set,
                    narrowed,
                    &mut warnings,
                ) {
                    ids.push(rules.push(r));
                }
            }
            Role::Watch => {
                consumers += 1;
                let read_only = Planes {
                    media: false,
                    blob: false,
                    catalog_adv,
                };
                ids.push(rules.push(rule(
                    "watch-sub",
                    AclPermission::Allow,
                    Some(IN),
                    &DECLARES,
                    fleet_exprs(base, &read_only),
                    "watch-sub",
                    "RFC 09 §3 fact 4, for a read-only observer: the data classes, the \
                     catalog and RPC reads — never @media, never @blob",
                )));
                ids.push(rules.push(rule(
                    "watch-recv",
                    AclPermission::Allow,
                    Some(OUT),
                    &RECEIVES,
                    fleet_exprs(base, &read_only),
                    "watch-recv",
                    "RFC 09 §3: what a read-only observer receives, on egress",
                )));
                if p.adv {
                    ids.push(rules.push(rule(
                        "ops-own-token",
                        AclPermission::Allow,
                        Some(IN),
                        &[AclMessage::LivelinessToken],
                        adv_exprs(base, catalog_adv),
                        "ops-own-token",
                        "RFC 09 §3: the observer's own subscriber-detection token, confined \
                         to @adv",
                    )));
                }
                for r in write_rules(
                    base,
                    &sid,
                    p,
                    &write_set,
                    &sensitive_set,
                    narrowed,
                    &mut warnings,
                ) {
                    ids.push(rules.push(r));
                }
            }
            Role::Link => unreachable!("refused above"),
            Role::DesiredAuthor => {
                let origin = match service_origin(p, "@desired") {
                    Ok(o) => o,
                    Err((reason, cite)) => {
                        refuse(reason, cite);
                        continue;
                    }
                };
                let o = origin.as_str();
                ids.push(rules.push(rule(
                    format!("desired-author-{}", id_chunk(o)),
                    AclPermission::Allow,
                    Some(IN),
                    &[AclMessage::Put, AclMessage::Delete],
                    vec![wire(base, format!("v1/{o}/state/**"))],
                    "desired-author",
                    "RFC 09 §3, RFC 07 §3: exactly one ingress put/delete grant, on its OWN \
                     service-origin subtree — never on a host origin; the target host id is \
                     the first subject chunk, not the origin, so it cannot forge a host's \
                     state",
                )));
                ids.push(rules.push(interest_prop()));
            }
        }

        subjects.push(AclSubject {
            id: sid.clone(),
            role: p.role,
            cert_common_names: cn.map(|c| vec![c.to_string()]).unwrap_or_default(),
            zids: zid.map(|z| vec![z.to_string()]).unwrap_or_default(),
            usernames: user.map(|u| vec![u.to_string()]).unwrap_or_default(),
            link_protocols: Vec::new(),
            interfaces: Vec::new(),
        });
        policies.push(AclPolicy {
            id: sid.clone(),
            rules: ids,
            subjects: vec![sid],
        });
    }

    if hosts == 0 {
        warnings.push(warn(
            AclWarningKind::RoleAbsent,
            None,
            "RFC 09 §3",
            "no host enrolled: nothing in this fleet may publish an origin",
        ));
    }
    if consumers == 0 {
        warnings.push(warn(
            AclWarningKind::RoleAbsent,
            None,
            "RFC 09 §3 fact 4",
            "no catalog, console or watch enrolled: nothing may declare interest, so \
             every host publishes to nobody",
        ));
    }

    AclPlan {
        base: base.to_string(),
        default_permission: AclPermission::Deny,
        registry: facts.map_or(Asked::NotAsked, Asked::Asked),
        rules: rules.into_vec(),
        subjects,
        policies,
        downsampling: Vec::new(),
        warnings,
        refusals,
    }
}

/// One consumer's write rules (RFC 09 §3, v1.43): its `writes` grants, and
/// its deny — the shared `no-remote-actions` when nothing carves it, a
/// per-principal deny when a grant or `remote_actions` does.
///
/// Deny wins in zenoh, so a grant cannot punch a hole in a deny: the deny
/// has to be the declared writes *minus* what the grants include, which is
/// why a grant needs the registry — the unnarrowed leaf has nothing to
/// subtract from. A `sensitive` write stays in the deny for every
/// principal, `remote_actions` or not, unless a grant includes it.
fn write_rules(
    base: &str,
    sid: &str,
    p: &PrincipalSpec,
    write_set: &[String],
    sensitive_set: &[String],
    narrowed: bool,
    warnings: &mut Vec<AclWarning>,
) -> Vec<AclRule> {
    let mut out = Vec::new();
    let mut grants: Vec<String> = Vec::new();
    if !p.writes.is_empty() {
        if narrowed {
            for pattern in &p.writes {
                let expr = wire(base, format!("v1/*/@rpc/{pattern}"));
                let Ok(ke) = keyexpr::new(expr.as_str()) else {
                    warnings.push(warn(
                        AclWarningKind::GrantMatchesNothing,
                        Some(sid),
                        "RFC 03 §2",
                        format!(
                            "writes pattern {pattern:?} is not a valid key expression — skipped"
                        ),
                    ));
                    continue;
                };
                let covers = write_set
                    .iter()
                    .filter(|w| keyexpr::new(w.as_str()).is_ok_and(|wk| ke.includes(wk)))
                    .count();
                if covers == 0 {
                    // Overlapping a declared write without including it is
                    // not a carve: the deny keeps the write whole, because
                    // no finite set of key expressions includes every key of
                    // `config/*/*/set` but `config/rf0/air/set` — a `*`
                    // cannot be subtracted from — and deny wins. An allow
                    // emitted anyway would never decide (v1.49).
                    let overlapped: Vec<&str> = write_set
                        .iter()
                        .filter(|w| keyexpr::new(w.as_str()).is_ok_and(|wk| ke.intersects(wk)))
                        .map(String::as_str)
                        .collect();
                    if !overlapped.is_empty() {
                        warnings.push(warn(
                            AclWarningKind::GrantCannotCarve,
                            Some(sid),
                            "RFC 09 §3 (v1.49)",
                            format!(
                                "writes pattern {pattern:?} overlaps the declared write {} \
                                 without including it: deny wins and is by inclusion, and no \
                                 finite deny includes every key of that write but the grant's — \
                                 a `*` chunk cannot be subtracted from — so the deny keeps it \
                                 whole and the grant would never decide; not emitted. Grant the \
                                 write as the registry spells it (every {{var}} a `*`), or \
                                 declare the resource as a literal chunk",
                                overlapped.join(", ")
                            ),
                        ));
                        continue;
                    }
                    warnings.push(warn(
                        AclWarningKind::GrantMatchesNothing,
                        Some(sid),
                        "RFC 09 §3",
                        format!(
                            "writes pattern {pattern:?} intersects no declared write procedure — \
                             allowed as spelled, but nothing the registry knows answers there"
                        ),
                    ));
                }
                grants.push(expr);
            }
        } else {
            warnings.push(warn(
                AclWarningKind::GrantNotNarrowed,
                Some(sid),
                "RFC 09 §3",
                format!(
                    "writes = {:?} needs the registry: deny wins, so a grant is a carve-out of \
                     the deny, and without a registry the deny is the unnarrowed leaf with \
                     nothing to subtract — no grant emitted, the deny stays whole; pass \
                     --registry <dir>",
                    p.writes
                ),
            ));
        }
    }
    let granted = |w: &String| {
        grants.iter().any(|g| {
            keyexpr::new(g.as_str())
                .is_ok_and(|gk| keyexpr::new(w.as_str()).is_ok_and(|wk| gk.includes(wk)))
        })
    };
    if !grants.is_empty() {
        out.push(rule(
            format!("writes-{sid}"),
            AclPermission::Allow,
            None,
            &[AclMessage::Query],
            grants.clone(),
            "writes",
            "RFC 09 §3 (v1.43): a per-resource write grant — the resource is a path chunk, \
             so the grant is a literal prefix; the deny below is carved around it, \
             because deny wins and a carve-out has to be an absence",
        ));
    }
    let deny: Vec<String> = if p.remote_actions {
        sensitive_set
            .iter()
            .filter(|w| !granted(w))
            .cloned()
            .collect()
    } else {
        write_set.iter().filter(|w| !granted(w)).cloned().collect()
    };
    if deny.is_empty() {
        return out;
    }
    if deny == write_set {
        out.push(rule(
            NO_REMOTE_ACTIONS,
            AclPermission::Deny,
            None,
            &[AclMessage::Query],
            deny,
            "no-remote-actions",
            "RFC 09 §3: the write procedures are deniable per key because the key \
             IS the target; deny wins for a caller who spells it, and fact 6 \
             leaves a broader query to the server (RFC 05 §2.1)",
        ));
    } else {
        out.push(rule(
            format!("{NO_REMOTE_ACTIONS}-{sid}"),
            AclPermission::Deny,
            None,
            &[AclMessage::Query],
            deny,
            "no-remote-actions",
            if p.remote_actions {
                "RFC 08 §2 (v1.43): the sensitive writes stay denied to a console that may \
                 act — RFC 8341's default-deny-all as data — until a `writes` grant names one"
            } else {
                "RFC 09 §3 (v1.43): the declared writes this principal's grants do not \
                 include — carved, because deny wins and a grant cannot punch a hole"
            },
        ));
    }
    out
}

// ── The constrained face ──────────────────────────────────────────────────

const BOTH: &[AclFlow] = &[AclFlow::Egress, AclFlow::Ingress];

/// What a data class can carry over a face — the message kinds a deny on
/// it must name, both flows, because a rule that names neither relies on
/// a default the next zenoh may read differently.
fn class_messages(class: &str) -> &'static [AclMessage] {
    match class {
        "state" => &AclMessage::ALL,
        _ => &[
            AclMessage::Put,
            AclMessage::Delete,
            AclMessage::DeclareSubscriber,
            AclMessage::Query,
            AclMessage::Reply,
            AclMessage::DeclareQueryable,
        ],
    }
}

/// Plan one constrained face (RFC 09 §4, v1.43) from the registry's
/// `exposure` markers: the `access_control` block that keeps `host`
/// surfaces off the link, the `downsampling` block that caps the `link`
/// ones, and a note naming what still crosses.
///
/// Two facts shape the block, both found the hard way by the reference
/// adopter: `default_permission` is node-global, so a face-scoped deny
/// lives under `allow` and the host bus keeps flowing by absence; and deny
/// is by inclusion (RFC 09 §3 fact 6), so a *plane* is denied by its widest
/// spelling (`**/@rpc/**`), never by a producer-scoped literal a broader
/// query would step over. The default exposure is `fleet`, so an unmarked
/// registry crosses whole — said in a warning, never denied on the
/// planner's initiative: the registry is where the classification belongs.
///
/// `principals` are the enrollment's (v1.49). A `user` console or watch —
/// an operator on the far side, authenticated by the face's `usrpwd` — gets
/// a subject of its own on the face's transport, and that subject has to
/// **repeat every face deny**, because a transport matches every subject
/// whose properties match, the face's own included, and across matching
/// subjects zenoh lets **any allow win** (`AclActionMethods::action`,
/// `zenoh-1.10.0/src/net/routing/interceptor/access_control.rs`): a
/// principal subject holding only an allow, under this block's permissive
/// default, would evaluate Allow for everything the face denies. Of
/// `deny-rpc` it repeats the legs no call uses and carves the three a call
/// does (query, reply, declare_queryable) to the console's write shape —
/// `write_rules`, the declared writes no grant includes. Its denies are
/// therefore a subset of the face's, so its own evaluation is the
/// principal's whole answer. Every other principal is refused, never
/// dropped.
pub fn plan_face(
    slices: &SliceSet,
    base: &str,
    spec: &FaceSpec,
    principals: &[PrincipalSpec],
) -> AclPlan {
    use zenkey::slice::{Declared, Exposure};

    let mut rules = Rules::default();
    let mut ids: Vec<String> = Vec::new();
    let mut warnings = Vec::new();
    let mut downsampling: Vec<AclDownsample> = Vec::new();

    // A `link` entry is affordable only when the face states a rate; with
    // none, it is kept home like a `host` one.
    let effective = |d: Option<&Declared<Exposure>>| -> Exposure {
        match d {
            Some(Declared::Known(Exposure::Host)) => Exposure::Host,
            Some(Declared::Known(Exposure::Link)) => match spec.interval {
                LinkInterval::None => Exposure::Host,
                LinkInterval::EverySecs(_) => Exposure::Link,
            },
            // Unmarked, or a token this build cannot read: it crosses, and
            // the note below says so.
            _ => Exposure::Fleet,
        }
    };

    let mut sorted: Vec<&zenkey::slice::RegistrySlice> = slices.slices().iter().collect();
    sorted.sort_by(|a, b| a.name.cmp(&b.name));

    let mut any_host_procedure = false;
    let mut cut_procedures: Vec<String> = Vec::new();
    let mut open_procedures: Vec<String> = Vec::new();

    for slice in &sorted {
        let origin = slice
            .service_origin
            .as_ref()
            .map_or("*".to_string(), |o| o.token().to_string());
        let producer = slice.name.as_str();
        let mut by_class: BTreeMap<String, Vec<&zenkey::slice::SubjectDecl>> = BTreeMap::new();
        for s in &slice.subjects {
            by_class
                .entry(s.class.token().to_string())
                .or_default()
                .push(s);
        }
        let mut crosses: Vec<String> = Vec::new();
        for (class, subjects) in &by_class {
            let mut kept: Vec<String> = Vec::new();
            for s in subjects {
                let key = wire(
                    base,
                    format!(
                        "v1/{origin}/{class}/{producer}/{}",
                        procedure_pattern(&s.path)
                    ),
                );
                match effective(s.exposure.as_ref()) {
                    Exposure::Host => kept.push(key),
                    Exposure::Link => {
                        if let LinkInterval::EverySecs(secs) = spec.interval {
                            downsampling.push(AclDownsample {
                                key_expr: key,
                                freq: 1.0 / secs.max(1) as f64,
                            });
                        }
                    }
                    Exposure::Fleet => crosses.push(format!("{class}/{}", s.path)),
                }
            }
            if kept.is_empty() {
                continue;
            }
            if kept.len() == subjects.len() {
                // Every subject of the class stays home: one deny on the
                // subtree, which also covers the framework keys under it.
                ids.push(rules.push(rule(
                    format!("deny-{class}-{producer}"),
                    AclPermission::Deny,
                    Some(BOTH),
                    class_messages(class),
                    vec![wire(base, format!("v1/{origin}/{class}/{producer}/**"))],
                    "face-deny-class",
                    "RFC 09 §4 (v1.43): every subject of this class is `host`, so the class \
                     stays home whole — the subtree, not a list that a new subject would \
                     fall outside of",
                )));
            } else {
                ids.push(rules.push(rule(
                    format!("deny-{class}-{producer}-detail"),
                    AclPermission::Deny,
                    Some(BOTH),
                    class_messages(class),
                    kept,
                    "face-deny-detail",
                    "RFC 09 §4 (v1.43): the `host` subjects by name, because a sibling is \
                     `link` or `fleet` and deny is evaluated first — the carve-out for what \
                     crosses has to be an absence from this list",
                )));
            }
        }
        for p in &slice.procedures {
            let name = format!("{producer}/{}", p.path);
            match effective(p.exposure.as_ref()) {
                Exposure::Host => any_host_procedure = true,
                Exposure::Link | Exposure::Fleet => {
                    cut_procedures.push(name.clone());
                    open_procedures.push(name);
                }
            }
        }
        if !crosses.is_empty() {
            warnings.push(warn(
                AclWarningKind::FaceCrosses,
                Some(producer),
                "RFC 08 §2",
                format!(
                    "{} subject(s) cross this face as `fleet` (declared, or unmarked — the \
                     default): {}",
                    crosses.len(),
                    crosses.join(", ")
                ),
            ));
        }
    }

    // The planes, by their widest spelling (fact 6). @rpc when any
    // procedure stays home; @media and @blob always — a stream or a bulk
    // fetch has no business on a constrained link (RFC 09 §4); the admin
    // space and the sidecars always.
    if any_host_procedure {
        ids.push(rules.push(rule(
            "deny-rpc",
            AclPermission::Deny,
            Some(BOTH),
            &[
                AclMessage::Query,
                AclMessage::Reply,
                AclMessage::DeclareQueryable,
                AclMessage::Put,
                AclMessage::Delete,
                AclMessage::DeclareSubscriber,
            ],
            vec!["**/@rpc/**".to_string()],
            "face-deny-plane",
            "RFC 09 §3 fact 6 (v1.38): a plane is denied by the widest pattern that can \
             reach it — the verbatim chunk must be spelled by any query that reaches the \
             plane, and `**` on either side includes every spelling around it; a \
             producer-scoped literal is crossed by a broader query",
        )));
        if !cut_procedures.is_empty() {
            warnings.push(warn(
                AclWarningKind::FaceCutsPlane,
                None,
                "RFC 09 §3 fact 6",
                format!(
                    "{} procedure(s) marked `link` or `fleet` are cut with the @rpc plane, \
                     which is denied whole because a sibling is `host`: {}",
                    cut_procedures.len(),
                    cut_procedures.join(", ")
                ),
            ));
        }
    } else if !open_procedures.is_empty() {
        warnings.push(warn(
            AclWarningKind::FaceCrosses,
            None,
            "RFC 08 §2",
            format!(
                "the @rpc plane crosses this face: no procedure is marked `host`, so \
                 {} procedure(s) answer over the link: {}",
                open_procedures.len(),
                open_procedures.join(", ")
            ),
        ));
    }
    for (id, plane) in [("deny-media", "@media"), ("deny-blob", "@blob")] {
        ids.push(rules.push(rule(
            id,
            AclPermission::Deny,
            Some(BOTH),
            &[
                AclMessage::Put,
                AclMessage::Delete,
                AclMessage::DeclareSubscriber,
                AclMessage::Query,
                AclMessage::Reply,
                AclMessage::DeclareQueryable,
            ],
            vec![format!("**/{plane}/**")],
            "face-deny-plane",
            "RFC 09 §4: a stream or a bulk fetch has no business on a constrained link; \
             the widest spelling, for fact 6",
        )));
    }
    ids.push(rules.push(rule(
        "deny-adminspace",
        AclPermission::Deny,
        Some(BOTH),
        &AclMessage::ALL,
        vec!["@/**".to_string(), "**/@adv/**".to_string()],
        "face-deny-admin",
        "RFC 09 §4: the admin space and the advanced-tier sidecars never cross a \
         constrained link — every rule above is rooted at v1, so without this the \
         whole admin surface would be permitted by the permissive default",
    )));

    // Sorted by key, so the block reads the same whatever order the
    // registry lists its subjects in, and a diff of two generations is a
    // diff of the markers.
    downsampling.sort_by(|a, b| a.key_expr.cmp(&b.key_expr));
    // One timer per rule in zenoh, and a key resolves to the first
    // intersecting rule: two intersecting rules would share a budget with
    // an arbitrary winner.
    for (i, a) in downsampling.iter().enumerate() {
        for b in &downsampling[i + 1..] {
            if let (Ok(ka), Ok(kb)) = (
                keyexpr::new(a.key_expr.as_str()),
                keyexpr::new(b.key_expr.as_str()),
            ) && ka.intersects(kb)
            {
                warnings.push(warn(
                    AclWarningKind::FaceRulesIntersect,
                    None,
                    "zenoh downsampling: one timer per rule",
                    format!(
                        "{} and {} intersect and would share one downsampling timer with an \
                         arbitrary winner — declare the subjects so their patterns do not",
                        a.key_expr, b.key_expr
                    ),
                ));
            }
        }
    }

    let mut subjects = vec![AclSubject {
        id: spec.id.clone(),
        role: Role::Link,
        cert_common_names: Vec::new(),
        zids: Vec::new(),
        usernames: Vec::new(),
        link_protocols: spec.link_protocols.clone(),
        interfaces: spec.interfaces.clone(),
    }];
    let mut policies = vec![AclPolicy {
        id: format!("{}-mgmt", spec.id),
        rules: ids.clone(),
        subjects: vec![spec.id.clone()],
    }];
    let mut refusals = Vec::new();

    // The principals on the face (v1.49): see the doc above for why each
    // one repeats the face's denies rather than sitting beside them.
    let write_set = write_exprs(base, slices);
    let sensitive_set = sensitive_exprs(base, slices);
    // A principal's subject and policy share its id; the face holds one of
    // each already.
    let mut seen_ids = BTreeSet::from([spec.id.clone(), format!("{}-mgmt", spec.id)]);
    let mut seen_users = BTreeSet::new();
    for (i, p) in principals.iter().enumerate() {
        let name = principal_name(i, p);
        let mut refuse = |reason: String, cite: &str| {
            refusals.push(AclRefusal {
                principal: name.clone(),
                reason,
                cite: cite.into(),
            });
        };
        let user = p.user.as_deref().filter(|s| !s.is_empty());
        let other = [("cn", &p.cn), ("zid", &p.zid)]
            .into_iter()
            .find(|(_, v)| v.as_deref().is_some_and(|s| !s.is_empty()));
        if let Some((prop, _)) = other {
            refuse(
                format!(
                    "a `{prop}` on a face: a face principal is an operator the face's usrpwd \
                     authenticated, bound by `user` alone — a certificate or zid principal \
                     belongs to the principal plan (`acl gen` without --face), which runs \
                     under a deny default this face's router cannot share"
                ),
                "RFC 09 §4 (v1.49)",
            );
            continue;
        }
        let Some(user) = user else {
            refuse(
                "a principal on a face needs a `user` — the zenoh usrpwd user name the face \
                 authenticates"
                    .into(),
                "RFC 09 §4 (v1.49)",
            );
            continue;
        };
        if !matches!(p.role, Role::Console | Role::Watch) {
            refuse(
                format!(
                    "a {} on a face: a face principal is an operator on the far side — a \
                     console or a watch; a publisher's grants are the principal plan's",
                    p.role.as_str()
                ),
                "RFC 09 §4 (v1.49)",
            );
            continue;
        }
        if let Some(reason) = grant_refusal(p) {
            refuse(reason, "RFC 09 §3");
            continue;
        }
        if !any_host_procedure {
            refuse(
                "nothing to grant: this face denies no @rpc (no procedure is `host`), so the \
                 plane already crosses for every peer — and a principal's subject can only \
                 widen what the face's own allows, because any matching subject's allow wins"
                    .into(),
                "RFC 09 §4 (v1.49)",
            );
            continue;
        }
        if !seen_users.insert(user.to_string()) {
            refuse(
                format!(
                    "user {user:?} is already enrolled — one transport identity, one principal"
                ),
                "RFC 03 §4 D6",
            );
            continue;
        }
        let sid = p.id.clone().unwrap_or_else(|| user.to_string());
        if !seen_ids.insert(sid.clone()) {
            refuse(
                format!("subject id {sid:?} is already taken — give this principal an `id`"),
                "zenoh-config: subject ids are unique",
            );
            continue;
        }

        // Every face deny but `deny-rpc`, which is split: the legs no call
        // uses stay denied whole, the three a call does are carved.
        let mut own: Vec<String> = ids.iter().filter(|r| *r != "deny-rpc").cloned().collect();
        own.push(rules.push(rule(
            "deny-rpc-legs",
            AclPermission::Deny,
            Some(BOTH),
            &[
                AclMessage::Put,
                AclMessage::Delete,
                AclMessage::DeclareSubscriber,
            ],
            vec!["**/@rpc/**".to_string()],
            "face-deny-plane",
            "RFC 09 §4 (v1.49): a face principal's subject repeats every face deny, because \
             any matching subject's allow wins — of the @rpc plane, the legs no call uses; \
             query, reply and declare_queryable are carved to its grants below",
        )));
        if write_set.is_empty() {
            warnings.push(warn(
                AclWarningKind::NoWriteProcedures,
                Some(&sid),
                "RFC 09 §4 (v1.49)",
                "the registry declares no `kind = \"write\"` procedure, so nothing is carved: \
                 this principal reaches every @rpc call the face keeps from the link",
            ));
        }
        for r in write_rules(
            base,
            &sid,
            p,
            &write_set,
            &sensitive_set,
            true,
            &mut warnings,
        ) {
            own.push(rules.push(r));
        }
        subjects.push(AclSubject {
            id: sid.clone(),
            role: p.role,
            cert_common_names: Vec::new(),
            zids: Vec::new(),
            usernames: vec![user.to_string()],
            link_protocols: spec.link_protocols.clone(),
            interfaces: spec.interfaces.clone(),
        });
        policies.push(AclPolicy {
            id: sid.clone(),
            rules: own,
            subjects: vec![sid],
        });
    }

    AclPlan {
        base: base.to_string(),
        default_permission: AclPermission::Allow,
        registry: Asked::Asked(registry_facts(slices)),
        rules: rules.into_vec(),
        subjects,
        policies,
        downsampling,
        warnings,
        refusals,
    }
}

// ── JSON5 ─────────────────────────────────────────────────────────────────

fn js(s: &str) -> String {
    serde_json::to_string(s).expect("a string serializes")
}

fn js_list<'a>(items: impl IntoIterator<Item = &'a str>) -> String {
    let inner: Vec<String> = items.into_iter().map(js).collect();
    format!("[{}]", inner.join(", "))
}

/// The plan as the `access_control` block `zenohd` reads — with a comment
/// per rule naming the matrix row and the fact it exists for.
///
/// Field names are zenoh 1.10's (`zenoh-config-1.10.0/src/lib.rs`:
/// `AclConfig`, `AclConfigRule`, `AclMessage`, `InterceptorFlow`,
/// `AclConfigSubjects`, `AclConfigPolicyEntry`); `flows` is omitted where the
/// rule applies in both directions, which is what zenoh reads an absent
/// `flows` as.
pub fn to_json5(plan: &AclPlan) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    let _ = writeln!(
        out,
        "// zenohd access_control block — generated by `zenctl acl gen` (RFC 09 §3)."
    );
    let _ = write!(
        out,
        "// base {}; {} subject(s), {} rule(s), {} polic(y/ies); ",
        js(&plan.base),
        plan.subjects.len(),
        plan.rules.len(),
        plan.policies.len()
    );
    match plan.registry.as_option() {
        Some(r) => {
            let _ = writeln!(
                out,
                "registry: {} slice(s), {} write procedure(s), media by [{}], blob by [{}].",
                r.slices,
                r.write_procedures.len(),
                r.media_producers.join(", "),
                r.blob_producers.join(", ")
            );
        }
        None => {
            let _ = writeln!(
                out,
                "registry: not asked — planes are as the enrollment claims and the write \
                 set is the convention's `set` leaf, unnarrowed."
            );
        }
    }
    let _ = writeln!(
        out,
        "// Field names: zenoh 1.10 (zenoh-config-1.10.0/src/lib.rs — AclConfig, AclConfigRule,\n\
         // AclMessage, InterceptorFlow, AclConfigSubjects, AclConfigPolicyEntry). A rule with no\n\
         // `flows` applies in both directions. Merge at the router config's top level; the\n\
         // three lists are all required — rules alone are refused at startup (fact 3). ACL\n\
         // config is not runtime-reloadable: enrolling a host is a router restart (RFC 03 §4 D6)."
    );
    for r in &plan.refusals {
        let _ = writeln!(out, "// REFUSED {}: {} ({})", r.principal, r.reason, r.cite);
    }
    for w in &plan.warnings {
        let who = w
            .principal
            .as_deref()
            .map_or(String::new(), |p| format!(" [{p}]"));
        let _ = writeln!(
            out,
            "// ! {}{who}: {} ({})",
            w.kind.as_str(),
            w.text,
            w.cite
        );
    }
    let _ = writeln!(out, "access_control: {{");
    let _ = writeln!(out, "  enabled: true,");
    match plan.default_permission {
        AclPermission::Deny => {
            let _ = writeln!(
                out,
                "  default_permission: \"deny\",  // fact 4: deny, and every declaration allowed by name"
            );
        }
        AclPermission::Allow => {
            let _ = writeln!(
                out,
                "  default_permission: \"allow\",  // node-global: a face-scoped deny lives under a permissive default (RFC 09 §4)"
            );
        }
    }

    let _ = writeln!(out, "  rules: [");
    for r in &plan.rules {
        let _ = writeln!(out, "    // {}: {}", r.purpose, r.cite);
        let _ = write!(
            out,
            "    {{ id: {}, permission: {}",
            js(&r.id),
            js(r.permission.as_str())
        );
        if let Some(flows) = &r.flows {
            let _ = write!(
                out,
                ", flows: {}",
                js_list(flows.iter().map(|f| f.as_str()))
            );
        }
        let _ = writeln!(out, ",");
        let _ = writeln!(
            out,
            "      messages: {},",
            js_list(r.messages.iter().map(|m| m.as_str()))
        );
        let _ = writeln!(
            out,
            "      key_exprs: {} }},",
            js_list(r.key_exprs.iter().map(String::as_str))
        );
    }
    let _ = writeln!(out, "  ],");

    let _ = writeln!(
        out,
        "  subjects: [  // the enrollment: transport identity ↔ origin (RFC 03 §4 D6)"
    );
    for s in &plan.subjects {
        let _ = write!(out, "    {{ id: {}", js(&s.id));
        if !s.cert_common_names.is_empty() {
            let _ = write!(
                out,
                ", cert_common_names: {}",
                js_list(s.cert_common_names.iter().map(String::as_str))
            );
        }
        if !s.zids.is_empty() {
            let _ = write!(
                out,
                ", zids: {}",
                js_list(s.zids.iter().map(String::as_str))
            );
        }
        if !s.usernames.is_empty() {
            let _ = write!(
                out,
                ", usernames: {}",
                js_list(s.usernames.iter().map(String::as_str))
            );
        }
        if !s.link_protocols.is_empty() {
            let _ = write!(
                out,
                ", link_protocols: {}",
                js_list(s.link_protocols.iter().map(String::as_str))
            );
        }
        if !s.interfaces.is_empty() {
            let _ = write!(
                out,
                ", interfaces: {}",
                js_list(s.interfaces.iter().map(String::as_str))
            );
        }
        let _ = writeln!(out, " }},  // {}", s.role.as_str());
    }
    let _ = writeln!(out, "  ],");

    let _ = writeln!(out, "  policies: [");
    for p in &plan.policies {
        let _ = writeln!(
            out,
            "    {{ id: {}, rules: {},\n      subjects: {} }},",
            js(&p.id),
            js_list(p.rules.iter().map(String::as_str)),
            js_list(p.subjects.iter().map(String::as_str))
        );
    }
    let _ = writeln!(out, "  ],");
    // Each block ends in a member comma (#486): the output is a fragment
    // pasted into a router config's top-level object, and a trailing comma
    // is legal JSON5 even before the closing `}`.
    let _ = writeln!(out, "}},");
    if !plan.downsampling.is_empty() {
        // The face's second block (RFC 09 §4): egress puts only — dropping
        // on ingress saves no airtime, it has already been spent.
        let face = plan.subjects.first().expect("a face plan has its subject");
        let _ = writeln!(
            out,
            "// `link`-exposed subjects, capped (RFC 09 §4, v1.43): one rule per key, none intersecting —\n\
             // zenoh resolves a key to the first intersecting rule and gives each rule one timer."
        );
        let _ = writeln!(out, "downsampling: [");
        let _ = write!(out, "  {{ id: {}", js(&format!("{}-telemetry", face.id)));
        if !face.link_protocols.is_empty() {
            let _ = write!(
                out,
                ", link_protocols: {}",
                js_list(face.link_protocols.iter().map(String::as_str))
            );
        }
        if !face.interfaces.is_empty() {
            let _ = write!(
                out,
                ", interfaces: {}",
                js_list(face.interfaces.iter().map(String::as_str))
            );
        }
        let _ = writeln!(out, ",");
        let _ = writeln!(out, "    flows: [\"egress\"], messages: [\"put\"],");
        let _ = writeln!(out, "    rules: [");
        for d in &plan.downsampling {
            let _ = writeln!(
                out,
                "      {{ key_expr: {}, freq: {} }},",
                js(&d.key_expr),
                d.freq
            );
        }
        let _ = writeln!(out, "    ] }},");
        let _ = writeln!(out, "],");
    }
    out
}

// ── --check ───────────────────────────────────────────────────────────────

fn set<'a>(items: impl IntoIterator<Item = &'a str>) -> BTreeSet<String> {
    items.into_iter().map(str::to_string).collect()
}

/// A rule's comparable form: flows normalised so that absent = both.
fn rule_shape(
    permission: &str,
    flows: Option<&[String]>,
    messages: &[String],
    key_exprs: &[String],
) -> String {
    let flows: BTreeSet<&str> = match flows {
        Some(f) => f.iter().map(String::as_str).collect(),
        None => ["egress", "ingress"].into_iter().collect(),
    };
    let messages: BTreeSet<&str> = messages.iter().map(String::as_str).collect();
    let key_exprs: BTreeSet<&str> = key_exprs.iter().map(String::as_str).collect();
    format!(
        "{permission} {} {} {}",
        flows.into_iter().collect::<Vec<_>>().join("+"),
        messages.into_iter().collect::<Vec<_>>().join(","),
        key_exprs.into_iter().collect::<Vec<_>>().join(" ")
    )
}

fn planned_rule_shape(r: &AclRule) -> String {
    let flows: Option<Vec<String>> = r
        .flows
        .as_ref()
        .map(|f| f.iter().map(|x| x.as_str().to_string()).collect());
    let messages: Vec<String> = r.messages.iter().map(|m| m.as_str().to_string()).collect();
    rule_shape(
        r.permission.as_str(),
        flows.as_deref(),
        &messages,
        &r.key_exprs,
    )
}

/// The plan against the block a router's config file carries.
///
/// The observed side is what zenoh's own loader parsed, so what is compared
/// is what `zenohd` would run; `against` names the file (RFC 13 §3 O5). The
/// judged claim is *the block differs from the plan* — a finding is
/// `Established`, a block that carries the plan whole is `NotEstablished`.
pub fn check_acl(plan: &AclPlan, observed: &AclConfigDoc, against: &str) -> AclCheck {
    let mut findings = Vec::new();
    let mut finding = |kind, id: &str, planned: Option<String>, observed: Option<String>| {
        findings.push(AclFinding {
            kind,
            id: id.to_string(),
            planned,
            observed,
        });
    };

    if !observed.enabled {
        finding(
            AclFindingKind::Disabled,
            "access_control",
            Some("enabled: true".into()),
            Some("enabled: false".into()),
        );
    }
    if observed.default_permission != plan.default_permission.as_str() {
        finding(
            AclFindingKind::DefaultPermissionDiffers,
            "default_permission",
            Some(plan.default_permission.as_str().into()),
            Some(observed.default_permission.clone()),
        );
    }

    // Rules, by id.
    let observed_rules: BTreeMap<&str, &crate::report::AclRuleDoc> =
        observed.rules.iter().map(|r| (r.id.as_str(), r)).collect();
    for p in &plan.rules {
        let shape = planned_rule_shape(p);
        match observed_rules.get(p.id.as_str()) {
            None => finding(AclFindingKind::RuleMissing, &p.id, Some(shape), None),
            Some(o) => {
                let o_shape =
                    rule_shape(&o.permission, o.flows.as_deref(), &o.messages, &o.key_exprs);
                if o_shape != shape {
                    finding(
                        AclFindingKind::RuleDiffers,
                        &p.id,
                        Some(shape),
                        Some(o_shape),
                    );
                }
            }
        }
    }
    let planned_rule_ids: BTreeSet<&str> = plan.rules.iter().map(|r| r.id.as_str()).collect();
    for o in &observed.rules {
        if !planned_rule_ids.contains(o.id.as_str()) {
            finding(
                AclFindingKind::RuleExtra,
                &o.id,
                None,
                Some(rule_shape(
                    &o.permission,
                    o.flows.as_deref(),
                    &o.messages,
                    &o.key_exprs,
                )),
            );
        }
    }

    // Subjects, by id — and every configured CN against the enrollment.
    let observed_subjects: BTreeMap<&str, &crate::report::AclSubjectDoc> = observed
        .subjects
        .iter()
        .map(|s| (s.id.as_str(), s))
        .collect();
    let known_cns: BTreeSet<&str> = plan
        .subjects
        .iter()
        .flat_map(|s| s.cert_common_names.iter().map(String::as_str))
        .collect();
    let subject_shape =
        |cns: &[String], zids: &[String], users: &[String], protos: &[String], ifs: &[String]| {
            let mut s = format!("cns {cns:?} zids {zids:?}");
            if !users.is_empty() {
                s.push_str(&format!(" usernames {users:?}"));
            }
            if !protos.is_empty() {
                s.push_str(&format!(" link_protocols {protos:?}"));
            }
            if !ifs.is_empty() {
                s.push_str(&format!(" interfaces {ifs:?}"));
            }
            s
        };
    for p in &plan.subjects {
        let planned = subject_shape(
            &p.cert_common_names,
            &p.zids,
            &p.usernames,
            &p.link_protocols,
            &p.interfaces,
        );
        match observed_subjects.get(p.id.as_str()) {
            None => finding(AclFindingKind::SubjectMissing, &p.id, Some(planned), None),
            Some(o) => {
                let o_cns = o.cert_common_names.clone().unwrap_or_default();
                let o_zids = o.zids.clone().unwrap_or_default();
                let o_users = o.usernames.clone().unwrap_or_default();
                let o_protos = o.link_protocols.clone().unwrap_or_default();
                let o_ifs = o.interfaces.clone().unwrap_or_default();
                let differs = |a: &[String], b: &[String]| {
                    set(a.iter().map(String::as_str)) != set(b.iter().map(String::as_str))
                };
                if differs(&o_cns, &p.cert_common_names)
                    || differs(&o_zids, &p.zids)
                    || differs(&o_users, &p.usernames)
                    || differs(&o_protos, &p.link_protocols)
                    || differs(&o_ifs, &p.interfaces)
                {
                    finding(
                        AclFindingKind::SubjectDiffers,
                        &p.id,
                        Some(planned),
                        Some(subject_shape(&o_cns, &o_zids, &o_users, &o_protos, &o_ifs)),
                    );
                }
            }
        }
    }
    let planned_subject_ids: BTreeSet<&str> = plan.subjects.iter().map(|s| s.id.as_str()).collect();
    for o in &observed.subjects {
        if !planned_subject_ids.contains(o.id.as_str()) {
            finding(
                AclFindingKind::SubjectExtra,
                &o.id,
                None,
                Some(format!(
                    "cns {:?} zids {:?}",
                    o.cert_common_names.clone().unwrap_or_default(),
                    o.zids.clone().unwrap_or_default()
                )),
            );
        }
        // A property is unplanned when the plan's subject of that id does
        // not carry it (v1.49) — on a subject the plan does not know, every
        // one is. A carried property's value is SubjectDiffers' business.
        let planned = plan.subjects.iter().find(|p| p.id == o.id);
        let carried = |prop: &str| {
            planned.is_some_and(|p| match prop {
                "interfaces" => !p.interfaces.is_empty(),
                "usernames" => !p.usernames.is_empty(),
                _ => !p.link_protocols.is_empty(),
            })
        };
        for (prop, value) in [
            ("interfaces", &o.interfaces),
            ("usernames", &o.usernames),
            ("link_protocols", &o.link_protocols),
        ] {
            if carried(prop) {
                continue;
            }
            if value.as_ref().is_some_and(|v| !v.is_empty()) {
                finding(
                    AclFindingKind::SubjectUnplannedProperty,
                    &o.id,
                    None,
                    Some(format!("{prop}: {:?}", value.clone().unwrap_or_default())),
                );
            }
        }
        for cn in o.cert_common_names.iter().flatten() {
            if !known_cns.contains(cn.as_str()) {
                finding(
                    AclFindingKind::UnknownCn,
                    cn,
                    None,
                    Some(format!("bound by subject {:?}", o.id)),
                );
            }
        }
    }

    // Policies, as sets of (rules, subjects) — ids are optional in zenoh's
    // shape, so identity is what a policy binds.
    let policy_key = |rules: &[String], subjects: &[String]| {
        format!(
            "rules [{}] subjects [{}]",
            set(rules.iter().map(String::as_str))
                .into_iter()
                .collect::<Vec<_>>()
                .join(", "),
            set(subjects.iter().map(String::as_str))
                .into_iter()
                .collect::<Vec<_>>()
                .join(", ")
        )
    };
    let observed_policies: BTreeSet<String> = observed
        .policies
        .iter()
        .map(|p| policy_key(&p.rules, &p.subjects))
        .collect();
    let planned_policies: BTreeSet<String> = plan
        .policies
        .iter()
        .map(|p| policy_key(&p.rules, &p.subjects))
        .collect();
    for p in &plan.policies {
        let key = policy_key(&p.rules, &p.subjects);
        if !observed_policies.contains(&key) {
            finding(AclFindingKind::PolicyMissing, &p.id, Some(key), None);
        }
    }
    for (i, o) in observed.policies.iter().enumerate() {
        let key = policy_key(&o.rules, &o.subjects);
        if !planned_policies.contains(&key) {
            let id = o.id.clone().unwrap_or_else(|| format!("policy #{}", i + 1));
            finding(AclFindingKind::PolicyExtra, &id, None, Some(key));
        }
    }

    let judgement = if findings.is_empty() {
        Judgement::NotEstablished {
            reason: format!(
                "{against} carries the plan whole: {} rule(s), {} subject(s), {} polic(y/ies), \
                 enabled, default {}",
                plan.rules.len(),
                plan.subjects.len(),
                plan.policies.len(),
                plan.default_permission.as_str()
            ),
        }
    } else {
        Judgement::Established
    };
    AclCheck {
        base: plan.base.clone(),
        against: against.to_string(),
        planned_rules: plan.rules.len(),
        observed_rules: observed.rules.len(),
        planned_subjects: plan.subjects.len(),
        observed_subjects: observed.subjects.len(),
        findings,
        // Observable only from a publisher's matching listener (RFC 07 §1);
        // a config-file check has no publisher to ask, and a consumer-side
        // subscriber cannot see whether its interest was forwarded.
        interest_probe: Judgement::NotAsked,
        judgement,
    }
}

// ── --explain ─────────────────────────────────────────────────────────────

/// Does `principal` hold `message` on `key`, in each direction, and via
/// which rules — over the plan alone, inclusion by `zenoh-keyexpr`.
///
/// `principal` is a subject id, a CN, a user or a zid. On a face plan a
/// user principal's own subject is its whole answer: its denies are a
/// subset of the face's (`plan_face`), so the face's subject, which also
/// matches its link, never allows what it denies. A principal the plan does
/// not carry (unknown, or refused) is an [`Error::Unaskable`]: there is no
/// policy to explain.
pub fn explain_acl(
    plan: &AclPlan,
    principal: &str,
    key: &str,
    message: AclMessage,
) -> Result<AclExplain> {
    let subject = plan
        .subjects
        .iter()
        .find(|s| {
            s.id == principal
                || s.cert_common_names.iter().any(|c| c == principal)
                || s.usernames.iter().any(|u| u == principal)
                || s.zids.iter().any(|z| z == principal)
        })
        .ok_or_else(|| {
            let refused = plan.refusals.iter().any(|r| r.principal == principal);
            Error::unaskable(
                "explain",
                if refused {
                    format!("principal {principal:?} was refused by the plan — see its refusal")
                } else {
                    format!(
                        "principal {principal:?} is not enrolled; the plan knows {:?}",
                        plan.subjects
                            .iter()
                            .map(|s| s.id.as_str())
                            .collect::<Vec<_>>()
                    )
                },
            )
        })?;
    let k = keyexpr::new(key).map_err(|e| {
        Error::unaskable(
            "explain",
            format!("{key:?} is not a valid key expression (RFC 03 §2): {e}"),
        )
    })?;

    let rule_ids: BTreeSet<&str> = plan
        .policies
        .iter()
        .filter(|p| p.subjects.contains(&subject.id))
        .flat_map(|p| p.rules.iter().map(String::as_str))
        .collect();
    let rules: Vec<&AclRule> = plan
        .rules
        .iter()
        .filter(|r| rule_ids.contains(r.id.as_str()))
        .collect();

    let direction = |flow: AclFlow| -> AclDirection {
        let applicable = rules.iter().filter(|r| {
            r.messages.contains(&message) && r.flows.as_ref().is_none_or(|f| f.contains(&flow))
        });
        let mut via = Vec::new();
        let mut near: Vec<String> = Vec::new();
        for r in applicable {
            let including = r
                .key_exprs
                .iter()
                .find(|e| keyexpr::new(e.as_str()).is_ok_and(|ke| ke.includes(k)));
            match including {
                Some(e) => via.push(AclGrant {
                    rule: r.id.clone(),
                    permission: r.permission,
                    key_expr: e.clone(),
                    purpose: r.purpose.clone(),
                }),
                None => {
                    if let Some(e) = r
                        .key_exprs
                        .iter()
                        .find(|e| keyexpr::new(e.as_str()).is_ok_and(|ke| ke.intersects(k)))
                    {
                        near.push(format!("{} ({e})", r.id));
                    }
                }
            }
        }
        // Deny first, so the reader sees what won.
        via.sort_by_key(|g| g.permission == AclPermission::Allow);
        let denies: Vec<&str> = via
            .iter()
            .filter(|g| g.permission == AclPermission::Deny)
            .map(|g| g.rule.as_str())
            .collect();
        let allows: Vec<&str> = via
            .iter()
            .filter(|g| g.permission == AclPermission::Allow)
            .map(|g| g.rule.as_str())
            .collect();
        let (decision, mut reason) = if !denies.is_empty() {
            (
                AclDecision::Denied,
                format!(
                    "{} denies {} on {} — deny wins{}",
                    denies.join(", "),
                    message.as_str(),
                    flow.as_str(),
                    if allows.is_empty() {
                        String::new()
                    } else {
                        format!(" over {}", allows.join(", "))
                    }
                ),
            )
        } else if !allows.is_empty() {
            (
                AclDecision::Allowed,
                format!(
                    "{} includes it for {} on {}",
                    allows.join(", "),
                    message.as_str(),
                    flow.as_str()
                ),
            )
        } else if plan.default_permission == AclPermission::Allow {
            (
                AclDecision::AllowedByDefault,
                format!(
                    "no rule of {}'s policies includes {key} for {} on {}: this block's \
                     default_permission is allow, so it crosses — a face keeps things home \
                     by deny, and what nothing denies is what the registry marks `fleet` \
                     (RFC 09 §4)",
                    subject.id,
                    message.as_str(),
                    flow.as_str()
                ),
            )
        } else {
            (
                AclDecision::DeniedByDefault,
                format!(
                    "no rule of {}'s policies includes {key} for {} on {}: default_permission \
                     deny",
                    subject.id,
                    message.as_str(),
                    flow.as_str()
                ),
            )
        };
        if decision == AclDecision::DeniedByDefault && !near.is_empty() {
            let verbatim = key.split('/').any(|c| c.starts_with('@'));
            reason.push_str(&format!(
                " — {} intersect{} it but ACL matching is inclusion (RFC 09 §3 fact 1){}",
                near.join(", "),
                if near.len() == 1 { "s" } else { "" },
                if verbatim {
                    ", and `**` never crosses a verbatim `@` chunk (RFC 03 §4 D2): name the \
                     plane in its own rule"
                } else {
                    ""
                }
            ));
        }
        AclDirection {
            decision,
            via,
            reason,
        }
    };

    Ok(AclExplain {
        principal: subject.id.clone(),
        key: key.to_string(),
        message,
        base: plan.base.clone(),
        ingress: direction(AclFlow::Ingress),
        egress: direction(AclFlow::Egress),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report::{FleetSpec, PrincipalSpec};

    fn principal(cn: &str, role: Role) -> PrincipalSpec {
        PrincipalSpec {
            cn: Some(cn.into()),
            role,
            ..Default::default()
        }
    }

    /// Three hosts, a catalog, a console, a watch — the fixture fleet.
    fn fleet() -> Enrollment {
        Enrollment {
            base: Some("zensight".into()),
            fleet: FleetSpec {
                catalog_adv: true,
                salt: Some("example-salt-v1".into()),
            },
            principal: vec![
                PrincipalSpec {
                    origin: Some("h-3fa9c2d41b7e".into()),
                    adv: true,
                    blob_seed: true,
                    media: true,
                    ..principal("h-3fa9c2d41b7e", Role::Host)
                },
                // RFC 06 §1's test vector: computed, not given.
                PrincipalSpec {
                    machine_id: Some("b642b4217b34b1e8d3bd915fc65c4452".into()),
                    ..principal("edge-02.example", Role::Host)
                },
                PrincipalSpec {
                    origin: Some("h-0123456789ab".into()),
                    adv: true,
                    ..principal("h-0123456789ab", Role::Host)
                },
                principal("zensight-catalog", Role::Catalog),
                PrincipalSpec {
                    adv: true,
                    ..principal("zensight-console", Role::Console)
                },
                principal("zensight-watch", Role::Watch),
            ],
        }
    }

    fn plan() -> AclPlan {
        plan_acl(&fleet(), "zensight", None, AclOptions::default())
    }

    fn rule_of<'p>(plan: &'p AclPlan, id: &str) -> &'p AclRule {
        plan.rules
            .iter()
            .find(|r| r.id == id)
            .unwrap_or_else(|| panic!("rule {id}"))
    }

    fn policy_of<'p>(plan: &'p AclPlan, id: &str) -> &'p AclPolicy {
        plan.policies
            .iter()
            .find(|p| p.id == id)
            .unwrap_or_else(|| panic!("policy {id}"))
    }

    /// Fact 3: three lists, all present; one subject and one policy per
    /// enrolled principal.
    #[test]
    fn the_three_lists_are_present_and_nothing_was_refused() {
        let p = plan();
        assert!(p.refusals.is_empty(), "{:?}", p.refusals);
        assert_eq!(p.subjects.len(), 6);
        assert_eq!(p.policies.len(), 6);
        assert!(!p.rules.is_empty());
        assert_eq!(p.default_permission, AclPermission::Deny);
        // Every policy names rules that exist and a subject that exists.
        for pol in &p.policies {
            for r in &pol.rules {
                assert!(p.rules.iter().any(|x| &x.id == r), "{r} in {}", pol.id);
            }
            for s in &pol.subjects {
                assert!(p.subjects.iter().any(|x| &x.id == s), "{s} in {}", pol.id);
            }
        }
        // Rule ids are unique — zenoh refuses a duplicate.
        let ids: BTreeSet<&str> = p.rules.iter().map(|r| r.id.as_str()).collect();
        assert_eq!(ids.len(), p.rules.len());
    }

    /// Fact 1: one rule per plane, and the host's `**` rule reaches none of
    /// them.
    #[test]
    fn a_host_gets_one_rule_per_plane_and_the_data_rule_reaches_no_plane() {
        let p = plan();
        let pol = policy_of(&p, "h-3fa9c2d41b7e");
        assert_eq!(
            pol.rules,
            [
                "host-data-h-3fa9c2d41b7e",
                "host-serve-h-3fa9c2d41b7e",
                "host-media-h-3fa9c2d41b7e",
                "host-blob-seed-h-3fa9c2d41b7e",
                "host-adv-h-3fa9c2d41b7e",
                INTEREST_PROP,
            ]
        );
        let data = rule_of(&p, "host-data-h-3fa9c2d41b7e");
        assert_eq!(data.key_exprs, ["zensight/v1/h-3fa9c2d41b7e/**"]);
        assert_eq!(data.flows.as_deref(), Some(&[AclFlow::Ingress][..]));
        let data_ke = keyexpr::new(data.key_exprs[0].as_str()).unwrap();
        for plane in [
            "zensight/v1/h-3fa9c2d41b7e/@rpc/sysinfo/introspect",
            "zensight/v1/h-3fa9c2d41b7e/@media/parallax/cam0/video/h264/high",
            "zensight/v1/h-3fa9c2d41b7e/@blob/store/sha256/abc",
            "zensight/v1/h-3fa9c2d41b7e/state/x/@adv/pub/zid/1",
        ] {
            assert!(
                !data_ke.includes(keyexpr::new(plane).unwrap()),
                "host-data must not reach {plane}"
            );
        }
        let serve = rule_of(&p, "host-serve-h-3fa9c2d41b7e");
        assert_eq!(
            serve.flows, None,
            "both directions: query egress, reply ingress"
        );
        assert_eq!(
            serve.key_exprs,
            [
                "zensight/v1/h-3fa9c2d41b7e/@rpc/**",
                "zensight/v1/h-3fa9c2d41b7e/@blob/**"
            ]
        );
        // A plain host: data, serve, interest-prop and nothing else.
        assert_eq!(
            policy_of(&p, "edge-02.example").rules,
            [
                "host-data-h-20609002f7b6",
                "host-serve-h-20609002f7b6",
                INTEREST_PROP
            ]
        );
    }

    /// RFC 06 §1's test vector: the origin is computed from the machine-id,
    /// and a given origin that disagrees is a refusal.
    #[test]
    fn a_machine_id_computes_the_origin_and_a_disagreement_is_refused() {
        let p = plan();
        let s = p
            .subjects
            .iter()
            .find(|s| s.id == "edge-02.example")
            .unwrap();
        assert_eq!(s.cert_common_names, ["edge-02.example"]);
        assert!(rule_of(&p, "host-data-h-20609002f7b6").key_exprs[0].contains("h-20609002f7b6"));

        let mut e = fleet();
        e.principal[1].origin = Some("h-000000000000".into());
        let p = plan_acl(&e, "zensight", None, AclOptions::default());
        assert_eq!(p.refusals.len(), 1);
        assert_eq!(p.refusals[0].principal, "edge-02.example");
        assert!(
            p.refusals[0].reason.contains("h-20609002f7b6"),
            "{}",
            p.refusals[0].reason
        );
        assert_eq!(p.subjects.len(), 5, "the refused principal is left out");

        // No salt: the derivation cannot run.
        let mut e = fleet();
        e.fleet.salt = None;
        let p = plan_acl(&e, "zensight", None, AclOptions::default());
        assert!(p.refusals[0].reason.contains("salt"));
    }

    /// Fact 2: catalog access is its own rule, spelled on the verbatim
    /// origin, and `*` never reaches it.
    #[test]
    fn the_catalog_is_its_own_rule_and_a_star_never_reaches_it() {
        let p = plan();
        let own = rule_of(&p, "catalog-own-catalog");
        assert_eq!(
            own.key_exprs,
            [
                "zensight/v1/@catalog/**",
                "zensight/v1/@catalog/@rpc/**",
                "zensight/v1/@catalog/**/@adv/**"
            ]
        );
        let star = keyexpr::new("zensight/v1/*/state/**").unwrap();
        assert!(!star.includes(keyexpr::new("zensight/v1/@catalog/state/pdns/x").unwrap()));
        // And the consumers name it explicitly, adv sibling included.
        let sub = rule_of(&p, "ops-sub");
        assert!(
            sub.key_exprs
                .contains(&"zensight/v1/@catalog/**".to_string())
        );
        assert!(
            sub.key_exprs
                .contains(&"zensight/v1/@catalog/@rpc/**".to_string())
        );
        assert!(
            sub.key_exprs
                .contains(&"zensight/v1/@catalog/**/@adv/**".to_string())
        );
        assert!(
            !keyexpr::new("zensight/v1/**/@adv/**")
                .unwrap()
                .includes(keyexpr::new("zensight/v1/@catalog/state/x/@adv/pub/z/1").unwrap()),
            "the fifth fact's corollary: `**` cannot cross @catalog"
        );
    }

    /// Fact 4: every consumer policy carries ingress declares.
    #[test]
    fn every_consumer_policy_allows_its_declarations() {
        let p = plan();
        for (pid, rid) in [
            ("zensight-catalog", "catalog-intake-declare-catalog"),
            ("zensight-console", "ops-sub"),
            ("zensight-watch", "watch-sub"),
        ] {
            assert!(policy_of(&p, pid).rules.iter().any(|r| r == rid), "{pid}");
            let r = rule_of(&p, rid);
            assert_eq!(r.flows.as_deref(), Some(&[AclFlow::Ingress][..]));
            for m in [
                AclMessage::DeclareSubscriber,
                AclMessage::DeclareLivelinessSubscriber,
                AclMessage::Query,
            ] {
                assert!(r.messages.contains(&m), "{rid} lacks {}", m.as_str());
            }
        }
        // The catalog's intake is split by flow: a flowless rule would let it
        // tombstone any host's keys.
        let recv = rule_of(&p, "catalog-intake-recv-catalog");
        assert_eq!(recv.flows.as_deref(), Some(&[AclFlow::Egress][..]));
        assert!(recv.messages.contains(&AclMessage::Delete));
        // A watch never sees @media or @blob; a console does.
        let watch = rule_of(&p, "watch-sub");
        assert!(
            !watch
                .key_exprs
                .iter()
                .any(|e| e.contains("@media") || e.contains("@blob"))
        );
        let console = rule_of(&p, "ops-sub");
        assert!(console.key_exprs.iter().any(|e| e.contains("@media")));
        assert!(console.key_exprs.iter().any(|e| e.contains("@blob")));
    }

    /// The fifth fact: `interest-prop` on every publishing policy, egress
    /// only, declares and queries only — and it includes the selectors
    /// consumers actually declare.
    #[test]
    fn interest_prop_rides_every_host_policy_egress_only() {
        let p = plan();
        for pid in ["h-3fa9c2d41b7e", "edge-02.example", "h-0123456789ab"] {
            assert!(
                policy_of(&p, pid).rules.iter().any(|r| r == INTEREST_PROP),
                "{pid}"
            );
        }
        assert!(
            policy_of(&p, "zensight-catalog")
                .rules
                .iter()
                .any(|r| r == INTEREST_PROP)
        );
        let r = rule_of(&p, INTEREST_PROP);
        assert_eq!(r.flows.as_deref(), Some(&[AclFlow::Egress][..]));
        assert!(!r.messages.contains(&AclMessage::Put));
        assert!(!r.messages.contains(&AclMessage::Reply));
        assert!(r.messages.contains(&AclMessage::DeclareSubscriber));
        assert!(r.messages.contains(&AclMessage::Query));
        // The console's own selectors are included, `v1/**` and the fan-out
        // RPC shape among them — neither is included by any own-origin rule.
        let own = keyexpr::new("zensight/v1/h-3fa9c2d41b7e/@rpc/**").unwrap();
        let fanout = keyexpr::new("zensight/v1/*/@rpc/netlink/sockets").unwrap();
        assert!(!own.includes(fanout));
        assert!(
            r.key_exprs
                .iter()
                .any(|e| keyexpr::new(e.as_str()).unwrap().includes(fanout))
        );
        let firehose = keyexpr::new("zensight/v1/**").unwrap();
        assert!(
            r.key_exprs
                .iter()
                .any(|e| keyexpr::new(e.as_str()).unwrap().includes(firehose))
        );
    }

    /// Without a registry the deny is the convention's `set` leaf and the
    /// plan says so; with one it is the declared write set.
    #[test]
    fn the_write_set_is_narrowed_by_the_registry_and_unnarrowed_without() {
        let p = plan();
        let deny = rule_of(&p, NO_REMOTE_ACTIONS);
        assert_eq!(deny.permission, AclPermission::Deny);
        assert_eq!(deny.messages, [AclMessage::Query]);
        assert_eq!(deny.key_exprs, ["zensight/v1/*/@rpc/*/**/set"]);
        assert!(
            p.warnings
                .iter()
                .any(|w| w.kind == AclWarningKind::WriteSetNotNarrowed)
        );
        assert!(p.registry.is_not_asked());
        assert!(
            policy_of(&p, "zensight-console")
                .rules
                .iter()
                .any(|r| r == NO_REMOTE_ACTIONS)
        );
        assert!(
            policy_of(&p, "zensight-watch")
                .rules
                .iter()
                .any(|r| r == NO_REMOTE_ACTIONS)
        );

        let dir =
            std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixture-tests/registry");
        let slices = SliceSet::from_dirs(&[dir]).unwrap();
        let p = plan_acl(&fleet(), "zensight", Some(&slices), AclOptions::default());
        let facts = p.registry.as_option().unwrap();
        assert!(
            facts
                .write_procedures
                .contains(&"systemd/action/set".to_string())
        );
        assert!(facts.media_producers.contains(&"parallax".to_string()));
        assert!(facts.blob_producers.contains(&"logs".to_string()));
        let deny = rule_of(&p, NO_REMOTE_ACTIONS);
        assert!(
            deny.key_exprs
                .contains(&"zensight/v1/*/@rpc/systemd/action/set".to_string())
        );
        assert!(
            deny.key_exprs
                .contains(&"zensight/v1/@catalog/@rpc/catalog/link".to_string())
        );
        assert!(!deny.key_exprs.iter().any(|e| e.ends_with("/**/set")));
        assert!(
            !p.warnings
                .iter()
                .any(|w| w.kind == AclWarningKind::WriteSetNotNarrowed)
        );
        // A console allowed to act drops the deny.
        let mut e = fleet();
        e.principal[4].remote_actions = true;
        let p = plan_acl(&e, "zensight", Some(&slices), AclOptions::default());
        assert!(
            !policy_of(&p, "zensight-console")
                .rules
                .iter()
                .any(|r| r == NO_REMOTE_ACTIONS)
        );
        assert!(
            policy_of(&p, "zensight-watch")
                .rules
                .iter()
                .any(|r| r == NO_REMOTE_ACTIONS)
        );
    }

    /// The registry narrows the planes: a claimed plane no producer declares
    /// is omitted, and said so.
    #[test]
    fn a_plane_the_registry_does_not_declare_is_omitted_with_a_warning() {
        let dir =
            std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixture-tests/registry");
        let slices = SliceSet::from_dirs(&[dir]).unwrap();
        // A registry with the media producer removed.
        let kept: Vec<_> = slices
            .slices()
            .iter()
            .filter(|s| s.media.is_empty())
            .cloned()
            .collect();
        let narrowed = SliceSet::from_slices(kept);
        let p = plan_acl(&fleet(), "zensight", Some(&narrowed), AclOptions::default());
        assert!(p.rules.iter().all(|r| !r.id.starts_with("host-media-")));
        let w = p
            .warnings
            .iter()
            .find(|w| w.kind == AclWarningKind::PlaneNotDeclared)
            .expect("a plane warning");
        assert_eq!(w.principal.as_deref(), Some("h-3fa9c2d41b7e"));
        assert!(
            !rule_of(&p, "ops-sub")
                .key_exprs
                .iter()
                .any(|e| e.contains("@media"))
        );
    }

    #[test]
    fn refusals_name_their_reason() {
        let mut e = fleet();
        // Two principals sharing a CN.
        e.principal.push(principal("zensight-console", Role::Watch));
        // A host with neither origin nor machine_id.
        e.principal.push(principal("bare-host", Role::Host));
        // A zid subject without the flag.
        e.principal.push(PrincipalSpec {
            zid: Some("38a4829bce9166ee".into()),
            ..PrincipalSpec {
                cn: None,
                role: Role::Watch,
                ..Default::default()
            }
        });
        // A read-only watch asking to act.
        e.principal.push(PrincipalSpec {
            remote_actions: true,
            ..principal("acting-watch", Role::Watch)
        });
        let p = plan_acl(&e, "zensight", None, AclOptions::default());
        let reasons: Vec<(&str, &str)> = p
            .refusals
            .iter()
            .map(|r| (r.principal.as_str(), r.reason.as_str()))
            .collect();
        assert_eq!(reasons.len(), 4, "{reasons:?}");
        assert!(reasons[0].1.contains("already enrolled"));
        assert!(reasons[1].1.contains("`origin` or `machine_id`"));
        assert_eq!(reasons[2].0, "38a4829bce9166ee");
        assert!(reasons[2].1.contains("--allow-zid-subjects"));
        assert!(reasons[3].1.contains("read-only"));
        assert_eq!(p.subjects.len(), 6);

        // With the flag, the zid subject is admitted and warned about.
        let p = plan_acl(
            &e,
            "zensight",
            None,
            AclOptions {
                allow_zid_subjects: true,
            },
        );
        assert_eq!(p.refusals.len(), 3);
        let s = p
            .subjects
            .iter()
            .find(|s| s.id == "38a4829bce9166ee")
            .unwrap();
        assert_eq!(s.zids, ["38a4829bce9166ee"]);
        assert!(s.cert_common_names.is_empty());
        assert!(
            p.warnings
                .iter()
                .any(|w| w.kind == AclWarningKind::ZidSubject)
        );
    }

    /// #486: the output is a fragment for a router config's top-level
    /// object, so pasted into one it must parse — as zenoh itself reads it.
    fn assert_pastes_into_a_router_config(text: &str) {
        let config = format!("{{\n  mode: \"router\",\n{text}}}\n");
        if let Err(e) = zenoh::Config::from_json5(&config) {
            panic!("the pasted fragment does not parse: {e}\n{config}");
        }
    }

    #[test]
    fn the_json5_names_zenohs_fields_and_every_matrix_row() {
        let text = to_json5(&plan());
        assert_pastes_into_a_router_config(&text);
        assert!(text.starts_with("// zenohd access_control block"));
        assert!(text.contains("access_control: {"));
        assert!(text.contains("  enabled: true,"));
        assert!(text.contains("default_permission: \"deny\""));
        for field in ["rules: [", "subjects: [", "policies: ["] {
            assert!(text.contains(field), "{field}");
        }
        assert!(text.contains(
            "{ id: \"host-data-h-3fa9c2d41b7e\", permission: \"allow\", flows: [\"ingress\"],"
        ));
        assert!(text.contains("messages: [\"put\", \"delete\", \"liveliness_token\"],"));
        // A flowless rule has no `flows` key at all.
        assert!(text.contains("{ id: \"host-serve-h-3fa9c2d41b7e\", permission: \"allow\",\n"));
        assert!(text.contains("// interest-prop: the fifth fact"));
        assert!(text.contains("cert_common_names: [\"h-3fa9c2d41b7e\"] },  // host"));
        assert!(text.contains("// ! write_set_not_narrowed"));
        // And it round-trips through a JSON parser once the comments and the
        // bare keys are what a JSON5 reader accepts — checked here through
        // zenoh's own loader in the zenctl corpus; here, that every quoted
        // string is valid JSON.
        assert!(!text.contains("\\u"));
    }

    #[test]
    fn explain_answers_per_direction_with_the_rules_that_decided() {
        let p = plan();
        // A host's own put: allowed on ingress, nothing on egress.
        let x = explain_acl(
            &p,
            "h-3fa9c2d41b7e",
            "zensight/v1/h-3fa9c2d41b7e/state/sysinfo/health",
            AclMessage::Put,
        )
        .unwrap();
        assert_eq!(x.ingress.decision, AclDecision::Allowed);
        assert_eq!(x.ingress.via[0].rule, "host-data-h-3fa9c2d41b7e");
        assert_eq!(x.egress.decision, AclDecision::DeniedByDefault);

        // Its @rpc reply: host-data does not reach it; host-serve does.
        let x = explain_acl(
            &p,
            "h-3fa9c2d41b7e",
            "zensight/v1/h-3fa9c2d41b7e/@rpc/sysinfo/introspect",
            AclMessage::Reply,
        )
        .unwrap();
        assert_eq!(x.ingress.decision, AclDecision::Allowed);
        assert_eq!(x.ingress.via[0].rule, "host-serve-h-3fa9c2d41b7e");

        // Another host's origin: denied by default, and the reason names the
        // convention.
        let x = explain_acl(
            &p,
            "h-3fa9c2d41b7e",
            "zensight/v1/h-0123456789ab/state/sysinfo/health",
            AclMessage::Put,
        )
        .unwrap();
        assert_eq!(x.ingress.decision, AclDecision::DeniedByDefault);
        assert!(x.ingress.via.is_empty());

        // The console calling a write: denied, deny wins over ops-sub.
        let x = explain_acl(
            &p,
            "zensight-console",
            "zensight/v1/h-3fa9c2d41b7e/@rpc/systemd/action/set",
            AclMessage::Query,
        )
        .unwrap();
        assert_eq!(x.ingress.decision, AclDecision::Denied);
        assert_eq!(x.ingress.via[0].rule, NO_REMOTE_ACTIONS);
        assert_eq!(x.ingress.via[1].rule, "ops-sub");
        assert!(x.ingress.reason.contains("deny wins over ops-sub"));

        // A CN resolves to its subject; an unknown principal is unaskable.
        assert!(explain_acl(&p, "zensight-watch", "zensight/v1/**", AclMessage::Put).is_ok());
        let e = explain_acl(&p, "nobody", "zensight/v1/**", AclMessage::Put).unwrap_err();
        assert!(e.is_unaskable());
        let e = explain_acl(&p, "zensight-watch", "zensight//x", AclMessage::Put).unwrap_err();
        assert!(e.is_unaskable());
    }

    /// The plan's own JSON5, parsed back as zenoh would, checks clean; a
    /// hand-edited block does not.
    #[test]
    fn check_finds_what_differs_and_only_that() {
        let p = plan();
        // The observed side built from the plan itself, as a loader would
        // hand it back.
        let mut doc = AclConfigDoc {
            enabled: true,
            default_permission: "deny".into(),
            rules: p
                .rules
                .iter()
                .map(|r| crate::report::AclRuleDoc {
                    id: r.id.clone(),
                    key_exprs: r.key_exprs.clone(),
                    messages: r.messages.iter().map(|m| m.as_str().to_string()).collect(),
                    flows: r
                        .flows
                        .as_ref()
                        .map(|f| f.iter().map(|x| x.as_str().to_string()).collect()),
                    permission: r.permission.as_str().into(),
                })
                .collect(),
            subjects: p
                .subjects
                .iter()
                .map(|s| crate::report::AclSubjectDoc {
                    id: s.id.clone(),
                    cert_common_names: Some(s.cert_common_names.clone()),
                    ..Default::default()
                })
                .collect(),
            policies: p
                .policies
                .iter()
                .map(|pol| crate::report::AclPolicyDoc {
                    id: None,
                    rules: pol.rules.clone(),
                    subjects: pol.subjects.clone(),
                })
                .collect(),
        };
        let c = check_acl(&p, &doc, "router.json5");
        assert!(c.findings.is_empty(), "{:?}", c.findings);
        assert!(matches!(c.judgement, Judgement::NotEstablished { .. }));
        assert_eq!(c.interest_probe, Judgement::NotAsked);

        // Now break it four ways.
        doc.enabled = false;
        doc.rules.retain(|r| r.id != INTEREST_PROP);
        doc.rules[0].flows = None;
        doc.subjects.push(crate::report::AclSubjectDoc {
            id: "stranger".into(),
            cert_common_names: Some(vec!["not-enrolled".into()]),
            interfaces: Some(vec!["eth0".into()]),
            ..Default::default()
        });
        doc.policies[0].rules.pop();
        let c = check_acl(&p, &doc, "router.json5");
        let kinds: Vec<AclFindingKind> = c.findings.iter().map(|f| f.kind).collect();
        assert!(kinds.contains(&AclFindingKind::Disabled));
        assert!(kinds.contains(&AclFindingKind::RuleMissing));
        assert!(kinds.contains(&AclFindingKind::RuleDiffers));
        assert!(kinds.contains(&AclFindingKind::SubjectExtra));
        assert!(kinds.contains(&AclFindingKind::SubjectUnplannedProperty));
        assert!(kinds.contains(&AclFindingKind::UnknownCn));
        assert!(kinds.contains(&AclFindingKind::PolicyMissing));
        assert!(kinds.contains(&AclFindingKind::PolicyExtra));
        assert_eq!(c.judgement, Judgement::Established);
        assert_eq!(crate::judgement_exit_code(&c.judgement), 1);
    }

    #[test]
    fn a_procedure_path_with_variables_becomes_a_pattern() {
        assert_eq!(procedure_pattern("config/{ns}/{if}/set"), "config/*/*/set");
        assert_eq!(procedure_pattern("action/set"), "action/set");
        assert_eq!(procedure_pattern("subs/{path...}"), "subs/**");
    }

    /// A radio driver's registry, as the reference adopter marks it: sixteen
    /// counters that stay home, four an operator on the far side acts on,
    /// state and events that stay home, every procedure home, and one
    /// sensitive write.
    const MODEM_TOML: &str = "[registry]\nversion = \"1.0\"\napp = \"acme\"\nconvention = 1\n\n[producer]\nname = \"modem\"\n\n\
[[subject]]\npath = \"{device}/tx_sdus_total\"\nclass = \"telemetry\"\ntype = \"C\"\ncardinality = 4\nexposure = \"host\"\n\n\
[[subject]]\npath = \"{device}/rx_sdus_total\"\nclass = \"telemetry\"\ntype = \"C\"\ncardinality = 4\nexposure = \"host\"\n\n\
[[subject]]\npath = \"{device}/queue_depth\"\nclass = \"telemetry\"\ntype = \"G\"\ncardinality = 4\nexposure = \"link\"\n\n\
[[subject]]\npath = \"{device}/dropped_total\"\nclass = \"telemetry\"\ntype = \"C\"\ncardinality = 4\nexposure = \"link\"\n\n\
[[subject]]\npath = \"{device}/temperature\"\nclass = \"telemetry\"\ntype = \"G\"\ncardinality = 4\n\n\
[[subject]]\npath = \"link/{device}\"\nclass = \"state\"\ntype = \"L\"\ncardinality = 4\nttl_s = 60\nexposure = \"host\"\n\n\
[[subject]]\npath = \"endpoint/{device}/{endpoint}\"\nclass = \"state\"\ntype = \"E\"\ncardinality = 16\nttl_s = 60\nexposure = \"host\"\n\n\
[[subject]]\npath = \"link_change/{event_id}\"\nclass = \"events\"\ntype = \"V\"\ncardinality = 1000\nrate = \"low\"\nexposure = \"host\"\n\n\
[[procedure]]\npath = \"introspect\"\nkind = \"read\"\nreply = \"RegistrySlice\"\nexposure = \"host\"\n\n\
[[procedure]]\npath = \"config/{device}/power/set\"\nkind = \"write\"\nreply = \"ConfigView\"\ncardinality = 4\nexposure = \"host\"\n\n\
[[procedure]]\npath = \"config/{device}/access/set\"\nkind = \"write\"\nreply = \"ConfigView\"\ncardinality = 4\nexposure = \"host\"\nsensitive = true\n\n\
[[procedure]]\npath = \"config/{device}/persist\"\nkind = \"write\"\nreply = \"Ack\"\ncardinality = 4\nexposure = \"host\"\n";

    fn modem_slices() -> SliceSet {
        SliceSet::from_slices(vec![zenkey::parse_slice(MODEM_TOML).expect("parses")])
    }

    fn face(interval: LinkInterval) -> FaceSpec {
        FaceSpec {
            id: "modem-lane".into(),
            link_protocols: vec!["unixsock-stream".into()],
            interfaces: Vec::new(),
            interval,
        }
    }

    fn includes(rule: &AclRule, key: &str) -> bool {
        let k = keyexpr::new(key).unwrap();
        rule.key_exprs
            .iter()
            .any(|e| keyexpr::new(e.as_str()).unwrap().includes(k))
    }

    /// A `writes` grant is one allow and a carved deny: the declared writes
    /// the grant does not include, and nothing else. A sensitive write stays
    /// denied to a console that may act, until a grant names it.
    #[test]
    fn a_writes_grant_carves_the_deny_and_a_sensitive_write_stays_denied() {
        let slices = modem_slices();
        let mut e = fleet();
        e.principal[4].writes = vec!["modem/config/*/power/set".into()];
        let p = plan_acl(&e, "", Some(&slices), AclOptions::default());
        assert!(p.refusals.is_empty(), "{:?}", p.refusals);
        let grant = rule_of(&p, "writes-zensight-console");
        assert_eq!(grant.permission, AclPermission::Allow);
        assert_eq!(grant.key_exprs, ["v1/*/@rpc/modem/config/*/power/set"]);
        let deny = rule_of(&p, "no-remote-actions-zensight-console");
        assert!(!includes(
            deny,
            "v1/h-0123456789ab/@rpc/modem/config/rf0/power/set"
        ));
        assert!(includes(
            deny,
            "v1/h-0123456789ab/@rpc/modem/config/rf0/persist"
        ));
        assert!(includes(
            deny,
            "v1/h-0123456789ab/@rpc/modem/config/rf0/access/set"
        ));
        // The watch keeps the shared, whole deny.
        assert!(
            policy_of(&p, "zensight-watch")
                .rules
                .iter()
                .any(|r| r == NO_REMOTE_ACTIONS)
        );
        assert!(
            p.registry
                .as_option()
                .unwrap()
                .sensitive_procedures
                .contains(&"modem/config/{device}/access/set".to_string())
        );
        // `--explain` answers the per-resource question.
        let x = explain_acl(
            &p,
            "zensight-console",
            "v1/h-0123456789ab/@rpc/modem/config/rf0/power/set",
            AclMessage::Query,
        )
        .unwrap();
        assert_eq!(x.ingress.decision, AclDecision::Allowed, "{x:?}");

        // A console that may act still cannot reach the sensitive write —
        // until a grant names it.
        let mut e = fleet();
        e.principal[4].remote_actions = true;
        let p = plan_acl(&e, "", Some(&slices), AclOptions::default());
        let deny = rule_of(&p, "no-remote-actions-zensight-console");
        assert_eq!(deny.key_exprs, ["v1/*/@rpc/modem/config/*/access/set"]);
        e.principal[4].writes = vec!["modem/config/*/access/set".into()];
        let p = plan_acl(&e, "", Some(&slices), AclOptions::default());
        assert!(
            !policy_of(&p, "zensight-console")
                .rules
                .iter()
                .any(|r| r.starts_with("no-remote-actions")),
            "nothing left to deny the console; the watch keeps its own"
        );

        // Without a registry a grant cannot carve: the deny stays whole and
        // the plan says why.
        let mut e = fleet();
        e.principal[4].writes = vec!["modem/config/*/power/set".into()];
        let p = plan_acl(&e, "", None, AclOptions::default());
        assert!(!p.rules.iter().any(|r| r.id.starts_with("writes-")));
        assert!(rule_of(&p, NO_REMOTE_ACTIONS).key_exprs[0].ends_with("/**/set"));
        assert!(
            p.warnings
                .iter()
                .any(|w| w.kind == AclWarningKind::GrantNotNarrowed)
        );
        // A pattern nothing answers is allowed as spelled, and said.
        let mut e = fleet();
        e.principal[4].writes = vec!["modem/reboot".into()];
        let p = plan_acl(&e, "", Some(&slices), AclOptions::default());
        assert!(
            p.warnings
                .iter()
                .any(|w| w.kind == AclWarningKind::GrantMatchesNothing)
        );
        // A watch refuses a grant as it refuses remote_actions.
        let mut e = fleet();
        e.principal[5].writes = vec!["modem/config/*/power/set".into()];
        let p = plan_acl(&e, "", Some(&slices), AclOptions::default());
        assert_eq!(p.refusals.len(), 1);
        assert!(p.refusals[0].reason.contains("read-only"));
    }

    /// The radio face (RFC 09 §4): the `host` counters denied by name, the
    /// wholly-`host` classes by subtree, the planes by their widest
    /// spelling, the `link` counters capped — and the unmarked one crosses,
    /// said.
    #[test]
    fn a_constrained_face_keeps_host_surfaces_home_and_caps_link_ones() {
        let slices = modem_slices();
        let p = plan_face(&slices, "", &face(LinkInterval::EverySecs(60)), &[]);
        assert_eq!(p.default_permission, AclPermission::Allow);
        assert_eq!(p.subjects.len(), 1);
        assert_eq!(p.subjects[0].link_protocols, ["unixsock-stream"]);
        assert_eq!(p.subjects[0].role, Role::Link);
        assert_eq!(p.policies[0].subjects, ["modem-lane"]);
        assert_eq!(p.policies[0].rules.len(), p.rules.len());
        assert!(p.rules.iter().all(|r| r.flows.as_deref() == Some(BOTH)));

        let detail = rule_of(&p, "deny-telemetry-modem-detail");
        assert!(includes(
            detail,
            "v1/h-0123456789ab/telemetry/modem/rf0/tx_sdus_total"
        ));
        assert!(!includes(
            detail,
            "v1/h-0123456789ab/telemetry/modem/rf0/queue_depth"
        ));
        assert!(!includes(
            detail,
            "v1/h-0123456789ab/telemetry/modem/rf0/temperature"
        ));
        let state = rule_of(&p, "deny-state-modem");
        assert_eq!(state.key_exprs, ["v1/*/state/modem/**"]);
        assert!(includes(state, "v1/h-0123456789ab/state/modem/alive"));
        assert_eq!(state.messages.len(), AclMessage::ALL.len());
        assert_eq!(
            rule_of(&p, "deny-events-modem").key_exprs,
            ["v1/*/events/modem/**"]
        );
        let rpc = rule_of(&p, "deny-rpc");
        assert_eq!(rpc.key_exprs, ["**/@rpc/**"]);
        assert!(
            includes(rpc, "v1/*/@rpc/**"),
            "the broader query is included too"
        );
        assert!(includes(rule_of(&p, "deny-adminspace"), "@/abc/router/**"));
        assert!(includes(
            rule_of(&p, "deny-adminspace"),
            "v1/h-0123456789ab/state/modem/link/rf0/@adv/x"
        ));
        assert!(includes(
            rule_of(&p, "deny-media"),
            "v1/h-0123456789ab/@media/cam/main"
        ));

        let capped: Vec<&str> = p.downsampling.iter().map(|d| d.key_expr.as_str()).collect();
        assert_eq!(
            capped,
            [
                "v1/*/telemetry/modem/*/dropped_total",
                "v1/*/telemetry/modem/*/queue_depth"
            ]
        );
        assert!(p.downsampling.iter().all(|d| d.freq <= 0.017));
        let crosses = p
            .warnings
            .iter()
            .find(|w| w.kind == AclWarningKind::FaceCrosses)
            .expect("the unmarked gauge is said");
        assert!(
            crosses.text.contains("telemetry/{device}/temperature"),
            "{}",
            crosses.text
        );
        assert!(
            !p.warnings
                .iter()
                .any(|w| w.kind == AclWarningKind::FaceCutsPlane)
        );

        // The block, as zenohd reads it: the face's subject, both blocks.
        let text = to_json5(&p);
        assert_pastes_into_a_router_config(&text);
        assert!(text.contains("default_permission: \"allow\""));
        assert!(text.contains("link_protocols: [\"unixsock-stream\"] },  // link"));
        assert!(text.contains("downsampling: ["));
        assert!(text.contains("flows: [\"egress\"], messages: [\"put\"]"));
        // And --explain over the face: the deny decided, on ingress and egress.
        let x = explain_acl(
            &p,
            "modem-lane",
            "v1/h-0123456789ab/telemetry/modem/rf0/tx_sdus_total",
            AclMessage::Put,
        )
        .unwrap();
        assert_eq!(x.egress.decision, AclDecision::Denied);
        let x = explain_acl(
            &p,
            "modem-lane",
            "v1/h-0123456789ab/telemetry/modem/rf0/queue_depth",
            AclMessage::Put,
        )
        .unwrap();
        assert_eq!(
            x.egress.decision,
            AclDecision::AllowedByDefault,
            "capped, not denied"
        );

        // No affordable rate (a billed channel): the `link` counters stay
        // home too, the class is denied whole, nothing is capped.
        let p = plan_face(&slices, "", &face(LinkInterval::None), &[]);
        assert!(p.downsampling.is_empty());
        let detail = rule_of(&p, "deny-telemetry-modem-detail");
        assert!(includes(
            detail,
            "v1/h-0123456789ab/telemetry/modem/rf0/queue_depth"
        ));
        assert!(!includes(
            detail,
            "v1/h-0123456789ab/telemetry/modem/rf0/temperature"
        ));
        assert!(!to_json5(&p).contains("downsampling"));

        // A registry that marks nothing crosses whole, and the note says so;
        // a `link` procedure beside a `host` one is cut with the plane.
        let dir =
            std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixture-tests/registry");
        let fixtures = SliceSet::from_dirs(&[dir]).unwrap();
        let p = plan_face(
            &fixtures,
            "zensight",
            &face(LinkInterval::EverySecs(10)),
            &[],
        );
        assert!(
            p.rules.iter().any(|r| r.id == "deny-rpc"),
            "systemd marks a write host"
        );
        assert!(
            p.warnings
                .iter()
                .any(|w| w.kind == AclWarningKind::FaceCutsPlane)
        );
        assert!(
            p.warnings
                .iter()
                .any(|w| w.kind == AclWarningKind::FaceCrosses)
        );
        assert_eq!(p.downsampling.len(), 1, "sysinfo memory/used is link");
        assert!(
            p.downsampling[0]
                .key_expr
                .starts_with("zensight/v1/*/telemetry/sysinfo/memory/used")
        );
    }

    // ── user principals (v1.49, #529) ─────────────────────────────────────

    /// The pasted fragment read back through zenoh's own loader, as
    /// `acl gen --check --against` reads a router's config file.
    fn observed_of(text: &str) -> AclConfigDoc {
        let config = zenoh::Config::from_json5(&format!("{{\n  mode: \"router\",\n{text}}}\n"))
            .expect("the fragment parses");
        serde_json::from_str(&config.get_json("access_control").expect("a block"))
            .expect("zenoh's AclConfig shape")
    }

    fn user(name: &str, role: Role) -> PrincipalSpec {
        PrincipalSpec {
            user: Some(name.into()),
            role,
            ..Default::default()
        }
    }

    /// A `user` binds `usernames` as a `cn` binds `cert_common_names`, both
    /// together AND, and the plan checks clean against its own block.
    #[test]
    fn a_user_principal_is_bound_by_usernames() {
        let mut e = fleet();
        e.principal.push(user("ops", Role::Console));
        e.principal.push(PrincipalSpec {
            cn: Some("radio-desk".into()),
            ..user("desk", Role::Watch)
        });
        let p = plan_acl(&e, "zensight", None, AclOptions::default());
        assert!(p.refusals.is_empty(), "{:?}", p.refusals);
        let ops = p.subjects.iter().find(|s| s.id == "ops").expect("ops");
        assert_eq!(ops.usernames, ["ops"]);
        assert!(ops.cert_common_names.is_empty() && ops.zids.is_empty());
        let desk = p.subjects.iter().find(|s| s.id == "radio-desk").unwrap();
        assert_eq!(desk.usernames, ["desk"]);
        assert_eq!(desk.cert_common_names, ["radio-desk"]);
        assert!(
            policy_of(&p, "ops")
                .rules
                .iter()
                .any(|r| r == NO_REMOTE_ACTIONS)
        );

        let text = to_json5(&p);
        assert_pastes_into_a_router_config(&text);
        assert!(text.contains("{ id: \"ops\", usernames: [\"ops\"] },  // console"));
        let c = check_acl(&p, &observed_of(&text), "router.json5");
        assert!(c.findings.is_empty(), "{:?}", c.findings);
        // --explain resolves a principal by its user, too.
        let x = explain_acl(
            &p,
            "ops",
            "zensight/v1/h-3fa9c2d41b7e/state/x",
            AclMessage::Reply,
        )
        .unwrap();
        assert_eq!(x.principal, "ops");

        // A username the block carries and the plan does not is a
        // difference, not an unplanned property: the plan carries usernames
        // on that subject.
        let mut doc = observed_of(&text);
        let s = doc.subjects.iter_mut().find(|s| s.id == "ops").unwrap();
        s.usernames = Some(vec!["someone-else".into()]);
        let c = check_acl(&p, &doc, "router.json5");
        let kinds: Vec<AclFindingKind> = c.findings.iter().map(|f| f.kind).collect();
        assert_eq!(kinds, [AclFindingKind::SubjectDiffers], "{:?}", c.findings);
        // On a subject the plan binds by cn alone, it is unplanned.
        let mut doc = observed_of(&text);
        let s = doc
            .subjects
            .iter_mut()
            .find(|s| s.id == "zensight-console")
            .unwrap();
        s.usernames = Some(vec!["ops".into()]);
        let c = check_acl(&p, &doc, "router.json5");
        assert!(
            c.findings
                .iter()
                .any(|f| f.kind == AclFindingKind::SubjectUnplannedProperty
                    && f.id == "zensight-console"),
            "{:?}",
            c.findings
        );

        // One user, one principal; and nothing to bind by is refused, the
        // refusal naming the new binding.
        let mut e = fleet();
        e.principal.push(user("ops", Role::Console));
        e.principal.push(user("ops", Role::Watch));
        e.principal.push(PrincipalSpec {
            role: Role::Watch,
            ..Default::default()
        });
        let p = plan_acl(&e, "zensight", None, AclOptions::default());
        let reasons: Vec<&str> = p.refusals.iter().map(|r| r.reason.as_str()).collect();
        assert_eq!(reasons.len(), 2, "{reasons:?}");
        assert!(reasons[0].contains("user \"ops\" is already enrolled"));
        assert!(reasons[1].contains("or a `user`"));
    }

    /// A grant narrower than the declared write it falls in cannot carve
    /// it: no finite deny includes `config/*/power/set` but
    /// `config/rf0/power/set`. The allow is not emitted — it would never
    /// decide — and the plan says why.
    #[test]
    fn a_grant_narrower_than_its_declared_write_is_not_emitted() {
        let slices = modem_slices();
        let mut e = fleet();
        e.principal[4].writes = vec!["modem/config/rf0/power/set".into()];
        let p = plan_acl(&e, "", Some(&slices), AclOptions::default());
        assert!(!p.rules.iter().any(|r| r.id.starts_with("writes-")));
        let w = p
            .warnings
            .iter()
            .find(|w| w.kind == AclWarningKind::GrantCannotCarve)
            .expect("said");
        assert!(
            w.text.contains("v1/*/@rpc/modem/config/*/power/set"),
            "{}",
            w.text
        );
        assert!(
            !p.warnings
                .iter()
                .any(|w| w.kind == AclWarningKind::GrantMatchesNothing),
            "it is declared, and it is not allowed — both halves of the old note were wrong"
        );
        let x = explain_acl(
            &p,
            "zensight-console",
            "v1/h-0123456789ab/@rpc/modem/config/rf0/power/set",
            AclMessage::Query,
        )
        .unwrap();
        assert_eq!(x.ingress.decision, AclDecision::Denied);
    }

    /// Every deny of `inner`'s policy is included by a deny of `outer`'s,
    /// message for message and flow for flow.
    fn denies_within(p: &AclPlan, inner: &str, outer: &str) -> bool {
        let rules_of = |id: &str| -> Vec<&AclRule> {
            let ids = &policy_of(p, id).rules;
            p.rules
                .iter()
                .filter(|r| ids.contains(&r.id) && r.permission == AclPermission::Deny)
                .collect()
        };
        let flows = |r: &AclRule| r.flows.clone().unwrap_or_else(|| BOTH.to_vec());
        let outer = rules_of(outer);
        rules_of(inner).iter().all(|r| {
            r.messages.iter().all(|m| {
                flows(r).iter().all(|f| {
                    r.key_exprs.iter().all(|k| {
                        outer.iter().any(|o| {
                            o.messages.contains(m) && flows(o).contains(f) && includes(o, k)
                        })
                    })
                })
            })
        })
    }

    /// A user principal on the face (RFC 09 §4, v1.49): its own subject on
    /// the face's transport, repeating every face deny — any matching
    /// subject's allow wins in zenoh, so an allow beside the face's denies
    /// would open the face — with `deny-rpc` split into the legs no call
    /// uses and the console's carve.
    #[test]
    fn a_user_on_a_face_repeats_every_face_deny_and_carves_its_grant() {
        let slices = modem_slices();
        let ops = PrincipalSpec {
            writes: vec!["modem/config/*/power/set".into()],
            ..user("ops", Role::Console)
        };
        let p = plan_face(&slices, "", &face(LinkInterval::EverySecs(60)), &[ops]);
        assert!(p.refusals.is_empty(), "{:?}", p.refusals);
        assert_eq!(p.default_permission, AclPermission::Allow);
        assert_eq!(p.subjects.len(), 2);
        assert_eq!(p.subjects[0].id, "modem-lane", "the face stays first");
        let s = &p.subjects[1];
        assert_eq!((s.id.as_str(), s.role), ("ops", Role::Console));
        assert_eq!(s.usernames, ["ops"]);
        assert_eq!(s.link_protocols, ["unixsock-stream"], "and the face's link");

        let face_rules = &policy_of(&p, "modem-lane-mgmt").rules;
        let own = &policy_of(&p, "ops").rules;
        for r in face_rules {
            assert_eq!(own.contains(r), r != "deny-rpc", "{r}");
        }
        for r in ["deny-rpc-legs", "writes-ops", "no-remote-actions-ops"] {
            assert!(own.contains(&r.to_string()), "{r}");
        }
        assert!(
            denies_within(&p, "ops", "modem-lane-mgmt"),
            "the user's denies are a subset of the face's, so its own evaluation is its \
             whole answer"
        );

        let ask = |who: &str, key: &str, m: AclMessage| explain_acl(&p, who, key, m).unwrap();
        let rpc = "v1/h-0123456789ab/@rpc/modem/config/rf0";
        let x = ask("ops", &format!("{rpc}/power/set"), AclMessage::Query);
        assert_eq!(x.ingress.decision, AclDecision::Allowed, "{x:?}");
        let x = ask("ops", &format!("{rpc}/power/set"), AclMessage::Reply);
        assert_eq!(x.egress.decision, AclDecision::AllowedByDefault);
        for key in ["persist", "access/set"] {
            let x = ask("ops", &format!("{rpc}/{key}"), AclMessage::Query);
            assert_eq!(x.ingress.decision, AclDecision::Denied, "{key}");
        }
        let x = ask("ops", &format!("{rpc}/power/set"), AclMessage::Put);
        assert_eq!(
            x.ingress.decision,
            AclDecision::Denied,
            "a leg no call uses"
        );
        let x = ask(
            "ops",
            "v1/h-0123456789ab/telemetry/modem/rf0/tx_sdus_total",
            AclMessage::Put,
        );
        assert_eq!(
            x.egress.decision,
            AclDecision::Denied,
            "a face deny, repeated"
        );
        let x = ask("modem-lane", &format!("{rpc}/power/set"), AclMessage::Query);
        assert_eq!(x.ingress.decision, AclDecision::Denied, "everyone else");

        let text = to_json5(&p);
        assert_pastes_into_a_router_config(&text);
        assert!(text.contains(
            "{ id: \"ops\", usernames: [\"ops\"], link_protocols: [\"unixsock-stream\"] },  // console"
        ));
        assert!(text.contains("{ id: \"modem-lane-telemetry\", link_protocols:"));
        let c = check_acl(&p, &observed_of(&text), "router.json5");
        assert!(c.findings.is_empty(), "{:?}", c.findings);

        // A watch on the face: no grant, so the whole write set stays denied.
        let p = plan_face(
            &slices,
            "",
            &face(LinkInterval::EverySecs(60)),
            &[user("viewer", Role::Watch)],
        );
        assert!(p.refusals.is_empty(), "{:?}", p.refusals);
        assert!(
            policy_of(&p, "viewer")
                .rules
                .contains(&NO_REMOTE_ACTIONS.to_string())
        );
        let x = explain_acl(
            &p,
            "viewer",
            "v1/h-0123456789ab/@rpc/modem/config/rf0/power/set",
            AclMessage::Query,
        )
        .unwrap();
        assert_eq!(x.ingress.decision, AclDecision::Denied);
    }

    /// What a face cannot plan is refused with its reason — never dropped,
    /// which is what `--face` did with every principal before v1.49.
    #[test]
    fn a_face_refuses_what_it_cannot_plan_and_says_why() {
        let slices = modem_slices();
        let principals = vec![
            principal("zensight-console", Role::Console),
            PrincipalSpec {
                zid: Some("38a4829bce9166ee".into()),
                role: Role::Watch,
                ..Default::default()
            },
            PrincipalSpec {
                role: Role::Console,
                ..Default::default()
            },
            PrincipalSpec {
                origin: Some("h-0123456789ab".into()),
                ..user("far-host", Role::Host)
            },
            PrincipalSpec {
                writes: vec!["modem/config/*/power/set".into()],
                ..user("viewer", Role::Watch)
            },
            user("ops", Role::Console),
            user("ops", Role::Watch),
            PrincipalSpec {
                id: Some("modem-lane".into()),
                ..user("lane-squatter", Role::Console)
            },
        ];
        let p = plan_face(&slices, "", &face(LinkInterval::None), &principals);
        let reasons: Vec<(&str, &str)> = p
            .refusals
            .iter()
            .map(|r| (r.principal.as_str(), r.reason.as_str()))
            .collect();
        assert_eq!(reasons.len(), 7, "{reasons:#?}");
        assert!(reasons[0].1.contains("a `cn` on a face"));
        assert!(reasons[1].1.contains("a `zid` on a face"));
        assert!(reasons[2].1.contains("needs a `user`"));
        assert!(reasons[3].1.contains("a host on a face"));
        assert!(reasons[4].1.contains("read-only"));
        assert!(reasons[5].1.contains("user \"ops\" is already enrolled"));
        assert!(reasons[6].1.contains("\"modem-lane\" is already taken"));
        assert_eq!(p.subjects.len(), 2, "the face and the one ops");

        // A face that denies no @rpc has nothing to carve: a principal's
        // subject could only widen what the face's own already allows.
        let open = SliceSet::from_slices(vec![
            zenkey::parse_slice(
                "[registry]\nversion = \"1.0\"\napp = \"acme\"\nconvention = 1\n\n\
                 [producer]\nname = \"modem\"\n\n\
                 [[subject]]\npath = \"{device}/tx_sdus_total\"\nclass = \"telemetry\"\n\
                 type = \"C\"\ncardinality = 4\nexposure = \"host\"\n\n\
                 [[procedure]]\npath = \"introspect\"\nkind = \"read\"\n\
                 reply = \"RegistrySlice\"\nexposure = \"link\"\n",
            )
            .expect("parses"),
        ]);
        let p = plan_face(
            &open,
            "",
            &face(LinkInterval::EverySecs(60)),
            &[user("ops", Role::Console)],
        );
        assert_eq!(p.refusals.len(), 1);
        assert!(p.refusals[0].reason.contains("nothing to grant"));
        assert_eq!(p.subjects.len(), 1);
    }
}