lm15 1.0.0-rc.7

One request and response model for every LLM provider (OpenAI, Anthropic, Gemini, xAI, Groq, Bedrock, Azure, Vertex, local servers), with visible adaptations. Implements the lm15 contract.
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
//! The three cloud credential chains as data over ten rung kinds
//! (spec/auth.md AUTH-1 `aws-chain` / `azure-chain` / `gcp-chain`,
//! AUTH-11; the reference's `lm15/cloud/chains.py`). Every order,
//! variable, path and endpoint is the cloud SDK's own resolver order,
//! cited in `research/cloud-hosts/10-facts-*.md`.
//!
//! Two entry points:
//!
//! - [`explain`] — the offline doctor walk (AUTH-7): every rung reports
//!   `selected` / `shadowed` / `absent` / `unprobed`. No network, no
//!   subprocess: a rung that needs either is `unprobed` when its
//!   configuration is present.
//! - [`ChainProvider`] — the AUTH-2 provider: resolves once (over the
//!   network, asynchronously, in [`CredentialProvider::prepare`]), caches
//!   until the AUTH-3 skew window, re-resolves after. Cache key =
//!   provider id + the identity-selecting settings.
//!
//! Rungs declared but not implemented raise `NotConfigured` naming the
//! gap and the fix; they never fall through silently (`aws login`
//! refresh with a DPoP key; Azure Service Fabric managed identity; GCP
//! `external_account` with an AWS source).
//!
//! Design (stated in the README): the family's `CredentialProvider` is
//! synchronous. A token exchange is a network round trip, and blocking
//! a runtime worker on one is the hazard this port refuses elsewhere; so
//! the chain answers `credential()` from its cache and does the network
//! work in the async `prepare()` the adapter awaits first.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use futures_util::StreamExt;
use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};

use crate::auth::{
    format_rfc3339, parse_rfc3339, AccessPolicy, AuthError, Credential, CredentialPolicy,
    CredentialProvider, CredentialSource,
};
use crate::cloud::hosts::HostSettings;
use crate::cloud::ini::{Ini, Section};
use crate::cloud::rs256;
use crate::cloud::sigv4::{self, AwsKeys, SigningRequest};
use crate::transport::{BoxFuture, Transport};
use crate::wire::TransportRequest;

const MAX_CREDENTIAL_BYTES: usize = 1024 * 1024;
const SKEW_SECONDS: i64 = 300; // AUTH-3
const GCP_SCOPE: &str = "https://www.googleapis.com/auth/cloud-platform";
const GCP_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
const GCP_STS_URL: &str = "https://sts.googleapis.com/v1/token";
const JWT_BEARER: &str = "urn:ietf:params:oauth:grant-type:jwt-bearer";
const CLIENT_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";

// ─── Context: everything a chain touches, injectable ─────────────────

/// What a chain reads. `http: None` means offline (the doctor); `files`
/// overrides the filesystem for the harness; `now` is the fixed clock.
#[derive(Clone)]
pub struct ChainContext {
    pub env: BTreeMap<String, String>,
    pub home: PathBuf,
    pub files: Option<BTreeMap<String, String>>,
    pub http: Option<Arc<dyn Transport>>,
    /// Whether subprocess rungs (`credential_process`, `az`, `gcloud`)
    /// may run. Offline (the doctor) never runs one.
    pub subprocess: bool,
    pub now: i64,
    pub settings: HostSettings,
}

impl ChainContext {
    /// An offline context (the doctor): no network, no subprocess.
    pub fn offline(env: BTreeMap<String, String>, now: i64) -> Self {
        let home = env
            .get("HOME")
            .filter(|h| !h.is_empty())
            .map(PathBuf::from)
            .or_else(|| std::env::var_os("HOME").map(PathBuf::from))
            .unwrap_or_else(|| PathBuf::from("/"));
        ChainContext {
            env,
            home,
            files: None,
            http: None,
            subprocess: false,
            now,
            settings: HostSettings::new(),
        }
    }

    /// An online context over `transport`.
    pub fn online(env: BTreeMap<String, String>, transport: Arc<dyn Transport>, now: i64) -> Self {
        let mut ctx = ChainContext::offline(env, now);
        ctx.http = Some(transport);
        ctx.subprocess = true;
        ctx
    }

    pub fn with_settings(mut self, settings: HostSettings) -> Self {
        self.settings = settings;
        self
    }

    pub fn with_files(mut self, files: BTreeMap<String, String>) -> Self {
        self.files = Some(files);
        self
    }

    fn env(&self, key: &str) -> Option<&str> {
        self.env
            .get(key)
            .map(String::as_str)
            .filter(|v| !v.is_empty())
    }

    pub fn path(&self, text: &str) -> PathBuf {
        if let Some(rest) = text.strip_prefix('~') {
            return self.home.join(rest.trim_start_matches(['/', '\\']));
        }
        PathBuf::from(text)
    }

    pub fn read(&self, text: &str) -> Option<String> {
        if let Some(files) = &self.files {
            let wanted = self.path(text);
            return files
                .iter()
                .find(|(key, _)| self.path(key) == wanted)
                .map(|(_, content)| content.clone());
        }
        std::fs::read_to_string(self.path(text)).ok()
    }

    pub fn exists(&self, text: &str) -> bool {
        self.read(text).is_some()
    }

    /// Where `command` would run from, from the context's PATH only — an
    /// offline file check, so the doctor can say "not installed".
    pub fn on_path(&self, command: &str) -> Option<String> {
        if command.contains('/') || command.contains('\\') {
            return self.exists(command).then(|| command.to_string());
        }
        let path = self.env("PATH").unwrap_or("");
        // The platform's separator, as the reference (os.pathsep): ";" on
        // Windows, where every entry holds a ":" (C:\...).
        let separator = if cfg!(windows) { ';' } else { ':' };
        for directory in path.split(separator).filter(|d| !d.is_empty()) {
            let candidate = format!("{}/{command}", directory.trim_end_matches(['/', '\\']));
            if self.files.is_some() {
                if self.exists(&candidate) {
                    return Some(candidate);
                }
                continue;
            }
            if is_executable(&self.path(&candidate)) {
                return Some(candidate);
            }
            // Windows runs `gcloud` as gcloud.cmd, `az` as az.cmd: try the
            // executable extensions it tries (PATHEXT), as shutil.which does.
            if cfg!(windows) {
                let pathext = self.env("PATHEXT").unwrap_or(".COM;.EXE;.BAT;.CMD");
                for ext in pathext.split(';').filter(|e| !e.is_empty()) {
                    let with_ext = format!("{candidate}{}", ext.to_ascii_lowercase());
                    if is_executable(&self.path(&with_ext)) {
                        return Some(with_ext);
                    }
                }
            }
        }
        None
    }

    pub fn is_offline(&self) -> bool {
        self.http.is_none()
    }

    async fn http(
        &self,
        method: &str,
        url: &str,
        headers: Vec<(String, String)>,
        body: Option<Vec<u8>>,
        timeout_secs: u64,
    ) -> Result<(u16, Vec<(String, String)>, Vec<u8>), AuthError> {
        let transport = self
            .http
            .as_ref()
            .ok_or_else(|| not_configured("this credential source needs the network".into()))?;
        let request = TransportRequest {
            method: method.into(),
            url: url.into(),
            params: Vec::new(),
            headers,
            body: None,
            raw: body,
            read_timeout: Some(std::time::Duration::from_secs(timeout_secs)),
            credential_source: None,
        };
        // Credential exchanges are small and finite, unlike inference streams.
        // Bound the entire operation and decoded body, including custom transports.
        // Never render a transport error: it can contain a token-bearing URL/body.
        tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), async {
            let mut response = transport
                .send(request)
                .await
                .map_err(|_| rejected("credential HTTP request failed".into()))?;
            let status = response.status;
            let headers = std::mem::take(&mut response.headers);
            let mut stream = response.into_body();
            let mut body = Vec::new();
            while let Some(chunk) = stream.next().await {
                let chunk =
                    chunk.map_err(|_| rejected("credential HTTP response failed".into()))?;
                if chunk.len() > MAX_CREDENTIAL_BYTES - body.len() {
                    return Err(rejected("credential HTTP response exceeds 1 MiB".into()));
                }
                body.extend_from_slice(&chunk);
            }
            Ok((status, headers, body))
        })
        .await
        .map_err(|_| rejected("credential HTTP request timed out".into()))?
    }

    /// Like `http` but a connection failure is "not there" (metadata
    /// servers off-cloud), not an error.
    async fn http_probe(
        &self,
        method: &str,
        url: &str,
        headers: Vec<(String, String)>,
        body: Option<Vec<u8>>,
        timeout_secs: u64,
    ) -> Option<(u16, Vec<(String, String)>, Vec<u8>)> {
        self.http(method, url, headers, body, timeout_secs)
            .await
            .ok()
    }

    async fn run(&self, argv: Vec<String>, timeout_secs: u64) -> Result<String, AuthError> {
        if !self.subprocess {
            return Err(not_configured(
                "this credential source needs to run a command".into(),
            ));
        }
        let env = self.env.clone();
        let handle = tokio::task::spawn_blocking(move || {
            let (program, args) = argv.split_first().ok_or("empty command")?;
            let output = std::process::Command::new(program)
                .args(args)
                .env_clear()
                .envs(env)
                .stdin(std::process::Stdio::null())
                .output()
                .map_err(|err| format!("{program}: {err}"))?;
            if !output.status.success() {
                return Err(format!("{program}: exit status {}", output.status));
            }
            Ok(String::from_utf8_lossy(&output.stdout).into_owned())
        });
        let joined = tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), handle)
            .await
            .map_err(|_| AuthError::Rejected {
                provider: None,
                message: "credential command timed out".into(),
                hint: None,
            })?
            .map_err(|err| AuthError::Rejected {
                provider: None,
                message: format!("credential command failed: {err}"),
                hint: None,
            })?;
        joined.map_err(|message| AuthError::Rejected {
            provider: None,
            message,
            hint: None,
        })
    }
}

fn is_executable(path: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::metadata(path)
            .map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
            .unwrap_or(false)
    }
    #[cfg(not(unix))]
    {
        path.is_file()
    }
}

fn not_configured(message: String) -> AuthError {
    AuthError::NotConfigured {
        provider: None,
        message,
        hint: None,
    }
}

fn not_configured_hint(message: String, hint: &str) -> AuthError {
    AuthError::NotConfigured {
        provider: None,
        message,
        hint: Some(hint.to_string()),
    }
}

fn rejected(message: String) -> AuthError {
    AuthError::Rejected {
        provider: None,
        message,
        hint: None,
    }
}

// ─── Rungs and steps ─────────────────────────────────────────────────

/// The rung kinds of AUTH-11.
pub const RUNG_KINDS: &[&str] = &[
    "env",
    "ini-profile",
    "json-file",
    "file-cache",
    "sigv4-sts",
    "unsigned-sts",
    "http-token-exchange",
    "http-metadata",
    "jwt-rs256",
    "subprocess",
];

/// What a rung needs beyond files: nothing, the network, or a command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Needs {
    Offline,
    Network,
    Subprocess,
}

/// One rung of a chain: the fixture kind (`name`), the AUTH-11 kind, a
/// human label, and what it needs.
#[derive(Debug, Clone)]
pub struct Rung {
    pub name: String,
    pub kind: &'static str,
    pub source: String,
    pub needs: Needs,
    id: RungId,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RungId {
    DoorKey,
    // AWS
    AwsStaticEnv,
    AssumeRole,
    WebIdentity,
    Sso,
    SharedCredentialsFile,
    Login,
    CredentialProcess,
    ConfigFile,
    Container,
    Imds,
    // Azure
    AzureEnvironment,
    AzureWorkload,
    AzureManagedIdentity,
    AzCli,
    Pwsh,
    Azd,
    // GCP
    AdcEnv,
    AdcFile,
    GceMetadata,
    Gcloud,
}

/// The probe verdict of a rung, offline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
    Usable,
    Configured,
    Absent,
}

/// One row of the doctor's report.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Step {
    pub kind: String,
    pub source: String,
    pub detail: String,
    /// `selected` | `shadowed` | `absent` | `unprobed`
    pub state: &'static str,
}

fn rung(name: &str, kind: &'static str, source: &str, needs: Needs, id: RungId) -> Rung {
    Rung {
        name: name.to_string(),
        kind,
        source: source.to_string(),
        needs,
        id,
    }
}

/// The chain of a cloud policy, in resolution order.
pub fn chain_for(policy: &AccessPolicy) -> Result<Vec<Rung>, AuthError> {
    let door_key = policy.env_keys.first().copied();
    let mut rungs = Vec::new();
    if let Some(key) = door_key {
        rungs.push(rung(
            &format!("env:{key}"),
            "env",
            &format!("env ${key}"),
            Needs::Offline,
            RungId::DoorKey,
        ));
    }
    match policy.credential_policy {
        CredentialPolicy::AwsChain => rungs.extend([
            rung(
                "env:AWS_ACCESS_KEY_ID",
                "env",
                "env $AWS_ACCESS_KEY_ID (+SECRET, +SESSION_TOKEN)",
                Needs::Offline,
                RungId::AwsStaticEnv,
            ),
            rung(
                "assume-role",
                "sigv4-sts",
                "profile assume-role via STS",
                Needs::Network,
                RungId::AssumeRole,
            ),
            rung(
                "web-identity",
                "unsigned-sts",
                "web identity via STS",
                Needs::Network,
                RungId::WebIdentity,
            ),
            rung(
                "sso",
                "file-cache",
                "IAM Identity Center (~/.aws/sso/cache)",
                Needs::Network,
                RungId::Sso,
            ),
            rung(
                "shared-credentials-file",
                "ini-profile",
                "~/.aws/credentials",
                Needs::Offline,
                RungId::SharedCredentialsFile,
            ),
            rung(
                "login",
                "file-cache",
                "aws login session (~/.aws/login/cache)",
                Needs::Offline,
                RungId::Login,
            ),
            rung(
                "credential_process",
                "subprocess",
                "profile credential_process",
                Needs::Subprocess,
                RungId::CredentialProcess,
            ),
            rung(
                "config-file",
                "ini-profile",
                "~/.aws/config static keys",
                Needs::Offline,
                RungId::ConfigFile,
            ),
            rung(
                "container",
                "http-metadata",
                "container credentials endpoint",
                Needs::Network,
                RungId::Container,
            ),
            rung(
                "imds",
                "http-metadata",
                "EC2 instance metadata (IMDSv2)",
                Needs::Network,
                RungId::Imds,
            ),
        ]),
        CredentialPolicy::AzureChain => rungs.extend([
            rung(
                "environment",
                "http-token-exchange",
                "Entra service principal from AZURE_* env",
                Needs::Network,
                RungId::AzureEnvironment,
            ),
            rung(
                "workload-identity",
                "http-token-exchange",
                "Entra workload identity",
                Needs::Network,
                RungId::AzureWorkload,
            ),
            rung(
                "managed-identity",
                "http-metadata",
                "Azure managed identity",
                Needs::Network,
                RungId::AzureManagedIdentity,
            ),
            rung(
                "az",
                "subprocess",
                "az account get-access-token",
                Needs::Subprocess,
                RungId::AzCli,
            ),
            rung(
                "pwsh",
                "subprocess",
                "Azure PowerShell Get-AzAccessToken",
                Needs::Subprocess,
                RungId::Pwsh,
            ),
            rung(
                "azd",
                "subprocess",
                "azd auth token",
                Needs::Subprocess,
                RungId::Azd,
            ),
        ]),
        CredentialPolicy::GcpChain => rungs.extend([
            rung(
                "adc-env",
                "json-file",
                "GOOGLE_APPLICATION_CREDENTIALS file",
                Needs::Network,
                RungId::AdcEnv,
            ),
            rung(
                "adc-file",
                "json-file",
                "gcloud application default credentials file",
                Needs::Network,
                RungId::AdcFile,
            ),
            rung(
                "metadata",
                "http-metadata",
                "GCE metadata server",
                Needs::Network,
                RungId::GceMetadata,
            ),
            rung(
                "gcloud",
                "subprocess",
                "gcloud auth print-access-token",
                Needs::Subprocess,
                RungId::Gcloud,
            ),
        ]),
        _ => {
            return Err(not_configured(format!(
                "{}: not a cloud chain policy",
                policy.provider
            )))
        }
    }
    Ok(rungs)
}

// ─── Helpers ─────────────────────────────────────────────────────────

fn json_body(body: &[u8]) -> Map<String, Value> {
    match serde_json::from_slice::<Value>(body) {
        Ok(Value::Object(map)) => map,
        _ => Map::new(),
    }
}

fn form(pairs: &[(String, String)]) -> Vec<u8> {
    let encoded: Vec<String> = pairs
        .iter()
        .map(|(k, v)| format!("{}={}", form_encode(k), form_encode(v)))
        .collect();
    encoded.join("&").into_bytes()
}

/// `urllib.parse.urlencode` (quote_plus): unreserved `-_.~` and
/// alphanumerics verbatim, space as `+`, the rest `%XX`.
fn form_encode(text: &str) -> String {
    let mut out = String::new();
    for byte in text.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char)
            }
            b' ' => out.push('+'),
            other => out.push_str(&format!("%{other:02X}")),
        }
    }
    out
}

fn value_str(value: Option<&Value>) -> Option<String> {
    match value? {
        Value::String(s) if !s.is_empty() => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        Value::Bool(b) => Some(b.to_string()),
        _ => None,
    }
}

fn expires_from(now: i64, seconds: Option<&Value>) -> Option<i64> {
    let seconds = match seconds? {
        Value::Number(n) => n.as_f64()?,
        Value::String(s) => s.trim().parse::<f64>().ok()?,
        _ => return None,
    };
    Some(now + seconds as i64)
}

/// AUTH-21 (clarified 2026-09-24): from a failed auth-endpoint exchange
/// only the status and, when the reply's `error` (or `error.code` /
/// `error.type`) is one of these fixed words, that word. An error
/// description can reflect the request (a refresh token, a signed
/// assertion); a fixed word cannot.
const OAUTH_ERROR_WORDS: &[&str] = &[
    "invalid_request",
    "invalid_client",
    "invalid_grant",
    "unauthorized_client",
    "unsupported_grant_type",
    "invalid_scope",
    "access_denied",
    "server_error",
    "temporarily_unavailable",
    "authorization_pending",
    "slow_down",
    "expired_token",
];

fn oauth_error_word(data: &Map<String, Value>) -> Option<&'static str> {
    let candidates: Vec<Option<&Value>> = match data.get("error") {
        Some(Value::Object(err)) => vec![err.get("code"), err.get("type")],
        other => vec![other],
    };
    candidates
        .into_iter()
        .flatten()
        .filter_map(Value::as_str)
        .find_map(|w| OAUTH_ERROR_WORDS.iter().copied().find(|known| *known == w))
}

async fn exchange(
    ctx: &ChainContext,
    method: &str,
    url: &str,
    headers: Vec<(String, String)>,
    body: Option<Vec<u8>>,
    what: &str,
) -> Result<Map<String, Value>, AuthError> {
    exchange_hint(ctx, method, url, headers, body, what, None).await
}

/// One token-endpoint round trip. A refusal carries the status, a fixed
/// OAuth word (AUTH-21, in the message: `AuthError::Rejected` has no code
/// field) and, when the caller knows it, the one action that fixes it.
async fn exchange_hint(
    ctx: &ChainContext,
    method: &str,
    url: &str,
    headers: Vec<(String, String)>,
    body: Option<Vec<u8>>,
    what: &str,
    hint: Option<String>,
) -> Result<Map<String, Value>, AuthError> {
    let (status, _, raw) = ctx.http(method, url, headers, body, 30).await?;
    if !(200..300).contains(&status) {
        let word = oauth_error_word(&json_body(&raw))
            .map(|w| format!(" ({w})"))
            .unwrap_or_default();
        return Err(AuthError::Rejected {
            provider: None,
            message: format!("{what}: HTTP {status}{word}"),
            hint,
        });
    }
    Ok(json_body(&raw))
}

fn gcp_user_login_hint(where_: &str) -> String {
    format!(
        "the saved Google login in {where_} has expired or was revoked; run \
         `gcloud auth application-default login` (Google ends these sessions on its own schedule)"
    )
}

/// `_bearer_from_oauth`: `access_token`, expiry from `expires_on` (Unix
/// seconds) else `expires_in` (seconds from now).
pub fn bearer_from_oauth(
    data: &Map<String, Value>,
    now: i64,
    what: &str,
) -> Result<Credential, AuthError> {
    let token = value_str(data.get("access_token"))
        .ok_or_else(|| rejected(format!("{what}: no valid access_token in response")))?;
    let mut expires = data
        .get("expires_on")
        .filter(|v| !v.is_null() && v.as_str() != Some(""))
        .and_then(|v| match v {
            Value::Number(n) => n.as_f64().map(|f| f as i64),
            Value::String(s) => s.trim().parse::<f64>().ok().map(|f| f as i64),
            _ => None,
        });
    if expires.is_none() {
        expires = expires_from(
            now,
            data.get("expires_in").filter(|v| v.as_str() != Some("")),
        );
    }
    Credential::bearer_token(token, expires)
}

// ─── AWS ─────────────────────────────────────────────────────────────

struct AwsConfig {
    credentials: Ini,
    config: Ini,
    profile: String,
}

fn aws_config(ctx: &ChainContext) -> Result<AwsConfig, AuthError> {
    let profile = ctx.env("AWS_PROFILE").unwrap_or("default").to_string();
    let creds_path = ctx
        .env("AWS_SHARED_CREDENTIALS_FILE")
        .unwrap_or("~/.aws/credentials");
    let conf_path = ctx.env("AWS_CONFIG_FILE").unwrap_or("~/.aws/config");
    let credentials = match ctx.read(creds_path) {
        Some(text) => Ini::parse(&text)?,
        None => Ini::default(),
    };
    let config = match ctx.read(conf_path) {
        Some(text) => Ini::parse(&text)?,
        None => Ini::default(),
    };
    Ok(AwsConfig {
        credentials,
        config,
        profile,
    })
}

fn aws_profile_section(conf: &Ini, profile: &str) -> Section {
    let name = if profile == "default" {
        profile.to_string()
    } else {
        format!("profile {profile}")
    };
    conf.section(&name)
        .or_else(|| conf.section(profile))
        .cloned()
        .unwrap_or_default()
}

fn get<'a>(section: &'a Section, key: &str) -> Option<&'a str> {
    section
        .get(key)
        .map(String::as_str)
        .filter(|v| !v.is_empty())
}

fn aws_static(section: &Section) -> Option<Credential> {
    let key = get(section, "aws_access_key_id")?;
    let secret = get(section, "aws_secret_access_key")?;
    Credential::aws(
        key,
        secret,
        get(section, "aws_session_token").map(str::to_string),
        None,
    )
    .ok()
}

/// `_aws_from_response`: a credential object in any of the AWS spellings
/// (IMDS, container, credential_process, SSO, login cache).
pub fn aws_from_response(data: &Map<String, Value>) -> Result<Credential, AuthError> {
    let raw = data.get("Expiration").or_else(|| data.get("expiration"));
    let expires = match raw {
        Some(Value::String(text)) => parse_rfc3339(text),
        Some(Value::Number(n)) => n.as_f64().map(|f| {
            if f > 1e11 {
                (f / 1000.0) as i64
            } else {
                f as i64
            }
        }),
        _ => None,
    };
    let key = value_str(data.get("AccessKeyId").or_else(|| data.get("accessKeyId")));
    let secret = value_str(
        data.get("SecretAccessKey")
            .or_else(|| data.get("secretAccessKey")),
    );
    let (Some(key), Some(secret)) = (key, secret) else {
        return Err(rejected(
            "AWS credential response lacks access key id or secret access key".into(),
        ));
    };
    let session = value_str(
        data.get("SessionToken")
            .or_else(|| data.get("Token"))
            .or_else(|| data.get("sessionToken")),
    );
    Credential::aws(key, secret, session, expires)
}

/// The `Credentials` element of an STS XML response.
fn sts_xml_credentials(raw: &[u8]) -> Result<Credential, AuthError> {
    let text = String::from_utf8_lossy(raw);
    let tag = |name: &str| -> Option<String> {
        let open = format!("<{name}>");
        let close = format!("</{name}>");
        let start = text.find(&open)? + open.len();
        let end = text[start..].find(&close)? + start;
        Some(xml_unescape(text[start..end].trim()))
    };
    if !text.contains("<Credentials>") {
        return Err(rejected("STS: no Credentials in response".into()));
    }
    let key = tag("AccessKeyId").unwrap_or_default();
    let secret = tag("SecretAccessKey").unwrap_or_default();
    Credential::aws(
        key,
        secret,
        tag("SessionToken").filter(|s| !s.is_empty()),
        tag("Expiration").and_then(|e| parse_rfc3339(&e)),
    )
}

fn xml_unescape(text: &str) -> String {
    text.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&apos;", "'")
        .replace("&amp;", "&")
}

fn aws_region(ctx: &ChainContext, section: Option<&Section>) -> String {
    ctx.settings
        .get("region")
        .cloned()
        .filter(|r| !r.is_empty())
        .or_else(|| ctx.env("AWS_REGION").map(str::to_string))
        .or_else(|| ctx.env("AWS_DEFAULT_REGION").map(str::to_string))
        .or_else(|| section.and_then(|s| get(s, "region")).map(str::to_string))
        .unwrap_or_else(|| "us-east-1".into())
}

fn session_name() -> String {
    format!("lm15-{}", &crate::surfaces::boundary()[5..17])
}

fn aws_source_credentials<'a>(
    ctx: &'a ChainContext,
    section: &'a Section,
    depth: u32,
) -> BoxFuture<'a, Result<Credential, AuthError>> {
    Box::pin(async move {
        if depth > 5 {
            return Err(rejected(
                "assume-role: source_profile chain too deep".into(),
            ));
        }
        if let Some(source_profile) = get(section, "source_profile") {
            let cfg = aws_config(ctx)?;
            let mut sub = aws_profile_section(&cfg.config, source_profile);
            if let Some(creds) = cfg.credentials.section(source_profile) {
                sub.extend(creds.clone());
            }
            if get(&sub, "role_arn").is_some() {
                return assume_role(ctx, &sub, depth + 1).await;
            }
            return aws_static(&sub).ok_or_else(|| {
                not_configured(format!(
                    "assume-role: source_profile {source_profile:?} has no keys"
                ))
            });
        }
        match get(section, "credential_source") {
            Some("Environment") => env_aws(ctx).ok_or_else(|| {
                not_configured(
                    "assume-role: credential_source=Environment but AWS_ACCESS_KEY_ID is not set"
                        .into(),
                )
            }),
            Some("EcsContainer") => container_acquire(ctx).await?.ok_or_else(|| {
                not_configured(
                    "assume-role: credential_source=EcsContainer but no container endpoint is configured"
                        .into(),
                )
            }),
            Some("Ec2InstanceMetadata") => imds_acquire(ctx).await?.ok_or_else(|| {
                not_configured(
                    "assume-role: credential_source=Ec2InstanceMetadata but IMDS answered nothing"
                        .into(),
                )
            }),
            _ => Err(not_configured(
                "assume-role: profile needs source_profile or credential_source".into(),
            )),
        }
    })
}

fn assume_role<'a>(
    ctx: &'a ChainContext,
    section: &'a Section,
    depth: u32,
) -> BoxFuture<'a, Result<Credential, AuthError>> {
    Box::pin(async move {
        let source = aws_source_credentials(ctx, section, depth).await?;
        let region = aws_region(ctx, Some(section));
        let url = format!("https://sts.{region}.amazonaws.com/");
        let mut pairs = vec![
            ("Action".to_string(), "AssumeRole".to_string()),
            ("Version".to_string(), "2011-06-15".to_string()),
            (
                "RoleArn".to_string(),
                get(section, "role_arn").unwrap_or("").to_string(),
            ),
            (
                "RoleSessionName".to_string(),
                get(section, "role_session_name")
                    .map(str::to_string)
                    .unwrap_or_else(session_name),
            ),
        ];
        if let Some(external) = get(section, "external_id") {
            pairs.push(("ExternalId".into(), external.into()));
        }
        if let Some(duration) = get(section, "duration_seconds") {
            pairs.push(("DurationSeconds".into(), duration.into()));
        }
        let body = form(&pairs);
        let headers = vec![(
            "content-type".to_string(),
            "application/x-www-form-urlencoded".to_string(),
        )];
        let keys =
            AwsKeys::from_credential(&source).map_err(|err| rejected(err.message().to_string()))?;
        let signed = sigv4::sign(
            &SigningRequest {
                method: "POST",
                url: &url,
                headers: &headers,
                payload: &body,
            },
            &keys,
            &region,
            "sts",
            ctx.now,
        );
        let (status, _, raw) = ctx
            .http("POST", &url, signed.headers, Some(body), 30)
            .await?;
        if status >= 400 {
            return Err(rejected(format!("STS AssumeRole: HTTP {status}")));
        }
        sts_xml_credentials(&raw)
    })
}

fn env_aws(ctx: &ChainContext) -> Option<Credential> {
    let key = ctx.env("AWS_ACCESS_KEY_ID")?;
    let secret = ctx.env("AWS_SECRET_ACCESS_KEY")?;
    Credential::aws(
        key,
        secret,
        ctx.env("AWS_SESSION_TOKEN").map(str::to_string),
        None,
    )
    .ok()
}

fn web_identity_config(ctx: &ChainContext) -> Result<Option<(String, String, String)>, AuthError> {
    if let (Some(file), Some(role)) = (
        ctx.env("AWS_WEB_IDENTITY_TOKEN_FILE"),
        ctx.env("AWS_ROLE_ARN"),
    ) {
        let session = ctx.env("AWS_ROLE_SESSION_NAME").unwrap_or("").to_string();
        return Ok(Some((file.to_string(), role.to_string(), session)));
    }
    let cfg = aws_config(ctx)?;
    let section = aws_profile_section(&cfg.config, &cfg.profile);
    match (
        get(&section, "web_identity_token_file"),
        get(&section, "role_arn"),
    ) {
        (Some(file), Some(role))
            if get(&section, "source_profile").is_none()
                && get(&section, "credential_source").is_none() =>
        {
            Ok(Some((
                file.to_string(),
                role.to_string(),
                get(&section, "role_session_name").unwrap_or("").to_string(),
            )))
        }
        _ => Ok(None),
    }
}

async fn web_identity_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    let Some((token_file, role, session)) = web_identity_config(ctx)? else {
        return Ok(None);
    };
    let token = ctx.read(&token_file).ok_or_else(|| {
        not_configured(format!(
            "web identity token file {token_file} is unreadable"
        ))
    })?;
    let region = aws_region(ctx, None);
    let body = form(&[
        ("Action".into(), "AssumeRoleWithWebIdentity".into()),
        ("Version".into(), "2011-06-15".into()),
        ("RoleArn".into(), role),
        (
            "RoleSessionName".into(),
            if session.is_empty() {
                session_name()
            } else {
                session
            },
        ),
        ("WebIdentityToken".into(), token.trim().into()),
    ]);
    let (status, _, raw) = ctx
        .http(
            "POST",
            &format!("https://sts.{region}.amazonaws.com/"),
            vec![(
                "content-type".into(),
                "application/x-www-form-urlencoded".into(),
            )],
            Some(body),
            30,
        )
        .await?;
    if status >= 400 {
        return Err(rejected(format!(
            "STS AssumeRoleWithWebIdentity: HTTP {status}"
        )));
    }
    sts_xml_credentials(&raw).map(Some)
}

fn sha1_hex(text: &str) -> String {
    let digest = aws_lc_rs::digest::digest(
        &aws_lc_rs::digest::SHA1_FOR_LEGACY_USE_ONLY,
        text.as_bytes(),
    );
    digest.as_ref().iter().map(|b| format!("{b:02x}")).collect()
}

fn sso_config(ctx: &ChainContext) -> Result<Option<Section>, AuthError> {
    let cfg = aws_config(ctx)?;
    let section = aws_profile_section(&cfg.config, &cfg.profile);
    if let Some(name) = get(&section, "sso_session") {
        let sess = cfg
            .config
            .section(&format!("sso-session {name}"))
            .cloned()
            .unwrap_or_default();
        if get(&sess, "sso_start_url").is_none() {
            return Ok(None);
        }
        let mut merged = sess;
        merged.extend(section.clone());
        merged.insert("cache_key".into(), sha1_hex(name));
        merged.insert("session_name".into(), name.to_string());
        return Ok(Some(merged));
    }
    if let Some(start_url) = get(&section, "sso_start_url") {
        let mut merged = section.clone();
        merged.insert("cache_key".into(), sha1_hex(start_url));
        return Ok(Some(merged));
    }
    Ok(None)
}

async fn sso_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    let Some(cfg) = sso_config(ctx)? else {
        return Ok(None);
    };
    let cache_key = get(&cfg, "cache_key").unwrap_or("");
    let raw = ctx
        .read(&format!("~/.aws/sso/cache/{cache_key}.json"))
        .ok_or_else(|| {
            not_configured_hint(
                "IAM Identity Center: no cached token; run `aws sso login`".into(),
                "aws sso login",
            )
        })?;
    let token = json_body(raw.as_bytes());
    let expires = value_str(token.get("expiresAt")).and_then(|e| parse_rfc3339(&e));
    let mut access = value_str(token.get("accessToken"));
    let sso_region = get(&cfg, "sso_region").unwrap_or("us-east-1").to_string();
    if access.is_none() || expires.is_some_and(|e| e - ctx.now <= SKEW_SECONDS) {
        let (Some(refresh), Some(client_id), Some(client_secret)) = (
            value_str(token.get("refreshToken")),
            value_str(token.get("clientId")),
            value_str(token.get("clientSecret")),
        ) else {
            return Err(not_configured_hint(
                "IAM Identity Center: token expired and not refreshable; run `aws sso login`"
                    .into(),
                "aws sso login",
            ));
        };
        let body = json!({"clientId": client_id, "clientSecret": client_secret, "grantType": "refresh_token", "refreshToken": refresh});
        let data = exchange(
            ctx,
            "POST",
            &format!("https://oidc.{sso_region}.amazonaws.com/token"),
            vec![("content-type".into(), "application/json".into())],
            Some(serde_json::to_vec(&body).expect("serializes")),
            "sso-oidc CreateToken",
        )
        .await?;
        access = value_str(data.get("accessToken"));
        if access.is_none() {
            return Err(rejected("sso-oidc CreateToken: no accessToken".into()));
        }
    }
    let (Some(account), Some(role)) = (get(&cfg, "sso_account_id"), get(&cfg, "sso_role_name"))
    else {
        return Err(not_configured(
            "IAM Identity Center: profile needs sso_account_id and sso_role_name".into(),
        ));
    };
    let query = form(&[
        ("role_name".into(), role.into()),
        ("account_id".into(), account.into()),
    ]);
    let (status, _, raw) = ctx
        .http(
            "GET",
            &format!(
                "https://portal.sso.{sso_region}.amazonaws.com/federation/credentials?{}",
                String::from_utf8_lossy(&query)
            ),
            vec![("x-amz-sso_bearer_token".into(), access.unwrap_or_default())],
            None,
            30,
        )
        .await?;
    if status >= 400 {
        return Err(rejected(format!("sso GetRoleCredentials: HTTP {status}")));
    }
    let creds = json_body(&raw)
        .get("roleCredentials")
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    aws_from_response(&creds).map(Some)
}

fn login_config(ctx: &ChainContext) -> Result<Option<String>, AuthError> {
    let cfg = aws_config(ctx)?;
    Ok(get(
        &aws_profile_section(&cfg.config, &cfg.profile),
        "login_session",
    )
    .map(str::to_string))
}

fn login_cached(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    let Some(session) = login_config(ctx)? else {
        return Ok(None);
    };
    let directory = ctx
        .env("AWS_LOGIN_CACHE_DIRECTORY")
        .unwrap_or("~/.aws/login/cache");
    let hash: String = Sha256::digest(session.as_bytes())
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect();
    let Some(raw) = ctx.read(&format!("{directory}/{hash}.json")) else {
        return Ok(None);
    };
    let token = json_body(raw.as_bytes())
        .get("accessToken")
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    if value_str(token.get("accessKeyId")).is_none() {
        return Ok(None);
    }
    let mut data = Map::new();
    for (from, to) in [
        ("accessKeyId", "AccessKeyId"),
        ("secretAccessKey", "SecretAccessKey"),
        ("sessionToken", "SessionToken"),
        ("expiresAt", "Expiration"),
    ] {
        if let Some(v) = token.get(from) {
            data.insert(to.into(), v.clone());
        }
    }
    aws_from_response(&data).map(Some)
}

fn login_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    if login_config(ctx)?.is_none() {
        return Ok(None);
    }
    if let Some(cached) = login_cached(ctx)? {
        if !cached.is_expired_at(ctx.now) {
            return Ok(Some(cached));
        }
    }
    // Refresh needs the signin CreateOAuth2Token call with a DPoP proof over
    // the cached EC key (botocore LoginCredentialFetcher): a stated gap.
    Err(not_configured_hint(
        "AWS login session expired; run `aws login`".into(),
        "aws login",
    ))
}

/// POSIX `shlex.split`: whitespace-separated words, single and double
/// quotes, backslash escapes.
pub fn shlex_split(command: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut word = String::new();
    let mut in_word = false;
    let mut quote: Option<char> = None;
    let mut chars = command.chars().peekable();
    while let Some(c) = chars.next() {
        match quote {
            Some('\'') => {
                if c == '\'' {
                    quote = None;
                } else {
                    word.push(c);
                }
            }
            Some('"') => match c {
                '"' => quote = None,
                '\\' => match chars.next() {
                    Some(n @ ('"' | '\\' | '$' | '`')) => word.push(n),
                    Some(n) => {
                        word.push('\\');
                        word.push(n);
                    }
                    None => word.push('\\'),
                },
                other => word.push(other),
            },
            _ => match c {
                '\'' | '"' => {
                    quote = Some(c);
                    in_word = true;
                }
                '\\' => {
                    if let Some(n) = chars.next() {
                        word.push(n);
                        in_word = true;
                    }
                }
                c if c.is_whitespace() => {
                    if in_word {
                        out.push(std::mem::take(&mut word));
                        in_word = false;
                    }
                }
                other => {
                    word.push(other);
                    in_word = true;
                }
            },
        }
    }
    if in_word {
        out.push(word);
    }
    out
}

async fn process_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    let cfg = aws_config(ctx)?;
    let Some(command) = get(
        &aws_profile_section(&cfg.config, &cfg.profile),
        "credential_process",
    )
    .map(str::to_string) else {
        return Ok(None);
    };
    if !ctx.subprocess {
        return Ok(None);
    }
    let out = ctx.run(shlex_split(&command), 60).await?;
    let data = json_body(out.as_bytes());
    if data.get("Version").and_then(Value::as_i64) != Some(1) {
        return Err(rejected(
            "credential_process: output Version must be 1".into(),
        ));
    }
    aws_from_response(&data).map(Some)
}

const CONTAINER_ALLOWED: &[&str] = &[
    "169.254.170.2",
    "169.254.170.23",
    "fd00:ec2::23",
    "localhost",
];

fn container_config(ctx: &ChainContext) -> Result<Option<String>, AuthError> {
    if let Some(rel) = ctx.env("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI") {
        if !rel.starts_with('/')
            || rel.starts_with("//")
            || rel.contains(['\\', '\r', '\n', '\t', '#'])
        {
            return Err(not_configured(
                "container credentials relative URI must be an absolute path".into(),
            ));
        }
        return Ok(Some(format!("http://169.254.170.2{rel}")));
    }
    if let Some(full) = ctx.env("AWS_CONTAINER_CREDENTIALS_FULL_URI") {
        let (scheme, rest) = full.split_once("://").ok_or_else(|| {
            not_configured(
                "container credentials URI must be HTTP(S), without userinfo or fragment".into(),
            )
        })?;
        let authority = rest.split(['/', '?']).next().unwrap_or("");
        let host = authority
            .rsplit_once('@')
            .map(|_| "")
            .unwrap_or(authority)
            .trim_start_matches('[')
            .split([']', ':'])
            .next()
            .unwrap_or("")
            .to_string();
        let host = if authority.starts_with('[') {
            authority[1..authority.find(']').unwrap_or(authority.len())].to_string()
        } else {
            host
        };
        if !matches!(scheme, "http" | "https")
            || host.is_empty()
            || authority.contains('@')
            || full.contains('#')
        {
            return Err(not_configured(
                "container credentials URI must be HTTP(S), without userinfo or fragment".into(),
            ));
        }
        let loopback = host == "127.0.0.1" || host == "::1" || host.starts_with("127.");
        if scheme != "https" && !loopback && !CONTAINER_ALLOWED.contains(&host.as_str()) {
            return Err(not_configured(format!(
                "Unsupported host {host:?}. Can only retrieve metadata from a loopback address or one of these hosts: {}",
                CONTAINER_ALLOWED.join(", ")
            )));
        }
        return Ok(Some(full.to_string()));
    }
    Ok(None)
}

async fn container_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    let Some(url) = container_config(ctx)? else {
        return Ok(None);
    };
    if ctx.is_offline() {
        return Ok(None);
    }
    let mut headers = Vec::new();
    let mut token = ctx
        .env("AWS_CONTAINER_AUTHORIZATION_TOKEN")
        .map(str::to_string);
    if token.is_none() {
        if let Some(file) = ctx.env("AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE") {
            token = ctx.read(file).map(|t| t.trim().to_string());
        }
    }
    if let Some(token) = token.filter(|t| !t.is_empty()) {
        headers.push(("Authorization".into(), token));
    }
    let (status, _, raw) = ctx.http("GET", &url, headers, None, 5).await?;
    if status >= 400 {
        return Err(rejected(format!("container credentials: HTTP {status}")));
    }
    aws_from_response(&json_body(&raw)).map(Some)
}

fn imds_disabled(ctx: &ChainContext) -> bool {
    ctx.env("AWS_EC2_METADATA_DISABLED")
        .map(|v| v.trim().eq_ignore_ascii_case("true"))
        .unwrap_or(false)
}

async fn imds_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    if imds_disabled(ctx) || ctx.is_offline() {
        return Ok(None);
    }
    let base = ctx
        .env("AWS_EC2_METADATA_SERVICE_ENDPOINT")
        .map(str::to_string)
        .unwrap_or_else(|| {
            if ctx
                .env("AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE")
                .is_some_and(|m| m.eq_ignore_ascii_case("ipv6"))
            {
                "http://[fd00:ec2::254]".into()
            } else {
                "http://169.254.169.254".into()
            }
        });
    let base = base.trim_end_matches('/').to_string();
    let Some((status, _, tok)) = ctx
        .http_probe(
            "PUT",
            &format!("{base}/latest/api/token"),
            vec![(
                "X-aws-ec2-metadata-token-ttl-seconds".into(),
                "21600".into(),
            )],
            None,
            1,
        )
        .await
    else {
        return Ok(None); // not on EC2: absent, not an error
    };
    if status != 200 {
        return Ok(None);
    }
    let headers = vec![(
        "X-aws-ec2-metadata-token".to_string(),
        String::from_utf8_lossy(&tok).into_owned(),
    )];
    let (status, _, role) = ctx
        .http(
            "GET",
            &format!("{base}/latest/meta-data/iam/security-credentials/"),
            headers.clone(),
            None,
            1,
        )
        .await?;
    let role = String::from_utf8_lossy(&role).trim().to_string();
    if status != 200 || role.is_empty() {
        return Ok(None);
    }
    let role = role.lines().next().unwrap_or("").trim().to_string();
    let (status, _, raw) = ctx
        .http(
            "GET",
            &format!("{base}/latest/meta-data/iam/security-credentials/{role}"),
            headers,
            None,
            1,
        )
        .await?;
    if status != 200 {
        return Ok(None);
    }
    let data = json_body(&raw);
    if data
        .get("Code")
        .is_some_and(|c| c.as_str() != Some("Success"))
    {
        return Err(rejected("IMDS rejected the credential request".into()));
    }
    aws_from_response(&data).map(Some)
}

// ─── Azure ───────────────────────────────────────────────────────────

fn azure_authority(ctx: &ChainContext) -> String {
    ctx.settings
        .get("authority_host")
        .cloned()
        .filter(|v| !v.is_empty())
        .or_else(|| ctx.env("AZURE_AUTHORITY_HOST").map(str::to_string))
        .unwrap_or_else(|| "https://login.microsoftonline.com".into())
        .trim_end_matches('/')
        .to_string()
}

fn azure_scope(ctx: &ChainContext) -> String {
    ctx.settings
        .get("scope")
        .cloned()
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| "https://ai.azure.com/.default".into())
}

fn azure_token_url(ctx: &ChainContext, tenant: &str) -> String {
    format!("{}/{tenant}/oauth2/v2.0/token", azure_authority(ctx))
}

/// The Entra client assertion: RS256, `x5t` = base64url SHA-1 of the DER
/// certificate, claims in MSAL's order, 600 s lifetime.
pub fn azure_certificate_assertion(
    ctx: &ChainContext,
    tenant: &str,
    client_id: &str,
    pem: &str,
    jti: Option<&str>,
    send_chain: bool,
) -> Result<String, AuthError> {
    let key = rs256::load_private_key(pem)?;
    let der = rs256::certificate_der(pem)?;
    let now = ctx.now;
    let mut header = Map::new();
    header.insert("alg".into(), json!("RS256"));
    header.insert("typ".into(), json!("JWT"));
    header.insert("x5t".into(), json!(rs256::x5t(&der)));
    if send_chain {
        header.insert("x5c".into(), json!([crate::types::base64_encode(&der)]));
    }
    let payload = json!({
        "aud": azure_token_url(ctx, tenant),
        "iss": client_id,
        "sub": client_id,
        "exp": now + 600,
        "iat": now,
        "jti": jti.map(str::to_string).unwrap_or_else(uuid4),
    });
    rs256::jwt_encode(&Value::Object(header), &payload, &key)
}

/// A random UUIDv4 string from the boundary generator's entropy.
fn uuid4() -> String {
    let hex = crate::surfaces::boundary()[5..].to_string();
    let hex = format!("{hex}{}", &crate::surfaces::boundary()[5..]);
    format!(
        "{}-{}-4{}-{}{}-{}",
        &hex[0..8],
        &hex[8..12],
        &hex[13..16],
        "8",
        &hex[17..20],
        &hex[20..32]
    )
}

fn azure_environment_kind(ctx: &ChainContext) -> Option<&'static str> {
    if ctx.env("AZURE_TENANT_ID").is_none() || ctx.env("AZURE_CLIENT_ID").is_none() {
        return None;
    }
    if ctx.env("AZURE_CLIENT_SECRET").is_some() {
        return Some("secret");
    }
    if ctx.env("AZURE_CLIENT_CERTIFICATE_PATH").is_some() {
        return Some("certificate");
    }
    None
}

/// (token URL, form pairs) for the environment service principal.
pub fn azure_environment_request(
    ctx: &ChainContext,
    jti: Option<&str>,
) -> Result<(String, Vec<(String, String)>), AuthError> {
    let kind = azure_environment_kind(ctx);
    let tenant = ctx.env("AZURE_TENANT_ID").unwrap_or("").to_string();
    let client = ctx.env("AZURE_CLIENT_ID").unwrap_or("").to_string();
    let url = azure_token_url(ctx, &tenant);
    let scope = azure_scope(ctx);
    match kind {
        Some("secret") => Ok((
            url,
            vec![
                ("client_id".into(), client),
                ("scope".into(), scope),
                ("client_secret".into(), ctx.env("AZURE_CLIENT_SECRET").unwrap_or("").into()),
                ("grant_type".into(), "client_credentials".into()),
            ],
        )),
        Some("certificate") => {
            let path = ctx.env("AZURE_CLIENT_CERTIFICATE_PATH").unwrap_or("");
            let pem = ctx
                .read(path)
                .ok_or_else(|| not_configured(format!("AZURE_CLIENT_CERTIFICATE_PATH {path} is unreadable")))?;
            if ctx.env("AZURE_CLIENT_CERTIFICATE_PASSWORD").is_some() {
                return Err(not_configured_hint(
                    "password-protected certificates are not supported; decrypt with `openssl pkey`".into(),
                    "openssl pkey -in cert.pem -out cert-plain.pem",
                ));
            }
            let send_chain = ctx
                .env("AZURE_CLIENT_SEND_CERTIFICATE_CHAIN")
                .is_some_and(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true"));
            let assertion = azure_certificate_assertion(ctx, &tenant, &client, &pem, jti, send_chain)?;
            Ok((
                url,
                vec![
                    ("client_id".into(), client),
                    ("scope".into(), scope),
                    ("client_assertion_type".into(), CLIENT_ASSERTION_TYPE.into()),
                    ("client_assertion".into(), assertion),
                    ("grant_type".into(), "client_credentials".into()),
                ],
            ))
        }
        _ => Err(not_configured(
            "Azure environment credential needs AZURE_CLIENT_SECRET or AZURE_CLIENT_CERTIFICATE_PATH".into(),
        )),
    }
}

async fn azure_environment_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    if azure_environment_kind(ctx).is_none() {
        return Ok(None);
    }
    let (url, pairs) = azure_environment_request(ctx, None)?;
    let data = exchange(
        ctx,
        "POST",
        &url,
        vec![(
            "content-type".into(),
            "application/x-www-form-urlencoded".into(),
        )],
        Some(form(&pairs)),
        "Entra client credentials",
    )
    .await?;
    bearer_from_oauth(&data, ctx.now, "Entra").map(Some)
}

fn azure_workload_config(ctx: &ChainContext) -> bool {
    ctx.env("AZURE_FEDERATED_TOKEN_FILE").is_some()
        && ctx.env("AZURE_CLIENT_ID").is_some()
        && ctx.env("AZURE_TENANT_ID").is_some()
}

async fn azure_workload_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    if !azure_workload_config(ctx) {
        return Ok(None);
    }
    let file = ctx.env("AZURE_FEDERATED_TOKEN_FILE").unwrap_or("");
    let token = ctx.read(file).ok_or_else(|| {
        not_configured(format!("AZURE_FEDERATED_TOKEN_FILE {file} is unreadable"))
    })?;
    let pairs = vec![
        (
            "client_id".to_string(),
            ctx.env("AZURE_CLIENT_ID").unwrap_or("").to_string(),
        ),
        ("scope".to_string(), azure_scope(ctx)),
        (
            "client_assertion_type".to_string(),
            CLIENT_ASSERTION_TYPE.to_string(),
        ),
        ("client_assertion".to_string(), token.trim().to_string()),
        ("grant_type".to_string(), "client_credentials".to_string()),
    ];
    let data = exchange(
        ctx,
        "POST",
        &azure_token_url(ctx, ctx.env("AZURE_TENANT_ID").unwrap_or("")),
        vec![(
            "content-type".into(),
            "application/x-www-form-urlencoded".into(),
        )],
        Some(form(&pairs)),
        "Entra workload identity",
    )
    .await?;
    bearer_from_oauth(&data, ctx.now, "Entra").map(Some)
}

fn azure_msi_flavor(ctx: &ChainContext) -> &'static str {
    if ctx.env("IDENTITY_ENDPOINT").is_some() {
        if ctx.env("IDENTITY_HEADER").is_some() {
            return if ctx.env("IDENTITY_SERVER_THUMBPRINT").is_some() {
                "service-fabric"
            } else {
                "app-service"
            };
        }
        if ctx.env("IMDS_ENDPOINT").is_some() {
            return "azure-arc";
        }
    }
    if ctx.env("MSI_ENDPOINT").is_some() {
        return if ctx.env("MSI_SECRET").is_some() {
            "azure-ml"
        } else {
            "cloud-shell"
        };
    }
    "imds"
}

async fn azure_msi_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    if ctx.is_offline() {
        return Ok(None);
    }
    let flavor = azure_msi_flavor(ctx);
    let resource = azure_scope(ctx)
        .strip_suffix("/.default")
        .map(str::to_string)
        .unwrap_or_else(|| azure_scope(ctx));
    let client_id = ctx.env("AZURE_CLIENT_ID").map(str::to_string);
    let now = ctx.now;
    let query = |version: &str, client_key: &str| {
        let mut pairs = vec![
            ("api-version".to_string(), version.to_string()),
            ("resource".to_string(), resource.clone()),
        ];
        if let Some(id) = &client_id {
            pairs.push((client_key.to_string(), id.clone()));
        }
        String::from_utf8_lossy(&form(&pairs)).into_owned()
    };
    match flavor {
        "imds" => {
            let url = format!(
                "http://169.254.169.254/metadata/identity/oauth2/token?{}",
                query("2018-02-01", "client_id")
            );
            let Some((status, _, raw)) = ctx
                .http_probe("GET", &url, vec![("Metadata".into(), "true".into())], None, 1)
                .await
            else {
                return Ok(None); // not on Azure: absent
            };
            if status != 200 {
                return Ok(None);
            }
            bearer_from_oauth(&json_body(&raw), now, "managed identity").map(Some)
        }
        "app-service" => {
            let url = format!("{}?{}", ctx.env("IDENTITY_ENDPOINT").unwrap_or(""), query("2019-08-01", "client_id"));
            let data = exchange(
                ctx,
                "GET",
                &url,
                vec![("X-IDENTITY-HEADER".into(), ctx.env("IDENTITY_HEADER").unwrap_or("").into())],
                None,
                "App Service managed identity",
            )
            .await?;
            bearer_from_oauth(&data, now, "managed identity").map(Some)
        }
        "cloud-shell" => {
            let data = exchange(
                ctx,
                "POST",
                ctx.env("MSI_ENDPOINT").unwrap_or(""),
                vec![
                    ("Metadata".into(), "true".into()),
                    ("content-type".into(), "application/x-www-form-urlencoded".into()),
                ],
                Some(form(&[("resource".into(), resource.clone())])),
                "Cloud Shell managed identity",
            )
            .await?;
            bearer_from_oauth(&data, now, "managed identity").map(Some)
        }
        "azure-ml" => {
            let url = format!("{}?{}", ctx.env("MSI_ENDPOINT").unwrap_or(""), query("2017-09-01", "clientid"));
            let data = exchange(
                ctx,
                "GET",
                &url,
                vec![("secret".into(), ctx.env("MSI_SECRET").unwrap_or("").into())],
                None,
                "Azure ML managed identity",
            )
            .await?;
            bearer_from_oauth(&data, now, "managed identity").map(Some)
        }
        "azure-arc" => {
            let url = format!(
                "{}?{}",
                ctx.env("IDENTITY_ENDPOINT").unwrap_or(""),
                String::from_utf8_lossy(&form(&[
                    ("api-version".into(), "2019-11-01".into()),
                    ("resource".into(), resource.clone())
                ]))
            );
            let (status, headers, _) = ctx
                .http("GET", &url, vec![("Metadata".into(), "true".into())], None, 5)
                .await?;
            let challenge = crate::surfaces::header(&headers, "www-authenticate").unwrap_or("").to_string();
            if status != 401 || !challenge.contains("realm=") {
                return Err(rejected(format!(
                    "Azure Arc managed identity: expected a 401 challenge, got {status}"
                )));
            }
            let key_path = challenge
                .split_once("realm=")
                .map(|(_, rest)| rest.trim().trim_matches('"').to_string())
                .unwrap_or_default();
            let directory = if cfg!(windows) {
                PathBuf::from(ctx.env("PROGRAMDATA").unwrap_or("C:/ProgramData"))
                    .join("AzureConnectedMachineAgent")
                    .join("Tokens")
            } else {
                PathBuf::from("/var/opt/azcmagent/tokens")
            };
            let path = PathBuf::from(&key_path);
            if path.parent() != Some(directory.as_path()) || path.extension().and_then(|e| e.to_str()) != Some("key") {
                return Err(rejected("Azure Arc managed identity: invalid challenge file location".into()));
            }
            if ctx.files.is_none() {
                let resolved = std::fs::canonicalize(&path).ok();
                let dir_resolved = std::fs::canonicalize(&directory).ok();
                if resolved.and_then(|p| p.parent().map(Path::to_path_buf)) != dir_resolved {
                    return Err(rejected("Azure Arc managed identity: invalid challenge file location".into()));
                }
            }
            let secret = ctx.read(&key_path);
            let Some(secret) = secret.filter(|s| s.len() <= 4096) else {
                return Err(rejected("Azure Arc managed identity: challenge file missing or too large".into()));
            };
            let data = exchange(
                ctx,
                "GET",
                &url,
                vec![
                    ("Metadata".into(), "true".into()),
                    ("Authorization".into(), format!("Basic {}", secret.trim())),
                ],
                None,
                "Azure Arc managed identity",
            )
            .await?;
            bearer_from_oauth(&data, now, "managed identity").map(Some)
        }
        _ => Err(not_configured(
            "Service Fabric managed identity (TLS thumbprint pinning) is not supported; use a certificate or secret".into(),
        )),
    }
}

async fn az_cli_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    if !ctx.subprocess || ctx.on_path("az").is_none() {
        return Ok(None);
    }
    let mut argv: Vec<String> = [
        "az",
        "account",
        "get-access-token",
        "--output",
        "json",
        "--scope",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    argv.push(azure_scope(ctx));
    if let Some(tenant) = ctx.env("AZURE_TENANT_ID") {
        argv.push("--tenant".into());
        argv.push(tenant.into());
    }
    let data = json_body(ctx.run(argv, 30).await?.as_bytes());
    let Some(token) = value_str(data.get("accessToken")) else {
        return Ok(None);
    };
    let mut fake = Map::new();
    fake.insert("access_token".into(), Value::String(token));
    if let Some(on) = data.get("expires_on") {
        fake.insert("expires_on".into(), on.clone());
    }
    let parsed = bearer_from_oauth(&fake, ctx.now, "Azure CLI")?;
    let mut expires = parsed.expires_at();
    if expires.is_none() {
        if let Some(text) = value_str(data.get("expiresOn")) {
            // `YYYY-MM-DD HH:MM:SS.ffffff` in local time in the CLI's
            // output; read as UTC when no offset is given (the reference's
            // fromisoformat().astimezone() on a naive value).
            expires = parse_rfc3339(&text.replacen(' ', "T", 1))
                .or_else(|| parse_rfc3339(&format!("{}Z", text.replacen(' ', "T", 1))));
        }
    }
    match parsed {
        Credential::BearerToken { value, .. } => Credential::bearer_token(value, expires).map(Some),
        other => Ok(Some(other)),
    }
}

async fn pwsh_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    if !ctx.subprocess || ctx.on_path("pwsh").is_none() {
        return Ok(None);
    }
    let resource = azure_scope(ctx)
        .strip_suffix("/.default")
        .map(str::to_string)
        .unwrap_or_else(|| azure_scope(ctx))
        .replace('\'', "''");
    let script = format!(
        "Get-AzAccessToken -ResourceUrl '{resource}' -AsSecureString:$false | ConvertTo-Json -Compress"
    );
    let argv = vec![
        "pwsh".to_string(),
        "-NoProfile".into(),
        "-NonInteractive".into(),
        "-Command".into(),
        script,
    ];
    let data = json_body(ctx.run(argv, 30).await?.as_bytes());
    let Some(token) = value_str(data.get("Token")) else {
        return Ok(None);
    };
    let mut fake = Map::new();
    fake.insert("access_token".into(), Value::String(token));
    bearer_from_oauth(&fake, ctx.now, "Azure PowerShell").map(Some)
}

async fn azd_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    if !ctx.subprocess || ctx.on_path("azd").is_none() {
        return Ok(None);
    }
    let argv = vec![
        "azd".to_string(),
        "auth".into(),
        "token".into(),
        "--output".into(),
        "json".into(),
        "--scope".into(),
        azure_scope(ctx),
    ];
    let data = json_body(ctx.run(argv, 30).await?.as_bytes());
    let Some(token) = value_str(data.get("token")) else {
        return Ok(None);
    };
    let expires = value_str(data.get("expiresOn")).and_then(|e| parse_rfc3339(&e));
    Credential::bearer_token(token, expires).map(Some)
}

/// `AZURE_TOKEN_CREDENTIALS=prod|dev|<CredentialName>` narrowing.
fn azure_narrowed(ctx: &ChainContext, name: &str, developer: bool) -> bool {
    let value = ctx
        .env("AZURE_TOKEN_CREDENTIALS")
        .map(|v| v.trim().to_ascii_lowercase())
        .unwrap_or_default();
    if value.is_empty() {
        return false;
    }
    match value.as_str() {
        "prod" => developer,
        "dev" => !developer,
        other => other != name.to_ascii_lowercase(),
    }
}

// ─── Google Cloud ────────────────────────────────────────────────────

/// (token_uri, JWT) for a `service_account` file: header alg/typ/kid,
/// claims iat, exp=iat+3600, iss, aud, scope.
pub fn gcp_service_account_assertion(
    ctx: &ChainContext,
    info: &Map<String, Value>,
    scope: &str,
) -> Result<(String, String), AuthError> {
    let pem = value_str(info.get("private_key"))
        .ok_or_else(|| not_configured("service_account file lacks private_key".into()))?;
    let key = rs256::load_private_key(&pem)?;
    let now = ctx.now;
    let token_uri = value_str(info.get("token_uri")).unwrap_or_else(|| GCP_TOKEN_URL.into());
    let mut header = Map::new();
    header.insert("alg".into(), json!("RS256"));
    header.insert("typ".into(), json!("JWT"));
    if let Some(kid) = value_str(info.get("private_key_id")) {
        header.insert("kid".into(), Value::String(kid));
    }
    let payload = json!({
        "iat": now,
        "exp": now + 3600,
        "iss": value_str(info.get("client_email")).unwrap_or_default(),
        "aud": token_uri,
        "scope": scope,
    });
    let jwt = rs256::jwt_encode(&Value::Object(header), &payload, &key)?;
    Ok((token_uri, jwt))
}

fn gcp_credential_file(
    ctx: &ChainContext,
    path: &str,
) -> Result<Option<Map<String, Value>>, AuthError> {
    let Some(raw) = ctx.read(path) else {
        return Ok(None);
    };
    match serde_json::from_str::<Value>(&raw) {
        Ok(Value::Object(map)) => Ok(Some(map)),
        Ok(_) => Ok(None),
        Err(_) => Err(not_configured(format!("{path}: not valid JSON"))),
    }
}

fn gcp_from_info<'a>(
    ctx: &'a ChainContext,
    info: &'a Map<String, Value>,
    where_: &'a str,
) -> BoxFuture<'a, Result<Credential, AuthError>> {
    Box::pin(async move {
        let kind = info.get("type").and_then(Value::as_str).unwrap_or("");
        let now = ctx.now;
        match kind {
            "authorized_user" => {
                for key in ["refresh_token", "client_id", "client_secret"] {
                    if value_str(info.get(key)).is_none() {
                        return Err(not_configured(format!(
                            "{where_}: authorized_user file lacks {key}"
                        )));
                    }
                }
                let pairs = vec![
                    ("grant_type".to_string(), "refresh_token".to_string()),
                    (
                        "client_id".to_string(),
                        value_str(info.get("client_id")).unwrap_or_default(),
                    ),
                    (
                        "client_secret".to_string(),
                        value_str(info.get("client_secret")).unwrap_or_default(),
                    ),
                    (
                        "refresh_token".to_string(),
                        value_str(info.get("refresh_token")).unwrap_or_default(),
                    ),
                ];
                let data = exchange_hint(
                    ctx,
                    "POST",
                    &value_str(info.get("token_uri")).unwrap_or_else(|| GCP_TOKEN_URL.into()),
                    vec![(
                        "content-type".into(),
                        "application/x-www-form-urlencoded".into(),
                    )],
                    Some(form(&pairs)),
                    &format!("Google OAuth refresh ({where_})"),
                    Some(gcp_user_login_hint(where_)),
                )
                .await?;
                bearer_from_oauth(&data, now, "Google OAuth")
            }
            "service_account" => {
                let (token_uri, assertion) = gcp_service_account_assertion(ctx, info, GCP_SCOPE)?;
                let data = exchange_hint(
                    ctx,
                    "POST",
                    &token_uri,
                    vec![(
                        "content-type".into(),
                        "application/x-www-form-urlencoded".into(),
                    )],
                    Some(form(&[
                        ("grant_type".into(), JWT_BEARER.into()),
                        ("assertion".into(), assertion),
                    ])),
                    &format!("Google service account key ({where_})"),
                    Some(format!(
                        "the key in {where_} may have been deleted or disabled, or this machine's \
                         clock is off; create a new key (Cloud console: IAM & Admin > Service \
                         accounts > Keys) or use another identity"
                    )),
                )
                .await?;
                bearer_from_oauth(&data, now, "Google service account")
            }
            "external_account" => gcp_external_account(ctx, info, where_).await,
            "impersonated_service_account" => {
                let Some(source) = info.get("source_credentials").and_then(Value::as_object) else {
                    return Err(not_configured(format!(
                        "{where_}: impersonated_service_account lacks source_credentials"
                    )));
                };
                let base =
                    gcp_from_info(ctx, source, &format!("{where_}.source_credentials")).await?;
                let url =
                    value_str(info.get("service_account_impersonation_url")).unwrap_or_default();
                let delegates = info.get("delegates").cloned().unwrap_or_else(|| json!([]));
                gcp_impersonate(ctx, &base, &url, delegates, where_).await
            }
            other => Err(not_configured(format!(
                "{where_}: credential type {other:?} is not supported by lm15 \
                 (external_account_authorized_user and gdch_service_account are stated gaps)"
            ))),
        }
    })
}

async fn gcp_impersonate(
    ctx: &ChainContext,
    source: &Credential,
    url: &str,
    delegates: Value,
    where_: &str,
) -> Result<Credential, AuthError> {
    let token = match source {
        Credential::BearerToken { value, .. } | Credential::ApiKey { value } => value.clone(),
        Credential::AwsCredentials { .. } => {
            return Err(rejected(
                "generateAccessToken: source credential is not a token".into(),
            ))
        }
    };
    let body = json!({"delegates": delegates, "scope": [GCP_SCOPE], "lifetime": "3600s"});
    let data = exchange_hint(
        ctx,
        "POST",
        url,
        vec![
            ("content-type".into(), "application/json".into()),
            ("authorization".into(), format!("Bearer {token}")),
        ],
        Some(serde_json::to_vec(&body).expect("serializes")),
        &format!("service account impersonation ({where_}; generateAccessToken)"),
        Some(format!(
            "the service account named in {where_} must exist, and the source identity needs \
             roles/iam.serviceAccountTokenCreator on it (roles/iam.workloadIdentityUser for a \
             workload identity pool), and the IAM Credentials API (iamcredentials.googleapis.com) \
             enabled; a new grant can take several minutes to apply"
        )),
    )
    .await?;
    let token = value_str(data.get("accessToken"))
        .ok_or_else(|| rejected("generateAccessToken: no accessToken".into()))?;
    let expires = value_str(data.get("expireTime")).and_then(|e| parse_rfc3339(&e));
    Credential::bearer_token(token, expires)
}

async fn gcp_external_account(
    ctx: &ChainContext,
    info: &Map<String, Value>,
    where_: &str,
) -> Result<Credential, AuthError> {
    let source = info
        .get("credential_source")
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    if source.contains_key("environment_id") {
        return Err(not_configured(format!(
            "{where_}: external_account with an AWS credential_source is a stated gap in lm15; \
             use a file/url/executable source or a service account"
        )));
    }
    let mut fmt = source
        .get("format")
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    let subject: Option<String> = if let Some(file) = value_str(source.get("file")) {
        Some(
            ctx.read(&file)
                .ok_or_else(|| {
                    not_configured(format!("{where_}: subject token file {file} is unreadable"))
                })?
                .trim()
                .to_string(),
        )
    } else if let Some(url) = value_str(source.get("url")) {
        let headers: Vec<(String, String)> = source
            .get("headers")
            .and_then(Value::as_object)
            .map(|h| {
                h.iter()
                    .map(|(k, v)| {
                        (
                            k.clone(),
                            v.as_str()
                                .map(str::to_string)
                                .unwrap_or_else(|| v.to_string()),
                        )
                    })
                    .collect()
            })
            .unwrap_or_default();
        let (status, _, raw) = ctx.http("GET", &url, headers, None, 30).await?;
        if status >= 400 {
            return Err(rejected(format!(
                "{where_}: subject token url HTTP {status}"
            )));
        }
        Some(String::from_utf8_lossy(&raw).trim().to_string())
    } else if let Some(executable) = source.get("executable").and_then(Value::as_object) {
        if !ctx.subprocess {
            return Err(not_configured(format!(
                "{where_}: executable credential source needs subprocess access"
            )));
        }
        if ctx.env("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES") != Some("1") {
            return Err(not_configured(format!(
                "{where_}: set GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES=1 to allow the executable source"
            )));
        }
        let command = value_str(executable.get("command")).unwrap_or_default();
        let timeout = executable
            .get("timeout_millis")
            .and_then(Value::as_u64)
            .unwrap_or(30000)
            / 1000;
        let out = ctx.run(shlex_split(&command), timeout.max(1)).await?;
        let data = json_body(out.as_bytes());
        if data.get("success").and_then(Value::as_bool) == Some(false) {
            return Err(rejected(
                "external account executable reported failure".into(),
            ));
        }
        fmt = Map::new();
        fmt.insert("type".into(), json!("text"));
        value_str(data.get("id_token").or_else(|| data.get("saml_response")))
    } else {
        None
    };
    let Some(mut subject) = subject else {
        return Err(not_configured(format!(
            "{where_}: external_account credential_source is not file/url/executable"
        )));
    };
    if fmt.get("type").and_then(Value::as_str) == Some("json") {
        let field = value_str(fmt.get("subject_token_field_name")).unwrap_or_default();
        subject = value_str(json_body(subject.as_bytes()).get(&field)).unwrap_or_default();
    }
    let body = json!({
        "grantType": "urn:ietf:params:oauth:grant-type:token-exchange",
        "audience": value_str(info.get("audience")).unwrap_or_default(),
        "scope": GCP_SCOPE,
        "requestedTokenType": "urn:ietf:params:oauth:token-type:access_token",
        "subjectToken": subject,
        "subjectTokenType": value_str(info.get("subject_token_type")).unwrap_or_default(),
    });
    let data = exchange_hint(
        ctx,
        "POST",
        &value_str(info.get("token_url")).unwrap_or_else(|| GCP_STS_URL.into()),
        vec![("content-type".into(), "application/json".into())],
        Some(serde_json::to_vec(&body).expect("serializes")),
        &format!("Google STS exchange ({where_})"),
        Some(
            "the workload identity pool refused the external token: check the provider's \
             issuer, allowed audience and attribute condition, and that the subject token is fresh"
                .into(),
        ),
    )
    .await?;
    let token = bearer_from_oauth(&data, ctx.now, "Google STS")?;
    if let Some(url) = value_str(info.get("service_account_impersonation_url")) {
        return gcp_impersonate(ctx, &token, &url, json!([]), where_).await;
    }
    Ok(token)
}

fn no_gce_check(ctx: &ChainContext) -> bool {
    ctx.env("NO_GCE_CHECK")
        .is_some_and(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true"))
}

async fn gcp_metadata_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    if ctx.is_offline() || no_gce_check(ctx) {
        return Ok(None);
    }
    let host = ctx
        .env("GCE_METADATA_HOST")
        .or_else(|| ctx.env("GCE_METADATA_ROOT"))
        .unwrap_or("metadata.google.internal");
    let Some((status, _, raw)) = ctx
        .http_probe(
            "GET",
            &format!("http://{host}/computeMetadata/v1/instance/service-accounts/default/token"),
            vec![("Metadata-Flavor".into(), "Google".into())],
            None,
            1,
        )
        .await
    else {
        return Ok(None);
    };
    if status != 200 {
        return Ok(None);
    }
    bearer_from_oauth(&json_body(&raw), ctx.now, "GCE metadata").map(Some)
}

async fn gcloud_acquire(ctx: &ChainContext) -> Result<Option<Credential>, AuthError> {
    if !ctx.subprocess || ctx.on_path("gcloud").is_none() {
        return Ok(None);
    }
    let token = match ctx
        .run(
            vec!["gcloud".into(), "auth".into(), "print-access-token".into()],
            30,
        )
        .await
    {
        Ok(out) => out.trim().to_string(),
        // gcloud's own words stay unread (AUTH-5: a command's stderr is not shown).
        Err(AuthError::Rejected { message, .. }) => return Err(AuthError::Rejected {
            provider: None,
            message: format!("`gcloud auth print-access-token` failed: {message}"),
            hint: Some(
                "run `gcloud auth print-access-token` yourself to see gcloud's reason; usually \
                     `gcloud auth login` fixes it (or `gcloud auth application-default login`, \
                     which lm15 reads first)"
                    .into(),
            ),
        }),
        Err(other) => return Err(other),
    };
    if token.is_empty() {
        return Ok(None);
    }
    Credential::bearer_token(token, None).map(Some)
}

fn adc_file_path(ctx: &ChainContext) -> String {
    let base = ctx.env("CLOUDSDK_CONFIG").unwrap_or("~/.config/gcloud");
    format!(
        "{}/application_default_credentials.json",
        base.trim_end_matches('/')
    )
}

// ─── Settings from the cloud's own configuration (AUTH-10, after env) ──

pub use crate::cloud::hosts::ProfileValue;

/// gcloud's own rule for a configuration name (named_configs.py:37); it
/// also keeps the name inside the configurations directory.
fn gcloud_config_name_ok(name: &str) -> bool {
    let mut chars = name.chars();
    matches!(chars.next(), Some('a'..='z'))
        && chars.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '-'))
}

/// The project `gcloud config get project` prints, read from the files
/// gcloud reads: `CLOUDSDK_CORE_PROJECT`, then `[core] project` in
/// `$CLOUDSDK_CONFIG/configurations/config_<name>` (`<name>` from
/// `CLOUDSDK_ACTIVE_CONFIG_NAME`, else the `active_config` file, else
/// `default`).
pub fn gcloud_config_project(ctx: &ChainContext) -> Option<(String, String)> {
    if let Some(value) = ctx
        .env("CLOUDSDK_CORE_PROJECT")
        .map(str::trim)
        .filter(|v| !v.is_empty())
    {
        return Some((value.to_string(), "env:CLOUDSDK_CORE_PROJECT".into()));
    }
    let base = ctx
        .env("CLOUDSDK_CONFIG")
        .unwrap_or("~/.config/gcloud")
        .trim_end_matches('/')
        .to_string();
    let name = ctx
        .env("CLOUDSDK_ACTIVE_CONFIG_NAME")
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
        .or_else(|| {
            ctx.read(&format!("{base}/active_config"))
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty())
        })
        .unwrap_or_else(|| "default".into());
    if !gcloud_config_name_ok(&name) {
        return None;
    }
    let raw = ctx.read(&format!("{base}/configurations/config_{name}"))?;
    let ini = Ini::parse(&raw).ok()?;
    let value = ini
        .section("core")
        .and_then(|s| get(s, "project"))?
        .trim()
        .to_string();
    (!value.is_empty()).then(|| (value, "gcloud-config".into()))
}

/// `project/project-id` from the metadata server: the project a Cloud Run
/// service, GKE pod or VM runs in (asked before the first request).
pub async fn metadata_project(ctx: &ChainContext) -> Option<String> {
    if ctx.is_offline() || no_gce_check(ctx) {
        return None;
    }
    let host = ctx
        .env("GCE_METADATA_HOST")
        .or_else(|| ctx.env("GCE_METADATA_ROOT"))
        .unwrap_or("metadata.google.internal");
    let (status, _, raw) = ctx
        .http_probe(
            "GET",
            &format!("http://{host}/computeMetadata/v1/project/project-id"),
            vec![("Metadata-Flavor".into(), "Google".into())],
            None,
            1,
        )
        .await?;
    let value = String::from_utf8_lossy(&raw).trim().to_string();
    (status == 200
        && !value.is_empty()
        && !value.contains(|c: char| c.is_whitespace() || "/?#".contains(c)))
    .then_some(value)
}

/// The setting values the cloud's own configuration carries. AWS `region`:
/// the active profile. Google `project` (amended 2026-09-26, the order
/// google-auth and gcloud give it): the GOOGLE_APPLICATION_CREDENTIALS
/// file's `project_id` (then `quota_project_id`); gcloud's active
/// configuration; the ADC file's `quota_project_id` / `project_id`; then
/// the metadata server ([`ProfileValue::Metadata`]). Nothing for Azure.
pub fn profile_setting(
    policy: &AccessPolicy,
    ctx: &ChainContext,
    name: &str,
) -> Option<ProfileValue> {
    match (policy.credential_policy, name) {
        (CredentialPolicy::AwsChain, "region") => {
            let cfg = aws_config(ctx).ok()?;
            let section = aws_profile_section(&cfg.config, &cfg.profile);
            get(&section, "region")
                .map(str::to_string)
                .or_else(|| {
                    cfg.credentials
                        .section(&cfg.profile)
                        .and_then(|s| get(s, "region"))
                        .map(str::to_string)
                })
                .map(|v| ProfileValue::Found(v, "aws-profile".into()))
        }
        (CredentialPolicy::GcpChain, "project") => {
            if let Some(path) = ctx
                .env("GOOGLE_APPLICATION_CREDENTIALS")
                .map(str::to_string)
            {
                if let Ok(Some(info)) = gcp_credential_file(ctx, &path) {
                    if let Some(value) = value_str(info.get("project_id"))
                        .or_else(|| value_str(info.get("quota_project_id")))
                    {
                        return Some(ProfileValue::Found(value, "adc-env".into()));
                    }
                }
            }
            if let Some((value, from)) = gcloud_config_project(ctx) {
                return Some(ProfileValue::Found(value, from));
            }
            if let Ok(Some(info)) = gcp_credential_file(ctx, &adc_file_path(ctx)) {
                if let Some(value) = value_str(info.get("quota_project_id"))
                    .or_else(|| value_str(info.get("project_id")))
                {
                    return Some(ProfileValue::Found(value, "adc-file".into()));
                }
            }
            (!no_gce_check(ctx)).then_some(ProfileValue::Metadata)
        }
        _ => None,
    }
}

// ─── Probe (offline) and acquire (online) per rung ───────────────────

fn probe(
    policy: &AccessPolicy,
    rung: &Rung,
    ctx: &ChainContext,
) -> Result<(Verdict, String), AuthError> {
    let door_key = policy.env_keys.first().copied();
    Ok(match rung.id {
        RungId::DoorKey => {
            if ctx.env(door_key.unwrap_or("")).is_some() {
                (Verdict::Usable, "set (value never shown)".into())
            } else {
                (Verdict::Absent, "not set".into())
            }
        }
        RungId::AwsStaticEnv => {
            if env_aws(ctx).is_some() {
                (Verdict::Usable, "set (values never shown)".into())
            } else {
                (
                    Verdict::Absent,
                    "AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY not set".into(),
                )
            }
        }
        RungId::AssumeRole => {
            let cfg = aws_config(ctx)?;
            let section = aws_profile_section(&cfg.config, &cfg.profile);
            if get(&section, "role_arn").is_some()
                && (get(&section, "source_profile").is_some()
                    || get(&section, "credential_source").is_some())
            {
                (
                    Verdict::Configured,
                    format!(
                        "profile {:?} assumes {} (STS call at request time)",
                        cfg.profile,
                        get(&section, "role_arn").unwrap_or("")
                    ),
                )
            } else {
                (
                    Verdict::Absent,
                    format!("profile {:?} has no role_arn with a source", cfg.profile),
                )
            }
        }
        RungId::WebIdentity => match web_identity_config(ctx)? {
            Some((file, role, _)) => (
                Verdict::Configured,
                format!("token file {file} → {role} (STS call at request time)"),
            ),
            None => (
                Verdict::Absent,
                "AWS_WEB_IDENTITY_TOKEN_FILE / AWS_ROLE_ARN not set".into(),
            ),
        },
        RungId::Sso => match sso_config(ctx)? {
            None => (
                Verdict::Absent,
                "no sso_session / sso_start_url in the profile".into(),
            ),
            Some(cfg) => {
                let cached = ctx.exists(&format!(
                    "~/.aws/sso/cache/{}.json",
                    get(&cfg, "cache_key").unwrap_or("")
                ));
                (
                    Verdict::Configured,
                    if cached {
                        "cached token present (GetRoleCredentials at request time)".into()
                    } else {
                        "no cached token; run `aws sso login`".into()
                    },
                )
            }
        },
        RungId::SharedCredentialsFile => {
            let cfg = aws_config(ctx)?;
            let section = cfg
                .credentials
                .section(&cfg.profile)
                .cloned()
                .unwrap_or_default();
            if aws_static(&section).is_some() {
                (
                    Verdict::Usable,
                    format!("profile {:?} (values never shown)", cfg.profile),
                )
            } else {
                (
                    Verdict::Absent,
                    format!("no keys for profile {:?}", cfg.profile),
                )
            }
        }
        RungId::Login => {
            if login_config(ctx)?.is_none() {
                (Verdict::Absent, "no login_session in the profile".into())
            } else if login_cached(ctx)?.is_some_and(|c| !c.is_expired_at(ctx.now)) {
                (
                    Verdict::Usable,
                    "cached short-term credentials are fresh".into(),
                )
            } else {
                (
                    Verdict::Absent,
                    "cached credentials missing or expired; DPoP refresh is not supported; run `aws login`".into(),
                )
            }
        }
        RungId::CredentialProcess => {
            let cfg = aws_config(ctx)?;
            match get(
                &aws_profile_section(&cfg.config, &cfg.profile),
                "credential_process",
            ) {
                None => (
                    Verdict::Absent,
                    "no credential_process in the profile".into(),
                ),
                Some(command) => {
                    let executable = shlex_split(command).into_iter().next().unwrap_or_default();
                    if ctx.on_path(&executable).is_none() {
                        (
                            Verdict::Absent,
                            format!("credential_process {executable:?} is not on PATH"),
                        )
                    } else {
                        (
                            Verdict::Configured,
                            "credential_process configured (run at request time)".into(),
                        )
                    }
                }
            }
        }
        RungId::ConfigFile => {
            let cfg = aws_config(ctx)?;
            if aws_static(&aws_profile_section(&cfg.config, &cfg.profile)).is_some() {
                (
                    Verdict::Usable,
                    format!("static keys in config for profile {:?}", cfg.profile),
                )
            } else {
                (Verdict::Absent, "no static keys in config".into())
            }
        }
        RungId::Container => match container_config(ctx) {
            Err(err) => (
                Verdict::Absent,
                err.to_string().lines().next().unwrap_or("").to_string(),
            ),
            Ok(Some(_)) => (
                Verdict::Configured,
                "container endpoint configured (HTTP at request time)".into(),
            ),
            Ok(None) => (Verdict::Absent, "no AWS_CONTAINER_CREDENTIALS_* URI".into()),
        },
        RungId::Imds => {
            if imds_disabled(ctx) {
                (Verdict::Absent, "AWS_EC2_METADATA_DISABLED=true".into())
            } else {
                (
                    Verdict::Configured,
                    "instance metadata probed at request time".into(),
                )
            }
        }
        RungId::AzureEnvironment => {
            if azure_narrowed(ctx, "EnvironmentCredential", false) {
                (
                    Verdict::Absent,
                    "excluded by AZURE_TOKEN_CREDENTIALS".into(),
                )
            } else if let Some(kind) = azure_environment_kind(ctx) {
                (
                    Verdict::Configured,
                    format!("service principal by {kind} (token exchange at request time)"),
                )
            } else {
                (
                    Verdict::Absent,
                    "AZURE_TENANT_ID/AZURE_CLIENT_ID + secret or certificate not set".into(),
                )
            }
        }
        RungId::AzureWorkload => {
            if azure_narrowed(ctx, "WorkloadIdentityCredential", false) {
                (
                    Verdict::Absent,
                    "excluded by AZURE_TOKEN_CREDENTIALS".into(),
                )
            } else if azure_workload_config(ctx) {
                (
                    Verdict::Configured,
                    "federated token file present (exchange at request time)".into(),
                )
            } else {
                (Verdict::Absent, "AZURE_FEDERATED_TOKEN_FILE not set".into())
            }
        }
        RungId::AzureManagedIdentity => {
            if azure_narrowed(ctx, "ManagedIdentityCredential", false) {
                (
                    Verdict::Absent,
                    "excluded by AZURE_TOKEN_CREDENTIALS".into(),
                )
            } else if azure_msi_flavor(ctx) == "service-fabric" {
                (
                    Verdict::Absent,
                    "Service Fabric managed identity (TLS thumbprint pinning) is not supported; use a certificate or secret".into(),
                )
            } else {
                (
                    Verdict::Configured,
                    format!(
                        "managed identity ({}) probed at request time",
                        azure_msi_flavor(ctx)
                    ),
                )
            }
        }
        RungId::AzCli | RungId::Pwsh | RungId::Azd => {
            let (name, label, command) = match rung.id {
                RungId::AzCli => ("AzureCliCredential", "`az`", "az"),
                RungId::Pwsh => ("AzurePowerShellCredential", "`pwsh`", "pwsh"),
                _ => ("AzureDeveloperCliCredential", "`azd`", "azd"),
            };
            if azure_narrowed(ctx, name, true) {
                (
                    Verdict::Absent,
                    "excluded by AZURE_TOKEN_CREDENTIALS".into(),
                )
            } else if ctx.on_path(command).is_none() {
                (Verdict::Absent, format!("{command} is not on PATH"))
            } else {
                (Verdict::Configured, format!("{label} run at request time"))
            }
        }
        RungId::AdcEnv | RungId::AdcFile => {
            let (label, path) = match rung.id {
                RungId::AdcEnv => (
                    "GOOGLE_APPLICATION_CREDENTIALS",
                    ctx.env("GOOGLE_APPLICATION_CREDENTIALS")
                        .map(str::to_string),
                ),
                _ => ("ADC file", Some(adc_file_path(ctx))),
            };
            match path {
                None => (Verdict::Absent, format!("{label} not set")),
                Some(path) => match gcp_credential_file(ctx, &path)? {
                    None => (Verdict::Absent, format!("{path} missing or unreadable")),
                    Some(info) if info.get("type").and_then(Value::as_str) == Some("external_account")
                        && info.get("credential_source").and_then(Value::as_object)
                            .is_some_and(|source| source.contains_key("environment_id")) => (
                        Verdict::Absent,
                        format!("{path}: external_account with an AWS credential_source is not supported; use a file/url/executable source or a service account"),
                    ),
                    Some(info) => (
                        Verdict::Configured,
                        format!(
                            "{} credentials in {path} (token exchange at request time)",
                            info.get("type").and_then(Value::as_str).unwrap_or("?")
                        ),
                    ),
                },
            }
        }
        RungId::GceMetadata => {
            if no_gce_check(ctx) {
                (Verdict::Absent, "NO_GCE_CHECK set".into())
            } else {
                (
                    Verdict::Configured,
                    "GCE metadata server probed at request time".into(),
                )
            }
        }
        RungId::Gcloud => {
            if ctx.on_path("gcloud").is_some() {
                (Verdict::Configured, "`gcloud` run at request time".into())
            } else {
                (Verdict::Absent, "gcloud is not on PATH".into())
            }
        }
    })
}

async fn acquire(
    policy: &AccessPolicy,
    rung: &Rung,
    ctx: &ChainContext,
) -> Result<Option<Credential>, AuthError> {
    match rung.id {
        RungId::DoorKey => {
            let key = policy.env_keys.first().copied().unwrap_or("");
            match ctx.env(key) {
                None => Ok(None),
                Some(value) => {
                    if policy.credential_policy == CredentialPolicy::AwsChain
                        && key == "AWS_BEARER_TOKEN_BEDROCK"
                    {
                        Credential::bearer_token(value, None).map(Some)
                    } else {
                        Credential::api_key(value).map(Some)
                    }
                }
            }
        }
        RungId::AwsStaticEnv => Ok(env_aws(ctx)),
        RungId::AssumeRole => {
            let cfg = aws_config(ctx)?;
            let section = aws_profile_section(&cfg.config, &cfg.profile);
            if get(&section, "role_arn").is_some()
                && (get(&section, "source_profile").is_some()
                    || get(&section, "credential_source").is_some())
            {
                return assume_role(ctx, &section, 0).await.map(Some);
            }
            Ok(None)
        }
        RungId::WebIdentity => web_identity_acquire(ctx).await,
        RungId::Sso => sso_acquire(ctx).await,
        RungId::SharedCredentialsFile => {
            let cfg = aws_config(ctx)?;
            Ok(cfg.credentials.section(&cfg.profile).and_then(aws_static))
        }
        RungId::Login => login_acquire(ctx),
        RungId::CredentialProcess => process_acquire(ctx).await,
        RungId::ConfigFile => {
            let cfg = aws_config(ctx)?;
            Ok(aws_static(&aws_profile_section(&cfg.config, &cfg.profile)))
        }
        RungId::Container => container_acquire(ctx).await,
        RungId::Imds => imds_acquire(ctx).await,
        RungId::AzureEnvironment => {
            if azure_narrowed(ctx, "EnvironmentCredential", false) {
                return Ok(None);
            }
            azure_environment_acquire(ctx).await
        }
        RungId::AzureWorkload => {
            if azure_narrowed(ctx, "WorkloadIdentityCredential", false) {
                return Ok(None);
            }
            azure_workload_acquire(ctx).await
        }
        RungId::AzureManagedIdentity => {
            if azure_narrowed(ctx, "ManagedIdentityCredential", false) {
                return Ok(None);
            }
            azure_msi_acquire(ctx).await
        }
        RungId::AzCli => {
            if azure_narrowed(ctx, "AzureCliCredential", true) {
                return Ok(None);
            }
            az_cli_acquire(ctx).await
        }
        RungId::Pwsh => {
            if azure_narrowed(ctx, "AzurePowerShellCredential", true) {
                return Ok(None);
            }
            pwsh_acquire(ctx).await
        }
        RungId::Azd => {
            if azure_narrowed(ctx, "AzureDeveloperCliCredential", true) {
                return Ok(None);
            }
            azd_acquire(ctx).await
        }
        RungId::AdcEnv | RungId::AdcFile => {
            let path = match rung.id {
                RungId::AdcEnv => ctx
                    .env("GOOGLE_APPLICATION_CREDENTIALS")
                    .map(str::to_string),
                _ => Some(adc_file_path(ctx)),
            };
            let Some(path) = path else {
                return Ok(None);
            };
            match gcp_credential_file(ctx, &path)? {
                Some(info) => gcp_from_info(ctx, &info, &path).await.map(Some),
                None => Ok(None),
            }
        }
        RungId::GceMetadata => gcp_metadata_acquire(ctx).await,
        RungId::Gcloud => gcloud_acquire(ctx).await,
    }
}

// ─── Explain and resolve ─────────────────────────────────────────────

/// The four deterministic identity selections (AUTH-1, 2026-09-19).
pub const NAMED_CREDENTIALS: &[&str] = &["platform", "workload", "environment", "cli"];

pub fn named_meaning(policy: &AccessPolicy, name: &str) -> Result<&'static str, AuthError> {
    use CredentialPolicy::*;
    Ok(match (policy.credential_policy, name) {
        (AwsChain, "platform") => "the ECS/EKS container endpoint, then EC2 IMDSv2",
        (AwsChain, "workload") => "web identity via AWS_WEB_IDENTITY_TOKEN_FILE and AWS_ROLE_ARN",
        (AwsChain, "environment") => "AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY",
        (AwsChain, "cli") => {
            "the active AWS profile: assume-role, SSO, shared files, login, credential_process"
        }
        (AzureChain, "platform") => "Azure managed identity",
        (AzureChain, "workload") => "Entra workload identity via AZURE_FEDERATED_TOKEN_FILE",
        (AzureChain, "environment") => {
            "an Entra service principal: tenant, client, secret or certificate"
        }
        (AzureChain, "cli") => "az, Azure PowerShell, or azd sign-in",
        (GcpChain, "platform") => "the attached service account via GCE metadata",
        (GcpChain, "workload") => "GOOGLE_APPLICATION_CREDENTIALS of type external_account",
        (GcpChain, "environment") => {
            "GOOGLE_APPLICATION_CREDENTIALS of type service_account or impersonated_service_account"
        }
        (GcpChain, "cli") => "the ADC file or gcloud auth print-access-token",
        _ => {
            return Err(AuthError::NotConfigured {
                provider: Some(policy.provider.into()),
                message: if !NAMED_CREDENTIALS.contains(&name) {
                    // AUTH-1/AUTH-5 (amended 2026-10-10): a value that is not a name is
                    // usually a key in the wrong field; never repeat it.
                    "unknown named credential (one of platform, workload, environment, cli); the value given is not shown, because it may be a key. If it is your API key, pass it as api_key".to_string()
                } else {
                    "named credentials require a cloud door".into()
                },
                hint: None,
            });
        }
    })
}

pub fn chain_for_named(policy: &AccessPolicy, name: &str) -> Result<Vec<Rung>, AuthError> {
    named_meaning(policy, name)?;
    use CredentialPolicy::*;
    let allowed: &[&str] = match (policy.credential_policy, name) {
        (AwsChain, "platform") => &["container", "imds"],
        (AwsChain, "workload") => &["web-identity"],
        (AwsChain, "environment") => &["env:AWS_ACCESS_KEY_ID"],
        (AwsChain, "cli") => &[
            "assume-role",
            "sso",
            "shared-credentials-file",
            "login",
            "credential_process",
            "config-file",
        ],
        (AzureChain, "platform") => &["managed-identity"],
        (AzureChain, "workload") => &["workload-identity"],
        (AzureChain, "environment") => &["environment"],
        (AzureChain, "cli") => &["az", "pwsh", "azd"],
        (GcpChain, "platform") => &["metadata"],
        (GcpChain, "workload" | "environment") => &["adc-env"],
        (GcpChain, "cli") => &["adc-file", "gcloud"],
        _ => unreachable!("validated above"),
    };
    Ok(chain_for(policy)?
        .into_iter()
        .filter(|rung| allowed.contains(&rung.name.as_str()))
        .collect())
}

fn walk(policy: &AccessPolicy, named: Option<&str>) -> Result<Vec<Rung>, AuthError> {
    match named {
        Some(name) => chain_for_named(policy, name),
        None => chain_for(policy),
    }
}

fn check_named_file(
    policy: &AccessPolicy,
    ctx: &ChainContext,
    named: Option<&str>,
) -> Result<(), AuthError> {
    if policy.credential_policy != CredentialPolicy::GcpChain {
        return Ok(());
    }
    let Some(name @ ("workload" | "environment")) = named else {
        return Ok(());
    };
    let Some(path) = ctx.env("GOOGLE_APPLICATION_CREDENTIALS") else {
        return Ok(());
    };
    let Some(text) = ctx.read(path) else {
        return Ok(());
    };
    let info: Value = serde_json::from_str(&text).map_err(|_| {
        not_configured("GOOGLE_APPLICATION_CREDENTIALS must contain a credential object".into())
    })?;
    let kind = info.get("type").and_then(Value::as_str).unwrap_or("");
    let allowed = if name == "workload" {
        kind == "external_account"
    } else {
        matches!(kind, "service_account" | "impersonated_service_account")
    };
    if !allowed {
        let other = if name == "workload" {
            "environment"
        } else {
            "workload"
        };
        let actual = match kind {
            "service_account" => "service_account",
            "impersonated_service_account" => "impersonated_service_account",
            "external_account" => "external_account",
            "authorized_user" => "authorized_user",
            _ => "missing or unsupported type",
        };
        return Err(AuthError::NotConfigured { provider: Some(policy.provider.into()), message: format!("GOOGLE_APPLICATION_CREDENTIALS holds {actual} credentials, not named credential {name:?}; {other:?} names the other file identity type"), hint: None });
    }
    Ok(())
}

/// The AUTH-7 walk. `explicit`: an `api_keys` entry exists (rung 0).
/// Returns the steps and whether something may supply the credential (a
/// rung selected offline, or a configured network/subprocess rung the
/// offline doctor could not probe).
pub fn explain(
    policy: &AccessPolicy,
    ctx: &ChainContext,
    explicit: bool,
) -> Result<(Vec<Step>, bool), AuthError> {
    explain_walk(policy, ctx, explicit, None)
}

pub fn explain_named(
    policy: &AccessPolicy,
    ctx: &ChainContext,
    explicit: bool,
    name: &str,
) -> Result<(Vec<Step>, bool), AuthError> {
    if explicit {
        return Err(not_configured(
            "both api_keys and credentials select this provider's identity".into(),
        ));
    }
    explain_walk(policy, ctx, explicit, Some(name))
}

fn explain_walk(
    policy: &AccessPolicy,
    ctx: &ChainContext,
    explicit: bool,
    named: Option<&str>,
) -> Result<(Vec<Step>, bool), AuthError> {
    let mut steps = Vec::new();
    let mut selected = false;
    steps.push(Step {
        kind: "api_keys".into(),
        source: "explicit api_keys entry".into(),
        detail: if explicit {
            "provided (value never shown)".into()
        } else {
            "not provided".into()
        },
        state: if explicit { "selected" } else { "absent" },
    });
    selected |= explicit;
    for rung in walk(policy, named)? {
        let (verdict, detail) =
            match check_named_file(policy, ctx, named).and_then(|_| probe(policy, &rung, ctx)) {
                Ok(result) => result,
                Err(err) => (
                    Verdict::Absent,
                    err.to_string().lines().next().unwrap_or("").to_string(),
                ),
            };
        let state = match verdict {
            Verdict::Absent => "absent",
            Verdict::Configured => {
                if selected {
                    "shadowed"
                } else {
                    "unprobed"
                }
            }
            Verdict::Usable => {
                if selected {
                    "shadowed"
                } else {
                    selected = true;
                    "selected"
                }
            }
        };
        steps.push(Step {
            kind: rung.name.clone(),
            source: rung.source.clone(),
            detail,
            state,
        });
    }
    let configured = selected || steps.iter().any(|s| s.state == "unprobed");
    Ok((steps, configured))
}

/// Walk the chain online; the first rung that yields wins. A rung that
/// is configured and fails raises. Azure developer commands are the
/// AUTH-1 exception: all three are tried before their failure is
/// reported. Deployed Azure credentials and AWS/GCP failures never fall
/// through.
pub async fn resolve(policy: &AccessPolicy, ctx: &ChainContext) -> Result<Credential, AuthError> {
    resolve_sourced(policy, ctx, None)
        .await
        .map(|(value, _)| value)
}

pub async fn resolve_sourced(
    policy: &AccessPolicy,
    ctx: &ChainContext,
    named: Option<&str>,
) -> Result<(Credential, CredentialSource), AuthError> {
    let rungs = walk(policy, named)?;
    check_named_file(policy, ctx, named)?;
    let mut developer_failed = false;
    for rung in &rungs {
        match acquire(policy, rung, ctx).await {
            Ok(Some(credential)) => {
                let source = CredentialSource {
                    kind: rung.name.clone(),
                    label: rung.source.clone(),
                    named: named.map(str::to_string),
                    expires_at: credential.expires_at(),
                };
                return Ok((credential, source));
            }
            Ok(None) => {}
            Err(err) => {
                let developer = policy.credential_policy == CredentialPolicy::AzureChain
                    && matches!(rung.name.as_str(), "az" | "pwsh" | "azd");
                if developer && matches!(err, AuthError::Rejected { .. }) {
                    developer_failed = true;
                    continue;
                }
                let err = match err {
                    AuthError::NotConfigured {
                        provider,
                        message,
                        hint,
                    } => AuthError::NotConfigured {
                        provider,
                        message: format!(
                            "{message}\nCredential source: {}{}",
                            rung.source,
                            named
                                .map(|name| format!(" (named credential {name:?})"))
                                .unwrap_or_default()
                        ),
                        hint,
                    },
                    AuthError::Rejected {
                        provider,
                        message,
                        hint,
                    } => AuthError::Rejected {
                        provider,
                        message: format!(
                            "{message}\nCredential source: {}{}",
                            rung.source,
                            named
                                .map(|name| format!(" (named credential {name:?})"))
                                .unwrap_or_default()
                        ),
                        hint,
                    },
                    other => other,
                };
                return Err(with_provider(err, policy.provider));
            }
        }
    }
    if developer_failed {
        return Err(AuthError::Rejected {
            provider: Some(policy.provider.to_string()),
            message:
                "Azure developer credentials failed; sign in with az, Azure PowerShell, or azd"
                    .into(),
            hint: None,
        });
    }
    if let Some(name) = named {
        let probes = rungs
            .iter()
            .map(|rung| {
                let detail = probe(policy, rung, ctx)
                    .map(|(_, detail)| detail)
                    .unwrap_or_else(|err| err.to_string());
                format!("{}: {detail}", rung.source)
            })
            .collect::<Vec<_>>()
            .join("; ");
        return Err(AuthError::NotConfigured {
            provider: Some(policy.provider.into()),
            message: format!("named credential {name:?} — {} — answered nothing ({probes}); no other rung of the {} chain will be tried", named_meaning(policy, name)?, policy.credential_policy.as_str()),
            hint: Some("configure this identity, or omit the named credential to walk the chain".into()),
        });
    }
    let probed = rungs
        .iter()
        .map(|rung| {
            let detail = probe(policy, rung, ctx)
                .map(|(_, detail)| detail)
                .unwrap_or_else(|err| err.to_string());
            format!("{}: {detail}", rung.source)
        })
        .collect::<Vec<_>>()
        .join("; ");
    Err(AuthError::NotConfigured {
        provider: Some(policy.provider.to_string()),
        message: format!(
            "no credential found in the {} chain ({probed})",
            policy.credential_policy.as_str()
        ),
        hint: nothing_found_hint(policy),
    })
}

/// What to do when a whole chain answers nothing: the command that creates
/// a credential the chain reads, then the deployed alternatives.
fn nothing_found_hint(policy: &AccessPolicy) -> Option<String> {
    let hint = match policy.credential_policy {
        CredentialPolicy::GcpChain => "on a laptop: `gcloud auth application-default login`; elsewhere: set \
            GOOGLE_APPLICATION_CREDENTIALS to a service-account or workload-identity file, run on Google \
            Cloud with an attached service account, or pass an explicit credential for <provider> (a token, \
            a key, or a CredentialProvider)",
        CredentialPolicy::AzureChain => "on a laptop: `az login`; elsewhere: a managed identity, \
            AZURE_TENANT_ID + AZURE_CLIENT_ID with a secret or certificate, or an explicit credential \
            for <provider> (a token provider)",
        CredentialPolicy::AwsChain => "on a laptop: `aws sso login` or `aws configure`; elsewhere: the \
            instance or container role, AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY, or an explicit \
            credential for <provider> (a credentials provider)",
        _ => return None,
    };
    let hint = hint.replace("<provider>", policy.provider);
    Some(match policy.env_keys.first() {
        Some(key) => format!("set {key}, or {hint}"),
        None => hint,
    })
}

/// How a cloud door's wire refusal (HTTP 401/403 after a credential was
/// obtained) is fixed; replaces the generic API-key guidance. `sent` is
/// what the adapter knows it sent: `Some("key")`, `Some("token")`, or
/// `None` (a provider decides per request).
pub fn wire_auth_hint(
    policy: &AccessPolicy,
    status: Option<u16>,
    sent: Option<&str>,
) -> Option<String> {
    if policy.credential_policy != CredentialPolicy::GcpChain {
        return None;
    }
    match (status, sent) {
        (Some(403), _) => Some("give the identity named above the Vertex AI User role \
            (roles/aiplatform.user) on the project and enable the Vertex AI API \
            (aiplatform.googleapis.com); a new project or a new grant can take a few minutes to \
            apply. To use another identity: `gcloud auth application-default login`, or \
            GOOGLE_APPLICATION_CREDENTIALS=<file>".into()),
        (Some(401), Some("key")) => Some("Google refused this API key: use a Vertex AI key (Cloud \
            console > APIs & Services > Credentials, restricted to the Vertex AI API or bound to a \
            service account); Claude on Vertex takes no keys. If the value is an access token that \
            does not start with `ya29.`, pass Credential::bearer_token(value, None)".into()),
        (Some(401), _) => Some("Google refused this access token: it expired (they last an hour; \
            pass a CredentialProvider, or let lm15's chain refresh it) or it is not an OAuth token. \
            Sign in again with `gcloud auth application-default login`".into()),
        _ => None,
    }
}

fn with_provider(err: AuthError, provider: &str) -> AuthError {
    match err {
        AuthError::NotConfigured {
            provider: None,
            message,
            hint,
        } => AuthError::NotConfigured {
            provider: Some(provider.to_string()),
            message,
            hint,
        },
        AuthError::Rejected {
            provider: None,
            message,
            hint,
        } => AuthError::Rejected {
            provider: Some(provider.to_string()),
            message,
            hint,
        },
        other => other,
    }
}

/// AUTH-2/AUTH-3: resolve once, hand out until the skew window, then
/// re-resolve. In memory only; never written to a foreign file. The
/// resolution runs in [`CredentialProvider::prepare`] (async); the
/// synchronous [`CredentialProvider::credential`] answers from the cache.
pub struct ChainProvider {
    policy: &'static AccessPolicy,
    ctx: ChainContext,
    cached: Mutex<Option<(Credential, CredentialSource)>>,
    named: Option<String>,
}

impl ChainProvider {
    pub fn new(policy: &'static AccessPolicy, ctx: ChainContext) -> Self {
        ChainProvider {
            policy,
            ctx,
            cached: Mutex::new(None),
            named: None,
        }
    }

    pub fn named(
        policy: &'static AccessPolicy,
        ctx: ChainContext,
        name: &str,
    ) -> Result<Self, AuthError> {
        chain_for_named(policy, name)?;
        Ok(Self {
            named: Some(name.into()),
            ..Self::new(policy, ctx)
        })
    }

    pub fn named_credential(&self) -> Option<&str> {
        self.named.as_deref()
    }

    /// Provider id + the identity-selecting settings (AUTH-3).
    pub fn cache_key(&self) -> String {
        let e = |k: &str| self.ctx.env(k).unwrap_or("").to_string();
        let mut parts = vec![
            self.policy.provider.to_string(),
            e("AWS_PROFILE"),
            e("AZURE_TENANT_ID"),
            e("AZURE_CLIENT_ID"),
            e("GOOGLE_APPLICATION_CREDENTIALS"),
            e("CLOUDSDK_CONFIG"),
            self.ctx.home.display().to_string(),
        ];
        if let Some(name) = &self.named {
            parts.push(format!("credential={name}"));
        }
        parts.extend(self.ctx.settings.iter().map(|(k, v)| format!("{k}={v}")));
        let digest = Sha256::digest(parts.join("\u{1f}").as_bytes());
        digest.iter().map(|b| format!("{b:02x}")).collect()
    }

    fn now(&self) -> i64 {
        crate::auth::time_now()
    }

    fn fresh(&self) -> Option<Credential> {
        let cached = self.cached.lock().unwrap_or_else(|p| p.into_inner());
        cached
            .as_ref()
            .filter(|(c, _)| !c.is_expired_at(self.now()))
            .map(|(c, _)| c.clone())
    }

    /// Resolve (or refresh) the cached credential.
    pub async fn refresh(&self) -> Result<Credential, AuthError> {
        if let Some(credential) = self.fresh() {
            // A token with no expiry must resolve on every prepare, but remains
            // available to credential() for the request being prepared.
            if !matches!(
                &credential,
                Credential::BearerToken {
                    expires_at: None,
                    ..
                }
            ) {
                return Ok(credential);
            }
        }
        let mut ctx = self.ctx.clone();
        ctx.now = self.now();
        let (value, source) = resolve_sourced(self.policy, &ctx, self.named.as_deref()).await?;
        if value.is_expired_at(ctx.now) {
            return Err(AuthError::Rejected {
                provider: Some(self.policy.provider.to_string()),
                message: format!("cloud credential is expired; renew the configured credential source\nCredential source: {}", source.describe()),
                hint: None,
            });
        }
        let mut cached = self.cached.lock().unwrap_or_else(|p| p.into_inner());
        *cached = Some((value.clone(), source));
        Ok(value)
    }
}

impl CredentialProvider for ChainProvider {
    fn credential_with_source(&self) -> Result<(Credential, Option<CredentialSource>), AuthError> {
        let cached = self.cached.lock().unwrap_or_else(|p| p.into_inner());
        match cached.as_ref().filter(|(value, _)| !value.is_expired_at(self.now())) {
            Some((value, source)) => Ok((value.clone(), Some(source.clone()))),
            None => Err(AuthError::NotConfigured { provider: Some(self.policy.provider.into()), message: "the cloud credential has not been prepared or has expired; call prepare before request build".into(), hint: None }),
        }
    }
    fn source(&self) -> Option<CredentialSource> {
        self.cached
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .as_ref()
            .map(|(_, source)| source.clone())
    }
    fn credential(&self) -> Result<Credential, AuthError> {
        self.fresh().ok_or_else(|| AuthError::NotConfigured {
            provider: Some(self.policy.provider.to_string()),
            message:
                "the cloud credential chain has not been resolved yet; the adapter resolves it \
                      before a request (`prepare`), or call `refresh` on the ChainProvider"
                    .into(),
            hint: None,
        })
    }

    fn prepare(&self) -> Option<BoxFuture<'_, Result<(), AuthError>>> {
        Some(Box::pin(async move { self.refresh().await.map(|_| ()) }))
    }
}

impl std::fmt::Debug for ChainProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "<cloud credential provider for {}>",
            self.policy.provider
        )
    }
}

// ─── Harness ops (PROTOCOL.md token_exchange_build / token_exchange_parse) ──

/// The exact token-exchange request a rung would send under `ctx.now`.
pub fn token_exchange_build(
    rung: &str,
    inputs: &Map<String, Value>,
    ctx: &ChainContext,
) -> Result<Value, AuthError> {
    match rung {
        "adc-env" | "adc-file" | "service-account" => {
            let info = inputs
                .get("credential_file")
                .and_then(Value::as_object)
                .ok_or_else(|| {
                    not_configured("token_exchange_build: credential_file is required".into())
                })?;
            let scope = value_str(inputs.get("scope")).unwrap_or_else(|| GCP_SCOPE.into());
            let (token_uri, assertion) = gcp_service_account_assertion(ctx, info, &scope)?;
            Ok(json!({
                "method": "POST", "url": token_uri,
                "headers": {"content-type": "application/x-www-form-urlencoded"},
                "body_encoding": "form",
                "body": {"grant_type": JWT_BEARER, "assertion": assertion},
            }))
        }
        "environment" => {
            let (url, pairs) =
                azure_environment_request(ctx, inputs.get("jti").and_then(Value::as_str))?;
            let body: Map<String, Value> = pairs
                .into_iter()
                .map(|(k, v)| (k, Value::String(v)))
                .collect();
            Ok(json!({
                "method": "POST", "url": url,
                "headers": {"content-type": "application/x-www-form-urlencoded"},
                "body_encoding": "form",
                "body": body,
            }))
        }
        other => Err(not_configured(format!(
            "token_exchange_build: rung {other:?} has no deterministic request"
        ))),
    }
}

/// The credential a rung produces from a pinned response body.
pub fn token_exchange_parse(
    rung: &str,
    status: u16,
    body: &Map<String, Value>,
    ctx: &ChainContext,
) -> Result<Credential, AuthError> {
    match rung {
        "adc-env" | "adc-file" | "service-account" | "environment" | "workload-identity"
        | "managed-identity" | "metadata" => {
            if !(200..300).contains(&status) {
                return Err(rejected(format!("{rung}: HTTP {status}")));
            }
            bearer_from_oauth(body, ctx.now, rung)
        }
        "credential_process" => {
            if status != 0 || body.get("Version").and_then(Value::as_i64) != Some(1) {
                return Err(rejected(
                    "credential_process failed or returned an unsupported Version".into(),
                ));
            }
            aws_from_response(body)
        }
        "imds" | "container" => {
            if !(200..300).contains(&status) {
                return Err(rejected(format!("{rung}: HTTP {status}")));
            }
            aws_from_response(body)
        }
        other => Err(not_configured(format!(
            "token_exchange_parse: rung {other:?} is not a parse vector"
        ))),
    }
}

#[allow(dead_code)]
fn _format(unix: i64) -> String {
    format_rfc3339(unix)
}

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

    #[test]
    fn shlex_handles_quotes_and_escapes() {
        assert_eq!(shlex_split("a b"), ["a", "b"]);
        assert_eq!(shlex_split("a 'b c' \"d e\""), ["a", "b c", "d e"]);
        assert_eq!(shlex_split("a\\ b"), ["a b"]);
        assert_eq!(shlex_split("  "), Vec::<String>::new());
    }

    #[test]
    fn form_encoding_is_quote_plus() {
        assert_eq!(
            String::from_utf8(form(&[
                ("a b".into(), "c&d=e".into()),
                ("x".into(), "~".into())
            ]))
            .unwrap(),
            "a+b=c%26d%3De&x=~"
        );
    }

    #[test]
    fn oauth_bodies_fold_expiry_from_now() {
        let mut body = Map::new();
        body.insert("access_token".into(), json!("t"));
        body.insert("expires_in".into(), json!(3599));
        let cred = bearer_from_oauth(&body, 1788436800, "x").unwrap();
        assert_eq!(cred.expires_at(), Some(1788436800 + 3599));
        body.insert("expires_on".into(), json!("1788440399"));
        assert_eq!(
            bearer_from_oauth(&body, 0, "x").unwrap().expires_at(),
            Some(1788440399)
        );
        body.remove("access_token");
        assert!(matches!(
            bearer_from_oauth(&body, 0, "x"),
            Err(AuthError::Rejected { .. })
        ));
    }

    #[test]
    fn sts_xml_is_read_without_a_parser() {
        let xml = r#"<AssumeRoleResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"><AssumeRoleResult><Credentials><AccessKeyId>AKID</AccessKeyId><SecretAccessKey>S&amp;K</SecretAccessKey><SessionToken>T</SessionToken><Expiration>2026-09-03T13:00:00Z</Expiration></Credentials></AssumeRoleResult></AssumeRoleResponse>"#;
        let cred = sts_xml_credentials(xml.as_bytes()).unwrap();
        assert!(
            matches!(&cred, Credential::AwsCredentials { access_key_id, secret_access_key, session_token, .. }
            if access_key_id == "AKID" && secret_access_key == "S&K" && session_token.as_deref() == Some("T"))
        );
        assert_eq!(
            cred.expires_at(),
            Some(parse_rfc3339("2026-09-03T13:00:00Z").unwrap())
        );
    }

    #[test]
    fn container_uri_rules_match_botocore() {
        let mut env = BTreeMap::new();
        env.insert(
            "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI".to_string(),
            "/v2/creds".to_string(),
        );
        let ctx = ChainContext::offline(env.clone(), 0);
        assert_eq!(
            container_config(&ctx).unwrap().as_deref(),
            Some("http://169.254.170.2/v2/creds")
        );
        env.clear();
        env.insert(
            "AWS_CONTAINER_CREDENTIALS_FULL_URI".to_string(),
            "http://evil.example/x".to_string(),
        );
        assert!(container_config(&ChainContext::offline(env.clone(), 0)).is_err());
        env.insert(
            "AWS_CONTAINER_CREDENTIALS_FULL_URI".to_string(),
            "http://localhost:8080/x".to_string(),
        );
        assert!(container_config(&ChainContext::offline(env.clone(), 0))
            .unwrap()
            .is_some());
        env.insert(
            "AWS_CONTAINER_CREDENTIALS_FULL_URI".to_string(),
            "https://any.example/x".to_string(),
        );
        assert!(container_config(&ChainContext::offline(env, 0))
            .unwrap()
            .is_some());
    }
}