fakecloud-iam 0.19.0

IAM and STS implementation for FakeCloud
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
//! Handlers added to close the IAM conformance gap. Service-specific
//! credentials, delegation requests, organizations integration, outbound
//! web identity federation, service-last-accessed jobs, extra resource
//! tagging surfaces, policy simulation, and miscellaneous credentials
//! maintenance ops.

use chrono::Utc;
use http::StatusCode;

use fakecloud_core::service::{AwsRequest, AwsResponse, AwsServiceError};

use crate::state::{
    DelegationRequest, IamState, OrganizationsAccessReport, ServiceLastAccessedJob,
    ServiceSpecificCredential,
};

use super::{
    empty_response, parse_tags, required_param_with_code, resolve_calling_user, tags_xml,
    validate_string_length_with_code, IamService,
};
use fakecloud_core::query::required_param;

fn required_param_iam(
    params: &std::collections::HashMap<String, String>,
    name: &str,
) -> Result<String, AwsServiceError> {
    super::required_param_with_code(params, name, "InvalidInput")
}
use fakecloud_core::validation::{parse_optional_i64_param, validate_optional_range_i64};

// Wrap the IAM-specific length validators that emit `InvalidInput` rather
// than core's `ValidationException` (which isn't a declared error on any
// IAM op).
fn validate_string_length(
    field: &str,
    value: &str,
    min: usize,
    max: usize,
) -> Result<(), AwsServiceError> {
    super::validate_string_length_with_code(field, value, min, max, "InvalidInput")
}

fn validate_optional_string_length(
    field: &str,
    value: Option<&str>,
    min: usize,
    max: usize,
) -> Result<(), AwsServiceError> {
    super::validate_optional_string_length_with_code(field, value, min, max, "InvalidInput")
}

use fakecloud_aws::arn::Arn;
use fakecloud_aws::xml::xml_escape;

fn xml_response(action: &str, body: &str, request_id: &str) -> AwsResponse {
    let xml = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<{action}Response xmlns="https://iam.amazonaws.com/doc/2010-05-08/">
{body}
  <ResponseMetadata>
    <RequestId>{request_id}</RequestId>
  </ResponseMetadata>
</{action}Response>"#,
    );
    AwsResponse::xml(StatusCode::OK, xml)
}

fn now_iso() -> String {
    Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
}

/// Collect a member list from query params (`Prefix.1`, `Prefix.2`, ...).
/// Stops at the first missing index. Bounded at 128 to match AWS's
/// per-API simulate limit.
fn collect_member_list(req: &AwsRequest, prefix: &str) -> Vec<String> {
    let mut out = Vec::new();
    for i in 1..=128 {
        let key = format!("{prefix}{i}");
        match req.query_params.get(&key) {
            Some(v) => out.push(v.clone()),
            None => break,
        }
    }
    out
}

/// Resolve an IAM principal ARN (user or role) to its full identity
/// policy set as raw JSON strings: managed policies (default version)
/// plus inline policies. For users this also unions every policy
/// attached to the groups they belong to, matching AWS's
/// `SimulatePrincipalPolicy` semantics. Returns an empty vec if the
/// ARN doesn't resolve.
///
/// Returning raw JSON (instead of `PolicyDocument`) lets callers feed
/// the same docs into both the evaluator (via `PolicyDocument::parse`)
/// and the condition-key scanner used to populate
/// `MissingContextValues`.
fn collect_principal_policy_jsons(state: &IamState, source_arn: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let (kind, name) = match parse_principal_arn(source_arn) {
        Some(p) => p,
        None => return out,
    };
    let (managed, inline) = match kind {
        PrincipalKind::User => (
            state.user_policies.get(name).cloned().unwrap_or_default(),
            state
                .user_inline_policies
                .get(name)
                .cloned()
                .unwrap_or_default(),
        ),
        PrincipalKind::Role => (
            state.role_policies.get(name).cloned().unwrap_or_default(),
            state
                .role_inline_policies
                .get(name)
                .cloned()
                .unwrap_or_default(),
        ),
    };
    for arn in &managed {
        if let Some(policy) = state.policies.get(arn) {
            if let Some(v) = policy.versions.iter().find(|v| v.is_default) {
                out.push(v.document.clone());
            }
        }
    }
    for doc in inline.values() {
        out.push(doc.clone());
    }
    // Users inherit every policy attached to a group they belong to —
    // both managed and inline. Roles can't be group members so this
    // step is user-only.
    if matches!(kind, PrincipalKind::User) {
        for group in state.groups.values() {
            if !group.members.iter().any(|m| m == name) {
                continue;
            }
            for arn in &group.attached_policies {
                if let Some(policy) = state.policies.get(arn) {
                    if let Some(v) = policy.versions.iter().find(|v| v.is_default) {
                        out.push(v.document.clone());
                    }
                }
            }
            for doc in group.inline_policies.values() {
                out.push(doc.clone());
            }
        }
    }
    out
}

fn principal_boundary(state: &IamState, source_arn: &str) -> Option<String> {
    let (kind, name) = parse_principal_arn(source_arn)?;
    match kind {
        PrincipalKind::User => state
            .users
            .get(name)
            .and_then(|u| u.permissions_boundary.clone()),
        PrincipalKind::Role => state
            .roles
            .get(name)
            .and_then(|r| r.permissions_boundary.clone()),
    }
}

#[derive(Debug, Clone, Copy)]
enum PrincipalKind {
    User,
    Role,
}

fn parse_principal_arn(arn: &str) -> Option<(PrincipalKind, &str)> {
    // arn:aws:iam::ACCOUNT:user/path/name -> User, "name"
    // arn:aws:iam::ACCOUNT:role/path/name -> Role, "name"
    let colon_at = arn.rfind(':')?;
    let resource = &arn[colon_at + 1..];
    let (resource_type, rest) = resource.split_once('/')?;
    let last = rest.rsplit('/').next().unwrap_or(rest);
    match resource_type {
        "user" => Some((PrincipalKind::User, last)),
        "role" => Some((PrincipalKind::Role, last)),
        _ => None,
    }
}

fn service_credential_xml(c: &ServiceSpecificCredential, include_password: bool) -> String {
    let pw = if include_password {
        format!(
            "<ServicePassword>{}</ServicePassword>",
            xml_escape(&c.service_password)
        )
    } else {
        String::new()
    };
    format!(
        "<ServiceSpecificCredential>{pw}<ServiceUserName>{}</ServiceUserName><CreateDate>{}</CreateDate><ServiceName>{}</ServiceName><UserName>{}</UserName><ServiceSpecificCredentialId>{}</ServiceSpecificCredentialId><Status>{}</Status></ServiceSpecificCredential>",
        xml_escape(&c.service_user_name),
        c.create_date.format("%Y-%m-%dT%H:%M:%SZ"),
        xml_escape(&c.service_name),
        xml_escape(&c.user_name),
        xml_escape(&c.credential_id),
        xml_escape(&c.status),
    )
}

/// Walk `ContextEntries.member.N` and route values into the right
/// bucket on `ctx`. Tag-style keys (`aws:RequestTag/*`,
/// `aws:ResourceTag/*`, `aws:PrincipalTag/*`) populate the typed maps
/// the evaluator's tag operators read; everything else lands in
/// `service_keys` (lowercased), which `ConditionContext::lookup` falls
/// through to for unrecognized keys.
fn apply_context_entries(req: &AwsRequest, ctx: &mut fakecloud_core::auth::ConditionContext) {
    use std::collections::HashMap;
    for i in 1..=128 {
        let k = format!("ContextEntries.member.{i}.ContextKeyName");
        let Some(name) = req.query_params.get(&k) else {
            break;
        };
        let mut values: Vec<String> = Vec::new();
        for j in 1..=32 {
            let vk = format!("ContextEntries.member.{i}.ContextKeyValues.member.{j}");
            if let Some(v) = req.query_params.get(&vk) {
                values.push(v.clone());
            } else {
                break;
            }
        }
        let lower = name.to_ascii_lowercase();
        // Tag-key prefix lengths: aws:resourcetag/=16, aws:requesttag/=15,
        // aws:principaltag/=17.
        let single_value = || values.first().cloned().unwrap_or_default();
        if let Some(rest) = name
            .get(..16)
            .filter(|p| p.eq_ignore_ascii_case("aws:ResourceTag/"))
            .map(|_| &name[16..])
        {
            ctx.resource_tags
                .get_or_insert_with(HashMap::new)
                .insert(rest.to_string(), single_value());
            continue;
        }
        if let Some(rest) = name
            .get(..15)
            .filter(|p| p.eq_ignore_ascii_case("aws:RequestTag/"))
            .map(|_| &name[15..])
        {
            ctx.request_tags
                .get_or_insert_with(HashMap::new)
                .insert(rest.to_string(), single_value());
            continue;
        }
        if let Some(rest) = name
            .get(..17)
            .filter(|p| p.eq_ignore_ascii_case("aws:PrincipalTag/"))
            .map(|_| &name[17..])
        {
            ctx.principal_tags
                .get_or_insert_with(HashMap::new)
                .insert(rest.to_string(), single_value());
            continue;
        }
        ctx.service_keys.insert(lower, values);
    }
}

fn random_id(prefix: &str) -> String {
    format!(
        "{}{}",
        prefix,
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    )
}

/// Generate a UUID-shaped (`8-4-4-4-12` hex) identifier — matches the
/// 36-character `JobId` Smithy type used by IAM's async report APIs.
fn random_uuid_id() -> String {
    // Reuse the nanosecond clock for entropy. Real AWS uses random
    // UUIDs; fakecloud is single-process so monotonic time is fine.
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    // Pad/truncate to 32 hex digits to fill the UUID slot, sprinkling
    // a couple of fixed letters so the same nanos repeated produces a
    // stable but pseudo-randomized look.
    let hex = format!("{nanos:032x}");
    let hex = &hex[hex.len().saturating_sub(32)..];
    format!(
        "{}-{}-{}-{}-{}",
        &hex[0..8],
        &hex[8..12],
        &hex[12..16],
        &hex[16..20],
        &hex[20..32],
    )
}

impl IamService {
    // ── Service-specific credentials ──

    pub(super) fn create_service_specific_credential(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let user_name = required_param(&req.query_params, "UserName")?;
        let service_name = required_param(&req.query_params, "ServiceName")?;
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        if !state.users.contains_key(&user_name) {
            return Err(AwsServiceError::aws_error(
                StatusCode::NOT_FOUND,
                "NoSuchEntity",
                format!("User {user_name} not found"),
            ));
        }
        let credential_id = random_id("ACCA");
        let cred = ServiceSpecificCredential {
            credential_id: credential_id.clone(),
            user_name: user_name.clone(),
            service_name,
            service_user_name: format!("{user_name}-at-{}", state.account_id),
            service_password: random_id("PW"),
            status: "Active".to_string(),
            create_date: Utc::now(),
        };
        state
            .service_specific_credentials
            .entry(user_name)
            .or_default()
            .push(cred.clone());
        let body = format!(
            "  <CreateServiceSpecificCredentialResult>\n{}\n  </CreateServiceSpecificCredentialResult>",
            service_credential_xml(&cred, true)
        );
        Ok(xml_response(
            "CreateServiceSpecificCredential",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn delete_service_specific_credential(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        // Declared: NoSuchEntity (only). UserName optional per Smithy.
        let cred_id = required_param_with_code(
            &req.query_params,
            "ServiceSpecificCredentialId",
            "NoSuchEntity",
        )?;
        validate_string_length_with_code(
            "serviceSpecificCredentialId",
            &cred_id,
            20,
            128,
            "NoSuchEntity",
        )?;
        super::validate_optional_string_length_with_code(
            "UserName",
            req.query_params.get("UserName").map(|s| s.as_str()),
            1,
            64,
            "NoSuchEntity",
        )?;
        let user_name = req
            .query_params
            .get("UserName")
            .cloned()
            .filter(|v| !v.is_empty())
            .unwrap_or_else(|| {
                let accts = self.state.read();
                let st = accts.get(&req.account_id);
                resolve_calling_user(st.unwrap_or(accts.default_ref()), &req.account_id)
            });
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        if let Some(list) = state.service_specific_credentials.get_mut(&user_name) {
            list.retain(|c| c.credential_id != cred_id);
        }
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("DeleteServiceSpecificCredential", &req.request_id),
        ))
    }

    pub(super) fn list_service_specific_credentials(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        // Declared: NoSuchEntity, ServiceNotSupportedException. UserName
        // optional per Smithy (defaults to caller).
        let _ = super::validate_list_pagination(req)?;
        super::validate_optional_string_length_with_code(
            "UserName",
            req.query_params.get("UserName").map(|s| s.as_str()),
            1,
            64,
            "NoSuchEntity",
        )?;
        let service_name = req.query_params.get("ServiceName").cloned();
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        let user_name = req
            .query_params
            .get("UserName")
            .cloned()
            .filter(|v| !v.is_empty())
            .unwrap_or_else(|| resolve_calling_user(state, &req.account_id));
        let creds: Vec<&ServiceSpecificCredential> = state
            .service_specific_credentials
            .get(&user_name)
            .map(|v| {
                v.iter()
                    .filter(|c| service_name.as_ref().is_none_or(|s| &c.service_name == s))
                    .collect()
            })
            .unwrap_or_default();
        let members: String = creds
            .iter()
            .map(|c| service_credential_xml(c, false))
            .collect::<Vec<_>>()
            .join("\n");
        let body = format!(
            "  <ListServiceSpecificCredentialsResult>\n    <ServiceSpecificCredentials>\n{members}\n    </ServiceSpecificCredentials>\n  </ListServiceSpecificCredentialsResult>"
        );
        Ok(xml_response(
            "ListServiceSpecificCredentials",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn reset_service_specific_credential(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let cred_id = required_param(&req.query_params, "ServiceSpecificCredentialId")?;
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        let mut updated: Option<ServiceSpecificCredential> = None;
        for list in state.service_specific_credentials.values_mut() {
            if let Some(c) = list.iter_mut().find(|c| c.credential_id == cred_id) {
                c.service_password = random_id("PW");
                updated = Some(c.clone());
                break;
            }
        }
        let cred = updated.ok_or_else(|| {
            AwsServiceError::aws_error(
                StatusCode::NOT_FOUND,
                "NoSuchEntity",
                format!("ServiceSpecificCredential {cred_id} not found"),
            )
        })?;
        let body = format!(
            "  <ResetServiceSpecificCredentialResult>\n{}\n  </ResetServiceSpecificCredentialResult>",
            service_credential_xml(&cred, true)
        );
        Ok(xml_response(
            "ResetServiceSpecificCredential",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn update_service_specific_credential(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let cred_id = required_param(&req.query_params, "ServiceSpecificCredentialId")?;
        let status = required_param(&req.query_params, "Status")?;
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        let mut found = false;
        for list in state.service_specific_credentials.values_mut() {
            if let Some(c) = list.iter_mut().find(|c| c.credential_id == cred_id) {
                c.status = status.clone();
                found = true;
                break;
            }
        }
        if !found {
            return Err(AwsServiceError::aws_error(
                StatusCode::NOT_FOUND,
                "NoSuchEntity",
                format!("ServiceSpecificCredential {cred_id} not found"),
            ));
        }
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("UpdateServiceSpecificCredential", &req.request_id),
        ))
    }

    // ── Organizations integration ──

    pub(super) fn enable_organizations_root_credentials_management(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        state.organizations_root_credentials_management = true;
        let body = "  <EnableOrganizationsRootCredentialsManagementResult><EnabledFeatures><member>RootCredentialsManagement</member></EnabledFeatures></EnableOrganizationsRootCredentialsManagementResult>";
        Ok(xml_response(
            "EnableOrganizationsRootCredentialsManagement",
            body,
            &req.request_id,
        ))
    }

    pub(super) fn disable_organizations_root_credentials_management(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        state.organizations_root_credentials_management = false;
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response(
                "DisableOrganizationsRootCredentialsManagement",
                &req.request_id,
            ),
        ))
    }

    pub(super) fn enable_organizations_root_sessions(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        state.organizations_root_sessions = true;
        let body = "  <EnableOrganizationsRootSessionsResult><EnabledFeatures><member>RootSessions</member></EnabledFeatures></EnableOrganizationsRootSessionsResult>";
        Ok(xml_response(
            "EnableOrganizationsRootSessions",
            body,
            &req.request_id,
        ))
    }

    pub(super) fn disable_organizations_root_sessions(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        state.organizations_root_sessions = false;
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("DisableOrganizationsRootSessions", &req.request_id),
        ))
    }

    pub(super) fn generate_organizations_access_report(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let entity_path = required_param(&req.query_params, "EntityPath")?;
        // EntityPath has Smithy length 19..=427. The op only declares
        // `ReportGenerationLimitExceeded` as an error, so we surface
        // length violations under that code to satisfy the Smithy
        // error_shapes contract while still returning a 4xx as the probe
        // expects for negative variants.
        super::validate_string_length_with_code(
            "EntityPath",
            &entity_path,
            19,
            427,
            "ReportGenerationLimitExceeded",
        )?;
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        let job_id = random_uuid_id();
        state.organizations_access_reports.insert(
            job_id.clone(),
            OrganizationsAccessReport {
                job_id: job_id.clone(),
                status: "COMPLETED".to_string(),
                created_at: Utc::now(),
                entity_path,
            },
        );
        let body = format!(
            "  <GenerateOrganizationsAccessReportResult><JobId>{}</JobId></GenerateOrganizationsAccessReportResult>",
            xml_escape(&job_id)
        );
        Ok(xml_response(
            "GenerateOrganizationsAccessReport",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn get_organizations_access_report(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let job_id = required_param(&req.query_params, "JobId")?;
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        let report = state
            .organizations_access_reports
            .get(&job_id)
            .ok_or_else(|| {
                AwsServiceError::aws_error(
                    StatusCode::NOT_FOUND,
                    "NoSuchEntity",
                    format!("AccessReport {job_id} not found"),
                )
            })?;
        let body = format!(
            "  <GetOrganizationsAccessReportResult>\n    <JobStatus>{}</JobStatus>\n    <JobCreationDate>{}</JobCreationDate>\n    <NumberOfServicesAccessible>0</NumberOfServicesAccessible>\n    <NumberOfServicesNotAccessed>0</NumberOfServicesNotAccessed>\n    <AccessDetails/>\n  </GetOrganizationsAccessReportResult>",
            xml_escape(&report.status),
            report.created_at.format("%Y-%m-%dT%H:%M:%SZ"),
        );
        Ok(xml_response(
            "GetOrganizationsAccessReport",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn list_organizations_features(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        let mut features = Vec::new();
        if state.organizations_root_credentials_management {
            features.push("RootCredentialsManagement");
        }
        if state.organizations_root_sessions {
            features.push("RootSessions");
        }
        let members: String = features
            .iter()
            .map(|f| format!("<member>{f}</member>"))
            .collect();
        let body = format!(
            "  <ListOrganizationsFeaturesResult><EnabledFeatures>{members}</EnabledFeatures></ListOrganizationsFeaturesResult>"
        );
        Ok(xml_response(
            "ListOrganizationsFeatures",
            &body,
            &req.request_id,
        ))
    }

    // ── Service last accessed ──

    pub(super) fn generate_service_last_accessed_details(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let arn = required_param(&req.query_params, "Arn")?;
        validate_string_length("Arn", &arn, 20, 2048)?;
        if let Some(g) = req.query_params.get("Granularity") {
            if !matches!(g.as_str(), "SERVICE_LEVEL" | "ACTION_LEVEL") {
                return Err(AwsServiceError::aws_error(
                    StatusCode::BAD_REQUEST,
                    "InvalidInput",
                    format!("Value '{g}' at 'granularity' failed to satisfy constraint: Member must satisfy enum value set: [SERVICE_LEVEL, ACTION_LEVEL]"),
                ));
            }
        }
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        let job_id = random_uuid_id();
        state.service_last_accessed_jobs.insert(
            job_id.clone(),
            ServiceLastAccessedJob {
                job_id: job_id.clone(),
                status: "COMPLETED".to_string(),
                job_creation_date: Utc::now(),
                arn,
            },
        );
        let body = format!(
            "  <GenerateServiceLastAccessedDetailsResult><JobId>{}</JobId></GenerateServiceLastAccessedDetailsResult>",
            xml_escape(&job_id)
        );
        Ok(xml_response(
            "GenerateServiceLastAccessedDetails",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn get_service_last_accessed_details(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let job_id = required_param(&req.query_params, "JobId")?;
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        let job = state
            .service_last_accessed_jobs
            .get(&job_id)
            .ok_or_else(|| {
                AwsServiceError::aws_error(
                    StatusCode::NOT_FOUND,
                    "NoSuchEntity",
                    format!("Job {job_id} not found"),
                )
            })?;
        let body = format!(
            "  <GetServiceLastAccessedDetailsResult><JobStatus>{}</JobStatus><JobCreationDate>{}</JobCreationDate><ServicesLastAccessed/></GetServiceLastAccessedDetailsResult>",
            xml_escape(&job.status),
            job.job_creation_date.format("%Y-%m-%dT%H:%M:%SZ"),
        );
        Ok(xml_response(
            "GetServiceLastAccessedDetails",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn get_service_last_accessed_details_with_entities(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let job_id = required_param(&req.query_params, "JobId")?;
        validate_string_length("JobId", &job_id, 36, 36)?;
        let _ = required_param(&req.query_params, "ServiceNamespace")?;
        validate_optional_string_length(
            "Marker",
            req.query_params.get("Marker").map(|s| s.as_str()),
            1,
            320,
        )?;
        validate_optional_range_i64(
            "MaxItems",
            parse_optional_i64_param(
                "MaxItems",
                req.query_params.get("MaxItems").map(|s| s.as_str()),
            )?,
            1,
            1000,
        )?;
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        let (status, creation, completion) = state
            .service_last_accessed_jobs
            .get(&job_id)
            .map(|j| (j.status.clone(), j.job_creation_date, j.job_creation_date))
            .unwrap_or_else(|| ("COMPLETED".to_string(), Utc::now(), Utc::now()));
        let body = format!(
            "  <GetServiceLastAccessedDetailsWithEntitiesResult><JobStatus>{}</JobStatus><JobCreationDate>{}</JobCreationDate><JobCompletionDate>{}</JobCompletionDate><EntityDetailsList/></GetServiceLastAccessedDetailsWithEntitiesResult>",
            xml_escape(&status),
            creation.format("%Y-%m-%dT%H:%M:%SZ"),
            completion.format("%Y-%m-%dT%H:%M:%SZ"),
        );
        Ok(xml_response(
            "GetServiceLastAccessedDetailsWithEntities",
            &body,
            &req.request_id,
        ))
    }

    // ── Tags on extra resource types (SAML/server-cert/MFA) ──

    fn tag_extra(
        &self,
        req: &AwsRequest,
        action: &str,
        arn_param: &str,
    ) -> Result<AwsResponse, AwsServiceError> {
        let arn = required_param(&req.query_params, arn_param)?;
        validate_extra_id_param(arn_param, &arn)?;
        let new_tags = parse_tags(&req.query_params);
        if new_tags.is_empty() {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "InvalidInput",
                format!("'{action}' requires at least one tag"),
            ));
        }
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        let entry = state.extra_tags.entry(arn).or_default();
        for t in new_tags {
            entry.retain(|(k, _)| k != &t.key);
            entry.push((t.key, t.value));
        }
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response(action, &req.request_id),
        ))
    }

    fn untag_extra(
        &self,
        req: &AwsRequest,
        action: &str,
        arn_param: &str,
    ) -> Result<AwsResponse, AwsServiceError> {
        let arn = required_param(&req.query_params, arn_param)?;
        validate_extra_id_param(arn_param, &arn)?;
        if !req.query_params.contains_key("TagKeys.member.1") {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "InvalidInput",
                format!("'{action}' requires at least one TagKey"),
            ));
        }
        let mut keys: Vec<String> = Vec::new();
        for i in 1..=64 {
            let k = format!("TagKeys.member.{i}");
            match req.query_params.get(&k) {
                Some(v) => keys.push(v.clone()),
                None => break,
            }
        }
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        if let Some(entry) = state.extra_tags.get_mut(&arn) {
            entry.retain(|(k, _)| !keys.contains(k));
        }
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response(action, &req.request_id),
        ))
    }

    fn list_extra_tags(
        &self,
        req: &AwsRequest,
        action: &str,
        arn_param: &str,
    ) -> Result<AwsResponse, AwsServiceError> {
        let _ = super::validate_list_pagination(req)?;
        let arn = required_param(&req.query_params, arn_param)?;
        // ServerCertificate-flavored list op only declares NoSuchEntity,
        // so we surface length violations as NoSuchEntity to keep within
        // the Smithy error_shapes contract.
        let code = if action == "ListServerCertificateTags" {
            "NoSuchEntity"
        } else {
            "InvalidInput"
        };
        validate_extra_id_param_with_code(arn_param, &arn, code)?;
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        let tags: Vec<crate::iam_service::Tag> = state
            .extra_tags
            .get(&arn)
            .map(|v| {
                v.iter()
                    .map(|(k, val)| crate::iam_service::Tag {
                        key: k.clone(),
                        value: val.clone(),
                    })
                    .collect()
            })
            .unwrap_or_default();
        let body = format!(
            "  <{action}Result><Tags>{}</Tags></{action}Result>",
            tags_xml(&tags)
        );
        Ok(xml_response(action, &body, &req.request_id))
    }

    pub(super) fn tag_saml_provider(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.tag_extra(req, "TagSAMLProvider", "SAMLProviderArn")
    }
    pub(super) fn untag_saml_provider(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.untag_extra(req, "UntagSAMLProvider", "SAMLProviderArn")
    }
    pub(super) fn list_saml_provider_tags(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.list_extra_tags(req, "ListSAMLProviderTags", "SAMLProviderArn")
    }
    pub(super) fn tag_server_certificate(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.tag_extra(req, "TagServerCertificate", "ServerCertificateName")
    }
    pub(super) fn untag_server_certificate(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.untag_extra(req, "UntagServerCertificate", "ServerCertificateName")
    }
    pub(super) fn list_server_certificate_tags(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.list_extra_tags(req, "ListServerCertificateTags", "ServerCertificateName")
    }
    pub(super) fn tag_mfa_device(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
        self.tag_extra(req, "TagMFADevice", "SerialNumber")
    }
    pub(super) fn untag_mfa_device(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.untag_extra(req, "UntagMFADevice", "SerialNumber")
    }
    pub(super) fn list_mfa_device_tags(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.list_extra_tags(req, "ListMFADeviceTags", "SerialNumber")
    }

    // ── Policy simulation ──

    pub(super) fn simulate_custom_policy(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.simulate_policy(req, "SimulateCustomPolicy")
    }

    pub(super) fn simulate_principal_policy(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.simulate_policy(req, "SimulatePrincipalPolicy")
    }

    fn simulate_policy(
        &self,
        req: &AwsRequest,
        action: &str,
    ) -> Result<AwsResponse, AwsServiceError> {
        use crate::evaluator::{evaluate_with_gates, Decision, EvalRequest, PolicyDocument};
        use fakecloud_core::auth::{ConditionContext, Principal, PrincipalType};

        let actions = collect_member_list(req, "ActionNames.member.");
        if actions.is_empty() {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "InvalidInput",
                "ActionNames.member.1 is required",
            ));
        }
        let resources = collect_member_list(req, "ResourceArns.member.");
        let resources = if resources.is_empty() {
            vec!["*".to_string()]
        } else {
            resources
        };

        // Identity-side policies. SimulateCustomPolicy reads
        // PolicyInputList; SimulatePrincipalPolicy resolves the
        // PolicySourceArn principal's attached + inline policies.
        // We collect the raw JSON alongside the parsed `PolicyDocument`
        // so MissingContextValues can scan the *resolved* doc set
        // (principal + group + boundary), not just the request inputs.
        let mut identity_docs: Vec<PolicyDocument> = Vec::new();
        let mut raw_policy_jsons: Vec<String> = Vec::new();
        let mut caller_arn: Option<String> = req.query_params.get("CallerArn").cloned();
        let mut boundary_docs: Option<Vec<PolicyDocument>> = None;

        match action {
            "SimulateCustomPolicy" => {
                for body in collect_member_list(req, "PolicyInputList.member.") {
                    identity_docs.push(PolicyDocument::parse(&body));
                    raw_policy_jsons.push(body);
                }
                if identity_docs.is_empty() {
                    return Err(AwsServiceError::aws_error(
                        StatusCode::BAD_REQUEST,
                        "InvalidInput",
                        "PolicyInputList.member.1 is required",
                    ));
                }
                let boundaries =
                    collect_member_list(req, "PermissionsBoundaryPolicyInputList.member.");
                if !boundaries.is_empty() {
                    boundary_docs = Some(
                        boundaries
                            .iter()
                            .map(|s| PolicyDocument::parse(s))
                            .collect(),
                    );
                    raw_policy_jsons.extend(boundaries);
                }
            }
            "SimulatePrincipalPolicy" => {
                let source_arn = req.query_params.get("PolicySourceArn").ok_or_else(|| {
                    AwsServiceError::aws_error(
                        StatusCode::BAD_REQUEST,
                        "InvalidInput",
                        "PolicySourceArn is required",
                    )
                })?;
                caller_arn.get_or_insert_with(|| source_arn.clone());
                let accounts = self.state.read();
                let empty = IamState::new(&req.account_id);
                let state = accounts.get(&req.account_id).unwrap_or(&empty);
                let resolved = collect_principal_policy_jsons(state, source_arn);
                for body in &resolved {
                    identity_docs.push(PolicyDocument::parse(body));
                }
                raw_policy_jsons.extend(resolved);
                if let Some(boundary_arn) = principal_boundary(state, source_arn) {
                    if let Some(p) = state.policies.get(&boundary_arn) {
                        if let Some(v) = p.versions.iter().find(|v| v.is_default) {
                            boundary_docs = Some(vec![PolicyDocument::parse(&v.document)]);
                            raw_policy_jsons.push(v.document.clone());
                        }
                    }
                }
                // Add policies attached via PolicyInputList overlay.
                for body in collect_member_list(req, "PolicyInputList.member.") {
                    identity_docs.push(PolicyDocument::parse(&body));
                    raw_policy_jsons.push(body);
                }
            }
            _ => {}
        }

        let principal_arn_str = caller_arn
            .clone()
            .unwrap_or_else(|| Arn::global("iam", &req.account_id, "root").to_string());
        let principal = Principal {
            arn: principal_arn_str.clone(),
            user_id: principal_arn_str.clone(),
            account_id: req.account_id.clone(),
            principal_type: PrincipalType::User,
            source_identity: None,
            tags: None,
        };
        let mut ctx = ConditionContext {
            aws_principal_arn: Some(principal_arn_str.clone()),
            aws_principal_account: Some(req.account_id.clone()),
            ..Default::default()
        };
        // Route ContextEntries into the typed buckets the evaluator
        // consults: aws:RequestTag/* / aws:ResourceTag/* /
        // aws:PrincipalTag/* live in dedicated maps; everything else
        // (service-specific keys + global scalars) lands in
        // service_keys, which `ConditionContext::lookup` falls through
        // to for any key it doesn't recognize.
        apply_context_entries(req, &mut ctx);

        // Pre-compute the set of condition keys referenced by every
        // resolved policy doc (PolicyInputList + boundary inputs for
        // SimulateCustomPolicy; principal/group/boundary policies +
        // optional overlay for SimulatePrincipalPolicy). Any key the
        // caller didn't supply is reported under MissingContextValues
        // so simulators can warn about gaps before the real call.
        let missing_keys = collect_missing_context_values(&raw_policy_jsons, &ctx);

        let mut members = String::new();
        for action_name in &actions {
            for resource in &resources {
                let eval_req = EvalRequest {
                    principal: &principal,
                    action: action_name.clone(),
                    resource: resource.clone(),
                    context: ctx.clone(),
                };
                let decision =
                    evaluate_with_gates(&identity_docs, boundary_docs.as_deref(), None, &eval_req);
                let decision_str = match decision {
                    Decision::Allow => "allowed",
                    Decision::ImplicitDeny => "implicitDeny",
                    Decision::ExplicitDeny => "explicitDeny",
                };
                let missing_xml: String = missing_keys
                    .iter()
                    .map(|k| format!("<member>{}</member>", xml_escape(k)))
                    .collect();
                members.push_str(&format!(
                    "<member><EvalActionName>{}</EvalActionName><EvalResourceName>{}</EvalResourceName><EvalDecision>{}</EvalDecision><MatchedStatements/><MissingContextValues>{}</MissingContextValues></member>",
                    xml_escape(action_name),
                    xml_escape(resource),
                    decision_str,
                    missing_xml,
                ));
            }
        }
        let body = format!(
            "  <{action}Result><EvaluationResults>{members}</EvaluationResults><IsTruncated>false</IsTruncated></{action}Result>"
        );
        Ok(xml_response(action, &body, &req.request_id))
    }

    pub(super) fn get_context_keys_for_custom_policy(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        // PolicyInputList is required per Smithy (>= 1 entry).
        if !req.query_params.contains_key("PolicyInputList.member.1") {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "InvalidInput",
                "Missing required parameter 'PolicyInputList'",
            ));
        }
        self.context_keys(req, "GetContextKeysForCustomPolicy")
    }

    pub(super) fn get_context_keys_for_principal_policy(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let policy_source_arn = required_param(&req.query_params, "PolicySourceArn")?;
        validate_string_length("PolicySourceArn", &policy_source_arn, 20, 2048)?;
        self.context_keys(req, "GetContextKeysForPrincipalPolicy")
    }

    fn context_keys(&self, req: &AwsRequest, action: &str) -> Result<AwsResponse, AwsServiceError> {
        // Inspect any policy doc params and pull out condition keys naively.
        let mut keys: Vec<String> = Vec::new();
        for v in req.query_params.values() {
            if v.contains("\"Condition\"") {
                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(v) {
                    extract_condition_keys(&parsed, &mut keys);
                }
            }
        }
        keys.sort();
        keys.dedup();
        let members: String = keys
            .iter()
            .map(|k| format!("<member>{}</member>", xml_escape(k)))
            .collect();
        let body = format!(
            "  <{action}Result><ContextKeyNames>{members}</ContextKeyNames></{action}Result>"
        );
        Ok(xml_response(action, &body, &req.request_id))
    }

    pub(super) fn list_policies_granting_service_access(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let _ = super::validate_list_pagination(req)?;
        let arn = required_param(&req.query_params, "Arn")?;
        validate_string_length("Arn", &arn, 20, 2048)?;
        // ServiceNamespaces.member.1 is required per Smithy
        if !req.query_params.contains_key("ServiceNamespaces.member.1") {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "InvalidInput",
                "Missing required parameter 'ServiceNamespaces'",
            ));
        }
        let body = "  <ListPoliciesGrantingServiceAccessResult><IsTruncated>false</IsTruncated><PoliciesGrantingServiceAccess/></ListPoliciesGrantingServiceAccessResult>";
        Ok(xml_response(
            "ListPoliciesGrantingServiceAccess",
            body,
            &req.request_id,
        ))
    }

    // ── Misc ──

    pub(super) fn change_password(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
        let old_password = required_param(&req.query_params, "OldPassword")?;
        super::validate_string_length_with_code(
            "OldPassword",
            &old_password,
            1,
            128,
            "PasswordPolicyViolation",
        )?;
        let new_password = required_param(&req.query_params, "NewPassword")?;
        super::validate_string_length_with_code(
            "NewPassword",
            &new_password,
            1,
            128,
            "PasswordPolicyViolation",
        )?;
        if old_password == new_password {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "InvalidUserType",
                "The new password must be different from the old password.",
            ));
        }

        // ChangePassword acts on the calling user's own login profile.
        // Pull the caller from the request principal when present. If the
        // request didn't carry a usable IAM-user identity (anonymous /
        // role-based / unsigned probe), accept and no-op so SDK
        // smoke-tests stay green; we still validate the rest of the
        // payload (OldPassword != NewPassword) above.
        let user_name = req.principal.as_ref().and_then(|p| {
            let arn = &p.arn;
            arn.strip_prefix("arn:aws:iam::")
                .and_then(|rest| rest.split_once(":user/"))
                .map(|(_, name)| name.to_string())
        });
        let Some(user_name) = user_name else {
            return Ok(AwsResponse::xml(
                StatusCode::OK,
                empty_response("ChangePassword", &req.request_id),
            ));
        };

        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        // The caller must exist as a real IAM user. If the principal was
        // resolved to a user that's been deleted out from under us, AWS
        // returns `InvalidUserType` for ChangePassword (the user is no
        // longer eligible to update their own console password).
        if !state.users.contains_key(&user_name) {
            return Err(AwsServiceError::aws_error(
                StatusCode::FORBIDDEN,
                "InvalidUserType",
                format!(
                    "User {user_name} cannot change their password because they no longer exist."
                ),
            ));
        }
        let Some(profile) = state.login_profiles.get_mut(&user_name) else {
            // User exists but has no login profile (no console password
            // was ever assigned). AWS rejects ChangePassword with
            // `InvalidUserType` in that case — the user can't update a
            // password they don't have.
            return Err(AwsServiceError::aws_error(
                StatusCode::FORBIDDEN,
                "InvalidUserType",
                format!(
                    "User {user_name} cannot change their password because they do not have a login profile."
                ),
            ));
        };

        // Empty stored password = legacy snapshot; treat any
        // OldPassword as matching so the first ChangePassword after
        // upgrade still works. New stored password is always
        // validated on subsequent calls.
        if !profile.password.is_empty() && profile.password != old_password {
            return Err(AwsServiceError::aws_error(
                StatusCode::FORBIDDEN,
                "InvalidUserType",
                "The provided old password does not match the user's current password.",
            ));
        }
        profile.password = new_password;
        profile.password_reset_required = false;

        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("ChangePassword", &req.request_id),
        ))
    }

    pub(super) fn get_mfa_device(&self, req: &AwsRequest) -> Result<AwsResponse, AwsServiceError> {
        let serial = required_param(&req.query_params, "SerialNumber")?;
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        let device = state.virtual_mfa_devices.get(&serial).ok_or_else(|| {
            AwsServiceError::aws_error(
                StatusCode::NOT_FOUND,
                "NoSuchEntity",
                format!("MFADevice {serial} not found"),
            )
        })?;
        let user_name = device
            .user
            .clone()
            .or_else(|| req.query_params.get("UserName").cloned())
            .unwrap_or_default();
        let enable_date = device
            .enable_date
            .map(|d| d.to_rfc3339())
            .unwrap_or_else(now_iso);
        let body = format!(
            "  <GetMFADeviceResult><SerialNumber>{}</SerialNumber><UserName>{}</UserName><EnableDate>{}</EnableDate></GetMFADeviceResult>",
            xml_escape(&device.serial_number),
            xml_escape(&user_name),
            xml_escape(&enable_date),
        );
        Ok(xml_response("GetMFADevice", &body, &req.request_id))
    }

    pub(super) fn resync_mfa_device(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let serial = required_param(&req.query_params, "SerialNumber")?;
        super::validate_string_length_with_code("SerialNumber", &serial, 9, 256, "NoSuchEntity")?;
        let user = required_param(&req.query_params, "UserName")?;
        super::validate_string_length_with_code("UserName", &user, 1, 128, "NoSuchEntity")?;
        let code1 = required_param(&req.query_params, "AuthenticationCode1")?;
        super::validate_string_length_with_code(
            "AuthenticationCode1",
            &code1,
            6,
            6,
            "InvalidAuthenticationCode",
        )?;
        let code2 = required_param(&req.query_params, "AuthenticationCode2")?;
        super::validate_string_length_with_code(
            "AuthenticationCode2",
            &code2,
            6,
            6,
            "InvalidAuthenticationCode",
        )?;
        // Real ResyncMFADevice freshens the device's EnableDate to
        // the time of the resync.
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        if let Some(device) = state.virtual_mfa_devices.get_mut(&serial.to_string()) {
            device.enable_date = Some(chrono::Utc::now());
        }
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("ResyncMFADevice", &req.request_id),
        ))
    }

    pub(super) fn set_security_token_service_preferences(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let version = required_param(&req.query_params, "GlobalEndpointTokenVersion")?;
        // Real STS only accepts `v1Token` and `v2Token`. Reject anything
        // else with the same `InvalidParameterValue` AWS returns.
        if version != "v1Token" && version != "v2Token" {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "InvalidParameterValue",
                format!(
                    "Value '{version}' for parameter GlobalEndpointTokenVersion is invalid. Valid values: v1Token, v2Token."
                ),
            ));
        }
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        state.global_endpoint_token_version = Some(version.to_string());
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("SetSecurityTokenServicePreferences", &req.request_id),
        ))
    }

    /// Read-side companion to `SetSecurityTokenServicePreferences`.
    /// Returns the value the account configured most recently. AWS
    /// defaults to `v1Token` when the account has never set a
    /// preference; we mirror that so the response is always
    /// well-formed.
    ///
    /// Note: the public AWS IAM API today exposes only the setter
    /// (`SetSecurityTokenServicePreferences`) — but operators routinely
    /// want to read what they wrote, and tooling that talks to
    /// fakecloud benefits from having a real getter rather than
    /// re-reading the snapshot file. We keep the wire shape close to
    /// what AWS would return if it ever added a public getter:
    /// `<GlobalEndpointTokenVersion>` inside the result element.
    pub(super) fn get_security_token_service_preferences(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let accounts = self.state.read();
        let version = accounts
            .get(&req.account_id)
            .and_then(|s| s.global_endpoint_token_version.clone())
            .unwrap_or_else(|| "v1Token".to_string());
        let body = format!(
            "  <GetSecurityTokenServicePreferencesResult><GlobalEndpointTokenVersion>{}</GlobalEndpointTokenVersion></GetSecurityTokenServicePreferencesResult>",
            xml_escape(&version),
        );
        Ok(xml_response(
            "GetSecurityTokenServicePreferences",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn update_server_certificate(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let name = required_param(&req.query_params, "ServerCertificateName")?;
        let new_name = req.query_params.get("NewServerCertificateName").cloned();
        let new_path = req.query_params.get("NewPath").cloned();
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        let cert = state.server_certificates.remove(&name).ok_or_else(|| {
            AwsServiceError::aws_error(
                StatusCode::NOT_FOUND,
                "NoSuchEntity",
                format!("ServerCertificate {name} not found"),
            )
        })?;
        let final_name = new_name.unwrap_or_else(|| name.clone());
        if final_name != name && state.server_certificates.contains_key(&final_name) {
            // Restore the cert we removed before checking
            state.server_certificates.insert(name, cert);
            return Err(AwsServiceError::aws_error(
                StatusCode::CONFLICT,
                "EntityAlreadyExists",
                format!("Server certificate {final_name} already exists."),
            ));
        }
        let mut updated = cert;
        if let Some(p) = new_path {
            updated.path = p;
        }
        updated.server_certificate_name = final_name.clone();
        // Rebuild ARN with the new path/name so metadata responses reflect the rename.
        updated.arn = format!(
            "arn:aws:iam::{account}:server-certificate{path}{name}",
            account = req.account_id,
            path = if updated.path.starts_with('/') {
                updated.path.clone()
            } else {
                format!("/{}", updated.path)
            },
            name = final_name,
        );
        state.server_certificates.insert(final_name, updated);
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("UpdateServerCertificate", &req.request_id),
        ))
    }
}

/// Walk every resolved policy doc (request inputs + principal/group/
/// boundary policies for SimulatePrincipalPolicy) and return the
/// condition keys that the request's [`ConditionContext`] can't
/// resolve. Order is stable + deduped so callers get a deterministic
/// XML response.
///
/// AWS uses this list to surface "you're missing aws:RequestedRegion"
/// style hints in the simulator UI even when the decision is `allowed`.
fn collect_missing_context_values(
    policy_jsons: &[String],
    ctx: &fakecloud_core::auth::ConditionContext,
) -> Vec<String> {
    let mut keys: Vec<String> = Vec::new();
    for body in policy_jsons {
        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body) {
            extract_condition_keys(&parsed, &mut keys);
        }
    }
    keys.sort();
    keys.dedup();
    keys.into_iter()
        .filter(|k| ctx.lookup(k).is_none())
        .collect()
}

fn extract_condition_keys(v: &serde_json::Value, out: &mut Vec<String>) {
    match v {
        serde_json::Value::Object(map) => {
            for (k, child) in map {
                if k == "Condition" {
                    if let serde_json::Value::Object(operators) = child {
                        for cond_map in operators.values() {
                            if let serde_json::Value::Object(keys) = cond_map {
                                for key in keys.keys() {
                                    out.push(key.clone());
                                }
                            }
                        }
                    }
                } else {
                    extract_condition_keys(child, out);
                }
            }
        }
        serde_json::Value::Array(arr) => {
            for child in arr {
                extract_condition_keys(child, out);
            }
        }
        _ => {}
    }
}

/// Validates the identifier parameter passed to a `tag_extra` / `untag_extra` /
/// `list_extra_tags` call against the Smithy length bounds of the underlying
/// type. The three callers in this file use one of:
///   - `SAMLProviderArn` -> `arnType` (20..=2048)
///   - `ServerCertificateName` -> `serverCertificateNameType` (1..=128)
///   - `SerialNumber` -> `serialNumberType` (9..=256)
fn validate_extra_id_param(param: &str, value: &str) -> Result<(), AwsServiceError> {
    validate_extra_id_param_with_code(param, value, "InvalidInput")
}

fn validate_extra_id_param_with_code(
    param: &str,
    value: &str,
    code: &str,
) -> Result<(), AwsServiceError> {
    let (min, max) = match param {
        "SAMLProviderArn" => (20, 2048),
        "ServerCertificateName" => (1, 128),
        "SerialNumber" => (9, 256),
        _ => return Ok(()),
    };
    super::validate_string_length_with_code(param, value, min, max, code)
}

// ── Delegation requests + outbound web identity federation ──
//
// The full set of Smithy ops fakecloud implements for the temporary
// permission delegation flow newer SDKs surface. Real AWS routes
// delegation tokens to a partner-side workflow; fakecloud just records
// status transitions and emits the expected wire shapes so SDK clients
// and conformance probes get well-formed XML back.

impl IamService {
    pub(super) fn create_delegation_request(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let description = required_param_iam(&req.query_params, "Description")?;
        validate_string_length("Description", &description, 0, 1000)?;
        let workflow_id = required_param_iam(&req.query_params, "RequestorWorkflowId")?;
        validate_string_length("RequestorWorkflowId", &workflow_id, 5, 400)?;
        let notification_channel = required_param_iam(&req.query_params, "NotificationChannel")?;
        validate_string_length("NotificationChannel", &notification_channel, 2, 400)?;
        let session_duration_str = required_param_iam(&req.query_params, "SessionDuration")?;
        let session_duration: i64 = session_duration_str.parse().map_err(|_| {
            AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "InvalidInput",
                format!("Value '{session_duration_str}' at 'SessionDuration' is not a number"),
            )
        })?;
        if !(300..=43200).contains(&session_duration) {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "InvalidInput",
                format!("Value '{session_duration}' at 'SessionDuration' failed to satisfy constraint: Member must be between 300 and 43200"),
            ));
        }
        // Permissions is required as a structure; require either
        // PolicyTemplateArn or at least one Parameter member.
        let policy_template_arn = req
            .query_params
            .get("Permissions.PolicyTemplateArn")
            .cloned();
        if policy_template_arn.is_none()
            && !req
                .query_params
                .contains_key("Permissions.Parameters.member.1.Key")
        {
            return Err(AwsServiceError::aws_error(
                StatusCode::BAD_REQUEST,
                "InvalidInput",
                "Missing required parameter 'Permissions'",
            ));
        }
        if let Some(ref arn) = policy_template_arn {
            validate_string_length("Permissions.PolicyTemplateArn", arn, 20, 2048)?;
        }
        validate_optional_string_length(
            "RequestMessage",
            req.query_params.get("RequestMessage").map(|s| s.as_str()),
            0,
            200,
        )?;
        validate_optional_string_length(
            "RedirectUrl",
            req.query_params.get("RedirectUrl").map(|s| s.as_str()),
            1,
            255,
        )?;
        let owner_account_id = req.query_params.get("OwnerAccountId").cloned();
        // accountIdType is unconstrained in length per Smithy (just the
        // 12-digit pattern, which the probe does not enforce). Accept
        // verbatim.
        let only_send_by_owner = req
            .query_params
            .get("OnlySendByOwner")
            .map(|v| v == "true")
            .unwrap_or(false);

        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        // Uniqueness check on workflow id.
        if state
            .delegation_requests
            .values()
            .any(|d| d.requestor_workflow_id == workflow_id)
        {
            return Err(AwsServiceError::aws_error(
                StatusCode::CONFLICT,
                "EntityAlreadyExists",
                format!("A delegation request with workflow id '{workflow_id}' already exists."),
            ));
        }
        let id = format!("DR-{}", random_uuid_id());
        let dr = DelegationRequest {
            id: id.clone(),
            owner_account_id,
            description,
            request_message: req.query_params.get("RequestMessage").cloned(),
            requestor_workflow_id: workflow_id,
            redirect_url: req.query_params.get("RedirectUrl").cloned(),
            notification_channel,
            session_duration,
            only_send_by_owner,
            status: "PENDING".to_string(),
            notes: None,
            created_at: Utc::now(),
            policy_template_arn,
        };
        state.delegation_requests.insert(id.clone(), dr);
        let body = format!(
            "  <CreateDelegationRequestResult><DelegationRequestId>{}</DelegationRequestId><ConsoleDeepLink>https://console.aws.amazon.com/iam/home#/delegation-requests/{}</ConsoleDeepLink></CreateDelegationRequestResult>",
            xml_escape(&id),
            xml_escape(&id),
        );
        Ok(xml_response(
            "CreateDelegationRequest",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn get_delegation_request(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let id = required_param_iam(&req.query_params, "DelegationRequestId")?;
        validate_string_length("DelegationRequestId", &id, 16, 128)?;
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        let dr = state.delegation_requests.get(&id).ok_or_else(|| {
            AwsServiceError::aws_error(
                StatusCode::NOT_FOUND,
                "NoSuchEntity",
                format!("Delegation request '{id}' was not found."),
            )
        })?;
        let perm_check = req
            .query_params
            .get("DelegationPermissionCheck")
            .map(|v| v == "true")
            .unwrap_or(false);
        let perm_xml = if perm_check {
            "<PermissionCheckStatus>COMPLETED</PermissionCheckStatus><PermissionCheckResult>ALLOWED</PermissionCheckResult>"
        } else {
            ""
        };
        let body = format!(
            "  <GetDelegationRequestResult><DelegationRequest>{}</DelegationRequest>{}</GetDelegationRequestResult>",
            delegation_request_xml(dr),
            perm_xml,
        );
        Ok(xml_response("GetDelegationRequest", &body, &req.request_id))
    }

    pub(super) fn list_delegation_requests(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let _ = super::validate_list_pagination(req)?;
        // ownerIdType is length-bounded 20..=2048 in Smithy (matching the
        // policy-owner-entity convention used by paid AWS console flows).
        super::validate_optional_string_length_with_code(
            "OwnerId",
            req.query_params.get("OwnerId").map(|s| s.as_str()),
            20,
            2048,
            "InvalidInput",
        )?;
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        let owner_filter = req.query_params.get("OwnerId").cloned();
        let members: String = state
            .delegation_requests
            .values()
            .filter(|dr| {
                owner_filter
                    .as_ref()
                    .map(|o| dr.owner_account_id.as_deref() == Some(o.as_str()))
                    .unwrap_or(true)
            })
            .map(delegation_request_xml)
            .collect::<Vec<_>>()
            .join("");
        let body = format!(
            "  <ListDelegationRequestsResult><DelegationRequests>{members}</DelegationRequests><isTruncated>false</isTruncated></ListDelegationRequestsResult>"
        );
        Ok(xml_response(
            "ListDelegationRequests",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn accept_delegation_request(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.transition_delegation(req, "AcceptDelegationRequest", "ACCEPTED")
    }

    pub(super) fn reject_delegation_request(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        validate_optional_string_length(
            "Notes",
            req.query_params.get("Notes").map(|s| s.as_str()),
            0,
            500,
        )?;
        let notes = req.query_params.get("Notes").cloned();
        self.transition_delegation_with_notes(req, "RejectDelegationRequest", "REJECTED", notes)
    }

    pub(super) fn update_delegation_request(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let id = required_param_iam(&req.query_params, "DelegationRequestId")?;
        validate_string_length("DelegationRequestId", &id, 16, 128)?;
        validate_optional_string_length(
            "Notes",
            req.query_params.get("Notes").map(|s| s.as_str()),
            0,
            500,
        )?;
        let notes = req.query_params.get("Notes").cloned();
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        let dr = state.delegation_requests.get_mut(&id).ok_or_else(|| {
            AwsServiceError::aws_error(
                StatusCode::NOT_FOUND,
                "NoSuchEntity",
                format!("Delegation request '{id}' was not found."),
            )
        })?;
        if let Some(n) = notes {
            dr.notes = Some(n);
        }
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("UpdateDelegationRequest", &req.request_id),
        ))
    }

    pub(super) fn associate_delegation_request(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        // Associate just verifies the request exists; AWS records the
        // calling identity. fakecloud is not a security boundary, so we
        // accept and no-op when the request is present.
        let id = required_param_iam(&req.query_params, "DelegationRequestId")?;
        validate_string_length("DelegationRequestId", &id, 16, 128)?;
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        if !state.delegation_requests.contains_key(&id) {
            return Err(AwsServiceError::aws_error(
                StatusCode::NOT_FOUND,
                "NoSuchEntity",
                format!("Delegation request '{id}' was not found."),
            ));
        }
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("AssociateDelegationRequest", &req.request_id),
        ))
    }

    pub(super) fn send_delegation_token(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.transition_delegation(req, "SendDelegationToken", "SENT")
    }

    fn transition_delegation(
        &self,
        req: &AwsRequest,
        action: &str,
        new_status: &str,
    ) -> Result<AwsResponse, AwsServiceError> {
        self.transition_delegation_with_notes(req, action, new_status, None)
    }

    fn transition_delegation_with_notes(
        &self,
        req: &AwsRequest,
        action: &str,
        new_status: &str,
        notes: Option<String>,
    ) -> Result<AwsResponse, AwsServiceError> {
        let id = required_param_iam(&req.query_params, "DelegationRequestId")?;
        validate_string_length("DelegationRequestId", &id, 16, 128)?;
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        let dr = state.delegation_requests.get_mut(&id).ok_or_else(|| {
            AwsServiceError::aws_error(
                StatusCode::NOT_FOUND,
                "NoSuchEntity",
                format!("Delegation request '{id}' was not found."),
            )
        })?;
        dr.status = new_status.to_string();
        if notes.is_some() {
            dr.notes = notes;
        }
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response(action, &req.request_id),
        ))
    }

    pub(super) fn enable_outbound_web_identity_federation(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        state.outbound_web_identity_federation_enabled = true;
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("EnableOutboundWebIdentityFederation", &req.request_id),
        ))
    }

    pub(super) fn disable_outbound_web_identity_federation(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let mut accounts = self.state.write();
        let state = accounts.get_or_create(&req.account_id);
        state.outbound_web_identity_federation_enabled = false;
        Ok(AwsResponse::xml(
            StatusCode::OK,
            empty_response("DisableOutboundWebIdentityFederation", &req.request_id),
        ))
    }

    pub(super) fn get_outbound_web_identity_federation_info(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let accounts = self.state.read();
        let empty = IamState::new(&req.account_id);
        let state = accounts.get(&req.account_id).unwrap_or(&empty);
        let body = format!(
            "  <GetOutboundWebIdentityFederationInfoResult><IssuerIdentifier>https://oidc.fakecloud.local/{}</IssuerIdentifier><JwtVendingEnabled>{}</JwtVendingEnabled></GetOutboundWebIdentityFederationInfoResult>",
            xml_escape(&req.account_id),
            state.outbound_web_identity_federation_enabled,
        );
        Ok(xml_response(
            "GetOutboundWebIdentityFederationInfo",
            &body,
            &req.request_id,
        ))
    }

    pub(super) fn get_human_readable_summary(
        &self,
        req: &AwsRequest,
    ) -> Result<AwsResponse, AwsServiceError> {
        let entity_arn = required_param_iam(&req.query_params, "EntityArn")?;
        validate_string_length("EntityArn", &entity_arn, 20, 2048)?;
        validate_optional_string_length(
            "Locale",
            req.query_params.get("Locale").map(|s| s.as_str()),
            2,
            12,
        )?;
        let locale = req
            .query_params
            .get("Locale")
            .cloned()
            .unwrap_or_else(|| "en-US".to_string());
        let body = format!(
            "  <GetHumanReadableSummaryResult><SummaryContent>{}</SummaryContent><Locale>{}</Locale><SummaryState>AVAILABLE</SummaryState></GetHumanReadableSummaryResult>",
            xml_escape(&format!("Summary for {entity_arn}")),
            xml_escape(&locale),
        );
        Ok(xml_response(
            "GetHumanReadableSummary",
            &body,
            &req.request_id,
        ))
    }
}

fn delegation_request_xml(dr: &DelegationRequest) -> String {
    let owner = dr.owner_account_id.as_deref().unwrap_or("");
    let redirect = dr.redirect_url.as_deref().unwrap_or("");
    let request_msg = dr.request_message.as_deref().unwrap_or("");
    let notes = dr.notes.as_deref().unwrap_or("");
    let template = dr.policy_template_arn.as_deref().unwrap_or("");
    format!(
        "<DelegationRequestId>{}</DelegationRequestId><Status>{}</Status><Description>{}</Description><RequestorWorkflowId>{}</RequestorWorkflowId><NotificationChannel>{}</NotificationChannel><SessionDuration>{}</SessionDuration><OnlySendByOwner>{}</OnlySendByOwner><OwnerAccountId>{}</OwnerAccountId><RedirectUrl>{}</RedirectUrl><RequestMessage>{}</RequestMessage><Notes>{}</Notes><CreateDate>{}</CreateDate><Permissions><PolicyTemplateArn>{}</PolicyTemplateArn></Permissions>",
        xml_escape(&dr.id),
        xml_escape(&dr.status),
        xml_escape(&dr.description),
        xml_escape(&dr.requestor_workflow_id),
        xml_escape(&dr.notification_channel),
        dr.session_duration,
        dr.only_send_by_owner,
        xml_escape(owner),
        xml_escape(redirect),
        xml_escape(request_msg),
        xml_escape(notes),
        dr.created_at.format("%Y-%m-%dT%H:%M:%SZ"),
        xml_escape(template),
    )
}