awsim-cloudformation 0.5.0

AWS CloudFormation emulator for AWSim
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
/// CloudFormation template parsing and intrinsic function resolution.
///
/// Supports:
/// - JSON and YAML template formats
/// - Intrinsic functions: Ref, Fn::GetAtt, Fn::Sub, Fn::Join, Fn::Select, Fn::If
/// - Conditions
/// - DependsOn ordering
use serde_json::{Map, Value};
use std::collections::HashMap;

use crate::error::invalid_template;
use awsim_core::AwsError;

/// A parsed and validated CloudFormation template.
#[derive(Debug, Clone)]
pub struct ParsedTemplate {
    pub description: Option<String>,
    /// Resolved resource definitions, in dependency order.
    pub resources: Vec<ResourceDef>,
    /// Condition name -> resolved bool
    pub conditions: HashMap<String, bool>,
    /// Parameter definitions from the template
    pub parameters: Vec<ParameterDef>,
}

#[derive(Debug, Clone)]
pub struct ResourceDef {
    pub logical_id: String,
    pub resource_type: String,
    pub properties: Value,
    pub depends_on: Vec<String>,
    pub condition: Option<String>,
    /// AWS lifecycle attributes parsed verbatim and surfaced
    /// downstream. `DeletionPolicy` drives DeleteStack behavior
    /// (`Retain` skips the resource so it survives the stack);
    /// `CreationPolicy` and `UpdatePolicy` are stored for future
    /// rolling-update support but not yet enforced in the simulator.
    pub deletion_policy: Option<String>,
    #[allow(dead_code)]
    pub creation_policy: Option<Value>,
    #[allow(dead_code)]
    pub update_policy: Option<Value>,
}

#[derive(Debug, Clone)]
pub struct ParameterDef {
    pub name: String,
    pub param_type: String,
    pub default: Option<String>,
    pub description: Option<String>,
    /// Numeric and string parameter bounds. CFN documents both
    /// `MinValue`/`MaxValue` (for `Number` parameters) and
    /// `MinLength`/`MaxLength` (for `String` parameters); we keep
    /// each as `f64`/`usize` to mirror the spec.
    pub min_length: Option<usize>,
    pub max_length: Option<usize>,
    pub min_value: Option<f64>,
    pub max_value: Option<f64>,
    /// Allowed enum values. When non-empty, every supplied value
    /// must appear in this set (matched as a string).
    pub allowed_values: Vec<String>,
    /// Anchored regex the value must match. CFN evaluates this with
    /// the same flavour as ECMAScript regex; we delegate to the
    /// `regex` crate which is close enough for the simulator.
    pub allowed_pattern: Option<String>,
    /// Optional human-readable description surfaced in
    /// `ValidationError.message` on a constraint violation.
    pub constraint_description: Option<String>,
    /// When true, the parameter value is treated as a secret: the
    /// stack-event projection masks it as `****` rather than echoing
    /// it back, matching AWS's NoEcho semantics.
    pub no_echo: bool,
}

/// Parse a template body (JSON or YAML) and return the raw Value.
/// Validate the `<vendor>::<service>::<resource>` shape that CFN uses
/// for all resource types. Real CFN looks the type up against a
/// registry; we accept any well-formed name under the documented
/// vendor prefixes (`AWS`, `Custom`, `Alexa`).
fn is_valid_resource_type(t: &str) -> bool {
    // Custom resources are `Custom::<Name>` (single double-colon).
    if let Some(rest) = t.strip_prefix("Custom::") {
        return !rest.is_empty()
            && rest
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'));
    }
    let parts: Vec<&str> = t.split("::").collect();
    if parts.len() != 3 {
        return false;
    }
    if !matches!(parts[0], "AWS" | "Alexa") {
        return false;
    }
    parts[1..]
        .iter()
        .all(|seg| !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric()))
}

pub fn parse_template_body(body: &str) -> Result<Value, AwsError> {
    let trimmed = body.trim();

    if trimmed.starts_with('{') {
        serde_json::from_str(trimmed)
            .map_err(|e| invalid_template(format!("Invalid JSON template: {e}")))
    } else {
        use saphyr::{LoadableYamlNode, Yaml};
        let docs = Yaml::load_from_str(trimmed)
            .map_err(|e| invalid_template(format!("Invalid YAML template: {e}")))?;
        let doc = docs
            .into_iter()
            .next()
            .ok_or_else(|| invalid_template("Empty YAML template"))?;
        Ok(yaml_to_json(&doc))
    }
}

fn yaml_to_json(yaml: &saphyr::Yaml) -> Value {
    use saphyr::Yaml;
    match yaml {
        Yaml::Value(scalar) => scalar_to_json(scalar),
        Yaml::Sequence(seq) => Value::Array(seq.iter().map(yaml_to_json).collect()),
        Yaml::Mapping(map) => {
            let mut obj = Map::new();
            for (k, v) in map {
                let key = match k {
                    Yaml::Value(saphyr::Scalar::String(s)) => s.to_string(),
                    Yaml::Value(saphyr::Scalar::Integer(i)) => i.to_string(),
                    Yaml::Value(saphyr::Scalar::Boolean(b)) => b.to_string(),
                    _ => continue,
                };
                obj.insert(key, yaml_to_json(v));
            }
            Value::Object(obj)
        }
        Yaml::Tagged(_, inner) => yaml_to_json(inner),
        Yaml::Alias(_) | Yaml::BadValue | Yaml::Representation(_, _, _) => Value::Null,
    }
}

fn scalar_to_json(scalar: &saphyr::Scalar) -> Value {
    use saphyr::Scalar;
    match scalar {
        Scalar::Null => Value::Null,
        Scalar::Boolean(b) => Value::Bool(*b),
        Scalar::Integer(i) => Value::Number((*i).into()),
        Scalar::FloatingPoint(f) => serde_json::Number::from_f64(f.into_inner())
            .map(Value::Number)
            .unwrap_or(Value::Null),
        Scalar::String(s) => Value::String(s.to_string()),
    }
}

/// Validate and parse a CloudFormation template.
pub fn validate_and_parse(
    body: &str,
    supplied_params: &HashMap<String, String>,
) -> Result<ParsedTemplate, AwsError> {
    let template = parse_template_body(body)?;

    let description = template
        .get("Description")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    // Parse parameters
    let parameter_defs = parse_parameter_defs(&template);

    // Build effective parameter map: defaults + supplied values.
    // Each value runs through the per-parameter constraint checks so
    // a violation surfaces at CreateStack/UpdateStack time instead of
    // bleeding into resource provisioning.
    let mut params: HashMap<String, Value> = HashMap::new();
    for pd in &parameter_defs {
        let effective: Option<String> = supplied_params
            .get(&pd.name)
            .cloned()
            .or_else(|| pd.default.clone());
        if let Some(v) = effective {
            validate_parameter_value(pd, &v)?;
            params.insert(pd.name.clone(), Value::String(v));
        }
    }

    // Parse and evaluate conditions
    let conditions = evaluate_conditions(&template, &params);

    // Parse resources
    let resources_raw = template
        .get("Resources")
        .and_then(|v| v.as_object())
        .ok_or_else(|| invalid_template("Template must contain a 'Resources' section"))?;

    if resources_raw.is_empty() {
        return Err(invalid_template(
            "Template must contain at least one resource",
        ));
    }

    let mut resource_defs: Vec<ResourceDef> = Vec::new();
    for (logical_id, resource) in resources_raw {
        let resource_type = resource
            .get("Type")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                invalid_template(format!("Resource '{logical_id}' must have a 'Type' field"))
            })?
            .to_string();

        // CFN resource type names follow `<vendor>::<service>::<resource>`
        // where vendor is `AWS`, `Custom`, or `Alexa`. Anything outside
        // that shape is a malformed template and AWS surfaces it as
        // `ValidationError` (with the offending logical id). Catching it
        // here is cheap and avoids letting nonsense flow through to the
        // resource-provisioning event sink.
        if !is_valid_resource_type(&resource_type) {
            return Err(invalid_template(format!(
                "Resource '{logical_id}' has unknown resource type '{resource_type}'. \
                 Expected `AWS::<Service>::<Resource>`, `Custom::<Name>`, or `Alexa::<Service>::<Resource>`."
            )));
        }

        let properties = resource
            .get("Properties")
            .cloned()
            .unwrap_or(Value::Object(Map::new()));

        let depends_on: Vec<String> = match resource.get("DependsOn") {
            Some(Value::String(s)) => vec![s.clone()],
            Some(Value::Array(arr)) => arr
                .iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect(),
            _ => Vec::new(),
        };

        let condition = resource
            .get("Condition")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let deletion_policy = resource
            .get("DeletionPolicy")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let creation_policy = resource
            .get("CreationPolicy")
            .filter(|v| !v.is_null())
            .cloned();
        let update_policy = resource
            .get("UpdatePolicy")
            .filter(|v| !v.is_null())
            .cloned();

        if let Some(ref dp) = deletion_policy
            && !matches!(
                dp.as_str(),
                "Delete" | "Retain" | "Snapshot" | "RetainExceptOnCreate"
            )
        {
            return Err(invalid_template(format!(
                "Resource '{logical_id}' DeletionPolicy `{dp}` is not Delete, Retain, Snapshot, or RetainExceptOnCreate."
            )));
        }

        resource_defs.push(ResourceDef {
            logical_id: logical_id.clone(),
            resource_type,
            properties,
            depends_on,
            condition,
            deletion_policy,
            creation_policy,
            update_policy,
        });
    }

    // Topological sort by DependsOn
    let sorted = topological_sort(resource_defs)
        .map_err(|e| invalid_template(format!("Dependency error: {e}")))?;

    Ok(ParsedTemplate {
        description,
        resources: sorted,
        conditions,
        parameters: parameter_defs,
    })
}

fn parse_parameter_defs(template: &Value) -> Vec<ParameterDef> {
    let mut defs = Vec::new();

    if let Some(params_obj) = template.get("Parameters").and_then(|v| v.as_object()) {
        for (name, param) in params_obj {
            let param_type = param
                .get("Type")
                .and_then(|v| v.as_str())
                .unwrap_or("String")
                .to_string();

            let default = param.get("Default").and_then(|v| match v {
                Value::String(s) => Some(s.clone()),
                Value::Number(n) => Some(n.to_string()),
                Value::Bool(b) => Some(b.to_string()),
                _ => None,
            });

            let description = param
                .get("Description")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());

            let allowed_values: Vec<String> = param
                .get("AllowedValues")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| match v {
                            Value::String(s) => Some(s.clone()),
                            Value::Number(n) => Some(n.to_string()),
                            Value::Bool(b) => Some(b.to_string()),
                            _ => None,
                        })
                        .collect()
                })
                .unwrap_or_default();

            defs.push(ParameterDef {
                name: name.clone(),
                param_type,
                default,
                description,
                min_length: param
                    .get("MinLength")
                    .and_then(|v| v.as_u64())
                    .map(|n| n as usize),
                max_length: param
                    .get("MaxLength")
                    .and_then(|v| v.as_u64())
                    .map(|n| n as usize),
                min_value: param.get("MinValue").and_then(|v| v.as_f64()),
                max_value: param.get("MaxValue").and_then(|v| v.as_f64()),
                allowed_values,
                allowed_pattern: param
                    .get("AllowedPattern")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string()),
                constraint_description: param
                    .get("ConstraintDescription")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string()),
                no_echo: param
                    .get("NoEcho")
                    .and_then(|v| match v {
                        Value::Bool(b) => Some(*b),
                        Value::String(s) => Some(s.eq_ignore_ascii_case("true")),
                        _ => None,
                    })
                    .unwrap_or(false),
            });
        }
    }

    defs
}

/// Validate a supplied parameter value against the constraints
/// declared on `def`. Mirrors AWS's documented per-attribute checks:
/// `AllowedValues` membership, `AllowedPattern` regex, length bounds
/// for `String`/`CommaDelimitedList`, and numeric bounds for
/// `Number`/`List<Number>`. Returns a `ValidationError` carrying
/// `ConstraintDescription` when present, falling back to a generic
/// message otherwise.
pub fn validate_parameter_value(def: &ParameterDef, value: &str) -> Result<(), AwsError> {
    let fail = |default_msg: String| -> AwsError {
        let msg = def.constraint_description.clone().unwrap_or(default_msg);
        AwsError::bad_request("ValidationError", msg)
    };

    if !def.allowed_values.is_empty() && !def.allowed_values.iter().any(|av| av == value) {
        return Err(fail(format!(
            "Parameter '{}' must be one of [{}]; got `{value}`.",
            def.name,
            def.allowed_values.join(", "),
        )));
    }

    if let Some(min) = def.min_length
        && value.len() < min
    {
        return Err(fail(format!(
            "Parameter '{}' must be at least {min} characters long.",
            def.name,
        )));
    }
    if let Some(max) = def.max_length
        && value.len() > max
    {
        return Err(fail(format!(
            "Parameter '{}' must be at most {max} characters long.",
            def.name,
        )));
    }

    let numeric_type = matches!(def.param_type.as_str(), "Number" | "List<Number>");
    if numeric_type && (def.min_value.is_some() || def.max_value.is_some()) {
        let n: f64 = value.parse().map_err(|_| {
            fail(format!(
                "Parameter '{}' must be a number; got `{value}`.",
                def.name,
            ))
        })?;
        if let Some(min) = def.min_value
            && n < min
        {
            return Err(fail(format!(
                "Parameter '{}' must be >= {min}; got {n}.",
                def.name,
            )));
        }
        if let Some(max) = def.max_value
            && n > max
        {
            return Err(fail(format!(
                "Parameter '{}' must be <= {max}; got {n}.",
                def.name,
            )));
        }
    }

    if let Some(ref pat) = def.allowed_pattern {
        let anchored = if pat.starts_with('^') && pat.ends_with('$') {
            pat.clone()
        } else {
            format!("^(?:{pat})$")
        };
        let re = regex::Regex::new(&anchored).map_err(|e| {
            AwsError::bad_request(
                "ValidationError",
                format!("Parameter '{}' has invalid AllowedPattern: {e}", def.name,),
            )
        })?;
        if !re.is_match(value) {
            return Err(fail(format!(
                "Parameter '{}' value `{value}` does not match pattern `{pat}`.",
                def.name,
            )));
        }
    }

    Ok(())
}

fn evaluate_conditions(template: &Value, params: &HashMap<String, Value>) -> HashMap<String, bool> {
    let mut resolved: HashMap<String, bool> = HashMap::new();

    if let Some(conditions_obj) = template.get("Conditions").and_then(|v| v.as_object()) {
        for (name, condition) in conditions_obj {
            let result = eval_condition_value(condition, params, &resolved);
            resolved.insert(name.clone(), result);
        }
    }

    resolved
}

fn eval_condition_value(
    val: &Value,
    params: &HashMap<String, Value>,
    conditions: &HashMap<String, bool>,
) -> bool {
    match val {
        Value::Object(map) => {
            if let Some(eq_args) = map.get("Fn::Equals") {
                if let Value::Array(arr) = eq_args
                    && arr.len() == 2
                {
                    let a = resolve_value(&arr[0], params, conditions, &HashMap::new());
                    let b = resolve_value(&arr[1], params, conditions, &HashMap::new());
                    return a == b;
                }
                return false;
            }
            if let Some(not_arg) = map.get("Fn::Not") {
                if let Value::Array(arr) = not_arg
                    && let Some(first) = arr.first()
                {
                    return !eval_condition_value(first, params, conditions);
                }
                return false;
            }
            if let Some(and_args) = map.get("Fn::And") {
                if let Value::Array(arr) = and_args {
                    return arr
                        .iter()
                        .all(|a| eval_condition_value(a, params, conditions));
                }
                return false;
            }
            if let Some(or_args) = map.get("Fn::Or") {
                if let Value::Array(arr) = or_args {
                    return arr
                        .iter()
                        .any(|a| eval_condition_value(a, params, conditions));
                }
                return false;
            }
            false
        }
        Value::Bool(b) => *b,
        _ => false,
    }
}

/// Resolve intrinsic functions in a Value against parameters and pseudo-parameters.
pub fn resolve_value(
    val: &Value,
    params: &HashMap<String, Value>,
    conditions: &HashMap<String, bool>,
    resources: &HashMap<String, Value>,
) -> Value {
    match val {
        Value::Object(map) => {
            // Check for intrinsic function keys
            if let Some(ref_val) = map.get("Ref")
                && let Some(s) = ref_val.as_str()
            {
                return resolve_ref(s, params, resources);
            }
            if let Some(get_att) = map.get("Fn::GetAtt") {
                return resolve_get_att(get_att, resources);
            }
            if let Some(sub_val) = map.get("Fn::Sub") {
                return resolve_sub(sub_val, params, conditions, resources);
            }
            if let Some(join_val) = map.get("Fn::Join") {
                return resolve_join(join_val, params, conditions, resources);
            }
            if let Some(select_val) = map.get("Fn::Select") {
                return resolve_select(select_val, params, conditions, resources);
            }
            if let Some(if_val) = map.get("Fn::If") {
                return resolve_if(if_val, params, conditions, resources);
            }
            if let Some(b64_val) = map.get("Fn::Base64") {
                return resolve_base64(b64_val, params, conditions, resources);
            }
            if let Some(azs_val) = map.get("Fn::GetAZs") {
                return resolve_get_azs(azs_val, params, conditions, resources);
            }

            // Regular object: resolve all values recursively.
            let resolved_map: Map<String, Value> = map
                .iter()
                .map(|(k, v)| (k.clone(), resolve_value(v, params, conditions, resources)))
                .collect();
            Value::Object(resolved_map)
        }
        Value::Array(arr) => Value::Array(
            arr.iter()
                .map(|v| resolve_value(v, params, conditions, resources))
                .collect(),
        ),
        // Primitives pass through as-is
        _ => val.clone(),
    }
}

fn resolve_ref(
    name: &str,
    params: &HashMap<String, Value>,
    resources: &HashMap<String, Value>,
) -> Value {
    // Check pseudo-parameters first
    match name {
        "AWS::AccountId" => return Value::String("000000000000".to_string()),
        "AWS::Region" => return Value::String("us-east-1".to_string()),
        "AWS::StackId" => {
            return Value::String(
                "arn:aws:cloudformation:us-east-1:000000000000:stack/stack/unknown".to_string(),
            );
        }
        "AWS::StackName" => return Value::String("unknown-stack".to_string()),
        "AWS::NoValue" => return Value::Null,
        _ => {}
    }

    // Check parameters
    if let Some(v) = params.get(name) {
        return v.clone();
    }

    // Check resource physical IDs
    if let Some(res) = resources.get(name) {
        if let Some(phys_id) = res.get("PhysicalResourceId") {
            return phys_id.clone();
        }
        return res.clone();
    }

    // Unknown ref — return as-is string
    Value::String(name.to_string())
}

fn resolve_get_att(val: &Value, resources: &HashMap<String, Value>) -> Value {
    // Fn::GetAtt: [LogicalId, AttributeName] or "LogicalId.AttributeName"
    match val {
        Value::Array(arr) if arr.len() == 2 => {
            let logical_id = arr[0].as_str().unwrap_or("");
            let attr = arr[1].as_str().unwrap_or("");
            if let Some(res) = resources.get(logical_id)
                && let Some(v) = res.get(attr)
            {
                return v.clone();
            }
            Value::String(format!("{logical_id}.{attr}"))
        }
        Value::String(s) => {
            if let Some((logical_id, attr)) = s.split_once('.')
                && let Some(res) = resources.get(logical_id)
                && let Some(v) = res.get(attr)
            {
                return v.clone();
            }
            Value::String(s.clone())
        }
        _ => Value::Null,
    }
}

fn resolve_sub(
    val: &Value,
    params: &HashMap<String, Value>,
    conditions: &HashMap<String, bool>,
    resources: &HashMap<String, Value>,
) -> Value {
    let (template_str, extra_vars) = match val {
        Value::String(s) => (s.as_str(), HashMap::new()),
        Value::Array(arr) if arr.len() == 2 => {
            let s = arr[0].as_str().unwrap_or("");
            let mut extra = HashMap::new();
            if let Some(Value::Object(map)) = arr.get(1) {
                for (k, v) in map {
                    let resolved = resolve_value(v, params, conditions, resources);
                    extra.insert(k.clone(), resolved.as_str().unwrap_or("").to_string());
                }
            }
            (s, extra)
        }
        _ => return val.clone(),
    };

    // Substitute ${VarName} patterns
    let mut i = 0;
    let bytes = template_str.as_bytes();
    let mut out = String::new();
    while i < bytes.len() {
        if bytes[i] == b'$'
            && i + 1 < bytes.len()
            && bytes[i + 1] == b'{'
            && let Some(end) = template_str[i + 2..].find('}')
        {
            let var_name = &template_str[i + 2..i + 2 + end];
            let replacement = if let Some(v) = extra_vars.get(var_name) {
                v.clone()
            } else if let Some(v) = params.get(var_name) {
                v.as_str().unwrap_or("").to_string()
            } else if let Some(res) = resources.get(var_name) {
                res.get("PhysicalResourceId")
                    .and_then(|v| v.as_str())
                    .unwrap_or(var_name)
                    .to_string()
            } else {
                // Pseudo-parameters
                match var_name {
                    "AWS::AccountId" => "000000000000".to_string(),
                    "AWS::Region" => "us-east-1".to_string(),
                    _ => var_name.to_string(),
                }
            };
            out.push_str(&replacement);
            i += 2 + end + 1; // skip past the closing `}`
            continue;
        }
        out.push(bytes[i] as char);
        i += 1;
    }

    Value::String(out)
}

fn resolve_join(
    val: &Value,
    params: &HashMap<String, Value>,
    conditions: &HashMap<String, bool>,
    resources: &HashMap<String, Value>,
) -> Value {
    if let Value::Array(arr) = val
        && arr.len() == 2
    {
        let delimiter = arr[0].as_str().unwrap_or("");
        let resolved = resolve_value(&arr[1], params, conditions, resources);
        let items: Vec<String> = match &resolved {
            Value::Array(items) => items
                .iter()
                .map(|v| match v {
                    Value::String(s) => s.clone(),
                    other => other.to_string(),
                })
                .collect(),
            _ => return Value::String(String::new()),
        };
        return Value::String(items.join(delimiter));
    }
    Value::Null
}

fn resolve_select(
    val: &Value,
    params: &HashMap<String, Value>,
    conditions: &HashMap<String, bool>,
    resources: &HashMap<String, Value>,
) -> Value {
    if let Value::Array(arr) = val
        && arr.len() == 2
    {
        let idx = arr[0].as_u64().unwrap_or(0) as usize;
        let resolved = resolve_value(&arr[1], params, conditions, resources);
        if let Value::Array(items) = resolved
            && let Some(item) = items.get(idx)
        {
            return item.clone();
        }
    }
    Value::Null
}

fn resolve_if(
    val: &Value,
    params: &HashMap<String, Value>,
    conditions: &HashMap<String, bool>,
    resources: &HashMap<String, Value>,
) -> Value {
    if let Value::Array(arr) = val
        && arr.len() == 3
    {
        let condition_name = arr[0].as_str().unwrap_or("");
        let is_true = conditions.get(condition_name).copied().unwrap_or(false);
        let branch = if is_true { &arr[1] } else { &arr[2] };
        return resolve_value(branch, params, conditions, resources);
    }
    Value::Null
}

/// `Fn::Base64`: resolve the inner value and return its UTF-8
/// bytes base64-encoded as a string. CloudFormation uses this for
/// EC2 UserData and inline launch-config blobs; without it,
/// `Fn::Base64: !Sub <...>` produced an empty map and any AMI
/// that consumed UserData booted with no user data set.
fn resolve_base64(
    val: &Value,
    params: &HashMap<String, Value>,
    conditions: &HashMap<String, bool>,
    resources: &HashMap<String, Value>,
) -> Value {
    use base64::Engine as _;
    let inner = resolve_value(val, params, conditions, resources);
    let raw = match &inner {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    };
    let encoded = base64::engine::general_purpose::STANDARD.encode(raw.as_bytes());
    Value::String(encoded)
}

/// `Fn::GetAZs`: return the list of availability zones for the given
/// region. Real AWS varies the count per region; awsim is a single-
/// node emulator without real AZ topology, so we return three
/// synthesized zones (`<region>a`, `<region>b`, `<region>c`).
/// An empty string is shorthand for the calling region; CloudFormation
/// uses `Fn::GetAZs: ""` idiomatically inside `Fn::Select`.
fn resolve_get_azs(
    val: &Value,
    params: &HashMap<String, Value>,
    conditions: &HashMap<String, bool>,
    resources: &HashMap<String, Value>,
) -> Value {
    let inner = resolve_value(val, params, conditions, resources);
    let region = match &inner {
        Value::String(s) if !s.is_empty() => s.clone(),
        _ => "us-east-1".to_string(),
    };
    Value::Array(vec![
        Value::String(format!("{region}a")),
        Value::String(format!("{region}b")),
        Value::String(format!("{region}c")),
    ])
}

/// Topological sort of resources by DependsOn.
fn topological_sort(resources: Vec<ResourceDef>) -> Result<Vec<ResourceDef>, String> {
    let mut name_to_idx: HashMap<String, usize> = HashMap::new();
    for (i, r) in resources.iter().enumerate() {
        name_to_idx.insert(r.logical_id.clone(), i);
    }

    let n = resources.len();
    let mut in_degree = vec![0usize; n];
    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];

    for (i, r) in resources.iter().enumerate() {
        for dep in &r.depends_on {
            if let Some(&j) = name_to_idx.get(dep) {
                adj[j].push(i);
                in_degree[i] += 1;
            } else {
                return Err(format!("Unknown DependsOn target '{dep}'"));
            }
        }
    }

    // Kahn's algorithm
    let mut queue: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
    let mut order: Vec<usize> = Vec::with_capacity(n);

    while let Some(node) = queue.first().copied() {
        queue.remove(0);
        order.push(node);
        for &next in &adj[node] {
            in_degree[next] -= 1;
            if in_degree[next] == 0 {
                queue.push(next);
            }
        }
    }

    if order.len() != n {
        return Err("Circular dependency detected in resources".to_string());
    }

    let mut result: Vec<Option<ResourceDef>> = resources.into_iter().map(Some).collect();
    Ok(order
        .into_iter()
        .map(|i| result[i].take().unwrap())
        .collect())
}

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

    #[test]
    fn validates_resource_type_format() {
        assert!(is_valid_resource_type("AWS::S3::Bucket"));
        assert!(is_valid_resource_type("AWS::EC2::VPC"));
        assert!(is_valid_resource_type("Alexa::ASK::Skill"));
        assert!(is_valid_resource_type("Custom::MyResource"));
        assert!(!is_valid_resource_type(""));
        assert!(!is_valid_resource_type("S3::Bucket"));
        assert!(!is_valid_resource_type("AWS::"));
        assert!(!is_valid_resource_type("AWS::S3"));
        assert!(!is_valid_resource_type("Bogus::Service::Thing"));
        assert!(!is_valid_resource_type("AWS::S3::Bucket::Extra"));
    }

    #[test]
    fn rejects_unknown_resource_type_in_template() {
        let body = r#"{
            "Resources": {
                "X": { "Type": "Bogus::Service::Thing" }
            }
        }"#;
        let err = validate_and_parse(body, &HashMap::new()).unwrap_err();
        assert!(err.message.contains("unknown resource type"));
    }

    #[test]
    fn test_parse_json_template() {
        let body = r#"{
            "AWSTemplateFormatVersion": "2010-09-09",
            "Description": "Test template",
            "Resources": {
                "MyBucket": {
                    "Type": "AWS::S3::Bucket"
                }
            }
        }"#;

        let result = validate_and_parse(body, &HashMap::new());
        assert!(result.is_ok());
        let parsed = result.unwrap();
        assert_eq!(parsed.description, Some("Test template".to_string()));
        assert_eq!(parsed.resources.len(), 1);
        assert_eq!(parsed.resources[0].logical_id, "MyBucket");
        assert_eq!(parsed.resources[0].resource_type, "AWS::S3::Bucket");
    }

    #[test]
    fn test_depends_on_ordering() {
        let body = r#"{
            "Resources": {
                "ResourceB": {
                    "Type": "AWS::S3::Bucket",
                    "DependsOn": "ResourceA"
                },
                "ResourceA": {
                    "Type": "AWS::IAM::Role"
                }
            }
        }"#;

        let result = validate_and_parse(body, &HashMap::new());
        assert!(result.is_ok());
        let parsed = result.unwrap();
        // ResourceA must come before ResourceB
        let a_pos = parsed
            .resources
            .iter()
            .position(|r| r.logical_id == "ResourceA")
            .unwrap();
        let b_pos = parsed
            .resources
            .iter()
            .position(|r| r.logical_id == "ResourceB")
            .unwrap();
        assert!(a_pos < b_pos, "ResourceA should precede ResourceB");
    }

    #[test]
    fn test_ref_resolution() {
        let mut params = HashMap::new();
        params.insert("MyParam".to_string(), Value::String("my-value".to_string()));
        let val = json!({ "Ref": "MyParam" });
        let resolved = resolve_value(&val, &params, &HashMap::new(), &HashMap::new());
        assert_eq!(resolved, Value::String("my-value".to_string()));
    }

    #[test]
    fn test_fn_join() {
        let val = json!({ "Fn::Join": ["-", ["a", "b", "c"]] });
        let resolved = resolve_value(&val, &HashMap::new(), &HashMap::new(), &HashMap::new());
        assert_eq!(resolved, Value::String("a-b-c".to_string()));
    }

    #[test]
    fn test_parse_yaml_template() {
        let body = r#"
AWSTemplateFormatVersion: "2010-09-09"
Description: YAML test template
Parameters:
  BucketName:
    Type: String
    Default: my-bucket
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref BucketName
"#;
        let result = validate_and_parse(body, &HashMap::new()).unwrap();
        assert_eq!(result.description, Some("YAML test template".to_string()));
        assert_eq!(result.resources.len(), 1);
        assert_eq!(result.resources[0].logical_id, "MyBucket");
        assert_eq!(result.resources[0].resource_type, "AWS::S3::Bucket");
        assert_eq!(result.parameters.len(), 1);
        assert_eq!(result.parameters[0].name, "BucketName");
        assert_eq!(result.parameters[0].default, Some("my-bucket".to_string()));
    }
}

#[cfg(test)]
mod base64_intrinsic_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn fn_base64_encodes_static_string() {
        let val = json!({ "Fn::Base64": "hello world" });
        let got = resolve_value(&val, &HashMap::new(), &HashMap::new(), &HashMap::new());
        // base64("hello world") == "aGVsbG8gd29ybGQ="
        assert_eq!(got, json!("aGVsbG8gd29ybGQ="));
    }

    #[test]
    fn fn_base64_encodes_nested_intrinsic_result() {
        let val = json!({
            "Fn::Base64": {
                "Fn::Sub": "#!/bin/bash\necho ${Name}"
            }
        });
        let mut params = HashMap::new();
        params.insert("Name".to_string(), json!("alice"));
        let got = resolve_value(&val, &params, &HashMap::new(), &HashMap::new());
        // base64("#!/bin/bash\necho alice") == "IyEvYmluL2Jhc2gKZWNobyBhbGljZQ=="
        assert_eq!(got, json!("IyEvYmluL2Jhc2gKZWNobyBhbGljZQ=="));
    }

    #[test]
    fn fn_base64_handles_empty_string() {
        let val = json!({ "Fn::Base64": "" });
        let got = resolve_value(&val, &HashMap::new(), &HashMap::new(), &HashMap::new());
        assert_eq!(got, json!(""));
    }

    #[test]
    fn fn_get_azs_with_explicit_region() {
        let val = json!({ "Fn::GetAZs": "us-west-2" });
        let got = resolve_value(&val, &HashMap::new(), &HashMap::new(), &HashMap::new());
        assert_eq!(got, json!(["us-west-2a", "us-west-2b", "us-west-2c"]));
    }

    #[test]
    fn fn_get_azs_with_empty_region_defaults() {
        let val = json!({ "Fn::GetAZs": "" });
        let got = resolve_value(&val, &HashMap::new(), &HashMap::new(), &HashMap::new());
        assert_eq!(got, json!(["us-east-1a", "us-east-1b", "us-east-1c"]));
    }

    #[test]
    fn fn_get_azs_inside_fn_select_picks_first_zone() {
        let val = json!({ "Fn::Select": [0, { "Fn::GetAZs": "eu-central-1" }] });
        let got = resolve_value(&val, &HashMap::new(), &HashMap::new(), &HashMap::new());
        assert_eq!(got, json!("eu-central-1a"));
    }
}

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

    fn def(name: &str) -> ParameterDef {
        ParameterDef {
            name: name.into(),
            param_type: "String".into(),
            default: None,
            description: None,
            min_length: None,
            max_length: None,
            min_value: None,
            max_value: None,
            allowed_values: Vec::new(),
            allowed_pattern: None,
            constraint_description: None,
            no_echo: false,
        }
    }

    #[test]
    fn allowed_values_membership_enforced() {
        let mut d = def("Env");
        d.allowed_values = vec!["dev".into(), "prod".into()];
        validate_parameter_value(&d, "dev").unwrap();
        let err = validate_parameter_value(&d, "staging").unwrap_err();
        assert_eq!(err.code, "ValidationError");
    }

    #[test]
    fn min_length_and_max_length_bound_strings() {
        let mut d = def("Token");
        d.min_length = Some(4);
        d.max_length = Some(8);
        validate_parameter_value(&d, "abcd").unwrap();
        validate_parameter_value(&d, "abcdefgh").unwrap();
        assert!(validate_parameter_value(&d, "abc").is_err());
        assert!(validate_parameter_value(&d, "abcdefghi").is_err());
    }

    #[test]
    fn min_value_and_max_value_bound_numbers() {
        let mut d = def("Port");
        d.param_type = "Number".into();
        d.min_value = Some(1024.0);
        d.max_value = Some(65535.0);
        validate_parameter_value(&d, "8080").unwrap();
        assert!(validate_parameter_value(&d, "100").is_err());
        assert!(validate_parameter_value(&d, "70000").is_err());
        assert!(validate_parameter_value(&d, "not-a-number").is_err());
    }

    #[test]
    fn allowed_pattern_regex_enforced() {
        let mut d = def("Cidr");
        d.allowed_pattern = Some(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}".into());
        validate_parameter_value(&d, "10.0.0.0/16").unwrap();
        let err = validate_parameter_value(&d, "not-a-cidr").unwrap_err();
        assert_eq!(err.code, "ValidationError");
    }

    #[test]
    fn constraint_description_overrides_default_message() {
        let mut d = def("Env");
        d.allowed_values = vec!["dev".into(), "prod".into()];
        d.constraint_description = Some("Env must be dev or prod.".into());
        let err = validate_parameter_value(&d, "x").unwrap_err();
        assert_eq!(err.message, "Env must be dev or prod.");
    }

    #[test]
    fn no_echo_flag_parsed_from_template() {
        let body = r#"{
          "Parameters": {
            "DbPassword": { "Type": "String", "NoEcho": true, "Default": "hunter2" }
          },
          "Resources": {
            "X": { "Type": "AWS::S3::Bucket" }
          }
        }"#;
        let parsed = validate_and_parse(body, &HashMap::new()).unwrap();
        let p = parsed
            .parameters
            .iter()
            .find(|p| p.name == "DbPassword")
            .unwrap();
        assert!(p.no_echo);
    }

    #[test]
    fn validate_and_parse_rejects_violation_on_supplied_value() {
        let body = r#"{
          "Parameters": {
            "Env": {
              "Type": "String",
              "AllowedValues": ["dev", "prod"]
            }
          },
          "Resources": {
            "X": { "Type": "AWS::S3::Bucket" }
          }
        }"#;
        let mut supplied = HashMap::new();
        supplied.insert("Env".to_string(), "staging".to_string());
        let err = validate_and_parse(body, &supplied).unwrap_err();
        assert_eq!(err.code, "ValidationError");
    }
}