cloudformation-validate-template-model 1.12.0

AWS CloudFormation Validate
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
use template_model::SemanticModel;
use template_model::SpanProvider;
use template_model::resolver::ResolvedValue;

const TEMPLATES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../resources/templates");

fn model_from_fixture(path: &str) -> SemanticModel {
    let full = format!("{}/{}", TEMPLATES, path);
    let bytes = std::fs::read(&full).unwrap_or_else(|e| panic!("Failed to read {}: {}", full, e));
    SemanticModel::from_bytes(&bytes).unwrap_or_else(|e| panic!("Failed to parse {}: {}", full, e))
}

#[test]
fn model_resources_by_type() {
    let model = model_from_fixture("good/generic.yaml");
    let iam_roles = model.resources_of_type("AWS::IAM::Role");
    assert!(!iam_roles.is_empty(), "Expected IAM roles in generic template");
}

#[test]
fn model_rego_input_valid_json() {
    let model = model_from_fixture("good/generic.yaml");
    let json = serde_json::to_value(model.to_diagnostic_json()).unwrap();
    assert!(json.get("resources").is_some(), "expected 'resources' in diagnostic JSON");
    assert!(json.get("parameters").is_some(), "expected 'parameters' in diagnostic JSON");
    assert!(json.get("edges").is_some(), "expected 'edges' in diagnostic JSON");
}

#[test]
fn fixture_both_intrinsic_forms() {
    let model = model_from_fixture("good/both_forms.yaml");

    assert_eq!(model.resources.len(), 13);

    let bucket_short = model.resource("BucketShort").unwrap();
    match bucket_short.properties.get("BucketName") {
        Some(ResolvedValue::Enum { variants: _ }) => {}
        other => panic!("BucketShort.BucketName: expected Enum from Sub, got {:?}", other),
    }

    let bucket_long = model.resource("BucketLong").unwrap();
    match bucket_long.properties.get("BucketName") {
        Some(ResolvedValue::Enum { variants: _ }) => {}
        other => panic!("BucketLong.BucketName: expected Enum from Sub, got {:?}", other),
    }

    let with_getatt = model.resource("WithGetAtt").unwrap();
    match with_getatt.properties.get("ShortForm") {
        Some(ResolvedValue::Reference { target: t, .. }) => {
            assert_eq!(t, "BucketShort")
        }
        other => panic!("WithGetAtt.ShortForm: expected Reference, got {:?}", other),
    }
    match with_getatt.properties.get("LongFormDotted") {
        Some(ResolvedValue::Reference { target: t, .. }) => {
            assert_eq!(t, "BucketShort")
        }
        other => panic!("WithGetAtt.LongFormDotted: expected Reference, got {:?}", other),
    }
    match with_getatt.properties.get("LongFormArray") {
        Some(ResolvedValue::Reference { target: t, .. }) => {
            assert_eq!(t, "BucketLong")
        }
        other => panic!("WithGetAtt.LongFormArray: expected Reference, got {:?}", other),
    }

    let with_join = model.resource("WithJoin").unwrap();
    match with_join.properties.get("Short") {
        Some(ResolvedValue::Concrete { value: v }) => {
            assert_eq!(v.as_str().unwrap(), "a-b-c");
        }
        other => panic!("WithJoin.Short: expected Concrete 'a-b-c', got {:?}", other),
    }
    match with_join.properties.get("Long") {
        Some(ResolvedValue::Concrete { value: v }) => {
            assert_eq!(v.as_str().unwrap(), "x-y-z");
        }
        other => panic!("WithJoin.Long: expected Concrete 'x-y-z', got {:?}", other),
    }

    let with_select = model.resource("WithSelect").unwrap();
    match with_select.properties.get("Short") {
        Some(ResolvedValue::Concrete { value: v }) => {
            assert_eq!(v.as_str().unwrap(), "a")
        }
        other => panic!("WithSelect.Short: expected Concrete 'a', got {:?}", other),
    }
    match with_select.properties.get("Long") {
        Some(ResolvedValue::Concrete { value: v }) => {
            assert_eq!(v.as_str().unwrap(), "b")
        }
        other => panic!("WithSelect.Long: expected Concrete 'b', got {:?}", other),
    }

    let with_if = model.resource("WithIf").unwrap();
    assert!(
        matches!(with_if.properties.get("Short"), Some(ResolvedValue::Conditional { condition: c, .. }) if c == "IsProd")
    );
    assert!(
        matches!(with_if.properties.get("Long"), Some(ResolvedValue::Conditional { condition: c, .. }) if c == "IsProd")
    );

    let with_b64 = model.resource("WithBase64").unwrap();
    match with_b64.properties.get("Short") {
        Some(ResolvedValue::Concrete { value: v }) => {
            assert_eq!(v.as_str().unwrap(), "aGVsbG8=")
        }
        other => panic!("WithBase64.Short: expected Concrete base64, got {:?}", other),
    }

    let sub_block = model.resource("SubBlock").unwrap();
    match sub_block.properties.get("UserData") {
        Some(ResolvedValue::Enum { variants: _ }) => {}
        other => panic!("SubBlock.UserData: expected Enum from Sub, got {:?}", other),
    }

    assert!(model.conditions.conditions.contains_key("IsProd"));
    assert!(model.conditions.conditions.contains_key("IsDevShort"));
    assert!(model.conditions.conditions.contains_key("Combined"));

    assert!(model.mappings.contains_key("MyMap"));

    assert_eq!(model.outputs.len(), 1);
}

#[test]
fn parser_auto_detects_json() {
    let input = r#"{"Resources":{"R":{"Type":"T"}}}"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert_eq!(model.resources.len(), 1);
}

#[test]
fn parser_auto_detects_yaml() {
    let input = "Resources:\n  R:\n    Type: T\n";
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert_eq!(model.resources.len(), 1);
}

#[test]
fn parser_json_with_leading_whitespace() {
    let input = "  \n  {\"Resources\":{\"R\":{\"Type\":\"T\"}}}";
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert_eq!(model.resources.len(), 1);
}

#[test]
fn parser_yaml_with_comments() {
    let input = "# comment\nResources:\n  R:\n    Type: T\n    # inline comment\n";
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert_eq!(model.resources.len(), 1);
}

#[test]
fn parser_rejects_empty_input() {
    assert!(SemanticModel::from_bytes(b"").is_err(), "empty input should be rejected");
}

#[test]
fn parser_rejects_whitespace_only() {
    assert!(SemanticModel::from_bytes(b"   \n  \n  ").is_err(), "whitespace-only input should be rejected");
}

#[test]
fn parser_rejects_non_object_json() {
    assert!(SemanticModel::from_bytes(b"[1,2,3]").is_err(), "non-object JSON should be rejected");
}

#[test]
fn parser_rejects_scalar_yaml() {
    assert!(SemanticModel::from_bytes(b"just a string").is_err(), "scalar YAML should be rejected");
}

#[test]
fn parser_json_preserves_all_sections() {
    let input = r#"{
        "AWSTemplateFormatVersion": "2010-09-09",
        "Description": "Test template",
        "Parameters": {"P": {"Type": "String", "Default": "val"}},
        "Mappings": {"M": {"k1": {"k2": "v"}}},
        "Conditions": {"C": {"Fn::Equals": ["a", "a"]}},
        "Resources": {"R": {"Type": "T", "Properties": {"V": "x"}}},
        "Outputs": {"O": {"Value": {"Ref": "R"}}}
    }"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert_eq!(model.format_version.as_deref(), Some("2010-09-09"));
    assert_eq!(model.description.as_deref(), Some("Test template"));
    assert_eq!(model.parameters.len(), 1);
    assert_eq!(model.mappings.len(), 1);
    assert_eq!(model.conditions.conditions.len(), 1);
    assert_eq!(model.resources.len(), 1);
    assert_eq!(model.outputs.len(), 1);
}

#[test]
fn parser_yaml_preserves_all_sections() {
    let input = r#"
AWSTemplateFormatVersion: "2010-09-09"
Description: Test template
Parameters:
  P:
    Type: String
    Default: val
Mappings:
  M:
    k1:
      k2: v
Conditions:
  C:
    Fn::Equals: [a, a]
Resources:
  R:
    Type: T
    Properties:
      V: x
Outputs:
  O:
    Value: !Ref R
"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert_eq!(model.format_version.as_deref(), Some("2010-09-09"));
    assert_eq!(model.description.as_deref(), Some("Test template"));
    assert_eq!(model.parameters.len(), 1);
    assert_eq!(model.mappings.len(), 1);
    assert_eq!(model.conditions.conditions.len(), 1);
    assert_eq!(model.resources.len(), 1);
    assert_eq!(model.outputs.len(), 1);
}

#[test]
fn parser_json_yaml_produce_same_resource_types() {
    let json_input = r#"{"Resources":{"Bucket":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":"test"}}}}"#;
    let yaml_input = "Resources:\n  Bucket:\n    Type: AWS::S3::Bucket\n    Properties:\n      BucketName: test\n";
    let json_model = SemanticModel::from_bytes(json_input.as_bytes()).unwrap();
    let yaml_model = SemanticModel::from_bytes(yaml_input.as_bytes()).unwrap();
    assert_eq!(
        json_model.resource("Bucket").unwrap().resource_type,
        yaml_model.resource("Bucket").unwrap().resource_type
    );
}

#[test]
fn parser_yaml_intrinsic_short_forms() {
    let input = r#"
Resources:
  R:
    Type: T
    Properties:
      A: !Ref Param
      B: !Sub "hello-${AWS::Region}"
      C: !GetAtt Other.Arn
      D: !Join ["-", ["a", "b"]]
      E: !Select [0, ["x", "y"]]
      F: !Base64 hello
      G: !Split [",", "a,b"]
"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let r = model.resource("R").unwrap();
    assert_eq!(r.properties.len(), 7);
}

#[test]
fn parser_transform_single_string() {
    let input = "Transform: AWS::Serverless-2016-10-31\nResources:\n  R:\n    Type: T\n";
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert_eq!(model.transforms.len(), 1);
    assert_eq!(model.transforms[0], "AWS::Serverless-2016-10-31");
}

#[test]
fn parser_transform_list() {
    let input = r#"{"Transform":["AWS::Serverless-2016-10-31","AWS::Include"],"Resources":{"R":{"Type":"T"}}}"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert_eq!(model.transforms.len(), 2);
}

#[test]
fn parser_minimal_template_no_properties() {
    let input = r#"{"Resources":{"R":{"Type":"T"}}}"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let r = model.resource("R").unwrap();
    assert!(r.properties.is_empty());
    assert_eq!(r.resource_type, "T");
}

#[test]
fn parser_fn_if_undefined_condition_produces_e1028() {
    // An undefined Fn::If condition is reported once, as E1028, even when no
    // Conditions section is present, and points to the condition operand.
    let input = "Resources:\n  R:\n    Type: T\n    Properties:\n      V: !If [NonExistent, 1, 2]\n";
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let e1028: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E1028").collect();
    assert_eq!(e1028.len(), 1, "exactly one E1028 for an undefined Fn::If condition");
    assert!(e1028[0].message.contains("NonExistent"));
    assert_eq!(e1028[0].resource_id.as_deref(), Some("R"));
    assert_eq!(e1028[0].property_path.as_deref(), Some("Properties.V.Fn::If.0"));
    assert_eq!((e1028[0].span.start_line, e1028[0].span.start_column), (5, 15));
    assert!(!model.diagnostics.iter().any(|d| d.rule_id == "F1104"), "F1104 must no longer fire for this case");
}

#[test]
fn dynamic_reference_e1050_matches_reference_cases() {
    // Each malformed form fires E1050; each valid form does not. These mirror the
    // dynamic-reference schema (ssm numeric version, secretsmanager ARN 'secret'
    // segment, unknown service, and the tolerant ssm parameter-name search).
    let fires = |props: &str| {
        let input = format!(r#"{{"Resources":{{"B":{{"Type":"AWS::S3::Bucket","Properties":{props}}}}}}}"#);
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        model.diagnostics.iter().any(|d| d.rule_id == "E1050")
    };
    // Malformed → E1050
    assert!(fires(r#"{"BucketName":"{{resolve:ssm:/p:notanum}}"}"#), "ssm non-numeric version");
    assert!(fires(r#"{"BucketName":"{{resolve:not-a-service:foo}}"}"#), "unknown service");
    assert!(
        fires(r#"{"BucketName":"{{resolve:secretsmanager:arn:aws:s3:us-east-1:1:notsecret:n}}"}"#),
        "secretsmanager ARN missing 'secret' segment"
    );
    // Valid → no E1050
    assert!(!fires(r#"{"BucketName":"{{resolve:ssm:/my/param}}"}"#), "valid ssm");
    assert!(!fires(r#"{"BucketName":"{{resolve:ssm:my param with spaces}}"}"#), "ssm name with spaces is tolerated");
    assert!(!fires(r#"{"BucketName":"{{resolve:secretsmanager:}}"}"#), "empty secret-id is valid");
    assert!(
        !fires(r#"{"BucketName":"{{resolve:secretsmanager:s:SecretString:k:stage:id}}"}"#),
        "full non-ARN secretsmanager tail is valid"
    );
}

#[test]
fn dynamic_reference_inside_function_is_not_format_checked() {
    // A malformed dynamic reference that is an argument to Fn::Sub is owned by
    // the enclosing function, so E1050 does not fire on it.
    let input = r#"{"Resources":{"B":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":{"Fn::Sub":"x-{{resolve:ssm:p:notanum}}"}}}}}"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert!(!model.diagnostics.iter().any(|d| d.rule_id == "E1050"), "dynamic ref inside Fn::Sub must not fire E1050");
}

#[test]
fn bare_ref_condition_body_produces_e8001_not_e8007() {
    // A condition body that is a bare Fn::Ref (to a parameter) is not a boolean
    // and is not a condition reference: report E8001, never E8007.
    let input = r#"{
        "Parameters":{"MyParam":{"Type":"String"}},
        "Conditions":{"MyCond":{"Ref":"MyParam"}},
        "Resources":{"B":{"Type":"AWS::S3::Bucket","Condition":"MyCond"}}
    }"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert!(model.diagnostics.iter().any(|d| d.rule_id == "E8001"), "bare Fn::Ref condition body must be E8001");
    assert!(!model.diagnostics.iter().any(|d| d.rule_id == "E8007"), "must not be reported as an undefined condition");
}

#[test]
fn undefined_output_condition_produces_e6005_with_location() {
    // An output referencing an undefined condition is E6005 (resources use
    // E8002), located at the output.
    let input = r#"{
        "Conditions":{"IsProd":{"Fn::Equals":[{"Ref":"AWS::Region"},"us-east-1"]}},
        "Resources":{"R":{"Type":"AWS::S3::Bucket","Condition":"Missing"}},
        "Outputs":{"Out":{"Condition":"AlsoMissing","Value":"x"}}
    }"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let e6005: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E6005").collect();
    let e8002: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E8002").collect();
    assert_eq!(e6005.len(), 1, "output undefined condition -> E6005");
    assert!(e6005[0].message.contains("AlsoMissing"));
    assert_eq!(e8002.len(), 1, "resource undefined condition -> E8002");
    assert!(e8002[0].message.contains("Missing"));
}

#[test]
fn raw_pseudo_parameter_in_output_and_parameter_default_produce_w1054() {
    // W1054 covers pseudo-parameter strings in Outputs and parameter Defaults,
    // not only resource properties, and includes AWS::NoValue.
    let input = r#"{
        "Parameters":{"P":{"Type":"String","Default":"AWS::Region"}},
        "Resources":{"B":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":"AWS::NoValue"}}},
        "Outputs":{"Out":{"Value":"AWS::AccountId"}}
    }"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let w1054: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "W1054").collect();
    assert!(w1054.iter().any(|d| d.message.contains("AWS::Region")), "param Default pseudo-param -> W1054");
    assert!(w1054.iter().any(|d| d.message.contains("AWS::AccountId")), "output pseudo-param -> W1054");
    // AWS::NoValue in a resource property is collected for the engine rule; the
    // parse-time set here covers Outputs and parameter Defaults.
}

#[test]
fn yaml_merge_key_produces_w1100() {
    // The `<<` merge key is not supported by CloudFormation; W1100 must fire
    // (regression: the span capture used to read an already-emptied slot).
    let input = "\
.base: &base
  BucketName: my-bucket
Resources:
  B:
    Type: AWS::S3::Bucket
    Properties:
      <<: *base
";
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert!(model.diagnostics.iter().any(|d| d.rule_id == "W1100"), "YAML merge key must produce W1100");
}

#[test]
fn equals_operand_producing_non_scalar_produces_e8003() {
    // A function whose result is not a scalar (Fn::GetAtt, Fn::Base64,
    // Fn::GetAZs, Fn::ImportValue, boolean functions) is not a valid Fn::Equals
    // operand. Each must be rejected with E8003.
    let cases = [
        r#"{"Conditions":{"C":{"Fn::Equals":[{"Fn::GetAtt":["R","Arn"]},"x"]}},"Resources":{"R":{"Type":"AWS::S3::Bucket"}}}"#,
        r#"{"Conditions":{"C":{"Fn::Equals":[{"Fn::Base64":"abc"},"x"]}},"Resources":{"R":{"Type":"AWS::S3::Bucket"}}}"#,
        r#"{"Conditions":{"C":{"Fn::Equals":[{"Fn::ImportValue":"E"},"x"]}},"Resources":{"R":{"Type":"AWS::S3::Bucket"}}}"#,
        r#"{"Conditions":{"C":{"Fn::Equals":[{"Fn::GetAZs":""},"x"]}},"Resources":{"R":{"Type":"AWS::S3::Bucket"}}}"#,
    ];
    for input in cases {
        let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
        assert!(
            model.diagnostics.iter().any(|d| d.rule_id == "E8003"),
            "expected E8003 for a non-scalar Fn::Equals operand in: {input}"
        );
    }
}

#[test]
fn equals_operand_scalar_producing_function_is_accepted() {
    // The value-producing functions permitted by CloudFormation must not trip
    // E8003 when used as an Fn::Equals operand.
    let input = r#"{
        "Parameters":{"X":{"Type":"String"}},
        "Conditions":{
            "C1":{"Fn::Equals":[{"Ref":"X"},"a"]},
            "C2":{"Fn::Equals":[{"Fn::Select":[0,{"Fn::Split":[",","a,b"]}]},"a"]},
            "C3":{"Fn::Equals":[{"Fn::Sub":"${X}"},"a"]}
        },
        "Resources":{"R":{"Type":"AWS::S3::Bucket","Condition":"C1"}}
    }"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert!(
        !model.diagnostics.iter().any(|d| d.rule_id == "E8003"),
        "E8003 must not fire for scalar-producing Fn::Equals operands"
    );
}

#[test]
fn parser_tautological_condition_produces_w8003() {
    let input = r#"
Conditions:
  AlwaysTrue:
    Fn::Equals: ["same", "same"]
Resources:
  R:
    Type: T
"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert!(model.diagnostics.iter().any(|d| d.rule_id == "W8003" && d.message.contains("AlwaysTrue")));
}

#[test]
fn parser_span_index_populated() {
    let input = "Resources:\n  MyBucket:\n    Type: AWS::S3::Bucket\n    Properties:\n      BucketName: test\n";
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert!(model.span_index.contains_key("Resources/MyBucket"));
    assert!(model.span_index.contains_key("Resources/MyBucket/Properties/BucketName"));
}

#[test]
fn sam_globals_merged_into_function() {
    let model = model_from_fixture("good/transform_serverless_globals.yaml");
    let func = model.resource("myFunction").unwrap();
    // Globals.Function.Runtime should be merged into the function
    assert!(model.sam_globals.contains_key("Function"));
    assert!(model.sam_globals["Function"].contains_key("Runtime"));
    // The function should have the Runtime property from globals
    assert!(func.properties.contains_key("Runtime"));
    let runtime_span = model
        .source_location("Resources/myFunction/Properties/Runtime")
        .expect("inherited Runtime should retain its Globals source span");
    assert_eq!(runtime_span.start_line, 5, "inherited Runtime should point to Globals.Function.Runtime");
}

#[test]
fn sam_implicit_resources_detected() {
    let model = model_from_fixture("good/transform_serverless_globals.yaml");
    // SAM function generates implicit Role
    assert!(model.sam_implicit_resources.contains("myFunctionRole"));
    // Api event generates implicit ServerlessRestApi
    assert!(model.sam_implicit_resources.contains("ServerlessRestApi"));
}

#[test]
fn sam_globals_param_refs_collected() {
    // The globals template doesn't have param refs, but verify the mechanism works
    let model = model_from_fixture("good/transform_serverless_globals.yaml");
    // globals_param_refs should be populated (may be empty if no Refs in Globals)
    assert_eq!(model.globals_param_refs.len(), 0, "expected no param refs in globals for this template");
}

#[test]
fn dynamic_reference_resolves_to_typed_dynamic() {
    let input = r#"{"Resources":{"R":{"Type":"T","Properties":{"V":"{{resolve:ssm:my-param}}"}}}}"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    match model.resolve("R", "Properties.V") {
        Some(ResolvedValue::TypedDynamic { reason: msg, param_type: t }) => {
            assert_eq!(t, "String");
            assert!(msg.contains("dynamic reference"));
            assert!(msg.contains("{{resolve:ssm:my-param}}"), "reason should carry the literal, got {msg:?}");
        }
        other => panic!("Expected TypedDynamic, got {:?}", other),
    }
}

#[test]
fn sub_with_implicit_getatt() {
    let input =
        r#"{"Resources":{"R":{"Type":"T","Properties":{"V":{"Fn::Sub":"arn:${Other.Arn}"}}},"Other":{"Type":"T2"}}}"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    // Should produce a Dynamic (can't fully resolve GetAtt) but should record the edge
    assert!(model.graph.depends_on("R", "Other"));
}

#[test]
fn fn_if_edges_have_condition_context() {
    let input = r#"
Conditions:
  C:
    Fn::Equals: ["a", "a"]
Resources:
  R:
    Type: T
    Properties:
      V:
        Fn::If:
          - C
          - !Ref A
          - !Ref B
  A:
    Type: T
  B:
    Type: T
"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let edges = model.graph.outgoing("R");
    let a_edge = edges.iter().find(|e| e.target == "A").unwrap();
    assert!(a_edge.condition_context.as_ref().unwrap().contains("C"));
    let b_edge = edges.iter().find(|e| e.target == "B").unwrap();
    assert!(b_edge.condition_context.as_ref().unwrap().contains("!C"));
}

#[test]
fn resolve_scenarios_nested_conditionals() {
    let input = r#"
Conditions:
  A:
    Fn::Equals: ["x", "x"]
  B:
    Fn::Equals: ["y", "y"]
Resources:
  R:
    Type: T
    Properties:
      V:
        Fn::If:
          - A
          - Fn::If:
              - B
              - 1
              - 2
          - 3
"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let scenarios = model.resolve_scenarios("R", "Properties.V");
    // Should produce 3 scenarios: A=true,B=true→1; A=true,B=false→2; A=false→3
    assert_eq!(scenarios.len(), 3, "expected 3 scenarios, got {:?}", scenarios);
}

#[test]
fn source_location_returns_span() {
    let input = "Resources:\n  R:\n    Type: T\n    Properties:\n      Name: hello\n";
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let span = model.source_location("Resources/R").expect("expected span for Resources/R");
    assert!(span.start_line > 0, "start_line should be > 0, got {}", span.start_line);
}

#[test]
fn source_location_missing_returns_none() {
    let input = "Resources:\n  R:\n    Type: T\n";
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    assert_eq!(model.source_location("Resources/NonExistent"), None, "nonexistent path should return None");
}

#[test]
fn span_provider_trait_works() {
    let input = "Resources:\n  R:\n    Type: T\n";
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let span = SpanProvider::source_location(&model, "Resources/R");
    assert!(span.is_some(), "SpanProvider should return span for Resources/R");
}

#[test]
fn verify_diagnostic_json_contract() {
    let model = model_from_fixture("good/minimal.yaml");
    let diag = model.to_diagnostic_json();
    let json = serde_json::to_value(&diag).unwrap();

    // Top-level keys must match original contract exactly
    let obj = json.as_object().unwrap();
    let expected_keys: Vec<&str> = vec![
        "template",
        "parameters",
        "conditions",
        "conditionParamRefs",
        "conditionImplications",
        "conditionMutexGroups",
        "conditionExclusions",
        "resourceConditionMap",
        "mappings",
        "resources",
        "outputs",
        "edges",
        "cycles",
        "outputEmptyJoins",
        "samImplicitResources",
        "globalsParamRefs",
        "isCdk",
        "fnIfConditions",
        "findInMapNames",
        "paramsReferencedInDefinitions",
        "hasDynamicFindinmapName",
        "hasParseErrors",
        "parsedRules",
        "resolutionSources",
    ];
    for key in &expected_keys {
        assert!(obj.contains_key(*key), "Missing top-level key: {}", key);
    }
    for key in obj.keys() {
        assert!(expected_keys.contains(&key.as_str()), "Unexpected top-level key: {}", key);
    }

    // Template sub-keys
    let tmpl = obj["template"].as_object().unwrap();
    for key in &["formatVersion", "description", "transforms"] {
        assert!(tmpl.contains_key(*key), "Template missing key: {}", key);
    }

    // Resource sub-keys
    for (_id, res) in obj["resources"].as_object().unwrap() {
        let r = res.as_object().unwrap();
        for key in &[
            "resourceType",
            "condition",
            "dependsOn",
            "deletionPolicy",
            "updateReplacePolicy",
            "properties",
            "outgoingRefs",
            "incomingRefs",
            "findInMapRefs",
            "simpleSubs",
            "redundantSubs",
            "emptyJoins",
            "hardcodedPartitionArns",
            "conditionallyNullProps",
            "conditionRefs",
            "forEachExpansions",
            "unsubstitutedVariables",
            "invalidRefs",
        ] {
            assert!(r.contains_key(*key), "Resource missing key: {}", key);
        }
    }

    // Output sub-keys
    for (_id, out) in obj["outputs"].as_object().unwrap() {
        let o = out.as_object().unwrap();
        for key in &["value", "description", "condition", "exportName", "getattRefs"] {
            assert!(o.contains_key(*key), "Output missing key: {}", key);
        }
    }

    // Edge sub-keys
    for edge in obj["edges"].as_array().unwrap() {
        let e = edge.as_object().unwrap();
        for key in &["source", "sourcePath", "target", "kind"] {
            assert!(e.contains_key(*key), "Edge missing key: {}", key);
        }
    }
}

/// CDK-synthesized bootstrap-version assertion: `Fn::Not` wrapping
/// `Fn::Contains` references the `BootstrapVersion` parameter. The
/// resolver must walk the Rules subtree and emit a Ref edge to that
/// parameter; otherwise downstream "unused parameter" rules misfire.
#[test]
fn rules_section_ref_inside_fn_contains_emits_edge() {
    let input = r#"{
        "Parameters": {
            "BootstrapVersion": {"Type": "String"}
        },
        "Resources": {
            "B": {"Type": "AWS::S3::Bucket"}
        },
        "Rules": {
            "CheckBootstrapVersion": {
                "Assertions": [{
                    "Assert": {
                        "Fn::Not": [{
                            "Fn::Contains": [
                                ["1", "2", "3", "4", "5"],
                                {"Ref": "BootstrapVersion"}
                            ]
                        }]
                    }
                }]
            }
        }
    }"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let edges = model
        .graph
        .outgoing("__rule__CheckBootstrapVersion")
        .into_iter()
        .filter(|e| e.target == "BootstrapVersion")
        .count();
    assert_eq!(edges, 1, "expected a single Ref edge from __rule__CheckBootstrapVersion to BootstrapVersion");
}

#[test]
fn rules_section_ref_in_rule_condition_emits_edge() {
    let input = r#"{
        "Parameters": {
            "Env": {"Type": "String"}
        },
        "Resources": {
            "B": {"Type": "AWS::S3::Bucket"}
        },
        "Rules": {
            "ProdOnly": {
                "RuleCondition": {"Fn::Equals": [{"Ref": "Env"}, "prod"]},
                "Assertions": [{
                    "Assert": {"Fn::Equals": ["a", "a"]}
                }]
            }
        }
    }"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let env_edges = model.graph.outgoing("__rule__ProdOnly").into_iter().filter(|e| e.target == "Env").count();
    assert!(env_edges >= 1, "expected Ref edge from __rule__ProdOnly to Env (RuleCondition)");
}

#[test]
fn rules_section_value_of_emits_parameter_ref_edge() {
    let input = r#"{
        "Parameters": {
            "Subnets": {"Type": "List<AWS::EC2::Subnet::Id>"}
        },
        "Resources": {
            "B": {"Type": "AWS::S3::Bucket"}
        },
        "Rules": {
            "VpcCheck": {
                "Assertions": [{
                    "Assert": {
                        "Fn::EachMemberIn": [
                            {"Fn::ValueOfAll": ["Subnets", "VpcId"]},
                            {"Fn::RefAll": "AWS::EC2::VPC::Id"}
                        ]
                    }
                }]
            }
        }
    }"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let subnet_edges = model.graph.outgoing("__rule__VpcCheck").into_iter().filter(|e| e.target == "Subnets").count();
    assert!(subnet_edges >= 1, "expected Ref edge from __rule__VpcCheck to Subnets (Fn::ValueOfAll first arg)");
}

#[test]
fn rules_section_ref_appears_in_diagnostic_edges_array() {
    let input = r#"{
        "Parameters": {
            "BootstrapVersion": {"Type": "String"}
        },
        "Resources": {
            "B": {"Type": "AWS::S3::Bucket"}
        },
        "Rules": {
            "CheckBootstrapVersion": {
                "Assertions": [{
                    "Assert": {
                        "Fn::Not": [{
                            "Fn::Contains": [
                                ["1", "2", "3", "4", "5"],
                                {"Ref": "BootstrapVersion"}
                            ]
                        }]
                    }
                }]
            }
        }
    }"#;
    let model = SemanticModel::from_bytes(input.as_bytes()).unwrap();
    let json = serde_json::to_value(model.to_diagnostic_json()).unwrap();
    let edges = json["edges"].as_array().expect("edges array");
    let referenced = edges.iter().any(|e| {
        e.get("target").and_then(|t| t.as_str()) == Some("BootstrapVersion")
            && e.get("source").and_then(|s| s.as_str()).is_some_and(|s| s.starts_with("__rule__"))
    });
    assert!(
        referenced,
        "diagnostic edges array must contain a Ref to BootstrapVersion sourced from a Rules pseudo-resource"
    );
}

#[test]
fn rules_equals_getatt_operand_reports_once() {
    // A GetAtt operand of Fn::Equals in a Rules assertion is the parser's
    // not-a-string finding; the Rules-section allowlist walk must not report
    // the same operand a second time.
    let yaml = b"
Rules:
  R1:
    Assertions:
      - Assert: !Equals [!GetAtt B.Arn, x]
Resources:
  B:
    Type: AWS::S3::Bucket
";
    let model = SemanticModel::from_bytes(yaml).unwrap();
    let e8003 = model.diagnostics.iter().filter(|d| d.rule_id == "E8003").count();
    let f8611 = model.diagnostics.iter().filter(|d| d.rule_id == "F8611").count();
    assert_eq!(e8003, 1, "operand type finding fires once: {:?}", model.diagnostics);
    assert_eq!(f8611, 0, "allowlist walk must not double-report the operand: {:?}", model.diagnostics);
}

#[test]
fn e3001_missing_type_produces_diagnostic() {
    let input = br#"{"Resources":{"R":{"Properties":{"K":"V"}}}}"#;
    let model = SemanticModel::from_bytes(input).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "expected one E3001 for missing Type: {:?}", findings);
    assert!(findings[0].message.contains("missing required property 'Type'"), "message: {}", findings[0].message);
}

#[test]
fn e3001_non_object_resource_body_produces_diagnostic() {
    let yaml = b"
Resources:
  R: a string value
  S:
    Type: AWS::S3::Bucket
";
    let model = SemanticModel::from_bytes(yaml).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "expected one E3001 for non-object body: {:?}", findings);
    assert!(findings[0].message.contains("must be an object"), "message: {}", findings[0].message);
}

#[test]
fn e3001_non_string_type_produces_diagnostic() {
    let input = br#"{"Resources":{"R":{"Type":42,"Properties":{"K":"V"}}}}"#;
    let model = SemanticModel::from_bytes(input).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "expected one E3001 for non-string Type: {:?}", findings);
    assert!(findings[0].message.contains("'Type' must be a string"), "message: {}", findings[0].message);
}

#[test]
fn e3001_unknown_attribute_produces_diagnostic() {
    let input = br#"{"Resources":{"R":{"Type":"AWS::S3::Bucket","Bogus":"x","Properties":{}}}}"#;
    let model = SemanticModel::from_bytes(input).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "expected one E3001 for unknown attribute: {:?}", findings);
    assert!(findings[0].message.contains("invalid property 'Bogus'"), "message: {}", findings[0].message);
}

#[test]
fn e3001_condition_must_be_string() {
    let yaml = b"
Resources:
  R:
    Type: AWS::S3::Bucket
    Condition: true
";
    let model = SemanticModel::from_bytes(yaml).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "expected one E3001 for boolean Condition: {:?}", findings);
    assert!(findings[0].message.contains("'Condition' must be a string"), "message: {}", findings[0].message);
}

#[test]
fn e3001_depends_on_must_be_string_or_list() {
    let input = br#"{"Resources":{"R":{"Type":"AWS::S3::Bucket","DependsOn":123}}}"#;
    let model = SemanticModel::from_bytes(input).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "expected one E3001 for numeric DependsOn: {:?}", findings);
    assert!(findings[0].message.contains("must be a string or list of strings"), "message: {}", findings[0].message);
}

#[test]
fn e3001_depends_on_list_elements_must_be_strings() {
    let input = br#"{"Resources":{"R":{"Type":"AWS::S3::Bucket","DependsOn":["A",123]}}}"#;
    let model = SemanticModel::from_bytes(input).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "expected one E3001 for non-string list element: {:?}", findings);
    assert!(findings[0].message.contains("list elements must be strings"), "message: {}", findings[0].message);
}

#[test]
fn e3001_valid_resource_no_findings() {
    let input = br#"{"Resources":{"R":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":"b"},"Condition":"C","DependsOn":["X"],"Metadata":{},"DeletionPolicy":"Retain","UpdateReplacePolicy":"Retain","UpdatePolicy":{},"CreationPolicy":{}}}}"#;
    let model = SemanticModel::from_bytes(input).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert!(findings.is_empty(), "no E3001 for valid resource: {:?}", findings);
}

#[test]
fn e3001_version_attribute_accepted_for_custom_resource() {
    let input = br#"{"Resources":{"R":{"Type":"Custom::Thing","Version":"1.0"}}}"#;
    let model = SemanticModel::from_bytes(input).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert!(findings.is_empty(), "Version is valid for a custom resource: {:?}", findings);
}

#[test]
fn e3001_version_attribute_rejected_for_standard_resource() {
    let input = br#"{"Resources":{"R":{"Type":"AWS::S3::Bucket","Version":"1.0"}}}"#;
    let model = SemanticModel::from_bytes(input).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "Version is not valid for a standard resource: {:?}", findings);
    assert!(findings[0].message.contains("only valid for custom resources"), "message: {}", findings[0].message);
}

#[test]
fn e3001_plain_transform_attribute_is_rejected() {
    let input =
        br#"{"Resources":{"R":{"Type":"AWS::S3::Bucket","Transform":{"Name":"AWS::Include"},"Properties":{}}}}"#;
    let model = SemanticModel::from_bytes(input).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "plain Transform is not a resource attribute: {:?}", findings);
    assert!(findings[0].message.contains("invalid property 'Transform'"), "message: {}", findings[0].message);
}

#[test]
fn e3001_lifecycle_policies_must_be_objects() {
    let yaml = b"
Resources:
  Creation:
    Type: AWS::AutoScaling::AutoScalingGroup
    CreationPolicy: invalid
  Update:
    Type: AWS::AutoScaling::AutoScalingGroup
    UpdatePolicy: 7
";
    let model = SemanticModel::from_bytes(yaml).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 2, "both scalar lifecycle policies must be rejected: {:?}", findings);
    assert!(findings.iter().any(|finding| finding.message.contains("'CreationPolicy' must be an object")));
    assert!(findings.iter().any(|finding| finding.message.contains("'UpdatePolicy' must be an object")));
}

#[test]
fn lifecycle_attribute_status_tracks_effective_presence_and_shape() {
    let yaml = b"
Parameters:
  Env:
    Type: String
  Policy:
    Type: String
Conditions:
  Never: !Equals [always, never]
  Maybe: !Equals [!Ref Env, enabled]
Resources:
  Absent:
    Type: AWS::S3::Bucket
  Object:
    Type: AWS::S3::Bucket
    UpdatePolicy: {}
  Scalar:
    Type: AWS::AutoScaling::AutoScalingGroup
    UpdatePolicy: 7
  Intrinsic:
    Type: AWS::AutoScaling::AutoScalingGroup
    UpdatePolicy: !Ref Policy
  Impossible:
    Type: AWS::S3::Bucket
    UpdatePolicy: !If [Never, {AutoScalingRollingUpdate: {}}, !Ref AWS::NoValue]
  ImpossibleResource:
    Type: AWS::S3::Bucket
    Condition: Never
    UpdatePolicy: {}
  Conditional:
    Type: AWS::S3::Bucket
    UpdatePolicy: !If [Maybe, {AutoScalingRollingUpdate: {}}, !Ref AWS::NoValue]
";
    let model = SemanticModel::from_bytes(yaml).unwrap();

    let absent = model.lifecycle_attribute_status("Absent", "UpdatePolicy");
    assert!(!absent.may_be_present);
    assert_eq!(absent.invalid_value, None);

    let object = model.lifecycle_attribute_status("Object", "UpdatePolicy");
    assert!(object.may_be_present);
    assert_eq!(object.invalid_value, None);

    let scalar = model.lifecycle_attribute_status("Scalar", "UpdatePolicy");
    assert!(scalar.may_be_present);
    assert_eq!(scalar.invalid_value.as_deref(), Some("7"));

    let intrinsic = model.lifecycle_attribute_status("Intrinsic", "UpdatePolicy");
    assert!(intrinsic.may_be_present);
    assert_eq!(intrinsic.invalid_value, None);

    let impossible = model.lifecycle_attribute_status("Impossible", "UpdatePolicy");
    assert!(!impossible.may_be_present);
    assert_eq!(impossible.invalid_value, None);

    let impossible_resource = model.lifecycle_attribute_status("ImpossibleResource", "UpdatePolicy");
    assert!(!impossible_resource.may_be_present);
    assert_eq!(impossible_resource.invalid_value, None);

    let conditional = model.lifecycle_attribute_status("Conditional", "UpdatePolicy");
    assert!(conditional.may_be_present);
    assert_eq!(conditional.invalid_value, None);
}

#[test]
fn e3001_custom_resources_reject_lifecycle_policies() {
    let yaml = b"
Resources:
  R:
    Type: AWS::CloudFormation::CustomResource
    CreationPolicy: {}
    UpdatePolicy: {}
";
    let model = SemanticModel::from_bytes(yaml).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 2, "custom resources cannot use lifecycle policies: {:?}", findings);
    assert!(findings.iter().all(|finding| finding.message.contains("not valid for custom resources")));
}

#[test]
fn e3001_intrinsic_lifecycle_policy_shape_is_deferred() {
    let yaml = b"
Parameters:
  Policy:
    Type: String
Resources:
  R:
    Type: AWS::AutoScaling::AutoScalingGroup
    CreationPolicy: !Ref Policy
";
    let model = SemanticModel::from_bytes(yaml).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert!(findings.is_empty(), "an intrinsic policy shape is not statically known: {:?}", findings);
}

#[test]
fn e3001_sam_connectors_accepted_with_transform() {
    let yaml = b"
Transform: AWS::Serverless-2016-10-31
Resources:
  F:
    Type: AWS::Serverless::Function
    Connectors:
      MyConn:
        Properties:
          Destination:
            Id: F
          Permissions:
            - Read
    Properties:
      Runtime: python3.11
      Handler: index.handler
      CodeUri: ./src
";
    let model = SemanticModel::from_bytes(yaml).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert!(findings.is_empty(), "Connectors is valid under SAM transform: {:?}", findings);
}

#[test]
fn e3001_sam_ignore_globals_accepted_with_transform() {
    let yaml = b"
Transform: AWS::Serverless-2016-10-31
Resources:
  F:
    Type: AWS::Serverless::Function
    IgnoreGlobals: true
    Properties:
      Runtime: python3.11
      Handler: index.handler
      CodeUri: ./src
";
    let model = SemanticModel::from_bytes(yaml).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert!(findings.is_empty(), "IgnoreGlobals is valid under SAM transform: {:?}", findings);
}

#[test]
fn e3001_sam_connectors_rejected_without_transform() {
    let yaml = b"
Resources:
  R:
    Type: AWS::S3::Bucket
    Connectors:
      MyConn:
        Properties:
          Destination:
            Id: R
    Properties:
      BucketName: b
";
    let model = SemanticModel::from_bytes(yaml).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "Connectors without SAM transform is invalid: {:?}", findings);
    assert!(findings[0].message.contains("invalid property 'Connectors'"), "message: {}", findings[0].message);
}

#[test]
fn e3001_multiple_violations_per_resource() {
    let input = br#"{"Resources":{"R":{"Properties":{"K":"V"},"Bogus":"x"}}}"#;
    let model = SemanticModel::from_bytes(input).unwrap();
    let findings: Vec<_> = model.diagnostics.iter().filter(|d| d.rule_id == "E3001").collect();
    assert!(findings.len() >= 2, "expected at least 2 E3001 (missing Type + unknown attribute): {:?}", findings);
}

#[test]
fn resource_macros_are_not_resource_shape_or_logical_id_errors() {
    let yaml = b"
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Fn::Transform:
      Name: AWS::Include
      Parameters:
        Location: s3://example/fragment.yaml
  Fn::Transform:
    Name: AWS::Include
    Parameters:
      Location: s3://example/resources.yaml
";
    let model = SemanticModel::from_bytes(yaml).expect("resource macros parse");
    let resource_shape_findings: Vec<_> =
        model.diagnostics.iter().filter(|finding| finding.rule_id == "E3001").collect();
    assert!(
        resource_shape_findings.is_empty(),
        "valid resource macros must not be rejected: {resource_shape_findings:?}"
    );
}

#[test]
fn fn_transform_list_value_is_a_structural_error() {
    let yaml = b"
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Metadata:
      Included:
        Fn::Transform:
          - Name: AWS::Include
            Parameters:
              Location: s3://example/fragment.yaml
";
    let model = SemanticModel::from_bytes(yaml).expect("malformed transform still produces a semantic model");
    let findings: Vec<_> = model.diagnostics.iter().filter(|finding| finding.rule_id == "F1101").collect();
    assert_eq!(findings.len(), 1, "list-form Fn::Transform must produce one structural finding: {findings:?}");
    assert_eq!(findings[0].message, "Fn::Transform: Fn::Transform value must be an object");
}

#[test]
fn fn_transform_parameters_emit_reference_edges() {
    let yaml = b"
Parameters:
  IncludeBaseUrl:
    Type: String
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Metadata:
      Included:
        Fn::Transform:
          Name: AWS::Include
          Parameters:
            Location: !Sub '${IncludeBaseUrl}/fragment.yaml'
";
    let model = SemanticModel::from_bytes(yaml).expect("valid transform parses");
    let matching_edges: Vec<_> =
        model.graph.outgoing("Bucket").into_iter().filter(|edge| edge.target == "IncludeBaseUrl").collect();
    assert_eq!(matching_edges.len(), 1, "transform parameter must reference IncludeBaseUrl: {matching_edges:?}");
    assert_eq!(matching_edges[0].source_path, "Metadata.Included.Fn::Transform.Parameters.Location");
}

#[test]
fn custom_resource_version_must_be_string_or_integer() {
    let yaml = b"
Resources:
  ProviderBacked:
    Type: Custom::Thing
    Version: false
    Properties:
      ServiceToken: arn:aws:lambda:us-east-1:123456789012:function:provider
";
    let model = SemanticModel::from_bytes(yaml).expect("custom resource parses");
    let findings: Vec<_> = model.diagnostics.iter().filter(|finding| finding.rule_id == "E3001").collect();
    assert_eq!(findings.len(), 1, "invalid Version shape must produce one finding: {findings:?}");
    assert_eq!(findings[0].resource_id.as_deref(), Some("ProviderBacked"));
    assert!(findings[0].message.contains("must be a string or integer"), "unexpected message: {}", findings[0].message);
}

#[test]
fn every_malformed_condition_body_is_reported_at_its_condition_path() {
    let yaml = b"
Parameters:
  P:
    Type: String
Conditions:
  ScalarBody: not-a-condition
  EmptyBody: {}
  MultiBody:
    Fn::Equals: [!Ref P, prod]
    Fn::Not: [!Equals [!Ref P, dev]]
  UnknownFunction:
    Fn::Of: [true]
  BareRef: !Ref P
Resources:
  Topic:
    Type: AWS::SNS::Topic
";
    let model = SemanticModel::from_bytes(yaml).expect("condition template parses");
    let mut paths: Vec<_> = model
        .diagnostics
        .iter()
        .filter(|finding| finding.rule_id == "E8001")
        .filter_map(|finding| finding.property_path.clone())
        .collect();
    paths.sort();
    assert_eq!(
        paths,
        [
            "Conditions/BareRef",
            "Conditions/EmptyBody",
            "Conditions/MultiBody",
            "Conditions/ScalarBody",
            "Conditions/UnknownFunction",
        ]
    );
}

#[test]
fn foreach_generated_condition_body_is_validated_after_expansion() {
    let yaml = b"
Transform: AWS::LanguageExtensions
Conditions:
  Fn::ForEach::Conditions:
  - Identifier
  - [One]
  - Bad${Identifier}: not-a-condition
Resources:
  Topic:
    Type: AWS::SNS::Topic
";
    let model = SemanticModel::from_bytes(yaml).expect("ForEach condition template parses");
    let findings: Vec<_> = model.diagnostics.iter().filter(|finding| finding.rule_id == "E8001").collect();
    assert_eq!(findings.len(), 1, "expanded malformed condition must be reported once: {findings:?}");
    assert_eq!(findings[0].property_path.as_deref(), Some("Conditions/BadOne"));
}

#[test]
fn intrinsic_argument_shape_errors_have_precise_paths() {
    let yaml = b"
Conditions:
  IsProd: !Equals [!Ref AWS::Region, us-east-1]
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Metadata:
      Encoded:
        Fn::Base64: [not, a-string]
    Properties:
      BucketName:
        Fn::If:
        - Fn::Equals: [!Ref AWS::Region, us-east-1]
        - prod-bucket
        - other-bucket
";
    let model = SemanticModel::from_bytes(yaml).expect("intrinsic shape template parses");
    let base64 = model.diagnostics.iter().find(|finding| finding.rule_id == "E1021").expect("Base64 list is rejected");
    assert_eq!(base64.property_path.as_deref(), Some("Metadata.Encoded.Fn::Base64"));
    let condition =
        model.diagnostics.iter().find(|finding| finding.rule_id == "E1028").expect("If expression is rejected");
    assert_eq!(condition.property_path.as_deref(), Some("Properties.BucketName.Fn::If.0"));
}

#[test]
fn sub_literal_escapes_resolve_and_unresolved_variables_record_sub_edges() {
    let yaml = b"
Resources:
  R:
    Type: Test::Resource
    Properties:
      Escaped: !Sub 'literal-${!NotAReference}-end'
      Missing: !Sub 'prefix-${MissingTarget}'
";
    let model = SemanticModel::from_bytes(yaml).expect("Sub template parses");
    match model.resolve("R", "Properties.Escaped") {
        Some(ResolvedValue::Concrete { value }) => {
            assert_eq!(value.as_str(), Some("literal-${NotAReference}-end"));
        }
        other => panic!("literal escape must resolve concretely, got {other:?}"),
    }
    let missing_edge = model
        .graph
        .outgoing("R")
        .into_iter()
        .find(|edge| edge.target == "MissingTarget")
        .expect("unresolved Sub variable records an edge");
    assert!(matches!(missing_edge.kind, template_model::resolver::RefKind::Sub { .. }));
    assert_eq!(missing_edge.source_path, "Properties.Missing");
}

#[test]
fn parameter_allowed_values_preserve_float_and_boolean_scalars() {
    let yaml = b"
Parameters:
  Fraction:
    Type: Number
    Default: 1.5
    AllowedValues: [1.5, 2.5]
  Flag:
    Type: String
    Default: true
    AllowedValues: [true, false]
Resources:
  R:
    Type: Test::Resource
";
    let model = SemanticModel::from_bytes(yaml).expect("parameter template parses");
    assert_eq!(
        model.parameters["Fraction"].allowed_values.as_deref(),
        Some(&["1.5".to_string(), "2.5".to_string()][..])
    );
    assert_eq!(
        model.parameters["Flag"].allowed_values.as_deref(),
        Some(&["true".to_string(), "false".to_string()][..])
    );
}

#[test]
fn lifecycle_policy_scenarios_expands_conditional_branches() {
    let yaml = b"
Parameters:
  Policy:
    Type: String
Conditions:
  Never: !Equals [always, never]
  Maybe: !Equals [!Ref AWS::Region, us-east-1]
Resources:
  ValidConditional:
    Type: AWS::S3::Bucket
    DeletionPolicy: !If [Maybe, Retain, Delete]
  DirectNoValue:
    Type: AWS::S3::Bucket
    DeletionPolicy: !Ref AWS::NoValue
  JoinPolicy:
    Type: AWS::S3::Bucket
    DeletionPolicy: !Join ['', [Re, tain]]
  StackIdPolicy:
    Type: AWS::S3::Bucket
    DeletionPolicy: !Ref AWS::StackId
  ImpossibleBranch:
    Type: AWS::S3::Bucket
    DeletionPolicy: !If [Never, InvalidPolicy, !Ref AWS::NoValue]
  ImpossibleResource:
    Type: AWS::S3::Bucket
    Condition: Never
    DeletionPolicy: NotValid
  BothBranchesLiteral:
    Type: AWS::S3::Bucket
    DeletionPolicy: !If [Maybe, WrongOne, AlsoWrong]
  CorrelatedResource:
    Type: AWS::S3::Bucket
    Condition: Maybe
    DeletionPolicy: !If [Maybe, Retain, InvalidPolicy]
  DynamicObject:
    Type: AWS::S3::Bucket
    DeletionPolicy:
      Value: !Ref Policy
";
    let model = SemanticModel::from_bytes(yaml).unwrap();

    let valid = model.lifecycle_policy_scenarios("ValidConditional", "DeletionPolicy");
    assert_eq!(valid.len(), 2, "both branches are reachable: {:?}", valid);
    let values: Vec<&str> = valid.iter().filter_map(|(v, _)| v.as_str()).collect();
    assert!(values.contains(&"Retain"));
    assert!(values.contains(&"Delete"));

    let novalue = model.lifecycle_policy_scenarios("DirectNoValue", "DeletionPolicy");
    assert_eq!(novalue.len(), 1, "direct NoValue remains an invalid null value: {:?}", novalue);
    assert!(novalue[0].0.is_null());

    let join = model.lifecycle_policy_scenarios("JoinPolicy", "DeletionPolicy");
    assert_eq!(join.len(), 1, "Join resolves before lifecycle value validation: {join:?}");
    assert_eq!(join[0].0.as_str(), Some("Retain"));

    let stack_id = model.lifecycle_policy_scenarios("StackIdPolicy", "DeletionPolicy");
    assert_eq!(stack_id.len(), 1, "StackId has a deterministic pseudo-parameter value: {stack_id:?}");
    assert!(
        stack_id[0].0.as_str().is_some_and(|value| value.starts_with("arn:") && value.contains(":stack/")),
        "StackId must reach final-value validation as a concrete ARN: {stack_id:?}"
    );

    let impossible = model.lifecycle_policy_scenarios("ImpossibleBranch", "DeletionPolicy");
    assert_eq!(impossible.len(), 1, "the reachable NoValue branch remains invalid: {:?}", impossible);
    assert!(impossible[0].0.is_null());

    let unreachable = model.lifecycle_policy_scenarios("ImpossibleResource", "DeletionPolicy");
    assert!(unreachable.is_empty(), "unreachable resource: {:?}", unreachable);

    let both_invalid = model.lifecycle_policy_scenarios("BothBranchesLiteral", "DeletionPolicy");
    assert_eq!(both_invalid.len(), 2, "both branches are reachable: {:?}", both_invalid);

    let correlated = model.lifecycle_policy_scenarios("CorrelatedResource", "DeletionPolicy");
    assert_eq!(correlated.len(), 1, "resource condition excludes the false branch: {:?}", correlated);
    assert_eq!(correlated[0].0.as_str(), Some("Retain"));

    let dynamic_object = model.lifecycle_policy_scenarios("DynamicObject", "DeletionPolicy");
    assert_eq!(dynamic_object.len(), 1, "an authored object remains a concrete invalid shape");
    assert!(dynamic_object[0].0.is_object());
}

#[test]
fn lifecycle_policy_scenarios_defers_on_dynamic_ref() {
    let yaml = b"
Parameters:
  Policy:
    Type: String
Resources:
  RefPolicy:
    Type: AWS::S3::Bucket
    DeletionPolicy: !Ref Policy
";
    let model = SemanticModel::from_bytes(yaml).unwrap();
    let scenarios = model.lifecycle_policy_scenarios("RefPolicy", "DeletionPolicy");
    assert!(scenarios.is_empty(), "dynamic ref should defer (no scenarios): {:?}", scenarios);
}

#[test]
fn lifecycle_attribute_status_respects_conditions_for_all_attributes() {
    let yaml = b"
Parameters:
  Policy:
    Type: String
Conditions:
  Never: !Equals [always, never]
  Maybe: !Equals [!Ref AWS::Region, us-east-1]
Resources:
  DirectNoValue:
    Type: AWS::S3::Bucket
    CreationPolicy: !Ref AWS::NoValue
  ImpossibleBranch:
    Type: AWS::S3::Bucket
    CreationPolicy: !If [Never, {ResourceSignal: {Count: 1}}, !Ref AWS::NoValue]
  ImpossibleResource:
    Type: AWS::S3::Bucket
    Condition: Never
    CreationPolicy:
      ResourceSignal: {Count: 1}
  MaybePresent:
    Type: AWS::S3::Bucket
    CreationPolicy: !If [Maybe, {ResourceSignal: {Count: 1}}, !Ref AWS::NoValue]
  DeletionNoValue:
    Type: AWS::S3::Bucket
    DeletionPolicy: !Ref AWS::NoValue
  DeletionAlwaysAbsent:
    Type: AWS::S3::Bucket
    DeletionPolicy: !If [Maybe, !Ref AWS::NoValue, !Ref AWS::NoValue]
  DeletionDynamic:
    Type: AWS::S3::Bucket
    DeletionPolicy: !Ref Policy
  UpdateAlwaysAbsent:
    Type: AWS::AutoScaling::AutoScalingGroup
    UpdatePolicy: !If [Maybe, !Ref AWS::NoValue, !Ref AWS::NoValue]
  UpdateMaybePresent:
    Type: AWS::AutoScaling::AutoScalingGroup
    UpdatePolicy: !If [Maybe, {AutoScalingRollingUpdate: {}}, !Ref AWS::NoValue]
";
    let model = SemanticModel::from_bytes(yaml).unwrap();

    let direct = model.lifecycle_attribute_status("DirectNoValue", "CreationPolicy");
    assert!(direct.may_be_present, "illegal NoValue remains an authored CreationPolicy");

    let impossible = model.lifecycle_attribute_status("ImpossibleBranch", "CreationPolicy");
    assert!(impossible.may_be_present, "a root CreationPolicy Fn::If remains authored");

    let resource = model.lifecycle_attribute_status("ImpossibleResource", "CreationPolicy");
    assert!(!resource.may_be_present, "impossible resource means absent");

    let maybe = model.lifecycle_attribute_status("MaybePresent", "CreationPolicy");
    assert!(maybe.may_be_present, "reachable branch is present");

    let deletion_novalue = model.lifecycle_attribute_status("DeletionNoValue", "DeletionPolicy");
    assert!(deletion_novalue.may_be_present, "illegal NoValue is not policy omission");

    let deletion_always_absent = model.lifecycle_attribute_status("DeletionAlwaysAbsent", "DeletionPolicy");
    assert!(deletion_always_absent.may_be_present, "NoValue branches are not policy omission");

    let deletion_dynamic = model.lifecycle_attribute_status("DeletionDynamic", "DeletionPolicy");
    assert!(deletion_dynamic.may_be_present);

    let update_absent = model.lifecycle_attribute_status("UpdateAlwaysAbsent", "UpdatePolicy");
    assert!(!update_absent.may_be_present, "UpdatePolicy still supports conditional NoValue omission");

    let update_maybe = model.lifecycle_attribute_status("UpdateMaybePresent", "UpdatePolicy");
    assert!(update_maybe.may_be_present, "a reachable UpdatePolicy object remains present");
}

#[test]
fn lifecycle_policy_intrinsics_and_creation_policy_if_do_not_require_a_transform() {
    let yaml = b"
Parameters:
  Policy:
    Type: String
    AllowedValues: [Retain, Delete]
Conditions:
  Never: !Equals [always, never]
  Maybe: !Equals [!Ref Policy, Retain]
Resources:
  CreationConditional:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy: !If
      - Maybe
      - ResourceSignal: {Count: 1}
      - ResourceSignal: {Count: 2}
  DeletionConditional:
    Type: AWS::CloudFormation::WaitConditionHandle
    DeletionPolicy: !If [Maybe, Retain, Delete]
  UpdateRef:
    Type: AWS::CloudFormation::WaitConditionHandle
    UpdateReplacePolicy: !Ref Policy
  Unreachable:
    Type: AWS::CloudFormation::WaitConditionHandle
    Condition: Never
    CreationPolicy: !Ref Policy
    DeletionPolicy: !Ref Policy
";
    let model = SemanticModel::from_bytes(yaml).expect("lifecycle placement template parses");
    let findings: Vec<_> = model.diagnostics.iter().filter(|finding| finding.rule_id == "F1101").collect();
    assert!(findings.is_empty(), "valid lifecycle intrinsics must not produce placement findings: {findings:?}");
}

#[test]
fn lifecycle_policy_intrinsics_have_no_function_or_ref_placement_allowlist() {
    let yaml = b"
Parameters:
  Policy:
    Type: String
    AllowedValues: [Retain, Delete]
Mappings:
  Policies:
    us-east-1:
      Deletion: Retain
Conditions:
  Never: !Equals [always, never]
  Maybe: !Equals [!Ref Policy, Retain]
Resources:
  Target:
    Type: AWS::CloudFormation::WaitConditionHandle
  ValidConditional:
    Type: AWS::CloudFormation::WaitConditionHandle
    DeletionPolicy: !If
      - Maybe
      - !FindInMap [Policies, !Ref AWS::Region, Deletion]
      - !Ref Policy
  ValidSub:
    Type: AWS::CloudFormation::WaitConditionHandle
    DeletionPolicy: !Sub
      - '${PolicyName}'
      - PolicyName: Retain
  ValidSelect:
    Type: AWS::CloudFormation::WaitConditionHandle
    UpdateReplacePolicy: !Select [1, [Delete, Retain]]
  ValidJoin:
    Type: AWS::CloudFormation::WaitConditionHandle
    DeletionPolicy: !Join ['', [Re, tain]]
  CreationConditional:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy: !If [Maybe, {ResourceSignal: {Count: 1}}, {ResourceSignal: {Count: 2}}]
  NoValueRef:
    Type: AWS::CloudFormation::WaitConditionHandle
    UpdateReplacePolicy: !Ref AWS::NoValue
  StackIdRef:
    Type: AWS::CloudFormation::WaitConditionHandle
    DeletionPolicy: !Ref AWS::StackId
  ResourceRef:
    Type: AWS::CloudFormation::WaitConditionHandle
    DeletionPolicy: !Ref Target
  UnreachableJoin:
    Type: AWS::CloudFormation::WaitConditionHandle
    Condition: Never
    DeletionPolicy: !Join ['', [Re, tain]]
";
    let model = SemanticModel::from_bytes(yaml).expect("lifecycle intrinsic template parses");
    let findings: Vec<_> = model.diagnostics.iter().filter(|finding| finding.rule_id == "F1101").collect();
    assert!(findings.is_empty(), "lifecycle policy functions and Ref targets are not placement errors: {findings:?}");
}

#[test]
fn creation_policy_root_intrinsics_match_service_shape_contract() {
    let yaml = b"
Parameters:
  CreationValue:
    Type: String
    Default: not-an-object
  Toggle:
    Type: String
    AllowedValues: [enabled, disabled]
Mappings:
  CreationValues:
    Primary:
      Policy: not-an-object
Conditions:
  Maybe: !Equals [!Ref Toggle, enabled]
  Never: !Equals [always, never]
Resources:
  ValidIf:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy: !If
      - Maybe
      - ResourceSignal: {Count: 1}
      - ResourceSignal: {Count: 2}
  NestedIf:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy: !If
      - Maybe
      - !If [Never, invalid, {ResourceSignal: {Count: 1}}]
      - ResourceSignal: {Count: 2}
  ImpossibleScalarBranch:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy: !If [Never, invalid, {ResourceSignal: {Count: 1}}]
  CorrelatedScalarBranch:
    Type: AWS::CloudFormation::WaitCondition
    Condition: Maybe
    CreationPolicy: !If [Maybe, {ResourceSignal: {Count: 1}}, invalid]
  ReachableScalarBranch:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy: !If [Maybe, {ResourceSignal: {Count: 1}}, invalid]
  RootRef:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy: !Ref CreationValue
  RootFindInMap:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy: !FindInMap [CreationValues, Primary, Policy]
  RootSelect:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy: !Select
      - 0
      - - ResourceSignal: {Count: 1}
        - ResourceSignal: {Count: 2}
  RootSub:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy: !Sub
      - '${Value}'
      - Value: not-an-object
  NestedFunctions:
    Type: AWS::CloudFormation::WaitCondition
    CreationPolicy:
      ResourceSignal:
        Count: !Select [0, [1, 2]]
        Timeout: !Sub
          - 'PT${Minutes}M'
          - Minutes: 10
";
    let model = SemanticModel::from_bytes(yaml).expect("CreationPolicy matrix parses");
    let findings: Vec<_> = model.diagnostics.iter().filter(|finding| finding.rule_id == "F1101").collect();
    assert_eq!(findings.len(), 5, "four rejected roots and one reachable scalar branch: {findings:?}");

    for resource_id in ["RootRef", "RootFindInMap", "RootSelect", "RootSub"] {
        assert!(
            findings.iter().any(|finding| {
                finding.resource_id.as_deref() == Some(resource_id)
                    && finding.message.contains("not supported as a top-level CreationPolicy")
            }),
            "missing root CreationPolicy finding for {resource_id}: {findings:?}"
        );
    }
    assert!(
        findings.iter().any(|finding| {
            finding.resource_id.as_deref() == Some("ReachableScalarBranch")
                && finding.message.contains("Fn::If branch in CreationPolicy must be an object")
        }),
        "missing reachable branch-shape finding: {findings:?}"
    );
    for resource_id in ["ValidIf", "NestedIf", "ImpossibleScalarBranch", "CorrelatedScalarBranch", "NestedFunctions"] {
        assert!(
            !findings.iter().any(|finding| finding.resource_id.as_deref() == Some(resource_id)),
            "unexpected CreationPolicy finding for {resource_id}: {findings:?}"
        );
    }
}