alien-client-core 3.3.71

Deploy software into your customers' cloud accounts and keep it fully managed
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
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
//! Interceptors: an extension's code that changes a cloud call after Alien builds it and before
//! Alien signs it, and changes the response before Alien reads it.
//!
//! A deployment's chain travels on the clients built for it, never on a client config or in a
//! global, so two deployments in one process never see each other's interceptors. An
//! interceptor never sees the credentials Alien signs with. It may change what a call says about
//! the deployment's own resources, and Alien refuses any change to where a call goes, to its
//! method and path, to which identity it names, to an image in a cloud registry, or to a header
//! that carries or protects a credential; on Kubernetes it may change only an object's labels. A
//! call that changes who has access, acts as another identity or carries a Kubernetes credential
//! is never offered, and no call may become one.

use crate::error::{ErrorData, Result};
use crate::identity::{decoded, is_identity_call};
use alien_error::{AlienError, Context, IntoAlienError};
use base64::Engine;
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_LENGTH};
use reqwest::{Method, Url};
#[cfg(not(target_arch = "wasm32"))]
use reqwest::{ResponseBuilderExt, StatusCode};
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
use std::sync::Arc;

/// The API a call goes to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cloud {
    Aws,
    Gcp,
    Azure,
    Kubernetes,
}

impl std::fmt::Display for Cloud {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Cloud::Aws => "aws",
            Cloud::Gcp => "gcp",
            Cloud::Azure => "azure",
            Cloud::Kubernetes => "kubernetes",
        })
    }
}

/// A call as an interceptor sees it: the request Alien built, without credentials.
#[derive(Debug, Clone)]
pub struct HookRequest {
    pub cloud: Cloud,
    /// The service the call is signed for: the SigV4 signing name on AWS (`rds`), Alien's
    /// endpoint key on Google Cloud (`cloudsql`), `management` for Azure Resource Manager, and
    /// `kubernetes` for the API server.
    pub service: String,
    pub method: Method,
    pub url: Url,
    /// The request's headers, without `authorization`, `proxy-authorization` and
    /// `x-amz-security-token`.
    pub headers: HeaderMap,
    /// The body as text, or `None` when the request has no body. A binary body is never
    /// offered, so `matches` sees `None` for it as well, and a call it matches fails.
    pub body: Option<String>,
}

/// A response as an interceptor sees it, before Alien reads it.
#[derive(Debug, Clone)]
pub struct HookResponse {
    pub status: u16,
    pub headers: HeaderMap,
    pub body: String,
}

/// One extension's interceptor.
pub trait CallInterceptor: Send + Sync {
    /// The extension's name, which every error this interceptor causes carries.
    fn extension(&self) -> &str;

    /// Whether this interceptor sees `request`, the call as the interceptors before it left it.
    /// Only the interceptors that match a call see its request and its response. An error fails
    /// the call, as a failing `modify_request` does.
    fn matches(&self, request: &HookRequest) -> Result<bool>;

    fn modify_request(&self, request: &mut HookRequest) -> Result<()>;

    /// Changes `response`, error responses included. `request` is the request as sent. An error
    /// fails the call for good, even one the interceptor marked retryable.
    fn modify_response(&self, request: &HookRequest, response: &mut HookResponse) -> Result<()>;
}

/// A deployment's interceptors, in the order its stack lists extensions. Each one gets the
/// request as the previous one left it.
#[derive(Clone, Default)]
pub struct InterceptorChain {
    interceptors: Vec<Arc<dyn CallInterceptor>>,
    /// Set for a call whose body, sent or received, is an object's bytes.
    object_payload: bool,
}

impl std::fmt::Debug for InterceptorChain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_list()
            .entries(
                self.interceptors
                    .iter()
                    .map(|interceptor| interceptor.extension()),
            )
            .finish()
    }
}

/// Headers an interceptor may not set, change or remove: they pick the destination, the method
/// the server runs, the project billed or the object an S3 copy reads, carry a credential, are
/// signed with one, or say how the body is read.
const PROTECTED_HEADERS: [&str; 12] = [
    "host",
    "content-type",
    "x-http-method-override",
    "x-http-method",
    "authorization",
    "x-amz-date",
    "x-amz-security-token",
    "proxy-authorization",
    "x-goog-user-project",
    "x-goog-api-key",
    "x-ms-authorization-auxiliary",
    "x-amz-copy-source",
];

/// Query parameters Google Cloud reads the project billed, the caller's credential or the
/// format of the body and response from, in any case, so an interceptor may not set, change or
/// remove them on a Google Cloud call. Every system parameter written with a leading `$` (such
/// as `$ct`, which sets the body's content type) is protected the same way.
const PROTECTED_GCP_QUERY: [&str; 6] = [
    "userproject",
    "key",
    "access_token",
    "oauth_token",
    "bearer_token",
    "alt",
];

/// Kubernetes' impersonation headers (`impersonate-user`, `impersonate-group`,
/// `impersonate-extra-*`, ...) set who the call acts as, so an interceptor may not set, change or
/// remove any of them.
const PROTECTED_HEADER_PREFIX: &str = "impersonate-";

/// AWS operations that read or change a resource's policy, its grants or who may call it,
/// through the resource's own service: SNS and SQS permissions, KMS key policies and grants,
/// ECR repository policies, and Secrets Manager and CloudWatch Logs resource policies.
const AWS_POLICY_OPERATIONS: [&str; 13] = [
    "AddPermission",
    "RemovePermission",
    "PutKeyPolicy",
    "GetKeyPolicy",
    "CreateGrant",
    "RetireGrant",
    "RevokeGrant",
    "SetRepositoryPolicy",
    "GetRepositoryPolicy",
    "DeleteRepositoryPolicy",
    "PutResourcePolicy",
    "GetResourcePolicy",
    "DeleteResourcePolicy",
];

/// The WebAssembly reqwest cannot rebuild a response, and no WebAssembly build of Alien gives
/// its clients interceptors, so a call one matches fails before it is sent.
const WASM_UNSUPPORTED: &str = "interceptors do not run in WebAssembly builds of Alien";

/// Headers that carry a credential. The interceptor's view leaves them out, and the request
/// keeps them as they were.
const CREDENTIAL_HEADERS: [&str; 3] = [
    "authorization",
    "proxy-authorization",
    "x-amz-security-token",
];

/// Where a signed request carries a credential: these headers, and on Google Cloud these query
/// parameters. A response can quote them, as AWS quotes the signed headers, session token
/// included, when a signature does not match.
const CREDENTIAL_CARRIERS: [&str; 5] = [
    "authorization",
    "proxy-authorization",
    "x-amz-security-token",
    "x-goog-api-key",
    "x-ms-authorization-auxiliary",
];
const CREDENTIAL_QUERY: [&str; 3] = ["access_token", "key", "oauth_token"];

impl InterceptorChain {
    pub fn new(interceptors: Vec<Arc<dyn CallInterceptor>>) -> Self {
        Self {
            interceptors,
            object_payload: false,
        }
    }

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

    /// The same interceptors, for a call that sends or returns an object's bytes (an S3 or Cloud
    /// Storage object, a Lambda payload). Those bytes are never offered, whatever their content
    /// type, so the call fails before it is sent when an interceptor matches it.
    pub fn for_object_payload(&self) -> Self {
        Self {
            interceptors: self.interceptors.clone(),
            object_payload: true,
        }
    }

    /// Runs the interceptors that match `request`, which Alien built and has not sent, on it.
    /// Returns the hook its response must pass through, or `None` when no interceptor matched
    /// and the request is left as it was.
    pub fn intercept(
        &self,
        cloud: Cloud,
        service: &str,
        request: &mut reqwest::Request,
    ) -> Result<Option<ResponseHook>> {
        if self.is_empty() {
            return Ok(None);
        }
        let body = match request.body() {
            _ if self.object_payload => Err(()),
            None => Ok(None),
            Some(body) => match body.as_bytes() {
                None => Err(()),
                Some([]) => Ok(None),
                Some(bytes) => String::from_utf8(bytes.to_vec()).map(Some).map_err(|_| ()),
            },
        };
        let mut headers = request.headers().clone();
        for name in CREDENTIAL_HEADERS {
            headers.remove(name);
        }
        let original = HookRequest {
            cloud,
            service: service.to_string(),
            method: request.method().clone(),
            url: request.url().clone(),
            headers,
            body: body.clone().unwrap_or_default(),
        };
        // Not even `matches` sees it, so an interceptor that matches every call never fails it.
        if changes_access(&original) {
            return Ok(None);
        }

        if body.is_err() || cfg!(target_arch = "wasm32") {
            let mut first_match = None;
            for interceptor in &self.interceptors {
                if matches(interceptor.as_ref(), &original)? {
                    first_match = Some(interceptor);
                    break;
                }
            }
            let Some(interceptor) = first_match else {
                return Ok(None);
            };
            let reason = if body.is_err() {
                format!(
                    "the {cloud} {service} call {} {} carries a binary body, which interceptors are not offered",
                    original.method,
                    original.url.path()
                )
            } else {
                WASM_UNSUPPORTED.to_string()
            };
            return Err(failed(interceptor.extension(), reason));
        }

        let mut view = original.clone();
        let mut matched = Vec::new();
        for interceptor in &self.interceptors {
            if !matches(interceptor.as_ref(), &view)? {
                continue;
            }
            interceptor
                .modify_request(&mut view)
                .context_keeping_retry(ErrorData::InterceptorFailed {
                    extension: interceptor.extension().to_string(),
                    message: format!("modify_request failed on the {cloud} {service} call"),
                })?;
            // A JSON body is sent as it was parsed, and checked in that form, so a key written
            // twice or an escape a cloud would decode can't carry a change the checks never saw.
            if view.body != original.body {
                if let Some(Ok(parsed)) = view
                    .body
                    .as_deref()
                    .map(serde_json::from_str::<serde_json::Value>)
                {
                    view.body = Some(parsed.to_string());
                }
            }
            if let Some(reason) = refused_change(&original, &view) {
                return Err(failed(interceptor.extension(), reason));
            }
            matched.push(interceptor.clone());
        }
        if matched.is_empty() {
            return Ok(None);
        }

        let mut headers = view.headers.clone();
        for name in CREDENTIAL_HEADERS {
            for value in request.headers().get_all(name) {
                headers.append(name, value.clone());
            }
        }
        *request.method_mut() = view.method.clone();
        *request.url_mut() = view.url.clone();
        *request.headers_mut() = headers;
        if view.body != original.body {
            let body = view.body.clone().unwrap_or_default();
            rewrite_body_digests(request.headers_mut(), body.as_bytes())?;
            *request.body_mut() = view.body.clone().map(reqwest::Body::from);
        }

        let mut hook = ResponseHook {
            matched: matched.into(),
            request: Arc::new(view),
            secrets: Vec::new(),
        };
        // A client that signs before its interceptors run has its credential on the request
        // already; one that signs after adds it with `remember_credentials`.
        hook.remember_credentials(request);
        Ok(Some(hook))
    }

    /// Refuses `url` unless it is on `endpoint`, the endpoint this client was configured with.
    /// A response names URLs Alien then sends its credential to (an operation to poll, a next
    /// page), and an interceptor can rewrite a response, so a client with interceptors signs only
    /// for its own endpoint.
    pub fn check_destination(&self, url: &Url, endpoint: &str) -> Result<()> {
        if self.is_empty() {
            return Ok(());
        }
        let endpoint =
            Url::parse(endpoint)
                .into_alien_error()
                .context(ErrorData::InvalidClientConfig {
                    message: format!("The client's endpoint '{endpoint}' is not a URL"),
                    errors: None,
                })?;
        if url.origin() == endpoint.origin() {
            return Ok(());
        }
        Err(AlienError::new(ErrorData::DestinationRefused {
            url: url.origin().ascii_serialization(),
            endpoint: endpoint.origin().ascii_serialization(),
        }))
    }
}

/// The interceptors that matched one call, to run on its response.
#[derive(Clone)]
pub struct ResponseHook {
    matched: Arc<[Arc<dyn CallInterceptor>]>,
    request: Arc<HookRequest>,
    /// The credentials the call was sent with, cleared from its response before any interceptor
    /// reads it.
    secrets: Vec<String>,
}

impl std::fmt::Debug for ResponseHook {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_list()
            .entries(
                self.matched
                    .iter()
                    .map(|interceptor| interceptor.extension()),
            )
            .finish()
    }
}

impl ResponseHook {
    /// Records the credentials `request` carries, so they are cleared from the response before
    /// an interceptor reads it. A client that signs after the interceptors ran calls this with
    /// the signed request.
    pub fn remember_credentials(&mut self, request: &reqwest::Request) {
        for name in CREDENTIAL_CARRIERS {
            for value in request.headers().get_all(name) {
                let Ok(value) = value.to_str() else {
                    continue;
                };
                self.remember(value);
                // `Bearer <token>`, alone or listed, as Azure's auxiliary header lists them.
                for part in value.split(',') {
                    if let Some((_, credential)) = part.trim().split_once(' ') {
                        self.remember(credential);
                    }
                }
            }
        }
        for (name, value) in request.url().query_pairs() {
            if CREDENTIAL_QUERY
                .iter()
                .any(|carrier| name.eq_ignore_ascii_case(carrier))
            {
                self.remember(&value);
            }
        }
    }

    fn remember(&mut self, secret: &str) {
        let secret = secret.trim();
        // Short of any real credential, and short enough to match ordinary text.
        if secret.len() >= 8 && !self.secrets.iter().any(|known| known == secret) {
            self.secrets.push(secret.to_string());
        }
    }

    /// `bytes` with each recorded credential replaced by `[redacted]`, longest first, so one
    /// that contains another is cleared whole.
    fn cleared(&self, bytes: &[u8]) -> Vec<u8> {
        let mut secrets: Vec<&String> = self.secrets.iter().collect();
        secrets.sort_by_key(|secret| std::cmp::Reverse(secret.len()));
        secrets.into_iter().fold(bytes.to_vec(), |bytes, secret| {
            blank(bytes, secret.as_bytes())
        })
    }

    /// Reads the whole response, lets each interceptor that matched the call change it, and
    /// returns a response Alien reads as if the cloud had sent it.
    #[cfg(not(target_arch = "wasm32"))]
    pub async fn apply(&self, response: reqwest::Response) -> Result<reqwest::Response> {
        let status = response.status();
        let url = response.url().clone();
        let headers = response.headers().clone();
        let read = response.bytes().await.into_alien_error();
        // This runs inside the retry loop, and after a 2xx the cloud already acted on the call.
        let bytes = if status.is_success() {
            read.context(ErrorData::HttpResponseBodyReadFailed {
                http_status: status.as_u16(),
            })?
        } else {
            read.context(ErrorData::HttpRequestFailed {
                message: "Failed to read response body".to_string(),
            })?
        };
        let Ok(body) = String::from_utf8(bytes.to_vec()) else {
            return Err(failed(
                self.matched[0].extension(),
                format!(
                    "the response to the {} {} call {} {} has a binary body, which interceptors are not offered",
                    self.request.cloud,
                    self.request.service,
                    self.request.method,
                    self.request.url.path()
                ),
            ));
        };

        // Cleared before any interceptor runs: one could encode an echoed credential into what
        // it leaves, where clearing it later would no longer find it.
        let mut cleared_headers = HeaderMap::with_capacity(headers.len());
        for (name, value) in &headers {
            // `[redacted]` in place of the credential keeps the value a valid header.
            if let Ok(value) = HeaderValue::from_bytes(&self.cleared(value.as_bytes())) {
                cleared_headers.append(name.clone(), value);
            }
        }
        let body = String::from_utf8(self.cleared(body.as_bytes())).unwrap_or(body);
        let mut view = HookResponse {
            status: status.as_u16(),
            headers: cleared_headers,
            body,
        };
        let received = (view.status, view.headers.clone(), view.body.clone());
        for interceptor in self.matched.iter() {
            // Final whatever the hook said: the cloud already acted on the call, and a retry
            // would send it again.
            interceptor
                .modify_response(&self.request, &mut view)
                .context(ErrorData::InterceptorFailed {
                    extension: interceptor.extension().to_string(),
                    message: format!(
                        "modify_response failed on the {} {} call",
                        self.request.cloud, self.request.service
                    ),
                })?;
            let Ok(left) = StatusCode::from_u16(view.status) else {
                return Err(failed(
                    interceptor.extension(),
                    format!("{} is not an HTTP status", view.status),
                ));
            };
            // The cloud already acted on a call it answered with success, so a failure a hook
            // makes of it fails the call for good: a client would retry a status such as 429,
            // and send a create again.
            if status.is_success() && !left.is_success() {
                return Err(failed(
                    interceptor.extension(),
                    format!(
                        "it turned the {} {} call's success ({}) into {left}, after the cloud had acted on it",
                        self.request.cloud,
                        self.request.service,
                        status.as_u16()
                    ),
                ));
            }
            if self.request.cloud == Cloud::Kubernetes
                && (view.status, &view.headers, &view.body)
                    != (received.0, &received.1, &received.2)
            {
                return Err(failed(
                    interceptor.extension(),
                    "on Kubernetes an interceptor may not change a response".to_string(),
                ));
            }
        }

        let mut headers = view.headers;
        // The body's own length decides it; a stale one would cut or stall the read.
        headers.remove(CONTENT_LENGTH);
        let last = &self.matched[self.matched.len() - 1];
        let mut rebuilt = http::Response::builder()
            .status(view.status)
            .url(url)
            .body(view.body)
            .into_alien_error()
            .context(ErrorData::InterceptorFailed {
                extension: last.extension().to_string(),
                message: "the response it left could not be rebuilt".to_string(),
            })?;
        *rebuilt.headers_mut() = headers;
        Ok(reqwest::Response::from(rebuilt))
    }

    #[cfg(target_arch = "wasm32")]
    pub async fn apply(&self, _response: reqwest::Response) -> Result<reqwest::Response> {
        Err(failed(
            self.matched[0].extension(),
            format!(
                "{WASM_UNSUPPORTED}: the {} {} call",
                self.request.cloud, self.request.service
            ),
        ))
    }
}

/// Keeps an interceptor's failure final under a wrapper that marks the error retryable: the same
/// request fails the same way again. A failure before the call was sent that the interceptor
/// itself marked retryable, as a hook stopped at its deadline is, stays retryable.
pub fn keep_interceptor_failure_final<T>(result: Result<T>) -> Result<T> {
    result.map_err(|mut error| {
        let final_failure =
            |code: &str, retryable: bool| is_interceptor_failure(code) && !retryable;
        let mut caused_by_interceptor = final_failure(&error.code, error.retryable);
        let mut layer = error.source.as_deref();
        while let Some(source) = layer {
            caused_by_interceptor |= final_failure(&source.code, source.retryable);
            layer = source.source.as_deref();
        }
        if caused_by_interceptor {
            error.retryable = false;
        }
        error
    })
}

/// `bytes` with each occurrence of `secret` replaced by `[redacted]`.
fn blank(bytes: Vec<u8>, secret: &[u8]) -> Vec<u8> {
    const BLANK: &[u8] = b"[redacted]";
    let mut cleared = Vec::new();
    let mut rest = bytes.as_slice();
    while let Some(at) = rest
        .windows(secret.len())
        .position(|window| window == secret)
    {
        cleared.extend_from_slice(&rest[..at]);
        cleared.extend_from_slice(BLANK);
        rest = &rest[at + secret.len()..];
    }
    if cleared.is_empty() {
        return bytes;
    }
    cleared.extend_from_slice(rest);
    cleared
}

fn is_interceptor_failure(code: &str) -> bool {
    matches!(code, "INTERCEPTOR_FAILED" | "DESTINATION_REFUSED")
}

/// Passes `response` through `hook`, when the call had one.
pub async fn apply_response_hook(
    hook: Option<&ResponseHook>,
    response: reqwest::Response,
) -> Result<reqwest::Response> {
    match hook {
        Some(hook) => hook.apply(response).await,
        None => Ok(response),
    }
}

/// Asks `interceptor` whether it sees `request`, naming it in the error when it can't answer.
fn matches(interceptor: &dyn CallInterceptor, request: &HookRequest) -> Result<bool> {
    interceptor
        .matches(request)
        .context_keeping_retry(ErrorData::InterceptorFailed {
            extension: interceptor.extension().to_string(),
            message: format!(
                "matches failed on the {} {} call",
                request.cloud, request.service
            ),
        })
}

/// `.context` for an interceptor's error from `matches` or `modify_request`, before the call is
/// sent. The failure is final unless the interceptor itself said it may pass, as a hook stopped
/// at its deadline may.
trait KeepingRetry<T> {
    fn context_keeping_retry(self, context: ErrorData) -> Result<T>;
}

impl<T> KeepingRetry<T> for Result<T> {
    fn context_keeping_retry(self, context: ErrorData) -> Result<T> {
        self.map_err(|error| {
            let retryable = error.retryable && error.code == "INTERCEPTOR_FAILED";
            let mut wrapped = Err::<(), _>(error).context(context).unwrap_err();
            wrapped.retryable = retryable;
            wrapped
        })
    }
}

fn failed(extension: &str, message: String) -> AlienError<ErrorData> {
    AlienError::new(ErrorData::InterceptorFailed {
        extension: extension.to_string(),
        message,
    })
}

/// Why the change from `original` to `changed` is refused, if it is.
fn refused_change(original: &HookRequest, changed: &HookRequest) -> Option<String> {
    if original.cloud == Cloud::Kubernetes && !only_labels_changed(original, changed) {
        return Some(
            "on Kubernetes an interceptor may change only the object's metadata.labels".to_string(),
        );
    }
    if changed.url.origin() != original.url.origin() {
        return Some(format!(
            "it moved the call from {} to {}; it may change the query, not the scheme, host or port",
            original.url.origin().ascii_serialization(),
            changed.url.origin().ascii_serialization()
        ));
    }
    if changed.cloud != original.cloud || changed.service != original.service {
        return Some(format!(
            "it changed the call's cloud or service from {} {} to {} {}",
            original.cloud, original.service, changed.cloud, changed.service
        ));
    }
    if changes_access(changed) {
        return Some(
            "it turned the call into one that changes who has access or acts as another identity"
                .to_string(),
        );
    }
    let (before, after) = (exposure_settings(original), exposure_settings(changed));
    if let Some((place, _)) = before.symmetric_difference(&after).next() {
        return Some(format!(
            "it added, removed or changed a setting that decides who can reach a resource ({place}); an interceptor may not touch network, firewall, access or public-exposure settings"
        ));
    }
    if let Some(exposure) = public_exposures(changed)
        .difference(&public_exposures(original))
        .next()
    {
        return Some(format!(
            "it made the call open a resource to the internet ({exposure}); an interceptor may not make storage or a network public"
        ));
    }
    if is_json(original) && !is_json(changed) {
        return Some("it changed a JSON body into one that is not JSON".to_string());
    }
    // The checks read a body by its format, and the cloud by the call's content type, which a
    // call Alien sends without a body may not match.
    if original.body.is_none() && changed.body.is_some() {
        return Some("it added a body to a call Alien sends without one".to_string());
    }
    // A JSON body is sent as it was parsed, so a body read as something else may not become one.
    if !is_json(original) && is_json(changed) {
        return Some("it changed a body that is not JSON into JSON".to_string());
    }
    if named_identities(changed) != named_identities(original) {
        return Some(
            "it changed which identity the call names; a call acts only as the identities Alien gives it"
                .to_string(),
        );
    }
    if let Some(image) = registry_images(changed)
        .difference(&registry_images(original))
        .next()
    {
        return Some(format!(
            "it named {image}, a reference to a cloud registry the call didn't name; only an image from a public registry may be added"
        ));
    }
    if changed.method != original.method || changed.url.path() != original.url.path() {
        return Some(format!(
            "it changed {} {} to {} {}; the method and path say which resource the call acts on and how",
            original.method,
            original.url.path(),
            changed.method,
            changed.url.path()
        ));
    }
    if original.cloud == Cloud::Aws && aws_operations(original) != aws_operations(changed) {
        return Some(
            "it changed the AWS operation, in the Action parameter or the X-Amz-Target header"
                .to_string(),
        );
    }
    // A query parameter can be the operation, such as S3's `?logging` or API Gateway's
    // `?mode=import`, so on AWS a parameter's value may change, its name not.
    if original.cloud == Cloud::Aws && query_names(original) != query_names(changed) {
        return Some(
            "it added or removed a query parameter; on AWS the parameters a call has are part of its operation"
                .to_string(),
        );
    }
    if original.cloud == Cloud::Gcp {
        let values = |request: &HookRequest, name: &str| -> Vec<String> {
            request
                .url
                .query_pairs()
                .filter(|(key, _)| key.eq_ignore_ascii_case(name))
                .map(|(_, value)| value.into_owned())
                .collect()
        };
        let system: BTreeSet<String> = [original, changed]
            .into_iter()
            .flat_map(|request| {
                request
                    .url
                    .query_pairs()
                    .map(|(key, _)| key.to_ascii_lowercase())
            })
            .filter(|key| key.starts_with('$'))
            .collect();
        if let Some(name) = PROTECTED_GCP_QUERY
            .into_iter()
            .map(str::to_string)
            .chain(
                PROTECTED_GCP_QUERY
                    .into_iter()
                    .map(|name| format!("${name}")),
            )
            .chain(system)
            .find(|name| values(original, name) != values(changed, name))
        {
            return Some(format!(
                "it set, changed or removed the '{name}' query parameter"
            ));
        }
    }
    // Header names are stored lowercase, so the prefix matches whatever case was sent.
    let impersonation = original
        .headers
        .keys()
        .chain(changed.headers.keys())
        .map(|name| name.as_str())
        .filter(|name| name.starts_with(PROTECTED_HEADER_PREFIX));
    PROTECTED_HEADERS
        .into_iter()
        .chain(impersonation)
        .find(|name| {
            !original
                .headers
                .get_all(*name)
                .iter()
                .eq(changed.headers.get_all(*name).iter())
        })
        .map(|name| format!("it set, changed or removed the '{name}' header"))
}

/// Whether `request` changes who has access, acts as another identity, reads a policy Alien then
/// writes back, or carries a Kubernetes Secret or service account token. The path is read
/// as the cloud reads it: percent-decoded and in any case.
fn changes_access(request: &HookRequest) -> bool {
    let path = decoded(request.url.path());
    // A cloud may fold a character that is not ASCII into one that is, and reach a name the
    // checks look for.
    if !path.is_ascii() {
        return true;
    }
    let path = path.to_ascii_lowercase();
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    let query: Vec<(String, String)> = request.url.query_pairs().into_owned().collect();
    if is_identity_call(
        request.cloud,
        &[request.service.as_str()],
        request.method.as_str(),
        &segments,
        &query,
    ) {
        return true;
    }
    match request.cloud {
        // Alien reads a policy, adds its binding and writes the policy back, so a read's
        // response decides the write.
        Cloud::Gcp => {
            segments.iter().any(|s| s.contains("iampolicy"))
                || (request.service == "storage"
                    && (segments.last() == Some(&"iam")
                        || segments
                            .iter()
                            .any(|s| matches!(*s, "acl" | "defaultobjectacl"))))
        }
        Cloud::Aws => {
            aws_operations(request).iter().any(|operation| {
                // A target is `<service>.<operation>`.
                let name = operation.rsplit('.').next().unwrap_or(operation);
                AWS_POLICY_OPERATIONS.contains(&name)
            }) || request.body.as_deref().is_some_and(sets_a_policy)
                // The query protocol reads parameters from the URL as well as the form body.
                || form_sets_a_policy(request.url.query().unwrap_or_default())
                || (request.service == "s3"
                    && (query
                        .iter()
                        .any(|(name, _)| {
                            matches!(
                                name.to_ascii_lowercase().as_str(),
                                "policy" | "acl" | "publicaccessblock"
                            )
                        })
                        || request.headers.keys().any(|name| {
                            name == "x-amz-acl" || name.as_str().starts_with("x-amz-grant-")
                        })))
                || (request.service == "lambda" && segments.contains(&"policy"))
                || (request.service == "apigateway"
                    && request.body.as_deref().is_some_and(sets_an_api_policy))
        }
        // A Secret holds the deployment's registry credential, a token request mints a service
        // account's token, and a token review carries one.
        Cloud::Kubernetes => {
            segments.contains(&"tokenreviews")
                || segments
                    .windows(3)
                    .any(|w| w[0] == "namespaces" && w[2] == "secrets")
                || segments.windows(2).any(|w| w == ["v1", "secrets"])
                || segments
                    .windows(3)
                    .any(|w| w[0] == "serviceaccounts" && w[2] == "token")
        }
        Cloud::Azure => false,
    }
}

/// Network ranges that mean the whole internet, in any cloud.
const OPEN_RANGES: [&str; 5] = ["0.0.0.0/0", "::/0", "internet", "any", "*"];

/// Fields that hold a source range or address prefix on Azure, which may name the internet as a
/// tag (`Internet`, `Any`, `*`) and not only as a CIDR.
const AZURE_SOURCE_FIELDS: [&str; 4] = [
    "sourceaddressprefix",
    "sourceaddressprefixes",
    "sourceaddresses",
    "ipaddressorrange",
];

/// A field name without case, `_` and `-`, so `invoker_iam_disabled`, `invokerIamDisabled` and
/// `Invoker-Iam-Disabled` are one name.
fn field_key(name: &str) -> String {
    name.chars()
        .filter(|c| !matches!(c, '_' | '-'))
        .map(|c| c.to_ascii_lowercase())
        .collect()
}

/// Whether a field by this name sets who can reach a resource: a public-access, network, firewall,
/// source-range, ingress, ACL or access-policy setting, on any cloud.
fn exposure_field(name: &str) -> bool {
    let name = field_key(name);
    name.starts_with("publicaccess")
        || name.starts_with("sourceaddressprefix")
        || name.contains("ingress")
        || matches!(
            name.as_str(),
            "allowblobpublicaccess"
                | "allowpublicaccess"
                | "publicnetworkaccess"
                | "networkacls"
                | "defaultaction"
                | "iprules"
                | "ipranges"
                | "ipaddressorrange"
                | "sourceaddresses"
                | "sourceranges"
                | "invokeriamdisabled"
                | "publiclyaccessible"
                | "ipconfiguration"
                | "ipv4enabled"
                | "authorizednetworks"
                | "cidrip"
                | "cidripv6"
                | "acl"
                | "defaultobjectacl"
                | "iamconfiguration"
                | "accesspolicies"
                | "enablerbacauthorization"
        )
}

/// Every exposure or access setting a call carries, with where it sits and its whole value
/// (every leaf of a nested setting). The set must be equal before and after an interceptor: a
/// setting added, removed or changed in any way counts, so a range split in two, a firewall
/// field flipped, or a protection element dropped is caught without judging its value.
fn exposure_settings(request: &HookRequest) -> BTreeSet<(String, String)> {
    let body = request.body.as_deref().unwrap_or_default();
    let mut found = BTreeSet::new();
    let json = serde_json::from_str::<serde_json::Value>(body).ok();
    let mut pairs = |location: &str, text: &str| {
        for (key, value) in form_urlencoded::parse(text.as_bytes()) {
            if key.rsplit('.').next().is_some_and(exposure_field) {
                found.insert((format!("{location}{key}"), value.into_owned()));
            }
        }
    };
    pairs("?", request.url.query().unwrap_or_default());
    if json.is_none() {
        pairs("&", body);
    }
    if let Some(value) = &json {
        json_settings(value, "", &mut found);
    }
    // The S3 public access block is XML: each element is a setting, counted by position.
    let lower = body.to_ascii_lowercase();
    for tag in [
        "blockpublicacls",
        "ignorepublicacls",
        "blockpublicpolicy",
        "restrictpublicbuckets",
    ] {
        let open = format!("<{tag}>");
        for (n, (at, _)) in lower.match_indices(&open).enumerate() {
            let rest = &lower[at + open.len()..];
            let value = rest.split('<').next().unwrap_or_default().trim();
            found.insert((format!("S3 {tag} #{n}"), value.to_string()));
        }
    }
    found
}

fn json_settings(value: &serde_json::Value, pointer: &str, found: &mut BTreeSet<(String, String)>) {
    match value {
        serde_json::Value::Object(fields) => {
            for (key, field) in fields {
                let at = pointer_to(pointer, key);
                if exposure_field(key) {
                    every_leaf(field, &at, found);
                }
                json_settings(field, &at, found);
            }
        }
        serde_json::Value::Array(items) => {
            for (index, item) in items.iter().enumerate() {
                json_settings(item, &format!("{pointer}/{index}"), found);
            }
        }
        _ => {}
    }
}

/// What in `request` opens a resource to the internet, each as a short description. A call that
/// Alien builds with one of them (a bucket made public on purpose) keeps it; the check refuses an
/// exposure the original call did not have. It covers a storage account or container that allows
/// public access, a storage firewall, network security group or firewall rule whose source is the
/// internet, a security group open to `0.0.0.0/0` or `::/0`, `allUsers` and
/// `allAuthenticatedUsers` in a Cloud Storage body, and an S3 public access block turned off.
fn public_exposures(request: &HookRequest) -> BTreeSet<String> {
    let body = request.body.as_deref().unwrap_or_default();
    let query = request.url.query().unwrap_or_default();
    let json = serde_json::from_str::<serde_json::Value>(body).ok();
    let mut texts = vec![body.to_string(), decoded(body), decoded(query)];
    if let Some(value) = &json {
        json_strings(value, &mut texts);
    }
    let mut found = BTreeSet::new();
    // A needle counts once per place it appears, so a second one is a new exposure.
    for needle in ["0.0.0.0/0", "::/0", "allusers", "allauthenticatedusers"] {
        let count = texts
            .iter()
            .map(|text| text.to_ascii_lowercase().matches(needle).count())
            .max()
            .unwrap_or(0);
        for n in 0..count {
            found.insert(format!("{needle} #{n}"));
        }
    }
    // An S3 public access block with a protection turned off.
    let lower = body.to_ascii_lowercase();
    for tag in [
        "blockpublicacls",
        "ignorepublicacls",
        "blockpublicpolicy",
        "restrictpublicbuckets",
    ] {
        if lower.contains(&format!("<{tag}>false")) {
            found.insert(format!("S3 {tag} turned off"));
        }
    }
    if let Some(value) = &json {
        json_exposures(value, "", &mut found);
    }
    found
}

fn json_exposures(value: &serde_json::Value, pointer: &str, found: &mut BTreeSet<String>) {
    match value {
        serde_json::Value::Object(fields) => {
            for (key, field) in fields {
                let name = field_key(key);
                let at = pointer_to(pointer, key);
                let text = field.as_str().map(|text| text.trim().to_ascii_lowercase());
                let public = match name.as_str() {
                    "allowblobpublicaccess" | "allowpublicaccess" => {
                        field.as_bool() == Some(true) || text.as_deref() == Some("true")
                    }
                    // A container's access level: anything but none or off.
                    "publicaccess" => text
                        .as_deref()
                        .is_some_and(|t| !matches!(t, "none" | "off" | "")),
                    "publicnetworkaccess" => text.as_deref() == Some("enabled"),
                    "defaultaction" => text.as_deref() == Some("allow"),
                    // Cloud Storage: public access prevention turned off.
                    "publicaccessprevention" => text.as_deref().is_some_and(|t| t != "enforced"),
                    _ => false,
                };
                if public {
                    found.insert(at.clone());
                }
                if AZURE_SOURCE_FIELDS.contains(&name.as_str())
                    || name == "ipranges"
                    || name == "sourceranges"
                {
                    let mut leaves = Vec::new();
                    json_strings(field, &mut leaves);
                    if leaves.iter().any(|leaf| {
                        let leaf = leaf.trim().to_ascii_lowercase();
                        OPEN_RANGES.contains(&leaf.as_str()) || leaf.ends_with("/0")
                    }) {
                        found.insert(format!("{at}: an open source range"));
                    }
                }
                json_exposures(field, &at, found);
            }
        }
        serde_json::Value::Array(items) => {
            for (index, item) in items.iter().enumerate() {
                json_exposures(item, &format!("{pointer}/{index}"), found);
            }
        }
        _ => {}
    }
}

/// The identities a call's body or query names, each with where it names it: a Google service
/// account's email, an AWS IAM role or instance profile ARN, an Azure managed identity's
/// resource ID, and a field that names an identity by its name. A call that drops one may act as
/// a default identity instead, and a name kept in another field no longer picks the identity, so
/// a change of any kind counts.
fn named_identities(request: &HookRequest) -> BTreeSet<(String, String)> {
    let body = request.body.as_deref().unwrap_or_default();
    let query = request.url.query().unwrap_or_default();
    let json = serde_json::from_str::<serde_json::Value>(body).ok();
    // Every identity the text names, wherever it sits, so a duplicate JSON key or a body that is
    // neither JSON nor a form still counts. A JSON escape hides a name from the raw text, so the
    // decoded strings are read too.
    let mut texts = vec![body.to_string(), decoded(body), decoded(query)];
    if let Some(value) = &json {
        json_strings(value, &mut texts);
    }
    let mut named = BTreeSet::new();
    for text in texts {
        let tokens = text.split(|c: char| !(c.is_ascii_alphanumeric() || "@._:/+=,-".contains(c)));
        for token in tokens {
            if names_an_identity(token) {
                named.insert(("*".to_string(), token.to_ascii_lowercase()));
            }
        }
    }
    let pairs = |location: &str, text: &str, named: &mut BTreeSet<(String, String)>| {
        for (key, value) in form_urlencoded::parse(text.as_bytes()) {
            if key.split('.').any(identity_field)
                || names_an_identity(&key)
                || names_an_identity(&value)
            {
                named.insert((format!("{location}{key}"), value.into_owned()));
            }
        }
    };
    pairs("?", query, &mut named);
    match &json {
        Some(value) => identity_fields(value, "", false, &mut named),
        None => pairs("&", body, &mut named),
    }
    named
}

/// Whether `text` contains a Google service account's email, an AWS IAM ARN or an Azure managed
/// identity's resource ID.
fn names_an_identity(text: &str) -> bool {
    let text = text.to_ascii_lowercase();
    text.contains(".gserviceaccount.com")
        || (text.contains("arn:aws") && text.contains(":iam::"))
        || text.contains("/providers/microsoft.managedidentity/")
}

/// Whether a field by this name names the identity a resource acts as, whatever its value.
fn identity_field(name: &str) -> bool {
    let name = field_key(name);
    matches!(
        name.as_str(),
        "role" | "identity" | "serviceaccount" | "serviceaccountname" | "serviceaccountemail"
    ) || name.ends_with("rolearn")
        || name.starts_with("iaminstanceprofile")
}

/// Each identity in `value` with its JSON pointer: a key or string that names one, and the whole
/// value of a field named for one. `in_service_accounts` is set under a `serviceAccounts` field,
/// whose `email` names the account.
fn identity_fields(
    value: &serde_json::Value,
    pointer: &str,
    in_service_accounts: bool,
    named: &mut BTreeSet<(String, String)>,
) {
    match value {
        serde_json::Value::String(text) if names_an_identity(text) => {
            named.insert((pointer.to_string(), text.clone()));
        }
        serde_json::Value::Array(items) => {
            for (index, item) in items.iter().enumerate() {
                let at = format!("{pointer}/{index}");
                identity_fields(item, &at, in_service_accounts, named);
            }
        }
        serde_json::Value::Object(fields) => {
            // A label or tag may be named `role`, and no cloud reads an identity from a key in a
            // labels, tags or annotations map; only a value shaped like an identity counts there.
            let free_form = pointer
                .rsplit('/')
                .next()
                .is_some_and(|parent| matches!(parent, "labels" | "tags" | "Tags" | "annotations"));
            for (key, field) in fields {
                let at = pointer_to(pointer, key);
                if names_an_identity(key) {
                    named.insert((at.clone(), key.clone()));
                }
                if !free_form && (identity_field(key) || (in_service_accounts && key == "email")) {
                    every_leaf(field, &at, named);
                }
                let under = key.eq_ignore_ascii_case("serviceaccounts");
                identity_fields(field, &at, under, named);
            }
        }
        _ => {}
    }
}

/// Every value in `value` with its JSON pointer, objects and arrays as `{}` and `[]`, so a field
/// counts whatever order its keys are written in.
fn every_leaf(value: &serde_json::Value, pointer: &str, named: &mut BTreeSet<(String, String)>) {
    match value {
        serde_json::Value::Object(fields) => {
            named.insert((pointer.to_string(), "{}".to_string()));
            for (key, field) in fields {
                every_leaf(field, &pointer_to(pointer, key), named);
            }
        }
        serde_json::Value::Array(items) => {
            named.insert((pointer.to_string(), "[]".to_string()));
            for (index, item) in items.iter().enumerate() {
                every_leaf(item, &format!("{pointer}/{index}"), named);
            }
        }
        scalar => {
            named.insert((pointer.to_string(), scalar.to_string()));
        }
    }
}

/// The JSON pointer to `key` in the object at `pointer`.
fn pointer_to(pointer: &str, key: &str) -> String {
    format!("{pointer}/{}", key.replace('~', "~0").replace('/', "~1"))
}

/// Whether `changed` differs from `original` in at most labels added to the object's top-level
/// `metadata.labels`. A Kubernetes call is signed by an identity that reaches what every
/// deployment on the cluster shares, so nothing else of it may change.
fn only_labels_changed(original: &HookRequest, changed: &HookRequest) -> bool {
    if original.method == changed.method
        && original.url == changed.url
        && original.headers == changed.headers
        && original.body == changed.body
    {
        return true;
    }
    type Labels = serde_json::Map<String, serde_json::Value>;
    let split = |request: &HookRequest| -> Option<(serde_json::Value, Labels)> {
        let mut object = match request.body.as_deref() {
            None => return Some((serde_json::Value::Null, Labels::new())),
            Some(body) => serde_json::from_str::<serde_json::Value>(body).ok()?,
        };
        let labels = match object
            .get_mut("metadata")
            .and_then(|m| m.as_object_mut())
            .and_then(|metadata| metadata.remove("labels"))
        {
            None | Some(serde_json::Value::Null) => Labels::new(),
            Some(serde_json::Value::Object(labels))
                if labels.values().all(serde_json::Value::is_string) =>
            {
                labels
            }
            Some(_) => return None,
        };
        Some((object, labels))
    };
    let (Some((before, kept)), Some((after, labels))) = (split(original), split(changed)) else {
        return false;
    };
    // Alien and the cluster select and clean up objects by these labels (`alien.dev/deployment`,
    // `kubernetes.io/...`, `managed-by`), so an interceptor adds only other labels and leaves every
    // label Alien set as it was.
    let reserved = |key: &str| key.contains('/') || key == "managed-by";
    original.method == changed.method
        && original.url == changed.url
        && original.headers == changed.headers
        && original.body.is_some() == changed.body.is_some()
        && before == after
        && kept
            .iter()
            .all(|(key, value)| labels.get(key) == Some(value))
        && labels
            .keys()
            .all(|key| kept.contains_key(key) || !reserved(key))
}

/// Whether the request's body, when it has one, is JSON.
fn is_json(request: &HookRequest) -> bool {
    request
        .body
        .as_deref()
        .is_some_and(|body| serde_json::from_str::<serde_json::Value>(body).is_ok())
}

/// Every key and string value in `value`.
fn json_strings(value: &serde_json::Value, texts: &mut Vec<String>) {
    match value {
        serde_json::Value::String(text) => texts.push(text.clone()),
        serde_json::Value::Array(items) => items.iter().for_each(|item| json_strings(item, texts)),
        serde_json::Value::Object(fields) => {
            for (key, field) in fields {
                texts.push(key.clone());
                json_strings(field, texts);
            }
        }
        _ => {}
    }
}

/// The operations an AWS call names: its `Action` parameters, in the query and in a form body in
/// any case, and its `X-Amz-Target` headers.
fn aws_operations(request: &HookRequest) -> Vec<String> {
    let body = request.body.as_deref().unwrap_or_default();
    let targets = request
        .headers
        .get_all("x-amz-target")
        .iter()
        .map(|value| String::from_utf8_lossy(value.as_bytes()).into_owned());
    request
        .url
        .query_pairs()
        .chain(form_urlencoded::parse(body.as_bytes()))
        .filter(|(name, _)| name.eq_ignore_ascii_case("action"))
        .map(|(_, value)| value.into_owned())
        .chain(targets)
        .collect()
}

/// The names of a URL's query parameters, each as often as it appears.
fn query_names(request: &HookRequest) -> Vec<String> {
    let mut names: Vec<String> = request
        .url
        .query_pairs()
        .map(|(name, _)| name.into_owned())
        .collect();
    names.sort();
    names
}

/// Hosts of the cloud registries a deployment's images can be pulled from with Alien's grants:
/// Amazon ECR in every endpoint form (IPv4, dual-stack, FIPS), Artifact Registry and its `gcr.io`
/// hosts, and Azure Container Registry.
const CLOUD_REGISTRIES: [&str; 5] = [".dkr.ecr", ".dkr-ecr", "pkg.dev", "gcr.io", ".azurecr."];

/// Every reference to an image in a cloud registry that `request` names, lowercase, wherever it
/// sits: in the query or the body, in any field, raw and percent-decoded. Alien sets up the
/// grants a deployment pulls those images with, so an interceptor may not add or change one.
fn registry_images(request: &HookRequest) -> BTreeSet<String> {
    let body = request.body.as_deref().unwrap_or_default();
    // A changed JSON body is checked as it is sent, written out again, so a host written with a
    // `\u` escape is read as the cloud reads it.
    let texts = [
        body.to_string(),
        decoded(body),
        decoded(request.url.query().unwrap_or_default()),
    ];
    texts
        .iter()
        .flat_map(|text| {
            text.split(|c: char| !(c.is_alphanumeric() || "@._:/+-~%".contains(c)))
                .map(|token| token.to_lowercase())
                .collect::<Vec<_>>()
        })
        // A reference spelled with a character outside ASCII counts too, whatever it may fold to.
        .filter(|token| {
            CLOUD_REGISTRIES.iter().any(|host| token.contains(host))
                || (!token.is_ascii() && token.contains('.') && token.contains('/'))
        })
        .collect()
}

/// Whether an AWS body sets a resource policy: a `Policy` field (KMS, EventBridge), a
/// `ResourcePolicy` field (DynamoDB), a `Policy` attribute (SQS, SNS) in JSON, or one named in a
/// form.
fn sets_a_policy(body: &str) -> bool {
    if let Ok(serde_json::Value::Object(fields)) = serde_json::from_str(body) {
        return fields.iter().any(|(key, field)| {
            key.eq_ignore_ascii_case("Policy")
                || key.eq_ignore_ascii_case("ResourcePolicy")
                || (key.eq_ignore_ascii_case("Attributes")
                    && field.as_object().is_some_and(|attributes| {
                        attributes
                            .keys()
                            .any(|name| name.eq_ignore_ascii_case("Policy"))
                    }))
        });
    }
    form_sets_a_policy(body)
}

/// Whether an API Gateway body writes the API's resource policy: a `policy` field, an OpenAPI
/// document's `x-amazon-apigateway-policy`, or a patch to `/policy`, at any depth and in any
/// case.
fn sets_an_api_policy(body: &str) -> bool {
    fn writes(value: &serde_json::Value) -> bool {
        match value {
            serde_json::Value::Object(fields) => fields.iter().any(|(key, field)| {
                matches!(
                    key.to_ascii_lowercase().as_str(),
                    "policy" | "x-amazon-apigateway-policy"
                ) || ((key.eq_ignore_ascii_case("path") || key.eq_ignore_ascii_case("from"))
                    && field
                        .as_str()
                        .is_some_and(|path| path.to_ascii_lowercase().starts_with("/policy")))
                    || writes(field)
            }),
            serde_json::Value::Array(items) => items.iter().any(writes),
            _ => false,
        }
    }
    match serde_json::from_str::<serde_json::Value>(body) {
        Ok(value) => writes(&value),
        // An OpenAPI document may be YAML.
        Err(_) => body.to_ascii_lowercase().contains("policy"),
    }
}

/// Whether a form, in a body or a URL's query, names a `Policy` field or attribute.
fn form_sets_a_policy(form: &str) -> bool {
    form_urlencoded::parse(form.as_bytes()).any(|(name, value)| {
        let name = name.to_ascii_lowercase();
        name == "policy"
            || (value.eq_ignore_ascii_case("Policy")
                && (name.ends_with("name") || name.ends_with(".key")))
    })
}

/// Rewrites the headers that describe the body, when the request carries them, so a signature
/// never covers a digest of a body that is no longer sent.
fn rewrite_body_digests(headers: &mut HeaderMap, body: &[u8]) -> Result<()> {
    if headers.contains_key(CONTENT_LENGTH) {
        headers.insert(CONTENT_LENGTH, HeaderValue::from(body.len()));
    }
    let sha256 = format!("{:x}", Sha256::digest(body));
    let md5 = base64::engine::general_purpose::STANDARD.encode(md5::compute(body).0);
    for (name, digest) in [("x-amz-content-sha256", sha256), ("content-md5", md5)] {
        if headers.contains_key(name) {
            let value = HeaderValue::try_from(digest).into_alien_error().context(
                ErrorData::GenericError {
                    message: format!("Failed to write the '{name}' header"),
                },
            )?;
            headers.insert(name, value);
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::TestInterceptor;
    use std::sync::Mutex;

    fn chain(interceptors: Vec<TestInterceptor>) -> InterceptorChain {
        InterceptorChain::new(
            interceptors
                .into_iter()
                .map(|interceptor| Arc::new(interceptor) as Arc<dyn CallInterceptor>)
                .collect(),
        )
    }

    fn rds_request(body: &str) -> reqwest::Request {
        reqwest::Client::new()
            .post("https://rds.us-east-1.amazonaws.com/")
            .header("content-type", "application/x-www-form-urlencoded")
            .header("content-length", body.len())
            .header(
                "x-amz-content-sha256",
                format!("{:x}", Sha256::digest(body)),
            )
            .header("content-md5", "stale")
            .body(body.to_string())
            .build()
            .unwrap()
    }

    fn body_text(request: &reqwest::Request) -> String {
        String::from_utf8(request.body().unwrap().as_bytes().unwrap().to_vec()).unwrap()
    }

    fn assert_fails_naming(error: AlienError<ErrorData>, extension: &str) {
        assert_eq!(error.code, "INTERCEPTOR_FAILED", "{error}");
        assert!(
            !error.retryable,
            "an interceptor failure is not retried unless the interceptor says it may pass"
        );
        assert!(
            matches!(&error.error, Some(ErrorData::InterceptorFailed { extension: name, .. }) if name == extension),
            "{error}"
        );
    }

    #[test]
    fn a_call_no_interceptor_matches_is_left_as_it_was() {
        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "s3")
            .on_request(|_| panic!("an S3 interceptor never sees an RDS call"))]);
        let mut request = reqwest::Client::new()
            .put("https://bucket.s3.amazonaws.com/object")
            .body(vec![0xff, 0xfe, 0x00])
            .build()
            .unwrap();
        let before = format!("{request:?}");
        assert!(interceptors
            .intercept(Cloud::Aws, "rds", &mut request)
            .unwrap()
            .is_none());
        assert_eq!(format!("{request:?}"), before);
        assert_eq!(
            request.body().unwrap().as_bytes(),
            Some(&[0xff, 0xfe, 0x00][..])
        );
    }

    /// An interceptor that can't say whether it sees a call, as a hook that traps or runs out of
    /// time can't.
    struct CannotMatch;

    impl CallInterceptor for CannotMatch {
        fn extension(&self) -> &str {
            "acme"
        }

        fn matches(&self, _request: &HookRequest) -> Result<bool> {
            Err(AlienError::new(ErrorData::GenericError {
                message: "the hook ran out of time".to_string(),
            }))
        }

        fn modify_request(&self, _request: &mut HookRequest) -> Result<()> {
            panic!("a call the interceptor did not match is never offered to it")
        }

        fn modify_response(&self, _: &HookRequest, _: &mut HookResponse) -> Result<()> {
            panic!("a call the interceptor did not match is never offered to it")
        }
    }

    #[test]
    fn an_interceptor_that_cannot_answer_matches_fails_the_call() {
        let interceptors = InterceptorChain::new(vec![Arc::new(CannotMatch)]);
        let mut text = rds_request("Action=CreateDBCluster");
        let error = interceptors
            .intercept(Cloud::Aws, "rds", &mut text)
            .unwrap_err();
        assert_fails_naming(error, "acme");
        assert_eq!(body_text(&text), "Action=CreateDBCluster");

        let mut binary = reqwest::Client::new()
            .put("https://bucket.s3.amazonaws.com/object")
            .body(vec![0xff, 0xfe, 0x00])
            .build()
            .unwrap();
        let error = interceptors
            .intercept(Cloud::Aws, "s3", &mut binary)
            .unwrap_err();
        assert_fails_naming(error, "acme");
    }

    #[test]
    fn a_change_of_destination_or_credentials_is_refused() {
        let cases: Vec<(&str, fn(&mut HookRequest))> = vec![
            ("another host", |r| {
                r.url.set_host(Some("evil.example.com")).unwrap()
            }),
            ("another port", |r| r.url.set_port(Some(8443)).unwrap()),
            ("another scheme", |r| r.url.set_scheme("http").unwrap()),
            ("a Host header", |r| {
                r.headers
                    .insert("host", HeaderValue::from_static("evil.example.com"));
            }),
            ("an Authorization header", |r| {
                r.headers
                    .insert("authorization", HeaderValue::from_static("Bearer forged"));
            }),
            ("a session token", |r| {
                r.headers
                    .insert("x-amz-security-token", HeaderValue::from_static("stolen"));
            }),
            ("a signing date", |r| {
                r.headers
                    .insert("x-amz-date", HeaderValue::from_static("20000101T000000Z"));
            }),
            ("the signing service", |r| r.service = "ec2".to_string()),
            ("the cloud", |r| r.cloud = Cloud::Gcp),
        ];
        for (what, change) in cases {
            let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "rds")
                .on_request(move |r| {
                    change(r);
                    Ok(())
                })]);
            let mut request = rds_request("Action=CreateDBCluster");
            let error = interceptors
                .intercept(Cloud::Aws, "rds", &mut request)
                .expect_err(what);
            assert_fails_naming(error, "acme");
            assert_eq!(
                request.url().host_str(),
                Some("rds.us-east-1.amazonaws.com")
            );
        }
    }

    /// Headers that pick the project billed, the method the server runs or the object an S3 copy
    /// reads, add a credential, or set who the call acts as.
    #[test]
    fn a_header_that_picks_the_project_or_identity_is_refused() {
        use reqwest::header::HeaderName;

        let cases = [
            (
                Cloud::Gcp,
                "cloudsql",
                "https://sqladmin.googleapis.com/v1/projects/p/instances",
                "x-goog-user-project",
            ),
            (
                Cloud::Gcp,
                "cloudsql",
                "https://sqladmin.googleapis.com/v1/projects/p/instances",
                "x-goog-api-key",
            ),
            (
                Cloud::Azure,
                "management",
                "https://management.azure.com/subscriptions/sub",
                "x-ms-authorization-auxiliary",
            ),
            (
                Cloud::Gcp,
                "cloudsql",
                "https://sqladmin.googleapis.com/v1/projects/p/instances",
                "X-HTTP-Method-Override",
            ),
            (
                Cloud::Azure,
                "management",
                "https://management.azure.com/subscriptions/sub",
                "X-HTTP-Method",
            ),
            (
                Cloud::Kubernetes,
                "kubernetes",
                "https://cluster.local/api/v1/namespaces/ns/pods",
                "Impersonate-User",
            ),
            (
                Cloud::Kubernetes,
                "kubernetes",
                "https://cluster.local/api/v1/namespaces/ns/pods",
                "Impersonate-Extra-Scopes",
            ),
            (
                Cloud::Aws,
                "s3",
                "https://bucket.s3.amazonaws.com/copy",
                "x-amz-copy-source",
            ),
        ];
        for (cloud, service, url, name) in cases {
            let header = HeaderName::from_bytes(name.as_bytes()).unwrap();
            for already_sent in [false, true] {
                let set = header.clone();
                let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
                    .on_request(move |r| {
                        r.headers
                            .insert(set.clone(), HeaderValue::from_static("other"));
                        Ok(())
                    })]);
                let mut request = reqwest::Client::new().get(url);
                if already_sent {
                    request = request.header(header.clone(), "original");
                }
                let mut request = request.build().unwrap();
                let error = interceptors
                    .intercept(cloud, service, &mut request)
                    .expect_err(name);
                assert_fails_naming(error, "acme");
                assert_eq!(
                    request.headers().get(&header).is_some(),
                    already_sent,
                    "{name}"
                );
            }
        }
    }

    /// Google Cloud reads the project billed, an API key, a credential and the body's or
    /// response's format from these parameters, in any case.
    #[test]
    fn a_query_parameter_that_picks_the_project_billed_or_an_api_key_is_refused() {
        let url = "https://storage.googleapis.com/storage/v1/b/bucket/o?userProject=the-project";
        for (what, change) in [
            ("added", "userProject=the-project&userProject=other"),
            ("changed", "userProject=other"),
            ("removed", "prefix=a"),
            (
                "added in another case",
                "userProject=the-project&USERPROJECT=other",
            ),
            (
                "added with a $",
                "userProject=the-project&%24userProject=other",
            ),
            ("an API key", "userProject=the-project&key=other"),
            ("an API key with a $", "userProject=the-project&$Key=other"),
            (
                "an access token",
                "userProject=the-project&access_token=other",
            ),
            (
                "an OAuth token",
                "userProject=the-project&oauth_token=other",
            ),
            (
                "a bearer token",
                "userProject=the-project&bearer_token=other",
            ),
            ("a response format", "userProject=the-project&alt=media"),
            (
                "a content type for the body",
                "userProject=the-project&%24ct=application%2Fjson%2Bprotobuf",
            ),
            (
                "another system parameter",
                "userProject=the-project&$Fields=name",
            ),
        ] {
            let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Gcp, "storage")
                .on_request(move |r| {
                    r.url.set_query(Some(change));
                    Ok(())
                })]);
            let mut request = reqwest::Client::new().get(url).build().unwrap();
            let error = interceptors
                .intercept(Cloud::Gcp, "storage", &mut request)
                .expect_err(what);
            assert_fails_naming(error, "acme");
            assert_eq!(request.url().as_str(), url, "{what}");
        }

        // Every other parameter can change, as can these on another cloud's call.
        for (cloud, service, url, query) in [
            (
                Cloud::Gcp,
                "storage",
                url,
                "prefix=a&userProject=the-project",
            ),
            (
                Cloud::Aws,
                "rds",
                "https://rds.us-east-1.amazonaws.com/?key=x&userProject=y",
                "key=a&userProject=b",
            ),
        ] {
            let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
                .on_request(move |r| {
                    r.url.set_query(Some(query));
                    Ok(())
                })]);
            let mut request = reqwest::Client::new().get(url).build().unwrap();
            interceptors
                .intercept(cloud, service, &mut request)
                .unwrap()
                .expect("the interceptor matched");
            assert_eq!(request.url().query(), Some(query));
        }
    }

    #[test]
    fn a_query_value_and_other_headers_can_change() {
        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "rds")
            .on_request(|r| {
                r.url.set_query(Some("extension=1"));
                r.headers
                    .insert("x-extension", HeaderValue::from_static("acme"));
                Ok(())
            })]);
        let mut request = rds_request("Action=CreateDBCluster");
        request.url_mut().set_query(Some("extension=0"));
        interceptors
            .intercept(Cloud::Aws, "rds", &mut request)
            .unwrap()
            .expect("the interceptor matched");
        assert_eq!(
            request.url().as_str(),
            "https://rds.us-east-1.amazonaws.com/?extension=1"
        );
        assert_eq!(request.method(), Method::POST);
        assert_eq!(request.headers()["x-extension"], "acme");
        assert_eq!(body_text(&request), "Action=CreateDBCluster");
    }

    /// A request `(cloud, service, method, url, headers, body)` as Alien builds it.
    type Built = (
        Cloud,
        &'static str,
        Method,
        &'static str,
        &'static [(&'static str, &'static str)],
        Option<&'static str>,
    );

    fn build((_, _, method, url, headers, body): &Built) -> reqwest::Request {
        let mut builder = reqwest::Client::new().request(method.clone(), *url);
        for (name, value) in *headers {
            builder = builder.header(*name, *value);
        }
        if let Some(body) = body {
            builder = builder.body(*body);
        }
        builder.build().unwrap()
    }

    /// Runs `change` on `built` and expects the chain to refuse it before anything is sent.
    fn assert_change_refused(what: &str, built: Built, change: fn(&mut HookRequest)) {
        assert_change_refused_because(what, built, "", change)
    }

    /// Like `assert_change_refused`, and the refusal's reason must contain `reason`.
    fn assert_change_refused_because(
        what: &str,
        built: Built,
        reason: &str,
        change: fn(&mut HookRequest),
    ) {
        let (cloud, service) = (built.0, built.1);
        let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
            .on_request(move |r| {
                change(r);
                Ok(())
            })]);
        let mut request = build(&built);
        let before = format!("{request:?}");
        let error = interceptors
            .intercept(cloud, service, &mut request)
            .expect_err(what);
        assert_fails_naming(error.clone(), "acme");
        assert!(
            matches!(&error.error, Some(ErrorData::InterceptorFailed { message, .. }) if message.contains(reason)),
            "{what}: the reason should contain {reason:?}: {error}"
        );
        assert_eq!(format!("{request:?}"), before, "{what}");
    }

    const CLOUD_RUN_SERVICE: Built = (
        Cloud::Gcp,
        "cloudrun",
        Method::PATCH,
        "https://run.googleapis.com/v2/projects/p/locations/l/services/web",
        &[("content-type", "application/json")],
        Some(r#"{"labels":{"team":"a"}}"#),
    );

    /// An image in a cloud registry stays as Alien named it, however the change names one; an
    /// image from a public registry may be added.
    #[test]
    fn an_image_in_a_cloud_registry_is_never_added_or_changed() {
        const FUNCTION: Built = (
            Cloud::Aws,
            "lambda",
            Method::POST,
            "https://lambda.us-east-1.amazonaws.com/2015-03-31/functions",
            &[("content-type", "application/json")],
            Some(
                r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr.ecr.us-east-1.amazonaws.com/artifacts-a@sha256:00"}}"#,
            ),
        );
        const SERVICE: Built = (
            Cloud::Gcp,
            "run",
            Method::POST,
            "https://run.googleapis.com/v2/projects/p/locations/l/services",
            &[("content-type", "application/json")],
            Some(
                r#"{"template":{"containers":[{"image":"us-docker.pkg.dev/m/artifacts-a/web:1"}]}}"#,
            ),
        );
        const TEMPLATE: Built = (
            Cloud::Gcp,
            "aiplatform",
            Method::POST,
            "https://us-central1-aiplatform.googleapis.com/v1beta1/projects/p/locations/l/templates",
            &[("content-type", "application/json")],
            Some(r#"{"spec":{"imageUri":"docker.io/library/python:3.12"}}"#),
        );
        const SETTINGS: Built = (
            Cloud::Aws,
            "ssm",
            Method::POST,
            "https://ssm.us-east-1.amazonaws.com/",
            &[
                ("content-type", "application/x-amz-json-1.1"),
                ("x-amz-target", "AmazonSSM.PutParameter"),
            ],
            Some(r#"{"value":"REGISTRY=1.dkr.ecr.us-east-1.amazonaws.com/r:1,TAG=1"}"#),
        );
        let refused: [(&str, Built, fn(&mut HookRequest)); 11] = [
            (
                "a registry host with a character outside ASCII",
                FUNCTION,
                |r| {
                    r.body = Some(
                    "{\"FunctionName\":\"f\",\"Code\":{\"ImageUri\":\"1.d\u{212a}r.ecr.us-east-1.amazonaws.com/artifacts-b:1\"}}"
                        .into(),
                )
                },
            ),
            ("a FIPS registry host", FUNCTION, |r| {
                r.body = Some(
                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr.ecr-fips.us-east-1.amazonaws.com/artifacts-b:1"}}"#
                        .into(),
                )
            }),
            ("a dual-stack FIPS registry host", FUNCTION, |r| {
                r.body = Some(
                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr-ecr-fips.us-east-1.on.aws/artifacts-b:1"}}"#
                        .into(),
                )
            }),
            ("a gcr.io host", SERVICE, |r| {
                r.body = Some(
                    r#"{"template":{"containers":[{"image":"us-docker.pkg.dev/m/artifacts-a/web:1"},{"image":"us.gcr.io/m/artifacts-b:1"}]}}"#
                        .into(),
                )
            }),
            ("a regional Artifact Registry host", SERVICE, |r| {
                r.body = Some(
                    r#"{"template":{"containers":[{"image":"docker.us-east1.rep.pkg.dev/m/artifacts-b/web:1"}]}}"#
                        .into(),
                )
            }),
            ("another repository", FUNCTION, |r| {
                r.body = Some(
                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr.ecr.us-east-1.amazonaws.com/artifacts-b:latest"}}"#
                        .into(),
                )
            }),
            ("another tag of the same repository", FUNCTION, |r| {
                r.body = Some(
                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr.ecr.us-east-1.amazonaws.com/artifacts-a:v2"}}"#
                        .into(),
                )
            }),
            (
                "the registry host in another case and with a port",
                FUNCTION,
                |r| {
                    r.body = Some(
                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.DKR.ECR.us-east-1.amazonaws.com:443/artifacts-b:1"}}"#
                        .into(),
                )
                },
            ),
            ("a second container from the same registry", SERVICE, |r| {
                r.body = Some(
                    r#"{"template":{"containers":[{"image":"us-docker.pkg.dev/m/artifacts-a/web:1"},{"image":"us-docker.pkg.dev/m/artifacts-b/web:1"}]}}"#
                        .into(),
                )
            }),
            (
                "a cloud registry's image in a field of another name",
                TEMPLATE,
                |r| {
                    r.body = Some(
                    r#"{"spec":{"image_uri":"us-central1-docker.pkg.dev/m/artifacts-b/sandbox:1"}}"#
                        .into(),
                )
                },
            ),
            (
                "a cloud registry's image where the call named a public one",
                TEMPLATE,
                |r| {
                    r.body = Some(
                    r#"{"spec":{"imageUri":"us-central1-docker.pkg.dev/m/artifacts-b/sandbox:1"}}"#
                        .into(),
                )
                },
            ),
        ];
        for (what, built, change) in refused {
            assert_change_refused(what, built, change);
        }
        let sent: [(&str, Built, fn(&mut HookRequest)); 3] = [
            ("a setting beside an image in one string", SETTINGS, |r| {
                r.body = Some(
                    r#"{"value":"REGISTRY=1.dkr.ecr.us-east-1.amazonaws.com/r:1,TAG=2"}"#.into(),
                )
            }),
            ("another field beside the image", FUNCTION, |r| {
                r.body = Some(
                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr.ecr.us-east-1.amazonaws.com/artifacts-a@sha256:00"},"Description":"d"}"#
                        .into(),
                )
            }),
            ("a sidecar from a public registry", SERVICE, |r| {
                r.body = Some(
                    r#"{"template":{"containers":[{"image":"us-docker.pkg.dev/m/artifacts-a/web:1"},{"image":"ghcr.io/vendor/agent:1"}]}}"#
                        .into(),
                )
            }),
        ];
        for (what, built, change) in sent {
            assert_change_sent(what, built, change);
        }
    }

    /// The method and the path say which resource a call acts on and what it does to it.
    #[test]
    fn a_change_of_method_or_path_is_refused() {
        let cases: [(&str, fn(&mut HookRequest)); 4] = [
            ("another method", |r| r.method = Method::DELETE),
            ("a sibling service", |r| {
                r.url
                    .set_path("/v2/projects/p/locations/l/services/billing")
            }),
            ("a trailing slash", |r| {
                r.url.set_path("/v2/projects/p/locations/l/services/web/")
            }),
            ("another project", |r| {
                r.url.set_path("/v2/projects/q/locations/l/services/web")
            }),
        ];
        for (what, change) in cases {
            assert_change_refused(what, CLOUD_RUN_SERVICE, change);
        }
    }

    /// Which identity a call names decides who the resource acts as, wherever the name sits.
    #[test]
    fn a_change_to_the_identity_a_call_names_is_refused() {
        const LAMBDA: Built = (
            Cloud::Aws,
            "lambda",
            Method::PUT,
            "https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/fn/configuration",
            &[("content-type", "application/json")],
            Some(r#"{"Role":"arn:aws:iam::111111111111:role/app-fn","Timeout":30}"#),
        );
        const APP: Built = (
            Cloud::Azure,
            "management",
            Method::PUT,
            "https://management.azure.com/subscriptions/s/resourceGroups/rg/providers/Microsoft.App/containerApps/web",
            &[("content-type", "application/json")],
            Some(r#"{"location":"eastus"}"#),
        );
        let cases: [(&str, Built, fn(&mut HookRequest)); 8] = [
            ("a body that is no longer JSON", LAMBDA, |r| {
                r.body = Some("Role: arn:aws:iam::111111111111:role/admin\n".into())
            }),
            ("a body no JSON parser reads alike", LAMBDA, |r| {
                r.body = Some(
                    r#"{"Description":"\ud800","Role":"arn:aws:iam::111111111111:role/admin","Timeout":30}"#
                        .into(),
                )
            }),
            ("another content type", LAMBDA, |r| {
                r.headers
                    .insert("content-type", HeaderValue::from_static("application/yaml"));
            }),
            ("an escaped role", LAMBDA, |r| {
                r.body = Some(
                    r#"{"Role":"\u0061rn:aws:iam::111111111111:role/admin","Description":"arn:aws:iam::111111111111:role/app-fn","Timeout":30}"#
                        .into(),
                )
            }),
            ("another service account", CLOUD_RUN_SERVICE, |r| {
                r.body = Some(
                    r#"{"labels":{"team":"a"},"template":{"serviceAccount":"other@p.iam.gserviceaccount.com"}}"#
                        .into(),
                )
            }),
            ("another role", LAMBDA, |r| {
                r.body =
                    Some(r#"{"Role":"arn:aws:iam::111111111111:role/admin","Timeout":30}"#.into())
            }),
            ("no role", LAMBDA, |r| {
                r.body = Some(r#"{"Timeout":30}"#.into())
            }),
            ("a managed identity added", APP, |r| {
                r.body = Some(
                    r#"{"location":"eastus","identity":{"type":"UserAssigned","userAssignedIdentities":{"/subscriptions/s/resourceGroups/other/providers/Microsoft.ManagedIdentity/userAssignedIdentities/admin":{}}}}"#
                        .into(),
                )
            }),
        ];
        for (what, built, change) in cases {
            assert_change_refused(what, built, change);
        }
    }

    const LAUNCH_TEMPLATE: Built = (
        Cloud::Aws,
        "ec2",
        Method::POST,
        "https://ec2.us-east-1.amazonaws.com/",
        &[("content-type", "application/x-www-form-urlencoded")],
        Some("Action=CreateLaunchTemplate&LaunchTemplateName=web&LaunchTemplateData.IamInstanceProfile.Arn=arn%3Aaws%3Aiam%3A%3A111111111111%3Ainstance-profile%2Fweb&LaunchTemplateData.IamInstanceProfile.Name=web"),
    );

    const CLOUD_RUN_AS_APP: Built = (
        Cloud::Gcp,
        "cloudrun",
        Method::PATCH,
        "https://run.googleapis.com/v2/projects/p/locations/l/services/web",
        &[("content-type", "application/json")],
        Some(
            r#"{"labels":{"team":"a"},"template":{"serviceAccount":"app@p.iam.gserviceaccount.com"}}"#,
        ),
    );

    const INSTANCE_AS_APP: Built = (
        Cloud::Gcp,
        "compute",
        Method::POST,
        "https://compute.googleapis.com/compute/v1/projects/p/zones/z/instances",
        &[("content-type", "application/json")],
        Some(
            r#"{"name":"web","description":"","serviceAccounts":[{"email":"app@p.iam.gserviceaccount.com","scopes":[]}]}"#,
        ),
    );

    /// An identity is compared where it sits: a form value is read by its key, and a name moved
    /// to another field no longer names the identity the call acts as.
    #[test]
    fn an_identity_is_compared_where_the_call_names_it() {
        let cases: [(&str, Built, fn(&mut HookRequest)); 5] = [
            (
                "another instance profile ARN in a form",
                LAUNCH_TEMPLATE,
                |r| {
                    r.body = Some(
                        LAUNCH_TEMPLATE
                            .5
                            .unwrap()
                            .replace("profile%2Fweb", "profile%2Fadmin"),
                    )
                },
            ),
            (
                "another instance profile name in a form",
                LAUNCH_TEMPLATE,
                |r| {
                    r.body = Some(
                        LAUNCH_TEMPLATE
                            .5
                            .unwrap()
                            .replace("Profile.Name=web", "Profile.Name=admin"),
                    )
                },
            ),
            (
                "an instance profile ARN in the query",
                LAUNCH_TEMPLATE,
                |r| {
                    r.url
                        .set_query(Some("RoleArn=arn:aws:iam::111111111111:role/admin"))
                },
            ),
            (
                "a service account dropped and kept in a label",
                CLOUD_RUN_AS_APP,
                |r| {
                    r.body = Some(
                    r#"{"labels":{"team":"a","sa":"app@p.iam.gserviceaccount.com"},"template":{}}"#
                        .into(),
                )
                },
            ),
            (
                "a service account replaced and kept in the description",
                INSTANCE_AS_APP,
                |r| {
                    r.body = Some(
                    r#"{"name":"web","description":"app@p.iam.gserviceaccount.com","serviceAccounts":[{"email":"default","scopes":[]}]}"#
                        .into(),
                )
                },
            ),
        ];
        for (what, built, change) in cases {
            assert_change_refused(what, built, change);
        }
    }

    /// Runs `change` on `built` and expects the chain to send the changed call.
    fn assert_change_sent(what: &str, built: Built, change: fn(&mut HookRequest)) {
        let (cloud, service) = (built.0, built.1);
        let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
            .on_request(move |r| {
                change(r);
                Ok(())
            })]);
        let mut request = build(&built);
        interceptors
            .intercept(cloud, service, &mut request)
            .unwrap_or_else(|error| panic!("{what}: {error}"))
            .expect("the interceptor matched");
        assert_ne!(Some(body_text(&request).as_str()), built.5, "{what}");
    }

    #[test]
    fn a_change_that_keeps_every_identity_where_it_was_is_sent() {
        const APP_AS_APP: Built = (
            Cloud::Azure,
            "management",
            Method::PUT,
            "https://management.azure.com/subscriptions/s/resourceGroups/rg/providers/Microsoft.App/containerApps/web",
            &[("content-type", "application/json")],
            Some(r#"{"location":"eastus","identity":{"type":"UserAssigned","userAssignedIdentities":{"/subscriptions/s/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/app":{}}}}"#),
        );
        let cases: [(&str, Built, fn(&mut HookRequest)); 4] = [
            (
                "a tag on a container app, its identity's keys written in another order",
                APP_AS_APP,
                |r| {
                    r.body = Some(
                    r#"{"tags":{"team":"a"},"identity":{"userAssignedIdentities":{"/subscriptions/s/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/app":{}},"type":"UserAssigned"},"location":"eastus"}"#
                        .into(),
                )
                },
            ),
            ("a tag on a launch template", LAUNCH_TEMPLATE, |r| {
                r.body.as_mut().unwrap().push_str(
                    "&TagSpecification.1.ResourceType=launch-template&TagSpecification.1.Tag.1.Key=team&TagSpecification.1.Tag.1.Value=a",
                )
            }),
            ("a label on a Cloud Run service", CLOUD_RUN_AS_APP, |r| {
                r.body = Some(
                    r#"{"labels":{"team":"b"},"template":{"serviceAccount":"app@p.iam.gserviceaccount.com"}}"#
                        .into(),
                )
            }),
            ("a description on an instance", INSTANCE_AS_APP, |r| {
                r.body = Some(
                    r#"{"name":"web","description":"web tier","serviceAccounts":[{"email":"app@p.iam.gserviceaccount.com","scopes":[]}]}"#
                        .into(),
                )
            }),
        ];
        for (what, built, change) in cases {
            assert_change_sent(what, built, change);
        }
    }

    const DEPLOYMENT: Built = (
        Cloud::Kubernetes,
        "kubernetes",
        Method::POST,
        "https://cluster.example.com/apis/apps/v1/namespaces/app/deployments",
        &[("content-type", "application/json")],
        Some(
            r#"{"metadata":{"name":"web","labels":{"alien.dev/deployment":"d1"}},"spec":{"template":{"spec":{"containers":[{"name":"main","image":"web","securityContext":{"runAsNonRoot":true}}],"volumes":[{"name":"data","emptyDir":{}}]}}}}"#,
        ),
    );

    /// On Kubernetes an interceptor adds or changes the object's labels, and nothing else: the
    /// cluster's shared parts (ingress hosts, runtime classes, nodes) read the rest.
    #[test]
    fn a_kubernetes_interceptor_changes_only_the_object_s_labels() {
        assert_change_sent("a label", DEPLOYMENT, |r| {
            let mut value: serde_json::Value =
                serde_json::from_str(r.body.as_deref().unwrap()).unwrap();
            value["metadata"]["labels"]["team"] = "a".into();
            value["metadata"]["labels"]["role"] = "frontend".into();
            r.body = Some(value.to_string());
        });
        fn edit(r: &mut HookRequest, change: fn(&mut serde_json::Value)) {
            let mut value: serde_json::Value =
                serde_json::from_str(r.body.as_deref().unwrap()).unwrap();
            change(&mut value);
            r.body = Some(value.to_string());
        }
        let cases: [(&str, fn(&mut HookRequest)); 12] = [
            ("a sidecar", |r| {
                edit(r, |object| {
                    object["spec"]["template"]["spec"]["containers"]
                        .as_array_mut()
                        .unwrap()
                        .insert(0, serde_json::json!({"name":"agent","image":"agent"}))
                })
            }),
            ("an annotation", |r| {
                edit(
                    r,
                    |object| {
                        object["metadata"]["annotations"] =
                            serde_json::json!({"nginx.ingress.kubernetes.io/server-snippet": "x"})
                    },
                )
            }),
            ("a runtime class", |r| {
                edit(r, |object| {
                    object["spec"]["template"]["spec"]["runtimeClassName"] = "runc".into()
                })
            }),
            ("a label with a prefix", |r| {
                edit(r, |object| {
                    object["metadata"]["labels"]["alien.dev/resource"] = "other".into()
                })
            }),
            ("a label Alien set, changed", |r| {
                edit(r, |object| {
                    object["metadata"]["labels"]["alien.dev/deployment"] = "d2".into()
                })
            }),
            ("a label Alien set, removed", |r| {
                edit(r, |object| {
                    object["metadata"]["labels"] = serde_json::json!({})
                })
            }),
            ("a managed-by label", |r| {
                edit(r, |object| {
                    object["metadata"]["labels"]["managed-by"] = "acme".into()
                })
            }),
            ("a header", |r| {
                r.headers
                    .insert("x-extension", HeaderValue::from_static("acme"));
            }),
            ("another method", |r| r.method = Method::PUT),
            ("a label that is not text", |r| {
                edit(r, |object| {
                    object["metadata"]["labels"] = serde_json::json!({"a": 1})
                })
            }),
            ("a label on the pod template", |r| {
                edit(r, |object| {
                    object["spec"]["template"]["metadata"] =
                        serde_json::json!({"labels": {"a": "b"}})
                })
            }),
            ("a query parameter", |r| r.url.set_query(Some("dryRun=All"))),
        ];
        for (what, change) in cases {
            assert_change_refused(what, DEPLOYMENT, change);
        }
    }

    /// Each check reads the body as its protocol reads it, so a body may not change format: a
    /// form body turned into a JSON string would be checked as a form and sent decoded.
    #[test]
    fn a_body_that_changes_format_is_refused_saying_so() {
        const SQS: Built = (
            Cloud::Aws,
            "sqs",
            Method::POST,
            "https://sqs.us-east-1.amazonaws.com/",
            &[("content-type", "application/x-www-form-urlencoded")],
            Some("Action=CreateQueue&Version=2012-11-05&QueueName=q"),
        );
        const APP: Built = (
            Cloud::Azure,
            "management",
            Method::PUT,
            "https://management.azure.com/subscriptions/s/resourceGroups/rg/providers/Microsoft.App/containerApps/web",
            &[("content-type", "application/json")],
            Some(r#"{"location":"eastus"}"#),
        );
        const BODYLESS_SQS: Built = (
            Cloud::Aws,
            "sqs",
            Method::POST,
            "https://sqs.us-east-1.amazonaws.com/",
            &[("content-type", "application/x-www-form-urlencoded")],
            None,
        );
        let cases: [(&str, Built, fn(&mut HookRequest), &str); 5] = [
            (
                "an escaped form added to a call with no body",
                BODYLESS_SQS,
                |r| r.body = Some(r#""x\u0026Action\u003dAddPermission\u0026Label\u003dl""#.into()),
                "changes who has access",
            ),
            (
                "a policy as a form inside a JSON object added to a call with no body",
                BODYLESS_SQS,
                |r| {
                    r.body = Some(
                        r#"{"a":"x&Attribute.1.Name=Policy&Attribute.1.Value=%7B%7D&y="}"#.into(),
                    )
                },
                "added a body",
            ),
            (
                "an identity as a form inside a JSON string added to a call with no body",
                BODYLESS_SQS,
                |r| r.body = Some(r#""x&IamInstanceProfile.Name=admin&y=""#.into()),
                "added a body",
            ),
            (
                "a form body turned into a JSON string",
                SQS,
                |r| {
                    r.body = Some(
                        r#""Action=CreateQueue&Version=2012-11-05&QueueName=q&Attribute.1.Name\u003dPolicy""#
                            .into(),
                    )
                },
                "not JSON into JSON",
            ),
            (
                "a JSON body turned into text",
                APP,
                |r| r.body = Some("location: eastus\n".into()),
                "into one that is not JSON",
            ),
        ];
        for (what, built, change, reason) in cases {
            let (cloud, service) = (built.0, built.1);
            let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
                .on_request(move |r| {
                    change(r);
                    Ok(())
                })]);
            let mut request = build(&built);
            let error = interceptors
                .intercept(cloud, service, &mut request)
                .expect_err(what);
            assert!(!error.retryable, "{what}");
            assert!(format!("{error:?}").contains(reason), "{what}: {error:?}");
        }
    }

    /// The body sent is the one the checks read, so a key written twice can't carry a change
    /// a cloud's parser would merge in.
    #[test]
    fn a_json_body_is_sent_as_it_was_checked() {
        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Gcp, "cloudrun")
            .on_request(|r| {
                r.body = Some(r#"{"labels":{"team":"a"},"labels":{"team":"b"}}"#.to_string());
                Ok(())
            })]);
        let mut request = build(&CLOUD_RUN_SERVICE);
        interceptors
            .intercept(Cloud::Gcp, "cloudrun", &mut request)
            .unwrap()
            .expect("the interceptor matched");
        assert_eq!(body_text(&request), r#"{"labels":{"team":"b"}}"#);
    }

    /// On AWS's query and JSON protocols the operation is a body or query parameter, or a
    /// header, not the path.
    #[test]
    fn a_change_of_the_aws_operation_is_refused() {
        const RDS: Built = (
            Cloud::Aws,
            "rds",
            Method::POST,
            "https://rds.us-east-1.amazonaws.com/",
            &[("content-type", "application/x-www-form-urlencoded")],
            Some("Action=ModifyDBCluster&Version=2014-10-31&DBClusterIdentifier=db"),
        );
        const KMS: Built = (
            Cloud::Aws,
            "kms",
            Method::POST,
            "https://kms.us-east-1.amazonaws.com/",
            &[
                ("content-type", "application/x-amz-json-1.1"),
                ("x-amz-target", "TrentService.DescribeKey"),
            ],
            Some(r#"{"KeyId":"k"}"#),
        );
        const TAGGING: Built = (
            Cloud::Aws,
            "s3",
            Method::PUT,
            "https://bucket.s3.amazonaws.com/?tagging",
            &[("content-type", "application/xml")],
            Some("<Tagging><TagSet/></Tagging>"),
        );
        const CREATE_API: Built = (
            Cloud::Aws,
            "apigateway",
            Method::POST,
            "https://apigateway.us-east-1.amazonaws.com/restapis",
            &[("content-type", "application/json")],
            Some(r#"{"name":"api"}"#),
        );
        let cases: [(&str, Built, fn(&mut HookRequest)); 10] = [
            ("a query parameter added to a query API's call", RDS, |r| {
                r.url.set_query(Some("Tags.Tag.1.Key=a"))
            }),
            ("an API created by importing a document", CREATE_API, |r| {
                r.url.set_query(Some("mode=import"))
            }),
            ("another Action in the body", RDS, |r| {
                r.body = Some("Action=DeleteDBCluster&Version=2014-10-31".into())
            }),
            ("a second Action in the body", RDS, |r| {
                r.body.as_mut().unwrap().push_str("&Action=DeleteDBCluster")
            }),
            ("an Action in the query", RDS, |r| {
                r.url.set_query(Some("Action=DeleteDBCluster"))
            }),
            (
                "an S3 subresource that sends the bucket's logs elsewhere",
                TAGGING,
                |r| r.url.set_query(Some("logging")),
            ),
            (
                "an S3 subresource added beside the call's own",
                TAGGING,
                |r| r.url.set_query(Some("tagging&replication")),
            ),
            ("an S3 subresource removed", TAGGING, |r| {
                r.url.set_query(None)
            }),
            ("another target", KMS, |r| {
                r.headers.insert(
                    "x-amz-target",
                    HeaderValue::from_static("TrentService.ScheduleKeyDeletion"),
                );
            }),
            ("a form body on a JSON service", KMS, |r| {
                r.headers.remove("x-amz-target");
                r.body = Some("Action=ScheduleKeyDeletion&KeyId=k".into());
            }),
        ];
        for (what, built, change) in cases {
            assert_change_refused(what, built, change);
        }
    }

    /// A query parameter, a header or a body field can turn a call on the deployment's own
    /// resource into one that changes who has access to it.
    #[test]
    fn a_call_turned_into_one_that_changes_access_is_refused() {
        const CREATE_BUCKET: Built = (
            Cloud::Aws,
            "s3",
            Method::PUT,
            "https://bucket.s3.amazonaws.com/",
            &[],
            None,
        );
        const SQS_JSON: Built = (
            Cloud::Aws,
            "sqs",
            Method::POST,
            "https://sqs.us-east-1.amazonaws.com/",
            &[
                ("content-type", "application/x-amz-json-1.0"),
                ("x-amz-target", "AmazonSQS.SetQueueAttributes"),
            ],
            Some(r#"{"QueueUrl":"q","Attributes":{"VisibilityTimeout":"30"}}"#),
        );
        const SQS_QUERY: Built = (
            Cloud::Aws,
            "sqs",
            Method::POST,
            "https://sqs.us-east-1.amazonaws.com/",
            &[("content-type", "application/x-www-form-urlencoded")],
            Some(
                "Action=SetQueueAttributes&Attribute.1.Name=VisibilityTimeout&Attribute.1.Value=30",
            ),
        );
        const CREATE_KEY: Built = (
            Cloud::Aws,
            "kms",
            Method::POST,
            "https://kms.us-east-1.amazonaws.com/",
            &[
                ("content-type", "application/x-amz-json-1.1"),
                ("x-amz-target", "TrentService.CreateKey"),
            ],
            Some(r#"{"Description":"k"}"#),
        );
        const BUCKET_PATCH: Built = (
            Cloud::Gcp,
            "storage",
            Method::PATCH,
            "https://storage.googleapis.com/storage/v1/b/bucket",
            &[("content-type", "application/json")],
            Some(r#"{"labels":{"team":"a"}}"#),
        );
        const RESOURCE_GROUP: Built = (
            Cloud::Azure,
            "management",
            Method::PUT,
            "https://management.azure.com/subscriptions/s/resourcegroups/g",
            &[("content-type", "application/json")],
            Some(r#"{"location":"eastus"}"#),
        );
        const REST_API: Built = (
            Cloud::Aws,
            "apigateway",
            Method::POST,
            "https://apigateway.us-east-1.amazonaws.com/restapis",
            &[("content-type", "application/json")],
            Some(r#"{"name":"api","endpointConfiguration":{"types":["REGIONAL"]}}"#),
        );
        const REST_API_PATCH: Built = (
            Cloud::Aws,
            "apigateway",
            Method::PATCH,
            "https://apigateway.us-east-1.amazonaws.com/restapis/a1",
            &[("content-type", "application/json")],
            Some(r#"{"patchOperations":[{"op":"replace","path":"/description","value":"d"}]}"#),
        );
        const CREATE_TABLE: Built = (
            Cloud::Aws,
            "dynamodb",
            Method::POST,
            "https://dynamodb.us-east-1.amazonaws.com/",
            &[
                ("content-type", "application/x-amz-json-1.0"),
                ("x-amz-target", "DynamoDB_20120810.CreateTable"),
            ],
            Some(r#"{"TableName":"t"}"#),
        );
        let cases: [(&str, Built, fn(&mut HookRequest)); 20] = [
            (
                "a DynamoDB resource policy in another case",
                CREATE_TABLE,
                |r| r.body = Some(r#"{"TableName":"t","resourcePolicy":"{}"}"#.into()),
            ),
            (
                "an API Gateway policy moved away in a patch",
                REST_API_PATCH,
                |r| {
                    r.body = Some(
                    r#"{"patchOperations":[{"op":"move","from":"/policy","path":"/description"}]}"#
                        .into(),
                )
                },
            ),
            ("a DynamoDB resource policy", CREATE_TABLE, |r| {
                r.body = Some(r#"{"TableName":"t","ResourcePolicy":"{}"}"#.into())
            }),
            ("an API Gateway resource policy", REST_API, |r| {
                r.body = Some(r#"{"name":"api","policy":"{}"}"#.into())
            }),
            ("an API Gateway policy in a patch", REST_API_PATCH, |r| {
                r.body = Some(
                    r#"{"patchOperations":[{"op":"replace","path":"/policy","value":"{}"}]}"#
                        .into(),
                )
            }),
            (
                "an API Gateway policy in an OpenAPI document",
                REST_API,
                |r| {
                    r.body = Some(
                        r#"{"name":"api","body":{"x-amazon-apigateway-policy":{"Statement":[]}}}"#
                            .into(),
                    )
                },
            ),
            ("an S3 bucket policy", CREATE_BUCKET, |r| {
                r.url.set_query(Some("policy"));
                r.body = Some(r#"{"Statement":[]}"#.into());
            }),
            ("an S3 ACL", CREATE_BUCKET, |r| r.url.set_query(Some("acl"))),
            ("an S3 canned ACL header", CREATE_BUCKET, |r| {
                r.headers
                    .insert("x-amz-acl", HeaderValue::from_static("public-read"));
            }),
            ("an SQS queue policy in JSON", SQS_JSON, |r| {
                r.body = Some(
                    r#"{"QueueUrl":"q","Attributes":{"VisibilityTimeout":"30","Policy":"{}"}}"#
                        .into(),
                )
            }),
            (
                "an SQS queue policy in JSON, in another case",
                SQS_JSON,
                |r| r.body = Some(r#"{"QueueUrl":"q","attributes":{"policy":"{}"}}"#.into()),
            ),
            (
                "an SQS queue policy in a form, in another case",
                SQS_QUERY,
                |r| {
                    r.body
                        .as_mut()
                        .unwrap()
                        .push_str("&Attribute.2.name=policy&Attribute.2.Value=%7B%7D")
                },
            ),
            (
                "a policy field in a form, in another case",
                SQS_QUERY,
                |r| r.body.as_mut().unwrap().push_str("&policy=%7B%7D"),
            ),
            ("an SQS queue policy in a form", SQS_QUERY, |r| {
                r.body
                    .as_mut()
                    .unwrap()
                    .push_str("&Attribute.2.Name=Policy&Attribute.2.Value=%7B%7D")
            }),
            ("an SQS queue policy in the query", SQS_QUERY, |r| {
                r.url
                    .set_query(Some("Attribute.2.Name=Policy&Attribute.2.Value=%7B%7D"))
            }),
            ("an SQS form moved into the query", SQS_QUERY, |r| {
                let form = r.body.take().unwrap();
                r.url.set_query(Some(&format!(
                    "{form}&Attribute.2.Name=Policy&Attribute.2.Value=%7B%7D"
                )))
            }),
            ("a KMS key policy", CREATE_KEY, |r| {
                r.body = Some(r#"{"Description":"k","Policy":"{}"}"#.into())
            }),
            ("a Cloud Storage predefined ACL", BUCKET_PATCH, |r| {
                r.url.set_query(Some("predefinedAcl=publicRead"))
            }),
            ("a Cloud Run IAM policy", CLOUD_RUN_SERVICE, |r| {
                r.url
                    .set_path("/v2/projects/p/locations/l/services/web:setIamPolicy");
                r.method = Method::POST;
            }),
            ("an Azure role assignment", RESOURCE_GROUP, |r| {
                r.url.set_path(
                    "/subscriptions/s/resourcegroups/g/providers/Microsoft.Authorization/roleAssignments/a",
                )
            }),
        ];
        for (what, built, change) in cases {
            assert_change_refused(what, built, change);
        }
    }

    const AZURE_JSON: [(&str, &str, &str); 4] = [
        (
            "storage account",
            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.Storage/storageAccounts/acct?api-version=2023-01-01",
            r#"{"location":"eastus","properties":{"allowBlobPublicAccess":false,"networkAcls":{"defaultAction":"Deny","ipRules":[{"value":"10.0.0.0/8"}]}}}"#,
        ),
        (
            "container",
            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.Storage/storageAccounts/acct/blobServices/default/containers/c?api-version=2023-01-01",
            r#"{"properties":{"publicAccess":"None"}}"#,
        ),
        (
            "network security group",
            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.Network/networkSecurityGroups/nsg?api-version=2023-01-01",
            r#"{"location":"eastus","properties":{"securityRules":[{"name":"r","properties":{"access":"Allow","direction":"Inbound","sourceAddressPrefix":"10.0.0.0/16","sourceAddressPrefixes":[]}}]}}"#,
        ),
        (
            "storage account with a public default",
            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.Storage/storageAccounts/acct?api-version=2023-01-01",
            r#"{"properties":{"publicNetworkAccess":"Disabled"}}"#,
        ),
    ];

    fn azure_call(what: &str) -> Built {
        let (_, url, body) = AZURE_JSON.iter().find(|(name, ..)| *name == what).unwrap();
        (
            Cloud::Azure,
            "management",
            Method::PUT,
            url,
            &[("content-type", "application/json")],
            Some(body),
        )
    }

    /// An interceptor never makes storage or a network public, on any cloud.
    #[test]
    fn a_change_that_opens_storage_or_a_network_to_the_internet_is_refused() {
        const SECURITY_GROUP: Built = (
            Cloud::Aws,
            "ec2",
            Method::POST,
            "https://ec2.us-east-1.amazonaws.com/",
            &[("content-type", "application/x-www-form-urlencoded")],
            Some("Action=AuthorizeSecurityGroupIngress&GroupId=sg-1&IpPermissions.1.IpProtocol=-1&IpPermissions.1.IpRanges.1.CidrIp=10.0.0.0%2F16"),
        );
        const GCS_BUCKET: Built = (
            Cloud::Gcp,
            "storage",
            Method::PATCH,
            "https://storage.googleapis.com/storage/v1/b/bucket",
            &[("content-type", "application/json")],
            Some(r#"{"iamConfiguration":{"publicAccessPrevention":"enforced"}}"#),
        );
        const FIREWALL: Built = (
            Cloud::Gcp,
            "compute",
            Method::POST,
            "https://compute.googleapis.com/compute/v1/projects/p/global/firewalls",
            &[("content-type", "application/json")],
            Some(r#"{"name":"f","sourceRanges":["10.0.0.0/16"]}"#),
        );
        let cases: [(&str, Built, fn(&mut HookRequest)); 15] = [
            (
                "an Azure storage account allowing public blobs",
                azure_call("storage account"),
                |r| {
                    r.body = Some(r.body.as_ref().unwrap().replace(
                        r#""allowBlobPublicAccess":false"#,
                        r#""allowBlobPublicAccess":true"#,
                    ))
                },
            ),
            (
                "an Azure container with blob access",
                azure_call("container"),
                |r| r.body = Some(r#"{"properties":{"publicAccess":"Blob"}}"#.into()),
            ),
            (
                "an Azure container with container access",
                azure_call("container"),
                |r| r.body = Some(r#"{"properties":{"publicAccess":"Container"}}"#.into()),
            ),
            (
                "an Azure storage firewall that allows by default",
                azure_call("storage account"),
                |r| r.body = Some(r.body.as_ref().unwrap().replace(r#""Deny""#, r#""Allow""#)),
            ),
            (
                "an Azure storage firewall rule for the whole internet",
                azure_call("storage account"),
                |r| r.body = Some(r.body.as_ref().unwrap().replace("10.0.0.0/8", "0.0.0.0/0")),
            ),
            (
                "an Azure storage account with public network access",
                azure_call("storage account with a public default"),
                |r| r.body = Some(r#"{"properties":{"publicNetworkAccess":"Enabled"}}"#.into()),
            ),
            (
                "an Azure NSG rule from *",
                azure_call("network security group"),
                |r| r.body = Some(r.body.as_ref().unwrap().replace("10.0.0.0/16", "*")),
            ),
            (
                "an Azure NSG rule from Internet",
                azure_call("network security group"),
                |r| r.body = Some(r.body.as_ref().unwrap().replace("10.0.0.0/16", "Internet")),
            ),
            (
                "an Azure NSG rule from Any",
                azure_call("network security group"),
                |r| r.body = Some(r.body.as_ref().unwrap().replace("10.0.0.0/16", "any")),
            ),
            (
                "an Azure NSG rule from ::/0 in a prefix list",
                azure_call("network security group"),
                |r| {
                    r.body = Some(r.body.as_ref().unwrap().replace(
                        r#""sourceAddressPrefixes":[]"#,
                        r#""sourceAddressPrefixes":["::/0"]"#,
                    ))
                },
            ),
            ("an AWS security group open to IPv4", SECURITY_GROUP, |r| {
                r.body = Some(
                    r.body
                        .as_ref()
                        .unwrap()
                        .replace("10.0.0.0%2F16", "0.0.0.0%2F0"),
                )
            }),
            ("an AWS security group open to IPv6", SECURITY_GROUP, |r| {
                r.body
                    .as_mut()
                    .unwrap()
                    .push_str("&IpPermissions.1.Ipv6Ranges.1.CidrIpv6=%3A%3A%2F0")
            }),
            (
                "a Cloud Storage public access prevention turned off",
                GCS_BUCKET,
                |r| {
                    r.body = Some(
                        r#"{"iamConfiguration":{"publicAccessPrevention":"inherited"}}"#.into(),
                    )
                },
            ),
            ("a Cloud Storage ACL entry for allUsers", GCS_BUCKET, |r| {
                r.body = Some(r#"{"acl":[{"entity":"allUsers","role":"READER"}]}"#.into())
            }),
            ("a Google firewall open to the internet", FIREWALL, |r| {
                r.body = Some(r#"{"name":"f","sourceRanges":["10.0.0.0/16","0.0.0.0/0"]}"#.into())
            }),
        ];
        for (what, built, change) in cases {
            assert_change_refused(what, built, change);
        }
    }

    /// Any change to an exposure or access setting is refused, whatever its value: the check
    /// does not judge a value, so a split range or a flipped flag cannot slip past it.
    #[test]
    fn any_change_to_an_exposure_or_access_setting_is_refused_with_its_reason() {
        const REASON: &str = "a setting that decides who can reach a resource";
        const SECURITY_GROUP: Built = (
            Cloud::Aws,
            "ec2",
            Method::POST,
            "https://ec2.us-east-1.amazonaws.com/",
            &[("content-type", "application/x-www-form-urlencoded")],
            Some("Action=AuthorizeSecurityGroupIngress&GroupId=sg-1&IpPermissions.1.IpRanges.1.CidrIp=10.0.0.0%2F16"),
        );
        const RDS: Built = (
            Cloud::Aws,
            "rds",
            Method::POST,
            "https://rds.us-east-1.amazonaws.com/?Action=ModifyDBInstance&DBInstanceIdentifier=db&PubliclyAccessible=false",
            &[],
            None,
        );
        const SQL: Built = (
            Cloud::Gcp,
            "sqladmin",
            Method::PATCH,
            "https://sqladmin.googleapis.com/v1/projects/p/instances/i",
            &[("content-type", "application/json")],
            Some(
                r#"{"settings":{"ipConfiguration":{"ipv4Enabled":false,"authorizedNetworks":[]}}}"#,
            ),
        );
        const RUN: Built = (
            Cloud::Gcp,
            "run",
            Method::PATCH,
            "https://run.googleapis.com/v2/projects/p/locations/l/services/web",
            &[("content-type", "application/json")],
            Some(r#"{"ingress":"INGRESS_TRAFFIC_INTERNAL_ONLY","invokerIamDisabled":false}"#),
        );
        const APP: Built = (
            Cloud::Azure,
            "management",
            Method::PUT,
            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.App/containerApps/web?api-version=2024-03-01",
            &[("content-type", "application/json")],
            Some(r#"{"properties":{"configuration":{"ingress":{"external":false,"targetPort":80}}}}"#),
        );
        const VAULT: Built = (
            Cloud::Azure,
            "management",
            Method::PUT,
            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.KeyVault/vaults/v?api-version=2023-07-01",
            &[("content-type", "application/json")],
            Some(r#"{"properties":{"enableRbacAuthorization":true,"accessPolicies":[]}}"#),
        );
        const GCS: Built = (
            Cloud::Gcp,
            "storage",
            Method::PATCH,
            "https://storage.googleapis.com/storage/v1/b/bucket",
            &[("content-type", "application/json")],
            Some(r#"{"iamConfiguration":{"uniformBucketLevelAccess":{"enabled":true}},"acl":[]}"#),
        );
        const FIREWALL: Built = (
            Cloud::Gcp,
            "compute",
            Method::POST,
            "https://compute.googleapis.com/compute/v1/projects/p/global/firewalls",
            &[("content-type", "application/json")],
            Some(r#"{"name":"f","sourceRanges":["10.0.0.0/16"]}"#),
        );
        let cases: [(&str, Built, fn(&mut HookRequest)); 11] = [
            (
                "a range split in two halves of the internet",
                FIREWALL,
                |r| {
                    r.body =
                        Some(r#"{"name":"f","sourceRanges":["0.0.0.0/1","128.0.0.0/1"]}"#.into())
                },
            ),
            ("an RDS instance made publicly accessible", RDS, |r| {
                r.url = "https://rds.us-east-1.amazonaws.com/?Action=ModifyDBInstance&DBInstanceIdentifier=db&PubliclyAccessible=true"
                    .parse()
                    .unwrap()
            }),
            ("a Cloud SQL authorized network added", SQL, |r| {
                r.body = Some(
                    r#"{"settings":{"ipConfiguration":{"ipv4Enabled":false,"authorizedNetworks":[{"value":"203.0.113.0/24"}]}}}"#.into(),
                )
            }),
            (
                "a Cloud Run ingress opened and IAM invoker check off",
                RUN,
                |r| {
                    r.body = Some(
                        r#"{"ingress":"INGRESS_TRAFFIC_ALL","invokerIamDisabled":true}"#.into(),
                    )
                },
            ),
            ("a snake_case Cloud Run invoker_iam_disabled", RUN, |r| {
                r.body = Some(
                    r#"{"ingress":"INGRESS_TRAFFIC_INTERNAL_ONLY","invoker_iam_disabled":true}"#
                        .into(),
                )
            }),
            ("a snake_case publicly_accessible", SQL, |r| {
                r.body = Some(r#"{"settings":{"publicly_accessible":true}}"#.into())
            }),
            ("a Container App with external ingress", APP, |r| {
                r.body = Some(
                    r.body
                        .as_ref()
                        .unwrap()
                        .replace(r#""external":false"#, r#""external":true"#),
                )
            }),
            ("a Key Vault moved to access policies", VAULT, |r| {
                r.body = Some(
                    r#"{"properties":{"enableRbacAuthorization":false,"accessPolicies":[{"objectId":"o"}]}}"#.into(),
                )
            }),
            ("a bucket with uniform access off and an ACL", GCS, |r| {
                r.body = Some(
                    r#"{"iamConfiguration":{"uniformBucketLevelAccess":{"enabled":false}},"acl":[{"entity":"project-owners-1","role":"OWNER"}]}"#.into(),
                )
            }),
            (
                "a security group range added next to the original",
                SECURITY_GROUP,
                |r| {
                    r.body
                        .as_mut()
                        .unwrap()
                        .push_str("&IpPermissions.1.IpRanges.2.CidrIp=203.0.113.0%2F24")
                },
            ),
            ("a setting removed", FIREWALL, |r| {
                r.body = Some(r#"{"name":"f"}"#.into())
            }),
        ];
        for (what, built, change) in cases {
            assert_change_refused_because(what, built, REASON, change);
        }
    }

    /// Ordinary changes still go through, and a call Alien itself builds public stays so.
    #[test]
    fn a_change_that_does_not_open_anything_to_the_internet_is_sent() {
        const PUBLIC_CONTAINER: Built = (
            Cloud::Azure,
            "management",
            Method::PUT,
            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.Storage/storageAccounts/acct/blobServices/default/containers/c?api-version=2023-01-01",
            &[("content-type", "application/json")],
            Some(r#"{"properties":{"publicAccess":"Blob"}}"#),
        );
        const EGRESS: Built = (
            Cloud::Aws,
            "ec2",
            Method::POST,
            "https://ec2.us-east-1.amazonaws.com/",
            &[("content-type", "application/x-www-form-urlencoded")],
            Some("Action=AuthorizeSecurityGroupEgress&GroupId=sg-1&IpPermissions.1.IpRanges.1.CidrIp=0.0.0.0%2F0"),
        );
        const CONTAINER_APP: Built = (
            Cloud::Azure,
            "management",
            Method::PUT,
            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.App/containerApps/web?api-version=2024-03-01",
            &[("content-type", "application/json")],
            Some(r#"{"properties":{"template":{"containers":[{"name":"web","env":[{"name":"MODE","value":"a"}]}]}}}"#),
        );
        let cases: [(&str, Built, fn(&mut HookRequest)); 4] = [
            (
                "an environment variable that ends in /0 (a Redis URL)",
                CONTAINER_APP,
                |r| {
                    r.body = Some(r.body.as_ref().unwrap().replace(
                        r#"{"name":"MODE","value":"a"}"#,
                        r#"{"name":"MODE","value":"a"},{"name":"REDIS_URL","value":"redis://cache:6379/0"}"#,
                    ))
                },
            ),
            (
                "a tag on an Azure storage account",
                azure_call("storage account"),
                |r| {
                    r.body = Some(r.body.as_ref().unwrap().replace(
                        r#""location":"eastus""#,
                        r#""location":"eastus","tags":{"team":"a"}"#,
                    ))
                },
            ),
            (
                "an Azure container Alien made public on purpose",
                PUBLIC_CONTAINER,
                |r| {
                    r.body = Some(
                        r#"{"properties":{"publicAccess":"Blob"},"metadata":{"a":"b"}}"#.into(),
                    )
                },
            ),
            (
                "an AWS rule Alien already opened to the internet",
                EGRESS,
                |r| {
                    r.body
                        .as_mut()
                        .unwrap()
                        .push_str("&IpPermissions.1.IpRanges.1.Description=x")
                },
            ),
        ];
        for (what, built, change) in cases {
            assert_change_sent(what, built, change);
        }
    }

    /// A call Alien makes to change who has access, to act as another identity, or to read a
    /// policy it then writes back is sent as Alien built it: no interceptor is asked whether it
    /// matches it, so one that matches everything never fails it.
    #[test]
    fn a_call_that_changes_access_or_identity_is_never_offered() {
        let cases: [Built; 20] = [
            (
                Cloud::Aws,
                "iam",
                Method::POST,
                "https://iam.amazonaws.com/",
                &[("content-type", "application/x-www-form-urlencoded")],
                Some("Action=PutRolePolicy&RoleName=r&PolicyName=p&PolicyDocument=%7B%7D"),
            ),
            (
                Cloud::Aws,
                "cloudcontrolapi",
                Method::POST,
                "https://cloudcontrolapi.us-east-1.amazonaws.com/",
                &[(
                    "x-amz-target",
                    "CloudApiService.CreateResource",
                )],
                Some(r#"{"TypeName":"AWS::EC2::VPC"}"#),
            ),
            (
                Cloud::Aws,
                "s3",
                Method::PUT,
                "https://bucket.s3.amazonaws.com/?policy",
                &[],
                Some(r#"{"Statement":[]}"#),
            ),
            (
                Cloud::Aws,
                "s3",
                Method::PUT,
                "https://bucket.s3.amazonaws.com/?publicAccessBlock",
                &[],
                Some("<PublicAccessBlockConfiguration><BlockPublicAcls>false</BlockPublicAcls></PublicAccessBlockConfiguration>"),
            ),
            (
                Cloud::Aws,
                "s3",
                Method::GET,
                "https://bucket.s3.amazonaws.com/?policy",
                &[],
                None,
            ),
            (
                Cloud::Aws,
                "kms",
                Method::POST,
                "https://kms.us-east-1.amazonaws.com/",
                &[("x-amz-target", "TrentService.PutKeyPolicy")],
                Some(r#"{"KeyId":"k","Policy":"{}"}"#),
            ),
            (
                Cloud::Aws,
                "ecr",
                Method::POST,
                "https://api.ecr.us-east-1.amazonaws.com/",
                &[(
                    "x-amz-target",
                    "AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy",
                )],
                Some(r#"{"repositoryName":"r"}"#),
            ),
            (
                Cloud::Aws,
                "lambda",
                Method::POST,
                "https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/f/policy",
                &[],
                Some(r#"{"StatementId":"s","Action":"lambda:InvokeFunction"}"#),
            ),
            (
                Cloud::Aws,
                "sqs",
                Method::POST,
                "https://sqs.us-east-1.amazonaws.com/",
                &[],
                Some("Action=SetQueueAttributes&Attribute.1.Name=Policy&Attribute.1.Value=%7B%7D"),
            ),
            (
                Cloud::Aws,
                "logs",
                Method::POST,
                "https://logs.us-east-1.amazonaws.com/",
                &[("x-amz-target", "Logs_20140328.PutResourcePolicy")],
                Some(r#"{"policyName":"p","policyDocument":"{}"}"#),
            ),
            (
                Cloud::Gcp,
                "cloudrun",
                Method::POST,
                "https://run.googleapis.com/v2/projects/p/locations/l/services/web:setIamPolicy",
                &[],
                Some(r#"{"policy":{}}"#),
            ),
            (
                Cloud::Gcp,
                "cloudrun",
                Method::GET,
                "https://run.googleapis.com/v2/projects/p/locations/l/services/web:getIamPolicy",
                &[],
                None,
            ),
            (
                Cloud::Gcp,
                "storage",
                Method::GET,
                "https://storage.googleapis.com/storage/v1/b/bucket/iam",
                &[],
                None,
            ),
            (
                Cloud::Azure,
                "management",
                Method::PUT,
                "https://management.azure.com/subscriptions/s/providers/Microsoft.Authorization/roleAssignments/a",
                &[],
                Some(r#"{"properties":{}}"#),
            ),
            (
                Cloud::Azure,
                "management",
                Method::PUT,
                "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.ManagedIdentity/userAssignedIdentities/u/federatedIdentityCredentials/c",
                &[],
                Some(r#"{"properties":{}}"#),
            ),
            (
                Cloud::Kubernetes,
                "kubernetes",
                Method::POST,
                "https://cluster.example.com/api/v1/namespaces/app/secrets",
                &[("content-type", "application/json")],
                Some(r#"{"metadata":{"name":"registry"},"type":"kubernetes.io/dockerconfigjson"}"#),
            ),
            (
                Cloud::Kubernetes,
                "kubernetes",
                Method::GET,
                "https://cluster.example.com/api/v1/namespaces/app/secrets/registry",
                &[],
                None,
            ),
            (
                Cloud::Kubernetes,
                "kubernetes",
                Method::GET,
                "https://cluster.example.com/api/v1/secrets?labelSelector=app",
                &[],
                None,
            ),
            (
                Cloud::Kubernetes,
                "kubernetes",
                Method::POST,
                "https://cluster.example.com/api/v1/namespaces/app/serviceaccounts/app/token",
                &[("content-type", "application/json")],
                Some(r#"{"spec":{"audiences":["api"]}}"#),
            ),
            (
                Cloud::Kubernetes,
                "kubernetes",
                Method::POST,
                "https://cluster.example.com/apis/authentication.k8s.io/v1/tokenreviews",
                &[("content-type", "application/json")],
                Some(r#"{"spec":{"token":"t"}}"#),
            ),
        ];
        for built in cases {
            let (cloud, service) = (built.0, built.1);
            let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
                .when(|request| panic!("{} {} was offered", request.method, request.url))]);
            let mut request = build(&built);
            let before = format!("{request:?}");
            assert!(interceptors
                .intercept(cloud, service, &mut request)
                .unwrap()
                .is_none());
            assert_eq!(format!("{request:?}"), before);
        }
    }

    #[test]
    fn an_interceptor_never_sees_credentials_and_the_request_keeps_them() {
        let seen = Arc::new(Mutex::new(None));
        let spy = seen.clone();
        let interceptors = chain(vec![TestInterceptor::new(
            "acme",
            Cloud::Azure,
            "management",
        )
        .on_request(move |r| {
            *spy.lock().unwrap() = Some(r.headers.clone());
            Ok(())
        })]);
        let mut request = reqwest::Client::new()
            .get("https://management.azure.com/subscriptions/sub")
            .header("authorization", "Bearer azure-token")
            .header("proxy-authorization", "Basic proxy")
            .header("x-ms-version", "2023-11-03")
            .build()
            .unwrap();
        interceptors
            .intercept(Cloud::Azure, "management", &mut request)
            .unwrap();
        let seen = seen.lock().unwrap().clone().unwrap();
        assert!(seen.get("authorization").is_none());
        assert!(seen.get("proxy-authorization").is_none());
        assert_eq!(seen["x-ms-version"], "2023-11-03");
        assert_eq!(request.headers()["authorization"], "Bearer azure-token");
        assert_eq!(request.headers()["proxy-authorization"], "Basic proxy");
    }

    #[test]
    fn a_changed_body_gets_new_digest_headers() {
        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "rds")
            .on_request(|r| {
                r.body
                    .as_mut()
                    .unwrap()
                    .push_str("&EnableIAMDatabaseAuthentication=true");
                Ok(())
            })]);
        let mut request = rds_request("Action=CreateDBCluster");
        interceptors
            .intercept(Cloud::Aws, "rds", &mut request)
            .unwrap();
        let body = "Action=CreateDBCluster&EnableIAMDatabaseAuthentication=true";
        assert_eq!(body_text(&request), body);
        assert_eq!(
            request.headers()["content-length"],
            body.len().to_string().as_str()
        );
        assert_eq!(
            request.headers()["x-amz-content-sha256"],
            format!("{:x}", Sha256::digest(body)).as_str()
        );
        assert_eq!(
            request.headers()["content-md5"],
            base64::engine::general_purpose::STANDARD
                .encode(md5::compute(body).0)
                .as_str()
        );
    }

    #[test]
    fn interceptors_run_in_order_on_the_request_the_previous_one_left() {
        let interceptors = chain(vec![
            TestInterceptor::new("first", Cloud::Gcp, "cloudsql").on_request(|r| {
                r.body = Some(r#"{"tier":"small"}"#.to_string());
                Ok(())
            }),
            TestInterceptor::new("second", Cloud::Gcp, "cloudsql").on_request(|r| {
                assert_eq!(r.body.as_deref(), Some(r#"{"tier":"small"}"#));
                r.body = Some(r#"{"tier":"large"}"#.to_string());
                Ok(())
            }),
        ]);
        let mut request = reqwest::Client::new()
            .post("https://sqladmin.googleapis.com/v1/projects/p/instances")
            .json(&serde_json::json!({"tier": "tiny"}))
            .build()
            .unwrap();
        interceptors
            .intercept(Cloud::Gcp, "cloudsql", &mut request)
            .unwrap();
        assert_eq!(body_text(&request), r#"{"tier":"large"}"#);
    }

    #[test]
    fn an_interceptor_error_fails_the_call_naming_its_extension() {
        let interceptors = chain(vec![TestInterceptor::new(
            "acme",
            Cloud::Kubernetes,
            "kubernetes",
        )
        .on_request(|_| {
            Err(AlienError::new(ErrorData::GenericError {
                message: "label value missing".to_string(),
            }))
        })]);
        let mut request = reqwest::Client::new()
            .post("https://cluster.local/api/v1/namespaces/ns/pods")
            .json(&serde_json::json!({"kind": "Pod"}))
            .build()
            .unwrap();
        let error = interceptors
            .intercept(Cloud::Kubernetes, "kubernetes", &mut request)
            .unwrap_err();
        assert!(error
            .source
            .as_ref()
            .unwrap()
            .message
            .contains("label value missing"));
        assert_fails_naming(error, "acme");
    }

    #[test]
    fn a_binary_request_body_fails_a_call_an_interceptor_matches() {
        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "s3")
            .on_request(|_| panic!("a binary body is never offered"))]);
        let mut request = reqwest::Client::new()
            .put("https://bucket.s3.amazonaws.com/key")
            .header("content-type", "application/json")
            .body(vec![0xff, 0xfe])
            .build()
            .unwrap();
        let error = interceptors
            .intercept(Cloud::Aws, "s3", &mut request)
            .unwrap_err();
        assert_fails_naming(error, "acme");
    }

    #[test]
    fn an_object_payload_is_binary_whatever_its_content_type() {
        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "s3")
            .on_request(|_| panic!("an object's bytes are never offered"))]);
        for builder in [
            reqwest::Client::new()
                .put("https://bucket.s3.amazonaws.com/config.json")
                .header("content-type", "application/json")
                .body(r#"{"looks":"like json"}"#),
            reqwest::Client::new().get("https://bucket.s3.amazonaws.com/config.json"),
        ] {
            let mut request = builder.build().unwrap();
            let error = interceptors
                .for_object_payload()
                .intercept(Cloud::Aws, "s3", &mut request)
                .unwrap_err();
            assert_fails_naming(error, "acme");
        }
    }

    #[test]
    fn a_binary_call_no_interceptor_matches_is_sent_as_it_was() {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let spy = seen.clone();
        let tagging = TestInterceptor::new("acme", Cloud::Aws, "s3").when(move |request| {
            spy.lock()
                .unwrap()
                .push((request.method.clone(), request.body.clone()));
            request.url.query() == Some("tagging")
        });
        let interceptors = chain(vec![tagging]);
        let mut request = reqwest::Client::new()
            .put("https://bucket.s3.amazonaws.com/image.png")
            .body(vec![0x89, b'P', b'N', b'G'])
            .build()
            .unwrap();
        assert!(interceptors
            .for_object_payload()
            .intercept(Cloud::Aws, "s3", &mut request)
            .unwrap()
            .is_none());
        assert_eq!(
            request.body().unwrap().as_bytes(),
            Some(&[0x89, b'P', b'N', b'G'][..])
        );
        assert_eq!(*seen.lock().unwrap(), vec![(Method::PUT, None)]);
    }

    #[test]
    fn a_text_body_is_offered_whatever_its_content_type() {
        let interceptors = chain(vec![TestInterceptor::new(
            "acme",
            Cloud::Kubernetes,
            "kubernetes",
        )
        .on_request(|request| {
            assert_eq!(request.body.as_deref(), Some("plain words"));
            Ok(())
        })]);
        let mut request = reqwest::Client::new()
            .post("https://cluster.local/api/v1/namespaces/ns/configmaps")
            .header("content-type", "text/plain")
            .body("plain words")
            .build()
            .unwrap();
        assert!(interceptors
            .intercept(Cloud::Kubernetes, "kubernetes", &mut request)
            .unwrap()
            .is_some());
    }

    #[tokio::test]
    async fn modify_response_sees_and_can_change_an_error_response() {
        let interceptors = chain(vec![TestInterceptor::new(
            "acme",
            Cloud::Azure,
            "management",
        )
        .on_response(|request, response| {
            assert_eq!(request.method, Method::PUT);
            assert_eq!(response.status, 409);
            response.status = 200;
            response.body = r#"{"name":"recovered"}"#.to_string();
            Ok(())
        })]);
        let mut request = reqwest::Client::new()
            .put("https://management.azure.com/subscriptions/sub/thing")
            .json(&serde_json::json!({}))
            .build()
            .unwrap();
        let hook = interceptors
            .intercept(Cloud::Azure, "management", &mut request)
            .unwrap()
            .unwrap();
        let response = reqwest::Response::from(
            http::Response::builder()
                .status(409)
                .header("content-type", "application/json")
                .url(Url::parse("https://management.azure.com/subscriptions/sub/thing").unwrap())
                .body(r#"{"error":{"code":"Conflict"}}"#)
                .unwrap(),
        );
        let response = hook.apply(response).await.unwrap();
        assert_eq!(response.status(), 200);
        assert_eq!(
            response.url().as_str(),
            "https://management.azure.com/subscriptions/sub/thing"
        );
        assert_eq!(response.text().await.unwrap(), r#"{"name":"recovered"}"#);
    }

    async fn hooked_get(interceptor: TestInterceptor) -> ResponseHook {
        let mut request = reqwest::Client::new()
            .get("https://cluster.local/api/v1/namespaces/ns/pods/web")
            .build()
            .unwrap();
        chain(vec![interceptor])
            .intercept(Cloud::Kubernetes, "kubernetes", &mut request)
            .unwrap()
            .unwrap()
    }

    #[tokio::test]
    async fn a_binary_response_fails_a_call_an_interceptor_matches() {
        let hook = hooked_get(
            TestInterceptor::new("acme", Cloud::Kubernetes, "kubernetes")
                .on_response(|_, _| panic!("a binary body is never offered")),
        )
        .await;
        let response = reqwest::Response::from(
            http::Response::builder()
                .status(200)
                .header("content-type", "application/json")
                .body(vec![0x89, b'P', b'N', b'G', 0xff])
                .unwrap(),
        );
        assert_fails_naming(hook.apply(response).await.unwrap_err(), "acme");
    }

    /// A plain-text error page from an API server or a proxy is text: it reaches the client's own
    /// status handling and retries instead of failing the call.
    #[tokio::test]
    async fn a_plain_text_error_response_is_offered() {
        let hook = hooked_get(
            TestInterceptor::new("acme", Cloud::Kubernetes, "kubernetes").on_response(
                |_, response| {
                    assert_eq!(response.body, "upstream connect error");
                    Ok(())
                },
            ),
        )
        .await;
        let response = reqwest::Response::from(
            http::Response::builder()
                .status(503)
                .header("content-type", "text/plain")
                .body("upstream connect error")
                .unwrap(),
        );
        let response = hook.apply(response).await.unwrap();
        assert_eq!(response.status(), 503);
        assert_eq!(response.text().await.unwrap(), "upstream connect error");
    }

    /// A cloud's error can quote the request it refused, as AWS quotes the signed headers when a
    /// signature does not match. The credential the call was signed with is cleared before an
    /// interceptor reads the response, whether the client signed before the interceptors ran or
    /// after.
    #[tokio::test]
    async fn an_echoed_credential_is_cleared_before_an_interceptor_reads_the_response() {
        let token = "IQoJb3JpZ2luX2VjEXAMPLESESSIONTOKEN";
        let quoting = |request: &mut reqwest::Request| {
            chain(vec![TestInterceptor::new("acme", Cloud::Aws, "s3")
                .on_response(move |_, response| {
                    assert!(!response.body.contains(token), "{}", response.body);
                    assert!(response.body.contains("[redacted]"), "{}", response.body);
                    let echoed = response.headers["x-amz-echo"].to_str().unwrap();
                    assert!(!echoed.contains(token), "{echoed}");
                    Ok(())
                })])
            .intercept(Cloud::Aws, "s3", request)
            .unwrap()
            .unwrap()
        };
        let response = || {
            reqwest::Response::from(
                http::Response::builder()
                    .status(403)
                    .header("content-type", "application/xml")
                    .header("x-amz-echo", format!("token={token}"))
                    .body(format!(
                        "<Error><Code>SignatureDoesNotMatch</Code><CanonicalRequest>x-amz-security-token:{token}</CanonicalRequest></Error>"
                    ))
                    .unwrap(),
            )
        };
        let unsigned = || {
            reqwest::Client::new()
                .get("https://bucket.s3.us-east-1.amazonaws.com/key")
                .build()
                .unwrap()
        };

        // Signed after the interceptors ran: the signer hands the hook the signed request.
        let mut request = unsigned();
        let mut hook = quoting(&mut request);
        request.headers_mut().insert(
            "x-amz-security-token",
            HeaderValue::from_str(token).unwrap(),
        );
        hook.remember_credentials(&request);
        let read = hook.apply(response()).await.unwrap().text().await.unwrap();
        assert!(!read.contains(token), "{read}");

        // Signed before: the hook reads the credential off the request it intercepts.
        let mut request = unsigned();
        request.headers_mut().insert(
            "x-amz-security-token",
            HeaderValue::from_str(token).unwrap(),
        );
        let hook = quoting(&mut request);
        hook.apply(response()).await.unwrap();
    }

    /// A bearer token is cleared on its own as well as with its scheme, and a short value that
    /// could be ordinary text is left alone.
    #[test]
    fn a_bearer_token_is_cleared_on_its_own() {
        let mut request = reqwest::Client::new()
            .get("https://management.azure.com/subscriptions/sub?api-version=1")
            .header("authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi")
            .header("proxy-authorization", "Basic abc")
            .build()
            .unwrap();
        let hook = chain(vec![TestInterceptor::new(
            "acme",
            Cloud::Azure,
            "management",
        )])
        .intercept(Cloud::Azure, "management", &mut request)
        .unwrap()
        .unwrap();
        assert_eq!(
            hook.cleared(br#"{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOi","word":"abc"}"#),
            br#"{"token":"[redacted]","word":"abc"}"#.to_vec()
        );
    }

    /// A create the cloud answered with success already made the resource, so a hook that turns
    /// the answer into a throttle fails the call for good instead of having it sent again.
    #[tokio::test]
    async fn a_hook_that_fails_a_successful_call_fails_it_for_good() {
        let mut request = reqwest::Client::new()
            .post("https://ec2.us-east-1.amazonaws.com/")
            .header("content-type", "application/x-www-form-urlencoded")
            .body("Action=CreateVpc&CidrBlock=10.0.0.0%2F16")
            .build()
            .unwrap();
        let hook = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "ec2")
            .on_response(|_, response| {
                response.status = 429;
                Ok(())
            })])
        .intercept(Cloud::Aws, "ec2", &mut request)
        .unwrap()
        .unwrap();
        let response = reqwest::Response::from(
            http::Response::builder()
                .status(200)
                .header("content-type", "text/xml")
                .body("<CreateVpcResponse><vpc><vpcId>vpc-1</vpcId></vpc></CreateVpcResponse>")
                .unwrap(),
        );
        let error = hook.apply(response).await.unwrap_err();
        assert!(!error.retryable);
        assert_fails_naming(error, "acme");
    }

    /// Alien reads a Kubernetes response to decide its next calls on the cluster, so an
    /// interceptor may not change one.
    #[tokio::test]
    async fn a_kubernetes_response_is_not_changed() {
        let hook = hooked_get(
            TestInterceptor::new("acme", Cloud::Kubernetes, "kubernetes").on_response(
                |_, response| {
                    response.body = r#"{"metadata":{"name":"other"}}"#.to_string();
                    Ok(())
                },
            ),
        )
        .await;
        let response = reqwest::Response::from(
            http::Response::builder()
                .status(200)
                .header("content-type", "application/json")
                .body(r#"{"metadata":{"name":"web"}}"#)
                .unwrap(),
        );
        let error = hook.apply(response).await.unwrap_err();
        assert!(!error.retryable);
        assert_fails_naming(error, "acme");
    }

    /// The cloud already acted on the call when `modify_response` runs, so a failure there is
    /// final even when the hook marked it retryable: a retry would create the resource twice.
    #[tokio::test]
    async fn a_failed_modify_response_is_never_sent_again() {
        use crate::request_utils::InterceptedRequestBuilder;
        use crate::testing::capture;

        let server = capture::start(|_| capture::Reply::new(200, "application/json", "{}")).await;
        let client = reqwest::Client::new();
        let mut request = client
            .post(format!("{}/servers", server.base_url))
            .body("{}")
            .build()
            .unwrap();
        let hook = chain(vec![TestInterceptor::new(
            "acme",
            Cloud::Azure,
            "management",
        )
        .on_response(|_, _| {
            let mut deadline = failed(
                "acme",
                "its hook 'h' failed (HOOK_DEADLINE_EXCEEDED)".into(),
            );
            deadline.retryable = true;
            Err(deadline)
        })])
        .intercept(Cloud::Azure, "management", &mut request)
        .unwrap();

        let error = InterceptedRequestBuilder::new(
            reqwest::RequestBuilder::from_parts(client, request),
            hook,
        )
        .with_retry()
        .send_json::<serde_json::Value>()
        .await
        .unwrap_err();
        assert_eq!(error.code, "INTERCEPTOR_FAILED");
        assert!(!error.retryable);
        assert_eq!(server.requests().len(), 1);
    }

    /// A 2xx means the cloud acted on the call, so a body that breaks off after it is not
    /// retried through the interceptors either.
    #[tokio::test]
    async fn success_body_read_failure_does_not_replay_an_intercepted_mutation() {
        use crate::request_utils::InterceptedRequestBuilder;
        use backon::ExponentialBuilder;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::time::Duration;
        use tokio::io::{AsyncBufReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("listen");
        let address = listener.local_addr().expect("address");
        let requests = Arc::new(AtomicUsize::new(0));
        let seen = requests.clone();
        let server = tokio::spawn(async move {
            loop {
                let (mut stream, _) = listener.accept().await.expect("accept");
                {
                    let mut reader = tokio::io::BufReader::new(&mut stream);
                    loop {
                        let mut line = String::new();
                        assert!(reader.read_line(&mut line).await.expect("request header") > 0);
                        if line == "\r\n" {
                            break;
                        }
                    }
                }
                seen.fetch_add(1, Ordering::SeqCst);
                stream
                    .write_all(
                        b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\nshort",
                    )
                    .await
                    .expect("response");
                stream.shutdown().await.expect("close response");
            }
        });

        let client = reqwest::Client::builder()
            .no_proxy()
            .timeout(Duration::from_secs(5))
            .build()
            .expect("client");
        let mut request = client
            .post(format!("http://{address}/servers"))
            .build()
            .unwrap();
        let hook = chain(vec![TestInterceptor::new(
            "acme",
            Cloud::Azure,
            "management",
        )])
        .intercept(Cloud::Azure, "management", &mut request)
        .unwrap();
        assert!(hook.is_some(), "the interceptor matched");

        let error = InterceptedRequestBuilder::new(
            reqwest::RequestBuilder::from_parts(client, request),
            hook,
        )
        .with_retry()
        .backoff(
            ExponentialBuilder::default()
                .with_min_delay(Duration::from_millis(1))
                .with_max_delay(Duration::from_millis(1))
                .with_max_times(2),
        )
        .send_no_response()
        .await
        .expect_err("a truncated body fails the call");
        assert_eq!(
            requests.load(Ordering::SeqCst),
            1,
            "the mutation was sent again"
        );
        assert_eq!(error.code, "HTTP_RESPONSE_BODY_READ_FAILED", "{error}");
        assert!(!error.retryable);
        assert!(matches!(
            error.error,
            Some(ErrorData::HttpResponseBodyReadFailed { http_status: 200 })
        ));
        server.abort();
    }

    #[test]
    fn a_wrapper_keeps_an_interceptor_failure_final() {
        let wrapped: Result<()> =
            Err(failed("acme", "refused".to_string())).context(ErrorData::HttpRequestFailed {
                message: "GetObject request failed".to_string(),
            });
        assert!(wrapped.as_ref().unwrap_err().retryable);
        assert!(
            !keep_interceptor_failure_final(wrapped)
                .unwrap_err()
                .retryable
        );

        let mut deadline = failed(
            "acme",
            "its hook 'h' failed (HOOK_DEADLINE_EXCEEDED)".into(),
        );
        deadline.retryable = true;
        let wrapped: Result<()> = Err(deadline).context(ErrorData::HttpRequestFailed {
            message: "GetObject request failed".to_string(),
        });
        assert!(
            keep_interceptor_failure_final(wrapped)
                .unwrap_err()
                .retryable,
            "an interceptor's own retryable failure stays retryable"
        );

        let network: Result<()> = Err(AlienError::new(ErrorData::HttpRequestFailed {
            message: "connection reset".to_string(),
        }));
        assert!(
            keep_interceptor_failure_final(network)
                .unwrap_err()
                .retryable
        );
    }

    #[test]
    fn a_client_with_interceptors_signs_only_for_its_endpoint() {
        let endpoint = "https://management.azure.com";
        let elsewhere = Url::parse("https://evil.example.com/operations/1").unwrap();
        assert!(InterceptorChain::default()
            .check_destination(&elsewhere, endpoint)
            .is_ok());

        let interceptors = chain(vec![TestInterceptor::new(
            "acme",
            Cloud::Azure,
            "management",
        )]);
        let error = interceptors
            .check_destination(&elsewhere, endpoint)
            .unwrap_err();
        assert_eq!(error.code, "DESTINATION_REFUSED");
        assert!(!error.retryable);
        interceptors
            .check_destination(
                &Url::parse("https://management.azure.com/subscriptions/s/operations/1").unwrap(),
                endpoint,
            )
            .unwrap();
    }
}