dekopon-http-host 0.46.2

Statically linked bounded HTTP primitive for Dekopon broker hosts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
//! Every response from a credentialed context is checked for the raw or encoded secret and refused
//! as Denied rather than returned to the component.

#![forbid(unsafe_code)]
#![cfg_attr(test, allow(clippy::unwrap_used))]
#![cfg_attr(
    test,
    allow(
        clippy::disallowed_methods,
        clippy::disallowed_types,
        reason = "tests spawn, join and drain freely; production sites carry their own expectation"
    )
)]
pub mod asset;
mod stream;
pub use stream::{
    CHUNK_BYTES, FilePart, Part, Representation, StreamedRequest, StreamedResponse, read_decoded,
};

use std::{
    borrow::Cow,
    collections::{BTreeSet, HashMap},
    error::Error as _,
    fmt,
    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
    sync::Arc,
    time::Duration,
};

use base64::{Engine as _, engine::general_purpose::STANDARD};
use dekopon_capability::{
    ChatSlotValues, HttpConstraints, HttpConstraintsError, PathSegment, SecretUseGrant,
};
use dekopon_core::{Redacted, SecretBytes, SecretSinkKind};
use reqwest::{
    Method, Url,
    header::{ACCEPT_ENCODING, AUTHORIZATION, HeaderMap, HeaderName, HeaderValue},
    redirect,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::time::{Instant, timeout};
use tracing::Instrument as _;

const DEFAULT_HTTPS_PORT: u16 = 443;
const CHATGPT_ACCOUNT_HEADER: &str = "chatgpt-account-id";
const MAX_ERROR_MESSAGE_BYTES: usize = 256;
const MAX_RESOLVED_ADDRESSES: usize = 16;
const REQUEST_ENCODING_OVERHEAD_BYTES: u64 = 128;

pub const DEFAULT_MAX_REQUESTS: u32 = 32;
pub const DEFAULT_MAX_REQUEST_BYTES: u64 = 1024 * 1024;
pub const DEFAULT_MAX_RESPONSE_BYTES: u64 = 4 * 1024 * 1024;
pub const DEFAULT_MAX_HEADERS: usize = 128;
pub const DEFAULT_MAX_HEADER_BYTES: usize = 64 * 1024;
pub const MAX_CREDENTIAL_BYTES: usize = 4096;
/// The minimum is 16 bytes because the echo check substring-searches every response, and a shorter
/// secret like token would falsely match unrelated text.
pub const MIN_CREDENTIAL_BYTES: usize = 16;
const _: () = assert!(MIN_CREDENTIAL_BYTES == 16);

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Header {
    pub name: String,
    pub value: Vec<u8>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Request {
    pub method: String,
    pub uri: String,
    pub headers: Vec<Header>,
    pub body: Vec<u8>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Response {
    pub status: u16,
    pub headers: Vec<Header>,
    pub body: Vec<u8>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ErrorCode {
    InvalidMethod,
    InvalidUri,
    InvalidHeader,
    RequestTooLarge,
    Denied,
    HostCallLimit,
    Dns,
    Connect,
    Tls,
    Timeout,
    Protocol,
    ResponseTooLarge,
    Internal,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HttpError {
    pub code: ErrorCode,
    pub message: String,
}

impl fmt::Display for HttpError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{:?}: {}", self.code, self.message)
    }
}

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

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PlaintextHosts {
    hosts: Arc<BTreeSet<String>>,
}

impl PlaintextHosts {
    pub fn new<I>(entries: I) -> Result<Self, PlaintextHostError>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        let mut hosts = BTreeSet::new();
        for entry in entries {
            let entry = entry.as_ref().trim();
            if entry.is_empty() {
                return Err(PlaintextHostError::Empty);
            }
            let owned = || entry.to_owned();
            if entry.contains("://") {
                return Err(PlaintextHostError::Scheme { entry: owned() });
            }
            if entry.contains('*') {
                return Err(PlaintextHostError::Wildcard { entry: owned() });
            }
            if entry.contains('/') {
                return Err(PlaintextHostError::Path { entry: owned() });
            }
            if entry.contains(':') {
                return Err(PlaintextHostError::Port { entry: owned() });
            }
            if !is_bare_hostname(entry) {
                return Err(PlaintextHostError::InvalidHost { entry: owned() });
            }
            hosts.insert(entry.to_ascii_lowercase());
        }
        Ok(Self {
            hosts: Arc::new(hosts),
        })
    }

    #[must_use]
    pub fn contains(&self, host: &str) -> bool {
        self.hosts.contains(host.to_ascii_lowercase().as_str())
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.hosts.is_empty()
    }

    pub fn iter(&self) -> impl ExactSizeIterator<Item = &str> {
        self.hosts.iter().map(String::as_str)
    }
}

#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum PlaintextHostError {
    #[error("a plaintext host entry is empty")]
    Empty,
    #[error("plaintext host `{entry}` must be a bare hostname, without a scheme")]
    Scheme { entry: String },
    #[error("plaintext host `{entry}` must be a bare hostname, without a path")]
    Path { entry: String },
    #[error("plaintext host `{entry}` must carry no port: the port is irrelevant to this rule")]
    Port { entry: String },
    #[error("plaintext host `{entry}` must be an exact hostname: wildcards are not accepted")]
    Wildcard { entry: String },
    #[error("plaintext host `{entry}` is not a hostname")]
    InvalidHost { entry: String },
}

fn is_bare_hostname(entry: &str) -> bool {
    entry
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'.')
        && !entry.starts_with(['-', '.'])
        && !entry.ends_with(['-', '.'])
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NonPublicHttpsAuthority {
    pub authority: String,
}

impl NonPublicHttpsAuthority {
    pub fn new(authority: &str) -> Result<Self, &'static str> {
        let url = Url::parse(&format!("https://{authority}"))
            .map_err(|_error| "authority must be a DNS hostname and explicit port")?;
        let host = url.host_str().ok_or("authority must have a hostname")?;
        if url.username() != ""
            || url.password().is_some()
            || url.path() != "/"
            || url.query().is_some()
            || url.fragment().is_some()
            || url.port().is_none()
            || !is_bare_hostname(host)
            || host.parse::<IpAddr>().is_ok()
            || !authority
                .eq_ignore_ascii_case(&format!("{host}:{}", url.port().unwrap_or_default()))
        {
            return Err("authority must be an exact DNS hostname and explicit port");
        }
        Ok(Self {
            authority: authority.to_ascii_lowercase(),
        })
    }
}

/// Explicit HTTPS test destination pinned to loopback and a dedicated trust root.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LoopbackHttpsPin {
    authority: String,
    address: SocketAddr,
    ca_pem: Vec<u8>,
}

impl LoopbackHttpsPin {
    pub fn new(
        authority: &str,
        address: SocketAddr,
        ca_pem: Vec<u8>,
    ) -> Result<Self, &'static str> {
        let target = NonPublicHttpsAuthority::new(authority)?;
        if !address.ip().is_loopback()
            || address.port().to_string() != authority.rsplit(':').next().unwrap_or("")
            || ca_pem.is_empty()
        {
            return Err("test pin requires an exact loopback HTTPS authority and CA");
        }
        Ok(Self {
            authority: target.authority,
            address,
            ca_pem,
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HttpHostCeilings {
    pub max_requests: u32,
    pub max_request_bytes: u64,
    pub max_response_bytes: u64,
    pub max_headers: usize,
    pub max_header_bytes: usize,
    pub plaintext_hosts: PlaintextHosts,
    pub extra_ca_bundles: Arc<Vec<Vec<u8>>>,
    pub non_public_https: Arc<Vec<NonPublicHttpsAuthority>>,
    pub loopback_https_pin: Option<LoopbackHttpsPin>,
}

impl Default for HttpHostCeilings {
    fn default() -> Self {
        Self {
            max_requests: DEFAULT_MAX_REQUESTS,
            max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
            max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
            max_headers: DEFAULT_MAX_HEADERS,
            max_header_bytes: DEFAULT_MAX_HEADER_BYTES,
            plaintext_hosts: PlaintextHosts::default(),
            extra_ca_bundles: Arc::new(Vec::new()),
            non_public_https: Arc::new(Vec::new()),
            loopback_https_pin: None,
        }
    }
}

#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum ConfigurationError {
    #[error("HTTP host ceiling {field} must be greater than zero")]
    ZeroCeiling { field: &'static str },
    #[error("HTTP authorization is not exact: {source}")]
    InvalidGrant {
        #[source]
        source: HttpConstraintsError,
    },
    #[error("HTTP authorization exceeds native host ceilings")]
    GrantExceedsCeiling,
    #[error("HTTP execution deadline must be greater than zero")]
    ZeroTimeout,
    #[error("HTTP execution deadline is too large")]
    TimeoutOverflow,
    #[error("secret-use grant is invalid")]
    InvalidSecretGrant {
        #[source]
        source: dekopon_capability::SecretUseGrantError,
    },
    #[error("bound credential is invalid: {reason}")]
    InvalidCredential { reason: &'static str },
}

/// This lets an agent use a credential without ever seeing it: the value stays in a Redacted
/// wrapper end to end, and a guest-supplied authorization header is rejected, never overwritten.
#[derive(Clone)]
pub struct BoundCredential {
    header_value: Redacted<String>,
    companion_header: Option<(HeaderName, Redacted<String>)>,
    destinations: Vec<String>,
    secret_binding: Option<SecretBindingIdentity>,
    echo_values: Vec<SecretBytes>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct SecretBindingIdentity {
    grant: SecretUseGrant,
}

impl fmt::Debug for BoundCredential {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("BoundCredential")
            .field("header_value", &self.header_value)
            .field(
                "companion_header",
                &self
                    .companion_header
                    .as_ref()
                    .map(|(name, value)| (name, value)),
            )
            .field("destinations", &self.destinations)
            .field("secret_binding", &self.secret_binding.is_some())
            .field("echo_values", &self.echo_values)
            .finish()
    }
}

impl BoundCredential {
    pub fn bearer(
        scheme: &str,
        secret: Redacted<String>,
        destinations: Vec<String>,
    ) -> Result<Self, ConfigurationError> {
        let invalid = |reason| ConfigurationError::InvalidCredential { reason };
        if scheme.is_empty() || !scheme.bytes().all(|byte| byte.is_ascii_graphic()) {
            return Err(invalid("scheme must be a printable ASCII token"));
        }
        {
            let value = secret.expose();
            if value.len() < MIN_CREDENTIAL_BYTES {
                return Err(invalid("secret is shorter than the 16-byte minimum"));
            }
            if value.len() > MAX_CREDENTIAL_BYTES {
                return Err(invalid("secret exceeds the credential byte limit"));
            }
            if !value.bytes().all(|byte| byte.is_ascii_graphic()) {
                return Err(invalid(
                    "secret contains whitespace, control, or non-ASCII bytes",
                ));
            }
        }
        if destinations.is_empty() {
            return Err(invalid("at least one destination is required"));
        }
        if !destinations
            .iter()
            .all(|destination| is_destination_scope(destination))
        {
            return Err(invalid(
                "destinations must be host or host:port authorities",
            ));
        }
        let echo_value = SecretBytes::new(secret.expose().as_bytes().to_vec());
        let header_value = Redacted::new(format!("{scheme} {}", secret.expose()));
        Ok(Self {
            header_value,
            companion_header: None,
            destinations,
            secret_binding: None,
            echo_values: vec![echo_value],
        })
    }

    pub fn chatgpt_subscription(
        access: Redacted<String>,
        account_id: &str,
        destinations: Vec<String>,
    ) -> Result<Self, ConfigurationError> {
        let invalid = |reason| ConfigurationError::InvalidCredential { reason };
        if account_id.is_empty()
            || account_id.len() > MAX_CREDENTIAL_BYTES
            || !account_id.bytes().all(|byte| byte.is_ascii_graphic())
        {
            return Err(invalid(
                "ChatGPT account identifier must be a printable ASCII token",
            ));
        }
        let mut credential = Self::bearer("Bearer", access, destinations)?;
        credential.companion_header = Some((
            HeaderName::from_static(CHATGPT_ACCOUNT_HEADER),
            Redacted::new(account_id.to_owned()),
        ));
        Ok(credential)
    }

    pub fn secret_bearer(
        secret: SecretBytes,
        grant: &SecretUseGrant,
    ) -> Result<Self, ConfigurationError> {
        if grant.sink != SecretSinkKind::HttpBearer || grant.basic_username.is_some() {
            return Err(ConfigurationError::InvalidCredential {
                reason: "Bearer material does not match the secret-use sink",
            });
        }
        #[allow(
            clippy::map_err_ignore,
            reason = "Utf8Error carries the secret-derived invalid byte offset and valid prefix \
                      length; the fixed structural refusal must not expose either"
        )]
        let token = std::str::from_utf8(secret.expose()).map_err(|_| {
            ConfigurationError::InvalidCredential {
                reason: "Bearer secret must be UTF-8",
            }
        })?;
        if token.len() < MIN_CREDENTIAL_BYTES {
            return Err(ConfigurationError::InvalidCredential {
                reason: "Bearer secret is shorter than the 16-byte minimum",
            });
        }
        if token.len() > MAX_CREDENTIAL_BYTES
            || token
                .bytes()
                .any(|byte| byte.is_ascii_control() || byte.is_ascii_whitespace())
        {
            return Err(ConfigurationError::InvalidCredential {
                reason: "Bearer secret must be a bounded token without whitespace or controls",
            });
        }
        let rendered = format!("Bearer {token}");
        Ok(Self {
            header_value: Redacted::new(rendered),
            companion_header: None,
            destinations: grant.allowed_hosts.clone(),
            secret_binding: Some(SecretBindingIdentity {
                grant: grant.clone(),
            }),
            echo_values: vec![secret],
        })
    }

    pub fn secret_basic(
        password: SecretBytes,
        grant: &SecretUseGrant,
    ) -> Result<Self, ConfigurationError> {
        let Some(username) = grant.basic_username.as_deref() else {
            return Err(ConfigurationError::InvalidCredential {
                reason: "Basic secret use requires a fixed username",
            });
        };
        if password.expose().len() < MIN_CREDENTIAL_BYTES {
            return Err(ConfigurationError::InvalidCredential {
                reason: "Basic secret is shorter than the 16-byte minimum",
            });
        }
        if grant.sink != SecretSinkKind::HttpBasic
            || username.is_empty()
            || username.contains(':')
            || username.bytes().any(|byte| byte.is_ascii_control())
            || password.expose().len() > MAX_CREDENTIAL_BYTES
            || password.expose().contains(&b'\n')
            || password.expose().contains(&b'\r')
        {
            return Err(ConfigurationError::InvalidCredential {
                reason: "Basic credential fields are structurally invalid",
            });
        }
        let mut pair = Vec::with_capacity(username.len() + 1 + password.expose().len());
        pair.extend_from_slice(username.as_bytes());
        pair.push(b':');
        pair.extend_from_slice(password.expose());
        let encoded = STANDARD.encode(&pair);
        let rendered = format!("Basic {encoded}");
        Ok(Self {
            header_value: Redacted::new(rendered),
            companion_header: None,
            destinations: grant.allowed_hosts.clone(),
            secret_binding: Some(SecretBindingIdentity {
                grant: grant.clone(),
            }),
            echo_values: vec![password, SecretBytes::new(encoded.into_bytes())],
        })
    }

    #[must_use]
    pub fn destinations(&self) -> &[String] {
        &self.destinations
    }

    #[must_use]
    pub fn covers(&self, allowed_host: &str) -> bool {
        destinations_cover(&self.destinations, allowed_host)
    }

    fn matches(&self, host: &str, port: u16, scheme: &str) -> bool {
        self.destinations
            .iter()
            .any(|destination| authority_matches(destination, host, port, scheme))
    }

    #[must_use]
    pub fn matches_secret_grant(&self, grant: Option<&SecretUseGrant>) -> bool {
        match (&self.secret_binding, grant) {
            (None, None) => true,
            (Some(identity), Some(grant)) => &identity.grant == grant,
            _ => false,
        }
    }

    /// Appends `bytes` behind the held tail and scans the window. `None` is an echo; otherwise the
    /// count of leading window bytes that no later byte can complete into a secret, leaving
    /// exactly `overlap` bytes held.
    fn scan_stream_chunk(
        &self,
        window: &mut Vec<u8>,
        bytes: &[u8],
        overlap: usize,
    ) -> Option<usize> {
        window.extend_from_slice(bytes);
        if self
            .echo_values
            .iter()
            .any(|secret| !secret.expose().is_empty() && contains_bytes(window, secret.expose()))
        {
            return None;
        }
        Some(window.len() - window.len().min(overlap))
    }

    fn echo_overlap(&self) -> usize {
        self.echo_values
            .iter()
            .map(|secret| secret.expose().len().saturating_sub(1))
            .max()
            .unwrap_or(0)
    }

    fn echoes_credential(&self, response: &Response) -> bool {
        self.echo_values.iter().any(|secret| {
            let secret = secret.expose();
            !secret.is_empty()
                && (contains_bytes(&response.body, secret)
                    || response.headers.iter().any(|header| {
                        contains_bytes(header.name.as_bytes(), secret)
                            || contains_bytes(&header.value, secret)
                    }))
        })
    }

    fn render(&self) -> Result<HeaderValue, HttpError> {
        #[allow(
            clippy::map_err_ignore,
            reason = "`InvalidHeaderValue` reports only that parsing failed, and `bearer` already \
                      restricted these bytes to ASCII graphic; nothing derived from a credential \
                      value may be reported anyway"
        )]
        let mut value = HeaderValue::from_str(self.header_value.expose())
            .map_err(|_| http_error(ErrorCode::Internal, "credential could not be rendered"))?;
        value.set_sensitive(true);
        Ok(value)
    }

    fn companion_name(&self) -> Option<&HeaderName> {
        self.companion_header.as_ref().map(|(name, _)| name)
    }

    fn render_companion(&self) -> Option<Result<(HeaderName, HeaderValue), HttpError>> {
        let (name, value) = self.companion_header.as_ref()?;
        #[allow(
            clippy::map_err_ignore,
            reason = "`InvalidHeaderValue` reports only that parsing failed, and the constructor \
                      already restricted these bytes to ASCII graphic; nothing derived from a \
                      credential value may be reported anyway"
        )]
        let rendered = HeaderValue::from_str(value.expose())
            .map_err(|_| http_error(ErrorCode::Internal, "credential could not be rendered"));
        Some(rendered.map(|mut rendered| {
            rendered.set_sensitive(true);
            (name.clone(), rendered)
        }))
    }
}

/// This must agree exactly with BoundCredential's own coverage check, since a divergence would let
/// the policy layer accept a host the runtime injector then refuses.
#[must_use]
pub fn destinations_cover(destinations: &[String], allowed_host: &str) -> bool {
    let allowed = allowed_host.trim().to_ascii_lowercase();
    destinations
        .iter()
        .any(|destination| destination.trim().to_ascii_lowercase() == allowed)
}

fn is_destination_scope(value: &str) -> bool {
    !value.is_empty()
        && value.trim() == value
        && !value
            .bytes()
            .any(|byte| byte.is_ascii_control() || byte.is_ascii_whitespace())
        && !value.contains(['/', '?', '#', '@', '*'])
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct HttpCallEvidence {
    pub method: String,
    pub authority: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<u16>,
    /// request_bytes deliberately excludes any broker-injected credential header, since its length
    /// must not leak into evidence or cost the guest's byte grant.
    pub request_bytes: u64,
    pub response_bytes: u64,
    #[serde(default, skip_serializing_if = "is_false")]
    pub credential_injected: bool,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(value: &bool) -> bool {
    !*value
}

fn contains_bytes(bytes: &[u8], value: &[u8]) -> bool {
    !value.is_empty() && bytes.windows(value.len()).any(|window| window == value)
}

fn secret_raw_path_is_ambiguous(uri: &str) -> bool {
    let Some((_, authority_and_path)) = uri.split_once("://") else {
        return true;
    };
    if authority_and_path.contains('\\') {
        return true;
    }
    let raw_path = authority_and_path
        .find('/')
        .map_or("/", |index| &authority_and_path[index..]);
    let raw_path = raw_path.split_once('?').map_or(raw_path, |(path, _)| path);
    let raw_path = raw_path.split_once('#').map_or(raw_path, |(path, _)| path);
    raw_path.contains('%')
        || raw_path.contains("//")
        || raw_path
            .split('/')
            .skip(1)
            .any(|segment| matches!(segment, "." | ".."))
}

#[derive(Debug)]
pub struct BufferedHttpClient {
    grant: Option<HttpConstraints>,
    secret_grant: Option<SecretUseGrant>,
    credential: Option<BoundCredential>,
    slots: ChatSlotValues,
    ceilings: HttpHostCeilings,
    timeout: Duration,
    deadline: Instant,
    calls: u32,
    secret_injections: u32,
    attempted: bool,
    policy_violation: Option<&'static str>,
    asset_over_budget: bool,
    evidence: Vec<HttpCallEvidence>,
    resolved: HashMap<String, Vec<SocketAddr>>,
    pinned_client: Option<PinnedClient>,
}

#[derive(Debug)]
struct PinnedClient {
    host: String,
    addresses: Vec<SocketAddr>,
    client: reqwest::Client,
}

impl BufferedHttpClient {
    pub fn disabled(
        ceilings: HttpHostCeilings,
        timeout: Duration,
    ) -> Result<Self, ConfigurationError> {
        validate_configuration(None, &ceilings, timeout)?;
        Self::new(None, None, None, ceilings, timeout)
    }

    pub fn authorized(
        grant: HttpConstraints,
        ceilings: HttpHostCeilings,
        timeout: Duration,
    ) -> Result<Self, ConfigurationError> {
        validate_configuration(Some(&grant), &ceilings, timeout)?;
        Self::new(Some(grant), None, None, ceilings, timeout)
    }

    pub fn authorized_with_credential(
        grant: HttpConstraints,
        credential: Option<BoundCredential>,
        ceilings: HttpHostCeilings,
        timeout: Duration,
    ) -> Result<Self, ConfigurationError> {
        validate_configuration(Some(&grant), &ceilings, timeout)?;
        if credential
            .as_ref()
            .is_some_and(|credential| !credential.matches_secret_grant(None))
        {
            return Err(ConfigurationError::InvalidCredential {
                reason: "DRN-bound credential requires an authorization-bound secret grant",
            });
        }
        Self::new(Some(grant), None, credential, ceilings, timeout)
    }

    pub fn authorized_with_secret_credential(
        grant: HttpConstraints,
        secret_grant: SecretUseGrant,
        credential: BoundCredential,
        ceilings: HttpHostCeilings,
        timeout: Duration,
    ) -> Result<Self, ConfigurationError> {
        validate_configuration(Some(&grant), &ceilings, timeout)?;
        secret_grant
            .validate()
            .map_err(|source| ConfigurationError::InvalidSecretGrant { source })?;
        if !credential.matches_secret_grant(Some(&secret_grant)) {
            return Err(ConfigurationError::InvalidCredential {
                reason: "resolved credential does not match the authorization-bound secret grant",
            });
        }
        Self::new(
            Some(grant),
            Some(secret_grant),
            Some(credential),
            ceilings,
            timeout,
        )
    }

    fn new(
        grant: Option<HttpConstraints>,
        secret_grant: Option<SecretUseGrant>,
        credential: Option<BoundCredential>,
        ceilings: HttpHostCeilings,
        timeout: Duration,
    ) -> Result<Self, ConfigurationError> {
        let deadline = Instant::now()
            .checked_add(timeout)
            .ok_or(ConfigurationError::TimeoutOverflow)?;
        Ok(Self {
            grant,
            secret_grant,
            credential,
            slots: ChatSlotValues::default(),
            ceilings,
            timeout,
            deadline,
            calls: 0,
            secret_injections: 0,
            attempted: false,
            policy_violation: None,
            asset_over_budget: false,
            evidence: Vec::new(),
            resolved: HashMap::new(),
            pinned_client: None,
        })
    }

    #[must_use]
    pub fn with_chat_slots(mut self, slots: ChatSlotValues) -> Self {
        self.slots = slots;
        self
    }

    pub fn asset_over_budget(&self) -> bool {
        self.asset_over_budget
    }

    pub fn attempted(&self) -> bool {
        self.attempted
    }

    pub fn policy_violation(&self) -> Option<&'static str> {
        self.policy_violation
    }

    pub fn into_evidence(self) -> Vec<HttpCallEvidence> {
        self.evidence
    }

    pub async fn send(&mut self, request: Request) -> Result<Response, HttpError> {
        let span = tracing::info_span!(
            "http.request",
            "http.request.method" = tracing::field::Empty,
            "server.address" = tracing::field::Empty,
            "http.response.status_code" = tracing::field::Empty,
            "dekopon.http.request.accounted_bytes" = tracing::field::Empty,
            "dekopon.http.response.accounted_bytes" = tracing::field::Empty,
            "error.code" = tracing::field::Empty,
            "error.message" = tracing::field::Empty,
            "url.full" = tracing::field::Empty,
            outcome = tracing::field::Empty,
        );
        span.record("url.full", request.uri.as_str());

        let evidence_index = self.evidence.len();
        self.attempted = true;
        // This must use instrument, not enter: holding an entered guard across these awaits would
        // leave the span current on whatever thread happens to poll unrelated tasks.
        let result = self.send_checked(request).instrument(span.clone()).await;

        self.record_request(&span, evidence_index, &result);
        result
    }

    fn record_request<T>(
        &mut self,
        span: &tracing::Span,
        evidence_index: usize,
        result: &Result<T, HttpError>,
    ) {
        let outcome = outcome_label(result);
        let failure = result.as_ref().err();
        span.in_scope(|| {
            let evidence = self.evidence.get(evidence_index);
            if let Some(evidence) = evidence {
                span.record("http.request.method", evidence.method.as_str());
                span.record("server.address", evidence.authority.as_str());
                span.record(
                    "dekopon.http.request.accounted_bytes",
                    evidence.request_bytes,
                );
                span.record(
                    "dekopon.http.response.accounted_bytes",
                    evidence.response_bytes,
                );
                if let Some(status) = evidence.status {
                    span.record("http.response.status_code", status);
                }
            }
            if let Some(error) = failure {
                // Recording the error reason is safe only because every message this crate produces
                // is a static, pre-sanitized string; that property must be preserved.
                span.record("error.code", tracing::field::debug(error.code));
                span.record("error.message", error.message.as_str());
            }
            span.record("outcome", outcome);

            tracing::info!(
                target: "dekopon_http_host::audit",
                {
                    audit.event = "accounting.http.request",
                    "http.request.method" = evidence.map(|evidence| evidence.method.as_str()),
                    "server.address" = evidence.map(|evidence| evidence.authority.as_str()),
                    "http.response.status_code" = evidence.and_then(|evidence| evidence.status),
                    "dekopon.http.request.accounted_bytes" =
                        evidence.map(|evidence| evidence.request_bytes),
                    "dekopon.http.response.accounted_bytes" =
                        evidence.map(|evidence| evidence.response_bytes),
                    "error.code" = failure.map(|error| tracing::field::debug(error.code)),
                    "error.message" = failure.map(|error| error.message.as_str()),
                    outcome = outcome,
                },
                "external HTTP request accounted"
            );
        });

        if let Some(error) = failure {
            self.policy_violation = violation_label(error.code).or(self.policy_violation);
        }
    }

    async fn authorize_request(
        &mut self,
        request: Request,
        streamed: Option<stream::RequestLengths>,
    ) -> Result<(PreparedRequest, HttpConstraints, usize), HttpError> {
        let Some(grant) = self.grant.clone() else {
            return Err(http_error(
                ErrorCode::Denied,
                "this invocation has no HTTP authorization",
            ));
        };
        if self.calls >= grant.max_requests {
            return Err(http_error(
                ErrorCode::HostCallLimit,
                "the authorized HTTP request limit is exhausted",
            ));
        }
        self.calls = self.calls.saturating_add(1);
        // Each request gets the whole timeout: a provider parked on its stdin has done no work.
        self.deadline = Instant::now()
            .checked_add(self.timeout)
            .ok_or_else(|| http_error(ErrorCode::Internal, "request deadline overflowed"))?;

        if self.secret_grant.is_some() && secret_raw_path_is_ambiguous(&request.uri) {
            return Err(http_error(
                ErrorCode::Denied,
                "secret-bearing request path uses prohibited encoding or separators",
            ));
        }
        let mut prepared = self.prepare(request, &grant, streamed).await?;
        tracing::Span::current().record("url.full", prepared.url.as_str());
        // Credential injection happens strictly after every guest-facing check, and its binding is
        // narrower than the grant and fails closed: an allowed-but-unbound destination is refused
        // rather than sent unauthenticated.
        if let Some(secret) = &self.secret_grant {
            let path_allowed = secret
                .allowed_paths
                .iter()
                .any(|rule| rule.matches(prepared.url.path()));
            let method_allowed = secret
                .allowed_methods
                .iter()
                .any(|method| method == prepared.method.as_str());
            let port = prepared
                .url
                .port_or_known_default()
                .unwrap_or(DEFAULT_HTTPS_PORT);
            let host_allowed = secret.allowed_hosts.iter().any(|authority| {
                authority_matches(authority, &prepared.host, port, prepared.url.scheme())
            });
            if !path_allowed
                || !method_allowed
                || !host_allowed
                || (!secret.allow_query && prepared.url.query().is_some())
            {
                return Err(http_error(
                    ErrorCode::Denied,
                    "request is outside this secret's authorized HTTP scope",
                ));
            }
            if self.secret_injections >= secret.max_injections {
                return Err(http_error(
                    ErrorCode::HostCallLimit,
                    "the authorized secret injection limit is exhausted",
                ));
            }
        }

        let credential_header = self.credential.as_ref().map(|credential| {
            let port = prepared
                .url
                .port_or_known_default()
                .unwrap_or(DEFAULT_HTTPS_PORT);
            if credential.matches(&prepared.host, port, prepared.url.scheme()) {
                credential.render()
            } else {
                Err(http_error(
                    ErrorCode::Denied,
                    "destination is outside this credential's binding",
                ))
            }
        });

        // Evidence is pushed before the credential decision so a binding refusal still leaves an
        // accounted, status-less record rather than a silent gap.
        let evidence_index = self.evidence.len();
        self.evidence.push(HttpCallEvidence {
            method: prepared.method.as_str().to_owned(),
            authority: prepared.authority.clone(),
            status: None,
            request_bytes: prepared.request_bytes,
            response_bytes: 0,
            credential_injected: false,
        });
        if let Some(header) = credential_header {
            prepared.headers.insert(AUTHORIZATION, header?);
            // The companion header is inserted only after accounting, alongside the bearer token,
            // so it never counts against the guest's byte grant.
            if let Some(companion) = self
                .credential
                .as_ref()
                .and_then(BoundCredential::render_companion)
            {
                let (name, value) = companion?;
                prepared.headers.insert(name, value);
            }
            self.evidence[evidence_index].credential_injected = true;
            if self.secret_grant.is_some() {
                self.secret_injections = self.secret_injections.saturating_add(1);
            }
        }

        if grant.propagate_trace
            && let Some(context) = dekopon_telemetry::current_trace_context()
        {
            let value = format!(
                "00-{:032x}-{:016x}-{:02x}",
                u128::from_be_bytes(context.trace_id),
                u64::from_be_bytes(context.span_id),
                context.flags,
            );
            let header = HeaderValue::from_str(&value).map_err(|_error| {
                http_error(ErrorCode::Internal, "trace context could not be rendered")
            })?;
            prepared.headers.insert("traceparent", header);
        }

        Ok((prepared, grant, evidence_index))
    }

    async fn send_checked(&mut self, request: Request) -> Result<Response, HttpError> {
        let (prepared, grant, evidence_index) = self.authorize_request(request, None).await?;
        let response = self.execute(prepared, &grant, evidence_index).await?;
        if self
            .credential
            .as_ref()
            .is_some_and(|credential| credential.echoes_credential(&response))
        {
            return Err(stream::echoed());
        }
        Ok(response)
    }

    #[expect(
        clippy::too_many_lines,
        reason = "reshaped by the unit that next rewrites this"
    )]
    async fn prepare(
        &mut self,
        request: Request,
        grant: &HttpConstraints,
        streamed: Option<stream::RequestLengths>,
    ) -> Result<PreparedRequest, HttpError> {
        #[allow(
            clippy::map_err_ignore,
            reason = "`http::method::InvalidMethod` is an opaque unit error whose whole content is \
                      \"invalid HTTP method\", which the replacement already states"
        )]
        let method = Method::from_bytes(request.method.as_bytes()).map_err(|_| {
            http_error(ErrorCode::InvalidMethod, "method is not a valid HTTP token")
        })?;
        if !grant
            .allowed_methods
            .iter()
            .any(|allowed| allowed == method.as_str())
        {
            return Err(http_error(
                ErrorCode::Denied,
                "HTTP method is not authorized for this invocation",
            ));
        }
        let bounded_body_bytes =
            streamed.map_or(request.body.len() as u64, |lengths| lengths.literal);
        let minimum_request_bytes =
            encoded_request_bytes(method.as_str(), &request.uri, 0, bounded_body_bytes)
                .ok_or_else(|| http_error(ErrorCode::RequestTooLarge, "request size overflowed"))?;
        if minimum_request_bytes > grant.max_request_bytes {
            return Err(http_error(
                ErrorCode::RequestTooLarge,
                "request exceeds the authorized byte limit",
            ));
        }

        let mut url = Url::parse(&request.uri).map_err(|error| {
            http_error(
                ErrorCode::InvalidUri,
                format!("URI is not a valid absolute URL: {error}"),
            )
        })?;
        if url.username() != "" || url.password().is_some() || url.fragment().is_some() {
            return Err(http_error(
                ErrorCode::InvalidUri,
                "URI user information and fragments are prohibited",
            ));
        }
        // host_str() returns IPv6 addresses bracketed, but resolution, pinning, and credential
        // matching all require the bare unbracketed form.
        let host = unbracketed_host(
            url.host_str()
                .ok_or_else(|| http_error(ErrorCode::InvalidUri, "URI has no host"))?,
        )
        .to_ascii_lowercase();
        let port = url.port_or_known_default().ok_or_else(|| {
            http_error(
                ErrorCode::InvalidUri,
                "URI scheme has no recognized default port",
            )
        })?;
        let authority = canonical_authority(&host, port);
        if !grant
            .allowed_hosts
            .iter()
            .any(|allowed| authority_matches(allowed, &host, port, url.scheme()))
        {
            return Err(http_error(
                ErrorCode::Denied,
                "HTTP destination is not authorized for this invocation",
            ));
        }

        match url.scheme() {
            "https" => {}
            "http" if grant.allow_plaintext_loopback => {}
            "http" => {
                return Err(http_error(
                    ErrorCode::Denied,
                    "plaintext HTTP is not authorized",
                ));
            }
            _ => {
                return Err(http_error(
                    ErrorCode::InvalidUri,
                    "only HTTP and HTTPS URLs are supported",
                ));
            }
        }
        apply_request_templates(grant, &self.slots, &method, &mut url)?;
        if !grant.request_templates.is_empty()
            && (method == Method::GET || method == Method::HEAD)
            && (bounded_body_bytes > 0 || streamed.is_some())
        {
            return Err(http_error(
                ErrorCode::Denied,
                "a request template's GET or HEAD rule takes no body",
            ));
        }

        if request.headers.len() > self.ceilings.max_headers {
            return Err(http_error(
                ErrorCode::RequestTooLarge,
                "request has too many headers",
            ));
        }
        let companion = self
            .credential
            .as_ref()
            .and_then(BoundCredential::companion_name)
            .cloned();
        let mut headers = HeaderMap::new();
        let mut header_bytes = 0_u64;
        for header in request.headers {
            header_bytes = header_bytes
                .checked_add(header.name.len() as u64)
                .and_then(|size| size.checked_add(header.value.len() as u64))
                .and_then(|size| size.checked_add(4))
                .ok_or_else(|| {
                    http_error(ErrorCode::RequestTooLarge, "request header size overflowed")
                })?;
            if header_bytes > self.ceilings.max_header_bytes as u64 {
                return Err(http_error(
                    ErrorCode::RequestTooLarge,
                    "request headers exceed the host limit",
                ));
            }
            #[allow(
                clippy::map_err_ignore,
                reason = "`InvalidHeaderName` is an opaque unit error naming neither the offending \
                          byte nor its position"
            )]
            let name = HeaderName::from_bytes(header.name.as_bytes()).map_err(|_| {
                http_error(ErrorCode::InvalidHeader, "request header name is invalid")
            })?;
            if is_forbidden_request_header(&name, companion.as_ref()) {
                return Err(http_error(
                    ErrorCode::InvalidHeader,
                    "request header is broker-owned or hop-by-hop",
                ));
            }
            #[allow(
                clippy::map_err_ignore,
                reason = "`InvalidHeaderValue` is an opaque unit error naming neither the \
                          offending byte nor its position"
            )]
            let value = HeaderValue::from_bytes(&header.value).map_err(|_| {
                http_error(ErrorCode::InvalidHeader, "request header value is invalid")
            })?;
            headers.append(name, value);
        }

        let request_bytes = encoded_request_bytes(
            method.as_str(),
            url.as_str(),
            header_bytes,
            bounded_body_bytes,
        )
        .ok_or_else(|| http_error(ErrorCode::RequestTooLarge, "request size overflowed"))?;
        if request_bytes > grant.max_request_bytes {
            return Err(http_error(
                ErrorCode::RequestTooLarge,
                "request exceeds the authorized byte limit",
            ));
        }

        // DNS resolution is cached for this context's lifetime, but every cached address is still
        // validated on each call, so caching narrows latency, not what may be reached.
        let addresses = if let Some(addresses) = self.resolved.get(&authority) {
            addresses.clone()
        } else {
            let remaining = self.remaining()?;
            #[allow(
                clippy::map_err_ignore,
                reason = "`tokio::time::error::Elapsed` carries only \"deadline has elapsed\", which \
                          the Timeout message already states"
            )]
            let addresses = if let Some(pin) = self
                .ceilings
                .loopback_https_pin
                .as_ref()
                .filter(|pin| pin.authority == authority && url.scheme() == "https")
            {
                vec![pin.address]
            } else {
                timeout(remaining, resolve_destination(&host, port))
                    .await
                    .map_err(|_| {
                        http_error(ErrorCode::Timeout, "destination resolution timed out")
                    })??
            };
            self.resolved.insert(authority.clone(), addresses.clone());
            addresses
        };
        if !plaintext_permitted(
            url.scheme(),
            &host,
            &addresses,
            &self.ceilings.plaintext_hosts,
        ) {
            return Err(http_error(
                ErrorCode::Denied,
                format!(
                    "plaintext HTTP to {host} is refused: not a loopback destination, and not \
                     listed in the broker's http.plaintextHosts"
                ),
            ));
        }
        if url.scheme() == "https" {
            let non_public = self
                .ceilings
                .non_public_https
                .iter()
                .any(|entry| entry.authority == authority);
            let pinned_loopback = self
                .ceilings
                .loopback_https_pin
                .as_ref()
                .is_some_and(|pin| pin.authority == authority && addresses == [pin.address]);
            if !pinned_loopback && !https_addresses_permitted(non_public, &addresses) {
                return Err(http_error(
                    ErrorCode::Denied,
                    if non_public {
                        "non-public HTTPS requires private unicast addresses"
                    } else {
                        "destination resolved to a non-public address"
                    },
                ));
            }
        }

        Ok(PreparedRequest {
            method,
            url,
            headers,
            body: request.body,
            host,
            authority,
            addresses,
            request_bytes: streamed.map_or(request_bytes, |lengths| lengths.total),
        })
    }

    async fn execute(
        &mut self,
        request: PreparedRequest,
        grant: &HttpConstraints,
        evidence_index: usize,
    ) -> Result<Response, HttpError> {
        let remaining = self.remaining()?;
        let client = self.pinned_client(&request.host, &request.addresses, remaining)?;

        #[allow(
            clippy::map_err_ignore,
            reason = "`tokio::time::error::Elapsed` carries only \"deadline has elapsed\", which \
                      the Timeout message already states"
        )]
        let response = timeout(
            remaining,
            client
                .request(request.method.clone(), request.url)
                .headers(request.headers)
                .body(request.body)
                .send(),
        )
        .await
        .map_err(|_| http_error(ErrorCode::Timeout, "HTTP request timed out"))?
        .map_err(|error| map_reqwest_error(&error))?;

        let stream::Head {
            status,
            headers,
            bytes: mut response_bytes,
            body: mut decoded,
        } = self.accept_head(&request.method, response, grant, evidence_index)?;
        let mut body = Vec::new();
        while let Some(chunk) = decoded.next().await? {
            response_bytes = response_bytes
                .checked_add(chunk.len() as u64)
                .ok_or_else(|| {
                    http_error(ErrorCode::ResponseTooLarge, "response size overflowed")
                })?;
            self.evidence[evidence_index].response_bytes = response_bytes;
            if response_bytes > grant.max_response_bytes {
                return Err(http_error(
                    ErrorCode::ResponseTooLarge,
                    "response exceeds the authorized byte limit",
                ));
            }
            body.extend_from_slice(&chunk);
        }

        Ok(Response {
            status,
            headers,
            body,
        })
    }

    fn pinned_client(
        &mut self,
        host: &str,
        addresses: &[SocketAddr],
        budget: Duration,
    ) -> Result<reqwest::Client, HttpError> {
        if let Some(pinned) = &self.pinned_client
            && pinned.host == host
            && pinned.addresses == addresses
        {
            return Ok(pinned.client.clone());
        }
        let mut builder = reqwest::Client::builder()
            .redirect(redirect::Policy::none())
            .no_proxy()
            .default_headers(HeaderMap::from_iter([(
                ACCEPT_ENCODING,
                HeaderValue::from_static("gzip, deflate"),
            )]))
            .connect_timeout(budget)
            .resolve_to_addrs(host, addresses);
        let pinned_ca = self
            .ceilings
            .loopback_https_pin
            .as_ref()
            .filter(|pin| {
                pin.authority == canonical_authority(host, addresses[0].port())
                    && addresses == [pin.address]
            })
            .map(|pin| pin.ca_pem.as_slice());
        for pem in self
            .ceilings
            .extra_ca_bundles
            .iter()
            .map(Vec::as_slice)
            .chain(pinned_ca)
        {
            for cert in reqwest::Certificate::from_pem_bundle(pem)
                .map_err(|_error| http_error(ErrorCode::Denied, "invalid configured CA bundle"))?
            {
                builder = builder.add_root_certificate(cert);
            }
        }
        let client = builder.build().map_err(|error| map_reqwest_error(&error))?;
        self.pinned_client = Some(PinnedClient {
            host: host.to_owned(),
            addresses: addresses.to_vec(),
            client: client.clone(),
        });
        Ok(client)
    }

    fn remaining(&self) -> Result<Duration, HttpError> {
        self.deadline
            .checked_duration_since(Instant::now())
            .filter(|remaining| !remaining.is_zero())
            .ok_or_else(|| http_error(ErrorCode::Timeout, "invocation deadline expired"))
    }
}

/// The outgoing path is rebuilt from the template rather than edited in place, so how the provider
/// percent-encoded its placeholders can never change what the upstream receives.
fn apply_request_templates(
    grant: &HttpConstraints,
    slots: &ChatSlotValues,
    method: &Method,
    url: &mut Url,
) -> Result<(), HttpError> {
    if grant.request_templates.is_empty() {
        return Ok(());
    }
    let decoded = percent_encoding::percent_decode_str(url.path())
        .decode_utf8()
        .map_err(|_error| {
            http_error(
                ErrorCode::Denied,
                "request path is not UTF-8 once decoded, so no request template matches",
            )
        })?;
    let segments = if decoded == "/" {
        Vec::new()
    } else {
        decoded.split('/').skip(1).collect::<Vec<_>>()
    };
    let Some(template) = grant
        .request_templates
        .iter()
        .find(|template| template.method == method.as_str() && template.path.matches(&segments))
    else {
        return Err(http_error(
            ErrorCode::Denied,
            "request matches no request template of this capability",
        ));
    };
    let pairs = url
        .query_pairs()
        .map(|(key, value)| (key.into_owned(), value.into_owned()))
        .collect::<Vec<_>>();
    for (key, _) in &pairs {
        if template.query.pinned.contains_key(key) {
            return Err(http_error(
                ErrorCode::Denied,
                format!("query key {key:?} is host-filled by request template {template}"),
            ));
        }
        if !template.query.allowed.contains(key) {
            return Err(http_error(
                ErrorCode::Denied,
                format!("request template {template} does not allow one of the query keys"),
            ));
        }
    }
    let slot_value = |slot| {
        slots.get(slot).ok_or_else(|| {
            http_error(
                ErrorCode::Denied,
                format!(
                    "request template {template} needs {{{slot}}}, which this invocation lacks"
                ),
            )
        })
    };
    let mut path = Vec::with_capacity(template.path.segments().len());
    for segment in template.path.segments() {
        path.push(match segment {
            PathSegment::Literal(literal) => literal.as_str(),
            PathSegment::Slot(slot) => slot_value(*slot)?,
        });
    }
    let mut pinned = Vec::with_capacity(template.query.pinned.len());
    for (key, slot) in &template.query.pinned {
        pinned.push((key.as_str(), slot_value(*slot)?));
    }
    url.path_segments_mut()
        .map_err(|()| http_error(ErrorCode::InvalidUri, "URI cannot carry a path"))?
        .clear()
        .extend(path);
    if pairs.is_empty() && pinned.is_empty() {
        url.set_query(None);
    } else {
        url.query_pairs_mut()
            .clear()
            .extend_pairs(&pairs)
            .extend_pairs(pinned);
    }
    Ok(())
}

fn validate_configuration(
    grant: Option<&HttpConstraints>,
    ceilings: &HttpHostCeilings,
    timeout: Duration,
) -> Result<(), ConfigurationError> {
    for (field, value) in [
        ("max_requests", u128::from(ceilings.max_requests)),
        ("max_request_bytes", u128::from(ceilings.max_request_bytes)),
        (
            "max_response_bytes",
            u128::from(ceilings.max_response_bytes),
        ),
        ("max_headers", ceilings.max_headers as u128),
        ("max_header_bytes", ceilings.max_header_bytes as u128),
    ] {
        if value == 0 {
            return Err(ConfigurationError::ZeroCeiling { field });
        }
    }
    if timeout.is_zero() {
        return Err(ConfigurationError::ZeroTimeout);
    }
    if let Some(grant) = grant {
        grant
            .validate()
            .map_err(|source| ConfigurationError::InvalidGrant { source })?;
        if grant.max_requests > ceilings.max_requests
            || grant.max_request_bytes > ceilings.max_request_bytes
            || grant.max_response_bytes > ceilings.max_response_bytes
        {
            return Err(ConfigurationError::GrantExceedsCeiling);
        }
    }
    Ok(())
}

#[derive(Debug)]
struct PreparedRequest {
    method: Method,
    url: Url,
    headers: HeaderMap,
    body: Vec<u8>,
    host: String,
    authority: String,
    addresses: Vec<SocketAddr>,
    request_bytes: u64,
}

async fn resolve_destination(host: &str, port: u16) -> Result<Vec<SocketAddr>, HttpError> {
    let addresses = tokio::net::lookup_host((host, port))
        .await
        .map_err(|error| {
            tracing::debug!(error = %error, "destination resolution failed");
            http_error(ErrorCode::Dns, "destination could not be resolved")
        })?;
    bounded_addresses(addresses)
}

/// The bound truncates rather than refuses because refusing at the limit would make a large
/// round-robin or dual-stack destination permanently or intermittently unreachable.
fn bounded_addresses(
    addresses: impl IntoIterator<Item = SocketAddr>,
) -> Result<Vec<SocketAddr>, HttpError> {
    let mut unique = BTreeSet::new();
    for address in addresses {
        unique.insert(address);
        if unique.len() == MAX_RESOLVED_ADDRESSES {
            break;
        }
    }
    if unique.is_empty() {
        return Err(http_error(
            ErrorCode::Dns,
            "destination resolved to no addresses",
        ));
    }
    Ok(unique.into_iter().collect())
}

fn unbracketed_host(host: &str) -> &str {
    host.strip_prefix('[')
        .and_then(|rest| rest.strip_suffix(']'))
        .unwrap_or(host)
}

fn canonical_host(host: &str) -> Cow<'_, str> {
    if host.contains(':') {
        Cow::Owned(format!("[{host}]"))
    } else {
        Cow::Borrowed(host)
    }
}

fn canonical_authority(host: &str, port: u16) -> String {
    format!("{}:{port}", canonical_host(host))
}

/// The loopback branch requires every resolved address to be loopback; the list matches by
/// hostname, not address, since address alone can't distinguish a LAN answer from a chosen one.
fn plaintext_permitted(
    scheme: &str,
    host: &str,
    addresses: &[SocketAddr],
    allowed: &PlaintextHosts,
) -> bool {
    scheme != "http"
        || addresses.iter().all(|address| address.ip().is_loopback())
        || allowed.contains(host)
}

fn authority_matches(allowed: &str, host: &str, port: u16, scheme: &str) -> bool {
    let allowed = allowed.trim().to_ascii_lowercase();
    allowed == canonical_authority(host, port)
        || (scheme == "https"
            && allowed == canonical_host(host).as_ref()
            && port == DEFAULT_HTTPS_PORT)
}

fn is_forbidden_request_header(name: &HeaderName, companion: Option<&HeaderName>) -> bool {
    if companion == Some(name) {
        return true;
    }
    matches!(
        name.as_str(),
        "authorization"
            | "connection"
            | "content-length"
            | "cookie"
            | "host"
            | "keep-alive"
            | "proxy-authenticate"
            | "proxy-authorization"
            | "proxy-connection"
            | "te"
            | "traceparent"
            | "tracestate"
            | "trailer"
            | "transfer-encoding"
            | "upgrade"
    )
}

fn is_forbidden_response_header(name: &HeaderName) -> bool {
    matches!(
        name.as_str(),
        "connection"
            | "keep-alive"
            | "proxy-authenticate"
            | "proxy-authorization"
            | "set-cookie"
            | "te"
            | "trailer"
            | "transfer-encoding"
            | "upgrade"
            | "www-authenticate"
    )
}

fn encoded_request_bytes(
    method: &str,
    uri: &str,
    header_bytes: u64,
    body_bytes: u64,
) -> Option<u64> {
    REQUEST_ENCODING_OVERHEAD_BYTES
        .checked_add(method.len() as u64)?
        .checked_add(uri.len() as u64)?
        .checked_add(header_bytes)?
        .checked_add(body_bytes)
}

fn https_addresses_permitted(non_public: bool, addresses: &[SocketAddr]) -> bool {
    !addresses.is_empty()
        && addresses.iter().all(|address| {
            if non_public {
                is_private_unicast(address.ip())
            } else {
                !is_forbidden_public_destination(address.ip())
            }
        })
}

fn is_private_unicast(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ip) => ip.is_private() && !ip.is_loopback() && !ip.is_link_local(),
        IpAddr::V6(ip) => (ip.segments()[0] & 0xfe00) == 0xfc00,
    }
}

fn is_forbidden_public_destination(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ip) => is_forbidden_ipv4(ip),
        IpAddr::V6(ip) => is_forbidden_ipv6(ip),
    }
}

fn is_forbidden_ipv4(ip: Ipv4Addr) -> bool {
    let [a, b, c, _d] = ip.octets();
    a == 0
        || a == 10
        || a == 127
        || (a == 100 && (64..=127).contains(&b))
        || (a == 169 && b == 254)
        || (a == 172 && (16..=31).contains(&b))
        || (a == 192 && b == 0 && c == 0)
        || (a == 192 && b == 0 && c == 2)
        || (a == 192 && b == 88 && c == 99)
        || (a == 192 && b == 168)
        || (a == 198 && (b == 18 || b == 19))
        || (a == 198 && b == 51 && c == 100)
        || (a == 203 && b == 0 && c == 113)
        || a >= 224
}

fn is_forbidden_ipv6(ip: Ipv6Addr) -> bool {
    if let Some(ipv4) = ip.to_ipv4_mapped() {
        return is_forbidden_ipv4(ipv4);
    }
    let segments = ip.segments();
    ip.is_unspecified()
        || ip.is_loopback()
        // Permit only global-unicast 2000::/3, then remove IETF special-purpose 2001::/23.
        || (segments[0] & 0xe000) != 0x2000
        || (segments[0] == 0x2001 && (segments[1] & 0xfe00) == 0)
        || (segments[0] == 0x2001 && segments[1] == 0x0db8)
        || segments[0] == 0x2002
        || (segments[0] == 0x3fff && (segments[1] & 0xf000) == 0)
}

fn map_reqwest_error(error: &reqwest::Error) -> HttpError {
    if error.is_builder() {
        return http_error(ErrorCode::Internal, "native HTTP client setup failed");
    }
    let code = if error.is_timeout() {
        ErrorCode::Timeout
    } else if error.is_connect() {
        if error_chain_contains(error, &["tls", "certificate", "cert "]) {
            ErrorCode::Tls
        } else {
            ErrorCode::Connect
        }
    } else {
        ErrorCode::Protocol
    };
    http_error(code, "HTTP transport failed")
}

fn error_chain_contains(error: &reqwest::Error, fragments: &[&str]) -> bool {
    let mut source = error.source();
    while let Some(current) = source {
        let message = current.to_string().to_ascii_lowercase();
        if fragments.iter().any(|fragment| message.contains(fragment)) {
            return true;
        }
        source = current.source();
    }
    false
}

pub(crate) fn http_error(code: ErrorCode, message: impl AsRef<str>) -> HttpError {
    HttpError {
        code,
        message: bounded_message(message.as_ref()),
    }
}

fn bounded_message(message: &str) -> String {
    let mut output = String::with_capacity(message.len().min(MAX_ERROR_MESSAGE_BYTES));
    for character in message.chars() {
        if output.len() + character.len_utf8() > MAX_ERROR_MESSAGE_BYTES {
            break;
        }
        if character.is_control() {
            output.push(' ');
        } else {
            output.push(character);
        }
    }
    output
}

/// This match must stay exhaustive with no wildcard arm, or a new ErrorCode could silently disagree
/// across policy_violation, the span, and accounting.
fn violation_label(code: ErrorCode) -> Option<&'static str> {
    match code {
        ErrorCode::Denied => Some("denied"),
        ErrorCode::HostCallLimit => Some("host-call-limit"),
        ErrorCode::InvalidMethod | ErrorCode::InvalidUri | ErrorCode::InvalidHeader => {
            Some("invalid-http-request")
        }
        ErrorCode::RequestTooLarge | ErrorCode::ResponseTooLarge => Some("byte-limit"),
        ErrorCode::Dns
        | ErrorCode::Connect
        | ErrorCode::Tls
        | ErrorCode::Timeout
        | ErrorCode::Protocol
        | ErrorCode::Internal => None,
    }
}

fn outcome_label<T>(result: &Result<T, HttpError>) -> &'static str {
    match result {
        Ok(_) => "succeeded",
        Err(error) => violation_label(error.code).unwrap_or("failed"),
    }
}

#[cfg(test)]
mod tests {
    use std::{
        net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
        time::Duration,
    };

    use dekopon_test_support::LoopbackServer;

    use dekopon_capability::{
        ChatSlot, ChatSlotValues, HttpConstraints, HttpConstraintsError, HttpPathRule,
        RequestTemplate, SecretUseGrant,
    };
    use dekopon_core::{Redacted, SecretBytes, SecretSinkKind};

    use super::{
        BoundCredential, BufferedHttpClient, ConfigurationError, ErrorCode, Header,
        HttpCallEvidence, HttpHostCeilings, MAX_RESOLVED_ADDRESSES, MIN_CREDENTIAL_BYTES,
        PlaintextHostError, PlaintextHosts, Request, authority_matches, bounded_addresses,
        bounded_message, is_forbidden_public_destination, map_reqwest_error, plaintext_permitted,
    };

    fn grant(authority: String, method: &str) -> HttpConstraints {
        HttpConstraints {
            allowed_hosts: vec![authority],
            allowed_methods: vec![method.to_owned()],
            max_requests: 2,
            max_request_bytes: 64 * 1024,
            max_response_bytes: 64 * 1024,
            allow_plaintext_loopback: true,
            propagate_trace: false,
            request_templates: Vec::new(),
        }
    }

    fn address(ip: &str, port: u16) -> SocketAddr {
        SocketAddr::new(ip.parse().expect("valid fixture address"), port)
    }

    fn plaintext_hosts(entries: &[&str]) -> PlaintextHosts {
        PlaintextHosts::new(entries).expect("valid fixture host list")
    }

    #[test]
    fn plaintext_reaches_loopback_with_an_empty_allow_list() {
        let empty = PlaintextHosts::default();
        assert!(empty.is_empty());
        assert!(plaintext_permitted(
            "http",
            "localhost",
            &[address("127.0.0.1", 8080)],
            &empty
        ));
        assert!(plaintext_permitted(
            "http",
            "::1",
            &[address("::1", 8080)],
            &empty
        ));
        assert!(!plaintext_permitted(
            "http",
            "rpi.lan",
            &[address("192.168.1.20", 5080)],
            &empty
        ));
    }

    #[test]
    fn plaintext_reaches_a_listed_host_and_nothing_else() {
        let allowed = plaintext_hosts(&["rpi.lan", "openobserve.openobserve.svc"]);
        assert!(plaintext_permitted(
            "http",
            "rpi.lan",
            &[address("192.168.1.20", 5080)],
            &allowed
        ));
        assert!(plaintext_permitted(
            "http",
            "openobserve.openobserve.svc",
            &[address("10.43.7.9", 5080)],
            &allowed
        ));
        for refused in ["evil.rpi.lan", "rpi.lan.evil.test", "lan", "rpi"] {
            assert!(
                !plaintext_permitted("http", refused, &[address("192.168.1.20", 5080)], &allowed),
                "{refused} is not listed"
            );
        }
    }

    #[test]
    fn listed_plaintext_hosts_match_case_insensitively() {
        let allowed = plaintext_hosts(&["RPi.LAN"]);
        assert!(plaintext_permitted(
            "http",
            "rpi.lan",
            &[address("192.168.1.20", 5080)],
            &allowed
        ));
        assert!(allowed.contains("RPI.LAN"));
        assert_eq!(allowed.iter().collect::<Vec<_>>(), vec!["rpi.lan"]);
    }

    #[test]
    fn a_listed_host_does_not_relax_https_or_mixed_loopback_answers() {
        let allowed = plaintext_hosts(&["rpi.lan"]);
        assert!(plaintext_permitted(
            "https",
            "api.example.test",
            &[address("93.184.216.34", 443)],
            &allowed
        ));
        assert!(!plaintext_permitted(
            "http",
            "split.example.test",
            &[address("127.0.0.1", 80), address("93.184.216.34", 80)],
            &allowed
        ));
    }

    #[test]
    fn plaintext_host_entries_must_be_bare_hostnames() {
        for (entry, expected) in [
            ("", PlaintextHostError::Empty),
            ("   ", PlaintextHostError::Empty),
            (
                "http://rpi.lan",
                PlaintextHostError::Scheme {
                    entry: "http://rpi.lan".to_owned(),
                },
            ),
            (
                "rpi.lan/ingest",
                PlaintextHostError::Path {
                    entry: "rpi.lan/ingest".to_owned(),
                },
            ),
            (
                "rpi.lan:5080",
                PlaintextHostError::Port {
                    entry: "rpi.lan:5080".to_owned(),
                },
            ),
            (
                "::1",
                PlaintextHostError::Port {
                    entry: "::1".to_owned(),
                },
            ),
            (
                "*.lan",
                PlaintextHostError::Wildcard {
                    entry: "*.lan".to_owned(),
                },
            ),
            (
                "rpi lan",
                PlaintextHostError::InvalidHost {
                    entry: "rpi lan".to_owned(),
                },
            ),
            (
                "user@rpi.lan",
                PlaintextHostError::InvalidHost {
                    entry: "user@rpi.lan".to_owned(),
                },
            ),
            (
                ".rpi.lan",
                PlaintextHostError::InvalidHost {
                    entry: ".rpi.lan".to_owned(),
                },
            ),
            (
                "rpi.lan.",
                PlaintextHostError::InvalidHost {
                    entry: "rpi.lan.".to_owned(),
                },
            ),
        ] {
            let error = PlaintextHosts::new([entry]).expect_err("{entry} must be refused");
            assert_eq!(error, expected, "{entry}");
        }
        PlaintextHosts::new(["rpi.lan", "http://other.lan"])
            .expect_err("a single invalid entry must refuse the list");
        assert!(plaintext_hosts(&["  rpi.lan  "]).contains("rpi.lan"));
        assert!(plaintext_hosts(&["192.168.1.20"]).contains("192.168.1.20"));
    }

    #[test]
    fn matches_only_exact_authorities() {
        assert!(authority_matches(
            "api.example.test",
            "api.example.test",
            443,
            "https"
        ));
        assert!(authority_matches(
            "api.example.test:8443",
            "api.example.test",
            8443,
            "https"
        ));
        assert!(!authority_matches(
            "example.test",
            "api.example.test",
            443,
            "https"
        ));
        assert!(!authority_matches("127.0.0.1", "127.0.0.1", 80, "http"));
        assert!(authority_matches("127.0.0.1:80", "127.0.0.1", 80, "http"));
    }

    #[test]
    fn renders_ipv6_literal_authorities_with_exactly_one_pair_of_brackets() {
        assert!(authority_matches("[::1]:8080", "::1", 8080, "http"));
        assert!(authority_matches(
            "[2606:4700:4700::1111]",
            "2606:4700:4700::1111",
            443,
            "https"
        ));
        assert!(!authority_matches("[[::1]]:8080", "::1", 8080, "http"));
        assert!(!authority_matches("::1:8080", "::1", 8080, "http"));
    }

    #[test]
    fn rejects_private_and_special_addresses() {
        for ip in [
            IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
            IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)),
            IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254)),
            IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)),
            IpAddr::V6(Ipv6Addr::LOCALHOST),
            "fd00::1".parse().expect("valid fixture"),
            "2001:db8::1".parse().expect("valid fixture"),
            "2002:7f00:1::1".parse().expect("valid fixture"),
            "3fff::1".parse().expect("valid fixture"),
            "64:ff9b::127.0.0.1".parse().expect("valid fixture"),
        ] {
            assert!(is_forbidden_public_destination(ip), "{ip}");
        }
        assert!(!is_forbidden_public_destination(
            "93.184.216.34".parse().expect("valid fixture")
        ));
        assert!(!is_forbidden_public_destination(
            "2606:4700:4700::1111".parse().expect("valid fixture")
        ));
    }

    #[test]
    fn non_public_https_requires_exact_authority_independent_of_trust() {
        let profile = super::NonPublicHttpsAuthority::new(
            "OpenObserve-TLS.openobserve.svc.cluster.local:5443",
        )
        .expect("valid exact authority");
        assert_eq!(
            profile.authority,
            "openobserve-tls.openobserve.svc.cluster.local:5443"
        );
        for authority in [
            "openobserve-tls.openobserve.svc.cluster.local",
            "openobserve-tls.openobserve.svc.cluster.local:5443/path",
            "*.openobserve.svc.cluster.local:5443",
            "169.254.169.254:5443",
            "openobserve-tls.openobserve.svc.cluster.local:5443@evil.example:443",
        ] {
            assert!(
                super::NonPublicHttpsAuthority::new(authority).is_err(),
                "{authority}"
            );
        }
        for address in ["10.43.0.1", "172.16.0.2", "192.168.1.1", "fd00::1"] {
            assert!(
                super::is_private_unicast(address.parse().unwrap()),
                "{address}"
            );
        }
        for address in [
            "127.0.0.1",
            "169.254.169.254",
            "8.8.8.8",
            "::1",
            "fe80::1",
            "2001:db8::1",
        ] {
            assert!(
                !super::is_private_unicast(address.parse().unwrap()),
                "{address}"
            );
        }
        let private = ["10.43.0.1:5443".parse().unwrap()];
        let mixed = [
            "10.43.0.1:5443".parse().unwrap(),
            "8.8.8.8:5443".parse().unwrap(),
        ];
        let public = ["8.8.8.8:443".parse().unwrap()];
        assert!(super::https_addresses_permitted(true, &private));
        assert!(!super::https_addresses_permitted(false, &private));
        assert!(!super::https_addresses_permitted(true, &mixed));
        assert!(!super::https_addresses_permitted(true, &public));
        assert!(super::https_addresses_permitted(false, &public));
    }

    #[test]
    fn rejects_zero_or_overbroad_configuration() {
        let error = BufferedHttpClient::disabled(
            HttpHostCeilings {
                max_headers: 0,
                ..HttpHostCeilings::default()
            },
            Duration::from_secs(1),
        )
        .expect_err("zero native ceiling must fail");
        assert_eq!(
            error,
            ConfigurationError::ZeroCeiling {
                field: "max_headers"
            }
        );

        let error = BufferedHttpClient::authorized(
            HttpConstraints {
                max_requests: 33,
                ..grant("api.example.test".to_owned(), "GET")
            },
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect_err("grant cannot exceed native ceiling");
        assert_eq!(error, ConfigurationError::GrantExceedsCeiling);

        let error = BufferedHttpClient::disabled(HttpHostCeilings::default(), Duration::MAX)
            .expect_err("unrepresentable runtime deadline must fail");
        assert_eq!(error, ConfigurationError::TimeoutOverflow);
    }

    #[test]
    fn rejects_grant_entries_no_authority_can_match() {
        for host in [" api.example.test", "*", "a/b", ""] {
            let error = BufferedHttpClient::authorized(
                grant(host.to_owned(), "GET"),
                HttpHostCeilings::default(),
                Duration::from_secs(1),
            )
            .expect_err("an inexact host must not configure a client");
            assert_eq!(
                error,
                ConfigurationError::InvalidGrant {
                    source: HttpConstraintsError::InvalidHost {
                        value: host.to_owned()
                    }
                }
            );
        }

        let error = BufferedHttpClient::authorized(
            grant("api.example.test".to_owned(), "GET POST"),
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect_err("an inexact method must not configure a client");
        assert_eq!(
            error,
            ConfigurationError::InvalidGrant {
                source: HttpConstraintsError::InvalidMethod {
                    value: "GET POST".to_owned()
                }
            }
        );
    }

    #[test]
    fn truncates_resolver_fan_out_instead_of_refusing_it() {
        let addresses = (1..=17).map(|last| SocketAddr::from(([192, 0, 2, last], 443)));
        let bounded =
            bounded_addresses(addresses).expect("a large fan-out is truncated, not refused");
        assert_eq!(bounded.len(), MAX_RESOLVED_ADDRESSES);

        let duplicated = (1..=20).map(|_| SocketAddr::from(([192, 0, 2, 1], 443)));
        let bounded = bounded_addresses(duplicated).expect("duplicates collapse before the bound");
        assert_eq!(bounded.len(), 1);

        let error = bounded_addresses(Vec::new()).expect_err("an empty answer is still a failure");
        assert_eq!(error.code, ErrorCode::Dns);
    }

    #[test]
    fn client_builder_failures_are_setup_failures_not_protocol_failures() {
        let error = reqwest::Client::new()
            .get("not an absolute url")
            .build()
            .expect_err("the builder rejects a non-absolute URL");
        assert!(error.is_builder());
        assert_eq!(map_reqwest_error(&error).code, ErrorCode::Internal);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn sends_extension_methods_duplicate_headers_and_buffered_bodies() {
        let server = LoopbackServer::once(
            b"HTTP/1.1 200 OK\r\nX-Value: one\r\nX-Value: two\r\nSet-Cookie: secret=session\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",
        );
        let authority = server.authority().to_owned();
        let mut client = BufferedHttpClient::authorized(
            grant(authority.clone(), "PROPFIND"),
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization");
        let response = client
            .send(Request {
                method: "PROPFIND".to_owned(),
                uri: format!("http://{authority}/items?private=no"),
                headers: vec![
                    Header {
                        name: "x-probe".to_owned(),
                        value: b"one".to_vec(),
                    },
                    Header {
                        name: "x-probe".to_owned(),
                        value: b"two".to_vec(),
                    },
                ],
                body: b"payload".to_vec(),
            })
            .await
            .expect("bounded request succeeds");

        assert_eq!(response.status, 200);
        assert_eq!(response.body, b"ok");
        assert_eq!(
            response
                .headers
                .iter()
                .filter(|header| header.name == "x-value")
                .count(),
            2
        );
        assert!(
            response
                .headers
                .iter()
                .all(|header| header.name != "set-cookie")
        );
        let request = server.request();
        assert!(request.starts_with(b"PROPFIND /items?private=no HTTP/1.1\r\n"));
        assert!(request.ends_with(b"\r\n\r\npayload"));
        let evidence = client.into_evidence();
        assert_eq!(evidence.len(), 1);
        assert_eq!(evidence[0].authority, authority);
        server.join();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_listed_plaintext_host_still_needs_the_authorization_to_allow_it() {
        let ceilings = HttpHostCeilings {
            plaintext_hosts: plaintext_hosts(&["api.example.test"]),
            ..HttpHostCeilings::default()
        };
        let mut client = BufferedHttpClient::authorized(
            HttpConstraints {
                allow_plaintext_loopback: false,
                ..grant("api.example.test:80".to_owned(), "GET")
            },
            ceilings.clone(),
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization");
        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: "http://api.example.test/".to_owned(),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect_err("a constraint set that forbids plaintext still forbids it");
        assert_eq!(error.code, ErrorCode::Denied);
        assert_eq!(error.message, "plaintext HTTP is not authorized");

        let mut client = BufferedHttpClient::authorized(
            grant("other.example.test:80".to_owned(), "GET"),
            ceilings,
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization");
        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: "http://api.example.test/".to_owned(),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect_err("a listed host the grant does not name is still not a destination");
        assert_eq!(error.code, ErrorCode::Denied);
        assert_eq!(
            error.message,
            "HTTP destination is not authorized for this invocation"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn denies_other_destinations_and_sensitive_request_headers() {
        let mut client = BufferedHttpClient::authorized(
            grant("127.0.0.1:10".to_owned(), "GET"),
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization");
        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: "http://127.0.0.1:9/".to_owned(),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect_err("different authority must fail before connection");
        assert_eq!(error.code, ErrorCode::Denied);
        assert_eq!(client.policy_violation(), Some("denied"));

        let mut client = BufferedHttpClient::authorized(
            grant("127.0.0.1:9".to_owned(), "GET"),
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization");
        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: "http://127.0.0.1:9/".to_owned(),
                headers: vec![Header {
                    name: "authorization".to_owned(),
                    value: b"Bearer secret".to_vec(),
                }],
                body: Vec::new(),
            })
            .await
            .expect_err("guest authorization header must fail before connection");
        assert_eq!(error.code, ErrorCode::InvalidHeader);
        assert_eq!(client.policy_violation(), Some("invalid-http-request"));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn invalid_uris_name_the_rule_they_broke() {
        let mut client = BufferedHttpClient::authorized(
            grant("api.example.test".to_owned(), "GET"),
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization");

        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: "/relative/only".to_owned(),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect_err("a relative reference is not an absolute URL");
        assert_eq!(error.code, ErrorCode::InvalidUri);
        assert!(
            error.message.contains("relative URL without a base"),
            "{error}"
        );

        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: "https://api.example.test:notaport/".to_owned(),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect_err("a malformed port is not an absolute URL");
        assert_eq!(error.code, ErrorCode::InvalidUri);
        assert!(error.message.contains("invalid port number"), "{error}");
        assert!(!error.message.contains("api.example.test"), "{error}");
    }

    fn secret_grant(
        authority: &str,
        sink: SecretSinkKind,
        username: Option<&str>,
        path: &str,
    ) -> SecretUseGrant {
        SecretUseGrant {
            secret: "drn:com.xrl:secret:test:api/credential"
                .parse()
                .expect("canonical DRN"),
            sink,
            basic_username: username.map(str::to_owned),
            allowed_hosts: vec![authority.to_owned()],
            allowed_methods: vec!["GET".to_owned()],
            allowed_paths: vec![HttpPathRule::Exact {
                path: path.to_owned(),
            }],
            allow_query: false,
            max_injections: 1,
            binding_id: "api-credential".to_owned(),
            map_revision: None,
        }
    }

    fn credential_for(authority: &str) -> BoundCredential {
        BoundCredential::bearer(
            "Bearer",
            Redacted::new("fixture-secret-value".to_owned()),
            vec![authority.to_owned()],
        )
        .expect("valid fixture credential")
    }

    #[test]
    fn bound_credentials_fail_closed_on_structural_problems() {
        let secret = || Redacted::new("fixture-secret-value".to_owned());
        let destinations = || vec!["api.example.test".to_owned()];
        for (scheme, secret, destinations) in [
            ("", secret(), destinations()),
            ("Bea rer", secret(), destinations()),
            ("Bearer", Redacted::new(String::new()), destinations()),
            ("Bearer", Redacted::new("x".repeat(15)), destinations()),
            (
                "Bearer",
                Redacted::new("phrase shaped secret".to_owned()),
                destinations(),
            ),
            (
                "Bearer",
                Redacted::new("tab\tseparated-secret".to_owned()),
                destinations(),
            ),
            ("Bearer", Redacted::new("x".repeat(4097)), destinations()),
            (
                "Bearer",
                Redacted::new("bad\r\nheader-value-here".to_owned()),
                destinations(),
            ),
            ("Bearer", secret(), Vec::new()),
            (
                "Bearer",
                secret(),
                vec!["https://api.example.test/path".to_owned()],
            ),
            ("Bearer", secret(), vec!["*.example.test".to_owned()]),
        ] {
            assert!(matches!(
                BoundCredential::bearer(scheme, secret, destinations),
                Err(ConfigurationError::InvalidCredential { .. })
            ));
        }
        BoundCredential::bearer(
            "Bearer",
            Redacted::new("x".repeat(MIN_CREDENTIAL_BYTES)),
            destinations(),
        )
        .expect("a minimum-length secret is a valid credential");
        let error = BoundCredential::bearer(
            "Bearer",
            Redacted::new("tell-nobody-not-even-once\n".to_owned()),
            destinations(),
        )
        .expect_err("control bytes are refused");
        assert!(!error.to_string().contains("tell-nobody"), "{error}");
    }

    #[test]
    fn drn_credential_identity_commits_the_complete_effective_scope() {
        let original = secret_grant(
            "api.example.test",
            SecretSinkKind::HttpBearer,
            None,
            "/v1/allowed",
        );
        let credential = BoundCredential::secret_bearer(
            SecretBytes::new(b"fixture-bearer-token".to_vec()),
            &original,
        )
        .expect("credential");
        let mut swapped = original;
        swapped.allowed_paths = vec![HttpPathRule::Exact {
            path: "/v1/other".to_owned(),
        }];
        let error = BufferedHttpClient::authorized_with_secret_credential(
            grant("api.example.test".to_owned(), "GET"),
            swapped,
            credential,
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect_err("same DRN and binding id cannot hide a swapped scope");
        assert!(matches!(
            error,
            ConfigurationError::InvalidCredential { .. }
        ));
    }

    #[test]
    fn bound_credentials_never_render_their_value() {
        let credential = credential_for("api.example.test");
        let debug = format!("{credential:?}");
        assert!(!debug.contains("fixture-secret-value"), "{debug}");
        assert!(debug.contains("api.example.test"), "{debug}");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn injects_a_destination_bound_credential_after_guest_checks() {
        let response: &[u8] =
            b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok";
        let plain_server = LoopbackServer::once(response);
        let plain_authority = plain_server.authority().to_owned();
        let server = LoopbackServer::once(response);
        let authority = server.authority().to_owned();

        let request_to = |authority: &str| Request {
            method: "GET".to_owned(),
            uri: format!("http://{authority}/pulls/7"),
            headers: vec![Header {
                name: "x-probe".to_owned(),
                value: b"one".to_vec(),
            }],
            body: Vec::new(),
        };

        let mut plain = BufferedHttpClient::authorized(
            grant(plain_authority.clone(), "GET"),
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization");
        plain
            .send(request_to(&plain_authority))
            .await
            .expect("uncredentialed request succeeds");

        let mut credentialed = BufferedHttpClient::authorized_with_credential(
            grant(authority.clone(), "GET"),
            Some(credential_for(&authority)),
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization");
        credentialed
            .send(request_to(&authority))
            .await
            .expect("credentialed request succeeds");

        let plain_request =
            String::from_utf8(plain_server.request()).expect("fixture request is UTF-8");
        assert!(
            !plain_request.to_ascii_lowercase().contains("authorization"),
            "{plain_request}"
        );
        let request = String::from_utf8(server.request()).expect("fixture request is UTF-8");
        assert!(
            request.contains("authorization: Bearer fixture-secret-value"),
            "{request}"
        );

        let plain_evidence = plain.into_evidence();
        let evidence = credentialed.into_evidence();
        assert!(!plain_evidence[0].credential_injected);
        assert!(evidence[0].credential_injected);
        let authority_delta = authority.len() as i64 - plain_authority.len() as i64;
        assert_eq!(
            evidence[0].request_bytes as i64 - authority_delta,
            plain_evidence[0].request_bytes as i64
        );

        plain_server.join();
        server.join();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn drn_bound_basic_auth_is_rendered_only_for_the_exact_path() {
        let response: &[u8] =
            b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok";
        let server = LoopbackServer::once(response);
        let authority = server.authority().to_owned();
        let secret = secret_grant(
            &authority,
            SecretSinkKind::HttpBasic,
            Some("userA"),
            "/api/v1/thing",
        );
        let credential =
            BoundCredential::secret_basic(SecretBytes::new(b"fixture-password".to_vec()), &secret)
                .expect("valid Basic credential");
        let mut client = BufferedHttpClient::authorized_with_secret_credential(
            grant(authority.clone(), "GET"),
            secret,
            credential,
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid secret authorization");
        client
            .send(Request {
                method: "GET".to_owned(),
                uri: format!("http://{authority}/api/v1/thing"),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect("exact path succeeds");
        let request = String::from_utf8(server.request()).expect("request is UTF-8");
        assert!(
            request.contains("authorization: Basic dXNlckE6Zml4dHVyZS1wYXNzd29yZA=="),
            "{request}"
        );
        server.join();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn secret_scope_denies_path_prefix_confusion_and_queries_before_connection() {
        let secret = secret_grant(
            "127.0.0.1:9",
            SecretSinkKind::HttpBearer,
            None,
            "/api/v1/thing",
        );
        for uri in [
            "http://127.0.0.1:9/api/v1/things",
            "http://127.0.0.1:9/api/v1/thing?reflect=authorization",
            "http://127.0.0.1:9/api/v1/other",
            "http://127.0.0.1:9/api/v1/%74hing",
            "http://127.0.0.1:9\\api\\v1\\thing",
            "http://127.0.0.1:9/api/v1/x/../thing",
            "http://127.0.0.1:9/api//v1/thing",
        ] {
            let credential = BoundCredential::secret_bearer(
                SecretBytes::new(b"fixture-bearer-token".to_vec()),
                &secret,
            )
            .expect("credential");
            let mut client = BufferedHttpClient::authorized_with_secret_credential(
                grant("127.0.0.1:9".to_owned(), "GET"),
                secret.clone(),
                credential,
                HttpHostCeilings::default(),
                Duration::from_secs(1),
            )
            .expect("context");
            let error = client
                .send(Request {
                    method: "GET".to_owned(),
                    uri: uri.to_owned(),
                    headers: Vec::new(),
                    body: Vec::new(),
                })
                .await
                .expect_err("scope confusion is denied");
            assert_eq!(error.code, ErrorCode::Denied, "{uri}");
        }
    }

    fn templated(authority: &str, template: serde_json::Value) -> HttpConstraints {
        HttpConstraints {
            allowed_methods: vec!["GET".to_owned(), "POST".to_owned()],
            request_templates: vec![
                serde_json::from_value::<RequestTemplate>(template).expect("template fixture"),
            ],
            ..grant(authority.to_owned(), "GET")
        }
    }

    fn slack_replies(authority: &str) -> HttpConstraints {
        templated(
            authority,
            serde_json::json!({
                "method": "GET",
                "path": "/api/conversations.replies",
                "query": {
                    "pinned": {"channel": "conversation.id", "ts": "conversation.thread"},
                    "allowed": ["limit", "cursor"]
                }
            }),
        )
    }

    fn discord_messages(authority: &str) -> HttpConstraints {
        templated(
            authority,
            serde_json::json!({
                "method": "GET",
                "path": "/channels/{conversation.apiChannel}/messages",
                "query": {"allowed": ["limit", "before"]}
            }),
        )
    }

    fn slots(values: &[(ChatSlot, &str)]) -> ChatSlotValues {
        let mut slots = ChatSlotValues::default();
        for (slot, value) in values {
            slots.insert(*slot, (*value).to_owned());
        }
        slots
    }

    async fn sent_request_line(
        grant: HttpConstraints,
        slots: ChatSlotValues,
        path: &str,
    ) -> String {
        let server = LoopbackServer::once(
            b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",
        );
        let authority = server.authority().to_owned();
        let mut client = BufferedHttpClient::authorized(
            HttpConstraints {
                allowed_hosts: vec![authority.clone()],
                ..grant
            },
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization")
        .with_chat_slots(slots);
        client
            .send(Request {
                method: "GET".to_owned(),
                uri: format!("http://{authority}{path}"),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect("templated request succeeds");
        let request = String::from_utf8(server.request()).expect("fixture request is UTF-8");
        server.join();
        request.lines().next().expect("request line").to_owned()
    }

    async fn template_denial(
        grant: HttpConstraints,
        slots: ChatSlotValues,
        method: &str,
        path: &str,
    ) -> super::HttpError {
        template_denial_with_body(grant, slots, method, path, Vec::new(), Vec::new()).await
    }

    async fn template_denial_with_body(
        grant: HttpConstraints,
        slots: ChatSlotValues,
        method: &str,
        path: &str,
        headers: Vec<Header>,
        body: Vec<u8>,
    ) -> super::HttpError {
        let mut client = BufferedHttpClient::authorized(
            grant,
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization")
        .with_chat_slots(slots);
        let error = client
            .send(Request {
                method: method.to_owned(),
                uri: format!("http://127.0.0.1:9{path}"),
                headers,
                body,
            })
            .await
            .expect_err("the request template refuses this request");
        assert_eq!(error.code, ErrorCode::Denied, "{method} {path}");
        assert!(
            error.message.contains("request template"),
            "{method} {path}: {}",
            error.message
        );
        error
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_slack_replies_template_pins_the_attested_channel_and_thread() {
        let line = sent_request_line(
            slack_replies("127.0.0.1:9"),
            slots(&[
                (ChatSlot::ConversationId, "C0123ABC"),
                (ChatSlot::ConversationThread, "1700000000.000100"),
            ]),
            "/api/conversations.replies?limit=5",
        )
        .await;
        assert_eq!(
            line,
            "GET /api/conversations.replies?limit=5&channel=C0123ABC&ts=1700000000.000100 HTTP/1.1"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_slack_replies_template_denies_another_channel_and_unlisted_keys() {
        let attested = slots(&[
            (ChatSlot::ConversationId, "C0123ABC"),
            (ChatSlot::ConversationThread, "1700000000.000100"),
        ]);
        for query in [
            "?channel=C0999ZZZ&limit=5",
            "?ts=1.2",
            "?limit=5&user=U1",
            "?a;channel=C0999ZZZ",
        ] {
            let error = template_denial(
                slack_replies("127.0.0.1:9"),
                attested.clone(),
                "GET",
                &format!("/api/conversations.replies{query}"),
            )
            .await;
            assert_eq!(error.code, ErrorCode::Denied, "{query}");
            assert!(!error.message.contains("C0123ABC"), "{}", error.message);
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_discord_template_fills_the_api_channel_into_the_path() {
        let attested = slots(&[(ChatSlot::ConversationApiChannel, "1122334455")]);
        for path in [
            "/channels/{conversation.apiChannel}/messages?limit=10",
            "/channels/%7Bconversation.apiChannel%7D/messages?limit=10",
        ] {
            assert_eq!(
                sent_request_line(discord_messages("127.0.0.1:9"), attested.clone(), path).await,
                "GET /channels/1122334455/messages?limit=10 HTTP/1.1"
            );
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_discord_template_denies_another_channel_in_the_path_and_other_methods() {
        let attested = slots(&[(ChatSlot::ConversationApiChannel, "1122334455")]);
        for (method, path) in [
            ("GET", "/channels/9988776655/messages"),
            ("GET", "/channels/{conversation.id}/messages"),
            ("GET", "/channels/{conversation.apiChannel}/messages/1"),
            (
                "GET",
                "/channels/{conversation.apiChannel}/../9988776655/messages",
            ),
            ("POST", "/channels/{conversation.apiChannel}/messages"),
        ] {
            let error = template_denial(
                discord_messages("127.0.0.1:9"),
                attested.clone(),
                method,
                path,
            )
            .await;
            assert_eq!(error.code, ErrorCode::Denied, "{method} {path}");
            assert!(!error.message.contains("1122334455"), "{}", error.message);
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_templated_get_with_a_body_is_denied_so_the_body_carries_no_second_channel() {
        let error = template_denial_with_body(
            slack_replies("127.0.0.1:9"),
            slots(&[
                (ChatSlot::ConversationId, "C0123ABC"),
                (ChatSlot::ConversationThread, "1700000000.000100"),
            ]),
            "GET",
            "/api/conversations.replies?limit=5",
            vec![Header {
                name: "content-type".to_owned(),
                value: b"application/x-www-form-urlencoded".to_vec(),
            }],
            b"channel=C0999ZZZ&ts=1.2".to_vec(),
        )
        .await;
        assert!(error.message.contains("takes no body"), "{}", error.message);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_template_slot_the_invocation_lacks_is_denied_before_connection() {
        let error = template_denial(
            slack_replies("127.0.0.1:9"),
            slots(&[(ChatSlot::ConversationId, "C0123ABC")]),
            "GET",
            "/api/conversations.replies",
        )
        .await;
        assert_eq!(error.code, ErrorCode::Denied);
    }

    #[test]
    fn a_drn_bound_bearer_secret_below_the_floor_is_refused() {
        let grant = secret_grant("api.example.test", SecretSinkKind::HttpBearer, None, "/v1");
        let error = BoundCredential::secret_bearer(
            SecretBytes::new(vec![b'x'; MIN_CREDENTIAL_BYTES - 1]),
            &grant,
        )
        .expect_err("a short resolved secret is refused");
        assert!(error.to_string().contains("16-byte minimum"), "{error}");
        assert!(!error.to_string().contains('x'), "{error}");
        BoundCredential::secret_bearer(SecretBytes::new(vec![b'x'; MIN_CREDENTIAL_BYTES]), &grant)
            .expect("a minimum-length resolved secret is a valid credential");
    }

    #[test]
    fn a_drn_bound_basic_secret_below_the_floor_is_refused() {
        let grant = secret_grant(
            "api.example.test",
            SecretSinkKind::HttpBasic,
            Some("userA"),
            "/v1",
        );
        let error = BoundCredential::secret_basic(
            SecretBytes::new(vec![b'x'; MIN_CREDENTIAL_BYTES - 1]),
            &grant,
        )
        .expect_err("a short resolved password is refused");
        assert!(error.to_string().contains("16-byte minimum"), "{error}");
        assert!(!error.to_string().contains('x'), "{error}");
        BoundCredential::secret_basic(SecretBytes::new(vec![b'x'; MIN_CREDENTIAL_BYTES]), &grant)
            .expect("a minimum-length resolved password is a valid credential");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn direct_credential_echo_is_discarded() {
        let response: &[u8] =
            b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\nConnection: close\r\n\r\nfixture-bearer-token";
        let server = LoopbackServer::once(response);
        let authority = server.authority().to_owned();
        let secret = secret_grant(&authority, SecretSinkKind::HttpBearer, None, "/echo");
        let credential = BoundCredential::secret_bearer(
            SecretBytes::new(b"fixture-bearer-token".to_vec()),
            &secret,
        )
        .expect("credential");
        let mut client = BufferedHttpClient::authorized_with_secret_credential(
            grant(authority.clone(), "GET"),
            secret,
            credential,
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("context");
        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: format!("http://{authority}/echo"),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect_err("an echoed token is never returned");
        assert_eq!(error.code, ErrorCode::Denied);
        assert!(!error.message.contains("fixture-bearer-token"), "{error}");
        let evidence = client.into_evidence();
        assert_eq!(evidence[0].status, Some(200));
        assert!(evidence[0].response_bytes > 0);
        server.join();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn legacy_credential_echo_is_discarded() {
        for body in ["fixture-secret-value", "Bearer fixture-secret-value"] {
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len()
            );
            let server = LoopbackServer::once(response.as_bytes());
            let authority = server.authority().to_owned();
            let mut client = BufferedHttpClient::authorized_with_credential(
                grant(authority.clone(), "GET"),
                Some(credential_for(&authority)),
                HttpHostCeilings::default(),
                Duration::from_secs(5),
            )
            .expect("valid fixture authorization");
            let error = client
                .send(Request {
                    method: "GET".to_owned(),
                    uri: format!("http://{authority}/echo"),
                    headers: Vec::new(),
                    body: Vec::new(),
                })
                .await
                .expect_err("an echoed legacy credential is never returned");
            assert_eq!(error.code, ErrorCode::Denied);
            assert!(!error.message.contains("fixture-secret-value"), "{error}");
            let evidence = client.into_evidence();
            assert_eq!(evidence[0].status, Some(200));
            assert!(evidence[0].credential_injected);
            server.join();
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn refuses_destinations_outside_the_credential_binding() {
        let mut client = BufferedHttpClient::authorized_with_credential(
            grant("127.0.0.1:9".to_owned(), "GET"),
            Some(credential_for("other.example.test")),
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization");
        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: "http://127.0.0.1:9/".to_owned(),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect_err("unbound destinations are refused, not sent unauthenticated");
        assert_eq!(error.code, ErrorCode::Denied);
        assert_eq!(client.policy_violation(), Some("denied"));
        let evidence = client.into_evidence();
        assert_eq!(evidence.len(), 1);
        assert_eq!(evidence[0].authority, "127.0.0.1:9");
        assert_eq!(evidence[0].status, None);
        assert!(!evidence[0].credential_injected);
    }

    fn chatgpt_credential_for(authority: &str) -> BoundCredential {
        BoundCredential::chatgpt_subscription(
            Redacted::new("fixture-access-token".to_owned()),
            "acct-fixture",
            vec![authority.to_owned()],
        )
        .expect("valid fixture credential")
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_chatgpt_subscription_credential_injects_both_headers_outside_accounted_bytes() {
        let response: &[u8] =
            b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok";
        let plain_server = LoopbackServer::once(response);
        let plain_authority = plain_server.authority().to_owned();
        let server = LoopbackServer::once(response);
        let authority = server.authority().to_owned();
        let request_to = |authority: &str| Request {
            method: "GET".to_owned(),
            uri: format!("http://{authority}/images/generations"),
            headers: vec![Header {
                name: "x-probe".to_owned(),
                value: b"one".to_vec(),
            }],
            body: Vec::new(),
        };

        let mut plain = BufferedHttpClient::authorized(
            grant(plain_authority.clone(), "GET"),
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization");
        plain
            .send(request_to(&plain_authority))
            .await
            .expect("uncredentialed request succeeds");

        let mut client = BufferedHttpClient::authorized_with_credential(
            grant(authority.clone(), "GET"),
            Some(chatgpt_credential_for(&authority)),
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization");
        client
            .send(request_to(&authority))
            .await
            .expect("credentialed request succeeds");

        let request = String::from_utf8(server.request()).expect("fixture request is UTF-8");
        assert!(
            request.contains("authorization: Bearer fixture-access-token"),
            "{request}"
        );
        assert!(
            request.contains("chatgpt-account-id: acct-fixture"),
            "{request}"
        );

        let plain_evidence = plain.into_evidence();
        let evidence = client.into_evidence();
        assert!(evidence[0].credential_injected);
        let authority_delta = authority.len() as i64 - plain_authority.len() as i64;
        assert_eq!(
            evidence[0].request_bytes as i64 - authority_delta,
            plain_evidence[0].request_bytes as i64
        );
        let serialized = serde_json::to_string(&evidence).expect("evidence serializes");
        assert!(!serialized.contains("acct-fixture"), "{serialized}");
        assert!(!serialized.contains("fixture-access-token"), "{serialized}");
        assert!(!serialized.contains("chatgpt"), "{serialized}");

        plain_server.join();
        server.join();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_guest_set_companion_header_is_rejected_not_overwritten() {
        let forged = || Request {
            method: "GET".to_owned(),
            uri: "http://127.0.0.1:9/".to_owned(),
            headers: vec![Header {
                name: "chatgpt-account-id".to_owned(),
                value: b"acct-guest-forged".to_vec(),
            }],
            body: Vec::new(),
        };

        let mut client = BufferedHttpClient::authorized_with_credential(
            grant("127.0.0.1:9".to_owned(), "GET"),
            Some(chatgpt_credential_for("127.0.0.1:9")),
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization");
        let error = client
            .send(forged())
            .await
            .expect_err("a guest-set companion header must be rejected");
        assert_eq!(error.code, ErrorCode::InvalidHeader);

        let mut uncompanioned = BufferedHttpClient::authorized_with_credential(
            grant("127.0.0.1:9".to_owned(), "GET"),
            Some(credential_for("127.0.0.1:9")),
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization");
        let error = uncompanioned
            .send(forged())
            .await
            .expect_err("nothing listens on port 9");
        assert_ne!(error.code, ErrorCode::InvalidHeader);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_chatgpt_subscription_credential_refuses_destinations_outside_its_binding() {
        let mut client = BufferedHttpClient::authorized_with_credential(
            grant("127.0.0.1:9".to_owned(), "GET"),
            Some(chatgpt_credential_for("other.example.test")),
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization");
        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: "http://127.0.0.1:9/".to_owned(),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect_err("unbound destinations are refused, not sent unauthenticated");
        assert_eq!(error.code, ErrorCode::Denied);
        let evidence = client.into_evidence();
        assert_eq!(evidence.len(), 1);
        assert!(!evidence[0].credential_injected);
    }

    #[test]
    fn a_chatgpt_subscription_credential_fails_closed_on_a_structural_account_id() {
        for account in ["", "acct with space", "acct\u{7f}control"] {
            let error = BoundCredential::chatgpt_subscription(
                Redacted::new("fixture-access-token".to_owned()),
                account,
                vec!["chatgpt.com".to_owned()],
            )
            .expect_err("a structurally invalid account identifier is refused");
            let rendered = error.to_string();
            assert!(rendered.contains("account identifier"), "{rendered}");
            assert!(!rendered.contains("fixture-access-token"), "{rendered}");
        }
        let error = BoundCredential::chatgpt_subscription(
            Redacted::new(String::new()),
            "acct-fixture",
            vec!["chatgpt.com".to_owned()],
        )
        .expect_err("an empty access token is refused");
        assert!(error.to_string().contains("16-byte minimum"), "{error}");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn guest_authorization_is_rejected_not_overwritten_when_a_credential_exists() {
        let mut client = BufferedHttpClient::authorized_with_credential(
            grant("127.0.0.1:9".to_owned(), "GET"),
            Some(credential_for("127.0.0.1:9")),
            HttpHostCeilings::default(),
            Duration::from_secs(1),
        )
        .expect("valid fixture authorization");
        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: "http://127.0.0.1:9/".to_owned(),
                headers: vec![Header {
                    name: "authorization".to_owned(),
                    value: b"Bearer guest-supplied".to_vec(),
                }],
                body: Vec::new(),
            })
            .await
            .expect_err("guest authorization must still be rejected");
        assert_eq!(error.code, ErrorCode::InvalidHeader);
    }

    #[test]
    fn credential_evidence_flag_defaults_for_old_records_and_serializes_compactly() {
        let old_record = r#"{"method":"GET","authority":"api.example.test:443","requestBytes":10,"responseBytes":20}"#;
        let evidence =
            serde_json::from_str::<HttpCallEvidence>(old_record).expect("old records still parse");
        assert!(!evidence.credential_injected);
        let serialized = serde_json::to_string(&evidence).expect("serializes");
        assert!(!serialized.contains("credentialInjected"), "{serialized}");

        let injected = HttpCallEvidence {
            credential_injected: true,
            ..evidence
        };
        let serialized = serde_json::to_string(&injected).expect("serializes");
        assert!(
            serialized.contains("\"credentialInjected\":true"),
            "{serialized}"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn streams_into_response_bound_and_never_follows_redirects() {
        let body = "x".repeat(512);
        let oversized = format!(
            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body.len(),
            body
        );
        let server = LoopbackServer::once(oversized.as_bytes());
        let authority = server.authority().to_owned();
        let mut limited_grant = grant(authority.clone(), "GET");
        limited_grant.max_response_bytes = 128;
        let mut client = BufferedHttpClient::authorized(
            limited_grant,
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization");
        let error = client
            .send(Request {
                method: "GET".to_owned(),
                uri: format!("http://{authority}/large"),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect_err("response bound must stop buffering");
        assert_eq!(error.code, ErrorCode::ResponseTooLarge);
        assert_eq!(client.policy_violation(), Some("byte-limit"));
        server.join();

        let server = LoopbackServer::once(
            b"HTTP/1.1 302 Found\r\nLocation: http://169.254.169.254/latest\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
        );
        let authority = server.authority().to_owned();
        let mut client = BufferedHttpClient::authorized(
            grant(authority.clone(), "GET"),
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization");
        let response = client
            .send(Request {
                method: "GET".to_owned(),
                uri: format!("http://{authority}/redirect"),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect("redirect response is returned without following");
        assert_eq!(response.status, 302);
        assert_eq!(client.into_evidence().len(), 1);
        server.join();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn reaches_ipv6_literal_loopback_destinations() {
        let Some(server) = LoopbackServer::bound(
            "[::1]:0",
            b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",
        ) else {
            return;
        };
        let authority = server.authority().to_owned();
        assert!(authority.starts_with("[::1]:"), "{authority}");

        let mut client = BufferedHttpClient::authorized(
            grant(authority.clone(), "GET"),
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization");
        let response = client
            .send(Request {
                method: "GET".to_owned(),
                uri: format!("http://{authority}/items"),
                headers: Vec::new(),
                body: Vec::new(),
            })
            .await
            .expect("an IPv6 literal loopback destination is reachable");

        assert_eq!(response.status, 200);
        let request = server.request();
        assert!(request.starts_with(b"GET /items HTTP/1.1\r\n"));
        let evidence = client.into_evidence();
        assert_eq!(evidence[0].authority, authority);
        server.join();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn reuses_one_pinned_client_across_calls_to_the_same_authority() {
        // Client-level pinning is deterministic, but whether hyper's connection pool reuses one TCP
        // connection is a background-task race this crate doesn't control, so the fixture tolerates
        // it without requiring it.
        let server = LoopbackServer::pooled(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok", 2);
        let authority = server.authority().to_owned();
        let mut client = BufferedHttpClient::authorized(
            grant(authority.clone(), "GET"),
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization");
        for _ in 0..2 {
            let response = client
                .send(Request {
                    method: "GET".to_owned(),
                    uri: format!("http://{authority}/items"),
                    headers: Vec::new(),
                    body: Vec::new(),
                })
                .await
                .expect("both calls share one pooled connection");
            assert_eq!(response.status, 200);
        }
        assert_eq!(client.into_evidence().len(), 2);
        server.join();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_changed_pin_set_builds_a_new_client() {
        let response: &[u8] =
            b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok";
        let first_server = LoopbackServer::once(response);
        let first = first_server.authority().to_owned();
        let second_server = LoopbackServer::once(response);
        let second = second_server.authority().to_owned();

        let mut grant = grant(first.clone(), "GET");
        grant.allowed_hosts.push(second.clone());
        let mut client = BufferedHttpClient::authorized(
            grant,
            HttpHostCeilings::default(),
            Duration::from_secs(5),
        )
        .expect("valid fixture authorization");
        for (authority, path) in [(&first, "/first"), (&second, "/second")] {
            let response = client
                .send(Request {
                    method: "GET".to_owned(),
                    uri: format!("http://{authority}{path}"),
                    headers: Vec::new(),
                    body: Vec::new(),
                })
                .await
                .expect("each destination is reachable");
            assert_eq!(response.status, 200);
        }

        assert!(
            first_server
                .request()
                .starts_with(b"GET /first HTTP/1.1\r\n")
        );
        assert!(
            second_server
                .request()
                .starts_with(b"GET /second HTTP/1.1\r\n")
        );
        let evidence = client.into_evidence();
        assert_eq!(evidence[0].authority, first);
        assert_eq!(evidence[1].authority, second);
        first_server.join();
        second_server.join();
    }

    #[test]
    fn bounds_and_sanitizes_error_messages() {
        let message = bounded_message(&format!("line one\n{}", "x".repeat(400)));
        assert!(message.len() <= 256);
        assert!(!message.contains('\n'));
    }
}