orbit-tui 1.1.1

Terminal UI for AWS - navigate, observe, and manage AWS resources
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
//! AWS Credentials loading from multiple sources
//!
//! Supports:
//! - Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN)
//! - AWS profiles (~/.aws/credentials and ~/.aws/config)
//! - AWS SSO (IAM Identity Center) via cached tokens
//! - Console Login (aws login command) via cached tokens in ~/.aws/login/cache/
//! - IAM Role assumption via role_arn and source_profile/credential_source
//! - ECS container credentials (via credential_source = EcsContainer)
//! - IMDSv2 (EC2 instance metadata)

use anyhow::{anyhow, Result};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use thiserror::Error;
use tracing::{debug, trace};

/// Specific errors for credential loading failures
///
/// This enum distinguishes between different authentication methods:
/// - `SsoLoginRequired`: IAM Identity Center (aws sso login) - uses sso_session config
/// - `ConsoleLoginRequired`: Console credentials (aws login) - uses login_session config
#[derive(Debug, Error)]
pub enum CredentialsError {
    /// SSO login required - user needs to run `aws sso login`
    /// This is for IAM Identity Center authentication which uses:
    /// - Profile config: sso_session, sso_account_id, sso_role_name, sso_region
    /// - Token cache: ~/.aws/sso/cache/
    #[error("SSO login required for profile '{profile}' (session: {sso_session}). Run 'aws sso login --profile {profile}'")]
    SsoLoginRequired {
        profile: String,
        sso_session: String,
    },

    /// Console login required - user needs to run `aws login`
    /// This is for AWS Console credentials authentication which uses:
    /// - Profile config: login_session (typically an IAM user/role ARN)
    /// - Token cache: ~/.aws/login/cache/
    #[error("Console login required for profile '{profile}' (session: {login_session}). Run 'aws login --profile {profile}'")]
    ConsoleLoginRequired {
        profile: String,
        login_session: String,
    },

    #[error("{0}")]
    Other(#[from] anyhow::Error),
}

/// AWS credentials
#[derive(Debug, Clone)]
pub struct Credentials {
    pub access_key_id: String,
    pub secret_access_key: String,
    pub session_token: Option<String>,
}

/// Cached IMDS credentials with expiration
struct CachedImdsCredentials {
    credentials: Credentials,
    expiration: Instant,
}

/// Global cache for IMDS credentials
static IMDS_CACHE: OnceLock<std::sync::Mutex<Option<CachedImdsCredentials>>> = OnceLock::new();

/// Global cache for SSO credentials (keyed by profile name)
static SSO_CACHE: OnceLock<std::sync::Mutex<HashMap<String, CachedImdsCredentials>>> =
    OnceLock::new();

/// Global cache for Process credentials (keyed by profile name)
static PROCESS_CACHE: OnceLock<std::sync::Mutex<HashMap<String, CachedImdsCredentials>>> =
    OnceLock::new();

/// Global cache for Assume Role credentials (keyed by profile name)
static ASSUME_ROLE_CACHE: OnceLock<std::sync::Mutex<HashMap<String, CachedImdsCredentials>>> =
    OnceLock::new();

/// Global cache for ECS container credentials
static ECS_CACHE: OnceLock<std::sync::Mutex<Option<CachedImdsCredentials>>> = OnceLock::new();

/// Global cache for Console Login credentials (keyed by profile name)
static CONSOLE_LOGIN_CACHE: OnceLock<std::sync::Mutex<HashMap<String, CachedImdsCredentials>>> =
    OnceLock::new();

/// ECS container credentials endpoint base
const ECS_CREDENTIALS_ENDPOINT: &str = "http://169.254.170.2";

/// IMDSv2 metadata endpoint
const IMDS_ENDPOINT: &str = "http://169.254.169.254";
/// IMDSv2 token TTL in seconds (6 hours)
const IMDS_TOKEN_TTL: u64 = 21600;
/// Timeout for IMDS requests (2 seconds - fast fail if not on EC2)
const IMDS_TIMEOUT: Duration = Duration::from_secs(2);
/// Refresh credentials 5 minutes before expiration
const CREDENTIAL_REFRESH_BUFFER: Duration = Duration::from_secs(300);

/// Load credentials for a given profile
pub fn load_credentials(profile: &str) -> Result<Credentials> {
    load_credentials_inner(profile).map_err(|e| match e {
        CredentialsError::SsoLoginRequired {
            profile,
            sso_session,
        } => {
            anyhow!(
                "SSO login required for profile '{}' (session: {}). Run 'aws sso login --profile {}'",
                profile,
                sso_session,
                profile
            )
        }
        CredentialsError::ConsoleLoginRequired {
            profile,
            login_session,
        } => {
            anyhow!(
                "Console login required for profile '{}' (session: {}). Run 'aws login --profile {}'",
                profile,
                login_session,
                profile
            )
        }
        CredentialsError::Other(e) => e,
    })
}

/// Load credentials with detailed error types for SSO and Console Login
///
/// Returns specific error variants that distinguish between:
/// - `SsoLoginRequired`: User needs to run `aws sso login` (IAM Identity Center)
/// - `ConsoleLoginRequired`: User needs to run `aws login` (Console credentials)
pub fn load_credentials_with_sso_check(profile: &str) -> Result<Credentials, CredentialsError> {
    load_credentials_inner(profile)
}

/// Internal credential loading with specific SSO error
fn load_credentials_inner(profile: &str) -> Result<Credentials, CredentialsError> {
    // 1. Try environment variables first (if default profile or explicitly set)
    if profile == "default" {
        if let Ok(creds) = load_from_env() {
            debug!("Loaded credentials from environment variables");
            return Ok(creds);
        }
    }

    // 2. Check if SSO is configured for this profile - if so, prioritize SSO
    //    This ensures we don't use stale static credentials when SSO is the intended auth method
    if let Some(sso_config) = super::sso::get_sso_config(profile) {
        debug!(
            "SSO is configured for profile '{}', trying SSO first",
            profile
        );
        match load_from_sso(profile) {
            Ok(creds) => {
                debug!("Loaded credentials from AWS SSO for profile '{}'", profile);
                return Ok(creds);
            }
            Err(e) => {
                debug!(
                    "SSO configured for profile '{}' but token unavailable: {}",
                    profile, e
                );
                return Err(CredentialsError::SsoLoginRequired {
                    profile: profile.to_string(),
                    sso_session: sso_config.sso_session,
                });
            }
        }
    }

    // 2.5. Check if console login is configured for this profile (aws login)
    if let Some(login_session) = get_login_session_config(profile) {
        debug!(
            "Console login session configured for profile '{}': {}",
            profile, login_session
        );
        match load_from_console_login(profile, &login_session) {
            Ok(creds) => {
                debug!(
                    "Loaded credentials from console login cache for profile '{}'",
                    profile
                );
                return Ok(creds);
            }
            Err(e) => {
                debug!(
                    "Console login configured for profile '{}' but credentials unavailable: {}",
                    profile, e
                );
                return Err(CredentialsError::ConsoleLoginRequired {
                    profile: profile.to_string(),
                    login_session,
                });
            }
        }
    }

    // 3. Check if role_arn is configured for this profile (role assumption)
    if let Some(assume_role_config) = get_assume_role_config(profile) {
        debug!(
            "Role assumption configured for profile '{}', role_arn: {}",
            profile, assume_role_config.role_arn
        );

        // 3a. First try to read from AWS CLI cache (credentials from `aws` CLI commands)
        if let Ok(creds) = load_from_cli_cache(profile, &assume_role_config.role_arn) {
            debug!(
                "Loaded credentials from AWS CLI cache for profile '{}'",
                profile
            );
            return Ok(creds);
        }

        // 3b. Fall back to performing role assumption ourselves
        match load_from_assume_role(profile, &assume_role_config) {
            Ok(creds) => {
                debug!(
                    "Loaded credentials via role assumption for profile '{}'",
                    profile
                );
                return Ok(creds);
            }
            Err(e) => {
                debug!("Role assumption failed for profile '{}': {}", profile, e);
                return Err(CredentialsError::Other(e));
            }
        }
    }

    // 5. Try AWS credentials file
    if let Ok(creds) = load_from_credentials_file(profile) {
        debug!(
            "Loaded credentials from credentials file for profile '{}'",
            profile
        );
        return Ok(creds);
    }

    // 6. Try config file with direct credentials
    if let Ok(creds) = load_from_config_file(profile) {
        debug!(
            "Loaded credentials from config file for profile '{}'",
            profile
        );
        return Ok(creds);
    }

    // 7. Try IMDSv2 (EC2 instance metadata) - only for default profile
    if profile == "default" {
        match load_from_imds() {
            Ok(creds) => {
                debug!("Loaded credentials from EC2 instance metadata (IMDSv2)");
                return Ok(creds);
            }
            Err(e) => {
                debug!("IMDSv2 credential loading failed: {}", e);
            }
        }
    }

    Err(CredentialsError::Other(anyhow!(
        "No credentials found for profile '{}'. Run 'aws configure', 'aws sso login --profile {}', 'aws login --profile {}', or set AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY",
        profile,
        profile,
        profile
    )))
}

/// Load credentials from environment variables
fn load_from_env() -> Result<Credentials> {
    let access_key_id =
        env::var("AWS_ACCESS_KEY_ID").map_err(|_| anyhow!("AWS_ACCESS_KEY_ID not set"))?;
    let secret_access_key =
        env::var("AWS_SECRET_ACCESS_KEY").map_err(|_| anyhow!("AWS_SECRET_ACCESS_KEY not set"))?;
    let session_token = env::var("AWS_SESSION_TOKEN").ok();

    Ok(Credentials {
        access_key_id,
        secret_access_key,
        session_token,
    })
}

/// Get AWS config directory
pub fn aws_config_dir() -> Result<PathBuf> {
    if let Ok(path) = env::var("AWS_CONFIG_FILE") {
        if let Some(parent) = PathBuf::from(path).parent() {
            return Ok(parent.to_path_buf());
        }
    }

    dirs::home_dir()
        .map(|h| h.join(".aws"))
        .ok_or_else(|| anyhow!("Could not find home directory"))
}

/// Get the AWS config file path, respecting AWS_CONFIG_FILE environment variable
pub fn get_aws_config_file_path() -> Result<PathBuf> {
    if let Ok(path) = env::var("AWS_CONFIG_FILE") {
        return Ok(PathBuf::from(path));
    }

    dirs::home_dir()
        .map(|h| h.join(".aws").join("config"))
        .ok_or_else(|| anyhow!("Could not find home directory"))
}

/// Parse an INI-style file into sections
/// Returns (profiles, sso_sessions) where sso_sessions contains [sso-session X] sections
fn parse_ini_file(content: &str) -> HashMap<String, HashMap<String, String>> {
    let mut sections: HashMap<String, HashMap<String, String>> = HashMap::new();
    let mut current_section = String::new();

    for line in content.lines() {
        let line = line.trim();

        // Skip empty lines and comments
        if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
            continue;
        }

        // Section header
        if line.starts_with('[') && line.ends_with(']') {
            current_section = line[1..line.len() - 1].trim().to_string();
            // Handle "profile name" format in config file
            if current_section.starts_with("profile ") {
                current_section = current_section["profile ".len()..].to_string();
            }
            // Keep sso-session sections with their prefix for identification
            sections.entry(current_section.clone()).or_default();
            continue;
        }

        // Key-value pair
        if let Some((key, value)) = line.split_once('=') {
            if !current_section.is_empty() {
                sections
                    .entry(current_section.clone())
                    .or_default()
                    .insert(key.trim().to_string(), value.trim().to_string());
            }
        }
    }

    sections
}

/// Load credentials from ~/.aws/credentials or AWS_SHARED_CREDENTIALS_FILE
fn load_from_credentials_file(profile: &str) -> Result<Credentials> {
    // Check AWS_SHARED_CREDENTIALS_FILE env var first (AWS SDK standard)
    let creds_path = if let Ok(path) = env::var("AWS_SHARED_CREDENTIALS_FILE") {
        PathBuf::from(path)
    } else {
        aws_config_dir()?.join("credentials")
    };
    let content =
        fs::read_to_string(&creds_path).map_err(|_| anyhow!("Could not read {:?}", creds_path))?;

    let sections = parse_ini_file(&content);

    let section = sections
        .get(profile)
        .ok_or_else(|| anyhow!("Profile '{}' not found in credentials file", profile))?;

    if let Some(command) = section.get("credential_process") {
        debug!("Found credential_process for profile '{}'", profile);
        return load_from_process(profile, command);
    }

    let access_key_id = section
        .get("aws_access_key_id")
        .ok_or_else(|| anyhow!("aws_access_key_id not found for profile '{}'", profile))?
        .clone();

    let secret_access_key = section
        .get("aws_secret_access_key")
        .ok_or_else(|| anyhow!("aws_secret_access_key not found for profile '{}'", profile))?
        .clone();

    let session_token = section.get("aws_session_token").cloned();

    Ok(Credentials {
        access_key_id,
        secret_access_key,
        session_token,
    })
}

/// Load credentials from ~/.aws/config (for direct credentials only)
fn load_from_config_file(profile: &str) -> Result<Credentials> {
    let config_path = get_aws_config_file_path()?;
    let content = fs::read_to_string(&config_path)
        .map_err(|_| anyhow!("Could not read {:?}", config_path))?;

    let sections = parse_ini_file(&content);

    let section = sections
        .get(profile)
        .ok_or_else(|| anyhow!("Profile '{}' not found in config file", profile))?;

    if let Some(command) = section.get("credential_process") {
        debug!("Found credential_process for profile '{}'", profile);
        return load_from_process(profile, command);
    }

    // Check for direct credentials in config (less common but valid)
    if let (Some(access_key), Some(secret_key)) = (
        section.get("aws_access_key_id"),
        section.get("aws_secret_access_key"),
    ) {
        return Ok(Credentials {
            access_key_id: access_key.clone(),
            secret_access_key: secret_key.clone(),
            session_token: section.get("aws_session_token").cloned(),
        });
    }

    Err(anyhow!(
        "No direct credentials found in config for profile '{}'",
        profile
    ))
}

// =============================================================================
// AWS SSO (IAM Identity Center) Support
// =============================================================================

/// Load credentials from AWS SSO (IAM Identity Center)
/// This only works with cached tokens - for interactive login, use the sso module directly
fn load_from_sso(profile: &str) -> Result<Credentials> {
    use super::sso;

    // Check credential cache first (keyed by profile)
    let cache = SSO_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));

    if let Ok(guard) = cache.lock() {
        if let Some(cached) = guard.get(profile) {
            if cached.expiration > Instant::now() + CREDENTIAL_REFRESH_BUFFER {
                trace!("Using cached SSO credentials for profile '{}'", profile);
                return Ok(cached.credentials.clone());
            }
        }
    }

    // Get SSO config for this profile
    let sso_config = sso::get_sso_config(profile)
        .ok_or_else(|| anyhow!("Profile '{}' does not have SSO configured", profile))?;

    // Try to read cached SSO token
    let access_token = sso::read_cached_token(&sso_config).ok_or_else(|| {
        anyhow!(
            "SSO token not found or expired for profile '{}'. Interactive login required.",
            profile
        )
    })?;

    // Exchange token for credentials
    let credentials = sso::get_role_credentials(&sso_config, &access_token)?;

    // Cache the credentials (keyed by profile)
    let expiration = Instant::now() + Duration::from_secs(3600); // Default 1 hour
    let cache = SSO_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));
    if let Ok(mut guard) = cache.lock() {
        guard.insert(
            profile.to_string(),
            CachedImdsCredentials {
                credentials: credentials.clone(),
                expiration,
            },
        );
        debug!("Cached SSO credentials for profile '{}'", profile);
    }

    Ok(credentials)
}

// =============================================================================
// Console Login Support (aws login command)
// =============================================================================

/// Check if console login is configured for a profile
fn get_login_session_config(profile: &str) -> Option<String> {
    let config_path = get_aws_config_file_path().ok()?;
    let content = fs::read_to_string(&config_path).ok()?;
    let sections = parse_ini_file(&content);

    sections
        .get(profile)
        .and_then(|section| section.get("login_session").cloned())
}

/// Get the console login cache directory
/// Respects AWS_LOGIN_CACHE_DIRECTORY environment variable
fn get_login_cache_dir() -> Result<PathBuf> {
    if let Ok(dir) = env::var("AWS_LOGIN_CACHE_DIRECTORY") {
        return Ok(PathBuf::from(dir));
    }
    Ok(aws_config_dir()?.join("login").join("cache"))
}

/// Load credentials from console login cache (~/.aws/login/cache/)
/// Cache filename is SHA256(login_session.trim()).hex() + ".json"
fn load_from_console_login(profile: &str, login_session: &str) -> Result<Credentials> {
    use sha2::{Digest, Sha256};

    // Check cache first
    let cache = CONSOLE_LOGIN_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));

    if let Ok(guard) = cache.lock() {
        if let Some(cached) = guard.get(profile) {
            if cached.expiration > Instant::now() + CREDENTIAL_REFRESH_BUFFER {
                trace!(
                    "Using cached console login credentials for profile '{}'",
                    profile
                );
                return Ok(cached.credentials.clone());
            }
        }
    }

    let cache_dir = get_login_cache_dir()?;

    if !cache_dir.exists() {
        return Err(anyhow!(
            "Console login cache directory not found. Run 'aws login'"
        ));
    }

    // Cache filename is SHA256 hash of the login_session ARN (trimmed)
    let mut hasher = Sha256::new();
    hasher.update(login_session.trim().as_bytes());
    let hash = hasher.finalize();
    let cache_filename = format!("{}.json", hex::encode(hash));
    let cache_file = cache_dir.join(&cache_filename);

    if !cache_file.exists() {
        return Err(anyhow!(
            "No login cache file found for profile '{}'. Run 'aws login --profile {}'",
            profile,
            profile
        ));
    }

    debug!("Reading login cache from {:?}", cache_file);

    let content = fs::read_to_string(&cache_file)
        .map_err(|e| anyhow!("Failed to read login cache: {}", e))?;

    let cache_data: serde_json::Value = serde_json::from_str(&content)
        .map_err(|e| anyhow!("Failed to parse login cache: {}", e))?;

    // Extract credentials from accessToken object
    let access_token = cache_data
        .get("accessToken")
        .ok_or_else(|| anyhow!("accessToken not found in login cache"))?;

    let access_key_id = access_token
        .get("accessKeyId")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("accessKeyId not found in login cache"))?
        .to_string();

    let secret_access_key = access_token
        .get("secretAccessKey")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("secretAccessKey not found in login cache"))?
        .to_string();

    let session_token = access_token
        .get("sessionToken")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    // Check expiration and determine cache duration
    let expiration = if let Some(exp_str) = access_token.get("expiresAt").and_then(|v| v.as_str()) {
        if let Ok(expiration_time) = chrono::DateTime::parse_from_rfc3339(exp_str) {
            if expiration_time <= chrono::Utc::now() {
                return Err(anyhow!(
                    "Console login credentials expired. Run 'aws login --profile {}'",
                    profile
                ));
            }
            trace!("Login credentials valid until: {}", expiration_time);

            // Convert to Instant for caching
            let now = chrono::Utc::now();
            let duration_until_expiration = (expiration_time.with_timezone(&chrono::Utc) - now)
                .to_std()
                .unwrap_or(Duration::from_secs(3600));
            Instant::now() + duration_until_expiration
        } else {
            // Default to 1 hour if parsing fails
            Instant::now() + Duration::from_secs(3600)
        }
    } else {
        // Default to 1 hour if no expiration provided
        Instant::now() + Duration::from_secs(3600)
    };

    let credentials = Credentials {
        access_key_id,
        secret_access_key,
        session_token,
    };

    // Cache the credentials
    if let Ok(mut guard) = cache.lock() {
        guard.insert(
            profile.to_string(),
            CachedImdsCredentials {
                credentials: credentials.clone(),
                expiration,
            },
        );
        debug!(
            "Cached console login credentials for profile '{}', expires in {:?}",
            profile,
            expiration - Instant::now()
        );
    }

    Ok(credentials)
}

// =============================================================================
// AWS CLI Cache Support
// =============================================================================

/// Load credentials from AWS CLI cache directory (~/.aws/cli/cache/)
/// The AWS CLI caches assumed role credentials when using profiles with role_arn
fn load_from_cli_cache(profile: &str, role_arn: &str) -> Result<Credentials> {
    let cache_dir = aws_config_dir()?.join("cli").join("cache");

    if !cache_dir.exists() {
        return Err(anyhow!("AWS CLI cache directory not found"));
    }

    trace!(
        "Searching AWS CLI cache for role_arn: {} (profile: {})",
        role_arn,
        profile
    );

    // Search through all cache files to find one matching this role_arn
    let entries = fs::read_dir(&cache_dir)
        .map_err(|e| anyhow!("Failed to read CLI cache directory: {}", e))?;

    for entry in entries.flatten() {
        let path = entry.path();

        // Only process .json files
        if path.extension().and_then(|s| s.to_str()) != Some("json") {
            continue;
        }

        // Try to read and parse the cache file
        if let Some(creds) = try_read_cli_cache_file(&path, role_arn) {
            debug!("Found valid credentials in CLI cache: {:?}", path);
            return Ok(creds);
        }
    }

    Err(anyhow!(
        "No valid cached credentials found for profile '{}'",
        profile
    ))
}

/// Try to read credentials from a CLI cache file if it matches the role_arn
fn try_read_cli_cache_file(path: &std::path::Path, role_arn: &str) -> Option<Credentials> {
    let content = fs::read_to_string(path).ok()?;
    let cache_data: serde_json::Value = serde_json::from_str(&content).ok()?;

    // Check if this cache file matches our role_arn
    // AssumedRoleUser ARN format: arn:aws:sts::account-id:assumed-role/role-name/session-name
    // role_arn format: arn:aws:iam::account-id:role/role-name
    let assumed_role_arn = cache_data
        .get("AssumedRoleUser")
        .and_then(|u| u.get("Arn"))
        .and_then(|a| a.as_str())?;

    // Extract role name and account from both ARNs and compare
    let cache_parts: Vec<&str> = assumed_role_arn.split(':').collect();
    let config_parts: Vec<&str> = role_arn.split(':').collect();

    // Compare account IDs (index 4)
    if cache_parts.get(4) != config_parts.get(4) {
        return None;
    }

    // Extract role names
    // assumed-role ARN: "assumed-role/role-name/session" -> role-name is second part
    // role ARN: "role/role-name" -> role-name is second part
    let cache_role_name = assumed_role_arn.split('/').nth(1)?;
    let config_role_name = role_arn.split('/').next_back()?;

    if cache_role_name != config_role_name {
        return None;
    }

    // Extract credentials
    let creds = cache_data.get("Credentials")?;

    let access_key_id = creds.get("AccessKeyId").and_then(|v| v.as_str())?;
    let secret_access_key = creds.get("SecretAccessKey").and_then(|v| v.as_str())?;
    let session_token = creds.get("SessionToken").and_then(|v| v.as_str());

    // Check expiration
    if let Some(expiration_str) = creds.get("Expiration").and_then(|v| v.as_str()) {
        if let Ok(expiration) = chrono::DateTime::parse_from_rfc3339(expiration_str) {
            if expiration <= chrono::Utc::now() {
                trace!("CLI cache credentials expired: {:?}", path);
                return None;
            }
            trace!(
                "CLI cache credentials valid until: {} (file: {:?})",
                expiration,
                path
            );
        }
    }

    Some(Credentials {
        access_key_id: access_key_id.to_string(),
        secret_access_key: secret_access_key.to_string(),
        session_token: session_token.map(|s| s.to_string()),
    })
}

// =============================================================================
// Process Credentials Support
// =============================================================================

/// Load credentials from external process
fn load_from_process(profile: &str, command: &str) -> Result<Credentials> {
    // Check cache first
    let cache = PROCESS_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));

    if let Ok(guard) = cache.lock() {
        if let Some(cached) = guard.get(profile) {
            // If the credentials are still valid, use them
            if cached.expiration > Instant::now() + CREDENTIAL_REFRESH_BUFFER {
                trace!("Using cached process credentials for profile '{}'", profile);
                return Ok(cached.credentials.clone());
            }
        }
    }

    // Execute command
    let (credentials, expiration) = execute_credential_process(command)?;

    // Determine cache expiration
    // If expiration is provided, use it (temporary credentials).
    // If not, treat as long-term credentials and cache for a very long time
    // to avoid re-running the process unnecessarily.
    let cache_expiration = expiration.unwrap_or_else(|| {
        Instant::now() + Duration::from_secs(365 * 24 * 60 * 60) // 1 year
    });

    // Cache the credentials
    if let Ok(mut guard) = cache.lock() {
        guard.insert(
            profile.to_string(),
            CachedImdsCredentials {
                credentials: credentials.clone(),
                expiration: cache_expiration,
            },
        );
        if expiration.is_some() {
            debug!(
                "Cached temporary process credentials for profile '{}'",
                profile
            );
        } else {
            debug!(
                "Cached long-term process credentials for profile '{}'",
                profile
            );
        }
    }

    Ok(credentials)
}

fn execute_credential_process(command: &str) -> Result<(Credentials, Option<Instant>)> {
    debug!("Executing credential_process: {}", command);

    #[cfg(not(windows))]
    let shell_cmd = Command::new("sh").arg("-c").arg(command).output();

    #[cfg(windows)]
    let shell_cmd = Command::new("cmd").arg("/C").arg(command).output();

    let output = shell_cmd.map_err(|e| anyhow!("Failed to execute credential_process: {}", e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow!(
            "credential_process failed with status {}: {}",
            output.status,
            stderr
        ));
    }

    let output_str = String::from_utf8(output.stdout)
        .map_err(|e| anyhow!("Invalid UTF-8 output from credential_process: {}", e))?;

    let json: serde_json::Value = serde_json::from_str(&output_str)
        .map_err(|e| anyhow!("Failed to parse credential_process output: {}", e))?;

    // Check version (should be 1)
    if let Some(version) = json.get("Version").and_then(|v| v.as_i64()) {
        if version != 1 {
            return Err(anyhow!(
                "Unsupported credential_process version: {}",
                version
            ));
        }
    }

    let access_key_id = json
        .get("AccessKeyId")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("AccessKeyId missing in credential_process output"))?
        .to_string();

    let secret_access_key = json
        .get("SecretAccessKey")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("SecretAccessKey missing in credential_process output"))?
        .to_string();

    let session_token = json
        .get("SessionToken")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let expiration = json
        .get("Expiration")
        .and_then(|v| v.as_str())
        .and_then(parse_expiration);

    Ok((
        Credentials {
            access_key_id,
            secret_access_key,
            session_token,
        },
        expiration,
    ))
}

/// Get the default region for a profile
#[allow(dead_code)]
pub fn get_profile_region(profile: &str) -> Option<String> {
    // 1. Check environment variable
    if let Ok(region) = env::var("AWS_REGION") {
        return Some(region);
    }
    if let Ok(region) = env::var("AWS_DEFAULT_REGION") {
        return Some(region);
    }

    // 2. Check config file
    if let Ok(config_dir) = aws_config_dir() {
        let config_path = config_dir.join("config");
        if let Ok(content) = fs::read_to_string(&config_path) {
            let sections = parse_ini_file(&content);
            if let Some(section) = sections.get(profile) {
                if let Some(region) = section.get("region") {
                    return Some(region.clone());
                }
            }
        }
    }

    None
}

/// List available AWS profiles
#[allow(dead_code)]
pub fn list_profiles() -> Vec<String> {
    let mut profiles = Vec::new();

    if let Ok(config_dir) = aws_config_dir() {
        // Read from credentials file
        if let Ok(content) = fs::read_to_string(config_dir.join("credentials")) {
            let sections = parse_ini_file(&content);
            profiles.extend(sections.keys().cloned());
        }

        // Read from config file
        if let Ok(content) = fs::read_to_string(config_dir.join("config")) {
            let sections = parse_ini_file(&content);
            for key in sections.keys() {
                if !profiles.contains(key) {
                    profiles.push(key.clone());
                }
            }
        }
    }

    profiles.sort();
    profiles
}

// =============================================================================
// IAM Role Assumption Support (role_arn + source_profile)
// =============================================================================

/// Configuration for assuming an IAM role
#[derive(Debug, Clone)]
pub struct AssumeRoleConfig {
    /// The ARN of the role to assume
    pub role_arn: String,
    /// The source profile to use for credentials (mutually exclusive with credential_source)
    pub source_profile: Option<String>,
    /// The credential source type (mutually exclusive with source_profile)
    /// Valid values: "Environment", "Ec2InstanceMetadata", "EcsContainer"
    pub credential_source: Option<CredentialSource>,
    /// Optional external ID for cross-account access
    pub external_id: Option<String>,
    /// Optional role session name (defaults to "orbit-session")
    pub role_session_name: Option<String>,
    /// Optional duration in seconds (defaults to 3600)
    pub duration_seconds: Option<u32>,
    /// Region for STS endpoint (from source profile or default)
    pub region: Option<String>,
}

/// Supported credential sources for role assumption
#[derive(Debug, Clone, PartialEq)]
pub enum CredentialSource {
    /// Load credentials from environment variables
    Environment,
    /// Load credentials from EC2 instance metadata (IMDSv2)
    Ec2InstanceMetadata,
    /// Load credentials from ECS container credentials endpoint
    EcsContainer,
}

/// Check if role assumption is configured for a profile
fn get_assume_role_config(profile: &str) -> Option<AssumeRoleConfig> {
    // Respect AWS_CONFIG_FILE environment variable
    let config_path = if let Ok(path) = env::var("AWS_CONFIG_FILE") {
        PathBuf::from(path)
    } else {
        aws_config_dir().ok()?.join("config")
    };
    let content = fs::read_to_string(&config_path).ok()?;
    let sections = parse_ini_file(&content);

    let section = sections.get(profile)?;

    // Must have role_arn to be a role assumption profile
    let role_arn = section.get("role_arn")?.clone();

    // Get source_profile and credential_source
    let source_profile = section.get("source_profile").cloned();
    let credential_source = section
        .get("credential_source")
        .and_then(|s| parse_credential_source(s));

    // Must have exactly one of source_profile or credential_source
    match (&source_profile, &credential_source) {
        (Some(_), Some(_)) => {
            debug!(
                "Profile '{}' has both source_profile and credential_source - invalid configuration",
                profile
            );
            return None;
        }
        (None, None) => {
            debug!(
                "Profile '{}' has role_arn but neither source_profile nor credential_source",
                profile
            );
            return None;
        }
        _ => {}
    }

    Some(AssumeRoleConfig {
        role_arn,
        source_profile,
        credential_source,
        external_id: section.get("external_id").cloned(),
        role_session_name: section.get("role_session_name").cloned(),
        duration_seconds: section.get("duration_seconds").and_then(|s| s.parse().ok()),
        region: section.get("region").cloned(),
    })
}

/// Parse credential_source string value
fn parse_credential_source(value: &str) -> Option<CredentialSource> {
    match value {
        "Environment" => Some(CredentialSource::Environment),
        "Ec2InstanceMetadata" => Some(CredentialSource::Ec2InstanceMetadata),
        "EcsContainer" => Some(CredentialSource::EcsContainer),
        _ => {
            debug!("Unknown credential_source value: {}", value);
            None
        }
    }
}

/// Load credentials by assuming a role using source profile or credential_source
fn load_from_assume_role(profile: &str, config: &AssumeRoleConfig) -> Result<Credentials> {
    // Check cache first
    let cache = ASSUME_ROLE_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));

    if let Ok(guard) = cache.lock() {
        if let Some(cached) = guard.get(profile) {
            if cached.expiration > Instant::now() + CREDENTIAL_REFRESH_BUFFER {
                trace!(
                    "Using cached assume role credentials for profile '{}'",
                    profile
                );
                return Ok(cached.credentials.clone());
            }
        }
    }

    // Load source credentials based on configuration
    let source_creds = if let Some(ref source_profile) = config.source_profile {
        // Recursively load credentials from source profile
        // This handles chained role assumption (source_profile can also use role_arn)
        debug!(
            "Loading source credentials from profile '{}'",
            source_profile
        );
        load_credentials(source_profile).map_err(|e| {
            anyhow!(
                "Failed to load source credentials from profile '{}': {}",
                source_profile,
                e
            )
        })?
    } else if let Some(ref credential_source) = config.credential_source {
        // Load credentials from credential_source
        debug!(
            "Loading source credentials from credential_source: {:?}",
            credential_source
        );
        load_from_credential_source(credential_source)?
    } else {
        return Err(anyhow!(
            "Profile '{}' has role_arn but no source_profile or credential_source",
            profile
        ));
    };

    // Determine region for STS call
    let region = config
        .region
        .clone()
        .or_else(|| {
            config
                .source_profile
                .as_ref()
                .and_then(|p| get_profile_region(p))
        })
        .unwrap_or_else(|| "us-east-1".to_string());

    // Call STS AssumeRole
    let (credentials, expiration) = call_sts_assume_role(config, &source_creds, &region)?;

    // Cache the credentials
    if let Ok(mut guard) = cache.lock() {
        guard.insert(
            profile.to_string(),
            CachedImdsCredentials {
                credentials: credentials.clone(),
                expiration,
            },
        );
        debug!(
            "Cached assume role credentials for profile '{}', expires in {:?}",
            profile,
            expiration - Instant::now()
        );
    }

    Ok(credentials)
}

/// Load credentials from a credential_source
fn load_from_credential_source(source: &CredentialSource) -> Result<Credentials> {
    match source {
        CredentialSource::Environment => {
            debug!("Loading credentials from Environment");
            load_from_env()
        }
        CredentialSource::Ec2InstanceMetadata => {
            debug!("Loading credentials from Ec2InstanceMetadata (IMDSv2)");
            load_from_imds()
        }
        CredentialSource::EcsContainer => {
            debug!("Loading credentials from EcsContainer");
            load_from_ecs_container()
        }
    }
}

/// Call STS AssumeRole API using signed HTTP request
fn call_sts_assume_role(
    config: &AssumeRoleConfig,
    source_creds: &Credentials,
    region: &str,
) -> Result<(Credentials, Instant)> {
    use aws_sigv4::http_request::{sign, SignableBody, SignableRequest, SigningSettings};
    use aws_sigv4::sign::v4::SigningParams;
    use aws_smithy_runtime_api::client::identity::Identity;
    use std::time::SystemTime;

    let role_session_name = config
        .role_session_name
        .clone()
        .unwrap_or_else(|| "orbit-session".to_string());
    let duration_seconds = config.duration_seconds.unwrap_or(3600);

    // Build STS endpoint - respect AWS_ENDPOINT_URL or ORBIT_STS_ENDPOINT for LocalStack/testing
    let sts_endpoint = env::var("ORBIT_STS_ENDPOINT")
        .or_else(|_| env::var("AWS_ENDPOINT_URL"))
        .unwrap_or_else(|_| format!("https://sts.{}.amazonaws.com", region));

    // Build query parameters
    let mut params = vec![
        ("Action", "AssumeRole"),
        ("Version", "2011-06-15"),
        ("RoleArn", &config.role_arn),
        ("RoleSessionName", &role_session_name),
    ];

    let duration_str = duration_seconds.to_string();
    params.push(("DurationSeconds", &duration_str));

    if let Some(ref external_id) = config.external_id {
        params.push(("ExternalId", external_id));
    }

    let query_string: String = params
        .iter()
        .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
        .collect::<Vec<_>>()
        .join("&");

    // Build full URL - handle endpoints with or without trailing slash
    let base = sts_endpoint.trim_end_matches('/');
    let url = format!("{}/?{}", base, query_string);

    debug!("Calling STS AssumeRole: {}", config.role_arn);
    debug!("STS endpoint: {}", sts_endpoint);
    trace!("STS URL: {}", url);

    // Parse URL for signing
    let parsed_url = url::Url::parse(&url)?;
    let host = parsed_url
        .host_str()
        .ok_or_else(|| anyhow!("Invalid STS URL"))?;
    let path_and_query = if let Some(query) = parsed_url.query() {
        format!("{}?{}", parsed_url.path(), query)
    } else {
        parsed_url.path().to_string()
    };

    // Build headers for signing
    let headers = [("host".to_string(), host.to_string())];

    // Create identity for signing
    let creds = aws_credential_types::Credentials::new(
        &source_creds.access_key_id,
        &source_creds.secret_access_key,
        source_creds.session_token.clone(),
        None,
        "orbit",
    );
    let identity: Identity = creds.into();

    // Create signing params
    let signing_params = SigningParams::builder()
        .identity(&identity)
        .region(region)
        .name("sts")
        .time(SystemTime::now())
        .settings(SigningSettings::default())
        .build()?
        .into();

    // Create signable request
    let signable_request = SignableRequest::new(
        "POST",
        &path_and_query,
        headers.iter().map(|(k, v)| (k.as_str(), v.as_str())),
        SignableBody::Bytes(&[]),
    )?;

    // Sign the request
    let (signing_instructions, _signature) = sign(signable_request, &signing_params)?.into_parts();

    // Build and send the request
    let client = super::tls::create_blocking_client_with_timeout(Duration::from_secs(30))?;

    let mut request = client.post(&url);

    // Apply signing headers
    for (name, value) in signing_instructions.headers() {
        request = request.header(name.to_string(), value.to_string());
    }

    let response = request.send()?;
    let status = response.status();
    let text = response.text()?;

    if !status.is_success() {
        // Parse error message from XML response
        let error_msg = parse_sts_error(&text).unwrap_or_else(|| text.clone());
        return Err(anyhow!("STS AssumeRole failed ({}): {}", status, error_msg));
    }

    // Parse the XML response
    parse_assume_role_response(&text)
}

/// Parse STS error response
fn parse_sts_error(xml: &str) -> Option<String> {
    // Simple XML parsing for error message
    // Format: <Error><Code>...</Code><Message>...</Message></Error>
    let code_start = xml.find("<Code>")? + 6;
    let code_end = xml.find("</Code>")?;
    let code = &xml[code_start..code_end];

    let msg_start = xml.find("<Message>")? + 9;
    let msg_end = xml.find("</Message>")?;
    let message = &xml[msg_start..msg_end];

    Some(format!("{}: {}", code, message))
}

/// Parse AssumeRole XML response
fn parse_assume_role_response(xml: &str) -> Result<(Credentials, Instant)> {
    // Parse XML response for credentials
    // Format: <AssumeRoleResponse><AssumeRoleResult><Credentials>...</Credentials></AssumeRoleResult></AssumeRoleResponse>

    let extract_value = |tag: &str| -> Option<String> {
        let start_tag = format!("<{}>", tag);
        let end_tag = format!("</{}>", tag);
        let start = xml.find(&start_tag)? + start_tag.len();
        let end = xml.find(&end_tag)?;
        if start < end {
            Some(xml[start..end].to_string())
        } else {
            None
        }
    };

    let access_key_id = extract_value("AccessKeyId")
        .ok_or_else(|| anyhow!("AccessKeyId not found in AssumeRole response"))?;

    let secret_access_key = extract_value("SecretAccessKey")
        .ok_or_else(|| anyhow!("SecretAccessKey not found in AssumeRole response"))?;

    let session_token = extract_value("SessionToken")
        .ok_or_else(|| anyhow!("SessionToken not found in AssumeRole response"))?;

    let expiration_str = extract_value("Expiration")
        .ok_or_else(|| anyhow!("Expiration not found in AssumeRole response"))?;

    let expiration = parse_expiration(&expiration_str)
        .unwrap_or_else(|| Instant::now() + Duration::from_secs(3600));

    Ok((
        Credentials {
            access_key_id,
            secret_access_key,
            session_token: Some(session_token),
        },
        expiration,
    ))
}

// =============================================================================
// IMDSv2 (EC2 Instance Metadata Service) Support
// =============================================================================

/// Load credentials from EC2 Instance Metadata Service (IMDSv2)
///
/// This function:
/// 1. Checks if we have valid cached credentials
/// 2. If not, fetches a session token from IMDSv2
/// 3. Uses the token to get the IAM role name
/// 4. Fetches temporary credentials for that role
/// 5. Caches the credentials until near expiration
fn load_from_imds() -> Result<Credentials> {
    // Check cache first
    let cache = IMDS_CACHE.get_or_init(|| std::sync::Mutex::new(None));

    if let Ok(guard) = cache.lock() {
        if let Some(ref cached) = *guard {
            // Return cached credentials if not expired (with buffer)
            if cached.expiration > Instant::now() + CREDENTIAL_REFRESH_BUFFER {
                trace!("Using cached IMDS credentials");
                return Ok(cached.credentials.clone());
            }
        }
    }

    // Fetch fresh credentials
    let creds = fetch_imds_credentials()?;

    Ok(creds)
}

/// Fetch credentials from IMDSv2 endpoint
fn fetch_imds_credentials() -> Result<Credentials> {
    // Use a blocking HTTP client with short timeout
    let client = reqwest::blocking::Client::builder()
        .timeout(IMDS_TIMEOUT)
        .connect_timeout(IMDS_TIMEOUT)
        .build()
        .map_err(|e| anyhow!("Failed to create HTTP client: {}", e))?;

    // Step 1: Get IMDSv2 session token
    trace!("Fetching IMDSv2 session token");
    let token_url = format!("{}/latest/api/token", IMDS_ENDPOINT);
    let token_response = client
        .put(&token_url)
        .header(
            "X-aws-ec2-metadata-token-ttl-seconds",
            IMDS_TOKEN_TTL.to_string(),
        )
        .send()
        .map_err(|e| anyhow!("Failed to get IMDS token (not running on EC2?): {}", e))?;

    if !token_response.status().is_success() {
        return Err(anyhow!(
            "IMDS token request failed with status: {}",
            token_response.status()
        ));
    }

    let token = token_response
        .text()
        .map_err(|e| anyhow!("Failed to read IMDS token: {}", e))?;

    // Step 2: Get IAM role name
    trace!("Fetching IAM role name from IMDS");
    let role_url = format!(
        "{}/latest/meta-data/iam/security-credentials/",
        IMDS_ENDPOINT
    );
    let role_response = client
        .get(&role_url)
        .header("X-aws-ec2-metadata-token", &token)
        .send()
        .map_err(|e| anyhow!("Failed to get IAM role: {}", e))?;

    if !role_response.status().is_success() {
        return Err(anyhow!(
            "No IAM role attached to this EC2 instance (status: {})",
            role_response.status()
        ));
    }

    let role_text = role_response
        .text()
        .map_err(|e| anyhow!("Failed to read IAM role name: {}", e))?;

    // Take the first role if multiple are returned (newline-separated)
    let role_name = role_text
        .lines()
        .next()
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| anyhow!("No IAM role attached to this EC2 instance"))?
        .to_string();

    debug!("Found IAM role: {}", role_name);

    // Step 3: Get credentials for the role
    trace!("Fetching credentials for IAM role: {}", role_name);
    let creds_url = format!(
        "{}/latest/meta-data/iam/security-credentials/{}",
        IMDS_ENDPOINT, role_name
    );
    let creds_response = client
        .get(&creds_url)
        .header("X-aws-ec2-metadata-token", &token)
        .send()
        .map_err(|e| anyhow!("Failed to get credentials: {}", e))?;

    if !creds_response.status().is_success() {
        return Err(anyhow!(
            "Failed to get credentials for role '{}' (status: {})",
            role_name,
            creds_response.status()
        ));
    }

    let creds_json: serde_json::Value = creds_response
        .json()
        .map_err(|e| anyhow!("Failed to parse credentials JSON: {}", e))?;

    // Parse the credentials
    let access_key_id = creds_json
        .get("AccessKeyId")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("AccessKeyId not found in IMDS response"))?
        .to_string();

    let secret_access_key = creds_json
        .get("SecretAccessKey")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("SecretAccessKey not found in IMDS response"))?
        .to_string();

    let session_token = creds_json
        .get("Token")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    // Parse expiration time
    let expiration = if let Some(exp_str) = creds_json.get("Expiration").and_then(|v| v.as_str()) {
        // Parse ISO 8601 format: "2024-01-15T12:00:00Z"
        parse_expiration(exp_str).unwrap_or_else(|| {
            // Default to 1 hour if parsing fails
            Instant::now() + Duration::from_secs(3600)
        })
    } else {
        // Default to 1 hour if no expiration provided
        Instant::now() + Duration::from_secs(3600)
    };

    let credentials = Credentials {
        access_key_id,
        secret_access_key,
        session_token,
    };

    // Cache the credentials
    let cache = IMDS_CACHE.get_or_init(|| std::sync::Mutex::new(None));
    if let Ok(mut guard) = cache.lock() {
        *guard = Some(CachedImdsCredentials {
            credentials: credentials.clone(),
            expiration,
        });
        debug!(
            "Cached IMDS credentials, expires in {:?}",
            expiration - Instant::now()
        );
    }

    Ok(credentials)
}

/// Parse ISO 8601 expiration time to Instant
fn parse_expiration(exp_str: &str) -> Option<Instant> {
    // Parse "2024-01-15T12:00:00Z" format
    use chrono::{DateTime, Utc};

    let expiration_time: DateTime<Utc> = exp_str.parse().ok()?;
    let now = Utc::now();

    if expiration_time <= now {
        return None;
    }

    let duration_until_expiration = (expiration_time - now).to_std().ok()?;
    Some(Instant::now() + duration_until_expiration)
}

/// Check if IMDS is available (useful for detecting EC2 environment)
#[allow(dead_code)]
pub fn is_imds_available() -> bool {
    let client = match reqwest::blocking::Client::builder()
        .timeout(IMDS_TIMEOUT)
        .connect_timeout(IMDS_TIMEOUT)
        .build()
    {
        Ok(c) => c,
        Err(_) => return false,
    };

    let token_url = format!("{}/latest/api/token", IMDS_ENDPOINT);
    client
        .put(&token_url)
        .header("X-aws-ec2-metadata-token-ttl-seconds", "21600")
        .send()
        .map(|r| r.status().is_success())
        .unwrap_or(false)
}

// =============================================================================
// ECS Container Credentials Support
// =============================================================================

/// Load credentials from ECS container credentials endpoint
///
/// This function:
/// 1. Checks for AWS_CONTAINER_CREDENTIALS_RELATIVE_URI or AWS_CONTAINER_CREDENTIALS_FULL_URI
/// 2. Fetches credentials from the ECS metadata endpoint
/// 3. Caches the credentials until near expiration
fn load_from_ecs_container() -> Result<Credentials> {
    // Check cache first
    let cache = ECS_CACHE.get_or_init(|| std::sync::Mutex::new(None));

    if let Ok(guard) = cache.lock() {
        if let Some(ref cached) = *guard {
            if cached.expiration > Instant::now() + CREDENTIAL_REFRESH_BUFFER {
                trace!("Using cached ECS container credentials");
                return Ok(cached.credentials.clone());
            }
        }
    }

    // Fetch fresh credentials
    let (credentials, expiration) = fetch_ecs_container_credentials()?;

    // Cache the credentials
    if let Ok(mut guard) = cache.lock() {
        *guard = Some(CachedImdsCredentials {
            credentials: credentials.clone(),
            expiration,
        });
        debug!(
            "Cached ECS container credentials, expires in {:?}",
            expiration - Instant::now()
        );
    }

    Ok(credentials)
}

/// Fetch credentials from ECS container credentials endpoint
fn fetch_ecs_container_credentials() -> Result<(Credentials, Instant)> {
    // Determine the credentials URL
    // Priority: AWS_CONTAINER_CREDENTIALS_FULL_URI > AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
    let (url, auth_token) = if let Ok(full_uri) = env::var("AWS_CONTAINER_CREDENTIALS_FULL_URI") {
        // Full URI mode - may require authorization token
        let token = env::var("AWS_CONTAINER_AUTHORIZATION_TOKEN").ok();
        debug!("Using ECS full URI: {}", full_uri);
        (full_uri, token)
    } else if let Ok(relative_uri) = env::var("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI") {
        // Relative URI mode - use the standard ECS endpoint
        let url = format!("{}{}", ECS_CREDENTIALS_ENDPOINT, relative_uri);
        debug!("Using ECS relative URI: {}", url);
        (url, None)
    } else {
        return Err(anyhow!(
            "ECS container credentials not available: neither AWS_CONTAINER_CREDENTIALS_FULL_URI \
             nor AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set"
        ));
    };

    // Create HTTP client with timeout
    let client = reqwest::blocking::Client::builder()
        .timeout(Duration::from_secs(5))
        .connect_timeout(Duration::from_secs(2))
        .build()
        .map_err(|e| anyhow!("Failed to create HTTP client: {}", e))?;

    // Build request
    let mut request = client.get(&url);

    // Add authorization header if token is present
    if let Some(ref token) = auth_token {
        request = request.header("Authorization", token);
    }

    // Send request
    trace!("Fetching ECS container credentials from: {}", url);
    let response = request
        .send()
        .map_err(|e| anyhow!("Failed to fetch ECS container credentials: {}", e))?;

    if !response.status().is_success() {
        return Err(anyhow!(
            "ECS container credentials request failed with status: {}",
            response.status()
        ));
    }

    // Parse JSON response
    let creds_json: serde_json::Value = response
        .json()
        .map_err(|e| anyhow!("Failed to parse ECS credentials JSON: {}", e))?;

    // Extract credentials
    let access_key_id = creds_json
        .get("AccessKeyId")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("AccessKeyId not found in ECS credentials response"))?
        .to_string();

    let secret_access_key = creds_json
        .get("SecretAccessKey")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("SecretAccessKey not found in ECS credentials response"))?
        .to_string();

    let session_token = creds_json
        .get("Token")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    // Parse expiration time
    let expiration = if let Some(exp_str) = creds_json.get("Expiration").and_then(|v| v.as_str()) {
        parse_expiration(exp_str).unwrap_or_else(|| Instant::now() + Duration::from_secs(3600))
    } else {
        Instant::now() + Duration::from_secs(3600)
    };

    debug!(
        "Fetched ECS container credentials, expires in {:?}",
        expiration - Instant::now()
    );

    Ok((
        Credentials {
            access_key_id,
            secret_access_key,
            session_token,
        },
        expiration,
    ))
}

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

    const LOGIN_CACHE_DIR_ENV: &str = "AWS_LOGIN_CACHE_DIRECTORY";

    /// Serialises the tests that override AWS_LOGIN_CACHE_DIRECTORY and restores
    /// the old value on drop.
    ///
    /// The test harness runs tests as threads in one process, but the environment
    /// is process-global, so two of these tests running at once each saw the
    /// other's cache directory and failed to find their own fixture. Restoring in
    /// Drop rather than inline also stops a failing assert from leaking the
    /// override into whatever runs next.
    struct LoginCacheDirVar {
        _guard: std::sync::MutexGuard<'static, ()>,
        original: Option<String>,
    }

    impl LoginCacheDirVar {
        fn set(value: impl AsRef<std::ffi::OsStr>) -> Self {
            let held = Self::acquire();
            env::set_var(LOGIN_CACHE_DIR_ENV, value);
            held
        }

        fn unset() -> Self {
            let held = Self::acquire();
            env::remove_var(LOGIN_CACHE_DIR_ENV);
            held
        }

        fn acquire() -> Self {
            static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
            // A failing test poisons the lock. The guarded value is (), so there
            // is nothing to corrupt and the remaining tests should still run.
            let guard = LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
            Self {
                _guard: guard,
                original: env::var(LOGIN_CACHE_DIR_ENV).ok(),
            }
        }
    }

    impl Drop for LoginCacheDirVar {
        fn drop(&mut self) {
            match &self.original {
                Some(value) => env::set_var(LOGIN_CACHE_DIR_ENV, value),
                None => env::remove_var(LOGIN_CACHE_DIR_ENV),
            }
        }
    }

    #[test]
    fn test_sso_cache_is_profile_aware() {
        // This test verifies that SSO credentials are cached per-profile,
        // not globally. This is a regression test for the bug where switching
        // profiles would return cached credentials from the previous profile.

        let cache = SSO_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));

        // Create credentials for two different profiles
        let creds_profile_a = Credentials {
            access_key_id: "AKIAPROFILE_A_KEY".to_string(),
            secret_access_key: "secret_a".to_string(),
            session_token: Some("token_a".to_string()),
        };
        let creds_profile_b = Credentials {
            access_key_id: "AKIAPROFILE_B_KEY".to_string(),
            secret_access_key: "secret_b".to_string(),
            session_token: Some("token_b".to_string()),
        };

        let expiration = Instant::now() + Duration::from_secs(3600);

        // Cache credentials for both profiles
        {
            let mut guard = cache.lock().unwrap();
            guard.insert(
                "profile-a".to_string(),
                CachedImdsCredentials {
                    credentials: creds_profile_a.clone(),
                    expiration,
                },
            );
            guard.insert(
                "profile-b".to_string(),
                CachedImdsCredentials {
                    credentials: creds_profile_b.clone(),
                    expiration,
                },
            );
        }

        // Verify that looking up profile-a returns profile-a's credentials
        {
            let guard = cache.lock().unwrap();
            let cached_a = guard.get("profile-a").unwrap();
            assert_eq!(
                cached_a.credentials.access_key_id, "AKIAPROFILE_A_KEY",
                "Profile A should return Profile A's credentials"
            );
        }

        // Verify that looking up profile-b returns profile-b's credentials (not profile-a's)
        {
            let guard = cache.lock().unwrap();
            let cached_b = guard.get("profile-b").unwrap();
            assert_eq!(
                cached_b.credentials.access_key_id, "AKIAPROFILE_B_KEY",
                "Profile B should return Profile B's credentials, not Profile A's"
            );
        }

        // Verify that a non-existent profile returns None
        {
            let guard = cache.lock().unwrap();
            assert!(
                guard.get("profile-c").is_none(),
                "Non-existent profile should not return cached credentials"
            );
        }
    }

    #[test]
    fn test_parse_ini_file() {
        let content = r#"
[default]
aws_access_key_id = AKIADEFAULT
aws_secret_access_key = secret_default

[profile dev]
aws_access_key_id = AKIADEV
aws_secret_access_key = secret_dev
"#;
        let sections = parse_ini_file(content);

        assert!(sections.contains_key("default"));
        assert!(sections.contains_key("dev")); // "profile " prefix stripped

        let default_section = sections.get("default").unwrap();
        assert_eq!(
            default_section.get("aws_access_key_id").unwrap(),
            "AKIADEFAULT"
        );
    }

    #[test]
    fn test_credential_process_success() {
        // We use 'echo' to simulate a credential process
        // This relies on 'echo' being available, which is true on Unix and Windows (usually).
        let json = r#"{"Version": 1, "AccessKeyId": "test_key", "SecretAccessKey": "test_secret", "SessionToken": "test_token", "Expiration": "2099-01-01T00:00:00Z"}"#;

        // Escape quotes for shell
        // On unix sh -c 'echo ...'
        // On windows cmd /C echo ...
        #[cfg(not(windows))]
        let cmd = format!("echo '{}'", json);
        #[cfg(windows)]
        let cmd = format!("echo {}", json.replace("\"", "\\\""));

        let result = execute_credential_process(&cmd);
        assert!(
            result.is_ok(),
            "credential_process failed: {:?}",
            result.err()
        );

        let (creds, exp) = result.unwrap();
        assert_eq!(creds.access_key_id, "test_key");
        assert_eq!(creds.secret_access_key, "test_secret");
        assert_eq!(creds.session_token, Some("test_token".to_string()));
        assert!(exp.is_some());
    }

    #[test]
    fn test_parse_assume_role_response() {
        let xml = r#"
        <AssumeRoleResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
            <AssumeRoleResult>
                <Credentials>
                    <AccessKeyId>ASIATEST123</AccessKeyId>
                    <SecretAccessKey>testsecret456</SecretAccessKey>
                    <SessionToken>testsessiontoken789</SessionToken>
                    <Expiration>2099-01-15T12:00:00Z</Expiration>
                </Credentials>
                <AssumedRoleUser>
                    <AssumedRoleId>AROATEST:orbit-session</AssumedRoleId>
                    <Arn>arn:aws:sts::123456789012:assumed-role/TestRole/orbit-session</Arn>
                </AssumedRoleUser>
            </AssumeRoleResult>
        </AssumeRoleResponse>
        "#;

        let result = parse_assume_role_response(xml);
        assert!(result.is_ok(), "Failed to parse: {:?}", result.err());

        let (creds, _exp) = result.unwrap();
        assert_eq!(creds.access_key_id, "ASIATEST123");
        assert_eq!(creds.secret_access_key, "testsecret456");
        assert_eq!(creds.session_token, Some("testsessiontoken789".to_string()));
    }

    #[test]
    fn test_parse_sts_error() {
        let xml = r#"
        <ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
            <Error>
                <Code>AccessDenied</Code>
                <Message>User is not authorized to perform sts:AssumeRole</Message>
            </Error>
            <RequestId>12345678-1234-1234-1234-123456789012</RequestId>
        </ErrorResponse>
        "#;

        let result = parse_sts_error(xml);
        assert!(result.is_some());
        let error_msg = result.unwrap();
        assert!(error_msg.contains("AccessDenied"));
        assert!(error_msg.contains("not authorized"));
    }

    #[test]
    fn test_assume_role_cache_is_profile_aware() {
        let cache = ASSUME_ROLE_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));

        let creds_dev = Credentials {
            access_key_id: "ASIA_DEV_KEY".to_string(),
            secret_access_key: "secret_dev".to_string(),
            session_token: Some("token_dev".to_string()),
        };
        let creds_prod = Credentials {
            access_key_id: "ASIA_PROD_KEY".to_string(),
            secret_access_key: "secret_prod".to_string(),
            session_token: Some("token_prod".to_string()),
        };

        let expiration = Instant::now() + Duration::from_secs(3600);

        {
            let mut guard = cache.lock().unwrap();
            guard.insert(
                "dev-role".to_string(),
                CachedImdsCredentials {
                    credentials: creds_dev.clone(),
                    expiration,
                },
            );
            guard.insert(
                "prod-role".to_string(),
                CachedImdsCredentials {
                    credentials: creds_prod.clone(),
                    expiration,
                },
            );
        }

        // Verify separate caching
        {
            let guard = cache.lock().unwrap();
            let cached_dev = guard.get("dev-role").unwrap();
            assert_eq!(cached_dev.credentials.access_key_id, "ASIA_DEV_KEY");

            let cached_prod = guard.get("prod-role").unwrap();
            assert_eq!(cached_prod.credentials.access_key_id, "ASIA_PROD_KEY");
        }
    }

    #[test]
    fn test_parse_ini_file_with_role_arn() {
        let content = r#"
[default]
aws_access_key_id = AKIADEFAULT
aws_secret_access_key = secret_default
region = us-east-1

[profile production]
role_arn = arn:aws:iam::123456789012:role/ProductionAccess
source_profile = default
region = us-west-2
external_id = my-external-id

[profile staging]
role_arn = arn:aws:iam::987654321098:role/StagingAccess
source_profile = default
role_session_name = my-custom-session
duration_seconds = 7200
"#;
        let sections = parse_ini_file(content);

        // Check default profile
        assert!(sections.contains_key("default"));
        let default_section = sections.get("default").unwrap();
        assert_eq!(
            default_section.get("aws_access_key_id").unwrap(),
            "AKIADEFAULT"
        );

        // Check production profile with role_arn
        assert!(sections.contains_key("production"));
        let prod_section = sections.get("production").unwrap();
        assert_eq!(
            prod_section.get("role_arn").unwrap(),
            "arn:aws:iam::123456789012:role/ProductionAccess"
        );
        assert_eq!(prod_section.get("source_profile").unwrap(), "default");
        assert_eq!(prod_section.get("external_id").unwrap(), "my-external-id");

        // Check staging profile
        assert!(sections.contains_key("staging"));
        let staging_section = sections.get("staging").unwrap();
        assert_eq!(
            staging_section.get("role_arn").unwrap(),
            "arn:aws:iam::987654321098:role/StagingAccess"
        );
        assert_eq!(
            staging_section.get("role_session_name").unwrap(),
            "my-custom-session"
        );
        assert_eq!(staging_section.get("duration_seconds").unwrap(), "7200");
    }

    #[test]
    fn test_parse_credential_source() {
        assert_eq!(
            parse_credential_source("Environment"),
            Some(CredentialSource::Environment)
        );
        assert_eq!(
            parse_credential_source("Ec2InstanceMetadata"),
            Some(CredentialSource::Ec2InstanceMetadata)
        );
        assert_eq!(
            parse_credential_source("EcsContainer"),
            Some(CredentialSource::EcsContainer)
        );
        assert_eq!(parse_credential_source("Invalid"), None);
        assert_eq!(parse_credential_source("environment"), None); // Case sensitive
    }

    #[test]
    fn test_parse_ini_file_with_credential_source() {
        let content = r#"
[profile ecs-role]
role_arn = arn:aws:iam::123456789012:role/EcsRole
credential_source = EcsContainer
region = us-east-1

[profile ec2-role]
role_arn = arn:aws:iam::123456789012:role/Ec2Role
credential_source = Ec2InstanceMetadata

[profile env-role]
role_arn = arn:aws:iam::123456789012:role/EnvRole
credential_source = Environment
"#;
        let sections = parse_ini_file(content);

        // Check ECS profile
        assert!(sections.contains_key("ecs-role"));
        let ecs_section = sections.get("ecs-role").unwrap();
        assert_eq!(
            ecs_section.get("role_arn").unwrap(),
            "arn:aws:iam::123456789012:role/EcsRole"
        );
        assert_eq!(
            ecs_section.get("credential_source").unwrap(),
            "EcsContainer"
        );
        assert!(ecs_section.get("source_profile").is_none());

        // Check EC2 profile
        assert!(sections.contains_key("ec2-role"));
        let ec2_section = sections.get("ec2-role").unwrap();
        assert_eq!(
            ec2_section.get("credential_source").unwrap(),
            "Ec2InstanceMetadata"
        );

        // Check Environment profile
        assert!(sections.contains_key("env-role"));
        let env_section = sections.get("env-role").unwrap();
        assert_eq!(env_section.get("credential_source").unwrap(), "Environment");
    }

    #[test]
    fn test_ecs_cache() {
        let cache = ECS_CACHE.get_or_init(|| std::sync::Mutex::new(None));

        let creds = Credentials {
            access_key_id: "ASIA_ECS_KEY".to_string(),
            secret_access_key: "secret_ecs".to_string(),
            session_token: Some("token_ecs".to_string()),
        };

        let expiration = Instant::now() + Duration::from_secs(3600);

        {
            let mut guard = cache.lock().unwrap();
            *guard = Some(CachedImdsCredentials {
                credentials: creds.clone(),
                expiration,
            });
        }

        // Verify caching
        {
            let guard = cache.lock().unwrap();
            let cached = guard.as_ref().unwrap();
            assert_eq!(cached.credentials.access_key_id, "ASIA_ECS_KEY");
        }
    }

    #[test]
    fn test_try_read_cli_cache_file_matching_role() {
        // Test that try_read_cli_cache_file correctly matches role ARNs
        use std::io::Write;
        use tempfile::NamedTempFile;

        let cache_json = r#"{
            "Credentials": {
                "AccessKeyId": "ASIATESTACCESSKEY",
                "SecretAccessKey": "testsecretkey123",
                "SessionToken": "testsessiontoken456",
                "Expiration": "2099-01-01T00:00:00Z"
            },
            "AssumedRoleUser": {
                "AssumedRoleId": "AROATESTROLE:orbit-session",
                "Arn": "arn:aws:sts::123456789012:assumed-role/TestRole/orbit-session"
            }
        }"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(cache_json.as_bytes()).unwrap();

        // Matching role ARN
        let role_arn = "arn:aws:iam::123456789012:role/TestRole";
        let result = try_read_cli_cache_file(temp_file.path(), role_arn);
        assert!(result.is_some(), "Should find matching credentials");

        let creds = result.unwrap();
        assert_eq!(creds.access_key_id, "ASIATESTACCESSKEY");
        assert_eq!(creds.secret_access_key, "testsecretkey123");
        assert_eq!(creds.session_token, Some("testsessiontoken456".to_string()));
    }

    #[test]
    fn test_try_read_cli_cache_file_non_matching_role() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let cache_json = r#"{
            "Credentials": {
                "AccessKeyId": "ASIATESTACCESSKEY",
                "SecretAccessKey": "testsecretkey123",
                "SessionToken": "testsessiontoken456",
                "Expiration": "2099-01-01T00:00:00Z"
            },
            "AssumedRoleUser": {
                "AssumedRoleId": "AROATESTROLE:orbit-session",
                "Arn": "arn:aws:sts::123456789012:assumed-role/TestRole/orbit-session"
            }
        }"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(cache_json.as_bytes()).unwrap();

        // Non-matching role ARN (different role name)
        let role_arn = "arn:aws:iam::123456789012:role/DifferentRole";
        let result = try_read_cli_cache_file(temp_file.path(), role_arn);
        assert!(
            result.is_none(),
            "Should not find credentials for different role"
        );

        // Non-matching role ARN (different account)
        let role_arn = "arn:aws:iam::999999999999:role/TestRole";
        let result = try_read_cli_cache_file(temp_file.path(), role_arn);
        assert!(
            result.is_none(),
            "Should not find credentials for different account"
        );
    }

    #[test]
    fn test_try_read_cli_cache_file_expired() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let cache_json = r#"{
            "Credentials": {
                "AccessKeyId": "ASIATESTACCESSKEY",
                "SecretAccessKey": "testsecretkey123",
                "SessionToken": "testsessiontoken456",
                "Expiration": "2020-01-01T00:00:00Z"
            },
            "AssumedRoleUser": {
                "AssumedRoleId": "AROATESTROLE:orbit-session",
                "Arn": "arn:aws:sts::123456789012:assumed-role/TestRole/orbit-session"
            }
        }"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(cache_json.as_bytes()).unwrap();

        let role_arn = "arn:aws:iam::123456789012:role/TestRole";
        let result = try_read_cli_cache_file(temp_file.path(), role_arn);
        assert!(result.is_none(), "Should not return expired credentials");
    }

    #[test]
    fn test_console_login_cache_is_profile_aware() {
        let cache = CONSOLE_LOGIN_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));

        let creds_profile_a = Credentials {
            access_key_id: "ASIA_LOGIN_A_KEY".to_string(),
            secret_access_key: "secret_login_a".to_string(),
            session_token: Some("token_login_a".to_string()),
        };
        let creds_profile_b = Credentials {
            access_key_id: "ASIA_LOGIN_B_KEY".to_string(),
            secret_access_key: "secret_login_b".to_string(),
            session_token: Some("token_login_b".to_string()),
        };

        let expiration = Instant::now() + Duration::from_secs(3600);

        {
            let mut guard = cache.lock().unwrap();
            guard.insert(
                "login-profile-a".to_string(),
                CachedImdsCredentials {
                    credentials: creds_profile_a.clone(),
                    expiration,
                },
            );
            guard.insert(
                "login-profile-b".to_string(),
                CachedImdsCredentials {
                    credentials: creds_profile_b.clone(),
                    expiration,
                },
            );
        }

        // Verify profile-a returns profile-a's credentials
        {
            let guard = cache.lock().unwrap();
            let cached_a = guard.get("login-profile-a").unwrap();
            assert_eq!(
                cached_a.credentials.access_key_id, "ASIA_LOGIN_A_KEY",
                "Profile A should return Profile A's credentials"
            );
        }

        // Verify profile-b returns profile-b's credentials
        {
            let guard = cache.lock().unwrap();
            let cached_b = guard.get("login-profile-b").unwrap();
            assert_eq!(
                cached_b.credentials.access_key_id, "ASIA_LOGIN_B_KEY",
                "Profile B should return Profile B's credentials"
            );
        }
    }

    #[test]
    fn test_parse_ini_file_with_login_session() {
        let content = r#"
[default]
aws_access_key_id = AKIADEFAULT
aws_secret_access_key = secret_default
region = us-east-1

[profile console-login]
login_session = arn:aws:iam::123456789012:user/Admin
region = us-west-2
"#;
        let sections = parse_ini_file(content);

        // Check console-login profile
        assert!(sections.contains_key("console-login"));
        let login_section = sections.get("console-login").unwrap();
        assert_eq!(
            login_section.get("login_session").unwrap(),
            "arn:aws:iam::123456789012:user/Admin"
        );
        assert_eq!(login_section.get("region").unwrap(), "us-west-2");
    }

    #[test]
    fn test_load_from_console_login_valid() {
        use sha2::{Digest, Sha256};
        use std::io::Write;
        use tempfile::TempDir;

        // Create a temp directory structure for login cache
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path();

        // Create login cache JSON with valid credentials
        let login_cache_json = r#"{
            "accessToken": {
                "accessKeyId": "ASIALOGINTESTACCESSKEY",
                "secretAccessKey": "loginTestSecretKey123",
                "sessionToken": "loginTestSessionToken456",
                "accountId": "123456789012",
                "expiresAt": "2099-01-01T00:00:00Z"
            },
            "tokenType": "aws_sigv4",
            "refreshToken": "testRefreshToken",
            "idToken": "testIdToken",
            "clientId": "arn:aws:iam::123456789012:client/test"
        }"#;

        // Calculate the cache filename (SHA256 of login_session ARN)
        let login_session = "arn:aws:iam::123456789012:user/TestUser";
        let mut hasher = Sha256::new();
        hasher.update(login_session.trim().as_bytes());
        let hash = hasher.finalize();
        let cache_filename = format!("{}.json", hex::encode(hash));

        // Write the cache file
        let cache_file_path = cache_dir.join(&cache_filename);
        let mut cache_file = std::fs::File::create(&cache_file_path).unwrap();
        cache_file.write_all(login_cache_json.as_bytes()).unwrap();

        // Override the cache directory for the duration of the call. Held until
        // the end of the test, which also keeps the other tests that touch this
        // variable from running concurrently.
        let _cache_dir = LoginCacheDirVar::set(cache_dir);

        let result = load_from_console_login("test-profile", login_session);

        assert!(
            result.is_ok(),
            "Should load credentials: {:?}",
            result.err()
        );
        let creds = result.unwrap();
        assert_eq!(creds.access_key_id, "ASIALOGINTESTACCESSKEY");
        assert_eq!(creds.secret_access_key, "loginTestSecretKey123");
        assert_eq!(
            creds.session_token,
            Some("loginTestSessionToken456".to_string())
        );
    }

    #[test]
    fn test_load_from_console_login_expired() {
        use sha2::{Digest, Sha256};
        use std::io::Write;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path();

        // Create login cache JSON with expired credentials
        let login_cache_json = r#"{
            "accessToken": {
                "accessKeyId": "ASIAEXPIREDKEY",
                "secretAccessKey": "expiredSecret",
                "sessionToken": "expiredToken",
                "accountId": "123456789012",
                "expiresAt": "2020-01-01T00:00:00Z"
            },
            "tokenType": "aws_sigv4"
        }"#;

        let login_session = "arn:aws:iam::123456789012:user/ExpiredUser";
        let mut hasher = Sha256::new();
        hasher.update(login_session.trim().as_bytes());
        let hash = hasher.finalize();
        let cache_filename = format!("{}.json", hex::encode(hash));

        let cache_file_path = cache_dir.join(&cache_filename);
        let mut cache_file = std::fs::File::create(&cache_file_path).unwrap();
        cache_file.write_all(login_cache_json.as_bytes()).unwrap();

        let _cache_dir = LoginCacheDirVar::set(cache_dir);

        let result = load_from_console_login("test-expired-profile", login_session);

        assert!(result.is_err(), "Should fail for expired credentials");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("expired"),
            "Error should mention expiration: {}",
            err_msg
        );
    }

    #[test]
    fn test_get_login_cache_dir_default() {
        // Test without env var set
        let _cache_dir = LoginCacheDirVar::unset();

        let result = get_login_cache_dir();

        assert!(result.is_ok());
        let path = result.unwrap();
        // Should end with "login/cache"
        assert!(path.ends_with("login/cache") || path.to_string_lossy().contains("login"));
    }

    #[test]
    fn test_get_login_cache_dir_env_override() {
        let _cache_dir = LoginCacheDirVar::set("/custom/login/cache");

        let result = get_login_cache_dir();

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), PathBuf::from("/custom/login/cache"));
    }

    #[test]
    fn test_credentials_error_sso_vs_console_login() {
        // Test that SSO and Console Login errors are distinct
        let sso_error = CredentialsError::SsoLoginRequired {
            profile: "sso-profile".to_string(),
            sso_session: "my-sso-session".to_string(),
        };

        let console_error = CredentialsError::ConsoleLoginRequired {
            profile: "console-profile".to_string(),
            login_session: "arn:aws:iam::123456789012:user/Admin".to_string(),
        };

        // SSO error message should mention sso login
        let sso_msg = sso_error.to_string();
        assert!(
            sso_msg.contains("aws sso login"),
            "SSO error should suggest 'aws sso login': {}",
            sso_msg
        );
        assert!(
            sso_msg.contains("sso-profile"),
            "SSO error should contain profile name: {}",
            sso_msg
        );
        assert!(
            sso_msg.contains("my-sso-session"),
            "SSO error should contain session name: {}",
            sso_msg
        );

        // Console login error message should mention aws login (not sso login)
        let console_msg = console_error.to_string();
        assert!(
            console_msg.contains("aws login"),
            "Console error should suggest 'aws login': {}",
            console_msg
        );
        assert!(
            !console_msg.contains("sso"),
            "Console error should NOT mention 'sso': {}",
            console_msg
        );
        assert!(
            console_msg.contains("console-profile"),
            "Console error should contain profile name: {}",
            console_msg
        );
        assert!(
            console_msg.contains("123456789012"),
            "Console error should contain login session: {}",
            console_msg
        );
    }

    #[test]
    fn test_credentials_error_matching() {
        // Test that we can match on both error types
        let test_cases: Vec<CredentialsError> = vec![
            CredentialsError::SsoLoginRequired {
                profile: "sso".to_string(),
                sso_session: "session".to_string(),
            },
            CredentialsError::ConsoleLoginRequired {
                profile: "console".to_string(),
                login_session: "arn".to_string(),
            },
            CredentialsError::Other(anyhow!("generic error")),
        ];

        for error in test_cases {
            match &error {
                CredentialsError::SsoLoginRequired { profile, .. } => {
                    assert_eq!(profile, "sso");
                }
                CredentialsError::ConsoleLoginRequired { profile, .. } => {
                    assert_eq!(profile, "console");
                }
                CredentialsError::Other(e) => {
                    assert!(e.to_string().contains("generic"));
                }
            }
        }
    }
}