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
//! Control-plane **authorization** vocabulary and RBAC policy.
//!
//! This is the wasm-clean, pure core of authorization: the `action × resource`
//! right vocabulary, the request → required-[`Right`] mapping (the analogue of
//! the old `required_scope`), the RBAC [`AuthzPolicy`] (roles → right
//! templates) with its built-in default, and the pure [`RightSet::allows`]
//! decision. The COSE/Cedar engine (`boatramp_core::cose` + `::cedar`) reuses these types
//! and mirrors [`RightSet::allows`]; keeping the semantics
//! here means the server, CLI, and tests can't drift from the token format.
//!
//! No IO, no async, no authz-engine dependency — so it compiles to the edge target
//! and is exhaustively unit-testable.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
/// What a principal may *do* to a resource. [`Action::Admin`] is the superuser
/// action: holding it on a resource satisfies any other action there.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Action {
/// Read/list (GET endpoints).
Read,
/// Mutate configuration (site config, aliases, domain verification, cache).
Write,
/// Ship content: create + activate deployments, upload blobs.
Deploy,
/// Full control of the resource (implies read/write/deploy).
Admin,
}
/// A class of control-plane resource a [`Right`] governs. Four are **target-scoped**:
/// [`Resource::Site`] (target = `"<project>/<site>"`, the 0.2.0 project-qualified
/// form), [`Resource::Project`] (target = `"<project>"`, governing the project's
/// **own** resources — functions, compute, workflows, and the project entity itself),
/// [`Resource::Secrets`] (target = `"<project>"`, the project's sealed secret
/// store), and [`Resource::BlobUpload`] (target = `"<project>"` at the mint route —
/// the project derived from the request path, mirroring repair/migrate — while a
/// *grant* may narrow to `"<project>/<site>/<container>"`; minting an S3-ingress
/// upload credential for a container). The rest are global.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Resource {
/// A single site (`target` = `"<project>/<site>"`): deployments, config, aliases, …
Site,
/// A project (`target` = `"<project>"`): its functions, compute, workflows, and
/// project-level config/CRUD. The owning + tenant boundary above a site.
Project,
/// A project's internal secret store (`target` = `"<project>"`): the sealed
/// `boatramp:<name>` values. Separate from [`Resource::Project`] so managing
/// credentials is a distinct, admin-gated right, auditable on its own.
Secrets,
/// Content-addressed blob uploads (`PUT /api/blobs/<hash>`).
Blobs,
/// **Minting a scoped S3-ingress upload credential** for a blob container. The
/// *required* right at the mint route is `BlobUpload·Write` scoped to the
/// **project** the request path names (`target` = `"<project>"`, derived from the
/// path — mirroring the repair/migrate precedent), so a project-scoped
/// `BlobUpload·Write` grant can mint for its OWN project, a DIFFERENT project's
/// grant is refused, and a global `admin` / global `BlobUpload·Write` (target
/// `None`) still satisfies it. A *grant* may be narrower — a
/// `"<project>/<site>/<container>"` target — but that finer resolution is enforced
/// by the handler's host-forcing, not by this route mapping. This gates the *mint*
/// verb (the operator `boatramp blob mint-upload` route + the guest `blob-upload`
/// binding's control-plane authorization), NOT the S3 ingress PUT itself — an
/// upload is authorized by the short-lived temp credential it carries, never by
/// this control-plane right. Deliberately **separate** from [`Resource::Blobs`]
/// (content-addressed control-plane artifact uploads, a `deploy`-grade action a
/// publisher holds): minting an external-ingress credential is a distinct,
/// admin-gated capability, so it is granted only to `admin` (via
/// [`Resource::ALL`]) — never to the default `publisher`/`deployer`/`project_*`
/// roles, which would otherwise let a site publisher hand out ingress creds.
BlobUpload,
/// API token management (`/api/tokens`).
Tokens,
/// TLS certificate status (`/api/certs`).
Certs,
/// Cache invalidation (`/api/cache/invalidate`).
Cache,
/// Node/system operations: metrics, prune, scrub, site listing.
System,
}
impl Resource {
/// Every resource variant — used to expand the `admin` role to "all rights".
pub const ALL: [Self; 9] = [
Self::Site,
Self::Project,
Self::Secrets,
Self::Blobs,
Self::BlobUpload,
Self::Tokens,
Self::Certs,
Self::Cache,
Self::System,
];
/// The serde term for this resource (matches `rename_all`).
pub fn as_str(self) -> &'static str {
match self {
Self::Site => "site",
Self::Project => "project",
Self::Secrets => "secrets",
Self::Blobs => "blobs",
Self::BlobUpload => "blob_upload",
Self::Tokens => "tokens",
Self::Certs => "certs",
Self::Cache => "cache",
Self::System => "system",
}
}
}
impl Action {
/// The serde term for this action (matches `rename_all`).
pub fn as_str(self) -> &'static str {
match self {
Self::Read => "read",
Self::Write => "write",
Self::Deploy => "deploy",
Self::Admin => "admin",
}
}
}
impl std::fmt::Display for Resource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl std::fmt::Display for Action {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// A single grant or requirement: an `action` on a `resource`, optionally scoped
/// to a `target` (a site name for [`Resource::Site`]). A `target` of `None` on a
/// *granted* right is a wildcard ("all targets"); a required right for a site
/// always carries `Some(site)`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Right {
/// The resource class this right governs.
pub resource: Resource,
/// The site name for [`Resource::Site`]; `None` (wildcard/global) otherwise.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
/// The permitted action.
pub action: Action,
}
impl Right {
/// Construct a right.
pub fn new(resource: Resource, target: Option<String>, action: Action) -> Self {
Self {
resource,
target,
action,
}
}
/// The target term: the site name, or `*` for a wildcard/global right.
pub fn target_term(&self) -> &str {
self.target.as_deref().unwrap_or("*")
}
/// Whether holding `self` (a *granted* right) satisfies a `required` right:
/// same resource, the granted action matches or is [`Action::Admin`], and the
/// granted target is a wildcard (`None`/`*`) or equals the required target.
pub fn satisfies(&self, required: &Self) -> bool {
self.resource == required.resource
&& (self.action == required.action || self.action == Action::Admin)
&& target_matches(self.target.as_deref(), required.target.as_deref())
}
/// Map an HTTP `method` + request `path` to the single right it requires, or
/// `None` for endpoints not gated by a right (the OIDC→token exchange).
///
/// This is the authoritative request→right table. Unknown
/// `/api/sites/<s>/…` subpaths fall through to the most restrictive
/// `system · admin` so a narrow token can never reach an unmapped action.
pub fn required(method: &str, path: &str) -> Option<Self> {
let m = method.to_ascii_uppercase();
let get = m == "GET";
// Self-service endpoints gated only by holding *some* valid token, not a
// right: the OIDC→token exchange (carries an IdP JWT) and `whoami`
// (a principal reading its own identity). The handlers verify the token.
if path == "/api/auth/exchange" || path == "/api/auth/whoami" {
return None;
}
// Mesh join: the joiner presents a single-use *join
// token* (verified by the handler), not an admin bearer — so this exact
// path is unauthenticated at the RBAC layer. Note the `==`: the sibling
// `/api/cluster/join-token` (minting) stays admin-scoped via the default.
if path == "/api/cluster/join" {
return None;
}
// First-token bootstrap: the caller presents a single-use, operator-set
// *bootstrap secret* (verified by the handler), not an admin bearer — so
// this exact path is unauthenticated at the RBAC layer. Note the `==`: the
// sibling `/api/tokens` (minting) stays admin-scoped via the default below.
if path == "/api/tokens/bootstrap" {
return None;
}
// Content blobs are content-addressed (not site-specific); uploading is
// a deploy-grade action.
if path.starts_with("/api/blobs/") {
return Some(Self::new(Resource::Blobs, None, Action::Deploy));
}
// Attaching a host **without** an ownership proof (`domain add
// --unverified`) is an admin-only override: it asserts ownership of an
// arbitrary hostname, so a site-scoped publisher must never reach it
// (that would let them claim someone else's domain). Gate it at
// `system·admin` explicitly, above the per-site branch that would
// otherwise map it to the site-write right.
if m == "POST" && path.contains("/domains/") && path.ends_with("/attach-unverified") {
return Some(Self::new(Resource::System, None, Action::Admin));
}
// The generic multi-record DNS verifier (`domain verify-records`) is an
// operator-only diagnostic that resolves ARBITRARY record names over DNS —
// not confined to a host the site owns. Like `attach-unverified`, it must
// never be reachable by a site-scoped publisher, so gate it at `system·admin`
// explicitly, above the per-site branch that would otherwise map a
// `/domains/` POST to the site-write right. (Matches both the direct and the
// project-scoped `/api/projects/<p>/sites/…` path forms.)
if m == "POST" && path.contains("/domains/") && path.ends_with("/verify-records") {
return Some(Self::new(Resource::System, None, Action::Admin));
}
// Persistent-**volume** management (`compute volume ls/rm`) is a NODE-GLOBAL
// operator tool: it lists/removes volume directories across *every*
// project/tenant on the node (keyed by bare volume name, not scoped to a
// project). It must therefore be gated at `system·admin` — never reachable by a
// project-scoped grant. Both the general `/api/compute/*` branch and the
// project-scoped `.../compute/*` catch-all below would otherwise map it to a
// per-project `Project·Read/Deploy` right, which a `project_admin`/`_publisher`
// (delete) or even a `project_viewer` (list) token on *any* project satisfies —
// letting that tenant enumerate and irreversibly destroy *another* tenant's
// volumes. Gate it explicitly, above both branches, matching both the direct
// (`/api/compute/volumes…`) and project-scoped (`/api/projects/<p>/compute/
// volumes…`) path forms (`require_auth` authorizes the original, project-
// qualified path, so both can appear here).
if is_compute_volumes_path(path) {
return Some(Self::new(Resource::System, None, Action::Admin));
}
// Compute **maintenance/diagnostic** tools (`compute status|ipam|dns|reconcile|
// restart|set-health|netdiag`) are NODE-GLOBAL operator instruments: they
// observe *and* override the reconcile plane across *every* tenant on the node
// (all replicas' health/state/IP, the shared IP pool, the internal-DNS fleet,
// and forcing/kicking replicas). Like `compute volumes`, they must be gated at
// `system·admin` — the general `/api/compute/*` branch and the project-scoped
// catch-all below would otherwise map them to a per-project `Project·Read/Deploy`
// right that any tenant's token satisfies, leaking cross-tenant state or letting
// one tenant flip another's health. Gate explicitly, above both branches,
// matching both the direct (`/api/compute/status…`) and project-scoped
// (`/api/projects/<p>/compute/status…`) forms.
if is_compute_maintenance_path(path) {
return Some(Self::new(Resource::System, None, Action::Admin));
}
// Project-scoped endpoints: `/api/projects/<proj>/<rest...>` (0.2.0). Parsed
// through the shared `project_api_path` so this and the request-scoping
// middleware agree on the tenant segment.
if let Some((proj, sub)) = project_api_path(path) {
if proj.is_empty() {
// `/api/projects/` (trailing slash) or a malformed `//…` — listing.
return Some(Self::new(Resource::System, None, Action::Read));
}
let sub: Vec<&str> = sub.split('/').filter(|s| !s.is_empty()).collect();
return Some(match sub.split_first() {
// The project entity itself: read, or manage (admin).
None => Self::new(
Resource::Project,
Some(proj.to_string()),
if get { Action::Read } else { Action::Admin },
),
// A site within the project: `.../sites/<site>/<site-sub...>`.
Some((&"sites", tail)) => {
let site = tail.first().copied().unwrap_or("");
if site.is_empty() {
return Some(Self::new(
Resource::Project,
Some(proj.to_string()),
Action::Read,
));
}
let site_sub: Vec<&str> = tail.iter().skip(1).copied().collect();
match site_subpath_action(&m, get, &site_sub) {
Some(a) => Self::new(Resource::Site, Some(format!("{proj}/{site}")), a),
// Unknown subpath — deny-safe.
None => Self::new(Resource::System, None, Action::Admin),
}
}
// The project's internal secret store: sensitive (sealed credentials),
// so gated above the general project-owned mapping with its own
// `Resource::Secrets` — list with `Read`, mutate with `Write` (both
// satisfied by a `Secrets·Admin` grant); target = the project.
Some((&"secrets", _)) => Self::new(
Resource::Secrets,
Some(proj.to_string()),
if get { Action::Read } else { Action::Write },
),
// The project's SMTP email profiles are credential config (a sealed
// password + relay config), so — like `secrets` — they are gated with
// `Resource::Secrets` rather than the general project mapping: list/show
// with `Read`, set/delete with `Write` (both satisfied by a
// `Secrets·Admin` grant); target = the project.
Some((&"email", _)) => Self::new(
Resource::Secrets,
Some(proj.to_string()),
if get { Action::Read } else { Action::Write },
),
// The project's tenancy schema defines the tenant-isolation boundary
// that scopes **every** guest query — which column keys each table,
// and deny-by-default on undeclared tables. Weakening it (marking a
// sensitive table `Unscoped`, or repointing a tenant key) would expose
// cross-tenant rows, so it is an owner-level act: read with
// `Project·Read`, but **mutate with `Project·Admin`** — never the
// deploy-grade publisher right the general project-owned mapping below
// would grant (a publisher who can ship code must not be able to
// redraw the isolation boundary). Gated explicitly, above that
// catch-all, so a `project_publisher` token cannot reach it.
Some((&"tenancy", _)) => Self::new(
Resource::Project,
Some(proj.to_string()),
if get { Action::Read } else { Action::Admin },
),
// Owner-gated schema migrations (`/api/projects/<proj>/migrate/…`) apply
// owner-authority DDL — at least as boundary-critical as the tenancy schema — so the
// mutating verbs (apply/dry-run) gate at **`Project·Admin`**, never the deploy-grade
// publisher the general project-owned catch-all below would grant; read-only status is
// `Project·Read`. Gated explicitly here, above that catch-all, so a `project_publisher`
// can never migrate a project's schema.
Some((&"migrate", _)) => Self::new(
Resource::Project,
Some(proj.to_string()),
if get { Action::Read } else { Action::Admin },
),
// Owner-gated provisioning DRIFT-REPAIR (`/api/projects/<proj>/repair/…`) runs
// host-derived privileged provisioning DDL (role create, `ALTER DATABASE OWNER`,
// `REASSIGN OWNED`) — an escalation risk at least as boundary-critical as the
// migrate surface. BOTH forms (apply = `POST …/repair/<db>`, dry-run = `POST
// …/repair/<db>/dry-run`) gate at **`Project·Admin`** on THIS project, never the
// deploy-grade publisher the general project catch-all below would grant. Gated
// explicitly here, above that catch-all, so a `project_publisher` can never run
// the superuser repair DDL. (`repair` is read-free — every verb is a POST — so
// even the dry-run stays Admin; the `get` branch is unreachable but harmless.)
Some((&"repair", _)) => {
Self::new(Resource::Project, Some(proj.to_string()), Action::Admin)
}
// Owner-gated DECLARATIVE managed-database front door
// (`/api/projects/<proj>/databases/…`, #501 Stage B): a `PUT` (declare) /
// `POST …/ensure` provisions owner-role identities (CREATE ROLE / owner-role
// DDL as superuser, exactly like migrate/repair), so the mutating verbs gate at
// **`Project·Admin`** — never the deploy-grade publisher the general project
// catch-all below would grant; read-only `GET` (ls/get/status) is
// `Project·Read`. Gated explicitly here, ABOVE that catch-all, so a
// `project_publisher`/deployer can NEVER declare a database (mirrors the
// migrate/repair placement — the `/api/repair` escalation lesson).
Some((&"databases", _)) => Self::new(
Resource::Project,
Some(proj.to_string()),
if get { Action::Read } else { Action::Admin },
),
// Operator S3 upload-credential minting (`POST /api/projects/<proj>/blob-mint-upload`,
// M3): gated with the DEDICATED `Resource::BlobUpload` scoped to THIS project (target
// `Some(<proj>)`, derived from the path — mirroring the repair/migrate precedent), NOT
// the deploy-grade publisher the general project catch-all below would grant. Scoping
// to the project (rather than a global `None`) lets a project-scoped `BlobUpload·Write`
// grant mint for ITS OWN project while a DIFFERENT project's grant is refused; a global
// `admin` / global `BlobUpload·Write` (target `None`) still satisfies it (the global
// wildcard covers every target). The concrete `<project>/<site>/<container>` is still
// host-forced from this project + the body at the handler. `BlobUpload` is
// admin/explicit-grant only (never the default publisher/deployer/project_* roles), so
// this surface stays operator-only. A POST-only surface ⇒ always `Action::Write`. Gated
// explicitly, above that catch-all, so a `project_publisher` can never mint a credential.
Some((&"blob-mint-upload", _)) => {
Self::new(Resource::BlobUpload, Some(proj.to_string()), Action::Write)
}
// The project-bus operator surface (`/api/projects/<proj>/_boatramp/bus/…`):
// dead-letter + work-queue inspection/management for the **shared project
// bus** (the `{project}/bus/{topic}` keyspace a `bus:<topic>` publish routes
// to, common to every site in the project). Because the bus is a
// project-wide shared resource — one operator managing it affects every
// site — the destructive ops are gated ABOVE the deploy-grade publisher
// right: read (`ls`/`show`/`peek`/`replay`/`groups`) with `Project·Read`,
// but the destructive POSTs (`dlq` purge/redrive/discard, `queue/group`
// reset/delete, `queue/pause`) with **`Project·Admin`** — stronger than the
// per-SITE `Site·Write` the site bus surface uses, and never satisfied by a
// `project_publisher`. The `proj` segment is the tenant boundary (parsed via
// the shared `project_api_path`), so a token scoped to project P can reach
// ONLY P's bus. Gated explicitly, above the general project-owned catch-all,
// so a publisher cannot redrive/purge the shared bus.
Some((&"_boatramp", _)) => Self::new(
Resource::Project,
Some(proj.to_string()),
if get { Action::Read } else { Action::Admin },
),
// The project's per-tenant sealed-secret store (`/api/projects/<proj>/
// tenant-secrets/<tenant>/<name>`, task #493) — sealed per-tenant credentials (each
// firm's OWN third-party OAuth `client_secret`), at least as sensitive as the
// project `secrets/` store. Gated with the DEDICATED `Resource::Secrets` (list/show
// with `Read`, set/delete with `Write` — both satisfied by a `Secrets·Admin` grant,
// matching `/api/secrets`), NOT the general project mapping below. This mirrors the
// `secrets`/`email` arms and is placed ABOVE the `Some(_)` catch-all so a
// `project_publisher` (whose deploy-grade right the catch-all would grant) can NEVER
// write a firm's OAuth secret (Security HIGH-1 — the `/api/repair` escalation
// lesson). Target = the project.
Some((&"tenant-secrets", _)) => Self::new(
Resource::Secrets,
Some(proj.to_string()),
if get { Action::Read } else { Action::Write },
),
// Project-owned resources (functions/compute/workflows/config/…):
// read with `Project·Read`, mutate with `Project·Deploy`.
Some(_) => Self::new(
Resource::Project,
Some(proj.to_string()),
if get { Action::Read } else { Action::Deploy },
),
});
}
// Legacy per-site endpoints: `/api/sites/<site>/<sub...>`. The site lives in
// the `default` project post-migration, so the target is project-qualified.
if let Some(rest) = path.strip_prefix("/api/sites/") {
let mut segs = rest.split('/');
let site = segs.next().unwrap_or("");
if site.is_empty() {
// `/api/sites/` (trailing slash) — listing.
return Some(Self::new(Resource::System, None, Action::Read));
}
let target = Some(format!("{}/{site}", crate::project::DEFAULT_PROJECT));
let sub: Vec<&str> = segs.filter(|s| !s.is_empty()).collect();
let action = site_subpath_action(&m, get, &sub);
return Some(match action {
Some(a) => Self::new(Resource::Site, target, a),
// Unknown subpath — deny-safe.
None => Self::new(Resource::System, None, Action::Admin),
});
}
// Exact, non-site endpoints.
let default_project = crate::project::DEFAULT_PROJECT.to_string();
let right = match path {
"/api/sites" => Self::new(Resource::System, None, Action::Read),
// Node-level instance-lifecycle + memory observability (construens
// memory-instance-observability): read-only telemetry over the node's shared wasm engine
// (warm/cold/evict + RSS). A NODE-global read, gated `System·Read` EXPLICITLY (never a
// per-project mapping) — it reveals resident component hashes + memory across every project
// on the node, so a project-scoped role must not reach it.
"/api/instance-stats" => Self::new(Resource::System, None, Action::Read),
// Node-global health snapshot (construens node-health-alerting): `/data` filesystem
// headroom + (later) managed-SQL health. A NODE-global read gated `System·Read`
// EXPLICITLY — never a per-project mapping (it reveals node-wide disk/health, and the
// disk-full incident it guards is a node fault, not a project one).
"/api/node-health" => Self::new(Resource::System, None, Action::Read),
// Listing projects is a node-level read; creating one is a node-admin act
// (only `/api/projects` exactly — a specific project is handled above).
"/api/projects" => {
let action = if get { Action::Read } else { Action::Admin };
Self::new(Resource::System, None, action)
}
// Functions (FA-1/FA-2) are **project-owned** (0.2.0): read the view with
// `project·read`, mutate (deploy a version, alias, rollback, delete) with
// `project·deploy`, scoped to the default project for the legacy path.
p if p == "/api/functions" || p.starts_with("/api/functions/") => {
let action = if get { Action::Read } else { Action::Deploy };
Self::new(Resource::Project, Some(default_project.clone()), action)
}
// Workflows (FA-6) are project-owned too; same shape as `/api/functions`.
p if p == "/api/workflows" || p.starts_with("/api/workflows/") => {
let action = if get { Action::Read } else { Action::Deploy };
Self::new(Resource::Project, Some(default_project.clone()), action)
}
// Compute workloads (project-owned): read/deploy within the default project.
p if p == "/api/compute" || p.starts_with("/api/compute/") => {
let action = if get { Action::Read } else { Action::Deploy };
Self::new(Resource::Project, Some(default_project.clone()), action)
}
// The owner-gated **schema-migration** surface (`/api/migrate/{db}/{apply,dry-run,
// status}`): boatramp applies an ordered migration set as the project's non-superuser
// OWNER role (owner-authority DDL — CREATE/ALTER/DROP tables, RLS policies, allowlisted
// extensions). Because DDL redraws the schema — at least as boundary-critical as the
// tenancy schema above — the mutating verbs are gated at **`Project·Admin`**, NEVER the
// deploy-grade publisher right the `/api/sql/` path below uses (a ship-only CI token must
// not be able to migrate the schema). Read-only `status` needs only `Project·Read`.
// Gated explicitly ABOVE the `/api/sql/` catch-all so a publisher cannot reach it.
// Control-plane STORE-layout migration (the default-scope re-home — the console wizard's
// back end). NODE-DESTRUCTIVE, so node-global `System·Admin` for the mutating verbs and
// `System·Read` for status — NEVER the per-project `Project·Admin(default)` the
// `/api/migrate/` SQL-schema arm below resolves to. The SINGULAR-HYPHEN path
// `/api/store-migrate/…` cannot match `starts_with("/api/migrate/")`, and these explicit
// arms sit ABOVE that arm as defense-in-depth (a store-migration token must never be a
// per-project right). Re-checked in-handler via `assert_store_migrate_is_system_admin`.
"/api/store-migrate/status" => Self::new(Resource::System, None, Action::Read),
p if p.starts_with("/api/store-migrate/") => {
Self::new(Resource::System, None, Action::Admin)
}
p if p.starts_with("/api/migrate/") => Self::new(
Resource::Project,
Some(default_project.clone()),
if get { Action::Read } else { Action::Admin },
),
// The owner-gated provisioning DRIFT-REPAIR surface (`POST /api/repair/{db}` +
// `/api/repair/{db}/dry-run`): repair runs host-derived privileged provisioning DDL
// (role create, `ALTER DATABASE OWNER`, `REASSIGN OWNED`). Because `/api/repair/…`
// would OTHERWISE be swept by the `/api/sql/` catch-all below — which resolves to
// `Project·Deploy`, a right a ship-only publisher token holds — nesting it under `sql`
// would be an ESCALATION (a publisher could run the superuser repair DDL). So it gets
// its OWN prefix, gated at **`Project·Admin`** for BOTH apply and dry-run, placed
// ABOVE the `/api/sql/` arm. (Every repair verb is a POST, so the dry-run stays Admin
// too; the `get` branch is unreachable but kept uniform.)
p if p.starts_with("/api/repair/") => Self::new(
Resource::Project,
Some(default_project.clone()),
Action::Admin,
),
// The owner-gated DECLARATIVE managed-database front door (`/api/databases`,
// `/api/databases/{name}`, `/api/databases/{name}/{ensure,status}`, #501 Stage B).
// A `PUT` (declare) / `POST …/ensure` mints owner-role identities as the superuser
// (CREATE ROLE / owner-role DDL), so — exactly like `/api/migrate/` and
// `/api/repair/` above — the mutating verbs gate at **`Project·Admin`**, NEVER the
// deploy-grade publisher right the project-owned catch-all arms use (a ship-only
// publisher must not be able to provision a database). Read-only `GET` (ls/get/
// status) needs only `Project·Read`. Its OWN prefix, gated explicitly, so a
// publisher can never reach the declare/provision path (the escalation lesson).
p if p == "/api/databases" || p.starts_with("/api/databases/") => Self::new(
Resource::Project,
Some(default_project.clone()),
if get { Action::Read } else { Action::Admin },
),
// Operator S3 upload-credential minting (`POST /api/blob-mint-upload`, PLAN-blob-s3-ingress
// §6 / M3): mint a short-lived, scoped S3 upload credential for a project+site's blob
// container. Gated with the DEDICATED `Resource::BlobUpload` scoped to the DEFAULT project
// (target `Some(default_project)` — this global path is the legacy default-project form, so
// it mirrors the sibling `/api/repair/` and `/api/migrate/` arms which likewise scope to the
// default project; the concrete `<project>/<site>/<container>` is host-forced from the
// token's project + the request body at the handler). A project-scoped `BlobUpload·Write`
// grant for the default project satisfies it; a global `admin` / global `BlobUpload·Write`
// (target `None`) still does too. Placed ABOVE the `/api/blobs` arm (which resolves to
// `Blobs·Deploy`, a right a ship-only publisher holds — nesting under it would be an
// ESCALATION, letting a publisher mint upload credentials). `BlobUpload` is NOT granted to
// the default publisher/deployer/project_* roles (only via `admin` / an explicit grant), so
// this surface stays operator-only. A POST-only surface ⇒ always `Action::Write`.
"/api/blob-mint-upload" => Self::new(
Resource::BlobUpload,
Some(default_project.clone()),
Action::Write,
),
// Operator SQL to a managed database (project-owned): migrations + queries
// are operator tools scoped to the default project. `project·deploy` (they
// are POST bodies that mutate or read the project's managed DB); the
// `compute exec`-style risk on writes is additionally posture-gated.
p if p.starts_with("/api/sql/") => Self::new(
Resource::Project,
Some(default_project.clone()),
Action::Deploy,
),
// GraphQL administration — subgraph registration, the operation safelist,
// and the composed supergraph — is project-owned (0.2.0), the same as
// functions/compute/workflows: read the surface with `project·read`, mutate
// it with `project·deploy`, scoped to the default project for this global
// path (the project-scoped `/api/projects/<proj>/graphql/…` form is handled
// above).
p if p == "/api/graphql" || p.starts_with("/api/graphql/") => {
let action = if get { Action::Read } else { Action::Deploy };
Self::new(Resource::Project, Some(default_project.clone()), action)
}
"/api/blobs" => Self::new(Resource::Blobs, None, Action::Deploy),
"/api/certs" => Self::new(Resource::Certs, None, Action::Read),
"/api/cache/invalidate" => Self::new(Resource::Cache, None, Action::Write),
"/api/metrics" => Self::new(Resource::System, None, Action::Read),
// Prune/scrub are node-level destructive maintenance ops; so is a libsql
// database relocation (`sql move`, which vacuums a copy and removes the
// source file). All three gate at `system·admin`.
"/api/prune" | "/api/scrub" | "/api/sql-move" => {
Self::new(Resource::System, None, Action::Admin)
}
p if p == "/api/tokens" || p.starts_with("/api/tokens/") => {
Self::new(Resource::Tokens, None, Action::Admin)
}
p if p == "/api/authz/policy" || p.starts_with("/api/authz/") => {
Self::new(Resource::System, None, Action::Admin)
}
// The daemon-mediated blob drain (`POST /api/blob-drain`, v0.6.3): the running node
// drains its OWN configured `[serve.blob_fallback]` secondary → primary. This is a
// NODE-level maintenance op (like prune/scrub/sql-move) — it touches every tenant's
// objects on the node's blob store and is not scoped to a project — so it is gated at
// `system·admin`, never a per-project right a tenant token satisfies. The SINGULAR,
// HYPHENATED path is deliberate: it does NOT match the `/api/blobs/` (Blobs·Deploy)
// prefix matcher above (that requires a literal `/api/blobs/` — a ship-only publisher
// holds `Blobs·Deploy`, so a collision would be an ESCALATION), nor the exact
// `/api/blobs` / `/api/blob-mint-upload` arms. Gated explicitly here (above the
// deny-safe `_` default that resolves the same, so a routing/table regression is
// visible) and re-checked defense-in-depth at the handler.
"/api/blob-drain" => {
// GATE MUTATION SEAM (D4, the crux): under `blob-drain-gate-mutation` +
// `BOATRAMP_BLOBDRAIN_MUTATE_LOWER_AUTHZ`, downgrade this node-level op to a
// project-scoped `Deploy` right — the exact escalation a bad routing/table change
// would introduce (a ship-only Deploy token could then trigger the drain). The
// gate proves the check is load-bearing: a Deploy/Project·Admin token must NOT
// satisfy the required right, so the mutation FAILS the gate. Compiled OUT of every
// real build.
#[cfg(feature = "blob-drain-gate-mutation")]
if std::env::var("BOATRAMP_BLOBDRAIN_MUTATE_LOWER_AUTHZ")
.map(|v| !v.is_empty() && v != "0")
.unwrap_or(false)
{
return Some(Self::new(
Resource::Project,
Some(default_project.clone()),
Action::Deploy,
));
}
Self::new(Resource::System, None, Action::Admin)
}
// The general blob purge (`POST /api/blob-purge`, v0.6.4): a PROVABLY-SAFE-only reclaim —
// `unreferenced` GC (blobs no live manifest references) or the `drained_source`
// decommission (delete a migration-source key only once byte-confirmed in the primary).
// Like the blob DRAIN (and prune/scrub/sql-move), it is a NODE-level DESTRUCTIVE op that
// touches every tenant's objects on the node's blob store and is not scoped to a project,
// so it is gated at `system·admin`, never a per-project right a tenant token satisfies.
// The SINGULAR, HYPHENATED path is deliberate: it does NOT match the `/api/blobs/`
// (Blobs·Deploy) prefix matcher above (that requires a literal `/api/blobs/` — a
// ship-only publisher holds `Blobs·Deploy`, so a collision would be an ESCALATION), nor
// the exact `/api/blobs` / `/api/blob-mint-upload` / `/api/blob-drain` arms. Gated
// explicitly here (above the deny-safe `_` default that resolves the same, so a
// routing/table regression is visible) and re-checked defense-in-depth at the handler.
"/api/blob-purge" => Self::new(Resource::System, None, Action::Admin),
// The on-demand LIVE control-plane KV checkpoint (`POST /api/kv-checkpoint`, v0.9.0
// KV-recovery, #3): a node-level MUTATING op (freeze WAL→L0, advance the durable
// frontier) not scoped to a project, so `system·admin` — never a per-project right.
// Explicit (above the deny-safe `_` default that resolves the same, so a routing/table
// regression is visible) and re-checked defense-in-depth at the handler.
"/api/kv-checkpoint" => Self::new(Resource::System, None, Action::Admin),
// The portable control-plane KV dump/restore (`GET /api/kv-export` / `POST
// /api/kv-import`, kv-sql WS7): a node-GLOBAL op over the WHOLE control plane — sealed
// secrets, config, RBAC. Both are gated `System·Admin` EXPLICITLY (never a per-project
// right): an export streams the whole control plane, and an import can REPLACE/overlay
// it. Gated here above the deny-safe `_` default that resolves the same (so a
// routing/table regression is visible), and re-checked defense-in-depth at each handler.
// The SINGULAR, HYPHENATED paths deliberately do NOT match any `/api/<family>/*`
// project-scoped matcher, so a project-scoped token can never satisfy them.
"/api/kv-export" => Self::new(Resource::System, None, Action::Admin),
"/api/kv-import" => Self::new(Resource::System, None, Action::Admin),
// Native project export/import (env-clone, `POST /api/project-export` / `POST
// /api/project-import`): a node-GLOBAL op that moves a project's LIVE tenant data —
// managed-DB dumps, the control-plane KV slice, blobs — between environments. Gated
// `System·Admin` EXPLICITLY (never a per-project right): an export streams real data
// out and an import writes/overlays it. Same hyphenated-path collision-avoidance as the
// kv-* arms (the SINGULAR path never matches a `/api/<family>/*` project matcher), and
// re-checked defense-in-depth at each handler.
"/api/project-export" => Self::new(Resource::System, None, Action::Admin),
"/api/project-import" => Self::new(Resource::System, None, Action::Admin),
// The structured blob transition-mode state (`GET /api/blob-status`, v0.6.4): whether a
// read-fallback secondary is attached (the node is mid-migration). A READ-only node
// status — the same grade as `/api/sites` / `/api/metrics` — so `system·read` (never a
// per-project right). Same hyphen-path collision-avoidance as the sibling `blob-*` arms.
"/api/blob-status" => Self::new(Resource::System, None, Action::Read),
"/api/blob-verify" => Self::new(Resource::System, None, Action::Read),
// The control-plane KV degraded state (`GET /api/kv-status`, v0.9.0 KV-recovery, C6):
// whether a self-heal-on-open quarantined a torn WAL tail. A READ-only node status
// (the same grade as `/api/blob-status` / `/api/metrics`) exposing NO secrets — only the
// quarantined ids + loss window — so `system·read`, NEVER a per-project right. Explicit
// (not the deny-safe `_` default, which would over-gate a read to `system·admin`).
"/api/kv-status" => Self::new(Resource::System, None, Action::Read),
// The running node's boatramp version (`GET /api/version`): the exact package version of
// the binary serving this request. Deliberately an OPERATOR-only read — the same grade as
// `/api/metrics` / `/api/blob-status`, so `system·read` (never a per-project right a tenant
// token satisfies, and — crucially — NEVER `None`: unlike `/healthz`/`/readyz`, the version
// is NOT on the unauthenticated public router, so a client cannot fingerprint the release
// without an operator token). Returning `Some(System, Read)` here (rather than leaning on
// the deny-safe `_` default, which would over-gate it to `system·admin`) is the whole
// point — an explicit READ arm keeps it reachable by a read-only operator token yet closed
// to the public. A regression that makes this `None` (public) or a `Project` right (tenant
// -reachable) is exactly what the `version_endpoint_is_operator_read_gated` gate catches.
"/api/version" => Self::new(Resource::System, None, Action::Read),
// Any other `/api/*` path: deny-safe (must hold system·admin).
_ => Self::new(Resource::System, None, Action::Admin),
};
Some(right)
}
}
/// The action a per-site subpath requires, or `None` if the subpath is unknown.
fn site_subpath_action(method: &str, get: bool, sub: &[&str]) -> Option<Action> {
match sub.first().copied() {
// `deployments`, `deployments/<id>`, `deployments/<id>/activate`.
Some("deployments") => {
let activate = sub.last() == Some(&"activate");
if activate || method == "POST" {
Some(Action::Deploy) // activate, or create a deployment
} else if get {
Some(Action::Read)
} else {
None
}
}
Some("current") if get => Some(Action::Read),
Some("config") => {
if get {
Some(Action::Read)
} else if method == "PUT" {
Some(Action::Write)
} else {
None
}
}
// `domains/<host>/verification[/check]`, `domain-verifications`.
Some("domains") => {
let check = sub.last() == Some(&"check"); // a status check (POST, but read-grade)
if get || check {
Some(Action::Read)
} else if method == "POST" || method == "DELETE" {
Some(Action::Write)
} else {
None
}
}
Some("domain-verifications") if get => Some(Action::Read),
Some("aliases") => {
if get {
Some(Action::Read)
} else if method == "PUT" || method == "DELETE" {
Some(Action::Write)
} else {
None
}
}
// `_boatramp/handlers`, `_boatramp/logs`, `_boatramp/queue/{peek,replay,groups}` (per-site
// observability, read); `_boatramp/dlq` purge/redrive/discard and
// `_boatramp/queue/group` reset/delete are destructive site-scoped writes.
Some("_boatramp") => {
let write_sub = matches!(sub.get(1).copied(), Some("dlq") | Some("queue"));
if method == "POST" && write_sub {
Some(Action::Write)
} else if get {
Some(Action::Read)
} else {
None
}
}
_ => None,
}
}
/// The project segment of a `"<project>/<site>"` target (the part before the first
/// `/`), or the whole string when it carries no `/` (a bare project target).
pub fn project_of(target: &str) -> &str {
target.split_once('/').map_or(target, |(p, _)| p)
}
/// Split an `/api/projects/<proj>/<sub…>` request path into its tenant project
/// segment and the remaining sub-path, or `None` when the path is not
/// project-scoped. `proj` is the first path segment after the prefix (possibly
/// empty for a malformed `//…` or a trailing-slash `/api/projects/`); `sub` is
/// everything after the first `/` (empty for the bare `/api/projects/<proj>` entity
/// path).
///
/// Both the request-scoping middleware (`project_scope::scope_of`) and
/// [`Right::required`] resolve the tenant through this one function, so the two can
/// never disagree on which project a request targets — a confused-deputy hazard if
/// they parsed it differently (each still applies its own policy to an empty
/// segment: the middleware carries the default tenant, `Right::required` treats it
/// as the listing/System right; both fail closed).
pub fn project_api_path(path: &str) -> Option<(&str, &str)> {
let rest = path.strip_prefix("/api/projects/")?;
Some(rest.split_once('/').unwrap_or((rest, "")))
}
/// Whether `path` targets the node-global persistent-**volume** management surface
/// (`compute volume ls/rm`) — `GET`/`DELETE` on `.../compute/volumes[/<name>]`, in
/// either the direct (`/api/compute/volumes…`) or the project-scoped
/// (`/api/projects/<proj>/compute/volumes…`) form. These endpoints operate across
/// every tenant on the node, so [`Right::required`] gates them at `system·admin`
/// rather than the per-project right the surrounding `/api/compute/*` mappings give.
fn is_compute_volumes_path(path: &str) -> bool {
// The `compute/` segment after either `/api/` or `/api/projects/<proj>/`.
let after_compute = path.strip_prefix("/api/compute/").or_else(|| {
project_api_path(path)
.and_then(|(proj, sub)| (!proj.is_empty()).then_some(sub)?.strip_prefix("compute/"))
});
matches!(after_compute, Some(rest) if rest == "volumes" || rest.starts_with("volumes/"))
}
/// Whether `path` targets the node-global compute **maintenance/diagnostic** surface
/// (`compute status|ipam|dns|reconcile` and the `compute/maintenance/*` mutators —
/// `restart`, `set-health`, `netdiag`), in either the direct (`/api/compute/status…`)
/// or the project-scoped (`/api/projects/<proj>/compute/status…`) form. These
/// instruments read and override the reconcile plane across every tenant on the node,
/// so [`Right::required`] gates them at `system·admin` rather than the per-project
/// right the surrounding `/api/compute/*` mappings give. The reserved first segments
/// (`status`, `ipam`, `dns`, `reconcile`, `maintenance`) therefore shadow any workload
/// of the same name on these routes — the same trade-off `volumes` already makes.
fn is_compute_maintenance_path(path: &str) -> bool {
let after_compute = path.strip_prefix("/api/compute/").or_else(|| {
project_api_path(path)
.and_then(|(proj, sub)| (!proj.is_empty()).then_some(sub)?.strip_prefix("compute/"))
});
matches!(
after_compute,
Some(rest) if rest == "status"
|| rest == "ipam"
|| rest == "dns"
|| rest.starts_with("dns/")
|| rest == "reconcile"
|| rest == "maintenance"
|| rest.starts_with("maintenance/")
)
}
/// Whether a granted target covers a required target:
/// - `None` — the global wildcard (an untargeted grant), covers everything;
/// - `"<project>/*"` — a project wildcard, covers any `"<project>/<site>"` (the
/// required target's project segment must equal `<project>`);
/// - anything else — an exact string match.
///
/// A grant target of the literal string `"*"` is **not** a global wildcard: the
/// wildcard is the *absence* of a target (`None`), so a `"*"` target matches only
/// a resource literally named `*`. This keeps the pure oracle faithful to the
/// Cedar authorizer, which likewise matches `"*"` as a literal set member — and a
/// resource named `*` cannot be created (`validate_resource_name` rejects it).
///
/// **Fail-closed A8 backstop (v0.7.0).** Before any positive match, a *present* grant
/// target that is not a conforming role target (`<seg>` / `<seg>/<seg>` / `<seg>/*`
/// with every segment a valid slug — [`is_conforming_role_target`]) matches NOTHING.
/// The four mint feeders reject a non-conforming target at issue time, but a token
/// minted before v0.7.0 — or offline — carries an unvalidated target; this screen
/// makes such a target inert at authorization time without a token-format migration.
/// A `required` target is host-derived and always conforming, so it is not re-screened
/// here (a required `*` is a legitimate literal-`*` resource lookup, which no real
/// resource can be — it simply won't match a real grant).
fn target_matches(granted: Option<&str>, required: Option<&str>) -> bool {
match granted {
None => true,
// A non-conforming grant target is inert — it can never cover a required right.
Some(g) if !crate::project::is_conforming_role_target(g) => false,
Some(g) => match g.strip_suffix("/*") {
Some(project) => required.is_some_and(|r| project_of(r) == project),
None => required == Some(g),
},
}
}
/// A set of granted [`Right`]s with the pure authorization decision. This is the
/// pure-Rust reference decision: the differential oracle the Cedar authorizer is
/// tested against, and used by issuance code that needs to reason about a role's
/// effective rights.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RightSet {
rights: Vec<Right>,
}
impl RightSet {
/// An empty set (grants nothing).
pub fn new() -> Self {
Self::default()
}
/// Add a right (de-duplicated).
pub fn insert(&mut self, right: Right) {
if !self.rights.contains(&right) {
self.rights.push(right);
}
}
/// Whether any held right satisfies `required`.
pub fn allows(&self, required: &Right) -> bool {
self.rights.iter().any(|g| g.satisfies(required))
}
/// Whether the set grants nothing.
pub fn is_empty(&self) -> bool {
self.rights.is_empty()
}
/// The held rights.
pub fn rights(&self) -> &[Right] {
&self.rights
}
}
impl FromIterator<Right> for RightSet {
fn from_iter<I: IntoIterator<Item = Right>>(iter: I) -> Self {
let mut set = Self::new();
for r in iter {
set.insert(r);
}
set
}
}
/// What a target-scoped role's grant target names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetKind {
/// A per-site role: target is `"<project>/<site>"`.
Site,
/// A per-project role: target is a bare `"<project>"`.
Project,
}
/// A role granted to a principal: a role `name` from the [`AuthzPolicy`], plus an
/// optional `target` for target-scoped roles — a `"<project>/<site>"` for a site
/// role, or a bare `"<project>"` for a project role.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GrantedRole {
/// The role name (a key in [`AuthzPolicy::roles`]).
pub name: String,
/// The site this instance is scoped to, for target-scoped roles.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
impl GrantedRole {
/// A global role (no target).
pub fn global(name: impl Into<String>) -> Self {
Self {
name: name.into(),
target: None,
}
}
/// A target-scoped role (e.g. `publisher` on a site).
pub fn scoped(name: impl Into<String>, target: impl Into<String>) -> Self {
Self {
name: name.into(),
target: Some(target.into()),
}
}
/// Parse a role spec: `"<role>"` (global) or `"<role>:<target>"`
/// (target-scoped). Used by the CLI `--role`, the API token-create body, and
/// the OIDC claim→roles mapping, so they agree on the format.
pub fn parse(spec: &str) -> Self {
match spec.split_once(':') {
Some((name, target)) if !target.trim().is_empty() => {
Self::scoped(name.trim(), target.trim())
}
_ => Self::global(spec.trim()),
}
}
}
/// How a [`RightTemplate`] derives its target when expanding a role.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetScope {
/// Wildcard/global: the expanded right has `target = None`.
AnyTarget,
/// Bind to the granted role instance's target verbatim (a site role's
/// `"<project>/<site>"`, or a project role's `"<project>"`).
RoleTarget,
/// A **project role** granting a per-site right over *every* site in its project:
/// the granted target is a bare project name `"<project>"` and the expanded right
/// gets the project-wildcard target `"<project>/*"`, which
/// [`target_matches`](Right::satisfies) treats as covering any `"<project>/<site>"`.
ProjectWildcard,
}
impl TargetScope {
/// Whether this scope binds a target (so its role is target-scoped).
pub fn is_targeted(self) -> bool {
matches!(self, Self::RoleTarget | Self::ProjectWildcard)
}
}
/// One right a role grants, before binding to a concrete target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RightTemplate {
/// The resource the right governs.
pub resource: Resource,
/// The action granted.
pub action: Action,
/// How the target is derived when the role is expanded.
pub scope: TargetScope,
}
impl RightTemplate {
/// A global right template (`AnyTarget`).
pub fn any(resource: Resource, action: Action) -> Self {
Self {
resource,
action,
scope: TargetScope::AnyTarget,
}
}
/// A target-scoped right template (`RoleTarget`).
pub fn scoped(resource: Resource, action: Action) -> Self {
Self {
resource,
action,
scope: TargetScope::RoleTarget,
}
}
/// A project-wildcard right template (`ProjectWildcard`): a per-site right a
/// project role confers over every site in the project.
pub fn project_wildcard(resource: Resource, action: Action) -> Self {
Self {
resource,
action,
scope: TargetScope::ProjectWildcard,
}
}
}
/// The RBAC policy: roles → the rights they grant. Stored at KV `authz/policy`
/// (schema v1); when absent the server uses [`AuthzPolicy::default_policy`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AuthzPolicy {
/// Pinned schema discriminant (`v1`).
#[serde(default = "crate::schema_version")]
pub version: u32,
/// Role name → the right templates it grants.
pub roles: BTreeMap<String, Vec<RightTemplate>>,
}
impl Default for AuthzPolicy {
fn default() -> Self {
Self::default_policy()
}
}
impl AuthzPolicy {
/// The built-in default policy: `admin`, `publisher`,
/// `deployer`, `viewer`, `operator`.
pub fn default_policy() -> Self {
let mut roles: BTreeMap<String, Vec<RightTemplate>> = BTreeMap::new();
// admin — every (resource, action). Expanded as one Admin right per
// resource with a wildcard target.
roles.insert(
"admin".to_string(),
Resource::ALL
.iter()
.map(|&r| RightTemplate::any(r, Action::Admin))
.collect(),
);
// publisher (site) — full control of its site + blob uploads.
roles.insert(
"publisher".to_string(),
vec![
RightTemplate::scoped(Resource::Site, Action::Read),
RightTemplate::scoped(Resource::Site, Action::Write),
RightTemplate::scoped(Resource::Site, Action::Deploy),
RightTemplate::any(Resource::Blobs, Action::Deploy),
],
);
// deployer (site) — ship + read, but not edit config.
roles.insert(
"deployer".to_string(),
vec![
RightTemplate::scoped(Resource::Site, Action::Read),
RightTemplate::scoped(Resource::Site, Action::Deploy),
RightTemplate::any(Resource::Blobs, Action::Deploy),
],
);
// viewer (site) — read-only on its site.
roles.insert(
"viewer".to_string(),
vec![RightTemplate::scoped(Resource::Site, Action::Read)],
);
// operator — node-level read + cache control, no site access.
roles.insert(
"operator".to_string(),
vec![
RightTemplate::any(Resource::System, Action::Read),
RightTemplate::any(Resource::Certs, Action::Read),
RightTemplate::any(Resource::Cache, Action::Write),
],
);
// project-admin (project) — full control of the project: its own resources
// (functions/compute/workflows/config, via `Project·Admin`) AND every site in
// it (`Site·Admin` over the project wildcard) + blob uploads.
roles.insert(
"project_admin".to_string(),
vec![
RightTemplate::scoped(Resource::Project, Action::Admin),
// Managing the project's sealed secrets is an admin-level right
// (reading/rotating credentials), granted to the project admin only —
// not to publishers, who merely *reference* a `boatramp:<name>`.
RightTemplate::scoped(Resource::Secrets, Action::Admin),
RightTemplate::project_wildcard(Resource::Site, Action::Admin),
RightTemplate::any(Resource::Blobs, Action::Deploy),
],
);
// project-publisher (project) — ship + configure any site in the project and
// manage its functions/compute (write + deploy + read), but not admin the
// project entity (no membership/role changes).
roles.insert(
"project_publisher".to_string(),
vec![
RightTemplate::scoped(Resource::Project, Action::Read),
RightTemplate::scoped(Resource::Project, Action::Write),
RightTemplate::scoped(Resource::Project, Action::Deploy),
RightTemplate::project_wildcard(Resource::Site, Action::Read),
RightTemplate::project_wildcard(Resource::Site, Action::Write),
RightTemplate::project_wildcard(Resource::Site, Action::Deploy),
RightTemplate::any(Resource::Blobs, Action::Deploy),
],
);
// project-viewer (project) — read-only across the whole project.
roles.insert(
"project_viewer".to_string(),
vec![
RightTemplate::scoped(Resource::Project, Action::Read),
RightTemplate::project_wildcard(Resource::Site, Action::Read),
],
);
Self {
version: crate::SCHEMA_VERSION,
roles,
}
}
/// Whether `role` is target-scoped (any of its templates binds the target).
pub fn role_takes_target(&self, role: &str) -> bool {
self.roles
.get(role)
.is_some_and(|ts| ts.iter().any(|t| t.scope.is_targeted()))
}
/// What kind of target a role's grant carries: a per-site `"<project>/<site>"`
/// ([`TargetKind::Site`], a role with a Site `RoleTarget` template) or a bare
/// `"<project>"` ([`TargetKind::Project`], a role with a `ProjectWildcard` or a
/// non-Site `RoleTarget` template). `None` for a global role. Used to normalize a
/// legacy site-only grant to the `default` project ([`normalize_grants`]).
///
/// [`normalize_grants`]: Self::normalize_grants
pub fn role_target_kind(&self, role: &str) -> Option<TargetKind> {
let templates = self.roles.get(role)?;
let mut site = false;
let mut project = false;
for t in templates {
match t.scope {
TargetScope::RoleTarget if t.resource == Resource::Site => site = true,
TargetScope::RoleTarget => project = true,
TargetScope::ProjectWildcard => project = true,
TargetScope::AnyTarget => {}
}
}
// A Site `RoleTarget` role is per-site; a project role (ProjectWildcard, or a
// `RoleTarget` on the Project resource) is per-project.
if site {
Some(TargetKind::Site)
} else if project {
Some(TargetKind::Project)
} else {
None
}
}
/// Normalize legacy grants for 0.2.0: a **site** role granted a bare target with
/// no project segment (a pre-project token, e.g. `publisher:blog`) is read as the
/// `default` project (`publisher:default/blog`). Project and global roles, and any
/// already-qualified `"<project>/<site>"` target, pass through unchanged. Run once
/// at token→roles ingestion, before either [`rights_for`](Self::rights_for) or the
/// Cedar authorizer, so both decide on the same normalized grants.
pub fn normalize_grants(&self, roles: &[GrantedRole]) -> Vec<GrantedRole> {
roles
.iter()
.map(|g| match (&g.target, self.role_target_kind(&g.name)) {
(Some(t), Some(TargetKind::Site)) if !t.contains('/') => {
GrantedRole::scoped(&g.name, format!("{}/{t}", crate::project::DEFAULT_PROJECT))
}
_ => g.clone(),
})
.collect()
}
/// Expand a principal's granted roles into the concrete [`RightSet`] they
/// confer under this policy. A target-scoped template on a role granted
/// without a target contributes nothing (defensive). This is the pure RBAC
/// expansion the Cedar authorizer reproduces as a policy set. Callers pass
/// grants already normalized by [`normalize_grants`](Self::normalize_grants).
pub fn rights_for(&self, roles: &[GrantedRole]) -> RightSet {
let mut set = RightSet::new();
for granted in roles {
let Some(templates) = self.roles.get(&granted.name) else {
continue;
};
for t in templates {
let target = match t.scope {
TargetScope::AnyTarget => None,
TargetScope::RoleTarget => match &granted.target {
Some(x) => Some(x.clone()),
None => continue,
},
// A project role's per-site right covers every site in its
// project: expand the bare project target to `"<project>/*"`.
TargetScope::ProjectWildcard => match &granted.target {
Some(x) => Some(format!("{x}/*")),
None => continue,
},
};
set.insert(Right::new(t.resource, target, t.action));
}
}
set
}
}
/// KV key for the RBAC policy document (`authz/policy`); absent ⇒ the built-in
/// [`AuthzPolicy::default_policy`].
pub const POLICY_KEY: &str = "authz/policy";
/// KV key prefix for revocation markers — presence of `authz/revoked/<id>`
/// means the token with authority revocation id `<id>` (and its attenuations)
/// is revoked.
pub const REVOKED_PREFIX: &str = "authz/revoked/";
/// KV key prefix for issued-token metadata (`authz/tokens/<id>`). The token
/// itself is never stored — only this metadata, for `token ls`.
pub const TOKEN_META_PREFIX: &str = "authz/tokens/";
/// The revocation-marker key for an authority revocation id.
pub fn revoked_key(revocation_id: &str) -> String {
format!("{REVOKED_PREFIX}{revocation_id}")
}
/// KV key prefix for extra trusted **root anchors** added by `auth rotate-root`
/// (`auth/root/{alg:hex}`). Each is a `TokenPublicKey` trusted alongside the
/// configured primary root during a make-before-break root rotation.
pub const ROOT_ANCHOR_PREFIX: &str = "auth/root/";
/// The root-anchor key trusting `pubkey` (an `alg:hex`-encoded `TokenPublicKey`).
pub fn root_anchor_key(pubkey: &str) -> String {
format!("{ROOT_ANCHOR_PREFIX}{pubkey}")
}
/// The metadata key for an issued token (keyed by its authority revocation id).
pub fn token_meta_key(id: &str) -> String {
format!("{TOKEN_META_PREFIX}{id}")
}
/// The single-use marker key for a redeemed first-token bootstrap secret
/// (keyed by the secret's SHA-256 hex).
pub fn bootstrap_key(secret_hash: &str) -> String {
format!("authz/bootstrap/{secret_hash}")
}
/// Metadata for an issued token (`authz/tokens/<id>`). The token itself is
/// shown once at creation and never stored; this is what `token ls` reports and
/// what `token rm` needs to find the revocation id. Schema v1.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenMeta {
/// Pinned schema discriminant (`v1`).
#[serde(default = "crate::schema_version")]
pub version: u32,
/// Human label for the token.
pub label: String,
/// The roles the token grants.
pub roles: Vec<GrantedRole>,
/// Unix timestamp (seconds) of creation.
pub created_at: u64,
/// Unix timestamp (seconds) of expiry, if the token carries a TTL.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<u64>,
/// The authority revocation id (hex) — also the `authz/tokens/<id>` key and
/// the argument to `token rm`.
pub revocation_id: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn admin_satisfies_every_action_on_its_resource() {
let admin_site = Right::new(Resource::Site, None, Action::Admin);
for action in [Action::Read, Action::Write, Action::Deploy, Action::Admin] {
let required = Right::new(Resource::Site, Some("blog".into()), action);
assert!(
admin_site.satisfies(&required),
"admin must satisfy {action:?}"
);
}
// …but not a different resource.
assert!(!admin_site.satisfies(&Right::new(Resource::Tokens, None, Action::Read)));
}
/// G3 (A8 fail-closed authz-match backstop): a right whose grant target is not a
/// conforming role target (a token minted before v0.7.0, or offline, carrying
/// `publisher:${PROJECT}` / `acme/../evil` / a literal `*`) must match NOTHING —
/// even a required right that names the identical string. This is the load-bearing
/// screen for already-issued tokens without a token-format migration.
///
/// Mutation witness: delete the `is_conforming_role_target` guard in
/// `target_matches` and this test fails — the `${PROJECT}` grant would then satisfy
/// a required `Some("${PROJECT}")` (self-match) and authorize.
#[test]
fn nonconforming_grant_target_matches_nothing() {
for bad in ["${PROJECT}", "acme/../evil", "*", "a b", "acme/a/b", "café"] {
let granted = Right::new(Resource::Site, Some(bad.to_string()), Action::Write);
// Even a required right naming the exact same string does not match.
let required_same = Right::new(Resource::Site, Some(bad.to_string()), Action::Write);
assert!(
!granted.satisfies(&required_same),
"a non-conforming grant target {bad:?} must match nothing, even itself"
);
// And it does not cover an ordinary site either.
let required_site = Right::new(Resource::Site, Some("blog".to_string()), Action::Write);
assert!(
!granted.satisfies(&required_site),
"a non-conforming grant target {bad:?} must not cover an ordinary target"
);
}
// A conforming grant still works (the backstop is not a blanket deny).
let ok = Right::new(Resource::Site, Some("acme/blog".to_string()), Action::Write);
assert!(ok.satisfies(&Right::new(
Resource::Site,
Some("acme/blog".to_string()),
Action::Write
)));
let wild = Right::new(Resource::Site, Some("acme/*".to_string()), Action::Write);
assert!(wild.satisfies(&Right::new(
Resource::Site,
Some("acme/blog".to_string()),
Action::Write
)));
}
/// The `is_conforming_role_target` grammar itself (the segment-aware predicate the
/// backstop and the feeders share): valid singles/pairs/wildcards accept; anything
/// with a bad segment, a homoglyph, an extra `/`, or the injection class rejects.
#[test]
fn conforming_role_target_grammar() {
use crate::project::is_conforming_role_target;
for ok in ["acme", "acme/blog", "acme/*", "a", "a1_b-2/c-3_d"] {
assert!(is_conforming_role_target(ok), "{ok:?} should conform");
}
for bad in [
"",
"*",
"/blog",
"acme/",
"acme//blog",
"acme/a/b",
"acme/../evil",
"${PROJECT}",
"{tenant}/blog",
"-acme",
"acme/-blog",
"аcme/blog", // Cyrillic homoglyph in the project segment
"acme/*/x",
] {
assert!(!is_conforming_role_target(bad), "{bad:?} must NOT conform");
}
}
#[test]
fn target_scoping_is_exact_unless_wildcard() {
let blog = Right::new(Resource::Site, Some("blog".into()), Action::Write);
assert!(blog.satisfies(&Right::new(
Resource::Site,
Some("blog".into()),
Action::Write
)));
assert!(!blog.satisfies(&Right::new(
Resource::Site,
Some("api".into()),
Action::Write
)));
// A wildcard grant covers any site.
let any = Right::new(Resource::Site, None, Action::Write);
assert!(any.satisfies(&Right::new(
Resource::Site,
Some("api".into()),
Action::Write
)));
}
#[test]
fn distinct_actions_do_not_imply_each_other() {
let write = Right::new(Resource::Site, Some("blog".into()), Action::Write);
let deploy_req = Right::new(Resource::Site, Some("blog".into()), Action::Deploy);
assert!(
!write.satisfies(&deploy_req),
"write must not imply deploy (only admin does)"
);
}
/// Every row of the request→right table.
#[test]
fn required_right_table() {
let cases: &[(&str, &str, Option<Right>)] = &[
("POST", "/api/auth/exchange", None),
("GET", "/api/auth/whoami", None),
// Minting a mesh join token is admin-scoped (deny-safe default for
// `/api/cluster/*`) — an operator issues it.
(
"POST",
"/api/cluster/join-token",
Some(Right::new(Resource::System, None, Action::Admin)),
),
// Presenting a join token to join is gated by the token itself, not
// an admin bearer (the handler verifies it) — exact-path `None`.
("POST", "/api/cluster/join", None),
// Rotating this node's mesh key is an operator action → admin-scoped.
(
"POST",
"/api/cluster/rotate-key",
Some(Right::new(Resource::System, None, Action::Admin)),
),
// Revoking a node from the mesh is an operator action → admin-scoped.
(
"POST",
"/api/cluster/revoke",
Some(Right::new(Resource::System, None, Action::Admin)),
),
(
"PUT",
"/api/blobs/abc123",
Some(Right::new(Resource::Blobs, None, Action::Deploy)),
),
(
"GET",
"/api/sites",
Some(Right::new(Resource::System, None, Action::Read)),
),
(
"POST",
"/api/sites/blog/deployments",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Deploy,
)),
),
(
"GET",
"/api/sites/blog/deployments",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Read,
)),
),
(
"GET",
"/api/sites/blog/deployments/d1",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Read,
)),
),
(
"POST",
"/api/sites/blog/deployments/d1/activate",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Deploy,
)),
),
(
"GET",
"/api/sites/blog/current",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Read,
)),
),
(
"GET",
"/api/sites/blog/config",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Read,
)),
),
(
"PUT",
"/api/sites/blog/config",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Write,
)),
),
(
"GET",
"/api/sites/blog/domains/x.example.com/verification",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Read,
)),
),
(
"POST",
"/api/sites/blog/domains/x.example.com/verification",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Write,
)),
),
(
"DELETE",
"/api/sites/blog/domains/x.example.com/verification",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Write,
)),
),
(
"POST",
"/api/sites/blog/domains/x.example.com/verification/check",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Read,
)),
),
(
"GET",
"/api/sites/blog/domain-verifications",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Read,
)),
),
(
"PUT",
"/api/sites/blog/aliases/www",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Write,
)),
),
(
"GET",
"/api/sites/blog/aliases",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Read,
)),
),
(
"GET",
"/api/sites/blog/_boatramp/handlers",
Some(Right::new(
Resource::Site,
Some("default/blog".into()),
Action::Read,
)),
),
(
"POST",
"/api/tokens",
Some(Right::new(Resource::Tokens, None, Action::Admin)),
),
(
"DELETE",
"/api/tokens/t1",
Some(Right::new(Resource::Tokens, None, Action::Admin)),
),
(
"GET",
"/api/prune",
Some(Right::new(Resource::System, None, Action::Admin)),
),
(
"POST",
"/api/scrub",
Some(Right::new(Resource::System, None, Action::Admin)),
),
// Relocating a libsql database is a node-level destructive maintenance
// op → `system·admin`, alongside prune/scrub.
(
"POST",
"/api/sql-move",
Some(Right::new(Resource::System, None, Action::Admin)),
),
(
"GET",
"/api/certs",
Some(Right::new(Resource::Certs, None, Action::Read)),
),
(
"POST",
"/api/cache/invalidate",
Some(Right::new(Resource::Cache, None, Action::Write)),
),
(
"GET",
"/api/metrics",
Some(Right::new(Resource::System, None, Action::Read)),
),
// GraphQL administration is project-owned (default project for the global
// path): read the surface with `project·read`, mutate it with
// `project·deploy` — the same shape as functions/compute/workflows.
(
"GET",
"/api/graphql/supergraph",
Some(Right::new(
Resource::Project,
Some("default".into()),
Action::Read,
)),
),
(
"PUT",
"/api/graphql/subgraphs/catalog",
Some(Right::new(
Resource::Project,
Some("default".into()),
Action::Deploy,
)),
),
(
"POST",
"/api/graphql/safelist",
Some(Right::new(
Resource::Project,
Some("default".into()),
Action::Deploy,
)),
),
// Project-scoped internal secrets: the dedicated `Resource::Secrets`
// (target = the project), listed with Read, mutated with Write — NOT the
// general project-owned `Project·Deploy` mapping.
(
"GET",
"/api/projects/acme/secrets",
Some(Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Read,
)),
),
(
"POST",
"/api/projects/acme/secrets",
Some(Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Write,
)),
),
(
"DELETE",
"/api/projects/acme/secrets/db-password",
Some(Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Write,
)),
),
// Project-scoped SMTP email profiles are credential config → the same
// `Resource::Secrets` mapping as secrets (list/show Read, set/delete Write).
(
"GET",
"/api/projects/acme/email/profiles",
Some(Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Read,
)),
),
(
"PUT",
"/api/projects/acme/email/profiles/default",
Some(Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Write,
)),
),
(
"DELETE",
"/api/projects/acme/email/profiles/default",
Some(Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Write,
)),
),
// Per-tenant sealed secrets (task #493): the SAME dedicated `Resource::Secrets`
// mapping (list/show Read, set/delete Write), NOT the deploy-grade project catch-all —
// so a `project_publisher` can never write a firm's OAuth secret (Security HIGH-1). The
// `<tenant>`/`<name>` path segments do not change the resource/action.
(
"GET",
"/api/projects/acme/tenant-secrets/firm-42",
Some(Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Read,
)),
),
(
"PUT",
"/api/projects/acme/tenant-secrets/firm-42/oauth_secret",
Some(Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Write,
)),
),
(
"DELETE",
"/api/projects/acme/tenant-secrets/firm-42/oauth_secret",
Some(Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Write,
)),
),
];
for (method, path, expected) in cases {
assert_eq!(
&Right::required(method, path),
expected,
"required({method}, {path})"
);
}
}
#[test]
fn unknown_site_subpath_is_deny_safe() {
// An unmapped subpath must require system·admin, not the site's action.
assert_eq!(
Right::required("PATCH", "/api/sites/blog/frobnicate"),
Some(Right::new(Resource::System, None, Action::Admin))
);
}
#[test]
fn attach_unverified_is_admin_only() {
// Attaching a host without a proof (`domain add --unverified`) must need
// system·admin — a site-write right must NOT satisfy it, so a scoped
// publisher can't claim an arbitrary host.
let required = Right::required(
"POST",
"/api/sites/blog/domains/evil.example.com/attach-unverified",
)
.expect("route is gated");
assert_eq!(required, Right::new(Resource::System, None, Action::Admin));
// A publisher's site-write right does not satisfy the admin gate.
let site_write = Right::new(Resource::Site, Some("blog".into()), Action::Write);
assert!(!site_write.satisfies(&required));
// A system-admin right does.
assert!(Right::new(Resource::System, None, Action::Admin).satisfies(&required));
}
#[test]
fn verify_records_is_admin_only() {
// The generic multi-record DNS verifier (`domain verify-records`) resolves
// arbitrary record names, so it must need system·admin in BOTH path forms —
// never the site-write right the per-site `/domains/` mapping would give a
// scoped publisher.
let admin = Right::new(Resource::System, None, Action::Admin);
for path in [
"/api/sites/blog/domains/example.com/verify-records",
"/api/projects/acme/sites/blog/domains/example.com/verify-records",
] {
let required = Right::required("POST", path).expect("route is gated");
assert_eq!(required, admin, "{path} must need system·admin");
// A publisher's site-write right does not satisfy the admin gate.
let site_write = Right::new(Resource::Site, Some("acme/blog".into()), Action::Write);
assert!(!site_write.satisfies(&required));
assert!(admin.satisfies(&required));
}
}
#[test]
fn compute_volume_management_is_node_admin_only() {
// `compute volume ls/rm` lists/removes volume directories across EVERY tenant
// on the node, so it must require system·admin in both path forms — never the
// per-project right the general `/api/compute/*` mapping gives. Otherwise a
// project-scoped token could enumerate/destroy another tenant's volumes.
let admin = Right::new(Resource::System, None, Action::Admin);
for (method, path) in [
// Direct (global) form.
("GET", "/api/compute/volumes"),
("DELETE", "/api/compute/volumes/pg-globex"),
// Project-scoped form (the `project_scope` rewrite's original path).
("GET", "/api/projects/acme/compute/volumes"),
("DELETE", "/api/projects/acme/compute/volumes/pg-globex"),
] {
let required = Right::required(method, path).expect("route is gated");
assert_eq!(required, admin, "{method} {path} must need system·admin");
// A cross-tenant project grant must NOT satisfy it — not even the target
// project's own admin/publisher/viewer.
for role in ["project_admin", "project_publisher", "project_viewer"] {
let granted =
AuthzPolicy::default_policy().rights_for(&[GrantedRole::scoped(role, "acme")]);
assert!(
!granted.allows(&required),
"{role}:acme must be refused on {method} {path}"
);
}
// A node admin does satisfy it.
assert!(admin.satisfies(&required));
}
// A sibling compute path that is NOT the volumes surface keeps its per-project
// right (so this special-case didn't over-reach).
assert_eq!(
Right::required("GET", "/api/compute/volumesnap"),
Some(Right::new(
Resource::Project,
Some(crate::project::DEFAULT_PROJECT.to_string()),
Action::Read
))
);
}
#[test]
fn compute_maintenance_tools_are_node_admin_only() {
// The compute maintenance/diagnostic surface (status/ipam/dns/reconcile +
// maintenance mutators) observes and overrides the reconcile plane across EVERY
// tenant, so it must require system·admin in both path forms — never the
// per-project right the general `/api/compute/*` mapping gives. Otherwise a
// project-scoped token could read another tenant's replica state or flip its
// health.
let admin = Right::new(Resource::System, None, Action::Admin);
for (method, path) in [
// Direct (global) form.
("GET", "/api/compute/status"),
("GET", "/api/compute/ipam"),
("GET", "/api/compute/dns"),
("POST", "/api/compute/dns/resolve"),
("POST", "/api/compute/reconcile"),
("POST", "/api/compute/maintenance/restart"),
("POST", "/api/compute/maintenance/set-health"),
("POST", "/api/compute/maintenance/netdiag"),
// Project-scoped form (the `project_scope` rewrite's original path).
("GET", "/api/projects/acme/compute/status"),
("POST", "/api/projects/acme/compute/maintenance/set-health"),
] {
let required = Right::required(method, path).expect("route is gated");
assert_eq!(required, admin, "{method} {path} must need system·admin");
// No project grant — not even the target project's own admin — satisfies it.
for role in ["project_admin", "project_publisher", "project_viewer"] {
let granted =
AuthzPolicy::default_policy().rights_for(&[GrantedRole::scoped(role, "acme")]);
assert!(
!granted.allows(&required),
"{role}:acme must be refused on {method} {path}"
);
}
assert!(admin.satisfies(&required));
}
// A workload whose name merely STARTS WITH a reserved word (e.g. `statuspage`)
// is not the maintenance surface — it keeps its per-project right.
assert_eq!(
Right::required("GET", "/api/compute/statuspage"),
Some(Right::new(
Resource::Project,
Some(crate::project::DEFAULT_PROJECT.to_string()),
Action::Read
))
);
}
#[test]
fn project_bus_operator_surface_is_project_scoped_and_admin_gated() {
// The project-bus operator surface (`/api/projects/<proj>/_boatramp/bus/…`)
// manages the SHARED project bus (`{project}/bus/{topic}`), so:
// - reads (`ls`/`show`/`peek`/`replay`/`groups`) grade as `Project·Read`;
// - destructive writes (dlq purge/redrive/discard, queue group reset/delete,
// pause) grade as `Project·Admin` — stronger than the per-site `Site·Write`
// the site bus surface uses — because one operator's redrive/purge affects
// every site in the project.
let read = |proj: &str| Right::new(Resource::Project, Some(proj.to_string()), Action::Read);
let admin =
|proj: &str| Right::new(Resource::Project, Some(proj.to_string()), Action::Admin);
let reads = [
("GET", "/api/projects/acme/_boatramp/bus/dlq"),
("GET", "/api/projects/acme/_boatramp/bus/queue/peek"),
("GET", "/api/projects/acme/_boatramp/bus/queue/replay"),
("GET", "/api/projects/acme/_boatramp/bus/queue/groups"),
];
for (method, path) in reads {
assert_eq!(
Right::required(method, path),
Some(read("acme")),
"{method} {path} must be Project·Read"
);
}
let writes = [
("POST", "/api/projects/acme/_boatramp/bus/dlq"),
("POST", "/api/projects/acme/_boatramp/bus/queue/group"),
("POST", "/api/projects/acme/_boatramp/bus/queue/pause"),
// v0.4.24 per-topic operator policy on the shared project bus.
("POST", "/api/projects/acme/_boatramp/bus/queue/policy"),
];
for (method, path) in writes {
assert_eq!(
Right::required(method, path),
Some(admin("acme")),
"{method} {path} must be Project·Admin"
);
}
// The per-SITE policy POST grades at Site·Write (the same `_boatramp/queue/*` write arm as
// pause/group), not Project·Admin — verified via the site-scoped path.
assert_eq!(
Right::required("POST", "/api/sites/blog/_boatramp/queue/policy"),
Right::required("POST", "/api/sites/blog/_boatramp/queue/pause"),
"site queue/policy grades identically to queue/pause (Site·Write)"
);
// The destructive project-bus POST needs `Project·Admin`: a `project_admin`
// token on the SAME project satisfies it; a `project_publisher` (deploy-grade)
// and `project_viewer` do NOT — they can ship code / read, but must never be
// able to redrive/purge the shared bus.
let policy = AuthzPolicy::default_policy();
let purge = Right::required("POST", "/api/projects/acme/_boatramp/bus/dlq")
.expect("route is gated");
assert!(
policy
.rights_for(&[GrantedRole::scoped("project_admin", "acme")])
.allows(&purge),
"project_admin:acme must be able to purge its own project bus"
);
for role in ["project_publisher", "project_viewer"] {
assert!(
!policy
.rights_for(&[GrantedRole::scoped(role, "acme")])
.allows(&purge),
"{role}:acme must NOT be able to purge the shared project bus"
);
}
// Cross-project isolation (the security-critical property): a token scoped to a
// DIFFERENT project — even a `project_admin` on it — must be refused on acme's
// bus, for both the read and the destructive-write grades. The `proj` path
// segment is the tenant boundary.
let peek = Right::required("GET", "/api/projects/acme/_boatramp/bus/queue/peek")
.expect("route is gated");
for role in ["project_admin", "project_publisher", "project_viewer"] {
let other = policy.rights_for(&[GrantedRole::scoped(role, "globex")]);
assert!(
!other.allows(&purge),
"{role}:globex must be refused on acme's project bus (write)"
);
assert!(
!other.allows(&peek),
"{role}:globex must be refused on acme's project bus (read)"
);
}
// A node admin (global) satisfies both, as for every project resource.
let node_admin = policy.rights_for(&[GrantedRole::global("admin")]);
assert!(node_admin.allows(&purge) && node_admin.allows(&peek));
}
#[test]
fn default_policy_publisher_can_deploy_and_write_its_site_only() {
let policy = AuthzPolicy::default_policy();
let rights = policy.rights_for(&[GrantedRole::scoped("publisher", "blog")]);
// Can read/write/deploy blog + upload blobs…
assert!(rights.allows(&Right::new(
Resource::Site,
Some("blog".into()),
Action::Deploy
)));
assert!(rights.allows(&Right::new(
Resource::Site,
Some("blog".into()),
Action::Write
)));
assert!(rights.allows(&Right::new(Resource::Blobs, None, Action::Deploy)));
// …but not another site, nor token management.
assert!(!rights.allows(&Right::new(
Resource::Site,
Some("api".into()),
Action::Read
)));
assert!(!rights.allows(&Right::new(Resource::Tokens, None, Action::Admin)));
}
#[test]
fn default_policy_deployer_cannot_edit_config() {
let policy = AuthzPolicy::default_policy();
let rights = policy.rights_for(&[GrantedRole::scoped("deployer", "blog")]);
assert!(rights.allows(&Right::new(
Resource::Site,
Some("blog".into()),
Action::Deploy
)));
assert!(rights.allows(&Right::new(
Resource::Site,
Some("blog".into()),
Action::Read
)));
assert!(
!rights.allows(&Right::new(
Resource::Site,
Some("blog".into()),
Action::Write
)),
"deployer must not edit config"
);
}
#[test]
fn default_policy_admin_can_do_anything() {
let policy = AuthzPolicy::default_policy();
let rights = policy.rights_for(&[GrantedRole::global("admin")]);
for resource in Resource::ALL {
for action in [Action::Read, Action::Write, Action::Deploy, Action::Admin] {
let target = matches!(resource, Resource::Site).then(|| "any".to_string());
assert!(
rights.allows(&Right::new(resource, target, action)),
"admin must allow {resource:?}·{action:?}"
);
}
}
}
#[test]
fn admin_expands_to_blob_upload_but_default_publisher_roles_do_not() {
// The S3-ingress mint right is admin-gated: `admin` (via `Resource::ALL`)
// holds it on any container; the default site/deploy/project roles that CAN
// deploy content blobs must NOT be able to mint an ingress credential — that
// would let a publisher hand out scoped write access to the store.
let policy = AuthzPolicy::default_policy();
let container = || Some("acme/blog/uploads".to_string());
let mint = |t: Option<String>, a: Action| Right::new(Resource::BlobUpload, t, a);
// admin can mint on any container, at every action.
let admin = policy.rights_for(&[GrantedRole::global("admin")]);
for action in [Action::Read, Action::Write, Action::Deploy, Action::Admin] {
assert!(
admin.allows(&mint(container(), action)),
"admin must allow BlobUpload·{action:?}"
);
}
// None of the default site/project roles expand to BlobUpload — check every
// action so no arm leaks. `has_blob_deploy` records whether the role still
// holds the DISTINCT content-blob deploy right (proving BlobUpload is a
// genuinely separate resource, not a blanket blob denial).
for (role, grant, has_blob_deploy) in [
(
"publisher",
GrantedRole::scoped("publisher", "acme/blog"),
true,
),
(
"deployer",
GrantedRole::scoped("deployer", "acme/blog"),
true,
),
(
"project_admin",
GrantedRole::scoped("project_admin", "acme"),
true,
),
(
"project_publisher",
GrantedRole::scoped("project_publisher", "acme"),
true,
),
(
"project_viewer",
GrantedRole::scoped("project_viewer", "acme"),
false, // read-only: holds no deploy right at all
),
] {
let rights = policy.rights_for(&[grant]);
for action in [Action::Read, Action::Write, Action::Deploy, Action::Admin] {
assert!(
!rights.allows(&mint(container(), action)),
"{role} must NOT expand to BlobUpload·{action:?}"
);
// …with a wildcard (no-target) required right either, so the
// deny isn't just a target mismatch.
assert!(
!rights.allows(&mint(None, action)),
"{role} must NOT hold a wildcard BlobUpload·{action:?}"
);
}
assert_eq!(
rights.allows(&Right::new(Resource::Blobs, None, Action::Deploy)),
has_blob_deploy,
"{role} content-blob deploy right unchanged (BlobUpload is separate)"
);
}
}
#[test]
fn blob_upload_is_in_resource_all_so_admin_covers_it() {
assert!(
Resource::ALL.contains(&Resource::BlobUpload),
"BlobUpload must be in Resource::ALL so `admin` expands to it"
);
// Its serde term is stable + distinct (routing/authz greppability).
assert_eq!(Resource::BlobUpload.as_str(), "blob_upload");
}
#[test]
fn instance_stats_endpoint_is_node_global_system_read() {
// construens memory-instance-observability: `/api/instance-stats` is a NODE-global read (the
// engine is shared across every project), gated `System·Read` — NOT a per-project right, so a
// project-scoped role (even that project's admin) must NOT reach it. The `operator`/node-read
// role does. Guards the node-global-authz discipline (a per-project mapping would leak every
// project's resident component hashes + memory to a single-project caller).
let required = Right::required("GET", "/api/instance-stats").expect("route is gated");
assert_eq!(required, Right::new(Resource::System, None, Action::Read));
// A project-scoped admin is refused.
let proj_admin = AuthzPolicy::default_policy()
.rights_for(&[GrantedRole::scoped("project_admin", "acme")]);
assert!(
!proj_admin.allows(&required),
"a project-scoped admin must not reach the node-global instance stats"
);
// A node operator (System·Read) is allowed; a global admin covers it too.
let operator = AuthzPolicy::default_policy().rights_for(&[GrantedRole::global("operator")]);
assert!(
operator.allows(&required),
"an operator (System·Read) may read node stats"
);
let admin = AuthzPolicy::default_policy().rights_for(&[GrantedRole::global("admin")]);
assert!(admin.allows(&required), "a node admin may read node stats");
}
#[test]
fn node_health_endpoint_is_node_global_system_read() {
// construens node-health-alerting: `/api/node-health` is a NODE-global read (disk headroom /
// health are node faults, not project ones), gated `System·Read` EXPLICITLY — a project-scoped
// role (even that project's admin) must NOT reach it (a per-project mapping would leak node-wide
// state + invert the node-global-authz discipline [[node-global-endpoint-authz]]).
let required = Right::required("GET", "/api/node-health").expect("route is gated");
assert_eq!(required, Right::new(Resource::System, None, Action::Read));
let proj_admin = AuthzPolicy::default_policy()
.rights_for(&[GrantedRole::scoped("project_admin", "acme")]);
assert!(
!proj_admin.allows(&required),
"a project-scoped admin must not reach the node-global health endpoint"
);
let operator = AuthzPolicy::default_policy().rights_for(&[GrantedRole::global("operator")]);
assert!(
operator.allows(&required),
"an operator (System·Read) may read node health"
);
let admin = AuthzPolicy::default_policy().rights_for(&[GrantedRole::global("admin")]);
assert!(admin.allows(&required), "a node admin may read node health");
}
#[test]
fn site_role_without_target_grants_nothing_site_scoped() {
let policy = AuthzPolicy::default_policy();
// `publisher` granted globally (no target) — the site templates are
// RoleTarget, so they contribute nothing; only the AnyTarget blobs right.
let rights = policy.rights_for(&[GrantedRole::global("publisher")]);
assert!(rights.allows(&Right::new(Resource::Blobs, None, Action::Deploy)));
assert!(!rights.allows(&Right::new(
Resource::Site,
Some("blog".into()),
Action::Read
)));
}
#[test]
fn role_takes_target_classifies_roles() {
let policy = AuthzPolicy::default_policy();
assert!(policy.role_takes_target("publisher"));
assert!(policy.role_takes_target("viewer"));
assert!(!policy.role_takes_target("admin"));
assert!(!policy.role_takes_target("operator"));
}
#[test]
fn policy_round_trips_through_json() {
let policy = AuthzPolicy::default_policy();
let json = serde_json::to_string(&policy).unwrap();
let back: AuthzPolicy = serde_json::from_str(&json).unwrap();
assert_eq!(policy, back);
assert_eq!(back.version, crate::SCHEMA_VERSION);
}
#[test]
fn unknown_role_is_ignored() {
let policy = AuthzPolicy::default_policy();
let rights = policy.rights_for(&[GrantedRole::global("nonesuch")]);
assert!(rights.is_empty());
}
// ---- 0.2.0 project scoping ---------------------------------------------
#[test]
fn legacy_site_grant_normalizes_to_default_project() {
let policy = AuthzPolicy::default_policy();
// A pre-project token `publisher:blog` reads as the default project.
let n = policy.normalize_grants(&[GrantedRole::scoped("publisher", "blog")]);
assert_eq!(n, vec![GrantedRole::scoped("publisher", "default/blog")]);
// An already-qualified site grant, a project grant, and a global grant pass
// through untouched (a project name must NOT gain a `default/` prefix).
let untouched = [
GrantedRole::scoped("publisher", "acme/blog"),
GrantedRole::scoped("project_admin", "acme"),
GrantedRole::global("admin"),
];
assert_eq!(policy.normalize_grants(&untouched), untouched);
}
#[test]
fn project_admin_covers_its_project_but_not_another() {
let policy = AuthzPolicy::default_policy();
let rights = policy.rights_for(&[GrantedRole::scoped("project_admin", "acme")]);
// Every site in acme, at every action.
for action in [Action::Read, Action::Write, Action::Deploy, Action::Admin] {
assert!(
rights.allows(&Right::new(
Resource::Site,
Some("acme/blog".into()),
action
)),
"project-admin:acme covers acme/blog·{action:?}"
);
}
// The project's own resources (functions/compute via Project).
assert!(rights.allows(&Right::new(
Resource::Project,
Some("acme".into()),
Action::Deploy
)));
assert!(rights.allows(&Right::new(
Resource::Project,
Some("acme".into()),
Action::Admin
)));
// But NOT another project's sites or project resource — the tenant boundary.
assert!(!rights.allows(&Right::new(
Resource::Site,
Some("shop/blog".into()),
Action::Read
)));
assert!(!rights.allows(&Right::new(
Resource::Project,
Some("shop".into()),
Action::Read
)));
// A bare/global site target is not covered by a project-scoped grant.
assert!(!rights.allows(&Right::new(
Resource::Site,
Some("blog".into()),
Action::Read
)));
}
#[test]
fn secrets_are_managed_by_project_admin_only_and_project_scoped() {
let policy = AuthzPolicy::default_policy();
// project_admin:acme manages acme's secrets (list + mutate, via Secrets·Admin)…
let admin = policy.rights_for(&[GrantedRole::scoped("project_admin", "acme")]);
for action in [Action::Read, Action::Write, Action::Admin] {
assert!(
admin.allows(&Right::new(Resource::Secrets, Some("acme".into()), action)),
"project-admin:acme manages acme secrets·{action:?}"
);
}
// …but NOT another project's secrets — the tenant boundary.
assert!(!admin.allows(&Right::new(
Resource::Secrets,
Some("globex".into()),
Action::Read
)));
// A project publisher ships + configures but must NOT manage secrets
// (credentials are admin-gated; a publisher only *references* boatramp:<name>).
let publisher = policy.rights_for(&[GrantedRole::scoped("project_publisher", "acme")]);
assert!(!publisher.allows(&Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Read
)));
assert!(!publisher.allows(&Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Write
)));
// A project viewer can't even list secret names.
let viewer = policy.rights_for(&[GrantedRole::scoped("project_viewer", "acme")]);
assert!(!viewer.allows(&Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Read
)));
// The global admin manages every project's secrets (via Resource::ALL).
let root = policy.rights_for(&[GrantedRole::global("admin")]);
assert!(root.allows(&Right::new(
Resource::Secrets,
Some("acme".into()),
Action::Admin
)));
assert!(root.allows(&Right::new(
Resource::Secrets,
Some("globex".into()),
Action::Write
)));
}
/// Task #493 (Security HIGH-1, the `/api/repair` escalation lesson): the per-tenant sealed-secret
/// routes gate on the dedicated `Resource::Secrets` (Read to list, Write to mutate), NOT the
/// deploy-grade project catch-all — so a `project_publisher` cannot write a firm's OAuth secret.
/// Drives the WHOLE route→required-right→role-allows path, both the global and project-scoped
/// role forms, so it fails if the `tenant-secrets` arm is removed and the route falls to the
/// catch-all (which a publisher WOULD satisfy).
#[test]
fn tenant_secrets_routes_gate_on_secrets_not_publisher() {
let policy = AuthzPolicy::default_policy();
let list = Right::required("GET", "/api/projects/acme/tenant-secrets/firm-42")
.expect("route is gated");
let write = Right::required(
"PUT",
"/api/projects/acme/tenant-secrets/firm-42/oauth_secret",
)
.expect("route is gated");
let del = Right::required(
"DELETE",
"/api/projects/acme/tenant-secrets/firm-42/oauth_secret",
)
.expect("route is gated");
// Each maps to the dedicated Resource::Secrets on the project (NOT Resource::Project).
assert_eq!(list.resource, Resource::Secrets);
assert_eq!(write.resource, Resource::Secrets);
assert_eq!(del.resource, Resource::Secrets);
assert_eq!(write.action, Action::Write);
assert_eq!(list.action, Action::Read);
// A `project_publisher` (deploy-grade) does NOT satisfy the write — the whole point.
let publisher = policy.rights_for(&[GrantedRole::scoped("project_publisher", "acme")]);
assert!(
!publisher.allows(&write),
"a publisher must NOT write a tenant secret"
);
assert!(
!publisher.allows(&list),
"a publisher must NOT even list tenant-secret names"
);
// A `Secrets·Admin` (project_admin) DOES — via both the scoped and global admin forms.
let admin = policy.rights_for(&[GrantedRole::scoped("project_admin", "acme")]);
assert!(admin.allows(&write) && admin.allows(&list) && admin.allows(&del));
let root = policy.rights_for(&[GrantedRole::global("admin")]);
assert!(root.allows(&write) && root.allows(&list) && root.allows(&del));
// The tenant boundary holds: acme's project-admin cannot write globex's tenant secrets.
let globex_write =
Right::required("PUT", "/api/projects/globex/tenant-secrets/firm-9/k").unwrap();
assert!(!admin.allows(&globex_write));
}
#[test]
fn project_viewer_is_read_only_across_the_project() {
let policy = AuthzPolicy::default_policy();
let rights = policy.rights_for(&[GrantedRole::scoped("project_viewer", "acme")]);
assert!(rights.allows(&Right::new(
Resource::Site,
Some("acme/blog".into()),
Action::Read
)));
assert!(rights.allows(&Right::new(
Resource::Project,
Some("acme".into()),
Action::Read
)));
// No writes/deploys anywhere.
assert!(!rights.allows(&Right::new(
Resource::Site,
Some("acme/blog".into()),
Action::Write
)));
assert!(!rights.allows(&Right::new(
Resource::Project,
Some("acme".into()),
Action::Deploy
)));
}
#[test]
fn project_publisher_ships_but_cannot_admin_the_project() {
let policy = AuthzPolicy::default_policy();
let rights = policy.rights_for(&[GrantedRole::scoped("project_publisher", "acme")]);
assert!(rights.allows(&Right::new(
Resource::Site,
Some("acme/blog".into()),
Action::Deploy
)));
assert!(rights.allows(&Right::new(
Resource::Project,
Some("acme".into()),
Action::Deploy
)));
assert!(rights.allows(&Right::new(Resource::Blobs, None, Action::Deploy)));
// Admin of the project entity (membership/roles) is reserved for project-admin.
assert!(!rights.allows(&Right::new(
Resource::Project,
Some("acme".into()),
Action::Admin
)));
}
#[test]
fn required_maps_project_paths() {
// A site within a project.
assert_eq!(
Right::required("POST", "/api/projects/acme/sites/blog/deployments"),
Some(Right::new(
Resource::Site,
Some("acme/blog".into()),
Action::Deploy
))
);
// A project-owned resource (a function): read vs mutate.
assert_eq!(
Right::required("GET", "/api/projects/acme/functions/resize"),
Some(Right::new(
Resource::Project,
Some("acme".into()),
Action::Read
))
);
assert_eq!(
Right::required("POST", "/api/projects/acme/functions/resize/versions"),
Some(Right::new(
Resource::Project,
Some("acme".into()),
Action::Deploy
))
);
// The project entity itself.
assert_eq!(
Right::required("DELETE", "/api/projects/acme"),
Some(Right::new(
Resource::Project,
Some("acme".into()),
Action::Admin
))
);
// Listing/creating projects is node-level.
assert_eq!(
Right::required("GET", "/api/projects"),
Some(Right::new(Resource::System, None, Action::Read))
);
assert_eq!(
Right::required("POST", "/api/projects"),
Some(Right::new(Resource::System, None, Action::Admin))
);
// Legacy top-level functions map to the default project now.
assert_eq!(
Right::required("GET", "/api/functions"),
Some(Right::new(
Resource::Project,
Some("default".into()),
Action::Read
))
);
}
/// The project tenancy schema is the tenant-isolation boundary: reading it is a
/// `Project·Read`, but **mutating it demands `Project·Admin`** — never the
/// deploy-grade publisher right the general project-owned catch-all would grant.
/// A `project_publisher` (who holds `Project·Deploy`) must therefore be refused,
/// while a `project_admin` is allowed — so a code-shipping role cannot redraw the
/// isolation boundary out from under the tenants.
#[test]
fn tenancy_schema_read_is_project_read_but_write_is_project_admin() {
assert_eq!(
Right::required("GET", "/api/projects/acme/tenancy"),
Some(Right::new(
Resource::Project,
Some("acme".into()),
Action::Read
))
);
for method in ["PUT", "POST", "DELETE"] {
assert_eq!(
Right::required(method, "/api/projects/acme/tenancy"),
Some(Right::new(
Resource::Project,
Some("acme".into()),
Action::Admin
)),
"{method} /tenancy must require Project·Admin, not Deploy",
);
}
// A publisher (Project·Deploy on acme) can ship code but MUST NOT rewrite the
// isolation boundary; an admin can.
let put_tenancy = Right::required("PUT", "/api/projects/acme/tenancy").unwrap();
let policy = AuthzPolicy::default_policy();
let publisher = policy.rights_for(&[GrantedRole::scoped("project_publisher", "acme")]);
assert!(
!publisher.allows(&put_tenancy),
"a project_publisher must not be able to PUT the tenancy schema",
);
let admin = policy.rights_for(&[GrantedRole::scoped("project_admin", "acme")]);
assert!(
admin.allows(&put_tenancy),
"a project_admin must be able to PUT the tenancy schema",
);
}
/// The owner-gated schema-migration surface (`/api/migrate/…`) applies owner-authority DDL,
/// so — like the tenancy schema — its mutating verbs require `Project·Admin`, never the
/// deploy-grade publisher right the sibling `/api/sql/` path uses. A `project_publisher` (who
/// can ship code) must be REFUSED; a `project_admin` allowed. Read-only `status` is `Project·Read`.
#[test]
fn migrate_surface_write_is_project_admin_not_publisher() {
// The path maps to the default project (a global operator path, like /api/sql).
let default_admin = Right::new(Resource::Project, Some("default".into()), Action::Admin);
for path in ["/api/migrate/appdb/apply", "/api/migrate/appdb/dry-run"] {
assert_eq!(
Right::required("POST", path),
Some(default_admin.clone()),
"POST {path} must require Project·Admin",
);
}
// Read-only status is a Project·Read.
assert_eq!(
Right::required("GET", "/api/migrate/appdb/status"),
Some(Right::new(
Resource::Project,
Some("default".into()),
Action::Read
)),
);
// A publisher on the default project ships code but MUST NOT migrate the schema; an admin can.
let apply = Right::required("POST", "/api/migrate/appdb/apply").unwrap();
let policy = AuthzPolicy::default_policy();
let publisher = policy.rights_for(&[GrantedRole::scoped("project_publisher", "default")]);
assert!(
!publisher.allows(&apply),
"a project_publisher must not be able to run migrations",
);
let admin = policy.rights_for(&[GrantedRole::scoped("project_admin", "default")]);
assert!(
admin.allows(&apply),
"a project_admin must be able to run migrations",
);
// The PROJECT-SCOPED form (`/api/projects/<p>/migrate/…`, the one a non-default tenant uses)
// must ALSO gate mutate at Project·Admin on THAT project — never the deploy-grade publisher.
for path in [
"/api/projects/acme/migrate/appdb/apply",
"/api/projects/acme/migrate/appdb/dry-run",
] {
assert_eq!(
Right::required("POST", path),
Some(Right::new(
Resource::Project,
Some("acme".into()),
Action::Admin
)),
"POST {path} must require Project·Admin on acme",
);
}
let acme_apply = Right::required("POST", "/api/projects/acme/migrate/appdb/apply").unwrap();
let acme_pub = policy.rights_for(&[GrantedRole::scoped("project_publisher", "acme")]);
assert!(
!acme_pub.allows(&acme_apply),
"a project_publisher on acme must not be able to migrate acme's schema",
);
let acme_admin = policy.rights_for(&[GrantedRole::scoped("project_admin", "acme")]);
assert!(
acme_admin.allows(&acme_apply),
"a project_admin on acme must be able to migrate acme's schema",
);
}
/// The owner-gated provisioning DRIFT-REPAIR surface (`/api/repair/…`) runs host-derived
/// privileged provisioning DDL (role create, `ALTER DATABASE OWNER`, `REASSIGN OWNED`). It must
/// NOT be reachable at the `Project·Deploy` grade the sibling `/api/sql/` catch-all grants (which
/// a ship-only publisher holds) — that would be an escalation. BOTH the apply (`POST
/// /api/repair/{db}`) AND the dry-run (`POST /api/repair/{db}/dry-run`) gate at `Project·Admin`;
/// a `project_publisher` is REFUSED, a `project_admin` ALLOWED, for the global + project-scoped
/// forms alike.
#[test]
fn repair_surface_is_project_admin_not_publisher() {
let policy = AuthzPolicy::default_policy();
// ---- Global (default-project) form: apply + dry-run both map to default-project Admin. ----
let default_admin = Right::new(Resource::Project, Some("default".into()), Action::Admin);
for path in ["/api/repair/appdb", "/api/repair/appdb/dry-run"] {
assert_eq!(
Right::required("POST", path),
Some(default_admin.clone()),
"POST {path} must require Project·Admin (never the /api/sql Deploy grade)",
);
}
// A publisher on the default project ships code but MUST NOT run the repair DDL; an admin can.
let publisher = policy.rights_for(&[GrantedRole::scoped("project_publisher", "default")]);
let admin = policy.rights_for(&[GrantedRole::scoped("project_admin", "default")]);
for path in ["/api/repair/appdb", "/api/repair/appdb/dry-run"] {
let req = Right::required("POST", path).unwrap();
assert!(
!publisher.allows(&req),
"a project_publisher must NOT be able to run repair ({path})",
);
assert!(
admin.allows(&req),
"a project_admin must be able to run repair ({path})",
);
}
// ---- Project-scoped form (the one a non-default tenant uses). ----
for path in [
"/api/projects/acme/repair/appdb",
"/api/projects/acme/repair/appdb/dry-run",
] {
assert_eq!(
Right::required("POST", path),
Some(Right::new(
Resource::Project,
Some("acme".into()),
Action::Admin
)),
"POST {path} must require Project·Admin on acme",
);
}
let acme_apply = Right::required("POST", "/api/projects/acme/repair/appdb").unwrap();
let acme_dry = Right::required("POST", "/api/projects/acme/repair/appdb/dry-run").unwrap();
let acme_pub = policy.rights_for(&[GrantedRole::scoped("project_publisher", "acme")]);
let acme_admin = policy.rights_for(&[GrantedRole::scoped("project_admin", "acme")]);
for req in [&acme_apply, &acme_dry] {
assert!(
!acme_pub.allows(req),
"a project_publisher on acme must NOT be able to repair acme's provisioning",
);
assert!(
acme_admin.allows(req),
"a project_admin on acme must be able to repair acme's provisioning",
);
}
// Cross-tenant: an acme admin grant does NOT satisfy repairing globex's provisioning.
let globex_apply = Right::required("POST", "/api/projects/globex/repair/appdb").unwrap();
assert!(
!acme_admin.allows(&globex_apply),
"an acme grant must not reach globex's repair surface",
);
}
/// #501 Stage B — the DECLARATIVE managed-database front door (`/api/databases/…`) mints
/// owner-role identities (CREATE ROLE / owner-role DDL as superuser, exactly like
/// migrate/repair), so the mutating verbs (`PUT` declare, `POST …/ensure`) MUST gate at
/// `Project·Admin` — never the `Project·Deploy` grade a ship-only publisher holds (that would
/// be an escalation). Read-only `GET` (ls/get/status) is `Project·Read`. A `project_publisher`
/// is REFUSED the mutating verbs; a `project_admin` is ALLOWED — for the global (default-project)
/// AND the project-scoped forms alike. Cross-tenant grants do not leak.
///
/// This is the mutation-sensitive assertion for the authz condition: a mutation that gated the
/// declare at `Project·Deploy` (nesting it under the general project catch-all) would let the
/// publisher `allows(&put)` — which this test asserts must be FALSE.
#[test]
fn databases_surface_is_project_admin_not_publisher() {
let policy = AuthzPolicy::default_policy();
// ---- Global (default-project) form. ----
let default_admin = Right::new(Resource::Project, Some("default".into()), Action::Admin);
let default_read = Right::new(Resource::Project, Some("default".into()), Action::Read);
// Mutating verbs (declare + ensure) → Admin.
for (method, path) in [
("PUT", "/api/databases/appdb"),
("POST", "/api/databases/appdb/ensure"),
] {
assert_eq!(
Right::required(method, path),
Some(default_admin.clone()),
"{method} {path} must require Project·Admin (never the Deploy grade)",
);
}
// Read verbs (ls/get/status) → Read.
for path in [
"/api/databases",
"/api/databases/appdb",
"/api/databases/appdb/status",
] {
assert_eq!(
Right::required("GET", path),
Some(default_read.clone()),
"GET {path} must require Project·Read",
);
}
let publisher = policy.rights_for(&[GrantedRole::scoped("project_publisher", "default")]);
let admin = policy.rights_for(&[GrantedRole::scoped("project_admin", "default")]);
let put = Right::required("PUT", "/api/databases/appdb").unwrap();
let ensure = Right::required("POST", "/api/databases/appdb/ensure").unwrap();
for req in [&put, &ensure] {
assert!(
!publisher.allows(req),
"a project_publisher must NOT be able to declare/provision a database",
);
assert!(
admin.allows(req),
"a project_admin must be able to declare/provision a database",
);
}
// ---- Project-scoped form (a non-default tenant). ----
let acme_admin_right = Right::new(Resource::Project, Some("acme".into()), Action::Admin);
assert_eq!(
Right::required("PUT", "/api/projects/acme/databases/appdb"),
Some(acme_admin_right.clone()),
"PUT on acme's databases must require Project·Admin on acme",
);
assert_eq!(
Right::required("POST", "/api/projects/acme/databases/appdb/ensure"),
Some(acme_admin_right),
"POST ensure on acme's databases must require Project·Admin on acme",
);
let acme_put = Right::required("PUT", "/api/projects/acme/databases/appdb").unwrap();
let acme_pub = policy.rights_for(&[GrantedRole::scoped("project_publisher", "acme")]);
let acme_admin = policy.rights_for(&[GrantedRole::scoped("project_admin", "acme")]);
assert!(
!acme_pub.allows(&acme_put),
"a project_publisher on acme must NOT declare acme's databases",
);
assert!(
acme_admin.allows(&acme_put),
"a project_admin on acme must declare acme's databases",
);
// Cross-tenant: an acme admin grant does NOT satisfy declaring globex's databases.
let globex_put = Right::required("PUT", "/api/projects/globex/databases/appdb").unwrap();
assert!(
!acme_admin.allows(&globex_put),
"an acme grant must not reach globex's databases surface",
);
}
/// The operator S3 upload-credential mint surface (`POST /api/blob-mint-upload`, M3) must gate at
/// the DEDICATED `BlobUpload·Write` right — NOT the `Blobs·Deploy` grade the sibling `/api/blobs`
/// path grants (which a ship-only publisher holds). A publisher/deployer must be REFUSED; only an
/// `admin` (which expands to `BlobUpload` via `Resource::ALL`) reaches it.
#[test]
fn blob_mint_upload_surface_is_blobupload_write_not_publisher() {
// MEDIUM-1 (M3 security review): the route maps to BlobUpload·Write scoped to the PROJECT the
// path names — the global form to the default project, the project-scoped form to `<proj>` —
// mirroring the repair/migrate precedent, so a project-scoped grant can reach its OWN project.
assert_eq!(
Right::required("POST", "/api/blob-mint-upload"),
Some(Right::new(
Resource::BlobUpload,
Some(crate::project::DEFAULT_PROJECT.to_string()),
Action::Write
)),
"POST /api/blob-mint-upload must require BlobUpload·Write scoped to the default project",
);
assert_eq!(
Right::required("POST", "/api/projects/acme/blob-mint-upload"),
Some(Right::new(
Resource::BlobUpload,
Some("acme".to_string()),
Action::Write
)),
"POST /api/projects/acme/blob-mint-upload must require BlobUpload·Write scoped to acme",
);
let req = Right::required("POST", "/api/blob-mint-upload").unwrap();
let policy = AuthzPolicy::default_policy();
// The default content-shipping roles must NOT reach it (no escalation from Blobs·Deploy).
for role in ["publisher", "deployer"] {
let rights = policy.rights_for(&[GrantedRole::scoped(role, "acme/blog")]);
assert!(
!rights.allows(&req),
"a {role} must NOT be able to mint an upload credential (Blobs·Deploy is not BlobUpload)",
);
}
for role in ["project_publisher", "project_admin"] {
let rights = policy.rights_for(&[GrantedRole::scoped(role, "acme")]);
assert!(
!rights.allows(&req),
"a {role} must NOT expand to BlobUpload (it is admin/explicit-grant only)",
);
}
// An `admin` (via Resource::ALL) reaches it.
let admin = policy.rights_for(&[GrantedRole::global("admin")]);
assert!(
admin.allows(&req),
"an admin must be able to mint an upload credential",
);
}
/// MEDIUM-1 (M3 security review): a **project-scoped** `BlobUpload·Write` grant can mint for ITS
/// OWN project but NOT another's — the whole point of scoping the route to `Some(<project>)`
/// (the pre-fix global `None`-target made this impossible: only a global grant could ever mint,
/// so a per-project grant was dead). A global `BlobUpload·Write` / `admin` still reaches every
/// project; the default ship-only roles never reach any.
#[test]
fn blob_mint_upload_is_reachable_by_a_project_scoped_grant_for_its_own_project_only() {
let acme_mint = Right::required("POST", "/api/projects/acme/blob-mint-upload").unwrap();
let other_mint = Right::required("POST", "/api/projects/other/blob-mint-upload").unwrap();
// A `BlobUpload·Write` grant scoped to `acme` can mint for acme, but NOT for `other`.
let acme_grant: RightSet = std::iter::once(Right::new(
Resource::BlobUpload,
Some("acme".to_string()),
Action::Write,
))
.collect();
assert!(
acme_grant.allows(&acme_mint),
"a BlobUpload·Write grant scoped to acme must mint for acme",
);
assert!(
!acme_grant.allows(&other_mint),
"a BlobUpload·Write grant scoped to acme must NOT mint for a DIFFERENT project",
);
// A GLOBAL `BlobUpload·Write` grant (target None) reaches every project.
let global_grant: RightSet =
std::iter::once(Right::new(Resource::BlobUpload, None, Action::Write)).collect();
assert!(global_grant.allows(&acme_mint) && global_grant.allows(&other_mint));
// A global `admin` reaches every project (via Resource::ALL).
let policy = AuthzPolicy::default_policy();
let admin = policy.rights_for(&[GrantedRole::global("admin")]);
assert!(admin.allows(&acme_mint) && admin.allows(&other_mint));
// The default ship-only / project roles reach NEITHER project's mint surface.
for (role, target) in [
("publisher", "acme/blog"),
("deployer", "acme/blog"),
("project_publisher", "acme"),
("project_admin", "acme"),
] {
let rights = policy.rights_for(&[GrantedRole::scoped(role, target)]);
assert!(
!rights.allows(&acme_mint) && !rights.allows(&other_mint),
"a {role} must NOT reach any blob-mint-upload surface",
);
}
}
/// A function's captured-guest-logs endpoint is a project-owned READ — it reuses the
/// `/api/functions/*` mapping (no dedicated right), so a project token reaches only
/// its own functions' logs. Both the legacy default-project form and the
/// project-scoped form resolve to `Project·Read` on the right project.
#[test]
fn function_logs_are_a_project_read() {
// Legacy/default-project form.
assert_eq!(
Right::required("GET", "/api/functions/identity/_boatramp/logs"),
Some(Right::new(
Resource::Project,
Some("default".into()),
Action::Read
))
);
// Project-scoped form (the request the CLI sends under `--project acme`, before
// `project_scope` rewrites it).
assert_eq!(
Right::required(
"GET",
"/api/projects/acme/functions/identity/_boatramp/logs"
),
Some(Right::new(
Resource::Project,
Some("acme".into()),
Action::Read
))
);
// Multi-tenant boundary: an `acme` project grant does not satisfy reading
// `globex`'s function logs.
let acme_read = AuthzPolicy::default_policy()
.rights_for(&[GrantedRole::scoped("project_viewer", "acme")]);
let globex_fn_logs = Right::required(
"GET",
"/api/projects/globex/functions/identity/_boatramp/logs",
)
.expect("gated");
assert!(
!acme_read.allows(&globex_fn_logs),
"acme token must not read globex fn logs"
);
}
/// GATE (v0.7.4) — `GET /api/version` is an OPERATOR-only read, never a public/tenant surface.
/// The whole security value of the version endpoint is that a client cannot fingerprint the
/// release without an operator token. This asserts the load-bearing arm and is mutation-verified:
/// a regression that makes `/api/version` unauthenticated (`None`, like `/healthz`), or a
/// per-project/tenant right, or anything other than the `system·read` tier, turns it red.
#[test]
fn version_endpoint_is_operator_read_gated() {
let req = Right::required("GET", "/api/version");
// NOT unauthenticated — unlike `/healthz`/`/readyz`, the auth layer MUST demand a token.
assert!(
req.is_some(),
"GET /api/version must require a token (never the unauthenticated `None` path) — else it \
is a public release fingerprint",
);
let req = req.unwrap();
// Exactly the operator system·read tier — the SAME grade as `/api/metrics` / `/api/blob-status`,
// never a per-project right a tenant token could satisfy.
assert_eq!(
req,
Right::new(Resource::System, None, Action::Read),
"GET /api/version must be gated at system·read (operator-only, not tenant-scoped)",
);
assert_eq!(
Right::required("GET", "/api/version"),
Right::required("GET", "/api/metrics"),
"the version read must be the same grade as /api/metrics",
);
// A read tier: a system·read token reaches it, but it is NOT the mutating system·admin tier.
assert_ne!(
req,
Right::new(Resource::System, None, Action::Admin),
"the version READ must not require the mutating system·admin tier",
);
}
/// `GET /api/kv-status` (v0.9.0 KV-recovery, C6) is operator `system·read` — the SAME grade as
/// `/api/version` / `/api/blob-status`, never `None` (public) and never `system·admin`. A
/// regression to the deny-safe `_` default (system·admin) would lock a read-only operator out;
/// a regression to `None` would leak the degraded state publicly.
#[test]
fn kv_status_endpoint_is_operator_read_gated() {
let req = Right::required("GET", "/api/kv-status");
assert!(
req.is_some(),
"GET /api/kv-status must require a token (never the unauthenticated `None` path)"
);
assert_eq!(
req.unwrap(),
Right::new(Resource::System, None, Action::Read),
"GET /api/kv-status must be gated at system·read (operator-only, not tenant-scoped)"
);
assert_eq!(
Right::required("GET", "/api/kv-status"),
Right::required("GET", "/api/blob-status"),
"the kv-status read must be the same grade as /api/blob-status",
);
}
/// kv-sql WS7 — `GET /api/kv-export` and `POST /api/kv-import` are gated `System·Admin`
/// EXPLICITLY (node-global: the WHOLE control plane incl. sealed secrets). A NON-admin right —
/// `System·Read`, or ANY project-scoped right — must NOT satisfy them; a regression that made
/// either `None` (public) or a `Project` right (tenant-reachable) is what this gate catches.
#[test]
fn kv_export_import_require_system_admin() {
let admin = Right::new(Resource::System, None, Action::Admin);
for (method, path) in [("GET", "/api/kv-export"), ("POST", "/api/kv-import")] {
let req = Right::required(method, path)
.unwrap_or_else(|| panic!("{method} {path} must require a token (never public)"));
assert_eq!(
req, admin,
"{method} {path} must be gated System·Admin (node-global control-plane dump)"
);
// A read-only operator right must NOT satisfy it.
assert!(
!Right::new(Resource::System, None, Action::Read).satisfies(&req),
"System·Read must NOT satisfy the {path} System·Admin gate"
);
// A project-scoped admin right must NOT satisfy it (it is node-global, not per-project).
assert!(
!Right::new(Resource::Project, Some("acme".to_string()), Action::Admin)
.satisfies(&req),
"a project-scoped right must NOT satisfy the node-global {path} gate"
);
// And over the real default policy: NO ordinary tenant role (publisher/deployer/
// project_admin) is refused-not — none satisfies the dump gate; only `admin` reaches it.
let policy = AuthzPolicy::default_policy();
for grant in [
GrantedRole::scoped("publisher", "default/site"),
GrantedRole::scoped("deployer", "default/site"),
GrantedRole::scoped("project_admin", "default"),
] {
let role = grant.name.clone();
assert!(
!policy.rights_for(&[grant]).allows(&req),
"a non-admin principal (role {role}) must be REFUSED {path}"
);
}
assert!(
policy
.rights_for(&[GrantedRole::global("admin")])
.allows(&req),
"System·Admin (operator) must reach {path}"
);
}
}
}