atomic-integration-proxy 0.4.3

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

const CONSENT_COOKIE: &str = "platform_consent";
const PROVIDER_COOKIE: &str = "platform_oauth";
/// Replaces `platform_consent` once it has been approved; holds its CSRF
/// token, so approving the same consent page again can say so.
const CONSENT_USED_COOKIE: &str = "platform_consent_used";
const ALREADY_APPROVED: &str = "You already approved this connection. Continue in the page that opened after approving; if it did not open or you closed it, start again from your hub";
const HANDOFF_AAD: &[u8] = b"platform-handoff-v2";
pub(crate) const OAUTH_CONTEXT_AAD: &[u8] = b"platform-oauth-v2";

/// A validated `/connect` request.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Request {
    pub platform: String,
    pub redirect_uri: String,
    pub code_challenge: String,
    pub code_challenge_method: String,
}

#[derive(Clone, Deserialize, Serialize)]
struct Consent {
    request: Request,
    csrf: String,
    expires: u64,
}

/// What travels (sealed) through the provider's authorization.
#[derive(Deserialize, Serialize)]
pub struct OAuthContext {
    pub request: Request,
    /// Random value also stored in a cookie, binding the callback to the
    /// browser that approved the consent screen.
    pub binding: String,
}

/// What a handoff code redeems to.
#[derive(Deserialize, Serialize)]
struct Handoff {
    platform: String,
    credential: crate::proxy::StoredCredential,
    /// From an API-key platform's key check; see [`check_api_key`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    label: Option<String>,
}

/// The longest connection label kept, in characters (as for delegation
/// labels in `connections.rs`).
const MAX_KEY_LABEL: usize = 200;
/// The longest key-check response read for a label.
const MAX_KEY_CHECK_BODY: usize = 64 * 1024;

/// What a platform's key check said about a pasted key.
#[derive(Debug, PartialEq, Eq)]
enum KeyCheck {
    /// 2xx, or no key check declared; with the declared label, if any.
    Accepted(Option<String>),
    /// 401 or 403.
    Rejected,
    /// Anything else, including no answer or a redirect.
    Undetermined,
}

/// Calls the scheme's `x-api-key-details.keyCheck` once with `key`
/// (openapi-extensions/spec/api-key-details, section 4.4). The shared client
/// follows no redirects; this call also gets a 10-second timeout. Nothing
/// here logs, and no error carries the key or the request URL.
async fn check_api_key(
    state: &AppState,
    scheme: &crate::providers::ApiKeyScheme,
    key: &str,
) -> KeyCheck {
    let Some(check) = &scheme.key_check else {
        return KeyCheck::Accepted(None);
    };
    let injection = match scheme.location {
        crate::providers::ApiKeyLocation::Header => crate::proxy::CredentialInjection::Header {
            name: scheme.name.clone(),
            value: key.to_owned(),
        },
        crate::providers::ApiKeyLocation::Query => {
            return run_key_check(state, check, Some((&scheme.name, key)), None).await
        }
        crate::providers::ApiKeyLocation::Cookie => return KeyCheck::Undetermined,
    };
    run_key_check(state, check, None, Some(injection)).await
}

/// The same key check for an `http` scheme's credential: the scheme's
/// `x-api-key-details.keyCheck`, called once with exactly the
/// `Authorization` header a proxied request would carry.
async fn check_http_credential(
    state: &AppState,
    scheme: &crate::providers::HttpScheme,
    credential: &crate::proxy::StoredCredential,
) -> KeyCheck {
    let Some(check) = &scheme.key_check else {
        return KeyCheck::Accepted(None);
    };
    let injection = match credential {
        crate::proxy::StoredCredential::HttpBearer { token, .. } => {
            crate::proxy::CredentialInjection::Bearer(token.clone())
        }
        crate::proxy::StoredCredential::HttpBasic {
            username, password, ..
        } => crate::proxy::CredentialInjection::Basic {
            username: username.clone(),
            password: password.clone(),
        },
        _ => return KeyCheck::Undetermined,
    };
    run_key_check(state, check, None, Some(injection)).await
}

/// Calls `check` once, with the credential in `query` (a query parameter)
/// or `injection` (a header), and reads the answer as section 4.4 of
/// openapi-extensions/spec/api-key-details says.
async fn run_key_check(
    state: &AppState,
    check: &crate::providers::KeyCheck,
    query: Option<(&str, &str)>,
    injection: Option<crate::proxy::CredentialInjection>,
) -> KeyCheck {
    let mut url = check.url.clone();
    #[cfg(test)]
    if let Some(upstream) = &state.test_upstream {
        url = Url::parse(&format!("{}{}", upstream.trim_end_matches('/'), url.path())).unwrap();
    }
    if let Some((name, value)) = query {
        url.query_pairs_mut().append_pair(name, value);
    }
    let request = injection
        .unwrap_or(crate::proxy::CredentialInjection::None)
        .apply(state.http_client.get(url));
    let Ok(response) = request
        .timeout(std::time::Duration::from_secs(10))
        .send()
        .await
    else {
        return KeyCheck::Undetermined;
    };
    let status = response.status();
    if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
        return KeyCheck::Rejected;
    }
    if !status.is_success() {
        return KeyCheck::Undetermined;
    }
    let Some(pointer) = &check.label_pointer else {
        return KeyCheck::Accepted(None);
    };
    let mut response = response;
    let mut body = Vec::new();
    let read = loop {
        match response.chunk().await {
            Ok(Some(chunk)) if body.len() + chunk.len() <= MAX_KEY_CHECK_BODY => {
                body.extend_from_slice(&chunk)
            }
            Ok(None) => break Ok(body),
            // Too long for a label, or broken off: accept without one.
            _ => break Err(()),
        }
    };
    let label = match read {
        Ok(body) => serde_json::from_slice::<serde_json::Value>(&body)
            .ok()
            .and_then(|body| {
                body.pointer(pointer)
                    .and_then(serde_json::Value::as_str)
                    .map(|label| {
                        label
                            .chars()
                            .filter(|c| !c.is_control())
                            .take(MAX_KEY_LABEL)
                            .collect::<String>()
                            .trim()
                            .to_owned()
                    })
            })
            .filter(|label| !label.is_empty()),
        _ => None,
    };
    KeyCheck::Accepted(label)
}

pub fn random() -> String {
    let mut bytes = [0u8; 32];
    rand::thread_rng().fill_bytes(&mut bytes);
    URL_SAFE_NO_PAD.encode(bytes)
}

pub fn pkce_challenge(verifier: &str) -> Option<String> {
    if !(43..=128).contains(&verifier.len())
        || !verifier
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b))
    {
        return None;
    }
    Some(URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())))
}

/// The Tauri app's deep-link scheme (decision 4). The OS hands such a URL to
/// the app; the provider itself only ever sees the proxy's `https` callback.
const DEEP_LINK_SCHEME: &str = "atomic";

impl Request {
    fn validate(&self) -> Result<Url, &'static str> {
        let url = Url::parse(&self.redirect_uri).map_err(|_| "Invalid return address")?;
        let loopback = matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"));
        let scheme_ok = url.scheme() == "https"
            || (url.scheme() == "http" && loopback)
            || url.scheme() == DEEP_LINK_SCHEME;
        if self.redirect_uri.len() > 1500
            || url.host_str().is_none_or(str::is_empty)
            || !scheme_ok
            || !url.username().is_empty()
            || url.password().is_some()
            || url.fragment().is_some()
            || url
                .query_pairs()
                .any(|(name, _)| matches!(name.as_ref(), "connection_code" | "error"))
        {
            return Err("Invalid return address");
        }
        if self.code_challenge_method != "S256"
            || self.code_challenge.len() != 43
            || URL_SAFE_NO_PAD
                .decode(&self.code_challenge)
                .map_or(true, |b| b.len() != 32)
            || crate::config::Config::provider_env_prefix(&self.platform).is_err()
        {
            return Err("Invalid connection request");
        }
        Ok(url)
    }
}

/// How the consent page names where the browser returns to: the origin for
/// a web address, the scheme and host for the app's deep link.
fn destination_label(url: &Url) -> String {
    if url.scheme() == DEEP_LINK_SCHEME {
        format!(
            "the Atomic app ({}://{})",
            url.scheme(),
            url.host_str().unwrap_or("")
        )
    } else {
        url.origin().ascii_serialization()
    }
}

/// The CSP source that lets the consent form's redirect chain end at `url`.
fn form_action_source(url: &Url) -> String {
    if url.scheme() == DEEP_LINK_SCHEME {
        format!("{DEEP_LINK_SCHEME}:")
    } else {
        url.origin().ascii_serialization()
    }
}

pub(crate) fn protected(response: impl IntoResponse) -> Response {
    let mut response = response.into_response();
    response
        .headers_mut()
        .insert(header::CACHE_CONTROL, "no-store".parse().unwrap());
    response
        .headers_mut()
        .insert("referrer-policy", "no-referrer".parse().unwrap());
    response.headers_mut().insert("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' https:; frame-ancestors 'none'; base-uri 'none'".parse().unwrap());
    response
}

fn error(message: &'static str) -> Response {
    protected((StatusCode::BAD_REQUEST, message))
}

fn private_cookie(name: &'static str, value: String) -> Cookie<'static> {
    Cookie::build((name, value))
        .path("/")
        .secure(true)
        .http_only(true)
        .same_site(SameSite::Lax)
        .max_age(time::Duration::minutes(10))
        .build()
}

/// `GET /connect`: the consent screen.
pub async fn page(
    State(state): State<AppState>,
    OriginalUri(uri): OriginalUri,
    jar: PrivateCookieJar,
) -> Response {
    let request = match Query::<Request>::try_from_uri(&uri) {
        Ok(Query(request)) => request,
        Err(_) => return error("Invalid connection request; start again from your hub"),
    };
    let target = match request.validate() {
        Ok(target) => target,
        Err(message) => return error(message),
    };
    if !state.catalog.names().contains(&request.platform) {
        return error("This platform is not available for connection");
    }
    let scheme = match state.catalog.security_scheme(&request.platform) {
        Ok(scheme) => scheme,
        Err(_) => return error("This platform is not available for connection"),
    };
    if matches!(scheme, crate::providers::SecurityScheme::OAuth(_))
        && Provider::configured(&state.catalog, &request.platform).is_err()
    {
        return error("This platform is not available for connection");
    }
    let consent = Consent {
        request: request.clone(),
        csrf: random(),
        expires: crate::now_secs() + 600,
    };
    let jar = jar.add(private_cookie(
        CONSENT_COOKIE,
        serde_json::to_string(&consent).unwrap(),
    ));
    consent_page(&state, jar, &consent, &target, &scheme, None)
}

/// The consent screen for `consent`, with the headers `page` documents.
/// `problem` is set when the page asks for an API key again.
fn consent_page(
    state: &AppState,
    jar: PrivateCookieJar,
    consent: &Consent,
    target: &Url,
    scheme: &crate::providers::SecurityScheme,
    problem: Option<&str>,
) -> Response {
    let request = &consent.request;
    let mut response = protected((
        jar,
        Html(templates::render_platform_connect(
            &state.operator,
            &request.platform,
            &destination_label(target),
            &consent.csrf,
            match scheme {
                crate::providers::SecurityScheme::OAuth(_) => templates::ConnectKind::OAuth,
                crate::providers::SecurityScheme::ApiKey(scheme) => {
                    templates::ConnectKind::ApiKey(templates::ApiKeyHelp {
                        description: scheme.description.as_deref(),
                        help_url: scheme.help_url.as_deref(),
                        problem,
                        ..templates::ApiKeyHelp::default()
                    })
                }
                crate::providers::SecurityScheme::Http(scheme) => {
                    templates::ConnectKind::ApiKey(templates::ApiKeyHelp {
                        description: scheme.description.as_deref(),
                        help_url: scheme.help_url.as_deref(),
                        problem,
                        secret: templates::SecretName::ApiToken,
                        username_label: match &scheme.auth {
                            crate::providers::HttpAuth::Basic(
                                crate::providers::BasicCredentials::PasswordTokenAskingUsername {
                                    label,
                                },
                            ) => Some(label.as_str()),
                            _ => None,
                        },
                    })
                }
                crate::providers::SecurityScheme::NoCredential => {
                    templates::ConnectKind::NoCredential
                }
            },
        )),
    ));
    // Keep the consent form's same-origin POST attributable while sending no
    // referrer to the selected provider.
    response
        .headers_mut()
        .insert(header::REFERRER_POLICY, "same-origin".parse().unwrap());
    // Chrome applies form-action to the whole redirect chain of a form
    // submission. An OAuth approval answers with a page (see
    // `templates::render_oauth_continue`) instead of redirecting, so the
    // provider's origins, however many it redirects through, and an
    // already-authorized provider returning straight through its callback to
    // the hub, are all outside that chain: only 'self' is needed. An apiKey
    // or no-credential approval redirects straight to the caller's
    // redirect_uri and never to a third party, so that origin is allowed too.
    let base = response.headers()["content-security-policy"]
        .to_str()
        .unwrap()
        .to_owned();
    let script = templates::consent_script_hash();
    let policy = match scheme {
        crate::providers::SecurityScheme::OAuth(_) => {
            format!("{base}; script-src {script}; form-action 'self'")
        }
        crate::providers::SecurityScheme::ApiKey(_)
        | crate::providers::SecurityScheme::Http(_)
        | crate::providers::SecurityScheme::NoCredential => format!(
            "{base}; script-src {script}; form-action 'self' {}",
            form_action_source(target)
        ),
    };
    response
        .headers_mut()
        .insert("content-security-policy", policy.parse().unwrap());
    response
}

#[derive(Deserialize)]
pub struct Approval {
    csrf: String,
    /// The pasted secret: an API key, or an `http` scheme's token.
    #[serde(default)]
    api_key: Option<String>,
    /// The username an `http` `basic` scheme asks for
    /// (`basicCredentials.usernameLabel`); ignored for every other kind.
    #[serde(default)]
    username: Option<String>,
}

fn valid_api_key(approval: &Approval) -> Option<&str> {
    approval
        .api_key
        .as_deref()
        .map(str::trim)
        .filter(|key| (4..=512).contains(&key.len()))
}

/// Whether `token` may be sent as `Authorization: Bearer <token>`: RFC 6750's
/// `b64token` (`[A-Za-z0-9-._~+/]+=*`), except that `:` is also allowed
/// before the padding. Asana's personal access tokens, as its documentation
/// shows them (`2/<user id>/<token id>:<secret>`), contain `:`; that format
/// is taken from its documentation, not checked against a live token. A `:`
/// cannot end or split the header value, so it widens nothing else.
fn bearer_token(token: &str) -> bool {
    let body = token.trim_end_matches('=');
    !body.is_empty()
        && body
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"-._~+/:".contains(&b))
}

/// The credential an `http` scheme's consent form submitted, laid out as
/// the scheme says, or why it cannot be used. A bearer token must be a
/// [`bearer_token`]; a Basic half may be any text without control
/// characters, and the username half may not contain `:` (RFC 7617).
fn http_credential(
    platform: &str,
    scheme: &crate::providers::HttpScheme,
    approval: &Approval,
) -> Result<crate::proxy::StoredCredential, &'static str> {
    use crate::providers::{BasicCredentials, HttpAuth};
    use crate::proxy::StoredCredential;
    let token = valid_api_key(approval).ok_or("Enter a valid API token")?;
    let printable = |text: &str| !text.chars().any(char::is_control);
    let provider = platform.to_owned();
    match &scheme.auth {
        HttpAuth::Bearer => {
            if !bearer_token(token) {
                return Err("Enter a valid API token");
            }
            Ok(StoredCredential::HttpBearer {
                provider,
                token: token.to_owned(),
                scheme: Some(scheme.name.clone()),
            })
        }
        HttpAuth::Basic(layout) => {
            if !printable(token) {
                return Err("Enter a valid API token");
            }
            let (username, password) = match layout {
                BasicCredentials::UsernameToken { password } => {
                    if token.contains(':') {
                        return Err("Enter a valid API token");
                    }
                    (token.to_owned(), password.clone())
                }
                BasicCredentials::PasswordToken { username } => {
                    (username.clone(), token.to_owned())
                }
                BasicCredentials::PasswordTokenAskingUsername { .. } => {
                    let username = approval
                        .username
                        .as_deref()
                        .map(str::trim)
                        .filter(|name| {
                            (1..=256).contains(&name.chars().count())
                                && printable(name)
                                && !name.contains(':')
                        })
                        .ok_or("Enter a valid username and API token")?;
                    (username.to_owned(), token.to_owned())
                }
            };
            Ok(StoredCredential::HttpBasic {
                provider,
                username,
                password,
                scheme: Some(scheme.name.clone()),
                layout: Some(layout.layout()),
            })
        }
    }
}

/// The most key checks one consent may make. A rejected key shows the
/// consent page again without spending the consent, so without a cap one
/// consent would let its holder try keys (or username and token pairs)
/// against the provider without limit.
const MAX_KEY_CHECKS: u32 = 5;
const TOO_MANY_KEY_CHECKS: &str =
    "Too many attempts to enter a key for this connection; start again from your hub";

fn key_check_slot(csrf: &str, n: u32) -> String {
    format!("consent-key-check:{csrf}:{n}")
}

/// Takes one of the consent's [`MAX_KEY_CHECKS`] key-check attempts before
/// a key check is called. The attempts are single-use records next to the
/// consent's own (`consent:<csrf>`, kept ten minutes, as long as a consent
/// lives), so they hold across instances and concurrent submissions. When
/// none is left the consent is spent, its cookie removed, and the answer is
/// "too many attempts"; an already spent consent answers as approved. On
/// success it also says whether this was the last attempt, so a rejection
/// then ends the consent instead of asking again.
async fn take_key_check(
    security: &Security,
    jar: PrivateCookieJar,
    csrf: &str,
) -> Result<(PrivateCookieJar, bool), Box<Response>> {
    let unavailable = || error("Connections are unavailable");
    match security
        .nonce_used(&key_check_slot(csrf, MAX_KEY_CHECKS))
        .await
    {
        Ok(true) => return Err(Box::new(too_many_key_checks(security, jar, csrf).await)),
        Ok(false) => {}
        Err(_) => return Err(Box::new(unavailable())),
    }
    match security.nonce_used(&format!("consent:{csrf}")).await {
        Ok(true) => return Err(Box::new(error(ALREADY_APPROVED))),
        Ok(false) => {}
        Err(_) => return Err(Box::new(unavailable())),
    }
    for n in 1..=MAX_KEY_CHECKS {
        match security.consume_nonce(&key_check_slot(csrf, n)).await {
            Ok(true) => return Ok((jar, n == MAX_KEY_CHECKS)),
            Ok(false) => {}
            Err(_) => return Err(Box::new(unavailable())),
        }
    }
    Err(Box::new(too_many_key_checks(security, jar, csrf).await))
}

/// Takes one of the client network's key checks for `platform`
/// (`KEY_CHECK_LIMIT_PER_HOUR`), before the consent's own
/// [`take_key_check`]. [`MAX_KEY_CHECKS`] bounds one consent page, but
/// `GET /connect` needs no signature, so without this a script could open
/// consent pages and test keys against the provider without end. When the
/// network has none left the answer is `429` and nothing else happens: no
/// key check, and the consent is not spent. Only the hashed bucket (and the
/// platform) is logged, never the address.
async fn take_network_key_check(
    state: &AppState,
    security: &Security,
    headers: &HeaderMap,
    peer: Option<std::net::SocketAddr>,
    platform: &str,
) -> Result<(), Box<Response>> {
    if state.key_check_limit == 0 {
        return Ok(());
    }
    let network = crate::client_addr::client_network(state.trust_forwarded_for, headers, peer);
    let bucket = security.key_check_bucket(platform, &network);
    if network == crate::client_addr::UNKNOWN || network == crate::client_addr::UNPARSEABLE {
        tracing::warn!(
            %bucket,
            "key check without a usable client address; every such check shares one limit"
        );
    }
    match security
        .take_key_check_allowance(&bucket, state.key_check_limit, state.key_check_window)
        .await
    {
        Ok(None) => Ok(()),
        Ok(Some(retry_after)) => {
            tracing::warn!(%bucket, platform, "key check limit reached");
            let mut response = protected((
                StatusCode::TOO_MANY_REQUESTS,
                format!(
                    "Too many key checks from your network for {}; try again later",
                    templates::platform_label(platform)
                ),
            ));
            response
                .headers_mut()
                .insert(header::RETRY_AFTER, retry_after.into());
            Err(Box::new(response))
        }
        Err(_) => Err(Box::new(error("Connections are unavailable"))),
    }
}

/// Spends the consent and says there were too many attempts.
async fn too_many_key_checks(security: &Security, jar: PrivateCookieJar, csrf: &str) -> Response {
    if security
        .consume_nonce(&format!("consent:{csrf}"))
        .await
        .is_err()
    {
        return error("Connections are unavailable");
    }
    protected((
        StatusCode::BAD_REQUEST,
        jar.remove(Cookie::build(CONSENT_COOKIE).path("/").build()),
        TOO_MANY_KEY_CHECKS,
    ))
}

/// `POST /connect/authorize`: the consent form's submission.
pub async fn authorize(
    State(state): State<AppState>,
    peer: Option<ConnectInfo<std::net::SocketAddr>>,
    jar: PrivateCookieJar,
    headers: HeaderMap,
    Form(approval): Form<Approval>,
) -> Response {
    // Browser form origin is an extra defense; the encrypted cookie and random CSRF token are required.
    if headers
        .get(header::ORIGIN)
        .is_some_and(|origin| origin.to_str().ok() != Some(state.public_origin.as_str()))
    {
        return error("Invalid connection approval");
    }
    let Some(cookie) = jar.get(CONSENT_COOKIE) else {
        // The first approval replaced the consent cookie with this marker, so
        // a second click on the same consent page (the back button, a
        // navigation that seemed stuck) is told what happened rather than
        // that the request expired.
        if jar
            .get(CONSENT_USED_COOKIE)
            .is_some_and(|used| used.value() == approval.csrf)
        {
            return error(ALREADY_APPROVED);
        }
        return error("Connection request expired; start again from your hub");
    };
    let Ok(consent) = serde_json::from_str::<Consent>(cookie.value()) else {
        return error("Invalid connection approval");
    };
    if consent.expires <= crate::now_secs()
        || consent.csrf != approval.csrf
        || consent.request.validate().is_err()
    {
        return error("Connection request expired or invalid; start again from your hub");
    }
    let Some(security) = &state.security else {
        return error("Connections are unavailable");
    };
    let peer = peer.map(|ConnectInfo(peer)| peer);
    let mut jar = jar;
    // Refuse an unusable API key before the consent is spent, so correcting
    // it and approving again works. That includes a key the platform's key
    // check (`x-api-key-details.keyCheck`) rejects: the page asks again.
    let mut key_label = None;
    if let Ok(scheme @ crate::providers::SecurityScheme::ApiKey(_)) =
        state.catalog.security_scheme(&consent.request.platform)
    {
        let crate::providers::SecurityScheme::ApiKey(api_key) = &scheme else {
            unreachable!("matched as ApiKey above");
        };
        let Some(key) = valid_api_key(&approval) else {
            return error("Enter a valid API key");
        };
        // Only a check that will reach the provider counts against the
        // network: none without a declared key check, and none for a
        // cookie key, which is never checked (`check_api_key`).
        let checks_upstream = api_key.key_check.is_some()
            && !matches!(api_key.location, crate::providers::ApiKeyLocation::Cookie);
        if checks_upstream {
            if let Err(response) =
                take_network_key_check(&state, security, &headers, peer, &consent.request.platform)
                    .await
            {
                return *response;
            }
        }
        let last = match take_key_check(security, jar, &consent.csrf).await {
            Ok((taken, last)) => {
                jar = taken;
                last
            }
            Err(response) => return *response,
        };
        match check_api_key(&state, api_key, key).await {
            KeyCheck::Accepted(label) => key_label = label,
            KeyCheck::Rejected if last => {
                return too_many_key_checks(security, jar, &consent.csrf).await
            }
            KeyCheck::Rejected => {
                let Ok(target) = consent.request.validate() else {
                    return error("Connection request expired or invalid; start again from your hub");
                };
                let problem = format!(
                    "{} did not accept that API key. Check it and enter it again.",
                    templates::platform_label(&consent.request.platform)
                );
                return consent_page(&state, jar, &consent, &target, &scheme, Some(&problem));
            }
            KeyCheck::Undetermined => {
                return error(
                    "Could not check the API key with the platform; nothing was stored. Try again later",
                )
            }
        }
    }
    // The same for an `http` scheme's token: built and checked before the
    // consent is spent, and handed off below as it was checked.
    let mut http_credential_checked = None;
    if let Ok(scheme @ crate::providers::SecurityScheme::Http(_)) =
        state.catalog.security_scheme(&consent.request.platform)
    {
        let crate::providers::SecurityScheme::Http(http) = &scheme else {
            unreachable!("matched as Http above");
        };
        let credential = match http_credential(&consent.request.platform, http, &approval) {
            Ok(credential) => credential,
            Err(message) => return error(message),
        };
        // Only a check that will reach the provider counts against the
        // network (`check_http_credential`).
        if http.key_check.is_some() {
            if let Err(response) =
                take_network_key_check(&state, security, &headers, peer, &consent.request.platform)
                    .await
            {
                return *response;
            }
        }
        let last = match take_key_check(security, jar, &consent.csrf).await {
            Ok((taken, last)) => {
                jar = taken;
                last
            }
            Err(response) => return *response,
        };
        match check_http_credential(&state, http, &credential).await {
            KeyCheck::Accepted(label) => key_label = label,
            KeyCheck::Rejected if last => {
                return too_many_key_checks(security, jar, &consent.csrf).await
            }
            KeyCheck::Rejected => {
                let Ok(target) = consent.request.validate() else {
                    return error("Connection request expired or invalid; start again from your hub");
                };
                let problem = format!(
                    "{} did not accept that API token. Check it and enter it again.",
                    templates::platform_label(&consent.request.platform)
                );
                return consent_page(&state, jar, &consent, &target, &scheme, Some(&problem));
            }
            KeyCheck::Undetermined => {
                return error(
                    "Could not check the API token with the platform; nothing was stored. Try again later",
                )
            }
        }
        http_credential_checked = Some(credential);
    }
    match security
        .consume_nonce(&format!("consent:{}", consent.csrf))
        .await
    {
        Ok(true) => {}
        // Spent by an earlier submission that still carried this cookie
        // (a double click before the first answer arrived).
        Ok(false) => return error(ALREADY_APPROVED),
        Err(_) => return error("Connections are unavailable"),
    }
    let jar = jar
        .remove(Cookie::build(CONSENT_COOKIE).path("/").build())
        .add(private_cookie(CONSENT_USED_COOKIE, consent.csrf.clone()));
    // Only an OAuth platform goes on to a third party from here; an apiKey
    // platform already has everything it needs (the submitted key), and a
    // no-credential platform needs nothing, so both complete the handoff
    // directly (decision 11).
    match state.catalog.security_scheme(&consent.request.platform) {
        Ok(crate::providers::SecurityScheme::ApiKey(api_key)) => {
            let Some(key) = valid_api_key(&approval) else {
                return error("Enter a valid API key");
            };
            let credential = crate::proxy::StoredCredential::ApiKey {
                provider: consent.request.platform.clone(),
                key: key.to_owned(),
                placement: Some(api_key.placement()),
                scheme: Some(api_key.scheme_name),
            };
            let code =
                match labelled_handoff(security, &consent.request, credential, key_label).await {
                    Ok(code) => code,
                    Err(()) => return error("Could not complete connection"),
                };
            finish_with_connection_code(jar, &consent.request.redirect_uri, &code)
        }
        Ok(crate::providers::SecurityScheme::Http(_)) => {
            let Some(credential) = http_credential_checked else {
                return error("Enter a valid API token");
            };
            let code =
                match labelled_handoff(security, &consent.request, credential, key_label).await {
                    Ok(code) => code,
                    Err(()) => return error("Could not complete connection"),
                };
            finish_with_connection_code(jar, &consent.request.redirect_uri, &code)
        }
        Ok(crate::providers::SecurityScheme::NoCredential) => {
            // Consent is all there is: no key is read, even if one was sent.
            let credential = crate::proxy::StoredCredential::NoCredential {
                provider: consent.request.platform.clone(),
            };
            let code = match handoff(security, &consent.request, credential).await {
                Ok(code) => code,
                Err(()) => return error("Could not complete connection"),
            };
            finish_with_connection_code(jar, &consent.request.redirect_uri, &code)
        }
        Ok(crate::providers::SecurityScheme::OAuth(_)) => {
            let context = OAuthContext {
                request: consent.request.clone(),
                binding: random(),
            };
            let Ok(sealed_context) =
                security.seal(&serde_json::to_vec(&context).unwrap(), OAUTH_CONTEXT_AAD)
            else {
                return error("Could not start connection");
            };
            let url = match oauth::begin(&state, &consent.request.platform, sealed_context).await {
                Ok(url) => url,
                Err(()) => return error("Could not start platform authorization"),
            };
            // The continue page puts this address in a refresh and a link;
            // only a web address may go there.
            if !Url::parse(&url).is_ok_and(|url| matches!(url.scheme(), "https" | "http")) {
                return error("Could not start platform authorization");
            }
            // A page, not a redirect: see `templates::render_oauth_continue`.
            // `protected` sends it with `Referrer-Policy: no-referrer`, so the
            // provider learns nothing about the proxy page it came from.
            protected((
                jar.add(private_cookie(PROVIDER_COOKIE, context.binding)),
                Html(templates::render_oauth_continue(
                    &state.operator,
                    &consent.request.platform,
                    &url,
                )),
            ))
        }
        Err(_) => error("This platform is not available for connection"),
    }
}

/// Opens a sealed OAuth context and checks it belongs to this browser.
pub fn oauth_context(
    security: &Security,
    value: &str,
    jar: &PrivateCookieJar,
) -> Option<OAuthContext> {
    let context: OAuthContext =
        serde_json::from_slice(&security.open(value, OAUTH_CONTEXT_AAD)?).ok()?;
    if jar.get(PROVIDER_COOKIE)?.value() != context.binding {
        return None;
    }
    Some(context)
}

pub fn clear_provider_cookie(jar: PrivateCookieJar) -> PrivateCookieJar {
    jar.remove(Cookie::build(PROVIDER_COOKIE).path("/").build())
}

/// Redirects the browser back to `redirect_uri` with the handoff
/// `connection_code` appended. Shared by the OAuth callback and the apiKey
/// branch of `authorize`.
pub(crate) fn finish_with_connection_code(
    jar: PrivateCookieJar,
    redirect_uri: &str,
    code: &str,
) -> Response {
    let Ok(mut redirect) = Url::parse(redirect_uri) else {
        return error("Could not complete connection");
    };
    redirect
        .query_pairs_mut()
        .append_pair("connection_code", code);
    protected((clear_provider_cookie(jar), Redirect::to(redirect.as_str())))
}

/// Seals `credential` into a single-use, five-minute handoff bound to the
/// request's PKCE challenge, and returns its code.
pub(crate) async fn handoff(
    security: &Security,
    request: &Request,
    credential: crate::proxy::StoredCredential,
) -> Result<String, ()> {
    labelled_handoff(security, request, credential, None).await
}

/// [`handoff`] with the display label the connection will carry.
async fn labelled_handoff(
    security: &Security,
    request: &Request,
    credential: crate::proxy::StoredCredential,
    label: Option<String>,
) -> Result<String, ()> {
    let handoff = Handoff {
        platform: request.platform.clone(),
        credential,
        label,
    };
    let envelope = security
        .seal(&serde_json::to_vec(&handoff).map_err(|_| ())?, HANDOFF_AAD)
        .map_err(|_| ())?;
    let code = random();
    security
        .store_handoff(&code, &request.code_challenge, &envelope)
        .await
        .map_err(|_| ())?;
    Ok(code)
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Redemption {
    code: String,
    code_verifier: String,
}

/// `POST /connect/redeem`, signed (Atomic v2) by the key that will own the
/// connection. Body `{"code", "code_verifier"}`; answers
/// `{"connection_id", "platform", "owner"}`.
pub async fn redeem(
    State(state): State<AppState>,
    method: Method,
    OriginalUri(uri): OriginalUri,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    match redeem_inner(&state, &method, &uri, &headers, &body).await {
        Ok(response) => protected(response),
        Err(error) => error.into_response(),
    }
}

/// An owner write refused because the owner was retired meanwhile (#410)
/// answers `agent_retired`; any other failure, `unavailable`.
pub(crate) fn owner_write_error(error: String) -> ApiError {
    if error == crate::security::OWNER_RETIRED {
        ApiError::AgentRetired
    } else {
        ApiError::Unavailable
    }
}

async fn redeem_inner(
    state: &AppState,
    method: &Method,
    uri: &axum::http::Uri,
    headers: &HeaderMap,
    body: &Bytes,
) -> Result<Json<serde_json::Value>, ApiError> {
    let security = state.security.as_ref().ok_or(ApiError::Unavailable)?;
    let owner = crate::signature::authenticate(state, security, method, uri, headers, body).await?;
    crate::check_access(state, &owner).await?;
    let request: Redemption = serde_json::from_slice(body)
        .map_err(|_| ApiError::BadRequest("body must be {\"code\", \"code_verifier\"}"))?;
    let challenge = pkce_challenge(&request.code_verifier).ok_or(ApiError::InvalidHandoff)?;
    if request.code.len() != 43 {
        return Err(ApiError::InvalidHandoff);
    }
    let envelope = security
        .take_handoff(&request.code, &challenge)
        .await
        .map_err(|_| ApiError::Unavailable)?
        .ok_or(ApiError::InvalidHandoff)?;
    let handoff: Handoff = security
        .open(&envelope, HANDOFF_AAD)
        .and_then(|plaintext| serde_json::from_slice(&plaintext).ok())
        .ok_or(ApiError::InvalidHandoff)?;
    let credential = serde_json::to_vec(&handoff.credential).map_err(|_| ApiError::Internal)?;
    let connection_id = security
        .create_labelled_connection(
            &handoff.platform,
            owner.as_str(),
            &credential,
            handoff.label.as_deref(),
        )
        .await
        .map_err(owner_write_error)?;
    let mut answer = serde_json::json!({
        "connection_id": connection_id,
        "platform": handoff.platform,
        "owner": owner.as_str(),
    });
    if let Some(label) = handoff.label {
        answer["label"] = label.into();
    }
    Ok(Json(answer))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent_id::test_signer::Agent;
    use crate::test_support::{body_json, signed_request, state};
    use tower::ServiceExt;

    fn request() -> Request {
        Request {
            platform: "github-issues".into(),
            redirect_uri:
                "https://hub.example/app/integrations?integration_state=state&platform=github-issues"
                    .into(),
            code_challenge: pkce_challenge(&"a".repeat(43)).unwrap(),
            code_challenge_method: "S256".into(),
        }
    }

    fn connect_uri(request: &Request) -> String {
        let query = url::form_urlencoded::Serializer::new(String::new())
            .append_pair("platform", &request.platform)
            .append_pair("redirect_uri", &request.redirect_uri)
            .append_pair("code_challenge", &request.code_challenge)
            .append_pair("code_challenge_method", &request.code_challenge_method)
            .finish();
        format!("/connect?{query}")
    }

    #[test]
    fn return_address_rejects_insecure_or_ambiguous_targets() {
        for value in [
            "http://hub.example/cb",
            "javascript:alert(1)",
            "https://user:pass@hub.example/cb",
            "https://hub.example/cb#fragment",
            "https://hub.example/cb?connection_code=evil",
            "https://hub.example/cb?error=evil",
            "tauri://localhost/app/integrations",
            "atomic:integrations",
            "atomic://user@integrations/return",
        ] {
            let mut request = request();
            request.redirect_uri = value.into();
            assert!(request.validate().is_err(), "{value}");
        }
        for value in [
            "http://localhost:6747/app/integrations",
            "http://127.0.0.1:9883/app/integrations",
            "atomic://integrations/return",
            "atomic://integrations/return?integration_state=abc",
        ] {
            let mut request = request();
            request.redirect_uri = value.into();
            assert!(request.validate().is_ok(), "{value}");
        }
    }

    #[test]
    fn pkce_uses_rfc7636_s256_and_rejects_weak_input() {
        assert_eq!(
            pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk").unwrap(),
            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
        );
        assert!(pkce_challenge("short").is_none());
        assert!(pkce_challenge(&"!".repeat(43)).is_none());
        let mut request = request();
        request.code_challenge_method = "plain".into();
        assert!(request.validate().is_err());
    }

    #[tokio::test]
    async fn the_consent_page_needs_no_login_and_names_the_destination() {
        let mut s = state(None);
        s.catalog = crate::catalog::Catalog::for_test("github-issues");
        let response = crate::router(s)
            .oneshot(
                axum::http::Request::builder()
                    .uri(connect_uri(&request()))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = response.status();
        let body = String::from_utf8(
            axum::body::to_bytes(response.into_body(), 65_536)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();
        // The fixture provider is only "configured" when CI's fixture OAuth
        // env vars are present; otherwise the page says so, without asking
        // anyone to log in either way.
        assert!(!body.to_lowercase().contains("log in"), "{body}");
        if status == StatusCode::OK {
            assert!(body.contains("https://hub.example"));
        } else {
            assert!(body.contains("not available"));
        }
    }

    async fn get_body(s: AppState, uri: &str) -> (StatusCode, String) {
        let response = crate::router(s)
            .oneshot(
                axum::http::Request::builder()
                    .uri(uri)
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = response.status();
        let body = axum::body::to_bytes(response.into_body(), 65_536)
            .await
            .unwrap();
        (status, String::from_utf8(body.to_vec()).unwrap())
    }

    async fn body_text(response: Response) -> String {
        let body = axum::body::to_bytes(response.into_body(), 65_536)
            .await
            .unwrap();
        String::from_utf8(body.to_vec()).unwrap()
    }

    /// The `name=value` pair of a cookie `response` sets, if any.
    fn set_cookie(response: &Response, name: &str) -> Option<String> {
        response
            .headers()
            .get_all(header::SET_COOKIE)
            .iter()
            .map(|v| v.to_str().unwrap().split(';').next().unwrap().to_string())
            .find(|v| v.starts_with(&format!("{name}=")))
    }

    /// Where an OAuth approval's continue page sends the browser. It must be
    /// a `200` page (not a redirect, which the consent page's `form-action`
    /// would govern), whose refresh and button both lead to the provider,
    /// and which sends no referrer and runs no script.
    async fn continue_page(response: Response) -> Url {
        assert_eq!(
            response.status(),
            StatusCode::OK,
            "configure fixture OAUTH_GITHUB_ISSUES_CLIENT_ID and CLIENT_SECRET"
        );
        assert!(response.headers().get(header::LOCATION).is_none());
        assert_eq!(response.headers()[header::REFERRER_POLICY], "no-referrer");
        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
        let policy = response.headers()["content-security-policy"]
            .to_str()
            .unwrap()
            .to_owned();
        assert!(policy.starts_with("default-src 'none';"), "{policy}");
        assert!(!policy.contains("script-src"), "{policy}");
        let html = body_text(response).await;
        assert!(!html.contains("<script"), "{html}");
        let attribute = |prefix: &str| {
            html.split(prefix)
                .nth(1)
                .unwrap_or_else(|| panic!("no {prefix} in {html}"))
                .split('"')
                .next()
                .unwrap()
                .replace("&amp;", "&")
        };
        let refresh = attribute(r#"<meta http-equiv="refresh" content="0;url="#);
        let button = attribute(r#"<a class="button" href=""#);
        assert_eq!(refresh, button);
        Url::parse(&refresh).unwrap()
    }

    #[tokio::test]
    async fn a_second_approval_says_it_was_already_approved_not_expired() {
        let s = state(None);
        // What the browser holds after a first approval: no consent cookie,
        // and the marker naming the consent it spent.
        let jar = PrivateCookieJar::new(s.key.clone())
            .add(private_cookie(CONSENT_USED_COOKIE, "used".into()));
        for (jar, csrf, message) in [
            (jar.clone(), "used", ALREADY_APPROVED),
            // Another consent page's token is not "already approved".
            (
                jar,
                "other",
                "Connection request expired; start again from your hub",
            ),
            (
                PrivateCookieJar::new(s.key.clone()),
                "used",
                "Connection request expired; start again from your hub",
            ),
        ] {
            let response = authorize(
                State(s.clone()),
                None,
                jar,
                HeaderMap::new(),
                Form(Approval {
                    csrf: csrf.into(),
                    api_key: None,
                    username: None,
                }),
            )
            .await;
            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
            assert_eq!(body_text(response).await, message, "{csrf}");
        }
    }

    #[tokio::test]
    async fn the_consent_page_allows_only_its_own_script() {
        let mut s = state(None);
        s.catalog = api_key_catalog();
        let (status, html) = get_body(s.clone(), &connect_uri(&api_key_request())).await;
        assert_eq!(status, StatusCode::OK);
        let response = crate::router(s)
            .oneshot(
                axum::http::Request::builder()
                    .uri(connect_uri(&api_key_request()))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let policy = response.headers()["content-security-policy"]
            .to_str()
            .unwrap()
            .to_owned();
        // An apiKey approval still redirects straight to the destination.
        assert!(
            policy.ends_with(&format!(
                "; script-src {}; form-action 'self' https://hub.example",
                templates::consent_script_hash()
            )),
            "{policy}"
        );
        assert!(
            !policy.contains("unsafe-inline'; script") && !policy.contains("script-src 'self'")
        );
        // The one inline script is exactly the one the hash allows.
        let scripts: Vec<_> = html.split("<script>").skip(1).collect();
        assert_eq!(scripts.len(), 1, "{html}");
        assert_eq!(
            scripts[0].split("</script>").next().unwrap(),
            templates::CONSENT_SCRIPT
        );
    }

    #[tokio::test]
    async fn the_pages_name_the_configured_operator_and_the_proxy_host() {
        let mut s = state(None);
        s.catalog = crate::catalog::Catalog::for_test("github-issues");
        s.operator = crate::templates::Operator::new(
            "Example <Co>",
            Some("https://operator.example/"),
            &crate::config::public_host(crate::test_support::BASE_URL),
        );

        let (status, home) = get_body(s.clone(), "/").await;
        assert_eq!(status, StatusCode::OK);
        assert!(home.contains("Example &lt;Co&gt;"), "{home}");
        assert!(home.contains("proxy.example"), "{home}");
        assert!(!home.contains("LocalThought"), "{home}");

        // As above: the fixture provider is only configured under CI's
        // fixture OAuth env vars.
        let (status, consent) = get_body(s, &connect_uri(&request())).await;
        if status == StatusCode::OK {
            assert!(
                consent.contains(
                    r#"Integration proxy <strong>proxy.example</strong>, run by <a href="https://operator.example/" rel="noopener noreferrer">Example &lt;Co&gt;</a>."#
                ),
                "{consent}"
            );
            assert!(!consent.contains("LocalThought"), "{consent}");
        } else {
            assert!(consent.contains("not available"));
        }
    }

    #[tokio::test]
    async fn legacy_connect_parameters_are_refused() {
        let s = state(None);
        for query in [
            // The tenant-secret bootstrap (flag day, decision 6).
            "/connect?redirect_uri=https%3A%2F%2Fhub.example%2Fcb&ts=1&nonce=n&challenge=c&tenant_id=t&user_id=u&user_id_sig=s&response=r",
            // No platform.
            "/connect?redirect_uri=https%3A%2F%2Fhub.example%2Fcb",
        ] {
            let response = crate::router(s.clone())
                .oneshot(
                    axum::http::Request::builder()
                        .uri(query)
                        .body(axum::body::Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{query}");
        }
    }

    #[tokio::test]
    async fn removed_tenant_routes_are_gone() {
        let s = state(None);
        for (method, path) in [
            ("GET", "/session"),
            ("GET", "/auth/login"),
            ("GET", "/auth/callback"),
            ("POST", "/auth/logout"),
            ("GET", "/auth/login/github-issues"),
            ("POST", "/connect"),
            ("GET", "/proxy"),
            ("GET", "/oauth/github-issues/start"),
        ] {
            let response = crate::router(s.clone())
                .oneshot(
                    axum::http::Request::builder()
                        .method(method)
                        .uri(path)
                        .body(axum::body::Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            assert!(
                matches!(
                    response.status(),
                    StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED
                ),
                "{method} {path}: {}",
                response.status()
            );
        }
    }

    #[tokio::test]
    async fn consent_rejects_a_missing_cookie_or_wrong_csrf() {
        let s = state(None);
        let jar = PrivateCookieJar::new(s.key.clone());
        let result = authorize(
            State(s.clone()),
            None,
            jar.clone(),
            HeaderMap::new(),
            Form(Approval {
                csrf: "wrong".into(),
                api_key: None,
                username: None,
            }),
        )
        .await;
        assert_eq!(result.status(), StatusCode::BAD_REQUEST);
        let consent = Consent {
            request: request(),
            csrf: "valid".into(),
            expires: crate::now_secs() + 600,
        };
        let jar = jar.add(private_cookie(
            CONSENT_COOKIE,
            serde_json::to_string(&consent).unwrap(),
        ));
        for (csrf, origin) in [
            ("wrong", None),
            ("valid", Some("https://foreign.example")),
            ("valid", Some("null")),
        ] {
            let mut headers = HeaderMap::new();
            if let Some(origin) = origin {
                headers.insert(header::ORIGIN, origin.parse().unwrap());
            }
            let result = authorize(
                State(s.clone()),
                None,
                jar.clone(),
                headers,
                Form(Approval {
                    csrf: csrf.into(),
                    api_key: None,
                    username: None,
                }),
            )
            .await;
            assert_eq!(
                result.status(),
                StatusCode::BAD_REQUEST,
                "{csrf} {origin:?}"
            );
        }
    }

    fn api_key_catalog() -> crate::catalog::Catalog {
        crate::catalog::Catalog::from_test_document(
            "clockify",
            serde_json::json!({
                "servers": [{"url": "https://api.clockify.me/v1"}],
                "components": {"securitySchemes": {"clockifyApiKey": {
                    "type": "apiKey", "in": "header", "name": "X-Api-Key"
                }}},
                "security": [{"clockifyApiKey": []}],
                "paths": {"/workspaces": {"get": {}}}
            }),
            serde_json::json!({}),
        )
    }

    fn api_key_request() -> Request {
        Request {
            platform: "clockify".into(),
            redirect_uri:
                "https://hub.example/app/integrations?integration_state=state&platform=clockify"
                    .into(),
            code_challenge: pkce_challenge(&"a".repeat(43)).unwrap(),
            code_challenge_method: "S256".into(),
        }
    }

    async fn redeem_as(
        s: &AppState,
        agent: &Agent,
        code: &str,
        verifier: &str,
    ) -> axum::response::Response {
        let body = serde_json::json!({"code": code, "code_verifier": verifier}).to_string();
        crate::router(s.clone())
            .oneshot(signed_request(
                s,
                agent,
                "POST",
                "/connect/redeem",
                body.into_bytes(),
            ))
            .await
            .unwrap()
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_api_key_connect_makes_the_redeem_signer_the_owner() {
        let security = crate::test_support::security().await;
        let mut s = state(Some(security.clone()));
        s.catalog = api_key_catalog();
        let consent = Consent {
            request: api_key_request(),
            csrf: random(),
            expires: crate::now_secs() + 600,
        };
        let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
            CONSENT_COOKIE,
            serde_json::to_string(&consent).unwrap(),
        ));
        // A blank key is refused without spending the consent, so the same
        // page can approve again with a corrected key.
        let blank = authorize(
            State(s.clone()),
            None,
            jar.clone(),
            HeaderMap::new(),
            Form(Approval {
                csrf: consent.csrf.clone(),
                api_key: Some("  ".into()),
                username: None,
            }),
        )
        .await;
        assert_eq!(blank.status(), StatusCode::BAD_REQUEST);
        assert_eq!(body_text(blank).await, "Enter a valid API key");
        let response = authorize(
            State(s.clone()),
            None,
            jar.clone(),
            HeaderMap::new(),
            Form(Approval {
                csrf: consent.csrf.clone(),
                api_key: Some("clockify-secret".into()),
                username: None,
            }),
        )
        .await;
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        let location = Url::parse(response.headers()[header::LOCATION].to_str().unwrap()).unwrap();
        assert_eq!(
            location.origin().ascii_serialization(),
            "https://hub.example"
        );
        let code = location
            .query_pairs()
            .find(|(k, _)| k == "connection_code")
            .unwrap()
            .1
            .into_owned();
        // The consent cannot be approved twice, and a second approval says
        // why.
        let again = authorize(
            State(s.clone()),
            None,
            jar,
            HeaderMap::new(),
            Form(Approval {
                csrf: consent.csrf.clone(),
                api_key: Some("clockify-secret".into()),
                username: None,
            }),
        )
        .await;
        assert_eq!(again.status(), StatusCode::BAD_REQUEST);
        assert_eq!(body_text(again).await, ALREADY_APPROVED);

        let owner = Agent::new(21);
        // Wrong verifier: refused, and the handoff survives.
        let wrong = redeem_as(&s, &owner, &code, &"b".repeat(43)).await;
        assert_eq!(wrong.status(), StatusCode::BAD_REQUEST);
        assert_eq!(body_json(wrong).await["error"], "invalid_handoff");
        let ok = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
        assert_eq!(ok.status(), StatusCode::OK);
        assert_eq!(ok.headers()[header::CACHE_CONTROL], "no-store");
        let body = body_json(ok).await;
        assert_eq!(body["platform"], "clockify");
        assert_eq!(body["owner"], owner.id());
        assert!(!body.to_string().contains("clockify-secret"));
        let connection_id = body["connection_id"].as_str().unwrap();
        let record = security
            .load_connection(connection_id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(record.owner, owner.id());
        let credential: crate::proxy::StoredCredential =
            serde_json::from_slice(&record.credential).unwrap();
        let crate::proxy::StoredCredential::ApiKey {
            key,
            scheme,
            placement,
            ..
        } = &credential
        else {
            panic!("{credential:?}");
        };
        assert_eq!(key, "clockify-secret");
        // Bound to the scheme it was entered for, and to where it goes.
        assert_eq!(scheme.as_deref(), Some("clockifyApiKey"));
        assert_eq!(
            *placement,
            Some(crate::providers::ApiKeyPlacement {
                location: "header".into(),
                name: "x-api-key".into(),
            })
        );
        // Single use.
        let reused = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
        assert_eq!(reused.status(), StatusCode::BAD_REQUEST);
    }

    /// An API-key document whose `x-api-key-details` declare a help link and
    /// a key check (openapi-extensions/spec/api-key-details).
    fn key_check_document(location: &str) -> serde_json::Value {
        serde_json::json!({
            "servers": [{"url": "https://api.service.example/api"}],
            "components": {"securitySchemes": {"serviceKey": {
                "type": "apiKey", "in": location, "name": "X-Api-Key",
                "description": "A personal key, made under Preferences, Advanced.",
                "x-api-key-details": {
                    "helpUrl": "https://service.example/help/api-keys",
                    "keyCheck": {"operationId": "getMe", "label": "$response.body#/email"}
                }
            }}},
            "security": [{"serviceKey": []}],
            "paths": {
                "/v1/user": {"get": {"operationId": "getMe"}},
                "/v1/workspaces": {"get": {}}
            }
        })
    }

    /// A stand-in provider for the key check: `/api/v1/user` answers by the
    /// key it gets, in the `X-Api-Key` header or the query.
    async fn key_check_upstream() -> (String, tokio::task::JoinHandle<()>) {
        key_check_upstream_counting(Default::default()).await
    }

    /// Wraps a stand-in provider so `counter` counts the requests it gets.
    fn counting(
        app: axum::Router,
        counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    ) -> axum::Router {
        app.layer(tower::util::MapRequestLayer::new(
            move |request: axum::http::Request<axum::body::Body>| {
                counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                request
            },
        ))
    }

    async fn key_check_upstream_counting(
        counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    ) -> (String, tokio::task::JoinHandle<()>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let app = axum::Router::new().route(
            "/api/v1/user",
            axum::routing::get(
                |headers: HeaderMap, OriginalUri(uri): OriginalUri| async move {
                    let key = headers
                        .get("x-api-key")
                        .and_then(|v| v.to_str().ok())
                        .map(str::to_owned)
                        .or_else(|| {
                            uri.query()
                                .and_then(|q| q.strip_prefix("X-Api-Key="))
                                .map(str::to_owned)
                        })
                        .unwrap_or_default();
                    match key.as_str() {
                        "good-key" => (
                            StatusCode::OK,
                            r#"{"id":"u1","email":"ada@example.test"}"#.to_owned(),
                        )
                            .into_response(),
                        "long-label-key" => (
                            StatusCode::OK,
                            serde_json::json!({"email": format!("\u{7}{}", "x".repeat(300))})
                                .to_string(),
                        )
                            .into_response(),
                        "no-label-key" => (StatusCode::OK, r#"{"email":7}"#).into_response(),
                        "forbidden-key" => StatusCode::FORBIDDEN.into_response(),
                        "moving-key" => (
                            StatusCode::FOUND,
                            [(header::LOCATION, "https://elsewhere.example/")],
                        )
                            .into_response(),
                        "broken-key" => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
                        _ => StatusCode::UNAUTHORIZED.into_response(),
                    }
                },
            ),
        );
        let app = counting(app, counter);
        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        (format!("http://{address}"), server)
    }

    #[tokio::test]
    async fn the_key_check_accepts_rejects_or_cannot_tell() {
        let (upstream, server) = key_check_upstream().await;
        let mut s = state(None);
        s.test_upstream = Some(upstream);
        let header_scheme =
            crate::providers::ApiKeyScheme::from_document(&key_check_document("header"), None)
                .unwrap();
        for (key, expected) in [
            (
                "good-key",
                KeyCheck::Accepted(Some("ada@example.test".into())),
            ),
            ("no-label-key", KeyCheck::Accepted(None)),
            ("wrong-key", KeyCheck::Rejected),
            ("forbidden-key", KeyCheck::Rejected),
            ("moving-key", KeyCheck::Undetermined),
            ("broken-key", KeyCheck::Undetermined),
        ] {
            assert_eq!(
                check_api_key(&s, &header_scheme, key).await,
                expected,
                "{key}"
            );
        }
        // A label loses control characters and stops at 200 characters.
        assert_eq!(
            check_api_key(&s, &header_scheme, "long-label-key").await,
            KeyCheck::Accepted(Some("x".repeat(MAX_KEY_LABEL)))
        );
        // Query-located keys go in the query, as the scheme says.
        let query_scheme =
            crate::providers::ApiKeyScheme::from_document(&key_check_document("query"), None)
                .unwrap();
        assert_eq!(
            check_api_key(&s, &query_scheme, "good-key").await,
            KeyCheck::Accepted(Some("ada@example.test".into()))
        );
        // A cookie-located key is not sent anywhere.
        let cookie_scheme =
            crate::providers::ApiKeyScheme::from_document(&key_check_document("cookie"), None)
                .unwrap();
        assert_eq!(
            check_api_key(&s, &cookie_scheme, "good-key").await,
            KeyCheck::Undetermined
        );
        // Without a key check every well-formed key is accepted, unlabelled,
        // and nothing is called.
        let mut plain = key_check_document("header");
        plain["components"]["securitySchemes"]["serviceKey"]
            .as_object_mut()
            .unwrap()
            .remove("x-api-key-details");
        let plain = crate::providers::ApiKeyScheme::from_document(&plain, None).unwrap();
        server.abort();
        let _ = server.await;
        assert_eq!(
            check_api_key(&s, &plain, "wrong-key").await,
            KeyCheck::Accepted(None)
        );
        // No answer at all: undetermined. A fresh client, so no pooled
        // connection to the stopped server is reused.
        let mut fresh = state(None);
        fresh.test_upstream = s.test_upstream.clone();
        assert_eq!(
            check_api_key(&fresh, &header_scheme, "good-key").await,
            KeyCheck::Undetermined
        );
    }

    #[tokio::test]
    async fn the_api_key_consent_page_shows_the_description_and_help_link() {
        let mut s = state(None);
        s.catalog = crate::catalog::Catalog::from_test_document(
            "clockify",
            key_check_document("header"),
            serde_json::json!({}),
        );
        let (status, html) = get_body(s, &connect_uri(&api_key_request())).await;
        assert_eq!(status, StatusCode::OK);
        assert!(html.contains("A personal key, made under Preferences, Advanced."));
        assert!(html.contains(
            r#"<a href="https://service.example/help/api-keys" target="_blank" rel="noopener noreferrer">Where to find your Clockify API key</a>"#
        ));
    }

    /// atomic-plugins#258: an API-key authentication profile of a document
    /// that also declares OAuth keeps its help link and key check; without a
    /// profile selection the mixed document is not offered at all.
    #[tokio::test]
    async fn an_api_key_profile_of_a_mixed_document_keeps_its_help_link_and_key_check() {
        let mut document = key_check_document("header");
        document["components"]["securitySchemes"]["userOAuth"] = serde_json::json!({
            "type": "oauth2", "flows": {"authorizationCode": {
                "authorizationUrl": "https://auth.service.example/authorize",
                "tokenUrl": "https://auth.service.example/token",
                "scopes": {"profile": "Profile"}
            }}
        });
        document["paths"]["/v1/me"] =
            serde_json::json!({"get": {"security": [{"userOAuth": ["profile"]}]}});
        document["components"]["x-authentication-profiles"] = serde_json::json!({
            "key": {"securityScheme": "serviceKey"},
            "user": {"securityScheme": "userOAuth"}
        });
        let page = |selection: serde_json::Value| {
            let mut s = state(None);
            s.catalog = crate::catalog::Catalog::from_test_document(
                "clockify",
                document.clone(),
                selection,
            );
            let uri = connect_uri(&api_key_request());
            async move { get_body(s, &uri).await }
        };

        let (status, html) = page(serde_json::json!({"authenticationProfile": "key"})).await;
        assert_eq!(status, StatusCode::OK);
        assert!(html.contains("A personal key, made under Preferences, Advanced."));
        assert!(html.contains(
            r#"<a href="https://service.example/help/api-keys" target="_blank" rel="noopener noreferrer">Where to find your Clockify API key</a>"#
        ));
        let catalog = crate::catalog::Catalog::from_test_document(
            "clockify",
            document.clone(),
            serde_json::json!({"authenticationProfile": "key"}),
        );
        let crate::providers::SecurityScheme::ApiKey(scheme) =
            catalog.security_scheme("clockify").unwrap()
        else {
            panic!("the key profile must resolve to an apiKey scheme");
        };
        let check = scheme.key_check.unwrap();
        assert_eq!(
            check.url.as_str(),
            "https://api.service.example/api/v1/user"
        );
        assert_eq!(check.label_pointer.as_deref(), Some("/email"));

        for selection in [
            serde_json::json!({}),
            serde_json::json!({"apiKeySecurityScheme": "serviceKey"}),
        ] {
            let (_, html) = page(selection).await;
            assert!(html.contains("This platform is not available for connection"));
        }
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_a_rejected_key_is_asked_again_and_an_accepted_one_keeps_its_label() {
        let (upstream, server) = key_check_upstream().await;
        let security = crate::test_support::security().await;
        let mut s = state(Some(security.clone()));
        s.test_upstream = Some(upstream);
        s.catalog = crate::catalog::Catalog::from_test_document(
            "clockify",
            key_check_document("header"),
            serde_json::json!({}),
        );
        let consent = Consent {
            request: api_key_request(),
            csrf: random(),
            expires: crate::now_secs() + 600,
        };
        let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
            CONSENT_COOKIE,
            serde_json::to_string(&consent).unwrap(),
        ));
        let approve = |key: &str| {
            authorize(
                State(s.clone()),
                None,
                jar.clone(),
                HeaderMap::new(),
                Form(Approval {
                    csrf: consent.csrf.clone(),
                    api_key: Some(key.into()),
                    username: None,
                }),
            )
        };
        // Rejected: the consent page again, with the reason, the same CSRF
        // token and its CSP, and the key nowhere in it.
        let rejected = approve("wrong-key").await;
        assert_eq!(rejected.status(), StatusCode::OK);
        assert!(rejected.headers()["content-security-policy"]
            .to_str()
            .unwrap()
            .contains("form-action 'self' https://hub.example"));
        let html = body_text(rejected).await;
        assert!(html.contains("Clockify did not accept that API key."));
        assert!(html.contains(&consent.csrf));
        assert!(!html.contains("wrong-key"));
        // Undetermined: an error, and still nothing spent.
        let broken = approve("broken-key").await;
        assert_eq!(broken.status(), StatusCode::BAD_REQUEST);
        let text = body_text(broken).await;
        assert!(text.starts_with("Could not check the API key"));
        assert!(!text.contains("broken-key"));
        // Accepted: the same consent still works.
        let accepted = approve("good-key").await;
        assert_eq!(accepted.status(), StatusCode::SEE_OTHER);
        server.abort();
        let location = Url::parse(accepted.headers()[header::LOCATION].to_str().unwrap()).unwrap();
        let code = location
            .query_pairs()
            .find(|(k, _)| k == "connection_code")
            .unwrap()
            .1
            .into_owned();
        let owner = Agent::new(22);
        let ok = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
        assert_eq!(ok.status(), StatusCode::OK);
        let body = body_json(ok).await;
        assert_eq!(body["label"], "ada@example.test");
        assert!(!body.to_string().contains("good-key"));
        let listed = crate::router(s.clone())
            .oneshot(signed_request(
                &s,
                &owner,
                "GET",
                "/connections",
                Vec::new(),
            ))
            .await
            .unwrap();
        assert_eq!(listed.status(), StatusCode::OK);
        let listed = body_json(listed).await;
        // Scoped to this test's own connection: the database may also hold
        // rows an earlier run left for the same agent seed.
        let mine = listed["connections"]
            .as_array()
            .unwrap()
            .iter()
            .find(|c| c["connection_id"] == body["connection_id"])
            .expect("the new connection is listed");
        assert_eq!(mine["label"], "ada@example.test");
    }

    /// A document whose one scheme is the `http` scheme `scheme`, with a
    /// help link and a key check (openapi-extensions/spec/api-key-details).
    fn http_document(scheme: serde_json::Value) -> serde_json::Value {
        let mut scheme = scheme;
        scheme["description"] = "A personal access token, made under Settings, Tokens.".into();
        scheme["x-api-key-details"]["helpUrl"] = "https://service.example/help/tokens".into();
        scheme["x-api-key-details"]["keyCheck"] =
            serde_json::json!({"operationId": "getMe", "label": "$response.body#/email"});
        serde_json::json!({
            "servers": [{"url": "https://api.service.example/api"}],
            "components": {"securitySchemes": {"serviceToken": scheme}},
            "security": [{"serviceToken": []}],
            "paths": {
                "/v1/user": {"get": {"operationId": "getMe"}},
                "/v1/workspaces": {"get": {}}
            }
        })
    }

    fn bearer() -> serde_json::Value {
        serde_json::json!({"type": "http", "scheme": "bearer"})
    }

    fn basic(layout: serde_json::Value) -> serde_json::Value {
        serde_json::json!({"type": "http", "scheme": "basic",
            "x-api-key-details": {"basicCredentials": layout}})
    }

    fn basic_header(username: &str, password: &str) -> String {
        format!(
            "Basic {}",
            base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"))
        )
    }

    fn http_scheme(document: serde_json::Value) -> crate::providers::HttpScheme {
        match crate::providers::SecurityScheme::from_document(&document, None, None, None) {
            Ok(crate::providers::SecurityScheme::Http(scheme)) => scheme,
            other => panic!("expected an http scheme, got {other:?}"),
        }
    }

    fn token_approval(token: &str, username: Option<&str>) -> Approval {
        Approval {
            csrf: String::new(),
            api_key: Some(token.into()),
            username: username.map(str::to_owned),
        }
    }

    /// A stand-in provider for an `http` scheme's key check: `/api/v1/user`
    /// answers by the `Authorization` header it gets.
    async fn http_key_check_upstream() -> (String, tokio::task::JoinHandle<()>) {
        http_key_check_upstream_counting(Default::default()).await
    }

    async fn http_key_check_upstream_counting(
        counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    ) -> (String, tokio::task::JoinHandle<()>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let accepted = [
            "Bearer good-token".to_owned(),
            basic_header("good-token", "api_token"),
            basic_header("ada@example.test", "good-token"),
            basic_header("api", "good-token"),
        ];
        let app = axum::Router::new().route(
            "/api/v1/user",
            axum::routing::get(move |headers: HeaderMap| {
                let accepted = accepted.clone();
                async move {
                    let authorization = headers
                        .get(header::AUTHORIZATION)
                        .and_then(|v| v.to_str().ok())
                        .unwrap_or_default();
                    if accepted.iter().any(|a| a == authorization) {
                        (StatusCode::OK, r#"{"id":"u1","email":"ada@example.test"}"#)
                            .into_response()
                    } else if authorization == "Bearer forbidden-token" {
                        StatusCode::FORBIDDEN.into_response()
                    } else if authorization == "Bearer broken-token" {
                        StatusCode::INTERNAL_SERVER_ERROR.into_response()
                    } else {
                        StatusCode::UNAUTHORIZED.into_response()
                    }
                }
            }),
        );
        let app = counting(app, counter);
        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        (format!("http://{address}"), server)
    }

    #[test]
    fn http_tokens_are_laid_out_as_declared_and_validated() {
        use crate::proxy::StoredCredential;
        let bearer_scheme = http_scheme(http_document(bearer()));
        let bearer_token = |token: &str, username: Option<&str>| match http_credential(
            "service",
            &bearer_scheme,
            &token_approval(token, username),
        ) {
            Ok(StoredCredential::HttpBearer {
                provider, token, ..
            }) => {
                assert_eq!(provider, "service");
                Ok(token)
            }
            Ok(other) => panic!("{other:?}"),
            Err(message) => Err(message),
        };
        assert_eq!(bearer_token(" good-token ", None), Ok("good-token".into()));
        // A typed username is ignored for a bearer token.
        assert_eq!(
            bearer_token("good-token", Some("someone")),
            Ok("good-token".into())
        );
        // Asana-style tokens with '/' and ':' are visible ASCII.
        assert_eq!(bearer_token("2/12/34:ab", None), Ok("2/12/34:ab".into()));
        for bad in ["abc", "has space", "tok\u{e9}n-1", "line\nbreak", ""] {
            assert_eq!(
                bearer_token(bad, None),
                Err("Enter a valid API token"),
                "{bad:?}"
            );
        }
        assert_eq!(
            bearer_token(&"x".repeat(513), None),
            Err("Enter a valid API token")
        );

        let halves = |layout: serde_json::Value, token: &str, username: Option<&str>| {
            let scheme = http_scheme(http_document(basic(layout)));
            match http_credential("service", &scheme, &token_approval(token, username)) {
                Ok(StoredCredential::HttpBasic {
                    username, password, ..
                }) => Ok((username, password)),
                Ok(other) => panic!("{other:?}"),
                Err(message) => Err(message),
            }
        };
        let as_username = serde_json::json!({"token": "username", "password": "api_token"});
        assert_eq!(
            halves(as_username.clone(), "good-token", Some("ignored")),
            Ok(("good-token".into(), "api_token".into()))
        );
        // RFC 7617: a user-id cannot contain ':'.
        assert_eq!(
            halves(as_username, "good:token", None),
            Err("Enter a valid API token")
        );
        assert_eq!(
            halves(
                serde_json::json!({"token": "password", "username": "api"}),
                "pass:with:colons",
                Some("ignored")
            ),
            Ok(("api".into(), "pass:with:colons".into()))
        );
        let asking = serde_json::json!({"token": "password", "usernameLabel": "Email"});
        assert_eq!(
            halves(asking.clone(), "good-token", Some(" ada@example.test ")),
            Ok(("ada@example.test".into(), "good-token".into()))
        );
        for username in [None, Some(""), Some("  "), Some("a:b"), Some("a\u{7}b")] {
            assert_eq!(
                halves(asking.clone(), "good-token", username),
                Err("Enter a valid username and API token"),
                "{username:?}"
            );
        }
        assert_eq!(
            halves(asking.clone(), "good-token", Some(&"u".repeat(257))),
            Err("Enter a valid username and API token")
        );
        assert_eq!(
            halves(asking, "tok\u{0}en", Some("ada@example.test")),
            Err("Enter a valid API token")
        );
    }

    #[tokio::test]
    async fn the_http_key_check_sends_the_authorization_a_request_would_carry() {
        let (upstream, server) = http_key_check_upstream().await;
        let mut s = state(None);
        s.test_upstream = Some(upstream);
        let check = |layout: Option<serde_json::Value>, token: &str, username: Option<&str>| {
            let scheme = http_scheme(http_document(layout.map_or_else(bearer, basic)));
            let credential =
                http_credential("service", &scheme, &token_approval(token, username)).unwrap();
            let s = s.clone();
            async move { check_http_credential(&s, &scheme, &credential).await }
        };
        let accepted = KeyCheck::Accepted(Some("ada@example.test".into()));
        assert_eq!(check(None, "good-token", None).await, accepted);
        assert_eq!(check(None, "wrong-token", None).await, KeyCheck::Rejected);
        assert_eq!(
            check(None, "forbidden-token", None).await,
            KeyCheck::Rejected
        );
        assert_eq!(
            check(None, "broken-token", None).await,
            KeyCheck::Undetermined
        );
        for (layout, username) in [
            (
                serde_json::json!({"token": "username", "password": "api_token"}),
                None,
            ),
            (
                serde_json::json!({"token": "password", "usernameLabel": "Email"}),
                Some("ada@example.test"),
            ),
            (
                serde_json::json!({"token": "password", "username": "api"}),
                None,
            ),
        ] {
            assert_eq!(
                check(Some(layout.clone()), "good-token", username).await,
                accepted,
                "{layout}"
            );
            assert_eq!(
                check(Some(layout.clone()), "wrong-token", username).await,
                KeyCheck::Rejected,
                "{layout}"
            );
        }
        server.abort();
    }

    #[tokio::test]
    async fn the_http_consent_page_asks_for_a_token_and_a_declared_username() {
        let page = |document: serde_json::Value| {
            let mut s = state(None);
            s.catalog = crate::catalog::Catalog::from_test_document(
                "clockify",
                document,
                serde_json::json!({}),
            );
            let uri = connect_uri(&api_key_request());
            let router = crate::router(s);
            async move {
                router
                    .oneshot(
                        axum::http::Request::builder()
                            .uri(uri)
                            .body(axum::body::Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap()
            }
        };
        let response = page(http_document(bearer())).await;
        assert_eq!(response.status(), StatusCode::OK);
        // Approval redirects to the destination, as for an API key.
        assert!(response.headers()["content-security-policy"]
            .to_str()
            .unwrap()
            .ends_with("form-action 'self' https://hub.example"));
        let html = body_text(response).await;
        assert!(html.contains("A personal access token, made under Settings, Tokens."));
        assert!(html.contains(
            r#"<a href="https://service.example/help/tokens" target="_blank" rel="noopener noreferrer">Where to find your Clockify API token</a>"#
        ));
        assert!(html.contains(
            r#"type="password" name="api_key" autocomplete="off" placeholder="API token""#
        ));
        assert!(!html.contains(r#"name="username""#));

        let html = body_text(
            page(http_document(basic(
                serde_json::json!({"token": "password", "usernameLabel": "Email <work>"}),
            )))
            .await,
        )
        .await;
        assert!(html.contains(
            r#"type="text" name="username" autocomplete="off" placeholder="Email &lt;work&gt;" aria-label="Email &lt;work&gt;" required"#
        ));
        assert!(html.contains(r#"name="api_key""#));
        // A fixed username is not asked for.
        let html = body_text(
            page(http_document(basic(
                serde_json::json!({"token": "username", "password": "api_token"}),
            )))
            .await,
        )
        .await;
        assert!(!html.contains(r#"name="username""#));
        assert!(!html.contains("api_token"));
        // A basic scheme without a declared token layout is not offered.
        let mut undeclared = http_document(basic(serde_json::json!({})));
        undeclared["components"]["securitySchemes"]["serviceToken"]["x-api-key-details"]
            .as_object_mut()
            .unwrap()
            .remove("basicCredentials");
        let html = body_text(page(undeclared).await).await;
        assert!(html.contains("This platform is not available for connection"));
    }

    /// Q-086, end to end for both kinds: a rejected token asks again
    /// without spending the consent, an undetermined check stores nothing,
    /// and an accepted token is sealed as checked, redeemed by the signer,
    /// and never returned.
    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_http_tokens_are_checked_then_sealed_and_never_returned() {
        let (upstream, server) = http_key_check_upstream().await;
        let security = crate::test_support::security().await;
        for (seed, scheme, username) in [
            (70u8, bearer(), None),
            (
                71,
                basic(serde_json::json!({"token": "password", "usernameLabel": "Email"})),
                Some("ada@example.test"),
            ),
        ] {
            let mut s = state(Some(security.clone()));
            s.test_upstream = Some(upstream.clone());
            s.catalog = crate::catalog::Catalog::from_test_document(
                "clockify",
                http_document(scheme),
                serde_json::json!({}),
            );
            let consent = Consent {
                request: api_key_request(),
                csrf: random(),
                expires: crate::now_secs() + 600,
            };
            let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
                CONSENT_COOKIE,
                serde_json::to_string(&consent).unwrap(),
            ));
            let approve = |token: &str, username: Option<&str>| {
                authorize(
                    State(s.clone()),
                    None,
                    jar.clone(),
                    HeaderMap::new(),
                    Form(Approval {
                        csrf: consent.csrf.clone(),
                        ..token_approval(token, username)
                    }),
                )
            };
            // Malformed: refused before any check, nothing spent.
            let blank = approve("  ", username).await;
            assert_eq!(blank.status(), StatusCode::BAD_REQUEST);
            assert!(body_text(blank).await.starts_with("Enter a valid"));
            // Rejected: the page again, with the reason and not the token.
            let rejected = approve("wrong-token", username).await;
            assert_eq!(rejected.status(), StatusCode::OK);
            let html = body_text(rejected).await;
            assert!(html.contains("Clockify did not accept that API token."));
            assert!(html.contains(&consent.csrf));
            assert!(!html.contains("wrong-token"));
            // Undetermined (only reachable for the bearer token here).
            if username.is_none() {
                let broken = approve("broken-token", None).await;
                assert_eq!(broken.status(), StatusCode::BAD_REQUEST);
                let text = body_text(broken).await;
                assert!(text.starts_with("Could not check the API token"));
                assert!(!text.contains("broken-token"));
            }
            // Accepted: the same consent still works.
            let accepted = approve("good-token", username).await;
            assert_eq!(accepted.status(), StatusCode::SEE_OTHER);
            let location =
                Url::parse(accepted.headers()[header::LOCATION].to_str().unwrap()).unwrap();
            assert!(!location.as_str().contains("good-token"));
            let code = location
                .query_pairs()
                .find(|(k, _)| k == "connection_code")
                .unwrap()
                .1
                .into_owned();
            let owner = Agent::new(seed);
            let ok = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
            assert_eq!(ok.status(), StatusCode::OK);
            let body = body_json(ok).await;
            assert_eq!(body["owner"], owner.id());
            assert_eq!(body["label"], "ada@example.test");
            assert!(!body.to_string().contains("good-token"));
            let record = security
                .load_connection(body["connection_id"].as_str().unwrap())
                .await
                .unwrap()
                .unwrap();
            let credential: crate::proxy::StoredCredential =
                serde_json::from_slice(&record.credential).unwrap();
            match (username, credential) {
                (None, crate::proxy::StoredCredential::HttpBearer { token, scheme, .. }) => {
                    assert_eq!(token, "good-token");
                    // Bound to the scheme it was entered for.
                    assert_eq!(scheme.as_deref(), Some("serviceToken"));
                }
                (
                    Some(expected),
                    crate::proxy::StoredCredential::HttpBasic {
                        username,
                        password,
                        scheme,
                        layout,
                        ..
                    },
                ) => {
                    assert_eq!(
                        (username.as_str(), password.as_str()),
                        (expected, "good-token")
                    );
                    assert_eq!(scheme.as_deref(), Some("serviceToken"));
                    assert_eq!(
                        layout,
                        Some(crate::providers::BasicLayout::Password { username: None })
                    );
                }
                (_, other) => panic!("{other:?}"),
            }
        }
        server.abort();
    }

    #[test]
    fn a_bearer_token_is_a_b64token_or_an_asana_style_token() {
        for good in [
            "good-token",
            "ghp_AbC123",
            "a.b_c~d+e/f",
            "dG9rZW4=",
            "dG9r==",
            "2/1234/5678:abcdef",
        ] {
            assert!(bearer_token(good), "{good}");
        }
        for bad in [
            "",
            "==",
            "a=b",
            "has space",
            "quote\"d",
            "semi;colon",
            "comma,",
            "tok\u{e9}n",
            "back\\slash",
            "a\tb",
            "<tag>",
            "50%",
        ] {
            assert!(!bearer_token(bad), "{bad:?}");
        }
    }

    /// One consent makes at most [`MAX_KEY_CHECKS`] key checks: the last
    /// rejection spends it and says so, and nothing is checked after that,
    /// for an API key and for an `http` token alike.
    ///
    /// The cap is per consent page, not per client: anyone can open another
    /// consent page (SECURITY.md).
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_a_consent_allows_at_most_five_key_checks() {
        use std::sync::atomic::Ordering::SeqCst;
        let security = crate::test_support::security().await;
        for http in [false, true] {
            let checks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
            let (upstream, server) = if http {
                http_key_check_upstream_counting(checks.clone()).await
            } else {
                key_check_upstream_counting(checks.clone()).await
            };
            let (document, wrong, good, asked_again) = if http {
                (
                    http_document(bearer()),
                    "wrong-token",
                    "good-token",
                    "did not accept that API token",
                )
            } else {
                (
                    key_check_document("header"),
                    "wrong-key",
                    "good-key",
                    "did not accept that API key",
                )
            };
            let mut s = state(Some(security.clone()));
            s.test_upstream = Some(upstream);
            s.catalog = crate::catalog::Catalog::from_test_document(
                "clockify",
                document,
                serde_json::json!({}),
            );
            let new_consent = || {
                let consent = Consent {
                    request: api_key_request(),
                    csrf: random(),
                    expires: crate::now_secs() + 600,
                };
                let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
                    CONSENT_COOKIE,
                    serde_json::to_string(&consent).unwrap(),
                ));
                (consent, jar)
            };
            let submit = |s: &AppState, jar: &PrivateCookieJar, csrf: &str, key: &str| {
                authorize(
                    State(s.clone()),
                    None,
                    jar.clone(),
                    HeaderMap::new(),
                    Form(Approval {
                        csrf: csrf.to_owned(),
                        ..token_approval(key, None)
                    }),
                )
            };
            let (consent, jar) = new_consent();
            let approve = |key: &str| submit(&s, &jar, &consent.csrf, key);
            // A malformed key is refused before any check and costs nothing.
            assert_eq!(approve("  ").await.status(), StatusCode::BAD_REQUEST);
            for attempt in 1..MAX_KEY_CHECKS {
                let response = approve(wrong).await;
                assert_eq!(response.status(), StatusCode::OK, "{http} {attempt}");
                assert!(body_text(response).await.contains(asked_again));
            }
            // The last allowed check is rejected too: the consent is spent.
            let last = approve(wrong).await;
            assert_eq!(last.status(), StatusCode::BAD_REQUEST);
            assert_eq!(body_text(last).await, TOO_MANY_KEY_CHECKS);
            assert!(security
                .nonce_used(&format!("consent:{}", consent.csrf))
                .await
                .unwrap());
            // Even a good key is not checked or accepted now.
            let after = approve(good).await;
            assert_eq!(after.status(), StatusCode::BAD_REQUEST);
            assert_eq!(body_text(after).await, TOO_MANY_KEY_CHECKS);
            // The provider was asked exactly five times.
            assert_eq!(checks.load(SeqCst), MAX_KEY_CHECKS as usize, "{http}");

            // Thirty concurrent submissions of one fresh consent: still
            // exactly five checks, and none is accepted.
            checks.store(0, SeqCst);
            let (consent, jar) = new_consent();
            let tasks: Vec<_> = (0..30)
                .map(|_| {
                    let request = submit(&s, &jar, &consent.csrf, wrong);
                    tokio::spawn(async move { request.await.status() })
                })
                .collect();
            for task in tasks {
                let status = task.await.unwrap();
                assert!(
                    matches!(status, StatusCode::OK | StatusCode::BAD_REQUEST),
                    "{status}"
                );
            }
            assert_eq!(checks.load(SeqCst), MAX_KEY_CHECKS as usize, "{http}");
            server.abort();
        }
    }

    /// A client network this test run has not used, so rows left by earlier
    /// runs (kept for an hour) do not count.
    fn fresh_ip() -> std::net::IpAddr {
        std::net::IpAddr::V4(std::net::Ipv4Addr::from(rand::random::<u32>()))
    }

    fn peer_at(ip: std::net::IpAddr) -> Option<ConnectInfo<std::net::SocketAddr>> {
        Some(ConnectInfo(std::net::SocketAddr::new(ip, 40_000)))
    }

    fn forwarded_for(value: &str) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert("x-forwarded-for", value.parse().unwrap());
        headers
    }

    /// A state whose only platform, `platform`, takes an API key checked by
    /// `upstream`, with the key-check limit set to `limit`.
    fn limited_state(
        security: &Security,
        upstream: &str,
        platform: &str,
        document: serde_json::Value,
        limit: u32,
    ) -> AppState {
        let mut s = state(Some(security.clone()));
        s.test_upstream = Some(upstream.to_owned());
        s.catalog =
            crate::catalog::Catalog::from_test_document(platform, document, serde_json::json!({}));
        s.key_check_limit = limit;
        s
    }

    /// Submits `key` on a consent page of its own, as a script that opens a
    /// new consent page for every attempt would. Returns the response and
    /// the consent's CSRF token.
    async fn submit_on_new_consent(
        s: &AppState,
        peer: Option<ConnectInfo<std::net::SocketAddr>>,
        headers: HeaderMap,
        key: &str,
    ) -> (Response, String) {
        let platform = s.catalog.names()[0].clone();
        let consent = Consent {
            request: Request {
                redirect_uri: format!(
                    "https://hub.example/app/integrations?integration_state=state&platform={platform}"
                ),
                platform,
                ..api_key_request()
            },
            csrf: random(),
            expires: crate::now_secs() + 600,
        };
        let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
            CONSENT_COOKIE,
            serde_json::to_string(&consent).unwrap(),
        ));
        let response = authorize(
            State(s.clone()),
            peer,
            jar,
            headers,
            Form(Approval {
                csrf: consent.csrf.clone(),
                ..token_approval(key, None)
            }),
        )
        .await;
        (response, consent.csrf)
    }

    /// Q-097: key checks are limited per client network and platform, across
    /// consent pages, before any upstream call, without spending the
    /// consent; other networks and platforms are unaffected; checks free up
    /// when their window has passed; `X-Forwarded-For` is read only as
    /// `TRUST_FORWARDED_FOR` says; `0` turns the limit off; and a concurrent
    /// burst makes no more checks than the limit.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_key_checks_are_limited_per_network_and_platform() {
        use std::sync::atomic::Ordering::SeqCst;
        let security = crate::test_support::security().await;
        let checks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let (upstream, server) = key_check_upstream_counting(checks.clone()).await;
        let document = key_check_document("header");
        let s = limited_state(&security, &upstream, "clockify", document.clone(), 3);
        let other_platform =
            limited_state(&security, &upstream, "clockify-other", document.clone(), 3);
        let ip = fresh_ip();
        let asked_again = "did not accept that API key";

        // Malformed keys are refused before the limit and cost nothing.
        for _ in 0..5 {
            let (response, _) = submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), " ").await;
            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        }
        assert_eq!(checks.load(SeqCst), 0);
        // Three checks from one network, each on a new consent page.
        for attempt in 1..=3 {
            let (response, _) =
                submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "wrong-key").await;
            assert_eq!(response.status(), StatusCode::OK, "{attempt}");
            assert!(body_text(response).await.contains(asked_again));
        }
        assert_eq!(checks.load(SeqCst), 3);
        // The fourth, even with a good key: 429, no upstream call, and the
        // consent is neither spent nor charged a key check.
        let (limited, csrf) =
            submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "good-key").await;
        assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
        let retry_after: u64 = limited.headers()[header::RETRY_AFTER]
            .to_str()
            .unwrap()
            .parse()
            .unwrap();
        assert!((1..=3600).contains(&retry_after), "{retry_after}");
        assert_eq!(limited.headers()[header::CACHE_CONTROL], "no-store");
        assert!(set_cookie(&limited, CONSENT_COOKIE).is_none());
        assert_eq!(
            body_text(limited).await,
            "Too many key checks from your network for Clockify; try again later"
        );
        assert_eq!(checks.load(SeqCst), 3);
        assert!(!security
            .nonce_used(&format!("consent:{csrf}"))
            .await
            .unwrap());
        assert!(!security
            .nonce_used(&key_check_slot(&csrf, 1))
            .await
            .unwrap());
        // Malformed input is still refused as such, and costs nothing.
        let (malformed, _) = submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), " ").await;
        assert_eq!(malformed.status(), StatusCode::BAD_REQUEST);

        // Another platform from the same network, and the same platform from
        // another network, are unaffected.
        let (response, _) =
            submit_on_new_consent(&other_platform, peer_at(ip), HeaderMap::new(), "wrong-key")
                .await;
        assert_eq!(response.status(), StatusCode::OK);
        let (response, _) =
            submit_on_new_consent(&s, peer_at(fresh_ip()), HeaderMap::new(), "good-key").await;
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        assert_eq!(checks.load(SeqCst), 5);

        // X-Forwarded-For does not get around it. Without trust, it is
        // ignored: the peer is the limited network.
        let spoofed = forwarded_for(&fresh_ip().to_string());
        let (response, _) = submit_on_new_consent(&s, peer_at(ip), spoofed, "good-key").await;
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        // Behind Heroku's router, only the entry the router appended counts:
        // a client-supplied entry to its left changes nothing, and neither
        // does which router address the request came from.
        let mut heroku = s.clone();
        heroku.trust_forwarded_for = crate::config::TrustForwardedFor::RightMost;
        let router = peer_at(fresh_ip());
        let spoofed = forwarded_for(&format!("{}, {ip}", fresh_ip()));
        let (response, _) = submit_on_new_consent(&heroku, router, spoofed, "good-key").await;
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        // Nor does a non-UTF-8 byte the client put before the router's
        // entry: that does not move it to the router's (peer's) bucket.
        let mut binary = HeaderMap::new();
        let mut line = b"\x80, ".to_vec();
        line.extend_from_slice(ip.to_string().as_bytes());
        binary.insert(
            "x-forwarded-for",
            axum::http::HeaderValue::from_bytes(&line).unwrap(),
        );
        let (response, _) =
            submit_on_new_consent(&heroku, peer_at(fresh_ip()), binary, "good-key").await;
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        // A client that sends its own X-Forwarded-For to a proxy that does
        // not trust it is counted by its own address.
        let (response, _) = submit_on_new_consent(
            &s,
            peer_at(ip),
            forwarded_for(&format!("{ip}, {}", fresh_ip())),
            "good-key",
        )
        .await;
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(checks.load(SeqCst), 5);

        // A platform that declares no key check makes no upstream call, so
        // connecting it from the limited network uses no allowance and is
        // not refused.
        let mut unchecked_document = document.clone();
        unchecked_document["components"]["securitySchemes"]["serviceKey"]
            .as_object_mut()
            .unwrap()
            .remove("x-api-key-details");
        let unchecked = limited_state(
            &security,
            &upstream,
            &format!("p-{:x}", rand::random::<u64>()),
            unchecked_document,
            1,
        );
        for _ in 0..3 {
            let (response, _) =
                submit_on_new_consent(&unchecked, peer_at(ip), HeaderMap::new(), "any-key").await;
            assert_eq!(response.status(), StatusCode::SEE_OTHER);
        }
        let bucket = security.key_check_bucket(
            &unchecked.catalog.names()[0],
            &crate::client_addr::network(ip),
        );
        assert_eq!(
            security
                .take_key_check_allowance(&bucket, 1, std::time::Duration::from_secs(3600))
                .await
                .unwrap(),
            None,
            "no slot was taken"
        );
        assert_eq!(checks.load(SeqCst), 5);

        // 0 turns the limit off.
        let mut unlimited = s.clone();
        unlimited.key_check_limit = 0;
        for _ in 0..2 {
            let (response, _) =
                submit_on_new_consent(&unlimited, peer_at(ip), HeaderMap::new(), "wrong-key").await;
            assert_eq!(response.status(), StatusCode::OK);
        }
        assert_eq!(checks.load(SeqCst), 7);

        // Without any client address, every such check shares one limit.
        let mut nowhere = limited_state(
            &security,
            &upstream,
            &format!("p-{:x}", rand::random::<u64>()),
            document.clone(),
            1,
        );
        nowhere.trust_forwarded_for = crate::config::TrustForwardedFor::RightMost;
        let (response, _) =
            submit_on_new_consent(&nowhere, None, HeaderMap::new(), "wrong-key").await;
        assert_eq!(response.status(), StatusCode::OK);
        let (response, _) =
            submit_on_new_consent(&nowhere, None, HeaderMap::new(), "wrong-key").await;
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(checks.load(SeqCst), 8);

        // A check frees up once its window has passed.
        let mut short = s.clone();
        short.key_check_limit = 1;
        short.key_check_window = std::time::Duration::from_secs(2);
        let network = fresh_ip();
        let (response, _) =
            submit_on_new_consent(&short, peer_at(network), HeaderMap::new(), "wrong-key").await;
        assert_eq!(response.status(), StatusCode::OK);
        let (response, _) =
            submit_on_new_consent(&short, peer_at(network), HeaderMap::new(), "wrong-key").await;
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        assert!(
            response.headers()[header::RETRY_AFTER]
                .to_str()
                .unwrap()
                .parse::<u64>()
                .unwrap()
                <= 2
        );
        tokio::time::sleep(std::time::Duration::from_millis(2_200)).await;
        let (response, _) =
            submit_on_new_consent(&short, peer_at(network), HeaderMap::new(), "wrong-key").await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(checks.load(SeqCst), 10);

        // Thirty concurrent submissions from one network, each on its own
        // consent page, with a limit of five: exactly five checks.
        checks.store(0, SeqCst);
        let mut burst = s.clone();
        burst.key_check_limit = 5;
        let network = fresh_ip();
        let tasks: Vec<_> = (0..30)
            .map(|_| {
                let burst = burst.clone();
                tokio::spawn(async move {
                    submit_on_new_consent(&burst, peer_at(network), HeaderMap::new(), "wrong-key")
                        .await
                        .0
                        .status()
                })
            })
            .collect();
        let mut statuses = Vec::new();
        for task in tasks {
            statuses.push(task.await.unwrap());
        }
        assert_eq!(statuses.iter().filter(|s| **s == StatusCode::OK).count(), 5);
        assert_eq!(
            statuses
                .iter()
                .filter(|s| **s == StatusCode::TOO_MANY_REQUESTS)
                .count(),
            25
        );
        assert_eq!(checks.load(SeqCst), 5);
        server.abort();
    }

    /// The limit covers `http` bearer and basic tokens as it covers API keys.
    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_http_token_checks_share_the_network_limit() {
        use std::sync::atomic::Ordering::SeqCst;
        let security = crate::test_support::security().await;
        let checks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let (upstream, server) = http_key_check_upstream_counting(checks.clone()).await;
        let s = limited_state(&security, &upstream, "clockify", http_document(bearer()), 2);
        let ip = fresh_ip();
        for _ in 0..2 {
            let (response, _) =
                submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "wrong-token").await;
            assert_eq!(response.status(), StatusCode::OK);
        }
        let (response, _) =
            submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "good-token").await;
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(checks.load(SeqCst), 2);
        server.abort();
    }

    /// A limited key check logs that it was limited, with the hashed bucket,
    /// and neither the client address nor the key. Run in a child process,
    /// like [`postgres_no_http_token_reaches_the_logs`].
    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_a_limited_key_check_logs_no_address() {
        const CHILD: &str = "INTEGRATION_PROXY_LOG_CAPTURE_CHILD";
        if std::env::var_os(CHILD).is_none() {
            let output = std::process::Command::new(std::env::current_exe().unwrap())
                .args([
                    "--exact",
                    "connect::tests::postgres_a_limited_key_check_logs_no_address",
                    "--include-ignored",
                    "--test-threads=1",
                ])
                .env(CHILD, "1")
                .output()
                .unwrap();
            let stdout = String::from_utf8_lossy(&output.stdout);
            assert!(
                output.status.success() && stdout.contains("1 passed"),
                "{stdout}\n{}",
                String::from_utf8_lossy(&output.stderr)
            );
            return;
        }
        let logs = LogBuffer::default();
        let writer = logs.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(tracing::Level::TRACE)
            .with_ansi(false)
            .with_writer(move || writer.clone())
            .finish();
        let _guard = tracing::subscriber::set_default(subscriber);

        let security = crate::test_support::security().await;
        let (upstream, server) = key_check_upstream().await;
        let s = limited_state(
            &security,
            &upstream,
            "clockify",
            key_check_document("header"),
            1,
        );
        let ip = fresh_ip();
        let (response, _) =
            submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "wrong-key").await;
        assert_eq!(response.status(), StatusCode::OK);
        let (response, _) =
            submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "good-key").await;
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        server.abort();

        let logs = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
        let bucket = security.key_check_bucket("clockify", &ip.to_string());
        assert_eq!(bucket.len(), 64);
        assert!(logs.contains("key check limit reached"), "{logs}");
        assert!(logs.contains(&bucket), "{logs}");
        for secret in [ip.to_string(), "wrong-key".into(), "good-key".into()] {
            assert!(!logs.contains(&secret), "{secret} in logs:\n{logs}");
        }
    }

    /// Collects everything a `tracing` subscriber writes.
    #[derive(Clone, Default)]
    struct LogBuffer(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

    impl std::io::Write for LogBuffer {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(bytes);
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// Q-086: with every `tracing` event recorded at TRACE level, a Basic
    /// connection's consent, key check, redeem and proxied request (through
    /// the router and its `TraceLayer`) log neither half of the credential
    /// nor its base64 form. `log`-crate records of dependencies are not
    /// captured here.
    ///
    /// `tracing` caches per-callsite interest process-wide, so a thread-local
    /// subscriber misses events while other tests run in parallel. The test
    /// therefore runs itself alone in a child process of the same test
    /// binary.
    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_no_http_token_reaches_the_logs() {
        const CHILD: &str = "INTEGRATION_PROXY_LOG_CAPTURE_CHILD";
        if std::env::var_os(CHILD).is_none() {
            let output = std::process::Command::new(std::env::current_exe().unwrap())
                .args([
                    "--exact",
                    "connect::tests::postgres_no_http_token_reaches_the_logs",
                    "--include-ignored",
                    "--test-threads=1",
                ])
                .env(CHILD, "1")
                .output()
                .unwrap();
            let stdout = String::from_utf8_lossy(&output.stdout);
            assert!(
                output.status.success() && stdout.contains("1 passed"),
                "{stdout}\n{}",
                String::from_utf8_lossy(&output.stderr)
            );
            return;
        }
        let logs = LogBuffer::default();
        let writer = logs.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(tracing::Level::TRACE)
            .with_ansi(false)
            .with_writer(move || writer.clone())
            .finish();
        let _guard = tracing::subscriber::set_default(subscriber);
        tracing::info!("log capture started");

        let (upstream, key_server) = http_key_check_upstream().await;
        let security = crate::test_support::security().await;
        let layout = serde_json::json!({"token": "password", "usernameLabel": "Email"});
        let mut s = state(Some(security.clone()));
        s.test_upstream = Some(upstream);
        s.catalog = crate::catalog::Catalog::from_test_document(
            "clockify",
            http_document(basic(layout.clone())),
            serde_json::json!({}),
        );
        let consent = Consent {
            request: api_key_request(),
            csrf: random(),
            expires: crate::now_secs() + 600,
        };
        let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
            CONSENT_COOKIE,
            serde_json::to_string(&consent).unwrap(),
        ));
        let accepted = authorize(
            State(s.clone()),
            None,
            jar,
            HeaderMap::new(),
            Form(Approval {
                csrf: consent.csrf.clone(),
                ..token_approval("good-token", Some("ada@example.test"))
            }),
        )
        .await;
        assert_eq!(accepted.status(), StatusCode::SEE_OTHER);
        key_server.abort();
        let location = Url::parse(accepted.headers()[header::LOCATION].to_str().unwrap()).unwrap();
        let code = location
            .query_pairs()
            .find(|(k, _)| k == "connection_code")
            .unwrap()
            .1
            .into_owned();
        let owner = Agent::new(72);
        let redeemed = body_json(redeem_as(&s, &owner, &code, &"a".repeat(43)).await).await;
        let connection_id = redeemed["connection_id"].as_str().unwrap();

        // A proxied request to a provider that answers anything.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let app = axum::Router::new().route(
            "/api/v1/workspaces",
            axum::routing::get(|| async { axum::Json(serde_json::json!([])) }),
        );
        let provider = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let mut document = http_document(basic(layout));
        document["servers"] = serde_json::json!([{"url": format!("http://{address}/api")}]);
        // The key check needs an https server; the proxied request does not.
        document["components"]["securitySchemes"]["serviceToken"]
            .as_object_mut()
            .unwrap()
            .remove("x-api-key-details");
        document["components"]["securitySchemes"]["serviceToken"]["x-api-key-details"] = serde_json::json!({"basicCredentials": {"token": "password", "usernameLabel": "Email"}});
        s.catalog = crate::catalog::Catalog::from_test_document(
            "clockify",
            document,
            serde_json::json!({}),
        );
        let response = crate::router(s.clone())
            .oneshot(signed_request(
                &s,
                &owner,
                "GET",
                &format!("/proxy/{connection_id}/clockify/api/v1/workspaces"),
                Vec::new(),
            ))
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        provider.abort();

        let logs = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
        // The capture works, and the router's TraceLayer reached it.
        assert!(logs.contains("log capture started"), "{logs}");
        assert!(
            logs.contains("tower_http") && logs.contains("/proxy/"),
            "{logs}"
        );
        // ... and so did the HTTP client's, for the key check and upstream.
        assert!(logs.contains("hyper_util"), "{logs}");
        let encoded = basic_header("ada@example.test", "good-token");
        for secret in [
            "good-token",
            encoded.trim_start_matches("Basic "),
            "ada@example.test",
        ] {
            assert!(!logs.contains(secret), "{secret} in logs:\n{logs}");
        }
    }

    fn no_credential_catalog() -> crate::catalog::Catalog {
        crate::catalog::Catalog::from_test_document(
            "pets",
            serde_json::json!({
                "servers": [{"url": "https://pets.example/api"}],
                "security": [],
                "paths": {"/pets": {"get": {}}}
            }),
            serde_json::json!({}),
        )
    }

    fn no_credential_request() -> Request {
        Request {
            platform: "pets".into(),
            redirect_uri:
                "https://hub.example/app/integrations?integration_state=state&platform=pets".into(),
            code_challenge: pkce_challenge(&"a".repeat(43)).unwrap(),
            code_challenge_method: "S256".into(),
        }
    }

    #[tokio::test]
    async fn no_credential_consent_page_asks_for_nothing_and_redirects_nowhere_else() {
        let mut s = state(None);
        s.catalog = no_credential_catalog();
        let r = no_credential_request();
        let uri = format!(
            "/connect?platform=pets&redirect_uri={}&code_challenge={}&code_challenge_method=S256",
            url::form_urlencoded::byte_serialize(r.redirect_uri.as_bytes()).collect::<String>(),
            r.code_challenge
        );
        let response = crate::router(s)
            .oneshot(
                axum::http::Request::builder()
                    .uri(uri)
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let policy = response.headers()["content-security-policy"]
            .to_str()
            .unwrap()
            .to_owned();
        assert!(policy.ends_with("form-action 'self' https://hub.example"));
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let html = String::from_utf8(bytes.to_vec()).unwrap();
        assert!(html.contains("Pets needs no account"));
        assert!(!html.contains("api_key"));
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_no_credential_connect_seals_no_secret_and_the_signer_owns_it() {
        let security = crate::test_support::security().await;
        let mut s = state(Some(security.clone()));
        s.catalog = no_credential_catalog();
        let consent = Consent {
            request: no_credential_request(),
            csrf: random(),
            expires: crate::now_secs() + 600,
        };
        let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
            CONSENT_COOKIE,
            serde_json::to_string(&consent).unwrap(),
        ));
        // A key sent anyway is ignored, not stored.
        let response = authorize(
            State(s.clone()),
            None,
            jar,
            HeaderMap::new(),
            Form(Approval {
                csrf: consent.csrf.clone(),
                api_key: Some("unexpected-secret".into()),
                username: None,
            }),
        )
        .await;
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        let location = Url::parse(response.headers()[header::LOCATION].to_str().unwrap()).unwrap();
        assert_eq!(
            location.origin().ascii_serialization(),
            "https://hub.example"
        );
        let code = location
            .query_pairs()
            .find(|(k, _)| k == "connection_code")
            .unwrap()
            .1
            .into_owned();
        let owner = Agent::new(25);
        let ok = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
        assert_eq!(ok.status(), StatusCode::OK);
        let body = body_json(ok).await;
        assert_eq!(body["platform"], "pets");
        assert_eq!(body["owner"], owner.id());
        let record = security
            .load_connection(body["connection_id"].as_str().unwrap())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(record.owner, owner.id());
        let credential: crate::proxy::StoredCredential =
            serde_json::from_slice(&record.credential).unwrap();
        assert!(matches!(
            credential,
            crate::proxy::StoredCredential::NoCredential { ref provider } if provider == "pets"
        ));
        assert!(!String::from_utf8_lossy(&record.credential).contains("unexpected-secret"));
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_redeem_canonicalizes_a_legacy_signer_and_refuses_unsigned_or_denied() {
        let security = crate::test_support::security().await;
        let s = state(Some(security.clone()));
        let credential = crate::proxy::StoredCredential::ApiKey {
            placement: None,
            scheme: None,
            provider: "github-issues".into(),
            key: "k".into(),
        };
        let owner = Agent::new(22);

        // Unsigned.
        let code = handoff(&security, &request(), credential.clone())
            .await
            .unwrap();
        let unsigned = crate::router(s.clone())
            .oneshot(
                axum::http::Request::builder()
                    .method("POST")
                    .uri("/connect/redeem")
                    .body(axum::body::Body::from(
                        serde_json::json!({"code": code, "code_verifier": "a".repeat(43)})
                            .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(unsigned.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(body_json(unsigned).await["error"], "missing_signature");

        // Signed with the legacy did:ad:agent spelling: owner is canonical.
        let body = serde_json::json!({"code": code, "code_verifier": "a".repeat(43)}).to_string();
        let mut legacy = signed_request(&s, &owner, "POST", "/connect/redeem", body.into_bytes());
        legacy.headers_mut().insert(
            crate::signature::AGENT_HEADER,
            owner.legacy_id().parse().unwrap(),
        );
        let response = crate::router(s.clone()).oneshot(legacy).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(body_json(response).await["owner"], owner.id());

        // The access policy refuses a denied owner before the handoff is spent.
        let mut denied = state(Some(security.clone()));
        denied.access =
            std::sync::Arc::new(crate::access::EnvAccessPolicy::new(None, vec![owner.id()]));
        let code = handoff(&security, &request(), credential.clone())
            .await
            .unwrap();
        let response = redeem_as(&denied, &owner, &code, &"a".repeat(43)).await;
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
        assert_eq!(body_json(response).await["error"], "access_denied");
        let response = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
        assert_eq!(response.status(), StatusCode::OK);

        // An expired handoff.
        let code = handoff(&security, &request(), credential).await.unwrap();
        crate::security::tests::admin()
            .await
            .execute(
                "UPDATE connection_handoffs SET expires_at = NOW() - INTERVAL '1 second' WHERE code = $1",
                &[&code],
            )
            .await
            .unwrap();
        let response = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
    async fn postgres_two_simultaneous_redemptions_create_one_connection() {
        let security = crate::test_support::security().await;
        let s = state(Some(security.clone()));
        let code = handoff(
            &security,
            &request(),
            crate::proxy::StoredCredential::ApiKey {
                placement: None,
                scheme: None,
                provider: "github-issues".into(),
                key: "k".into(),
            },
        )
        .await
        .unwrap();
        let (a, b) = (Agent::new(23), Agent::new(24));
        let verifier = "a".repeat(43);
        let (first, second) = tokio::join!(
            redeem_as(&s, &a, &code, &verifier),
            redeem_as(&s, &b, &code, &verifier)
        );
        let statuses = [first.status(), second.status()];
        assert!(statuses.contains(&StatusCode::OK));
        assert!(statuses.contains(&StatusCode::BAD_REQUEST));
    }

    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL and fixture OAuth credentials; CI runs it"]
    async fn postgres_oauth_consent_is_bound_to_the_browser_and_cancellation_returns_home() {
        let security = crate::test_support::security().await;
        let s = state(Some(security.clone()));
        let consent = Consent {
            request: request(),
            csrf: random(),
            expires: crate::now_secs() + 600,
        };
        let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
            CONSENT_COOKIE,
            serde_json::to_string(&consent).unwrap(),
        ));
        let response = authorize(
            State(s.clone()),
            None,
            jar.clone(),
            HeaderMap::new(),
            Form(Approval {
                csrf: consent.csrf.clone(),
                api_key: None,
                username: None,
            }),
        )
        .await;
        let binding_cookie = set_cookie(&response, "platform_oauth").unwrap();
        let destination = continue_page(response).await;
        assert_eq!(destination.host_str(), Some("auth.example"));
        let provider_state = destination
            .query_pairs()
            .find(|(k, _)| k == "state")
            .unwrap()
            .1
            .into_owned();
        // Another browser (no binding cookie) cannot complete the callback.
        let foreign = crate::router(s.clone())
            .oneshot(
                axum::http::Request::builder()
                    .uri(format!(
                        "/oauth/github-issues/callback?state={provider_state}&error=access_denied"
                    ))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(foreign.status(), StatusCode::BAD_REQUEST);
        // The state was spent by that attempt; start again for the real browser.
        let consent = Consent {
            request: request(),
            csrf: random(),
            expires: crate::now_secs() + 600,
        };
        let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
            CONSENT_COOKIE,
            serde_json::to_string(&consent).unwrap(),
        ));
        let response = authorize(
            State(s.clone()),
            None,
            jar,
            HeaderMap::new(),
            Form(Approval {
                csrf: consent.csrf.clone(),
                api_key: None,
                username: None,
            }),
        )
        .await;
        let binding_cookie_2 = set_cookie(&response, "platform_oauth").unwrap();
        let destination = continue_page(response).await;
        let provider_state = destination
            .query_pairs()
            .find(|(k, _)| k == "state")
            .unwrap()
            .1
            .into_owned();
        assert_ne!(binding_cookie, binding_cookie_2);
        let cancelled = crate::router(s.clone())
            .oneshot(
                axum::http::Request::builder()
                    .uri(format!(
                        "/oauth/github-issues/callback?state={provider_state}&error=access_denied"
                    ))
                    .header(header::COOKIE, binding_cookie_2)
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(cancelled.status(), StatusCode::SEE_OTHER);
        let target = Url::parse(cancelled.headers()[header::LOCATION].to_str().unwrap()).unwrap();
        assert_eq!(target.origin().ascii_serialization(), "https://hub.example");
        assert!(target
            .query_pairs()
            .any(|(k, v)| k == "error" && v == "access_denied"));
        assert!(!target.query_pairs().any(|(k, _)| k == "connection_code"));
        assert_eq!(cancelled.headers()[header::CACHE_CONTROL], "no-store");
    }

    /// The whole flow a data browser runs, against a mocked provider:
    /// consent, provider authorization, callback, signed redeem, a
    /// delegation, and proxied calls by the owner and the delegated app.
    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL and fixture OAuth credentials; CI runs it"]
    async fn postgres_oauth_connect_redeem_delegate_and_proxy_end_to_end() {
        use std::sync::{
            atomic::{AtomicUsize, Ordering},
            Arc,
        };
        let tokens = Arc::new(AtomicUsize::new(0));
        let token_counter = tokens.clone();
        let upstream = axum::Router::new()
            .route(
                "/token",
                axum::routing::post(move |body: Bytes| {
                    let token_counter = token_counter.clone();
                    async move {
                        token_counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                        let body = String::from_utf8(body.to_vec()).unwrap();
                        assert!(body.contains("grant_type=authorization_code"));
                        assert!(body.contains("code=provider-code"));
                        assert!(body.contains(
                            "redirect_uri=https%3A%2F%2Fproxy.example%2Foauth%2Fgithub-issues%2Fcallback"
                        ));
                        Json(serde_json::json!({"access_token": "provider-token", "refresh_token": "r", "expires_in": 3600}))
                    }
                }),
            )
            .route(
                "/records",
                axum::routing::get(|headers: HeaderMap| async move {
                    Json(serde_json::json!({
                        "authorization": headers.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()),
                    }))
                }),
            );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let upstream_url = format!("http://{}", listener.local_addr().unwrap());
        let server = tokio::spawn(async move { axum::serve(listener, upstream).await.unwrap() });

        let security = crate::test_support::security().await;
        let mut s = state(Some(security.clone()));
        s.catalog = crate::catalog::Catalog::from_test_document(
            "github-issues",
            serde_json::json!({
                "servers": [{"url": upstream_url}],
                "components": {"securitySchemes": {"oauth": {"type": "oauth2", "flows": {
                    "authorizationCode": {
                        "authorizationUrl": "https://auth.example/authorize",
                        "tokenUrl": "https://auth.example/token",
                        "scopes": {"read": "Read records"}
                    }
                }}}},
                "security": [{"oauth": ["read"]}],
                "paths": {"/records": {"get": {}}}
            }),
            serde_json::json!({}),
        );
        s.test_upstream = Some(upstream_url);

        // 1. The consent page, with no login, then approval.
        let page = crate::router(s.clone())
            .oneshot(
                axum::http::Request::builder()
                    .uri(connect_uri(&request()))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(page.status(), StatusCode::OK);
        let consent_cookie = page
            .headers()
            .get_all(header::SET_COOKIE)
            .iter()
            .map(|v| v.to_str().unwrap().split(';').next().unwrap().to_string())
            .find(|v| v.starts_with("platform_consent="))
            .unwrap();
        let html = String::from_utf8(
            axum::body::to_bytes(page.into_body(), 65_536)
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();
        let csrf = html
            .split("name=\"csrf\" value=\"")
            .nth(1)
            .unwrap()
            .split('"')
            .next()
            .unwrap()
            .to_owned();
        let approval = crate::router(s.clone())
            .oneshot(
                axum::http::Request::builder()
                    .method("POST")
                    .uri("/connect/authorize")
                    .header(header::COOKIE, &consent_cookie)
                    .header(header::ORIGIN, crate::test_support::PUBLIC_ORIGIN)
                    .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(format!("csrf={csrf}")))
                    .unwrap(),
            )
            .await
            .unwrap();
        let binding = set_cookie(&approval, "platform_oauth").unwrap();
        let provider = continue_page(approval).await;
        assert_eq!(provider.host_str(), Some("auth.example"));
        let provider_state = provider
            .query_pairs()
            .find(|(k, _)| k == "state")
            .unwrap()
            .1
            .into_owned();

        // 2. The provider calls back; the browser returns home with a handoff.
        let callback = crate::router(s.clone())
            .oneshot(
                axum::http::Request::builder()
                    .uri(format!(
                        "/oauth/github-issues/callback?state={provider_state}&code=provider-code"
                    ))
                    .header(header::COOKIE, binding)
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(callback.status(), StatusCode::SEE_OTHER);
        assert_eq!(tokens.load(Ordering::SeqCst), 1);
        let home = Url::parse(callback.headers()[header::LOCATION].to_str().unwrap()).unwrap();
        assert_eq!(home.origin().ascii_serialization(), "https://hub.example");
        assert!(home
            .query_pairs()
            .any(|(k, v)| k == "integration_state" && v == "state"));
        let handoff = home
            .query_pairs()
            .find(|(k, _)| k == "connection_code")
            .unwrap()
            .1
            .into_owned();
        assert!(!home.as_str().contains("provider-token"));

        // 3. The page redeems, signed with the user's key: the owner.
        let owner = Agent::new(61);
        let redeemed = redeem_as(&s, &owner, &handoff, &"a".repeat(43)).await;
        assert_eq!(redeemed.status(), StatusCode::OK);
        let redeemed = body_json(redeemed).await;
        let connection_id = redeemed["connection_id"].as_str().unwrap().to_owned();
        assert_eq!(redeemed["owner"], owner.id());

        // 4. The owner calls the provider through the proxy.
        let path = format!("/proxy/{connection_id}/github-issues/records");
        let call = crate::router(s.clone())
            .oneshot(signed_request(&s, &owner, "GET", &path, vec![]))
            .await
            .unwrap();
        assert_eq!(call.status(), StatusCode::OK);
        assert_eq!(
            body_json(call).await["authorization"],
            "Bearer provider-token"
        );

        // 5. The owner delegates to an app agent, which may then call too.
        let app = Agent::new(62);
        let delegation = crate::router(s.clone())
            .oneshot(signed_request(
                &s,
                &owner,
                "POST",
                &format!("/connections/{connection_id}/agents"),
                serde_json::json!({"agent": app.id(), "label": "Issue tracker"})
                    .to_string()
                    .into_bytes(),
            ))
            .await
            .unwrap();
        assert_eq!(delegation.status(), StatusCode::OK);
        let call = crate::router(s.clone())
            .oneshot(signed_request(&s, &app, "GET", &path, vec![]))
            .await
            .unwrap();
        assert_eq!(call.status(), StatusCode::OK);
        server.abort();
    }

    /// Regression (production, 2026-09-29): a provider whose authorization
    /// endpoint on its API host redirects to its sign-in UI on another host
    /// was blocked, because the approval was a `303` and Chrome held the
    /// whole redirect chain to the consent page's `form-action`, which only
    /// listed the authorization endpoint's origin. The approval now answers
    /// with a page, and the consent page allows form submissions to itself
    /// only, so no provider origin needs listing.
    #[tokio::test]
    #[ignore = "requires TEST_DATABASE_URL and fixture OAuth credentials; CI runs it"]
    async fn postgres_oauth_approval_leaves_the_form_before_the_provider_redirects() {
        let security = crate::test_support::security().await;
        let mut s = state(Some(security));
        s.catalog = crate::catalog::Catalog::from_test_document(
            "github-issues",
            serde_json::json!({
                "servers": [{"url": "https://api.provider.example/v1"}],
                "components": {"securitySchemes": {"oauth": {"type": "oauth2", "flows": {
                    "authorizationCode": {
                        "authorizationUrl": "https://api.provider.example/v1/oauth/authorize",
                        "tokenUrl": "https://api.provider.example/v1/oauth/token",
                        "scopes": {"read": "Read records"}
                    }
                }}}},
                "security": [{"oauth": ["read"]}],
                "paths": {"/records": {"get": {}}}
            }),
            serde_json::json!({}),
        );
        let page = crate::router(s.clone())
            .oneshot(
                axum::http::Request::builder()
                    .uri(connect_uri(&request()))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(page.status(), StatusCode::OK);
        let policy = page.headers()["content-security-policy"]
            .to_str()
            .unwrap()
            .to_owned();
        assert!(policy.ends_with("; form-action 'self'"), "{policy}");
        assert!(!policy.contains("provider.example"), "{policy}");
        let consent_cookie = set_cookie(&page, "platform_consent").unwrap();
        let html = body_text(page).await;
        let csrf = html
            .split("name=\"csrf\" value=\"")
            .nth(1)
            .unwrap()
            .split('"')
            .next()
            .unwrap()
            .to_owned();
        let approve = |cookie: String| {
            crate::router(s.clone()).oneshot(
                axum::http::Request::builder()
                    .method("POST")
                    .uri("/connect/authorize")
                    .header(header::COOKIE, cookie)
                    .header(header::ORIGIN, crate::test_support::PUBLIC_ORIGIN)
                    .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .body(axum::body::Body::from(format!("csrf={csrf}")))
                    .unwrap(),
            )
        };
        let approval = approve(consent_cookie.clone()).await.unwrap();
        let used = set_cookie(&approval, CONSENT_USED_COOKIE).unwrap();
        // The consent cookie is cleared (an empty value, already expired).
        assert_eq!(
            set_cookie(&approval, CONSENT_COOKIE).as_deref(),
            Some("platform_consent=")
        );
        let provider = continue_page(approval).await;
        assert_eq!(provider.host_str(), Some("api.provider.example"));
        assert_eq!(provider.path(), "/v1/oauth/authorize");
        assert!(provider.query_pairs().any(|(k, v)| k == "redirect_uri"
            && v == "https://proxy.example/oauth/github-issues/callback"));

        // A double click: the second submission still carries the consent
        // cookie, whose single use the first one spent.
        let again = approve(consent_cookie).await.unwrap();
        assert_eq!(again.status(), StatusCode::BAD_REQUEST);
        assert_eq!(body_text(again).await, ALREADY_APPROVED);
        // Approving again later from the same page (e.g. after going back).
        let later = approve(used).await.unwrap();
        assert_eq!(later.status(), StatusCode::BAD_REQUEST);
        assert_eq!(body_text(later).await, ALREADY_APPROVED);
    }
}