cloudformation-validate-cel-engine 1.14.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
use log::info;
use std::collections::HashMap;
use std::sync::Arc;

use diagnostics::{Diagnostic, Entity, PhaseMetric, phase_metric};
use rules::{RuleInfo, RuleMetadataEntry, RuleOrigin, Severity, build_rule_metadata_map, is_valid_custom_rule_id};
use schema_validator::{OverlayCatalog, SchemaMetadataCatalog, SchemaValidator, schema_metadata_catalog_with_overlays};
use template_model::{SemanticModel, UNKNOWN_SPAN};
use validation_engine::{
    EngineConfig, GuardRuleSet, ValidateConfig, ValidationEngine, ValidationError, build_rule_list,
    semantic_model_to_input_json,
};

use crate::rule_evaluator::GeneratedRuleRegistry;
use crate::rules::{CachedData, EvalContext, NativeRuleRegistry};

use serde::Deserialize;

use cel_interpreter::{Context, Program, Value as CelValue};

#[derive(Deserialize)]
struct CustomRuleFile {
    rules: Vec<CustomRuleDef>,
}

#[derive(Deserialize)]
struct CustomRuleDef {
    rule_id: String,
    severity: Severity,
    #[serde(default)]
    category: Option<String>,
    resource_type: Option<String>,
    expression: String,
    message: String,
    #[serde(default)]
    prop_path: Option<String>,
    #[serde(default)]
    suggested_fix: Option<String>,
}

pub struct CelEngine {
    native_rules: NativeRuleRegistry,
    generated_rules: GeneratedRuleRegistry,
    custom_rules: Vec<CustomRule>,
    /// Built-in rule metadata from the rules registry only.
    registry_metadata: HashMap<String, RuleMetadataEntry>,
    /// Metadata for custom user rules.
    external_rule_metadata: HashMap<String, RuleMetadataEntry>,
    /// Guard rules are evaluated by the shared Guard evaluator, not by CEL, so
    /// every engine reports the same Guard findings.
    guard_rules: Option<GuardRuleSet>,
    cached_data: CachedData,
    init_metric: PhaseMetric,
}

#[derive(Debug)]
struct CustomRule {
    rule_id: String,
    severity: Severity,
    category: Option<String>,
    resource_type: Option<String>,
    program: Program,
    message: String,
    prop_path: Option<String>,
    suggested_fix: Option<String>,
    source: RuleOrigin,
}

impl CelEngine {
    pub fn new(config: EngineConfig) -> anyhow::Result<Self> {
        let catalog =
            config.build_overlay_catalog().map_err(|e| anyhow::anyhow!("Failed to build overlay catalog: {e}"))?;
        let start = web_time::Instant::now();
        let schema_metadata = schema_metadata_catalog_with_overlays(&catalog)?;
        Self::new_from_parts(config, &catalog, schema_metadata, start)
    }

    /// Constructs the engine reusing metadata from an already-built
    /// [`SchemaValidator`]. The validator's overlay catalog is treated as
    /// authoritative - the engine does not re-resolve overlay schemas.
    ///
    /// This entry point is intended for language bindings and the CLI, which
    /// construct a `SchemaValidator` once and share it with the engine. The
    /// validator's shared schema-metadata catalog is reused rather than rebuilt,
    /// so every engine built from the same validator shares one catalog rather
    /// than rebuilding it.
    #[doc(hidden)]
    pub fn new_with_schema_validator(config: EngineConfig, validator: &SchemaValidator) -> anyhow::Result<Self> {
        let start = web_time::Instant::now();
        let schema_metadata = validator.schema_metadata_catalog()?;
        Self::new_from_parts(config, validator.overlay_catalog(), schema_metadata, start)
    }

    /// Internal constructor that accepts a pre-built overlay catalog and the
    /// shared schema-metadata catalog resolved for it.
    fn new_from_parts(
        config: EngineConfig,
        overlay_catalog: &OverlayCatalog,
        schema_metadata: Arc<SchemaMetadataCatalog>,
        start: web_time::Instant,
    ) -> anyhow::Result<Self> {
        let native_rules = NativeRuleRegistry::new();
        let generated_rules = GeneratedRuleRegistry::new()?;

        let registry_metadata = build_rule_metadata_map();
        let mut external_rule_metadata: HashMap<String, RuleMetadataEntry> = HashMap::new();

        let guard_rules = GuardRuleSet::compile(&config.guard_rules).map_err(|error| anyhow::anyhow!(error))?;

        let mut custom_rules = Vec::new();
        for entry in &config.custom_rules {
            match load_custom_rules(&entry.content, RuleOrigin::Custom) {
                Ok(rules) => {
                    info!("Loaded {} custom rules from {}", rules.len(), entry.name);
                    for r in &rules {
                        external_rule_metadata.entry(r.rule_id.clone()).or_insert_with(|| RuleMetadataEntry {
                            category: r.category.clone(),
                            description: r.message.clone(),
                            severity: r.severity,
                            origin: RuleOrigin::Custom,
                        });
                    }
                    custom_rules.extend(rules);
                }
                Err(e) => {
                    return Err(anyhow::anyhow!("Failed to load rules from {}: {}", entry.name, e));
                }
            }
        }

        info!(
            "CelEngine initialized: {} native rule fns, {} custom rules, {} Guard rules, {} registry + {} external \
             metadata entries",
            native_rules.rules.len(),
            custom_rules.len(),
            guard_rules.as_ref().map_or(0, |guard| guard.rule_metadata().len()),
            registry_metadata.len(),
            external_rule_metadata.len()
        );
        let mut cached_data = CachedData::load()?;
        // Resource types introduced by an overlay schema are legitimate targets,
        // so rules working from the build-time type catalog must treat them as
        // known rather than reporting them as nonexistent.
        if !overlay_catalog.is_empty() {
            cached_data.merge_overlay_catalog(overlay_catalog)?;
        }
        cached_data.set_schema_metadata(schema_metadata);
        let init_metric = phase_metric(start);
        Ok(CelEngine {
            native_rules,
            generated_rules,
            custom_rules,
            registry_metadata,
            external_rule_metadata,
            guard_rules,
            cached_data,
            init_metric,
        })
    }
}

impl ValidationEngine for CelEngine {
    fn engine_name(&self) -> &str {
        "cel"
    }

    fn evaluate_rules(
        &self,
        model: &Arc<SemanticModel>,
        config: &ValidateConfig,
    ) -> Result<Vec<Diagnostic>, ValidationError> {
        let input_json = semantic_model_to_input_json(model)?;
        let excluded_cats = config.filters.excluded_categories();
        let region = config.pseudo_parameter_overrides.region.clone();

        let mut diagnostics = if config.disable_builtin_rules {
            Vec::new()
        } else {
            let ctx = EvalContext { model, input: &input_json, region: &region, cached_data: &self.cached_data };
            let mut diags = self.native_rules.evaluate(&ctx, &excluded_cats);
            let gen_diags = self.generated_rules.evaluate(model, &input_json, &excluded_cats);
            diags.extend(gen_diags);
            diags
        };

        for rule in &self.custom_rules {
            if rule.category.as_deref().is_some_and(|c| excluded_cats.contains(c)) {
                continue;
            }
            if let Some(ref rtype) = rule.resource_type {
                for rid in model.resources_of_type(rtype) {
                    let cel_ctx = crate::functions::build_custom_context(&input_json, Some(rid), Some(model));
                    if execute_custom_rule(rule, &cel_ctx)? {
                        let msg = rule.message.replace("{name}", rid);
                        emit_custom_diagnostic(&mut diagnostics, rule, model, rid, &msg);
                    }
                }
            } else {
                let cel_ctx = crate::functions::build_custom_context(&input_json, None, Some(model));
                if execute_custom_rule(rule, &cel_ctx)? {
                    emit_custom_diagnostic(&mut diagnostics, rule, model, "", &rule.message);
                }
            }
        }

        if let Some(guard_rules) = &self.guard_rules {
            diagnostics.extend(guard_rules.evaluate(model)?);
        }

        Ok(diagnostics)
    }

    fn list_rules(&self) -> Vec<RuleInfo> {
        build_rule_list(&self.registry_metadata, &self.external_rule_metadata())
    }

    fn rule_metadata(&self) -> &HashMap<String, RuleMetadataEntry> {
        &self.registry_metadata
    }

    /// Custom CEL rules and Guard rules have disjoint rule IDs only by
    /// convention; a Guard rule that reuses a custom rule's ID keeps the custom
    /// entry, matching how each set resolves its own duplicates.
    fn external_rule_metadata(&self) -> HashMap<String, RuleMetadataEntry> {
        let mut merged = self.external_rule_metadata.clone();
        if let Some(guard_rules) = &self.guard_rules {
            for (rule_id, entry) in guard_rules.rule_metadata() {
                merged.entry(rule_id.clone()).or_insert_with(|| entry.clone());
            }
        }
        merged
    }

    fn init_metric(&self) -> &PhaseMetric {
        &self.init_metric
    }
}

fn execute_custom_rule(rule: &CustomRule, cel_ctx: &Context<'static>) -> Result<bool, ValidationError> {
    match rule.program.execute(cel_ctx) {
        Ok(CelValue::Bool(fired)) => Ok(fired),
        // A rule expression must decide whether the rule fires, so it must produce a
        // boolean. A non-boolean result means the expression is malformed (e.g. it
        // names a property instead of testing one); treating it as "did not fire"
        // would let the mistake pass silently, so surface it as an error.
        Ok(_) => Err(ValidationError::Engine(format!(
            "Custom rule '{}' expression must evaluate to a boolean, but produced a non-boolean value",
            rule.rule_id
        ))),
        Err(error) => {
            Err(ValidationError::Engine(format!("Custom rule '{}' failed to evaluate: {error}", rule.rule_id)))
        }
    }
}

// Custom rules are not in the rule registry, so their severity, category, and
// origin come from the parsed rule rather than the registry-driven
// `RegisteredDiagnostic` builder used for built-in rules.
fn emit_custom_diagnostic(
    out: &mut Vec<Diagnostic>,
    rule: &CustomRule,
    model: &Arc<SemanticModel>,
    rid: &str,
    msg: &str,
) {
    let span =
        if rid.is_empty() { UNKNOWN_SPAN } else { model.resource_span(rid, rule.prop_path.as_deref().unwrap_or("")) };
    out.push(Diagnostic {
        rule_id: rule.rule_id.clone(),
        severity: rule.severity,
        message: msg.to_string(),
        entity: Entity::resource(rid, model.resources.get(rid).map(|r| r.resource_type.clone())),
        property_path: rule.prop_path.clone(),
        suggested_fix: rule.suggested_fix.clone(),
        documentation_url: None,
        category: rule.category.clone(),
        location: if span == UNKNOWN_SPAN { None } else { Some(span) },
        related_resources: None,
        condition_scenario: None,
        rule_description: None,
        phase: None,
        context: None,
        source: rule.source,
    });
}

fn load_custom_rules(source: &str, origin: RuleOrigin) -> anyhow::Result<Vec<CustomRule>> {
    let file: CustomRuleFile = serde_json::from_str(source)?;
    let mut rules = Vec::new();
    for def in file.rules {
        // Required text fields must be present and non-blank. `serde` guarantees the
        // keys exist; these checks reject empty values that would otherwise yield a
        // diagnostic with no rule ID or no message.
        if def.rule_id.trim().is_empty() {
            return Err(anyhow::anyhow!("Custom rule has an empty 'rule_id'"));
        }
        // A custom rule ID may be any run of letters, digits, and the separators
        // `_`, `.`, `-` - it need not follow the built-in ID convention - but must
        // exclude whitespace and other punctuation that would corrupt formatting,
        // filtering, and de-duplication of diagnostics.
        if !is_valid_custom_rule_id(&def.rule_id) {
            return Err(anyhow::anyhow!(
                "Custom rule '{}' has an invalid 'rule_id': only letters, digits, and the separators '_', '.', '-' \
                 are allowed",
                def.rule_id
            ));
        }
        if def.message.trim().is_empty() {
            return Err(anyhow::anyhow!("Custom rule '{}' has an empty 'message'", def.rule_id));
        }
        if def.expression.trim().is_empty() {
            return Err(anyhow::anyhow!("Custom rule '{}' has an empty 'expression'", def.rule_id));
        }
        let program = Program::compile(&def.expression)
            .map_err(|e| anyhow::anyhow!("Failed to compile CEL expression for rule '{}': {}", def.rule_id, e))?;
        // A call to a function the interpreter cannot resolve errors only when the
        // expression is actually evaluated, so a rule scoped to an absent resource
        // type would load clean and silently never run. Reject it at load time
        // instead, when the failure is certain regardless of the template.
        for function in program.references().functions() {
            if !crate::functions::is_supported_function(function) {
                return Err(anyhow::anyhow!(
                    "Custom rule '{}' references unknown function '{}'",
                    def.rule_id,
                    function
                ));
            }
        }
        rules.push(CustomRule {
            rule_id: def.rule_id,
            severity: def.severity,
            category: def.category,
            resource_type: def.resource_type,
            program,
            message: def.message,
            prop_path: def.prop_path,
            suggested_fix: def.suggested_fix,
            source: origin,
        });
    }
    Ok(rules)
}

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

    #[test]
    fn load_custom_rules_valid_json() {
        let json = r#"{"rules": [
            {
                "rule_id": "CUSTOM001",
                "severity": "ERROR",
                "resource_type": "AWS::S3::Bucket",
                "expression": "has(properties.BucketEncryption)",
                "message": "Encryption required"
            }
        ]}"#;
        let rules = load_custom_rules(json, RuleOrigin::Custom).unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].rule_id, "CUSTOM001");
        assert!(matches!(rules[0].severity, Severity::Error));
        assert_eq!(rules[0].resource_type, Some("AWS::S3::Bucket".into()));
        assert_eq!(rules[0].category, None);
    }

    #[test]
    fn load_custom_rules_severity_mapping() {
        let make = |sev: &str| -> String {
            format!(
                r#"{{"rules": [{{"rule_id": "R1", "severity": "{}", "expression": "true", "message": "m"}}]}}"#,
                sev
            )
        };

        let error_rules = load_custom_rules(&make(Severity::Error.as_str()), RuleOrigin::Custom).unwrap();
        assert_eq!(error_rules[0].severity, Severity::Error);

        let warn_rules = load_custom_rules(&make(Severity::Warn.as_str()), RuleOrigin::Custom).unwrap();
        assert_eq!(warn_rules[0].severity, Severity::Warn);

        let info_rules = load_custom_rules(&make(Severity::Info.as_str()), RuleOrigin::Custom).unwrap();
        assert_eq!(info_rules[0].severity, Severity::Info);
    }

    #[test]
    fn load_custom_rules_custom_category() {
        let json = r#"{"rules": [{
            "rule_id": "R1",
            "severity": "ERROR",
            "category": "security",
            "expression": "true",
            "message": "m"
        }]}"#;
        let rules = load_custom_rules(json, RuleOrigin::Custom).unwrap();
        assert_eq!(rules[0].category, Some("security".into()));
    }

    #[test]
    fn load_custom_rules_optional_fields() {
        let json = r#"{"rules": [{
            "rule_id": "R1",
            "severity": "ERROR",
            "expression": "true",
            "message": "m",
            "prop_path": "Properties.X",
            "suggested_fix": "Add X"
        }]}"#;
        let rules = load_custom_rules(json, RuleOrigin::Custom).unwrap();
        assert_eq!(rules[0].prop_path, Some("Properties.X".into()));
        assert_eq!(rules[0].suggested_fix, Some("Add X".into()));
    }

    #[test]
    fn load_custom_rules_global_rule_no_resource_type() {
        let json = r#"{"rules": [{
            "rule_id": "R1",
            "severity": "ERROR",
            "expression": "true",
            "message": "m"
        }]}"#;
        let rules = load_custom_rules(json, RuleOrigin::Custom).unwrap();
        assert_eq!(rules[0].resource_type, None);
    }

    #[test]
    fn load_custom_rules_invalid_json() {
        let result = load_custom_rules("not json", RuleOrigin::Custom);
        result.unwrap_err();
    }

    #[test]
    fn load_custom_rules_bad_cel_expression() {
        let json = r#"{"rules": [{
            "rule_id": "R1",
            "severity": "ERROR",
            "expression": "((( invalid cel",
            "message": "m"
        }]}"#;
        let result = load_custom_rules(json, RuleOrigin::Custom);
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("R1"), "Error should mention rule_id, got: {}", err_msg);
    }

    #[test]
    fn load_custom_rules_empty_rules_array() {
        let json = r#"{"rules": []}"#;
        let rules = load_custom_rules(json, RuleOrigin::Custom).unwrap();
        assert!(rules.is_empty());
    }

    #[test]
    fn load_custom_rules_empty_rule_id_is_rejected() {
        let json = r#"{"rules": [{"rule_id": "", "severity": "ERROR", "expression": "true", "message": "m"}]}"#;
        let err = format!("{}", load_custom_rules(json, RuleOrigin::Custom).unwrap_err());
        assert!(err.contains("empty 'rule_id'"), "an empty rule_id must be rejected, got: {err}");
    }

    #[test]
    fn load_custom_rules_blank_rule_id_is_rejected() {
        let json = r#"{"rules": [{"rule_id": "   ", "severity": "ERROR", "expression": "true", "message": "m"}]}"#;
        let err = format!("{}", load_custom_rules(json, RuleOrigin::Custom).unwrap_err());
        assert!(err.contains("empty 'rule_id'"), "a whitespace-only rule_id must be rejected, got: {err}");
    }

    #[test]
    fn load_custom_rules_arbitrary_alphanumeric_id_with_separators_is_accepted() {
        // A custom rule ID need not follow the built-in convention: letters, digits,
        // and the separators `_`, `.`, `-` are all permitted.
        let json = r#"{"rules": [{"rule_id": "s3.encryption-required_1", "severity": "ERROR", "expression": "true", "message": "m"}]}"#;
        let rules = load_custom_rules(json, RuleOrigin::Custom).expect("an alphanumeric+separator id must load");
        assert_eq!(rules[0].rule_id, "s3.encryption-required_1");
    }

    #[test]
    fn load_custom_rules_rule_id_with_space_or_punctuation_is_rejected() {
        let json = r#"{"rules": [{"rule_id": "bad id", "severity": "ERROR", "expression": "true", "message": "m"}]}"#;
        let err = format!("{}", load_custom_rules(json, RuleOrigin::Custom).unwrap_err());
        assert!(err.contains("invalid 'rule_id'"), "a rule_id with a space must be rejected, got: {err}");

        let json = r#"{"rules": [{"rule_id": "bad/id", "severity": "ERROR", "expression": "true", "message": "m"}]}"#;
        let err = format!("{}", load_custom_rules(json, RuleOrigin::Custom).unwrap_err());
        assert!(err.contains("invalid 'rule_id'"), "a rule_id with punctuation must be rejected, got: {err}");
    }

    #[test]
    fn load_custom_rules_empty_message_is_rejected() {
        let json = r#"{"rules": [{"rule_id": "R1", "severity": "ERROR", "expression": "true", "message": ""}]}"#;
        let err = format!("{}", load_custom_rules(json, RuleOrigin::Custom).unwrap_err());
        assert!(err.contains("R1") && err.contains("empty 'message'"), "an empty message must be rejected, got: {err}");
    }

    #[test]
    fn load_custom_rules_empty_expression_is_rejected() {
        let json = r#"{"rules": [{"rule_id": "R1", "severity": "ERROR", "expression": "  ", "message": "m"}]}"#;
        let err = format!("{}", load_custom_rules(json, RuleOrigin::Custom).unwrap_err());
        assert!(
            err.contains("R1") && err.contains("empty 'expression'"),
            "a blank expression must be rejected, got: {err}"
        );
    }

    #[test]
    fn load_custom_rules_unknown_function_is_rejected_at_load() {
        // The failure must surface at load time, not only when a matching resource
        // happens to exist during evaluation.
        let json = r#"{"rules": [{
            "rule_id": "R1",
            "severity": "ERROR",
            "resource_type": "AWS::S3::Bucket",
            "expression": "totally_unknown_fn(properties.BucketName)",
            "message": "m"
        }]}"#;
        let err = format!("{}", load_custom_rules(json, RuleOrigin::Custom).unwrap_err());
        assert!(
            err.contains("R1") && err.contains("unknown function") && err.contains("totally_unknown_fn"),
            "an unknown function reference must be rejected at load, got: {err}"
        );
    }

    #[test]
    fn load_custom_rules_standard_functions_and_macros_are_accepted() {
        // has()/size()/matches() and comprehension macros must not be mistaken for
        // unknown functions.
        let json = r#"{"rules": [{
            "rule_id": "R1",
            "severity": "ERROR",
            "expression": "has(resource.Properties) && size(resources) > 0 && [1, 2].all(x, x > 0)",
            "message": "m"
        }]}"#;
        let rules = load_custom_rules(json, RuleOrigin::Custom).expect("standard functions and macros must load");
        assert_eq!(rules.len(), 1);
    }

    #[test]
    fn load_custom_rules_type_function_is_accepted() {
        // `type` is registered by build_custom_context for custom rules that
        // inspect a value's kind; it must pass the load-time check.
        let json = r#"{"rules": [{
            "rule_id": "R1",
            "severity": "ERROR",
            "resource_type": "AWS::S3::Bucket",
            "expression": "type(resource) == \"map\"",
            "message": "m"
        }]}"#;
        let rules = load_custom_rules(json, RuleOrigin::Custom).expect("type() must be an accepted function");
        assert_eq!(rules.len(), 1);
    }

    #[test]
    fn load_custom_rules_multiple_rules() {
        let json = r#"{"rules": [
            {"rule_id": "R1", "severity": "ERROR", "expression": "true", "message": "m1"},
            {"rule_id": "R2", "severity": "WARN", "expression": "false", "message": "m2"}
        ]}"#;
        let rules = load_custom_rules(json, RuleOrigin::Custom).unwrap();
        assert_eq!(rules.len(), 2);
        assert_eq!(rules[0].rule_id, "R1");
        assert_eq!(rules[1].rule_id, "R2");
    }

    fn single_rule(source: &str, origin: RuleOrigin) -> CustomRule {
        load_custom_rules(source, origin).expect("rule should load").pop().expect("one rule")
    }

    #[test]
    fn execute_custom_rule_boolean_true_fires() {
        let rule = single_rule(
            r#"{"rules": [{"rule_id": "R1", "severity": "ERROR", "expression": "true", "message": "m"}]}"#,
            RuleOrigin::Custom,
        );
        let ctx = crate::functions::build_custom_context(&serde_json::json!({}), None, None);
        assert!(execute_custom_rule(&rule, &ctx).expect("boolean expression evaluates"));
    }

    #[test]
    fn execute_custom_rule_boolean_false_does_not_fire() {
        let rule = single_rule(
            r#"{"rules": [{"rule_id": "R1", "severity": "ERROR", "expression": "false", "message": "m"}]}"#,
            RuleOrigin::Custom,
        );
        let ctx = crate::functions::build_custom_context(&serde_json::json!({}), None, None);
        assert!(!execute_custom_rule(&rule, &ctx).expect("boolean expression evaluates"));
    }

    #[test]
    fn execute_custom_rule_non_boolean_result_is_error() {
        // A rule whose expression yields a string (not a predicate) is malformed and
        // must error rather than silently be treated as "did not fire".
        let rule = single_rule(
            r#"{"rules": [{"rule_id": "R1", "severity": "ERROR", "expression": "\"a string\"", "message": "m"}]}"#,
            RuleOrigin::Custom,
        );
        let ctx = crate::functions::build_custom_context(&serde_json::json!({}), None, None);
        let err = execute_custom_rule(&rule, &ctx).expect_err("a non-boolean result must error");
        match err {
            ValidationError::Engine(message) => {
                assert!(message.contains("R1") && message.contains("boolean"), "got: {message}");
            }
            other => panic!("expected Engine error, got {other:?}"),
        }
    }

    #[test]
    fn execute_custom_rule_evaluation_error_is_fatal_for_custom_origin() {
        // A custom rule that errors at evaluation (e.g. reads a missing key) must
        // surface the error, not swallow it.
        let rule = single_rule(
            r#"{"rules": [{"rule_id": "R1", "severity": "ERROR", "expression": "resource.Missing.Deep == \"x\"", "message": "m"}]}"#,
            RuleOrigin::Custom,
        );
        let ctx = crate::functions::build_custom_context(&serde_json::json!({"resources": {}}), Some("Bucket"), None);
        execute_custom_rule(&rule, &ctx).expect_err("a custom-rule evaluation error must be fatal");
    }

    #[test]
    fn shared_engine_keeps_concurrent_cel_evaluations_template_local() {
        const THREAD_COUNT: usize = 8;
        const ITERATIONS_PER_THREAD: usize = 128;
        let custom_rule = r#"{"rules": [{
            "rule_id": "CELISOLATIONPROBE",
            "severity": "INFO",
            "resource_type": "Custom::Probe",
            "expression": "properties.Value == \"match\"",
            "message": "{name}"
        }]}"#;
        let engine = Arc::new(
            CelEngine::new(EngineConfig {
                custom_rules: vec![ExternalRuleSource {
                    name: "cel_isolation.json".into(),
                    content: custom_rule.into(),
                }],
                ..Default::default()
            })
            .unwrap(),
        );
        let barrier = Arc::new(std::sync::Barrier::new(THREAD_COUNT));
        let handles: Vec<_> = (0..THREAD_COUNT)
            .map(|index| {
                let engine = Arc::clone(&engine);
                let barrier = Arc::clone(&barrier);
                std::thread::spawn(move || {
                    let resource_name = format!("Probe{index}");
                    let template = format!(
                        "Resources:\n  {resource_name}:\n    Type: Custom::Probe\n    Properties:\n      Value: match\n"
                    );
                    let model = Arc::new(SemanticModel::from_bytes(template.as_bytes()).unwrap());
                    barrier.wait();
                    for _ in 0..ITERATIONS_PER_THREAD {
                        let diagnostics = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
                        let probes: Vec<&Diagnostic> =
                            diagnostics.iter().filter(|diagnostic| diagnostic.rule_id == "CELISOLATIONPROBE").collect();
                        assert_eq!(probes.len(), 1);
                        assert_eq!(probes[0].message, resource_name);
                        assert_eq!(probes[0].resource_logical_id(), Some(resource_name.as_str()));
                    }
                })
            })
            .collect();
        for handle in handles {
            handle.join().unwrap();
        }
    }
}