cloudformation-validate-template-model 1.12.1

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
//! Shared logic for validating region-scoped instance-type / node-type enum
//! values, used identically by the schema validator and both rule engines so
//! they cannot diverge.
//!
//! Each embedded enum document is a `{ "<region>": ... }` map. When a region is
//! configured, a value is checked against that one region's allowed set. When no
//! region is configured, it is checked against the **union of every region** -
//! flagged only when it is invalid in every region - so a value valid in the
//! caller's actual target region is not reported just because it is unavailable
//! in the platform-default region. The synthetic non-region keys some documents
//! carry (`all`, `description`) are excluded by intersecting the document's keys
//! with [`AWS_REGIONS`].
//!
//! Two document shapes exist:
//! - **Flat**: `{ "<region>": { "enum": [...] } }` (EC2, DocDB, AmazonMQ, …).
//! - **Conditional** (RDS `DBInstanceClass` / `DBClusterInstanceClass`): each
//!   region maps to an `allOf` of if/then branches keyed on Engine/LicenseModel;
//!   a value is valid in a region only when it is in the intersection of every
//!   matching branch's enum.

use crate::message::{quote, render_str_list};
use crate::model::SemanticModel;
use crate::regions::AWS_REGIONS;
use crate::resolved_value::resolved_value_at_path;
use crate::resolver::ResolvedValue;
use std::collections::{BTreeSet, HashSet};

/// Resource types and property paths whose instance-type / node-type value is
/// validated against a region-scoped enum. This is the single list of what
/// "region-scoped validation" covers, used to decide whether the no-region
/// best-effort advisory applies to a template. A `{}` segment matches every
/// element of a list. Both rule engines validate exactly these paths; keeping the
/// set here documents the advisory's trigger in one place.
pub const REGION_SCOPED_TYPE_PATHS: &[(&str, &str)] = &[
    ("AWS::EC2::Instance", "Properties.InstanceType"),
    ("AWS::GameLift::Fleet", "Properties.EC2InstanceType"),
    ("AWS::EMR::InstanceTypeConfig", "Properties.InstanceType"),
    ("AWS::EMR::InstanceFleetConfig", "Properties.InstanceType"),
    ("AWS::ManagedBlockchain::Node", "Properties.NodeConfiguration.InstanceType"),
    ("AWS::DocDB::DBInstance", "Properties.DBInstanceClass"),
    ("AWS::AppStream::Fleet", "Properties.InstanceType"),
    ("AWS::ElastiCache::CacheCluster", "Properties.CacheNodeType"),
    ("AWS::DAX::Cluster", "Properties.NodeType"),
    ("AWS::Neptune::DBInstance", "Properties.DBInstanceClass"),
    ("AWS::Redshift::Cluster", "Properties.NodeType"),
    ("AWS::AmazonMQ::Broker", "Properties.HostInstanceType"),
    ("AWS::RDS::DBInstance", "Properties.DBInstanceClass"),
    ("AWS::RDS::DBCluster", "Properties.DBClusterInstanceClass"),
    ("AWS::SageMaker::DataQualityJobDefinition", "Properties.JobResources.ClusterConfig.InstanceType"),
    ("AWS::SageMaker::ModelBiasJobDefinition", "Properties.JobResources.ClusterConfig.InstanceType"),
    ("AWS::SageMaker::ModelExplainabilityJobDefinition", "Properties.JobResources.ClusterConfig.InstanceType"),
    ("AWS::SageMaker::ModelQualityJobDefinition", "Properties.JobResources.ClusterConfig.InstanceType"),
    (
        "AWS::SageMaker::MonitoringSchedule",
        "Properties.MonitoringScheduleConfig.MonitoringJobDefinition.MonitoringResources.ClusterConfig.InstanceType",
    ),
    ("AWS::Elasticsearch::Domain", "Properties.ElasticsearchClusterConfig.InstanceType"),
    ("AWS::OpenSearchService::Domain", "Properties.ClusterConfig.InstanceType"),
    (
        "AWS::SageMaker::InferenceExperiment",
        "Properties.ModelVariants.{}.InfrastructureConfig.RealTimeInferenceConfig.InstanceType",
    ),
    (
        "AWS::SageMaker::ModelPackage",
        "Properties.ValidationSpecification.ValidationProfiles.{}.TransformJobDefinition.TransformResources.InstanceType",
    ),
    ("AWS::SageMaker::Cluster", "Properties.InstanceGroups.{}.InstanceType"),
    ("AWS::SageMaker::Cluster", "Properties.RestrictedInstanceGroups.{}.InstanceType"),
];

/// Whether the template contains at least one region-scoped instance-type /
/// node-type value that resolves to a concrete string - i.e. a value that the
/// region-scoped enum rules actually validate. Used to decide whether the
/// no-region best-effort advisory is worth emitting: a template with no such
/// value had nothing validated best-effort, so the advisory would be noise. The
/// result depends only on the model, so it is identical across engines.
pub fn template_has_region_scoped_value(model: &SemanticModel) -> bool {
    REGION_SCOPED_TYPE_PATHS.iter().any(|(rtype, path)| {
        model.resources_of_type(rtype).iter().any(|rid| resolves_to_concrete_string(model, rid, path))
    })
}

/// Whether `path` on `rid` resolves to any concrete string, collapsing an
/// `Fn::If` to its true branch and treating a `{}` wildcard as a match against
/// every list element - mirroring how the enum rules read the value.
fn resolves_to_concrete_string(model: &SemanticModel, rid: &str, path: &str) -> bool {
    let Some(resolved) = resolve_for_detection(model, rid, path) else {
        return false;
    };
    any_concrete_string(&resolved)
}

/// Resolves `path` (which may contain a `{}` wildcard) for the advisory detector.
fn resolve_for_detection(model: &SemanticModel, rid: &str, path: &str) -> Option<ResolvedValue> {
    if path.contains("{}") {
        let resource = model.resources.get(rid)?;
        let prop_path = path.strip_prefix("Properties.").unwrap_or(path);
        let mut segments = prop_path.splitn(2, '.');
        let top_key = segments.next()?;
        let resolved = resource.properties.get(top_key)?;
        return match segments.next() {
            Some(rest) if !rest.is_empty() => resolved_value_at_path(resolved, rest),
            _ => Some(resolved.clone()),
        };
    }
    model.resolve_deep(rid, path).or_else(|| model.resolve(rid, path).cloned())
}

/// Whether a resolved value yields any concrete string, descending through the
/// composite variants the enum rules also descend (lists, `Fn::If` true branches,
/// enum candidates).
fn any_concrete_string(value: &ResolvedValue) -> bool {
    match value {
        ResolvedValue::Concrete { value } => value.0.is_string(),
        ResolvedValue::List { items } | ResolvedValue::Enum { variants: items } => {
            items.iter().any(any_concrete_string)
        }
        ResolvedValue::Conditional { if_true, if_false, .. } => {
            any_concrete_string(if_true) || any_concrete_string(if_false)
        }
        _ => false,
    }
}

/// Fragment used in place of a region name in a diagnostic message when no region
/// is configured and the value was validated against the union of all regions.
pub const ANY_REGION_LABEL: &str = "any region";

/// The label naming what a region-scoped value was validated against: the
/// configured region, or [`ANY_REGION_LABEL`] when none was configured.
pub fn region_label(region: Option<&str>) -> &str {
    region.unwrap_or(ANY_REGION_LABEL)
}

/// Diagnostic message for a flat instance-type / node-type enum value that is not
/// valid for the effective scope. With a region configured this is today's
/// message verbatim; with none configured it states the value is valid in no
/// region. Built here so both engines emit byte-identical text.
pub fn flat_invalid_message(value: &str, region: Option<&str>) -> String {
    match region {
        Some(region) => format!("'{value}' is not valid for region '{region}'"),
        None => format!("'{value}' is not valid in any region"),
    }
}

/// Diagnostic message for a conditional RDS instance-class value that is not one
/// of the allowed classes for the effective scope, rendering the candidate enum.
/// This compatibility helper preserves the original context-free wording for
/// external callers; engine diagnostics use [`conditional_mismatch_message`].
pub fn conditional_invalid_message(value: &str, allowed_sorted: &[String], region: Option<&str>) -> String {
    let rendered = render_str_list(allowed_sorted);
    match region {
        Some(region) => format!("'{value}' is not one of {rendered} in '{region}'"),
        None => format!("'{value}' is not one of {rendered} in any region"),
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConditionalEnumMismatch {
    allowed_values: Vec<String>,
    property_constraints: Vec<(String, String)>,
}

#[derive(Clone, Debug)]
struct ConditionalBranchEnum {
    allowed_values: HashSet<String>,
    property_constraints: Vec<(String, String)>,
}

/// Diagnostic message for a conditional instance-class mismatch. It names the
/// resource properties whose values selected the failing enum branch so a class
/// that is valid for another engine or license model is not described as globally invalid.
pub fn conditional_mismatch_message(value: &str, mismatch: &ConditionalEnumMismatch, region: Option<&str>) -> String {
    if mismatch.property_constraints.is_empty() {
        return conditional_invalid_message(value, &mismatch.allowed_values, region);
    }

    let rendered_allowed = render_str_list(&mismatch.allowed_values);
    let rendered_constraints = mismatch
        .property_constraints
        .iter()
        .map(|(property, expected)| format!("{property} is {}", quote(expected)))
        .collect::<Vec<_>>()
        .join(" and ");
    match region {
        Some(region) => format!("'{value}' is not one of {rendered_allowed} when {rendered_constraints} in '{region}'"),
        None => format!("'{value}' is not one of {rendered_allowed} when {rendered_constraints} in any region"),
    }
}

/// The allowed values from a flat enum document for the effective scope: the
/// single `region` when configured, or the union across all AWS regions when not.
/// Returns `None` when the document has no entry for the effective scope, so the
/// caller skips validation - a dynamic or unknown configured region is not
/// validated, matching today's per-region lookup that returns `None` for a
/// missing region.
pub fn flat_allowed_value_set<'a>(
    doc: &'a serde_json::Map<String, serde_json::Value>,
    region: Option<&str>,
) -> Option<HashSet<&'a str>> {
    match region {
        Some(region) => {
            let values = doc.get(region)?.get("enum")?.as_array()?;
            Some(values.iter().filter_map(|v| v.as_str()).collect())
        }
        None => {
            let mut union = HashSet::new();
            for region in AWS_REGIONS {
                if let Some(values) = doc.get(*region).and_then(|r| r.get("enum")).and_then(|e| e.as_array()) {
                    union.extend(values.iter().filter_map(|v| v.as_str()));
                }
            }
            // An empty union means no region contributed any allowed value, so
            // there is nothing to validate against - skip (return `None`) rather
            // than flag every value as invalid, mirroring the per-region arm which
            // returns `None` when the region has no enum.
            (!union.is_empty()).then_some(union)
        }
    }
}

/// Returns the same allowed values in deterministic order for callers that iterate them.
pub fn flat_allowed_values<'a>(
    doc: &'a serde_json::Map<String, serde_json::Value>,
    region: Option<&str>,
) -> Option<BTreeSet<&'a str>> {
    flat_allowed_value_set(doc, region).map(|allowed| allowed.into_iter().collect())
}

/// For a conditional RDS document (`{ "<region>": { "allOf": [...] } }`), returns
/// the sorted enum to render when `value` is invalid for the effective scope, or
/// `None` when the value is valid or the document does not apply. `resolve_prop`
/// supplies the resource's scalar property values (Engine, LicenseModel) that the
/// branch `if.required` consts key on.
///
/// With a region configured, this validates against that one region's
/// matching-branch intersection. With no region configured, a value is valid
/// when it is valid in *any* region, so it is flagged only when it fails in every
/// region; the rendered enum is then the largest failing branch across all regions.
pub fn conditional_invalid_enum<F>(
    doc: &serde_json::Map<String, serde_json::Value>,
    region: Option<&str>,
    target_prop: &str,
    normalize_engine_case: bool,
    value: &str,
    resolve_prop: F,
) -> Option<Vec<String>>
where
    F: Fn(&str) -> Option<String>,
{
    conditional_enum_mismatch(doc, region, target_prop, normalize_engine_case, value, resolve_prop)
        .map(|mismatch| mismatch.allowed_values)
}

/// Returns the failing enum branch together with the property constraints that
/// selected it. A value that is valid under any region is accepted when no
/// region is configured; otherwise the largest failing branch is returned.
pub fn conditional_enum_mismatch<F>(
    doc: &serde_json::Map<String, serde_json::Value>,
    region: Option<&str>,
    target_prop: &str,
    normalize_engine_case: bool,
    value: &str,
    resolve_prop: F,
) -> Option<ConditionalEnumMismatch>
where
    F: Fn(&str) -> Option<String>,
{
    match region {
        Some(region) => {
            let region_doc = doc.get(region)?;
            let branch_enums = conditional_branch_enums(region_doc, target_prop, normalize_engine_case, &resolve_prop);
            invalid_branch_mismatch(&branch_enums, value)
        }
        None => {
            let mut valid_somewhere = false;
            let mut had_matching_branch = false;
            let mut failing_largest: Option<ConditionalEnumMismatch> = None;
            for region in AWS_REGIONS {
                let Some(region_doc) = doc.get(*region) else {
                    continue;
                };
                let branch_enums =
                    conditional_branch_enums(region_doc, target_prop, normalize_engine_case, &resolve_prop);
                if branch_enums.is_empty() {
                    continue;
                }
                had_matching_branch = true;
                if branch_enums.iter().all(|branch| branch.allowed_values.contains(value)) {
                    valid_somewhere = true;
                    break;
                }
                if let Some(mismatch) = invalid_branch_mismatch(&branch_enums, value)
                    && failing_largest
                        .as_ref()
                        .is_none_or(|current| mismatch.allowed_values.len() > current.allowed_values.len())
                {
                    failing_largest = Some(mismatch);
                }
            }
            if !had_matching_branch || valid_somewhere {
                return None;
            }
            failing_largest
        }
    }
}

/// Collects every `then.<target_prop>.enum` from a conditional region document
/// whose `allOf` branch `if.required` consts all match the resolved properties.
/// Each enum retains the const constraints that selected it because those values
/// explain why an otherwise valid instance class is incompatible.
fn conditional_branch_enums<F>(
    region_doc: &serde_json::Value,
    target_prop: &str,
    normalize_engine_case: bool,
    resolve_prop: &F,
) -> Vec<ConditionalBranchEnum>
where
    F: Fn(&str) -> Option<String>,
{
    let mut matching_branches = Vec::new();
    let Some(branches) = region_doc.get("allOf").and_then(|value| value.as_array()) else {
        return matching_branches;
    };
    for branch in branches {
        let (Some(required), Some(if_properties)) = (
            branch.get("if").and_then(|condition| condition.get("required")).and_then(|value| value.as_array()),
            branch.get("if").and_then(|condition| condition.get("properties")).and_then(|value| value.as_object()),
        ) else {
            continue;
        };

        let mut property_constraints = Vec::new();
        let mut all_required_match = true;
        for property in required.iter().filter_map(|value| value.as_str()).filter(|property| *property != target_prop) {
            let Some(expected) =
                if_properties.get(property).and_then(|schema| schema.get("const")).and_then(|value| value.as_str())
            else {
                all_required_match = false;
                break;
            };
            let Some(actual) = resolve_prop(property) else {
                all_required_match = false;
                break;
            };
            let matches = if normalize_engine_case && property == "Engine" {
                actual.eq_ignore_ascii_case(expected)
            } else {
                actual == expected
            };
            if !matches {
                all_required_match = false;
                break;
            }
            property_constraints.push((property.to_string(), expected.to_string()));
        }
        if !all_required_match {
            continue;
        }
        property_constraints.sort_unstable();

        let Some(enum_values) = branch
            .get("then")
            .and_then(|then_schema| then_schema.get("properties"))
            .and_then(|properties| properties.get(target_prop))
            .and_then(|property_schema| property_schema.get("enum"))
            .and_then(|value| value.as_array())
        else {
            continue;
        };
        matching_branches.push(ConditionalBranchEnum {
            allowed_values: enum_values.iter().filter_map(|value| value.as_str().map(String::from)).collect(),
            property_constraints,
        });
    }
    matching_branches
}

/// Returns the largest matching branch that excludes `value`, preserving the
/// constraints that selected it. `None` means every matching branch accepts the
/// value or no branch matched.
fn invalid_branch_mismatch(branch_enums: &[ConditionalBranchEnum], value: &str) -> Option<ConditionalEnumMismatch> {
    let failing_largest = branch_enums
        .iter()
        .filter(|branch| !branch.allowed_values.contains(value))
        .max_by_key(|branch| branch.allowed_values.len())?;
    let mut allowed_values: Vec<String> = failing_largest.allowed_values.iter().cloned().collect();
    allowed_values.sort();
    Some(ConditionalEnumMismatch { allowed_values, property_constraints: failing_largest.property_constraints.clone() })
}

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

    fn flat_doc() -> serde_json::Map<String, serde_json::Value> {
        // us-east-1 lacks "special.type"; ap-east-2 has it. "all"/"description"
        // are synthetic non-region keys that must never contribute.
        json!({
            "us-east-1": { "enum": ["common.type", "east.type"] },
            "ap-east-2": { "enum": ["common.type", "special.type"] },
            "all": { "enum": ["should.be.ignored"] },
            "description": "generated"
        })
        .as_object()
        .unwrap()
        .clone()
    }

    #[test]
    fn region_label_uses_region_or_any_region() {
        assert_eq!(region_label(Some("us-west-2")), "us-west-2");
        assert_eq!(region_label(None), "any region");
    }

    #[test]
    fn flat_with_region_validates_that_region_only() {
        let doc = flat_doc();
        let allowed = flat_allowed_values(&doc, Some("us-east-1")).unwrap();
        assert!(allowed.contains("east.type"));
        assert!(!allowed.contains("special.type"), "special.type is not valid in us-east-1");
    }

    #[test]
    fn flat_without_region_unions_all_regions() {
        let doc = flat_doc();
        let allowed = flat_allowed_values(&doc, None).unwrap();
        assert!(allowed.contains("east.type"));
        assert!(allowed.contains("special.type"), "special.type is valid in ap-east-2, so present in the union");
        assert!(!allowed.contains("should.be.ignored"), "the synthetic 'all' key must not contribute");
    }

    #[test]
    fn flat_unknown_configured_region_returns_none() {
        let doc = flat_doc();
        assert!(flat_allowed_values(&doc, Some("mars-north-1")).is_none());
    }

    #[test]
    fn flat_without_region_returns_none_when_no_region_keys() {
        let doc = json!({ "description": "x", "all": { "enum": ["a"] } }).as_object().unwrap().clone();
        assert!(flat_allowed_values(&doc, None).is_none(), "no real region keys → nothing to validate");
    }

    fn conditional_doc() -> serde_json::Map<String, serde_json::Value> {
        // mysql in us-east-1 allows only db.small; ap-east-2 also allows db.big.
        let branch = |class: &str| {
            json!({
                "if": { "required": ["Engine", "DBInstanceClass"], "properties": { "Engine": { "const": "mysql" } } },
                "then": { "properties": { "DBInstanceClass": { "enum": [class] } } }
            })
        };
        json!({
            "us-east-1": { "allOf": [branch("db.small")] },
            "ap-east-2": { "allOf": [ { "if": { "required": ["Engine", "DBInstanceClass"], "properties": { "Engine": { "const": "mysql" } } }, "then": { "properties": { "DBInstanceClass": { "enum": ["db.small", "db.big"] } } } } ] }
        })
        .as_object()
        .unwrap()
        .clone()
    }

    #[test]
    fn conditional_with_region_flags_value_absent_from_that_region() {
        let doc = conditional_doc();
        let engine = |p: &str| (p == "Engine").then(|| "mysql".to_string());
        // db.big is not valid for mysql in us-east-1.
        let invalid = conditional_invalid_enum(&doc, Some("us-east-1"), "DBInstanceClass", true, "db.big", engine);
        assert_eq!(invalid, Some(vec!["db.small".to_string()]));
    }

    #[test]
    fn conditional_without_region_accepts_value_valid_in_any_region() {
        let doc = conditional_doc();
        let engine = |p: &str| (p == "Engine").then(|| "mysql".to_string());
        // db.big is valid for mysql in ap-east-2, so with no region it is accepted.
        let invalid = conditional_invalid_enum(&doc, None, "DBInstanceClass", true, "db.big", engine);
        assert!(invalid.is_none(), "db.big is valid in ap-east-2 → not flagged when region is unset");
    }

    #[test]
    fn conditional_without_region_flags_value_valid_nowhere() {
        let doc = conditional_doc();
        let engine = |p: &str| (p == "Engine").then(|| "mysql".to_string());
        let invalid = conditional_invalid_enum(&doc, None, "DBInstanceClass", true, "db.bogus", engine);
        assert!(invalid.is_some(), "db.bogus is valid in no region → flagged");
        let rendered = invalid.unwrap();
        assert!(rendered.contains(&"db.big".to_string()), "renders the largest failing branch across regions");
    }

    #[test]
    fn conditional_message_names_the_engine_that_selected_the_enum() {
        let doc = conditional_doc();
        let engine = |property: &str| (property == "Engine").then(|| "MySQL".to_string());
        let mismatch = conditional_enum_mismatch(&doc, None, "DBInstanceClass", true, "db.bogus", engine).unwrap();

        assert_eq!(
            conditional_mismatch_message("db.bogus", &mismatch, None),
            "'db.bogus' is not one of ['db.big', 'db.small'] when Engine is 'mysql' in any region"
        );
    }

    #[test]
    fn conditional_message_includes_every_constraint_on_the_failing_branch() {
        let doc = json!({
            "us-east-1": {
                "allOf": [{
                    "if": {
                        "required": ["Engine", "LicenseModel", "DBInstanceClass"],
                        "properties": {
                            "Engine": { "const": "oracle-se2" },
                            "LicenseModel": { "const": "license-included" }
                        }
                    },
                    "then": { "properties": { "DBInstanceClass": { "enum": ["db.allowed"] } } }
                }]
            }
        })
        .as_object()
        .unwrap()
        .clone();
        let properties = |property: &str| match property {
            "Engine" => Some("oracle-se2".to_string()),
            "LicenseModel" => Some("license-included".to_string()),
            _ => None,
        };
        let mismatch =
            conditional_enum_mismatch(&doc, Some("us-east-1"), "DBInstanceClass", true, "db.bogus", properties)
                .unwrap();

        assert_eq!(
            conditional_mismatch_message("db.bogus", &mismatch, Some("us-east-1")),
            "'db.bogus' is not one of ['db.allowed'] when Engine is 'oracle-se2' and LicenseModel is 'license-included' in 'us-east-1'"
        );
    }

    #[test]
    fn conditional_unmatched_engine_is_not_validated() {
        let doc = conditional_doc();
        // Engine resolves to something no branch matches → no matching branch in
        // any region → not validated (mirrors the per-region contract).
        let engine = |p: &str| (p == "Engine").then(|| "oracle".to_string());
        assert!(conditional_invalid_enum(&doc, None, "DBInstanceClass", true, "db.bogus", engine).is_none());
        assert!(
            conditional_invalid_enum(&doc, Some("us-east-1"), "DBInstanceClass", true, "db.bogus", engine).is_none()
        );
    }
}