boatramp-types 0.35.2

Shared, wasm-clean wire types + routing/config logic for boatramp (used by the server, CLI, and the edge Worker so the wire format and routing can't drift)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
//! Deploy-scoped configuration (the `routing` section of `project.cfg`).
//!
//! This is the **immutable, deploy-scoped** config tier: it is authored as the
//! `routing` section of `project.cfg`, parsed at `sync` time, and folded into
//! the deployment manifest (`boatramp_core::deploy::Manifest`).
//! Because it travels inside the manifest it is atomic with the content and
//! rolls back with it.
//!
//! (The mutable, site-scoped tier — domains, TLS, access control — is a separate
//! `SiteConfig` in the KV store, added alongside the virtualhost/auth work.)

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::error::ConfigError;
use crate::matcher::Pattern;

/// Deploy-scoped configuration — the `routing` section of `project.cfg`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DeployConfig {
    /// Schema version, pinned at [`crate::SCHEMA_VERSION`]. Optional in
    /// `project.cfg` routing (defaults to 1); always present once folded in.
    pub version: u32,
    /// Directory-index candidates, tried in order (default `["index.html"]`).
    pub index: Vec<String>,
    /// Map extensionless URLs to `.html` files (`/about` → `/about.html`).
    pub clean_urls: bool,
    /// Match the request path **case-insensitively** against redirects, rewrites,
    /// and static files (`/About.HTML` serves `/about.html`). Off by default
    /// (paths are case-sensitive); opt-in for case-folding origins.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub case_insensitive: bool,
    /// Trailing-slash policy.
    pub trailing_slash: TrailingSlash,
    /// Status code → error document (e.g. `404 → /404.html`).
    pub error_documents: BTreeMap<u16, String>,
    /// Redirect rules (first match wins).
    pub redirects: Vec<Redirect>,
    /// Rewrite rules (internal rewrite or proxy; first match wins).
    pub rewrites: Vec<Rewrite>,
    /// Response-header rules (all matching rules apply, in order).
    pub headers: Vec<HeaderRule>,
    /// Cache-Control defaults.
    pub cache: CacheConfig,
    /// Extension → MIME overrides (e.g. `.webmanifest`).
    pub mime_overrides: BTreeMap<String, String>,
    /// Allowed upstream hosts for proxy rewrites (exact host or `.suffix`
    /// match). When empty, proxying to any *public* host is allowed; private,
    /// loopback, link-local, and similar internal addresses are always blocked
    /// (SSRF guard), regardless of this list.
    pub proxy_allow: Vec<String>,
    /// WebAssembly request handlers (deploy-scoped).
    /// Matched before static lookup, after redirects.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub handlers: Vec<HandlerConfig>,
    /// Message-consumer components, invoked per message on a topic.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub consumers: Vec<ConsumerConfig>,
    /// Scheduled handler invocations (cron).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub crons: Vec<CronConfig>,
    /// Host-level SSE endpoints fanning out messaging topics.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub streams: Vec<StreamConfig>,
    /// Duplex/resumable session routes (`PLAN-session-primitive`): a guest `session-handler` the
    /// host re-enters per inbound frame, with host-owned ordering/resume/lifetime.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sessions: Vec<SessionConfig>,
}

impl Default for DeployConfig {
    fn default() -> Self {
        Self {
            version: crate::SCHEMA_VERSION,
            index: vec!["index.html".to_string()],
            clean_urls: false,
            case_insensitive: false,
            trailing_slash: TrailingSlash::default(),
            error_documents: BTreeMap::new(),
            redirects: Vec::new(),
            rewrites: Vec::new(),
            headers: Vec::new(),
            cache: CacheConfig::default(),
            mime_overrides: BTreeMap::new(),
            proxy_allow: Vec::new(),
            handlers: Vec::new(),
            consumers: Vec::new(),
            crons: Vec::new(),
            streams: Vec::new(),
            sessions: Vec::new(),
        }
    }
}

impl DeployConfig {
    /// Parse a deploy-scoped `routing` document (RON). `implicit_some` is enabled
    /// so optional fields can be written as bare values (not `Some("...")`).
    pub fn from_ron(text: &str) -> Result<Self, ConfigError> {
        let options = ron::Options::default()
            .with_default_extension(ron::extensions::Extensions::IMPLICIT_SOME);
        let config: Self = options
            .from_str(text)
            .map_err(|err| ConfigError::parse(err.to_string()))?;
        config.compile_check()?;
        Ok(config)
    }

    /// Whether `host` is permitted as a proxy-rewrite upstream by the
    /// `proxy_allow` list. An empty list permits any host (the separate
    /// public-IP SSRF guard still applies); otherwise the host must equal an
    /// entry or be a subdomain of a `.`-prefixed suffix entry.
    pub fn proxy_host_allowed(&self, host: &str) -> bool {
        if self.proxy_allow.is_empty() {
            return true;
        }
        let host = host.trim_end_matches('.').to_ascii_lowercase();
        self.proxy_allow.iter().any(|entry| {
            let entry = entry.trim().to_ascii_lowercase();
            match entry.strip_prefix('.') {
                Some(suffix) => host_matches_suffix(&host, suffix),
                None => host == entry,
            }
        })
    }

    /// Verify every route/header pattern compiles. Used by `from_ron` and the
    /// `validate` subcommand so bad patterns fail fast at deploy time.
    pub fn compile_check(&self) -> Result<(), ConfigError> {
        for redirect in &self.redirects {
            Pattern::compile(&redirect.from)?;
            if let Some(when) = &redirect.when {
                crate::predicate::Predicate::compile(when)?;
            }
            if crate::predicate::Template::is_template(&redirect.to) {
                crate::predicate::Template::compile(&redirect.to)?;
            }
        }
        for rewrite in &self.rewrites {
            Pattern::compile(&rewrite.from)?;
            if let Some(when) = &rewrite.when {
                crate::predicate::Predicate::compile(when)?;
            }
            if crate::predicate::Template::is_template(&rewrite.to) {
                crate::predicate::Template::compile(&rewrite.to)?;
            }
        }
        for header in &self.headers {
            Pattern::compile(&header.matches)?;
        }
        self.check_handlers()?;
        Ok(())
    }

    /// Offline validation of the handler/consumer/cron/stream config: route
    /// patterns compile, HTTP methods and requested imports are recognized,
    /// cron schedules parse, and every cron route is served by some declared
    /// handler. (Component *binary* validation happens at `sync`, where the
    /// `.wasm` bytes are available.)
    fn check_handlers(&self) -> Result<(), ConfigError> {
        let handler_patterns: Vec<Pattern> = self
            .handlers
            .iter()
            .map(|h| Pattern::compile(&h.route))
            .collect::<Result<_, _>>()?;

        for handler in &self.handlers {
            if handler.component.is_empty() {
                return Err(ConfigError::parse(format!(
                    "handler {} has an empty component path",
                    handler.route
                )));
            }
            for method in &handler.methods {
                check_http_method(method)?;
            }
            for import in &handler.imports {
                check_import(import)?;
            }
            // `env` is for static, non-secret strings; a secret belongs in
            // `[handlers].secrets` as a *reference* to a host env var, so it
            // never lands in the (content-addressed, stored) manifest.
            // Best-effort heuristic — catches accidents.
            for (key, value) in &handler.env {
                if looks_like_secret(value) {
                    return Err(ConfigError::parse(format!(
                        "handler {} env var {key:?} looks like a secret; move it to \
                         [handlers].secrets as a reference to a host env var rather than \
                         inlining it in `env` (which is stored in the manifest)",
                        handler.route
                    )));
                }
            }
        }
        for consumer in &self.consumers {
            if consumer.topic.is_empty() || consumer.component.is_empty() {
                return Err(ConfigError::parse(
                    "consumer needs a non-empty topic and component".to_string(),
                ));
            }
            for import in &consumer.imports {
                check_import(import)?;
            }
        }
        for cron in &self.crons {
            check_cron_schedule(&cron.schedule)?;
            if !handler_patterns.iter().any(|p| p.is_match(&cron.route)) {
                return Err(ConfigError::parse(format!(
                    "cron route {} is not served by any declared handler",
                    cron.route
                )));
            }
        }
        for stream in &self.streams {
            Pattern::compile(&stream.route)?;
            if stream.topics.is_empty() {
                return Err(ConfigError::parse(format!(
                    "stream {} subscribes to no topics",
                    stream.route
                )));
            }
        }
        for session in &self.sessions {
            Pattern::compile(&session.route)?;
            if session.component.is_empty() {
                return Err(ConfigError::parse(format!(
                    "session {} has an empty component path",
                    session.route
                )));
            }
            for import in &session.imports {
                check_import(import)?;
            }
        }
        Ok(())
    }
}

/// The standard interface vocabulary a handler may request.
/// `sql` is the one generic non-`wasi:` interface.
const KNOWN_IMPORTS: &[&str] = &[
    "sql",
    "invoke",
    "graphql",
    "email",
    "capability",
    "wasi:http",
    "wasi:io",
    "wasi:keyvalue",
    "wasi:blobstore",
    "wasi:messaging",
    "wasi:clocks",
    "wasi:random",
    "wasi:logging",
    // Outbound-TCP `connect` capability (`PLAN-handler-tcp-egress`). The socket host is always
    // linked and deny-by-default (`SocketAddrCheck::default()` rejects every target); granting it
    // here only lets a handler DECLARE it. Reaching anything additionally needs the posture flag
    // `allow_guest_tcp_egress` (off under `multi-tenant`) AND a non-empty per-handler
    // `egress_allowlist` — deny-by-default at every layer.
    "wasi:sockets",
    // Host-owned inbound-TCP **listener** capability (`PLAN-handler-tcp-inbound`). A listener's guest
    // EXPORTS `tcp-connection-handler` (and `use`s `tcp-connection-types`); granting it here only lets
    // a component DECLARE it. The host owns the socket and hands the guest only `wasi:io` streams — the
    // guest NEVER imports `wasi:sockets`. Reaching anything additionally needs the posture flag
    // `allow_guest_tcp_listener` (off under `multi-tenant`) AND an operator-declared
    // `[serve.listeners.<name>]` — deny-by-default at every layer. Advertised Experimental (not the
    // blanket-Stable KNOWN_IMPORTS lifecycle).
    "tcp-listener",
];

/// The import names a deploy may declare in a handler's `imports` (baseline WASI
/// interfaces + boatramp capability tokens). `sql:<name>`/`sql:*` are additionally
/// accepted for named databases (see [`is_named_sql_import`]).
pub fn known_imports() -> &'static [&'static str] {
    KNOWN_IMPORTS
}

/// Best-effort heuristic: does `value` look like a credential that should be a
/// `secrets` reference rather than a static `env` string?
/// Catches the common accidents — it is a guard, not a guarantee.
fn looks_like_secret(value: &str) -> bool {
    let v = value.trim();
    // A PEM private-key block.
    if v.contains("-----BEGIN") && v.contains("PRIVATE KEY") {
        return true;
    }
    // Well-known credential prefixes (cloud keys, VCS/chat/LLM tokens, …).
    const PREFIXES: &[&str] = &[
        "AKIA",
        "ASIA",
        "ghp_",
        "gho_",
        "ghu_",
        "ghs_",
        "github_pat_",
        "xoxb-",
        "xoxp-",
        "xoxa-",
        "glpat-",
        "AIza",
        "AccountKey=",
    ];
    if PREFIXES.iter().any(|p| v.contains(p)) {
        return true;
    }
    let has_digit = v.bytes().any(|b| b.is_ascii_digit());
    // A long pure-hex blob (API key / hash-shaped secret).
    if v.len() >= 40 && has_digit && v.bytes().all(|b| b.is_ascii_hexdigit()) {
        return true;
    }
    // A long, mixed-case, token-charset, high-entropy string (base64-ish key).
    let charset_ok = v
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'-' | b'_'));
    let mixed_case =
        v.bytes().any(|b| b.is_ascii_uppercase()) && v.bytes().any(|b| b.is_ascii_lowercase());
    v.len() >= 32 && charset_ok && has_digit && mixed_case && shannon_entropy_bits(v) >= 3.5
}

/// Shannon entropy of `s` in bits per character (0 for empty).
fn shannon_entropy_bits(s: &str) -> f64 {
    if s.is_empty() {
        return 0.0;
    }
    let mut counts = [0u32; 256];
    for b in s.bytes() {
        counts[b as usize] += 1;
    }
    let len = s.len() as f64;
    counts
        .iter()
        .filter(|&&c| c > 0)
        .map(|&c| {
            let p = c as f64 / len;
            -p * p.log2()
        })
        .sum()
}

/// Whether `import` is a **named SQL binding** grant: `sql:<name>` (a specific database) or
/// `sql:*` (every named database the site exposes). The bare `sql` (in `KNOWN_IMPORTS`) remains
/// the default database. A name is a conservative identifier so it can't smuggle a path or
/// injection through `sql.open(name)`.
fn is_named_sql_import(import: &str) -> bool {
    let Some(name) = import.strip_prefix("sql:") else {
        return false;
    };
    name == "*"
        || (!name.is_empty()
            && name
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))
}

/// Whether `import` is a **guest project-admin surface** grant: `admin:<surface>` for one of
/// the config surfaces the `boatramp:handlers/admin` capability exposes. A bare `admin` is
/// deliberately NOT a grant — a guest must name the specific surface (deny-by-default,
/// least-privilege), and there is no `admin:*`. The surface set is closed; a new surface is an
/// explicit addition here + in the host.
pub fn is_named_admin_import(import: &str) -> bool {
    matches!(
        import,
        "admin:domains" | "admin:email" | "admin:site" | "admin:secrets"
    )
}

/// Whether `import` is a **per-tenant sealed-secret** grant (task #493): `tenant-secrets:read`
/// (grants the guest `get`/`list` on the `boatramp:handlers/tenant-secrets` capability) or
/// `tenant-secrets:admin` (grants `set`/`delete`). The two are INDEPENDENT rights, each separate
/// from the deploy/publisher right and from each other — a read-granted component cannot write. A
/// bare `tenant-secrets` is deliberately NOT a grant (a component must name the specific right,
/// deny-by-default / least-privilege), and there is no `tenant-secrets:*`. A typo (e.g.
/// `tenant-secrets:write`) is not recognized here and so fails at deploy.
pub fn is_named_tenant_secrets_import(import: &str) -> bool {
    matches!(import, "tenant-secrets:read" | "tenant-secrets:admin")
}

/// Whether `import` is a **blob-upload mint** grant (S3 external ingress): `blob-upload:write`
/// (grants a single-shot presigned `PutObject`) or `blob-upload:multipart` (grants the resumable
/// multipart quartet) on the `boatramp:handlers/blob-upload` capability. The two are INDEPENDENT
/// rights, each separate from the deploy/publisher right and from each other — a write-granted
/// component cannot mint a multipart credential. A bare `blob-upload` is deliberately NOT a grant (a
/// component must name the specific right, deny-by-default / least-privilege), and there is no
/// `blob-upload:*`. A typo (e.g. `blob-upload:read`) is not recognized here and so fails at deploy.
/// Parse-time recognition ONLY: the ABI/`requires` gate + the runtime allowlist still enforce host
/// support + the grant at activation.
pub fn is_named_blob_upload_import(import: &str) -> bool {
    matches!(import, "blob-upload:write" | "blob-upload:multipart")
}

fn check_import(import: &str) -> Result<(), ConfigError> {
    // `session` is accepted here (client-side cfg vocabulary) but is intentionally NOT in
    // `KNOWN_IMPORTS`: a session route grants the session binding intrinsically, and the host
    // advertises `session` as an Experimental capability only when the `session` feature is
    // compiled — so the ABI gate (a component's `requires = ["session"]` vs the host's advertised
    // set) enforces host support at activation, while this keeps `imports: ["session"]` from being
    // rejected offline regardless of which host build the deploy targets.
    // `tenancy` (Gap 3 `present-token`) is accepted here but, like `session`, intentionally NOT in
    // `KNOWN_IMPORTS`: the host advertises it as Experimental only when the `messaging` feature is
    // compiled, so the `requires` ABI gate enforces host support at activation while a deploy
    // targeting any host build still parses offline.
    // `messaging-stats` (read-only per-topic bus gauges) is accepted here but, like `session` and
    // `tenancy`, intentionally NOT in `KNOWN_IMPORTS`: the host advertises it as Experimental only
    // when the `messaging` feature is compiled, so the `requires` ABI gate enforces host support at
    // activation while a deploy targeting any host build still parses offline.
    // `tenant-secrets:{read,admin}` (per-tenant sealed-secret CRUD, task #493) are accepted here but,
    // like the above, intentionally NOT in `KNOWN_IMPORTS`: the host advertises the capability as
    // Experimental only when the `tenant-secrets` feature is compiled, so the `requires` ABI gate
    // enforces host support at activation while a deploy targeting any host build still parses offline.
    // `blob-upload:{write,multipart}` (S3-ingress upload-credential mint) are accepted here but, like
    // the above, intentionally NOT in `KNOWN_IMPORTS`: the host advertises the capability as
    // Experimental only when the `blob-upload` feature is compiled, so the `requires` ABI gate enforces
    // host support at activation while a deploy targeting any host build still parses offline.
    if KNOWN_IMPORTS.contains(&import)
        || import == "session"
        || import == "tenancy"
        || import == "messaging-stats"
        || is_named_sql_import(import)
        || is_named_admin_import(import)
        || is_named_tenant_secrets_import(import)
        || is_named_blob_upload_import(import)
    {
        Ok(())
    } else {
        Err(ConfigError::parse(format!(
            "unknown handler import {import:?}; allowed: {}, `session`, `tenancy`, `messaging-stats`, a named SQL binding `sql:<name>` / `sql:*`, an admin surface `admin:{{domains,email,site,secrets}}`, a tenant-secret right `tenant-secrets:{{read,admin}}`, or a blob-upload right `blob-upload:{{write,multipart}}`",
            KNOWN_IMPORTS.join(", ")
        )))
    }
}

/// The canonical standard HTTP verbs. Each is also a valid RFC 7230 `token`; they are
/// named explicitly so routing can treat these (and only these) case-insensitively — a
/// wire `post` still answers a declared `POST` — while an extension verb is matched
/// exactly. See [`crate::route::method_matches`].
pub(crate) const STANDARD_METHODS: &[&str] =
    &["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];

/// The explicit per-route catch-all sentinel: a route whose `methods` contains `"*"`
/// answers EVERY method. `*` is itself a valid RFC 7230 `tchar`, but no real HTTP method
/// is named `*`, so treating a declared `*` as the wildcard is unambiguous — and it is
/// opt-in per route, never an implicit broadening of any other route's method set.
pub(crate) const METHOD_WILDCARD: &str = "*";

/// RFC 7230 `tchar`: the characters allowed in a `token` (hence in an HTTP method).
/// `tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^" / "_" /
/// "`" / "|" / "~" / DIGIT / ALPHA`.
fn is_tchar(b: u8) -> bool {
    b.is_ascii_alphanumeric()
        || matches!(
            b,
            b'!' | b'#'
                | b'$'
                | b'%'
                | b'&'
                | b'\''
                | b'*'
                | b'+'
                | b'-'
                | b'.'
                | b'^'
                | b'_'
                | b'`'
                | b'|'
                | b'~'
        )
}

/// Whether `method` is a valid RFC 7230 `method` = `token` = `1*tchar`. Rejects the empty
/// string and anything carrying a space, CTL, CR/LF, DEL or a separator — so a method
/// token can never carry whitespace or a second request line (no request-smuggling /
/// header-injection via the method string).
fn is_http_method_token(method: &str) -> bool {
    !method.is_empty() && method.bytes().all(is_tchar)
}

/// Validate a configured route method: any valid RFC 7230 `token`. This admits the
/// standard verbs, the explicit `*` catch-all (`*` is a `tchar`), and extension verbs —
/// PROPFIND, PROPPATCH, REPORT, MKCALENDAR, MKCOL, MOVE, COPY, … — so a WebDAV / CalDAV
/// (RFC 4791) / CardDAV (RFC 6352) handler can be routed. Anything that is not a `token`
/// (a space, CTL, CR/LF, or separator) is rejected, so the method string cannot be an
/// injection vector. The wildcard/extension-match SEMANTICS live in routing
/// ([`crate::route::method_matches`]); this is purely the parse-time token gate.
fn check_http_method(method: &str) -> Result<(), ConfigError> {
    // Anti-hollow gate hook: `admit_nontoken` drops the token guard so the CI gate can prove
    // the guard is load-bearing (RED when a garbage method is wrongly accepted). Dead `None` —
    // and so a dead branch — in a shipped build.
    if extmethod_gate_mutation().as_deref() == Some("admit_nontoken") {
        return Ok(());
    }
    if is_http_method_token(method) {
        Ok(())
    } else {
        Err(ConfigError::parse(format!(
            "invalid HTTP method {method:?}: expected a standard verb, the `*` catch-all, or a \
             valid RFC 7230 token (an extension verb such as PROPFIND)"
        )))
    }
}

// Defense-in-depth: the ext-method routing anti-hollow seam is for `cargo test` only. Fail the build
// loudly if the gate feature is ever enabled in a non-test RELEASE profile (scoped to THIS seam).
#[cfg(all(feature = "extmethod-gate-mutation", not(test), not(debug_assertions)))]
compile_error!(
    "extmethod-gate-mutation is a test-only anti-hollow seam and must never be compiled into a \
     release build — remove it from the feature set"
);

/// The active ext-method routing/validation gate mutation (anti-hollow CI gate), or `None`. Present
/// ONLY under `cfg(test)` or the `extmethod-gate-mutation` feature; a shipped build has neither, so
/// both [`check_http_method`]'s token guard and [`crate::route::method_matches`]'s wildcard/extension
/// arms are unconditional and this is a dead `None`. Each recognized value neuters ONE property so the
/// CI gate can prove it goes RED: `admit_nontoken` (validation accepts a non-token method),
/// `drop_wildcard` (the `*` catch-all stops matching), `drop_ext_match` (a declared extension verb
/// stops matching). NOT a backdoor — it only reads a test env var.
#[cfg(any(test, feature = "extmethod-gate-mutation"))]
pub(crate) fn extmethod_gate_mutation() -> Option<String> {
    std::env::var("BOATRAMP_EXTMETHOD_MUTATION").ok()
}
#[cfg(not(any(test, feature = "extmethod-gate-mutation")))]
#[inline]
pub(crate) fn extmethod_gate_mutation() -> Option<String> {
    None
}

/// Validate a standard 5-field cron schedule (`minute hour dom month dow`).
/// Each field is `*`, `*/step`, a number, an `a-b` range, an `a-b/step`, or a
/// comma list of those, within the field's numeric bounds.
fn check_cron_schedule(schedule: &str) -> Result<(), ConfigError> {
    // Validation = parsing the schedule (the same parser the scheduler uses to
    // evaluate it — one grammar, no drift).
    crate::cron::CronSchedule::parse(schedule)
        .map(|_| ())
        .map_err(|err| ConfigError::parse(format!("cron schedule {schedule:?}: {err}")))
}

/// Trailing-slash handling for request paths.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum TrailingSlash {
    /// Leave the path as-is.
    #[default]
    Preserve,
    /// Redirect to add a trailing slash.
    Always,
    /// Redirect to strip a trailing slash.
    Never,
}

/// A redirect rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Redirect {
    /// Source pattern (see [`crate::matcher`]).
    pub from: String,
    /// Destination, with `:name`/`:splat` substitution.
    pub to: String,
    /// HTTP status (default 308 — permanent, method-preserving).
    #[serde(default = "default_redirect_status")]
    pub status: u16,
    /// Optional server-side condition (a [`crate::predicate`] expression over the
    /// request — `Accept-Language`, cookies, headers, `file_exists(...)`, …). When
    /// set, the rule fires only if it evaluates true. Compiled + type-checked at
    /// `validate`/`sync`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when: Option<String>,
}

fn default_redirect_status() -> u16 {
    308
}

/// A rewrite rule: serve a different path (internal) or proxy (absolute URL).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rewrite {
    /// Source pattern.
    pub from: String,
    /// Internal path or absolute proxy URL, with `:name`/`:splat` substitution.
    pub to: String,
    /// Status to serve for an internal rewrite (default 200).
    #[serde(default = "default_rewrite_status")]
    pub status: u16,
    /// Optional server-side condition — see [`Redirect::when`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when: Option<String>,
}

fn default_rewrite_status() -> u16 {
    200
}

/// A response-header rule applied to matching paths.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HeaderRule {
    /// Path pattern to match (named `matches` because `for` is a Rust keyword).
    pub matches: String,
    /// Headers to set.
    #[serde(default)]
    pub set: BTreeMap<String, String>,
    /// Header names to remove.
    #[serde(default)]
    pub unset: Vec<String>,
}

/// Cache-Control defaults.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CacheConfig {
    /// Default `Cache-Control` for responses not covered by a header rule.
    pub default: Option<String>,
}

/// A WebAssembly request handler bound to a route (deploy-scoped).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HandlerConfig {
    /// Route pattern (matcher syntax).
    pub route: String,
    /// HTTP methods this handler answers (empty = all).
    #[serde(default)]
    pub methods: Vec<String>,
    /// Path to the component `.wasm` within the deployment.
    pub component: String,
    /// Requested capabilities (interface names; see `KNOWN_IMPORTS`).
    #[serde(default)]
    pub imports: Vec<String>,
    /// A **streaming** handler: the guest writes its response body incrementally
    /// (SSE, chunked, agent token streaming) via a `#[handler(stream)]` body. The
    /// host serves it on the isolated **streaming lane** (its own concurrency
    /// budget + a much larger wall-clock) so a long-lived stream never holds a
    /// fast-request slot. Should match the guest's declared shape — the activation
    /// pre-check *warns* when a `#[handler(stream)]` guest is deployed without it
    /// (it would otherwise run on the sync lane and be cut at the sync timeout).
    /// Default `false` (a buffered handler).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub streaming: bool,
    /// Optional resource limits (capped by site config at activation).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limits: Option<HandlerLimits>,
    /// Static environment variables (never secrets).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
    /// Per-guest **secret allowlist** (task #492): the subset of the site
    /// `[handlers].secrets` pool KEYS (env-var names) this handler is granted at
    /// instantiation. Empty ⇒ inject the whole site pool (the default, non-breaking);
    /// non-empty ⇒ inject **only** these keys (least-privilege opt-in), so one site's
    /// handlers no longer all share the same secret env. Every entry must be a key of
    /// the site `[handlers].secrets` map (an unknown name is a hard activation error —
    /// typo/rot protection). Only the site pool is filtered; a handler's own static
    /// `env` is unaffected.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub secrets: Vec<String>,
    /// Resolve **NO** site secrets for this handler (least-privilege opt-out). The `secrets`
    /// allowlist above can scope DOWN to a subset, but an *empty* allowlist means "the whole site
    /// pool" (the non-breaking #492 default), so there was no way to say "none". A blob/image serve
    /// route on a secret-heavy site (e.g. construens `/img` on a site that declares ~18 IDP/OAuth
    /// secrets site-wide) reads none of them, yet paid to resolve + unseal all of them on every serve
    /// (image-serve-latency Ask B-3). Set `no_secrets: true` so `resolve_env` skips the site pool
    /// entirely for this handler — it then touches the secret store zero times per serve. The
    /// handler's own static `env` is unaffected. Default `false` (unchanged behavior). Mutually
    /// exclusive with a non-empty `secrets` allowlist (declaring both is an activation error).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub no_secrets: bool,
    /// Function-to-function invoke allowlist (FI): the target names this handler may
    /// call through the `invoke` capability (same contract as
    /// [`FunctionConfig::invoke_targets`](crate::function::FunctionConfig)). Each entry
    /// may use `*` wildcards (`*` = any function, `img-*` = a family, `resize` = one
    /// literal). Deny by default: empty ⇒ the handler cannot invoke anything, even if it
    /// imports `invoke`. Only consulted when `imports` contains `invoke` and the site's
    /// `allow_imports` permits it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub invoke_targets: Vec<String>,
    /// Declared `bus:` stats-topic templates for the read-only `messaging-stats` capability. Each is
    /// a `bus:`-relative topic that may contain a literal `{tenant}` placeholder the HOST fills with
    /// this invocation's resolved tenant (e.g. `sync/{tenant}/import`). A guest's `messaging-stats`
    /// call for a `bus:` topic must name one of these verbatim; the host substitutes the tenant, so
    /// the guest can never read another tenant's bus stats. Deny by default: empty ⇒ no bus stats
    /// readable (a plain private-namespace topic never needs a template). Only consulted when
    /// `imports` contains `messaging-stats` and the site allows it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stats_topics: Vec<String>,
    /// Per-component name allowlist for the per-tenant sealed-secret capability
    /// (`boatramp:handlers/tenant-secrets`, task #493): the secret names this component may address
    /// for its resolved tenant. Least-privilege, mirroring [`stats_topics`](Self::stats_topics):
    /// **empty ⇒ deny-all** (a component that declares `tenant-secrets:{read,admin}` but names no
    /// secrets can reach nothing). A `get`/`set`/`delete` of a name NOT in this list returns
    /// `access-denied` (before any store access); a `list` returns only the allowlisted names. The
    /// resolved tenant is always host-supplied — this bounds only WHICH names, never WHICH tenant.
    /// Only consulted when `imports` contains a `tenant-secrets:*` right and the site allows it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tenant_secret_names: Vec<String>,
    /// Per-component container allowlist for the guest blob-upload mint capability
    /// (`boatramp:handlers/blob-upload`, S3 external ingress): the blob containers this component may
    /// mint an upload credential for. Least-privilege, mirroring
    /// [`tenant_secret_names`](Self::tenant_secret_names): **empty ⇒ deny-all** (a component that
    /// declares `blob-upload:{write,multipart}` but names no containers can mint nothing). A `mint`
    /// naming a container NOT in this list returns `access-denied` (before any signing). The project +
    /// site are always host-forced from the resolved invocation scope — this bounds only WHICH
    /// container, never WHICH project/site. Only consulted when `imports` contains a `blob-upload:*`
    /// right and the site allows it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub upload_containers: Vec<String>,
    /// Per-component container allowlist for the **plain `wasi:blobstore`** capability
    /// (host-enforced tenant confinement). SEPARATE from [`upload_containers`](Self::upload_containers)
    /// (which gates the `blob-upload` MINT capability) — there is **no inheritance or fallback**
    /// between the two. Each entry is `{tenant}`-templated: an entry containing `{tenant}` is expanded
    /// with THIS invocation's host-resolved OWN tenant (never guest-supplied) before an exact match
    /// against the container the guest opens (`get-container`/`create-container`/…), so a
    /// `["assets-{tenant}"]` handler can only ever reach `assets-<own-tid>`. A plain entry (no
    /// `{tenant}`, e.g. `"shared"`) is a site-shared container the operator opts into.
    ///
    /// Behavior when **empty** depends on whether the site is multi-tenant (i.e. declares a tenancy,
    /// the same fact that scopes `sql`/`orm`): a **multi-tenant** site that grants `wasi:blobstore`
    /// but names no `blobstore_containers` **denies** every container op (fail-closed — add the
    /// one-line `blobstore_containers: ["assets-{tenant}"]`); a **single-tenant/dev** site with no
    /// tenancy stays permissive (today's behavior). Only consulted when `imports` contains
    /// `wasi:blobstore` and the site allows it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub blobstore_containers: Vec<String>,
    /// Per-handler **outbound-TCP allowlist** for the gated `wasi:sockets` capability
    /// (`PLAN-handler-tcp-egress`): the `host:port` / `ip:port` / `CIDR:port` targets this handler
    /// may `connect` to. Least-privilege, mirroring [`upload_containers`](Self::upload_containers):
    /// **empty ⇒ deny-all** (a handler that imports `wasi:sockets` but names no targets can reach
    /// nothing). A domain entry (`db.internal:5432`) is resolved host-side and matched against the
    /// resolved peer IP; an `ip:port` / `CIDR:port` entry (`10.0.0.5:5432`, `10.0.0.0/8:5432`) is
    /// matched structurally. The gate is `connect`-only (never `bind`/`listen`), and even an
    /// allowlisted target is still held to the `is_global_ip` SSRF floor unless the posture also
    /// allows private egress. Only consulted when `imports` contains `wasi:sockets` AND the node
    /// posture [`allow_guest_tcp_egress`](crate::security::SecurityPosture::allow_guest_tcp_egress)
    /// is on — with the posture off the RUNTIME denies all (the socket host's deny-all default
    /// stands; the engine never installs a permissive check). In this stage the capability is NOT
    /// refused at deploy: a deploy declaring `wasi:sockets` parses and activates regardless of
    /// posture, so the gate is purely runtime (fail-closed). Host config on the deploy record, never
    /// guest-supplied at runtime.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub egress_allowlist: Vec<String>,
    /// Per-handler in-site tenancy decision (Dimension 0), overriding the site-level
    /// [`HandlersSiteConfig::tenancy`] for this route. Absent ⇒ inherit the site decision. When
    /// present it must **narrow within** the site ceiling ([`crate::tenancy::Tenancy::narrows_within`])
    /// — a widening is refused fail-closed at bind. Lets one site host handlers at different modes
    /// (e.g. an `own` page handler beside an `all` admin handler under a site ceiling of `all`).
    ///
    /// A route may deliberately EXCEED the site ceiling (task #470) via
    /// [`Tenancy::Scoped::exceed_site_ceiling`](crate::tenancy::Tenancy::Scoped) — but only when the
    /// site has also set [`HandlersSiteConfig::allow_ceiling_exceptions`], and only a scoped
    /// read/write widening on the same tenant column (an `all` grant still needs the operator posture
    /// at runtime). This is the authorized, greppable way to run an unscoped `all` route (e.g. an M2M
    /// `/token`) under an otherwise `own`-ceilinged site.
    #[serde(
        default,
        deserialize_with = "crate::tenancy::de_opt_tenancy",
        skip_serializing_if = "Option::is_none"
    )]
    pub tenancy: Option<crate::tenancy::Tenancy>,
    /// Per-handler JWKS/issuer config verifying the app bearer for a
    /// [`crate::tenancy::TenantSource::Token`] tenant source, overriding the site's
    /// `[handlers.graphql.data].claims_from_token`. Absent ⇒ inherit the site's. Only consulted when
    /// this handler's `tenancy` (or the inherited site tenancy) names a `token` source.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_claims: Option<HandlerGraphqlTokenClaims>,
}

/// Per-handler resource limits.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HandlerLimits {
    /// Max linear memory, MiB.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory_mb: Option<u32>,
    /// Wall-clock timeout, milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u32>,
    /// CPU budget in wasmtime **fuel** units (instruction-count proxy); the
    /// guest traps when it runs out. A deterministic CPU bound on top of the
    /// wall-clock timeout. Omitted = unmetered.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fuel: Option<u64>,
}

/// Where a **new** consumer group starts consuming a topic (its initial cursor).
/// A group with no `group` name is the default work-queue and ignores this.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StartPosition {
    /// Only events published from the group's first subscription onward (the
    /// conventional default; prior history is not replayed).
    #[default]
    Latest,
    /// Every event still retained on the topic, oldest-first (replay the backlog).
    Earliest,
}

/// A message-consumer component, invoked per message on a topic.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConsumerConfig {
    /// Topic to subscribe to (namespaced like all topics).
    pub topic: String,
    /// Path to the component `.wasm` within the deployment.
    pub component: String,
    /// Requested capabilities.
    #[serde(default)]
    pub imports: Vec<String>,
    /// Consumer **group**: empty (default) = the competing-consumer work-queue
    /// (one of the site's consumers processes each message); a non-empty name = a
    /// durable fan-out subscriber that receives *every* message on the topic
    /// independently of other groups. Two consumers with different groups on one
    /// topic each get every message.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub group: String,
    /// Where a non-empty `group` starts on first subscription (`latest` |
    /// `earliest`). Ignored for the default work-queue.
    #[serde(default, skip_serializing_if = "crate::config::is_default_start")]
    pub start: StartPosition,
    /// In-site tenancy decision (Dimension 0) for this consumer's `sql`/`orm` when a drained
    /// message is processed. The async-lane analog of a function's tenancy: typically
    /// `Scoped { sources: [signed_context], .. }` so the consumer resolves the tenant the producer
    /// stamped on the message. Absent ⇒ *undeclared* (refused under `multi-tenant`, `Disabled`
    /// under single-tenant/dev).
    #[serde(
        default,
        deserialize_with = "crate::tenancy::de_opt_tenancy",
        skip_serializing_if = "Option::is_none"
    )]
    pub tenancy: Option<crate::tenancy::Tenancy>,
    /// JWKS/issuer config verifying an app bearer for a [`crate::tenancy::TenantSource::Token`]
    /// tenant source (rare on the async lane, but supported for a consumer invoked with a
    /// forwarded bearer). Absent ⇒ the token source can't verify (fail-closed).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_claims: Option<HandlerGraphqlTokenClaims>,
    /// Per-guest **secret allowlist** (task #492), identical contract to
    /// [`HandlerConfig::secrets`]: the subset of the site `[handlers].secrets` pool KEYS
    /// this consumer is granted. Empty ⇒ inject the whole site pool (default,
    /// non-breaking); non-empty ⇒ inject **only** these keys (least-privilege opt-in).
    /// Every entry must be a key of the site pool (an unknown name is a hard activation
    /// error).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub secrets: Vec<String>,
    /// Per-consumer redelivery **visibility timeout** in ms (≈ JetStream *AckWait*): how long a
    /// claimed-but-unacked message stays leased before redelivery. `None` ⇒ the server default
    /// (30 s). A short lease suits fast retry/DLQ; a long one suits big-blob work — one global
    /// constant can't serve both. (JetStream-per-consumer-config parity, P1.)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lease_ms: Option<u64>,
    /// Per-consumer **max delivery attempts** before a message is dead-lettered (≈ JetStream
    /// *MaxDeliver*). `None` ⇒ the server default (5).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_attempts: Option<u32>,
    /// Per-consumer **max messages claimed per tick** (the pull batch size). `None` ⇒ the server
    /// default (16). Bounds the consumer's in-flight window per dispatch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_batch: Option<usize>,
    /// Per-consumer **MaxAckPending** — the most leased-but-unacked messages this consumer may hold
    /// at once, ACROSS ticks (≈ JetStream *MaxAckPending*). Back-pressure for a slow consumer: the
    /// dispatcher claims only up to `max_ack_pending − current_in_flight` each tick, and nothing while
    /// already at the cap. `None` ⇒ unbounded (only `max_batch` per-tick bounds it). (P2 flow control.)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_ack_pending: Option<usize>,
    /// Per-consumer **max concurrency** — the most invocations of THIS consumer that may run at once
    /// across the node, independent of (and clamped by) the shared async-lane budget
    /// (`[handlers] async_max_concurrency`). `None` ⇒ the consumer shares the single lane budget with
    /// every other consumer, exactly as today (no regression). Set it to stop one consumer's burst
    /// (e.g. a 2000-image thumbnail backfill) from monopolizing the lane and starving latency-
    /// sensitive consumers (concept-gen, polish): the effective cap is
    /// `min(max_concurrency, async_max_concurrency)` — a value above the lane clamps down, a `0` is
    /// treated as unset. Purely an admission-control split: ordering, at-least-once, and retry
    /// semantics are unchanged. (P2 resource isolation.)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_concurrency: Option<usize>,
    /// Per-consumer **redelivery backoff** in ms (≈ JetStream *BackOff*). On a failed delivery
    /// (an explicit nack before `max_attempts`), the message is held invisible for
    /// `backoff_ms × attempts` before it can be redelivered — a linear escalation that spaces out
    /// retries of a persistently-failing message instead of hot-looping it. `None`/`0` ⇒ immediate
    /// redelivery (the historical behavior). Bounded by `lease_ms`-style visibility; a crash without
    /// a nack still redelivers on lease expiry (backoff applies only to explicit nacks). (P1.)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backoff_ms: Option<u64>,
    /// Per-consumer **retention** in ms for a grouped topic's retained log/payload (≈ JetStream
    /// stream *MaxAge*) — how long a fan-out message is kept for slow/absent groups before the
    /// retention sweep reclaims it. `None` ⇒ the server default (24 h). Only meaningful for a
    /// grouped consumer (the work-queue deletes on ack); a shorter value caps storage for a
    /// high-volume bus, a longer one tolerates a slower group. (P1.)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retention_ms: Option<u64>,
    /// Declared `bus:` stats-topic templates for the read-only `messaging-stats` capability (same
    /// contract as [`HandlerConfig::stats_topics`]): a `bus:`-relative topic with an optional literal
    /// `{tenant}` placeholder the host fills with the consumer's resolved tenant. A common shape for a
    /// consumer that also wants to observe its own bus DLQ depth. Deny by default: empty ⇒ no bus
    /// stats. Only consulted when `imports` contains `messaging-stats` and the site allows it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stats_topics: Vec<String>,
    /// Per-component tenant-secret name allowlist (same contract as
    /// [`HandlerConfig::tenant_secret_names`]): the secret names this consumer may address for its
    /// resolved tenant via `boatramp:handlers/tenant-secrets`. Empty ⇒ deny-all.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tenant_secret_names: Vec<String>,
    /// Per-component container allowlist for the guest blob-upload mint capability (same contract as
    /// [`HandlerConfig::upload_containers`]): the blob containers this consumer may mint an upload
    /// credential for via `boatramp:handlers/blob-upload`. Empty ⇒ deny-all. Project + site are always
    /// host-forced from the resolved invocation scope.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub upload_containers: Vec<String>,
    /// Per-component container allowlist for the **plain `wasi:blobstore`** capability (host-enforced
    /// tenant confinement; same contract as [`HandlerConfig::blobstore_containers`]): the blob
    /// containers this consumer may open, `{tenant}`-templated against its host-resolved OWN tenant.
    /// SEPARATE from [`upload_containers`](Self::upload_containers) — no inheritance/fallback. Empty
    /// on a multi-tenant consumer ⇒ deny-all (fail-closed); empty single-tenant ⇒ permissive.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub blobstore_containers: Vec<String>,
    /// Per-component **outbound-TCP allowlist** for the gated `wasi:sockets` capability (same
    /// contract as [`HandlerConfig::egress_allowlist`]): the `host:port` / `ip:port` / `CIDR:port`
    /// targets this consumer may `connect` to. **Empty ⇒ deny-all.** `connect`-only, posture-gated
    /// (`allow_guest_tcp_egress`), SSRF-floored.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub egress_allowlist: Vec<String>,
}

/// serde `skip_serializing_if` helper: a `Latest` start is the default and elided.
pub fn is_default_start(s: &StartPosition) -> bool {
    *s == StartPosition::default()
}

/// A scheduled invocation of a declared handler route.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CronConfig {
    /// Standard 5-field cron schedule.
    pub schedule: String,
    /// Handler route to invoke (must be served by a declared handler).
    pub route: String,
    /// Overlap policy when a previous run is still in flight.
    #[serde(default)]
    pub overlap: Overlap,
    /// Which principal this cron fires as (PLAN-system-principal P2). Default
    /// [`CronRunAs::Unauthenticated`] — today's behavior, an anonymous trigger with no principal.
    /// [`CronRunAs::Deployer`] fires as the class captured from the VERIFIED ACTIVATOR at ACTIVATION
    /// time (stored server-side, per-(project, site), in the `current-principal/<site>` record bound to
    /// the activated deployment id — NOT the global content-addressed deploy metadata, and never
    /// client-supplied): an activator who held the node-global `System·Admin` right ⇒ the system
    /// principal (base-row writes + a system `signed_context` on `emit`), which is how a self-service
    /// cron producer stamps a resolvable context for its downstream consumer. A `deployer` cron whose
    /// site's current deployment was NOT activated by a System·Admin is **refused at fire time** (fail
    /// closed) — a deploy identity carries no in-site tenant, so there is no tenant for it to run as.
    #[serde(default, skip_serializing_if = "CronRunAs::is_default")]
    pub run_as: CronRunAs,
}

/// Cron overlap policy.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Overlap {
    /// Skip the tick if the previous invocation is still running (default).
    #[default]
    Skip,
    /// Allow concurrent invocations.
    Allow,
}

/// Which principal a [`CronConfig`] fires as (PLAN-system-principal P2).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CronRunAs {
    /// Anonymous trigger, no principal (today's behavior; an `own`-scoped handler fails closed).
    #[default]
    Unauthenticated,
    /// Fire as the VERIFIED deployer's captured principal — honored only when that principal is the
    /// system class (a `System·Admin` deployer); refused at fire time otherwise.
    Deployer,
}

impl CronRunAs {
    /// Whether this is the default ([`Unauthenticated`](Self::Unauthenticated)) — for
    /// `skip_serializing_if`, so a pre-P2 config round-trips byte-identically.
    #[must_use]
    pub fn is_default(&self) -> bool {
        matches!(self, Self::Unauthenticated)
    }
}

/// A host-level SSE (or WebSocket) endpoint fanning out messaging topics.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StreamConfig {
    /// Route the SSE (or WebSocket) endpoint is served at.
    pub route: String,
    /// Topics whose messages are broadcast to connected clients (server→client).
    pub topics: Vec<String>,
    /// Serve this route as a **WebSocket** instead of SSE:
    /// the same `topics` fan out server→client, and — bidirectionally — messages
    /// the client sends are published to [`publish_topic`](Self::publish_topic).
    /// Off by default (SSE).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub websocket: bool,
    /// For a `websocket` stream, the (scope-relative) topic that client→server
    /// messages are published to. `None` = the socket is receive-only (client
    /// sends are dropped).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publish_topic: Option<String>,
}

/// A **duplex, resumable session** route (`PLAN-session-primitive`): a long-lived,
/// client-addressable, bidirectional channel served by a guest component's `session-handler`
/// export, which the host re-enters per inbound frame (mechanism B). The host opens the session on
/// `route` (SSE-out + POST-in), binds the verified principal, buffers/orders outbound frames with
/// resume-from-cursor, and persists a resumable checkpoint. Frames are opaque bytes. Unlike a
/// [`StreamConfig`] (host-only pub/sub fan-out), a session runs guest code and carries a backchannel.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SessionConfig {
    /// Route the session is opened at (the client `GET`s it for the SSE stream and `POST`s inbound
    /// frames to it). Matcher syntax, like a handler route.
    pub route: String,
    /// Path to the session component `.wasm` within the deployment (exports `session-handler`).
    pub component: String,
    /// Requested capabilities (interface names; see `KNOWN_IMPORTS`). A session handler declares
    /// `session` plus whatever `sql`/`orm`/`invoke`/… it uses per frame.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub imports: Vec<String>,
    /// Optional resource limits (capped by site config at activation).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limits: Option<HandlerLimits>,
    /// Static environment variables (never secrets).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
    /// Function-to-function invoke allowlist (same contract as a handler's `invoke_targets`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub invoke_targets: Vec<String>,
    /// Declared `bus:` stats-topic templates for the read-only `messaging-stats` capability (same
    /// contract as [`HandlerConfig::stats_topics`]).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stats_topics: Vec<String>,
    /// Per-component **outbound-TCP allowlist** for the gated `wasi:sockets` capability (same
    /// contract as [`HandlerConfig::egress_allowlist`]): the `host:port` / `ip:port` / `CIDR:port`
    /// targets this session's component may `connect` to. **Empty ⇒ deny-all.** `connect`-only,
    /// posture-gated (`allow_guest_tcp_egress`), SSRF-floored.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub egress_allowlist: Vec<String>,
    /// In-site tenancy decision for this session's `sql`/`orm` (Dimension 0). Resolved once at
    /// **open** from the verified source and carried across every re-entry, so a frame-triggered
    /// query is host-scoped identically to a normal handler. Absent ⇒ plain (project = database).
    #[serde(
        default,
        deserialize_with = "crate::tenancy::de_opt_tenancy",
        skip_serializing_if = "Option::is_none"
    )]
    pub tenancy: Option<crate::tenancy::Tenancy>,
    /// JWKS/issuer verifying the app bearer for a `token`-sourced tenant (same as a function's).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_claims: Option<HandlerGraphqlTokenClaims>,
}

/// Site-scoped, mutable configuration stored in the KV (not in the manifest).
///
/// Carries domains (virtualhost routing) and visitor access control; TLS,
/// previews, and retention land with their respective workstreams.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SiteConfig {
    /// Schema version, pinned at [`crate::SCHEMA_VERSION`].
    pub version: u32,
    /// Hostnames this site answers to.
    pub domains: DomainConfig,
    /// Transport security: HTTPS redirect + HSTS (site tier).
    #[serde(default)]
    pub security: SecurityConfig,
    /// Visitor access control (basic auth, IP rules, rate limiting).
    #[serde(default)]
    pub access: crate::access::AccessConfig,
    /// WebAssembly handler caps + import allowlist (site-scoped).
    /// `None` = handlers disabled for the site.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handlers: Option<HandlersSiteConfig>,
    /// On-the-fly response compression. Off by default;
    /// complements the precompressed-variant path for dynamic/unvaried responses.
    #[serde(default, skip_serializing_if = "CompressionConfig::is_default")]
    pub compression: CompressionConfig,
    /// Reverse-proxy gateway for publishing private services.
    /// `None` = no gateway routes. Declaring an upstream here is what authorizes
    /// reaching a private address (the SSRF guard stays public-only otherwise).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gateway: Option<crate::gateway::GatewayConfig>,
}

impl Default for SiteConfig {
    fn default() -> Self {
        Self {
            version: crate::SCHEMA_VERSION,
            domains: DomainConfig::default(),
            security: SecurityConfig::default(),
            access: crate::access::AccessConfig::default(),
            handlers: None,
            compression: CompressionConfig::default(),
            gateway: None,
        }
    }
}

/// On-the-fly compression policy. Opt-in: compresses a
/// response *only* when it has no precompressed variant / existing
/// `Content-Encoding`, its type is compressible, and (when known) its length is
/// at least `min_size`. Credentialed responses are skipped (BREACH safety).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CompressionConfig {
    /// Master toggle (default off).
    pub enabled: bool,
    /// Don't compress a response whose `Content-Length` is below this (bytes).
    /// Streaming responses with no declared length are always eligible.
    pub min_size: u64,
}

impl Default for CompressionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            min_size: 1024,
        }
    }
}

impl CompressionConfig {
    fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

/// Site-scoped handler policy: the capability allowlist and resource caps that
/// a deployment's requested handler config is intersected against at
/// activation (deny by default).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlersSiteConfig {
    /// Whether handlers run for this site at all.
    pub enabled: bool,
    /// Interfaces handlers on this site may import (subset of `KNOWN_IMPORTS`).
    pub allow_imports: Vec<String>,
    /// Cap on per-handler memory (MiB).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_memory_mb: Option<u32>,
    /// Cap on per-handler timeout (ms).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_timeout_ms: Option<u32>,
    /// Cap on concurrent invocations for the site.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_concurrency: Option<u32>,
    /// Cap on per-handler CPU **fuel** (instruction-count proxy). A per-handler
    /// `fuel` may only lower this, never raise it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_fuel: Option<u64>,
    /// Env-var name → secret reference, injected at instantiation (the value is
    /// a backend reference, resolved server-side — never a literal secret here).
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub secrets: BTreeMap<String, String>,
    /// Named aliases (besides the live/current deployment) whose deployments
    /// also run **background work** — consumers and crons. The
    /// current deployment always runs background work; previews never do. Empty
    /// by default, so only the current deployment is background-active. Each
    /// listed alias gets its own topic namespace (`{site}/{alias}/…`), isolated
    /// from the live one (e.g. opt `staging` in).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub background_aliases: Vec<String>,
    /// Cap on concurrent SSE stream connections for the site.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_stream_connections: Option<u32>,
    /// Cap on captured guest log lines per second for the site, so a noisy guest
    /// can't flood the log sink. Lines over the cap are
    /// dropped (counted). `None` = the server default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_log_rate: Option<u32>,
    /// Opt **out** of capturing the site's guest `stdout`/`stderr` + `wasi:logging`. Capture is
    /// **on by default** (served via the logs endpoint + SSE tail, mirrored to `serve.log`); set
    /// this `true` to disable it — e.g. when a guest's output may carry secrets/PII. When
    /// disabled, the guest's stdio is discarded and never reaches the store, the logs API, or
    /// `serve.log`. (Inverted so the default — capture on — matches `Default`.)
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub disable_log_capture: bool,
    /// Edge response cache. Off unless present + `enabled`. When on, a
    /// cacheable `GET`/`HEAD` response the handler opts in via
    /// `Cache-Control: max-age=…` is stored and served for later identical
    /// requests **without re-instantiating the handler**. Never caches a private
    /// response (`no-store`/`private`, `Set-Cookie`, `Vary: *`, or an
    /// `Authorization` request without `public`/`s-maxage`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache: Option<HandlerCacheConfig>,
    /// GraphQL edge query-guard. Off unless present + `enabled`. When on, an
    /// incoming GraphQL operation is parsed at the edge and rejected **before the
    /// handler runs** if it exceeds the depth or complexity limit, or (unless
    /// allowed) is a schema-introspection query. Defense-in-depth over the fuel cap.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub graphql: Option<HandlerGraphqlConfig>,
    /// Browser cookie session auth. Off unless present. When set, a request with the named
    /// cookie but **no** `Authorization` header is authenticated from the cookie value: it
    /// becomes the app bearer token everywhere the header bearer already flows (managed
    /// handlers, the GraphQL edge, the data connector, invoked functions, `graphql::run`). The
    /// `Authorization` header always wins, so API clients are unaffected. boatramp **only reads**
    /// the cookie — the app's auth handler issues + refreshes it. Set it `HttpOnly; Secure;
    /// SameSite=Lax` (Lax is a CSRF requirement — the browser half of the defense) with a
    /// `__Host-` name prefix; and keep cookie-auth `GET`/`HEAD` handlers side-effect-free (a
    /// same-origin top-level navigation passes the CSRF gate). A cookie-authenticated request is
    /// CSRF-checked: same-origin always passes, and `allowed_origins` adds any cross-origins.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cookie_auth: Option<CookieAuthConfig>,
    /// Site-level in-site tenancy decision (Dimension 0) — the **ceiling** for this site's
    /// handlers' `sql`/`orm` access. A per-function [`crate::function::FunctionConfig::tenancy`]
    /// may narrow within it but not widen it (e.g. a site pinned to `read: own` can't be raised
    /// to `all` by a function). Absent ⇒ *undeclared* (refused under `multi-tenant`, treated as
    /// `Disabled` under single-tenant/dev).
    #[serde(
        default,
        deserialize_with = "crate::tenancy::de_opt_tenancy",
        skip_serializing_if = "Option::is_none"
    )]
    pub tenancy: Option<crate::tenancy::Tenancy>,
    /// **Site-level enablement of per-route ceiling exceptions** (task #470, key 1 of the three-key
    /// model). Default `false`. Set NEXT TO the site [`tenancy`](Self::tenancy) ceiling, this is the
    /// baseline-definer affirmatively permitting routes to exceed its own baseline. While `false`,
    /// EVERY route's [`Tenancy::Scoped::exceed_site_ceiling`](crate::tenancy::Tenancy::Scoped) token
    /// is inert — a widening still fails closed. Turning it on unlocks nothing by itself (a route
    /// must ALSO carry the token, and `all` still needs the operator posture). Keeping it default
    /// `false` gives an honest one-line audit: a site with `allow_ceiling_exceptions = false` is
    /// provably exception-free without scanning every route, and exceptions require a conscious
    /// site-level decision rather than route-by-route sprinkling.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub allow_ceiling_exceptions: bool,
}

/// Browser cookie session auth for a site (see [`HandlersSiteConfig::cookie_auth`]). boatramp
/// only **reads** the cookie; the app sets it. The cookie value is the app bearer token, opaque
/// to boatramp (the app's own `Authorizer` / OIDC config verifies it, exactly as for a header
/// bearer).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CookieAuthConfig {
    /// The cookie whose value is used as the bearer when no `Authorization` header is present.
    pub cookie_name: String,
    /// The **additional cross-origin** CSRF allowlist. A **same-origin** request (its `Origin`
    /// authority equals the request's own `Host`) is always allowed — a page calling its own
    /// origin, the normal SPA case, is definitionally CSRF-safe. This list adds the *other*
    /// origins a browser app served from a **different** origin than this API may come from; each
    /// entry is a scheme+host[+port] origin, e.g. `https://app.example.com`. A cross-origin
    /// request whose `Origin` (or, absent that, `Referer`) is not same-origin and **not** listed
    /// is rejected. **Empty ⇒ same-origin only** — the common case needs no configuration.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allowed_origins: Vec<String>,
}

/// Per-site GraphQL edge query-guard tuning (see [`HandlersSiteConfig::graphql`]).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerGraphqlConfig {
    /// Master switch. `false` (the default) ⇒ the guard is inert even if present.
    pub enabled: bool,
    /// Deepest allowed selection-set nesting (fragments expanded). `None` ⇒ the
    /// server default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_depth: Option<u32>,
    /// Largest allowed total field count (a schema-free complexity proxy). `None` ⇒
    /// the server default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_complexity: Option<u32>,
    /// Whether a schema-introspection query is allowed. `None` ⇒ the posture default
    /// (**off** under the multi-tenant posture, on for single-tenant).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub introspection: Option<bool>,
    /// Automatic Persisted Queries: clients may send a query hash
    /// (`extensions.persistedQuery.sha256Hash`) instead of the full query; the edge
    /// resolves + caches `hash → query` (saving bandwidth + parse cost).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub persisted_queries: bool,
    /// Safelist-enforcement mode: only pre-registered query hashes run (a query
    /// allowlist); the edge never registers a new query. Implies (and is stronger
    /// than) `persisted_queries`. Renamed from `safelist` in v0.6.0 (breaking) to make
    /// the *enforcement* switch distinct from the declarative `safelisted_ops` /
    /// `safelisted_ops_path` source of operations.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub enforce_safelist: bool,
    /// Declarative source of persisted (safelisted) operations, **inline**: the exact
    /// operation texts to register in the project's GraphQL safelist at `apply` time.
    /// Registered **register-only (union)** through the existing control-plane
    /// `POST .../graphql/safelist` endpoint (server-side `guard_query` validation), so
    /// applying **never prunes** — removal stays an explicit `graphql safelist rm`.
    /// Mutually exclusive with [`Self::safelisted_ops_path`]. Authoring-only: skipped
    /// when the site config is serialized to the server (the ops live in the safelist
    /// store, not the site config).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub safelisted_ops: Vec<String>,
    /// Declarative source of persisted (safelisted) operations, **from a file**: a path
    /// (resolved client-side, relative to the manifest dir) to a file whose operations
    /// are registered at `apply` time, exactly like [`Self::safelisted_ops`]. Read
    /// **client-side only** — only the operation *text* crosses the wire, never the
    /// path. Mutually exclusive with `safelisted_ops`. Authoring-only: skipped when the
    /// site config is serialized to the server.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub safelisted_ops_path: Option<std::path::PathBuf>,
    /// Federation gateway: this site is a supergraph gateway. A GraphQL query is planned
    /// against the project's registered subgraphs and executed by dispatching fetches to
    /// the subgraph functions (a subgraph's name is its function name), stitching the
    /// results — instead of running a single handler component.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub federated: bool,
    /// Serve the GraphiQL in-browser explorer: a browser `GET` (an `Accept: text/html`
    /// request) to the endpoint gets the IDE, which posts queries back to the same URL.
    /// A developer convenience — off by default; pair with `introspection` for schema docs.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub graphiql: bool,
    /// The route pattern of the GraphQL endpoint on this site (a
    /// [`HandlerConfig::route`] value, e.g. `/graphql`). The GraphQL edge — the query
    /// guard (depth / complexity / introspection), the federation / data-connector planner,
    /// **and the GraphiQL explorer** — applies **only** to a request whose **path matches
    /// this pattern**, so every other declared guest route on the same site (an OAuth
    /// `/authorize`, `/jwks`, a social-login / SAML redirect start) is served by its own
    /// handler **regardless of `Accept`** — a browser always sends `Accept: text/html`,
    /// which previously got the GraphiQL IDE instead of the guest handler. Matched against
    /// the request **path** (not the *matched handler's* route string), so a broader handler
    /// declared before the graphql route cannot disable the edge/guard on the endpoint.
    /// `None` ⇒ `/graphql` (the convention). **If the graphql endpoint lives at a non-default
    /// path you MUST set this** — otherwise the edge (GraphiQL, APQ, and the query guard) will
    /// not engage at that path. Should be a single literal endpoint path, not a wildcard (a
    /// wildcard would re-widen the edge across sibling guest routes).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub route: Option<String>,
    /// Declarative data connector: serve the GraphQL API by generating it from a managed
    /// database (queries compiled to SQL) instead of running a wasm handler. Absent unless
    /// configured; exposure is deny-by-default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<HandlerGraphqlDataConfig>,
    /// **Edge-visibility per-operation excludes** (#495) for a `federated` gateway: root operations
    /// to make **unreachable from the external `/graphql` edge** while internal paths (guest
    /// `graphql::run`, `emit::invoke`) still reach them. Each entry is a **qualified**
    /// `"<subgraph>.<rootField>"` (e.g. `"identity.socialLogin"`); the field must exist as a root
    /// `Query`/`Mutation` field owned by that subgraph. A **bare** unqualified entry is rejected
    /// (ignored + logged) — a field name alone is ambiguous across subgraphs. An entry naming a
    /// non-existent / wrong-owner root is ignored + logged (never widens: this list can only ADD to
    /// the hidden set). An external operation naming a hidden root fails to plan **exactly like a
    /// genuinely-unknown field** (no oracle). This is the immediate, redeploy-free operator override
    /// (it applies fresh per request, with no recomposition lag); the code-local equivalent is the
    /// `@edgeHidden` SDL field directive. Default empty ⇒ nothing hidden (non-breaking, opt-out only).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub edge_hidden_operations: Vec<String>,
    /// **Edge-visibility per-subgraph excludes** (#495) for a `federated` gateway: every ROOT
    /// `Query`/`Mutation` field OWNED by a listed subgraph is made unreachable from the external
    /// `/graphql` edge (internal paths still reach them). Lets an operator split edge-facing reads
    /// into one subgraph and keep trust-boundary mutations in an invoke-only subgraph with a single
    /// flag. **ROOT-ONLY:** this hides a subgraph's root fields; it does NOT hide that subgraph's
    /// entity fields reached via a shared-type `_entities` jump from another root — a cross-type
    /// entity jump is the resolver's own authz responsibility (whole-subgraph entity hiding is a
    /// documented follow-up). A subgraph owning no root field is ignored + logged. Default empty ⇒
    /// nothing hidden (non-breaking, opt-out only).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub edge_hidden_subgraphs: Vec<String>,
}

/// The declarative GraphQL data connector's configuration (see
/// [`HandlerGraphqlConfig::data`]). A database-derived API is **deny-by-default**: only the
/// tables (and their columns) named here are exposed.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerGraphqlDataConfig {
    /// Master switch. `false` (the default) ⇒ the connector is inert even if present.
    pub enabled: bool,
    /// The managed SQL database name to expose (the site's default database if unset).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub source: String,
    /// The exposed tables, keyed by table name. Deny-by-default: a table absent here is
    /// neither in the generated schema nor queryable.
    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub tables: std::collections::BTreeMap<String, HandlerGraphqlTableConfig>,
    /// Allow mutations (insert/update/delete). Off by default — the connector is read-only
    /// unless a site opts in.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub mutations: bool,
    /// Bind `row_filter` claims from a **verified application bearer token** (the app's own
    /// IdP), not only the host-asserted `project`. This unlocks multi-tenant-within-one-project
    /// isolation: the app's tokens carry a tenant claim (e.g. `tid`) a `row_filter` scopes rows
    /// by. A claim value is used **only** from a fully verified token; a missing/invalid token
    /// leaves the claim absent, so a filter referencing it denies (never widens). Absent ⇒ only
    /// the host `project` claim is available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub claims_from_token: Option<HandlerGraphqlTokenClaims>,
}

/// How to verify an application bearer token whose claims a `row_filter` may bind (see
/// [`HandlerGraphqlDataConfig::claims_from_token`]). The token is verified against `issuer` +
/// the JWKS (signature, `iss`, `exp`/`nbf`, `kid`); on success its scalar claims are merged in
/// beside the host-asserted `project` (which a token can never override).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerGraphqlTokenClaims {
    /// The expected token issuer (`iss`).
    pub issuer: String,
    /// A **host environment variable** holding the app IdP's JWKS JSON — the operator maps
    /// the app's public JWKS in, exactly like a handler secret. Re-read per request, so a
    /// rotated JWKS takes effect without a restart.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jwks_env: Option<String>,
    /// Or a **URL** to fetch the JWKS from (cached per `kid`, refreshed on an unknown `kid` for
    /// IdP key rollover). Operator-configured, so not a request-controlled fetch.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jwks_url: Option<String>,
    /// An optional expected audience (`aud`); unset skips audience validation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audience: Option<String>,
    /// Which verified-JWT claim carries the caller's role/persona, sealed onto the async lane so a
    /// `signed_context` consumer's `graphql::run` sub-fetch can authorize a `role(…)`-gated field as
    /// the presenting caller (PLAN-async-persona). A single scalar (or a one-element array) is sealed
    /// into the durable `signed_context` envelope's `br_persona` claim; absent ⇒ no persona sealed
    /// (unchanged for every existing producer). Host-verified from the presented bearer — never
    /// guest-named.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_persona_claim: Option<String>,
    /// **Multi-issuer trust** (the trust-axis dual of the claim transform): instead of the single
    /// `issuer`, verify the token's `iss` against this policy — an explicit allow-list and/or an
    /// anchored host-suffix — then discover the JWKS per verified `iss` (see [`jwks`](Self::jwks)).
    /// Deny-by-default, host-evaluated, operator-authored (the guest never names an issuer). Set
    /// together with `jwks`; **mutually exclusive** with the single-issuer `issuer` +
    /// `jwks_url`/`jwks_env` form (mixing the two is a `boatramp apply` error). Absent ⇒ the
    /// single-issuer path, byte-identical.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub issuer_trust: Option<IssuerTrust>,
    /// Where to discover the JWKS per verified `iss` when using [`issuer_trust`](Self::issuer_trust).
    /// The URL is derived from the *verified* `iss` by the operator-chosen rule, never from a token
    /// field or any request input.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub jwks: Option<JwksDiscovery>,
    /// **Operator opt-in: a verified first-party token maps to the SYSTEM principal** (no tenant),
    /// not a tenant (PLAN-system-principal P1). Deny-by-default — set this ONLY to let a named,
    /// first-party admin IdP mint the node-wide system principal (base-row `IS NULL` writes +
    /// `app.principal_kind='system'`), retiring the `tid="platform"` sentinel. When a token verifies
    /// AND its `iss` is EXACTLY [`SystemWhen::issuer`] AND its [`SystemWhen::claim`] equals
    /// [`SystemWhen::equals`], the resolved principal is **System** (a typed class — never a tenant
    /// value). Every *other* token on the same source still resolves a tenant exactly as before; an
    /// absent/invalid/wrong-issuer/wrong-claim token confers **no** system (it is denied, or resolves
    /// a tenant, unchanged). Mere absence of a tenant NEVER confers system.
    ///
    /// **S0 (load-bearing):** [`SystemWhen::issuer`] must be an EXACT, operator-named issuer — the
    /// single [`issuer`](Self::issuer), or a member of [`IssuerTrust::allow`]. It can NEVER be
    /// satisfied by [`IssuerTrust::suffix`] (a *family* of orgs) or by discovery: a suffix-trusted or
    /// discovered issuer may confer a tenant, never the node-wide system class. Enforced at apply
    /// ([`validate`](Self::validate)) and re-checked by a runtime backstop before system is conferred.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub system_when: Option<SystemWhen>,
}

fn default_role_claim() -> String {
    "role".to_string()
}

/// Operator policy mapping a verified first-party token to the **SYSTEM principal**
/// ([`HandlerGraphqlTokenClaims::system_when`]). Deny-by-default and provenance-bound: it fires only
/// for a token that fully verifies against an EXACT, operator-named issuer and carries the named
/// claim value. It confers a typed class, never a tenant key.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SystemWhen {
    /// The EXACT issuer (`iss`, full `https://…`) permitted to mint the system principal. Apply-time
    /// it MUST equal the single [`issuer`](HandlerGraphqlTokenClaims::issuer) or be one of
    /// [`IssuerTrust::allow`]; it may NEVER be a value matched only by [`IssuerTrust::suffix`] or
    /// reached by discovery (S0). Compared by exact equality to the *verified* `iss` at resolution.
    pub issuer: String,
    /// The verified claim whose value gates system (default `role`). Read only from the fully
    /// verified token.
    #[serde(default = "default_role_claim")]
    pub claim: String,
    /// The exact string value [`claim`](Self::claim) must equal to confer system. A non-string or
    /// unequal claim confers no system (the token then resolves a tenant, or is denied, unchanged).
    pub equals: String,
}

/// A **trusted-issuer policy** for [`HandlerGraphqlTokenClaims::issuer_trust`]: an explicit
/// allow-list ∪ an anchored host-suffix. A token's `iss` (an `https://` URL) is trusted iff it is
/// an exact string in `allow`, OR its parsed host falls under `suffix` at a label boundary. At least
/// one of `allow`/`suffix` must be set (apply-time checked).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct IssuerTrust {
    /// Exact issuer strings (full `https://…`), e.g. `["https://acme.my.salesforce.com"]`. Matched
    /// by exact equality against the token's `iss` (and re-pinned into the signature check), so a
    /// userinfo/path trick in the token can never equal a listed entry.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allow: Vec<String>,
    /// An **anchored** host-suffix (leading dot), e.g. `.my.salesforce.com`, trusting a family of
    /// orgs without enumerating them. Matched at a label boundary over the *parsed* `https://` host
    /// (never a raw-string suffix): `.x.com` matches `a.x.com` / `a.b.x.com`, never `evilx.com`,
    /// `https://a.x.com@evil.com`, or a non-`https` scheme.
    ///
    /// **Operator warning:** scope the suffix to a registrar-controlled vendor domain you trust
    /// (e.g. `.my.salesforce.com`), NOT a *public suffix* where anyone can register a sub-label
    /// (`.co.uk`, `.github.io`, `.herokuapp.com`, …). The ≥2-label apply check rejects a bare TLD but
    /// cannot know the public-suffix list — a too-broad suffix would trust any tenant's self-hosted
    /// IdP under it. Prefer the explicit `allow` list when in doubt.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suffix: Option<String>,
}

/// How the JWKS is discovered per verified `iss` ([`HandlerGraphqlTokenClaims::jwks`]). Exactly one
/// of `discover`/`template` is set (apply-time checked). The resolved URL's host is always pinned to
/// the verified `iss` host before any fetch.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct JwksDiscovery {
    /// `"oidc"` → OIDC discovery: fetch `<iss>/.well-known/openid-configuration` and use its
    /// `jwks_uri` (whose host MUST match the `iss` host — a trusted-but-malicious org controls its
    /// own discovery doc). The general case.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discover: Option<String>,
    /// A `{iss}`-templated JWKS URL, e.g. `"{iss}/id/keys"` (Salesforce). Host-pinned by
    /// construction (no discovery doc) — the preferred form.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub template: Option<String>,
}

/// Anchored host-suffix match at a **label boundary**: `host` equals `bare_suffix` (the apex) or is
/// a sub-label of it. `bare_suffix` has NO leading dot; both args must already be parsed hosts,
/// lowercased and trailing-dot-stripped. Shared by `proxy_allow` and the issuer-trust suffix policy
/// so the one boundary rule lives in one audited place — never a raw `ends_with` on an unparsed
/// string (which `evilx.com` would satisfy for `x.com`).
#[must_use]
pub fn host_matches_suffix(host: &str, bare_suffix: &str) -> bool {
    host == bare_suffix || host.ends_with(&format!(".{bare_suffix}"))
}

impl HandlerGraphqlTokenClaims {
    /// Apply-time validation (a `boatramp apply` error on failure). The single-issuer form
    /// (`issuer`/`jwks_url`/`jwks_env`) and the multi-issuer form (`issuer_trust`/`jwks`) are
    /// mutually exclusive; the multi-issuer form needs a non-empty policy, well-formed `allow`
    /// entries and `suffix`, and exactly one well-formed `jwks` rule. These are STRING-level sanity
    /// checks — the authoritative, URL-parsed host extraction + label-boundary match happens at
    /// verify time in the server (which has a real URL parser); this just fails obvious misconfig
    /// fast.
    pub fn validate(&self) -> Result<(), ConfigError> {
        let multi = self.issuer_trust.is_some() || self.jwks.is_some();
        let single = !self.issuer.is_empty() || self.jwks_url.is_some() || self.jwks_env.is_some();
        if multi && single {
            return Err(ConfigError::parse(
                "token_claims: the single-issuer form (issuer/jwks_url/jwks_env) and the \
                 multi-issuer form (issuer_trust/jwks) are mutually exclusive — set one",
            ));
        }
        // S0 (PLAN-system-principal): `system_when` may confer the node-wide system class ONLY for an
        // EXACT, operator-named issuer — the single `issuer`, or a member of `issuer_trust.allow`.
        // NEVER one matched only by `issuer_trust.suffix` (a *family* of orgs) or reached by discovery.
        // Validated for BOTH forms here, ahead of either early return; a runtime backstop re-checks the
        // exact match before conferring system, so a control-plane deploy that bypassed apply is covered.
        if let Some(sw) = &self.system_when {
            if sw.issuer.is_empty() {
                return Err(ConfigError::parse(
                    "token_claims.system_when.issuer: set the EXACT first-party issuer permitted to \
                     mint the system principal",
                ));
            }
            if sw.claim.is_empty() {
                return Err(ConfigError::parse(
                    "token_claims.system_when.claim: must be a non-empty claim name",
                ));
            }
            if sw.equals.is_empty() {
                return Err(ConfigError::parse(
                    "token_claims.system_when.equals: set the exact claim value that confers system",
                ));
            }
            let exact_ok = if multi {
                self.issuer_trust
                    .as_ref()
                    .is_some_and(|t| t.allow.iter().any(|a| a == &sw.issuer))
            } else {
                !self.issuer.is_empty() && self.issuer == sw.issuer
            };
            if !exact_ok {
                return Err(ConfigError::parse(format!(
                    "token_claims.system_when.issuer {:?} must be an EXACT trusted issuer — the \
                     single `issuer`, or a member of `issuer_trust.allow`. A `suffix`-matched or \
                     discovered issuer may NEVER mint the node-wide system principal (S0)",
                    sw.issuer
                )));
            }
        }
        if !multi {
            return Ok(());
        }
        let trust = self.issuer_trust.as_ref().ok_or_else(|| {
            ConfigError::parse("token_claims: `jwks` (multi-issuer) requires `issuer_trust`")
        })?;
        let jwks = self
            .jwks
            .as_ref()
            .ok_or_else(|| ConfigError::parse("token_claims: `issuer_trust` requires `jwks`"))?;
        if trust.allow.is_empty() && trust.suffix.is_none() {
            return Err(ConfigError::parse(
                "token_claims.issuer_trust: set `allow` and/or `suffix` (deny-by-default)",
            ));
        }
        for a in &trust.allow {
            validate_issuer_entry(a)?;
        }
        if let Some(sfx) = &trust.suffix {
            validate_issuer_suffix(sfx)?;
        }
        match (jwks.discover.as_deref(), jwks.template.as_deref()) {
            (Some("oidc"), None) => {}
            (Some(other), None) => {
                return Err(ConfigError::parse(format!(
                    "token_claims.jwks.discover must be \"oidc\" (got {other:?})"
                )));
            }
            // Require `{iss}` at the AUTHORITY position (the template must START with it), so the
            // resolved URL's host is always the verified `iss` host — rejects e.g.
            // `https://evil/?iss={iss}`, where `{iss}` sits in a query and the host is attacker-chosen.
            (None, Some(t)) if t.starts_with("{iss}") => {}
            (None, Some(t)) => {
                return Err(ConfigError::parse(format!(
                    "token_claims.jwks.template must START with the `{{iss}}` placeholder (so the \
                     JWKS host is the issuer host), e.g. \"{{iss}}/id/keys\" (got {t:?})"
                )));
            }
            (None, None) => {
                return Err(ConfigError::parse(
                    "token_claims.jwks: set exactly one of `discover: \"oidc\"` or `template`",
                ));
            }
            (Some(_), Some(_)) => {
                return Err(ConfigError::parse(
                    "token_claims.jwks: set exactly one of `discover` or `template`, not both",
                ));
            }
        }
        Ok(())
    }
}

/// String-level check that an `allow` / issuer entry is a plausible `https://` issuer with no
/// embedded userinfo (the authoritative parse is server-side).
fn validate_issuer_entry(entry: &str) -> Result<(), ConfigError> {
    let rest = entry.strip_prefix("https://").ok_or_else(|| {
        ConfigError::parse(format!(
            "token_claims.issuer_trust.allow: {entry:?} must be an https:// issuer"
        ))
    })?;
    let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
    if authority.is_empty() {
        return Err(ConfigError::parse(format!(
            "token_claims.issuer_trust.allow: {entry:?} has no host"
        )));
    }
    if authority.contains('@') {
        return Err(ConfigError::parse(format!(
            "token_claims.issuer_trust.allow: {entry:?} must not contain userinfo (`@`)"
        )));
    }
    Ok(())
}

/// String-level check that a `suffix` is an anchored, multi-label host suffix (`.my.salesforce.com`):
/// a leading dot, no scheme/path/userinfo/port, and at least two labels (never a bare TLD `.com`).
fn validate_issuer_suffix(suffix: &str) -> Result<(), ConfigError> {
    let bare = suffix.strip_prefix('.').ok_or_else(|| {
        ConfigError::parse(format!(
            "token_claims.issuer_trust.suffix: {suffix:?} must start with a dot (anchored, e.g. \
             \".my.salesforce.com\")"
        ))
    })?;
    if bare.contains("://") || bare.contains(['/', '@', ':', '?', '#']) || bare.ends_with('.') {
        return Err(ConfigError::parse(format!(
            "token_claims.issuer_trust.suffix: {suffix:?} must be a bare host suffix (no scheme, \
             path, userinfo, or port)"
        )));
    }
    if bare.split('.').filter(|l| !l.is_empty()).count() < 2 {
        return Err(ConfigError::parse(format!(
            "token_claims.issuer_trust.suffix: {suffix:?} is too broad — need at least two labels \
             (never a bare TLD)"
        )));
    }
    Ok(())
}

/// One exposed table's policy (see [`HandlerGraphqlDataConfig::tables`]).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerGraphqlTableConfig {
    /// The readable columns (an allow-list). Deny-by-default: a column absent here is
    /// invisible.
    pub columns: Vec<String>,
    /// Row-level filter terms, all applied to every access — the tenant-isolation seam.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub row_filter: Vec<HandlerGraphqlRowTerm>,
    /// Fields on this type resolved by a **wasm function** instead of a column: `field →
    /// function name`. The connector resolves the row's columns from SQL, then batches one
    /// invoke to the function (a local `_entities` fetch) to fill the field. This map is also
    /// the allowlist — only these fields delegate, only to these functions.
    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub resolvers: std::collections::BTreeMap<String, String>,
}

/// One row-filter term: the `column` must equal the value of the request's `claim` (see
/// [`HandlerGraphqlTableConfig::row_filter`]). Claims are host-asserted (e.g. `project`).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerGraphqlRowTerm {
    /// The constrained column.
    pub column: String,
    /// The request claim whose value the column must equal.
    pub claim: String,
}

/// Per-site edge response-cache tuning (see [`HandlersSiteConfig::cache`]).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerCacheConfig {
    /// Master switch. `false` (the default) ⇒ the cache is inert even if present.
    pub enabled: bool,
    /// Largest cacheable entry (encoded status+headers+body), in bytes; a bigger
    /// response streams through uncached. `None` ⇒ the server default (256 KiB).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_entry_bytes: Option<u64>,
    /// Upper bound (seconds) on a stored entry's TTL, clamping an over-long
    /// `max-age`. `None` ⇒ the server default (3600s).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_ttl_secs: Option<u64>,
}

impl SiteConfig {
    /// Parse from JSON (the KV storage / API format).
    pub fn from_json(bytes: &[u8]) -> Result<Self, ConfigError> {
        serde_json::from_slice(bytes).map_err(|err| ConfigError::parse(err.to_string()))
    }

    /// Serialize to JSON for KV storage.
    pub fn to_json(&self) -> Result<Vec<u8>, ConfigError> {
        serde_json::to_vec(self).map_err(|err| ConfigError::parse(err.to_string()))
    }

    /// Validate the site-level handler import allowlist: every entry in
    /// [`HandlersSiteConfig::allow_imports`] must be a recognized import name (a
    /// `KNOWN_IMPORTS` interface, a named SQL binding `sql:<name>`/`sql:*`, or an admin
    /// surface `admin:<surface>`). Called on the guest `admin:site` config-write path so a
    /// self-configuring guest can't stash an unknown/typo'd capability name in the allowlist.
    /// Defense-in-depth: the effective runtime grant is still the deploy-pinned manifest
    /// `imports` ∩ this list ∩ posture, so a bogus entry can't escalate — this rejects it early.
    pub fn validate_allow_imports(&self) -> Result<(), ConfigError> {
        if let Some(handlers) = &self.handlers {
            for import in &handlers.allow_imports {
                check_import(import)?;
            }
        }
        Ok(())
    }
}

/// The hostnames a site answers to.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DomainConfig {
    /// Primary/canonical hostname (e.g. `example.com`).
    pub primary: Option<String>,
    /// Additional exact hostnames (e.g. `www.example.com`).
    pub aliases: Vec<String>,
    /// Wildcard patterns (`*.example.com`), matched by suffix at any depth.
    pub wildcards: Vec<String>,
    /// Redirect exact-alias hosts to [`primary`](Self::primary) with a 301
    /// (apex↔www canonicalization). Only exact aliases redirect — wildcard hosts
    /// serve as-is. Off by default.
    pub canonical_redirect: bool,
    /// Per-host **tenant context tag** (Stage 0 in-site tenancy): host-or-wildcard-pattern → an
    /// opaque tag the host binds as the in-site tenant when a function/site resolves "own" via
    /// [`crate::tenancy::TenantSource::Domain`]. This is what lets ONE deployment serve many
    /// customer storefronts, each on its own domain = its own tenant. An exact host with no own
    /// entry inherits [`primary`](Self::primary)'s tag (apex↔www share a tenant); a subdomain
    /// inherits its matching wildcard's tag. A host with no resolvable tag makes the domain source
    /// fail closed (no cross-tenant read). The tag is bound as a parameter, never formatted into
    /// SQL.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub contexts: BTreeMap<String, String>,
}

impl DomainConfig {
    /// All exact hostnames (primary first, then aliases).
    pub fn exact_hosts(&self) -> impl Iterator<Item = &str> {
        self.primary
            .as_deref()
            .into_iter()
            .chain(self.aliases.iter().map(String::as_str))
    }
}

/// Site-scoped **transport security** (the site config tier owns transport
/// concerns). Off by default; the operator opts in once TLS is in
/// front (directly or via a terminating proxy).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SecurityConfig {
    /// 301 plain-HTTP requests to HTTPS. Proxy-aware: the effective scheme is
    /// read from `X-Forwarded-Proto` behind a TLS-terminating proxy.
    pub https_redirect: bool,
    /// Send `Strict-Transport-Security` on HTTPS responses, when set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hsts: Option<Hsts>,
    /// `Content-Security-Policy` header value, when set (opt-in: a default CSP
    /// would break the inline scripts/styles common in static sites, so the
    /// operator supplies the policy). Applied on host-routed responses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub csp: Option<String>,
    /// `X-Frame-Options` header value (e.g. `DENY`, `SAMEORIGIN`), when set.
    /// Opt-in: it can break legitimate embedding, so it isn't a default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frame_options: Option<String>,
}

/// HTTP Strict-Transport-Security policy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Hsts {
    /// `max-age` in seconds.
    pub max_age: u64,
    /// Apply to subdomains too.
    pub include_subdomains: bool,
    /// Request inclusion in browser preload lists.
    pub preload: bool,
}

impl Default for Hsts {
    fn default() -> Self {
        // One year + includeSubDomains: the common safe baseline (preload is an
        // explicit opt-in since it's hard to undo).
        Self {
            max_age: 31_536_000,
            include_subdomains: true,
            preload: false,
        }
    }
}

impl Hsts {
    /// The `Strict-Transport-Security` header value.
    pub fn header_value(&self) -> String {
        let mut v = format!("max-age={}", self.max_age);
        if self.include_subdomains {
            v.push_str("; includeSubDomains");
        }
        if self.preload {
            v.push_str("; preload");
        }
        v
    }
}

/// Compute the canonicalization/HTTPS **redirect target** for a request, or
/// `None` if it's already canonical. `scheme` is the
/// effective scheme (`http`/`https`, proxy-aware), `host` the request host
/// (no port), `path_and_query` the rest of the URL. A single 301 collapses both
/// an HTTPS upgrade and an apex↔www redirect.
pub fn transport_redirect(
    security: &SecurityConfig,
    domains: &DomainConfig,
    scheme: &str,
    host: &str,
    path_and_query: &str,
) -> Option<String> {
    let target_scheme = if security.https_redirect && scheme == "http" {
        "https"
    } else {
        scheme
    };
    // Only exact aliases canonicalize to the primary; wildcard hosts serve as-is.
    let target_host = match &domains.primary {
        Some(primary)
            if domains.canonical_redirect
                && primary != host
                && domains.aliases.iter().any(|a| a == host) =>
        {
            primary.as_str()
        }
        _ => host,
    };
    if target_scheme == scheme && target_host == host {
        return None;
    }
    Some(format!("{target_scheme}://{target_host}{path_and_query}"))
}

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

    #[test]
    fn empty_config_uses_defaults() {
        let config = DeployConfig::from_ron("()").unwrap();
        assert_eq!(config.index, vec!["index.html".to_string()]);
        assert_eq!(config.trailing_slash, TrailingSlash::Preserve);
        assert!(config.redirects.is_empty());
    }

    #[test]
    fn consumer_per_consumer_tuning_is_optional_and_round_trips() {
        // Back-compat: a consumer with no tuning fields leaves them `None` (server defaults apply).
        let bare: ConsumerConfig =
            serde_json::from_str(r#"{"topic":"orders","component":"c.wasm"}"#).unwrap();
        assert_eq!(bare.lease_ms, None);
        assert_eq!(bare.max_attempts, None);
        assert_eq!(bare.max_batch, None);
        // Explicit per-consumer overrides (≈ JetStream AckWait/MaxDeliver/batch) round-trip.
        let tuned: ConsumerConfig = serde_json::from_str(
            r#"{"topic":"orders","component":"c.wasm","lease_ms":5000,"max_attempts":10,"max_batch":64}"#,
        )
        .unwrap();
        assert_eq!(tuned.lease_ms, Some(5000));
        assert_eq!(tuned.max_attempts, Some(10));
        assert_eq!(tuned.max_batch, Some(64));
        let reparsed: ConsumerConfig =
            serde_json::from_str(&serde_json::to_string(&tuned).unwrap()).unwrap();
        assert_eq!(reparsed.lease_ms, Some(5000));
        assert_eq!(reparsed.max_attempts, Some(10));
        assert_eq!(reparsed.max_batch, Some(64));
    }

    #[test]
    fn secret_allowlist_field_defaults_empty_and_round_trips() {
        // Task #492: the per-guest `secrets` allowlist is an optional opt-in. Absent ⇒ empty ⇒
        // "inject the whole site pool" (non-breaking), so a pre-#492 handler config still parses.
        let bare: HandlerConfig =
            serde_json::from_str(r#"{"route":"/*","component":"h.wasm"}"#).unwrap();
        assert!(
            bare.secrets.is_empty(),
            "absent ⇒ empty (inject-all default)"
        );

        // A non-empty allowlist deserializes and round-trips verbatim.
        let scoped: HandlerConfig = serde_json::from_str(
            r#"{"route":"/*","component":"h.wasm","secrets":["SECRET_A","SECRET_B"]}"#,
        )
        .unwrap();
        assert_eq!(
            scoped.secrets,
            vec!["SECRET_A".to_string(), "SECRET_B".to_string()]
        );
        let reparsed: HandlerConfig =
            serde_json::from_str(&serde_json::to_string(&scoped).unwrap()).unwrap();
        assert_eq!(reparsed.secrets, scoped.secrets);

        // And an empty allowlist is elided on serialize (skip_serializing_if), so a config that
        // never used the feature serializes byte-identically to before.
        let json = serde_json::to_string(&bare).unwrap();
        assert!(
            !json.contains("secrets"),
            "empty allowlist is not serialized: {json}"
        );

        // Same contract on a consumer.
        let consumer: ConsumerConfig = serde_json::from_str(
            r#"{"topic":"orders","component":"c.wasm","secrets":["SECRET_A"]}"#,
        )
        .unwrap();
        assert_eq!(consumer.secrets, vec!["SECRET_A".to_string()]);
        let bare_consumer: ConsumerConfig =
            serde_json::from_str(r#"{"topic":"orders","component":"c.wasm"}"#).unwrap();
        assert!(bare_consumer.secrets.is_empty());
    }

    #[test]
    fn edge_hidden_fields_default_empty_and_round_trip() {
        // #495: the edge-visibility manifest fields are opt-out (default empty ⇒ nothing hidden ⇒
        // non-breaking). A pre-#495 graphql config still parses (they're absent).
        let bare: HandlerGraphqlConfig =
            serde_json::from_str(r#"{"enabled":true,"federated":true}"#).unwrap();
        assert!(bare.edge_hidden_operations.is_empty());
        assert!(bare.edge_hidden_subgraphs.is_empty());
        // An empty manifest is elided on serialize (skip_serializing_if), so a config that never
        // used the feature serializes byte-identically to before.
        let json = serde_json::to_string(&bare).unwrap();
        assert!(
            !json.contains("edge_hidden"),
            "empty edge-hidden manifest is not serialized: {json}"
        );

        // Non-empty manifests deserialize and round-trip verbatim.
        let scoped: HandlerGraphqlConfig = serde_json::from_str(
            r#"{"enabled":true,"federated":true,"edge_hidden_operations":["identity.socialLogin","identity.exchange"],"edge_hidden_subgraphs":["identity"]}"#,
        )
        .unwrap();
        assert_eq!(
            scoped.edge_hidden_operations,
            vec![
                "identity.socialLogin".to_string(),
                "identity.exchange".to_string()
            ]
        );
        assert_eq!(scoped.edge_hidden_subgraphs, vec!["identity".to_string()]);
        let reparsed: HandlerGraphqlConfig =
            serde_json::from_str(&serde_json::to_string(&scoped).unwrap()).unwrap();
        assert_eq!(
            reparsed.edge_hidden_operations,
            scoped.edge_hidden_operations
        );
        assert_eq!(reparsed.edge_hidden_subgraphs, scoped.edge_hidden_subgraphs);
    }

    #[test]
    fn transport_redirect_https_canonical_and_noop() {
        let mut domains = DomainConfig {
            primary: Some("example.com".into()),
            aliases: vec!["www.example.com".into()],
            ..Default::default()
        };
        let mut sec = SecurityConfig::default();

        // Defaults: nothing configured → no redirect.
        assert_eq!(
            transport_redirect(&sec, &domains, "http", "example.com", "/a?b=1"),
            None
        );

        // HTTPS redirect only.
        sec.https_redirect = true;
        assert_eq!(
            transport_redirect(&sec, &domains, "http", "example.com", "/a?b=1").as_deref(),
            Some("https://example.com/a?b=1")
        );
        // Already https → no-op.
        assert_eq!(
            transport_redirect(&sec, &domains, "https", "example.com", "/a"),
            None
        );

        // Canonical: an exact alias → primary (and HTTPS in one hop).
        domains.canonical_redirect = true;
        assert_eq!(
            transport_redirect(&sec, &domains, "http", "www.example.com", "/p").as_deref(),
            Some("https://example.com/p")
        );
        // The primary itself is canonical → only the scheme may change.
        assert_eq!(
            transport_redirect(&sec, &domains, "https", "example.com", "/p"),
            None
        );
        // A wildcard/non-alias host is NOT canonicalized (only the scheme).
        assert_eq!(
            transport_redirect(&sec, &domains, "https", "blog.example.com", "/p"),
            None
        );
        sec.https_redirect = false;
        assert_eq!(
            transport_redirect(&sec, &domains, "https", "www.example.com", "/p").as_deref(),
            Some("https://example.com/p"),
            "canonical redirect applies even without https_redirect"
        );
    }

    #[test]
    fn hsts_header_value() {
        assert_eq!(
            Hsts::default().header_value(),
            "max-age=31536000; includeSubDomains"
        );
        assert_eq!(
            Hsts {
                max_age: 60,
                include_subdomains: false,
                preload: true
            }
            .header_value(),
            "max-age=60; preload"
        );
    }

    #[test]
    fn secret_heuristic_flags_credentials_not_plain_config() {
        // Plain, legitimate `env` values are NOT flagged.
        for ok in [
            "info",
            "production",
            "https://api.example.com/v1",
            "3000",
            "en-US,en;q=0.9",
            "a-normal-kebab-case-flag",
        ] {
            assert!(!looks_like_secret(ok), "false positive on {ok:?}");
        }
        // Credential-shaped values ARE flagged.
        let pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIabc\n-----END RSA PRIVATE KEY-----";
        for bad in [
            pem,
            "AKIAIOSFODNN7EXAMPLE",
            "ghp_16C7e42F292c6912E7710c838347Ae178B4a", // GitHub PAT shape
            "AIzaSyA-1234567890abcdefghijklmnopqrstuv", // Google API key shape
            "wJalrXUtnFEMI1bK7MDENGbPxRfiCYEXAMPLEKEY12", // mixed-case high-entropy
            "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef0123", // long hex
        ] {
            assert!(looks_like_secret(bad), "missed secret {bad:?}");
        }
    }

    #[test]
    fn check_handlers_rejects_secret_in_env() {
        use std::collections::BTreeMap;
        let config = DeployConfig {
            handlers: vec![HandlerConfig {
                tenancy: None,
                token_claims: None,
                no_secrets: false,
                route: "/h".into(),
                methods: Vec::new(),
                component: "h.wasm".into(),
                imports: Vec::new(),
                streaming: false,
                limits: None,
                env: BTreeMap::from([("AWS_KEY".to_string(), "AKIAIOSFODNN7EXAMPLE".to_string())]),
                secrets: Vec::new(),
                invoke_targets: Vec::new(),
                stats_topics: Vec::new(),
                tenant_secret_names: Vec::new(),
                upload_containers: Vec::new(),
                blobstore_containers: Vec::new(),
                egress_allowlist: Vec::new(),
            }],
            ..Default::default()
        };
        let err = config.compile_check().unwrap_err().to_string();
        assert!(err.contains("looks like a secret"), "got: {err}");
    }

    #[test]
    fn check_handlers_validates_sessions() {
        // A well-formed session (compiling route, non-empty component, recognized imports incl.
        // the intrinsic `session` token) passes.
        let ok = DeployConfig {
            sessions: vec![SessionConfig {
                route: "/agent".into(),
                component: "agent.wasm".into(),
                imports: vec!["session".into(), "sql".into()],
                ..Default::default()
            }],
            ..Default::default()
        };
        ok.compile_check().expect("valid session config");

        // An empty component path is rejected.
        let no_component = DeployConfig {
            sessions: vec![SessionConfig {
                route: "/agent".into(),
                component: String::new(),
                ..Default::default()
            }],
            ..Default::default()
        };
        assert!(
            no_component
                .compile_check()
                .unwrap_err()
                .to_string()
                .contains("empty component")
        );

        // An unknown import is rejected.
        let bad_import = DeployConfig {
            sessions: vec![SessionConfig {
                route: "/agent".into(),
                component: "agent.wasm".into(),
                imports: vec!["not-a-capability".into()],
                ..Default::default()
            }],
            ..Default::default()
        };
        assert!(
            bad_import
                .compile_check()
                .unwrap_err()
                .to_string()
                .contains("unknown handler import")
        );
    }

    #[test]
    fn parses_a_full_document() {
        let text = r#"(
            clean_urls: true,
            trailing_slash: Never,
            error_documents: { 404: "/404.html" },
            redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
            rewrites: [ (from: "/app/**", to: "/index.html") ],
            headers: [ (matches: "**.js", set: { "Cache-Control": "public, max-age=31536000, immutable" }) ],
            cache: ( default: "public, max-age=0, must-revalidate" ),
            mime_overrides: { ".webmanifest": "application/manifest+json" },
        )"#;
        let config = DeployConfig::from_ron(text).unwrap();
        assert!(config.clean_urls);
        assert_eq!(config.trailing_slash, TrailingSlash::Never);
        assert_eq!(config.redirects[0].status, 301);
        assert_eq!(config.rewrites[0].status, 200); // defaulted
        assert_eq!(
            config.error_documents.get(&404).map(String::as_str),
            Some("/404.html")
        );
    }

    #[test]
    fn rejects_bad_pattern_at_parse() {
        let text = r#"( redirects: [ (from: "/a/**/b/**", to: "/x") ] )"#;
        assert!(DeployConfig::from_ron(text).is_err());
    }

    #[test]
    fn rejects_unknown_field() {
        assert!(DeployConfig::from_ron("( nope: true )").is_err());
    }

    #[test]
    fn accepts_named_sql_imports_and_rejects_malformed_ones() {
        use super::check_import;
        // The bare capability + named-database grants are accepted.
        assert!(check_import("sql").is_ok());
        assert!(check_import("sql:product").is_ok());
        assert!(check_import("sql:privileged_2-a").is_ok());
        assert!(check_import("sql:*").is_ok());
        // Malformed named grants are rejected: empty name, or a name that could smuggle a path /
        // injection through `sql.open(name)`.
        assert!(check_import("sql:").is_err());
        assert!(check_import("sql:a/b").is_err());
        assert!(check_import("sql:a b").is_err());
        // The experimental capability tokens accepted offline (like `session`/`tenancy`) but
        // advertised only when the host build compiled them.
        assert!(check_import("session").is_ok());
        assert!(check_import("tenancy").is_ok());
        assert!(check_import("messaging-stats").is_ok());
        // The two INDEPENDENT per-tenant sealed-secret rights (task #493) are accepted; a bare
        // `tenant-secrets`, a wildcard, or a typo'd right is rejected (deny-by-default,
        // least-privilege — a component names the specific right).
        assert!(check_import("tenant-secrets:read").is_ok());
        assert!(check_import("tenant-secrets:admin").is_ok());
        assert!(super::is_named_tenant_secrets_import("tenant-secrets:read"));
        assert!(super::is_named_tenant_secrets_import(
            "tenant-secrets:admin"
        ));
        assert!(check_import("tenant-secrets").is_err());
        assert!(check_import("tenant-secrets:*").is_err());
        assert!(check_import("tenant-secrets:write").is_err());
        // The gated outbound-TCP capability is accepted offline (it is in `KNOWN_IMPORTS`); the
        // posture flag + per-handler `egress_allowlist` gate reach at activation/runtime, not here.
        assert!(check_import("wasi:sockets").is_ok());
        // A wholly-unknown import is still rejected.
        assert!(check_import("wasi:filesystem").is_err());
    }

    #[test]
    fn handler_config_with_a_sockets_import_and_egress_allowlist_round_trips() {
        // `PLAN-handler-tcp-egress` TE-1: the offline validator accepts a manifest declaring the
        // gated `wasi:sockets` import, and the per-handler `egress_allowlist` round-trips. (Deny-by-
        // default still holds: the capability does nothing until the node posture allows it AND the
        // allowlist is non-empty — enforced at activation/runtime, not at parse.)
        let text = r#"(
            handlers: [
                ( route: "/imap", methods: ["POST"],
                  component: "handlers/imap.wasm",
                  imports: ["wasi:sockets"],
                  egress_allowlist: ["imap.example.com:993", "10.0.0.0/8:5432"] ),
            ],
            consumers: [
                ( topic: "mail/fetch", component: "handlers/fetch.wasm",
                  imports: ["wasi:sockets"],
                  egress_allowlist: ["pop.example.com:995"] ),
            ],
        )"#;
        let config = DeployConfig::from_ron(text).expect("a wasi:sockets manifest parses");
        assert_eq!(config.handlers[0].imports, vec!["wasi:sockets".to_string()]);
        assert_eq!(
            config.handlers[0].egress_allowlist,
            vec![
                "imap.example.com:993".to_string(),
                "10.0.0.0/8:5432".to_string()
            ]
        );
        assert_eq!(
            config.consumers[0].egress_allowlist,
            vec!["pop.example.com:995".to_string()]
        );
        // An empty / absent allowlist is the deny-all default (serde default, skip-if-empty).
        let empty = DeployConfig::from_ron(
            r#"( handlers: [ ( route: "/x", component: "x.wasm", imports: ["wasi:sockets"] ) ] )"#,
        )
        .expect("parses without an allowlist");
        assert!(empty.handlers[0].egress_allowlist.is_empty());
    }

    #[test]
    fn accepts_named_blob_upload_imports_and_rejects_malformed_ones() {
        use super::{check_import, is_named_blob_upload_import};
        // The two INDEPENDENT blob-upload mint rights are accepted offline (mirrors the
        // `tenant-secrets:{read,admin}` shape); a bare `blob-upload`, a wildcard, or a typo'd right
        // is rejected (deny-by-default, least-privilege — a component names the specific right).
        assert!(is_named_blob_upload_import("blob-upload:write"));
        assert!(is_named_blob_upload_import("blob-upload:multipart"));
        assert!(check_import("blob-upload:write").is_ok());
        assert!(check_import("blob-upload:multipart").is_ok());
        // Not a grant: bare capability, wildcard, a read right (there is no read on this surface),
        // and any typo.
        assert!(!is_named_blob_upload_import("blob-upload"));
        assert!(!is_named_blob_upload_import("blob-upload:read"));
        assert!(!is_named_blob_upload_import("blob-upload:*"));
        assert!(check_import("blob-upload").is_err());
        assert!(check_import("blob-upload:read").is_err());
        assert!(check_import("blob-upload:*").is_err());
    }

    #[test]
    fn handler_config_with_a_blob_upload_import_passes_check_import() {
        // Part 5b: the offline validator must accept a manifest declaring the blob-upload grant — the
        // gap that blocked construens' manifest before the runtime (which honors the grant) is even
        // reached. `DeployConfig::from_ron` runs `check_import` for every handler import, so a config
        // carrying `imports: ["blob-upload:write"]` now parses.
        let text = r#"(
            handlers: [
                ( route: "/api/upload", methods: ["POST"],
                  component: "handlers/upload.wasm",
                  imports: ["blob-upload:write", "blob-upload:multipart"],
                  upload_containers: ["assets-{tenant}"] ),
            ],
        )"#;
        let config = DeployConfig::from_ron(text).expect("a blob-upload manifest now parses");
        assert_eq!(
            config.handlers[0].imports,
            vec![
                "blob-upload:write".to_string(),
                "blob-upload:multipart".to_string()
            ]
        );
        assert_eq!(
            config.handlers[0].upload_containers,
            vec!["assets-{tenant}".to_string()]
        );
    }

    #[test]
    fn proxy_allow_list_matching() {
        // Empty list permits any host (the IP guard still applies separately).
        assert!(DeployConfig::default().proxy_host_allowed("anything.example"));

        let cfg = DeployConfig {
            proxy_allow: vec!["api.example.com".into(), ".internal.test".into()],
            ..DeployConfig::default()
        };
        assert!(cfg.proxy_host_allowed("api.example.com")); // exact
        assert!(cfg.proxy_host_allowed("API.EXAMPLE.COM")); // case-insensitive
        assert!(cfg.proxy_host_allowed("a.internal.test")); // suffix
        assert!(cfg.proxy_host_allowed("internal.test")); // suffix apex
        assert!(!cfg.proxy_host_allowed("evil.com"));
        assert!(!cfg.proxy_host_allowed("notapi.example.com"));
    }

    #[test]
    fn parses_handler_config() {
        let text = r#"(
            handlers: [
                ( route: "/api/orders/*", methods: ["GET", "POST"],
                  component: "handlers/orders.wasm",
                  imports: ["sql", "wasi:keyvalue", "wasi:messaging", "messaging-stats"],
                  stats_topics: ["bus:sync/{tenant}/import"],
                  limits: ( memory_mb: 64, timeout_ms: 10000 ),
                  env: { "LOG_LEVEL": "info" } ),
            ],
            consumers: [
                ( topic: "orders/created", component: "handlers/agg.wasm",
                  imports: ["sql", "messaging-stats"],
                  stats_topics: ["bus:sync/{tenant}/import"] ),
            ],
            crons: [ ( schedule: "0 */6 * * *", route: "/api/orders/reindex", overlap: Skip ) ],
            streams: [ ( route: "/events/orders", topics: ["orders/created"] ) ],
        )"#;
        let config = DeployConfig::from_ron(text).unwrap();
        assert_eq!(config.handlers.len(), 1);
        assert_eq!(config.handlers[0].imports.len(), 4);
        assert_eq!(
            config.handlers[0].limits.as_ref().unwrap().memory_mb,
            Some(64)
        );
        // The new `messaging-stats` bus-topic template parses (and the `messaging-stats` import is
        // accepted by `check_import`, which `DeployConfig::from_ron` runs).
        assert_eq!(
            config.handlers[0].stats_topics,
            vec!["bus:sync/{tenant}/import".to_string()]
        );
        assert_eq!(config.consumers.len(), 1);
        assert_eq!(
            config.consumers[0].stats_topics,
            vec!["bus:sync/{tenant}/import".to_string()]
        );
        assert_eq!(config.crons[0].overlap, Overlap::Skip);
        assert_eq!(config.streams[0].topics, vec!["orders/created".to_string()]);
    }

    #[test]
    fn site_config_round_trips_through_json_and_ron() {
        // A fully-populated SiteConfig, exercising the newer handler sub-configs (cache,
        // graphql, cookie_auth) that the API stores and returns. `SiteConfig` has
        // `deny_unknown_fields`, so any serde drift — a field that serializes under one name
        // but deserializes under another, or one that silently drops — makes the round-trip
        // fail to parse or fail equality. This is the guard for the "config field doesn't
        // round-trip" class (write a config, can't read it back).
        let cfg = SiteConfig {
            handlers: Some(HandlersSiteConfig {
                enabled: true,
                allow_imports: vec!["sql".into(), "graphql".into()],
                cache: Some(HandlerCacheConfig {
                    enabled: true,
                    max_entry_bytes: Some(262_144),
                    max_ttl_secs: Some(600),
                }),
                graphql: Some(HandlerGraphqlConfig {
                    enabled: true,
                    federated: true,
                    max_depth: Some(12),
                    enforce_safelist: true,
                    ..Default::default()
                }),
                cookie_auth: Some(CookieAuthConfig {
                    cookie_name: "__Host-session".into(),
                    allowed_origins: vec!["https://app.example.com".into()],
                }),
                ..Default::default()
            }),
            ..Default::default()
        };

        // JSON is the API wire format (PUT/GET /api/sites/:site/config); `from_json` is the
        // parser the server uses, so this exercises the exact path.
        let json = serde_json::to_vec(&cfg).unwrap();
        let from_json = SiteConfig::from_json(&json)
            .unwrap_or_else(|e| panic!("SiteConfig JSON round-trip failed to parse: {e}"));
        assert_eq!(
            from_json, cfg,
            "SiteConfig did not survive a JSON round-trip"
        );

        // And RON (via the derived Deserialize), the on-disk config format.
        let ron = ron::ser::to_string(&cfg).unwrap();
        let from_ron: SiteConfig = ron::from_str(&ron)
            .unwrap_or_else(|e| panic!("SiteConfig RON round-trip failed to parse: {e}\n{ron}"));
        assert_eq!(from_ron, cfg, "SiteConfig did not survive a RON round-trip");
    }

    #[test]
    fn handler_validation_rejects_bad_config() {
        // Unknown import.
        assert!(
            DeployConfig::from_ron(
                r#"( handlers: [ ( route: "/a", component: "a.wasm", imports: ["wasi:gpu"] ) ] )"#
            )
            .is_err()
        );
        // Bad HTTP method: not an RFC 7230 token (embedded space). `FETCH` is now accepted
        // as an extension verb — only a NON-token method is rejected (see
        // `http_methods_accept_tokens_reject_non_tokens`).
        assert!(
            DeployConfig::from_ron(
                r#"( handlers: [ ( route: "/a", component: "a.wasm", methods: ["GET THING"] ) ] )"#
            )
            .is_err()
        );
        // Cron route not served by any handler.
        assert!(
            DeployConfig::from_ron(
                r#"( handlers: [ ( route: "/a", component: "a.wasm" ) ],
                 crons: [ ( schedule: "* * * * *", route: "/nope" ) ] )"#
            )
            .is_err()
        );
        // A cron whose route IS served validates.
        assert!(
            DeployConfig::from_ron(
                r#"( handlers: [ ( route: "/tasks/*", component: "a.wasm" ) ],
                 crons: [ ( schedule: "0 0 * * *", route: "/tasks/x" ) ] )"#
            )
            .is_ok()
        );
    }

    #[test]
    fn http_methods_accept_tokens_reject_non_tokens() {
        // Standard verbs.
        for m in STANDARD_METHODS {
            assert!(
                check_http_method(m).is_ok(),
                "standard verb {m} must validate"
            );
        }
        // Extension (WebDAV / CalDAV / CardDAV) verbs — all valid RFC 7230 tokens.
        for m in [
            "PROPFIND",
            "PROPPATCH",
            "REPORT",
            "MKCALENDAR",
            "MKCOL",
            "MOVE",
            "COPY",
            "ACL", // a token with only ALPHA
        ] {
            assert!(
                check_http_method(m).is_ok(),
                "extension verb {m} must validate"
            );
        }
        // The explicit `*` catch-all validates.
        assert!(check_http_method(METHOD_WILDCARD).is_ok());
        // Non-token methods are rejected (no injection via the method string).
        for bad in [
            "",            // empty
            "GET THING",   // space
            "GE/T",        // separator `/`
            "GET\r\nHost", // CR/LF (request smuggling)
            "GET\tX",      // TAB
            "G(ET)",       // separators `(` `)`
            "GET;X",       // separator `;`
            "GET@X",       // separator `@`
        ] {
            assert!(
                check_http_method(bad).is_err(),
                "non-token method {bad:?} must be rejected"
            );
        }
    }

    #[test]
    fn cron_schedule_validation() {
        for ok in [
            "* * * * *",
            "0 */6 * * *",
            "30 2 1 1 0",
            "0,15,30,45 9-17 * * 1-5",
        ] {
            assert!(check_cron_schedule(ok).is_ok(), "{ok} should be valid");
        }
        for bad in [
            "* * * *",     // 4 fields
            "60 * * * *",  // minute out of range
            "* 24 * * *",  // hour out of range
            "* * 0 * *",   // dom < 1
            "* * * 13 *",  // month > 12
            "*/0 * * * *", // zero step
            "5-1 * * * *", // descending range
        ] {
            assert!(check_cron_schedule(bad).is_err(), "{bad} should be invalid");
        }
    }

    #[test]
    fn handler_free_config_omits_handler_fields() {
        // A static-only deploy serializes without any handler keys (so existing
        // manifest ids are unchanged).
        let json = serde_json::to_string(&DeployConfig::default()).unwrap();
        assert!(!json.contains("handlers"));
        assert!(!json.contains("crons"));
    }

    #[test]
    fn schema_version_defaults_to_one() {
        // Optional in RON; defaults to 1.
        assert_eq!(DeployConfig::from_ron("()").unwrap().version, 1);
        assert_eq!(DeployConfig::from_ron("(version: 1)").unwrap().version, 1);
        assert_eq!(SiteConfig::default().version, 1);
        // A version-less stored SiteConfig still reads as v1.
        assert_eq!(SiteConfig::from_json(b"{}").unwrap().version, 1);
    }

    #[test]
    fn system_when_requires_an_exact_trusted_issuer_s0() {
        // PLAN-system-principal S0: `system_when` may confer the node-wide system class ONLY for an
        // EXACT, operator-named issuer. Prove every acceptance/refusal fork of the apply-time guard.
        let sw = |iss: &str| SystemWhen {
            issuer: iss.into(),
            claim: "role".into(),
            equals: "super_admin".into(),
        };

        // Single-issuer form: system_when.issuer must equal the single `issuer` exactly.
        let mut single = HandlerGraphqlTokenClaims {
            issuer: "https://admin.acme.example".into(),
            jwks_env: Some("ADMIN_JWKS".into()),
            system_when: Some(sw("https://admin.acme.example")),
            ..Default::default()
        };
        single
            .validate()
            .expect("exact single issuer confers system");
        // A different issuer than the single one is refused.
        single.system_when = Some(sw("https://other.example"));
        assert!(
            single.validate().is_err(),
            "non-matching single issuer must be refused"
        );

        // Multi-issuer form: only a member of `issuer_trust.allow` — NEVER a `suffix`-matched issuer.
        let multi = |iss: &str| HandlerGraphqlTokenClaims {
            issuer_trust: Some(IssuerTrust {
                allow: vec!["https://admin.acme.example".into()],
                suffix: Some(".my.salesforce.com".into()),
            }),
            jwks: Some(JwksDiscovery {
                template: Some("{iss}/id/keys".into()),
                ..Default::default()
            }),
            system_when: Some(sw(iss)),
            ..Default::default()
        };
        multi("https://admin.acme.example")
            .validate()
            .expect("an issuer in `allow` confers system");
        // S0 the load-bearing refusal: a suffix-covered issuer is trusted for a TENANT but can never
        // mint system, even though it would pass the suffix policy at verify time.
        assert!(
            multi("https://evilorg.my.salesforce.com")
                .validate()
                .is_err(),
            "a suffix-matched issuer must NEVER be allowed to mint the system principal (S0)"
        );
        // Empty issuer / empty equals are refused.
        let mut bad = multi("https://admin.acme.example");
        bad.system_when = Some(SystemWhen {
            issuer: String::new(),
            claim: "role".into(),
            equals: "x".into(),
        });
        assert!(bad.validate().is_err(), "empty system_when.issuer refused");
        bad.system_when = Some(SystemWhen {
            issuer: "https://admin.acme.example".into(),
            claim: "role".into(),
            equals: String::new(),
        });
        assert!(bad.validate().is_err(), "empty system_when.equals refused");
    }

    #[test]
    fn system_when_round_trips_and_defaults_the_claim_to_role() {
        // The `claim` defaults to `role`; absent system_when round-trips to None (byte-identical).
        let bare: HandlerGraphqlTokenClaims =
            serde_json::from_str(r#"{"issuer":"https://a.example"}"#).unwrap();
        assert!(bare.system_when.is_none());
        let with: HandlerGraphqlTokenClaims = serde_json::from_str(
            r#"{"issuer":"https://a.example","system_when":{"issuer":"https://a.example","equals":"super_admin"}}"#,
        )
        .unwrap();
        let sw = with.system_when.as_ref().unwrap();
        assert_eq!(sw.claim, "role", "claim defaults to `role`");
        assert_eq!(sw.equals, "super_admin");
        let reparsed: HandlerGraphqlTokenClaims =
            serde_json::from_str(&serde_json::to_string(&with).unwrap()).unwrap();
        assert_eq!(reparsed.system_when, with.system_when);
    }
}