Skip to main content

rego_engine/
engine.rs

1use crate::eval_context::{EvaluationContext, EvaluationScope, ReferenceRendering, ReferenceRenderingScope};
2use crate::policies;
3use data_source::embedded;
4use data_source::types::KnownResourceTypes;
5use diagnostics::{Diagnostic, PhaseMetric, phase_metric};
6use log::{debug, info};
7use rules::{RuleInfo, RuleMetadataEntry, RuleOrigin, build_rule_metadata_map};
8use schema_validator::{
9    OverlayCatalog, SchemaMetadataCatalog, SchemaValidator, getatt_data_with_overlays,
10    schema_metadata_catalog_with_overlays,
11};
12use std::collections::{HashMap, HashSet};
13use std::str::from_utf8;
14use std::sync::{Arc, LazyLock, Mutex};
15use template_model::SemanticModel;
16use validation_engine::{
17    EngineConfig, GuardRuleSet, ValidateConfig, ValidationEngine, ValidationError, build_rule_list,
18    extract_diagnostics_from_value, semantic_model_to_input_json,
19};
20
21static REGORUS_DATA: LazyLock<Vec<(&str, &[u8])>> = LazyLock::new(|| {
22    vec![
23        (KNOWN_RESOURCE_TYPES_PATH, &*embedded::KNOWN_RESOURCE_TYPES_BYTES),
24        (PRIMARY_IDENTIFIERS_PATH, &*embedded::PRIMARY_IDENTIFIERS_BYTES),
25        ("data/iam_action_resource_patterns", &*embedded::IAM_ACTION_RESOURCE_PATTERNS_BYTES),
26        ("data/stateful_resource_types", &*embedded::STATEFUL_RESOURCE_TYPES_BYTES),
27        ("data/aws_rds_dbinstance_dbinstanceclass_enum", &*embedded::AWS_RDS_DBINSTANCE_DBINSTANCECLASS_ENUM_BYTES),
28        ("data/aws_ec2_instance_instancetype_enum", &*embedded::AWS_EC2_INSTANCE_INSTANCETYPE_ENUM_BYTES),
29        (
30            "data/aws_emr_cluster_instancetypeconfig_instancetype_enum",
31            &*embedded::AWS_EMR_CLUSTER_INSTANCETYPECONFIG_INSTANCETYPE_ENUM_BYTES,
32        ),
33        ("data/aws_gamelift_fleet_ec2instancetype_enum", &*embedded::AWS_GAMELIFT_FLEET_EC2INSTANCETYPE_ENUM_BYTES),
34        ("data/aws_appstream_fleet_instancetype_enum", &*embedded::AWS_APPSTREAM_FLEET_INSTANCETYPE_ENUM_BYTES),
35        ("data/aws_dax_cluster_nodetype_enum", &*embedded::AWS_DAX_CLUSTER_NODETYPE_ENUM_BYTES),
36        ("data/aws_docdb_dbinstance_dbinstanceclass_enum", &*embedded::AWS_DOCDB_DBINSTANCE_DBINSTANCECLASS_ENUM_BYTES),
37        (
38            "data/aws_elasticache_cachecluster_cachenodetype_enum",
39            &*embedded::AWS_ELASTICACHE_CACHECLUSTER_CACHENODETYPE_ENUM_BYTES,
40        ),
41        (
42            "data/aws_managedblockchain_node_nodeconfiguration_instancetype_enum",
43            &*embedded::AWS_MANAGEDBLOCKCHAIN_NODE_NODECONFIGURATION_INSTANCETYPE_ENUM_BYTES,
44        ),
45        (
46            "data/aws_neptune_dbinstance_dbinstanceclass_enum",
47            &*embedded::AWS_NEPTUNE_DBINSTANCE_DBINSTANCECLASS_ENUM_BYTES,
48        ),
49        (
50            "data/aws_rds_dbcluster_dbclusterinstanceclass_enum",
51            &*embedded::AWS_RDS_DBCLUSTER_DBCLUSTERINSTANCECLASS_ENUM_BYTES,
52        ),
53        ("data/aws_rds_dbinstance_db_instance_class", &*embedded::AWS_RDS_DBINSTANCE_DB_INSTANCE_CLASS_BYTES),
54        ("data/aws_redshift_cluster_nodetype_enum", &*embedded::AWS_REDSHIFT_CLUSTER_NODETYPE_ENUM_BYTES),
55        ("data/aws_amazonmq_broker_instancetype_enum", &*embedded::AWS_AMAZONMQ_BROKER_INSTANCETYPE_ENUM_BYTES),
56        (
57            "data/aws_sagemaker_processing_instancetype_enum",
58            &*embedded::AWS_SAGEMAKER_PROCESSING_INSTANCETYPE_ENUM_BYTES,
59        ),
60        ("data/aws_sagemaker_hosting_instancetype_enum", &*embedded::AWS_SAGEMAKER_HOSTING_INSTANCETYPE_ENUM_BYTES),
61        ("data/aws_sagemaker_transform_instancetype_enum", &*embedded::AWS_SAGEMAKER_TRANSFORM_INSTANCETYPE_ENUM_BYTES),
62        ("data/aws_sagemaker_cluster_instancetype_enum", &*embedded::AWS_SAGEMAKER_CLUSTER_INSTANCETYPE_ENUM_BYTES),
63        (
64            "data/aws_elasticsearch_domain_elasticsearchclusterconfig_instancetype_enum",
65            &*embedded::AWS_ELASTICSEARCH_DOMAIN_ELASTICSEARCHCLUSTERCONFIG_INSTANCETYPE_ENUM_BYTES,
66        ),
67        (
68            "data/aws_opensearchservice_domain_clusterconfig_instancetype_enum",
69            &*embedded::AWS_OPENSEARCHSERVICE_DOMAIN_CLUSTERCONFIG_INSTANCETYPE_ENUM_BYTES,
70        ),
71        (GETATT_ATTRIBUTES_PATH, &*embedded::GETATT_ATTRIBUTES_BYTES),
72        ("data/codepipeline_action_artifact_counts", &*embedded::CODEPIPELINE_ACTION_ARTIFACT_COUNTS_BYTES),
73        ("data/deprecated_resource_types", &*embedded::DEPRECATED_RESOURCE_TYPES_BYTES),
74        ("data/retention_period_requirements", &*embedded::RETENTION_PERIOD_REQUIREMENTS_BYTES),
75        ("data/sensitive_ports", &*embedded::SENSITIVE_PORTS_BYTES),
76        ("data/secretsmanager_arn_fields", &*embedded::SECRETSMANAGER_ARN_FIELDS_BYTES),
77        ("data/rule_data", &*embedded::RULE_DATA_BYTES),
78        ("data/rule_tables", &*embedded::RULE_TABLES_BYTES),
79    ]
80});
81
82/// The built-in rule packages, one query each. A package groups rules by
83/// implementation area; the registry, not the package, decides a rule's category.
84const CORE_PACKAGES: &[&str] = &[
85    "data.structure.violation",
86    "data.intrinsics.violation",
87    "data.references.violation",
88    "data.best_practices.violation",
89    "data.resources.violation",
90];
91
92/// The [`REGORUS_DATA`] entry holding the catalog of resource types the rules
93/// treat as existing.
94const KNOWN_RESOURCE_TYPES_PATH: &str = "data/known_resource_types";
95
96/// The [`REGORUS_DATA`] entry holding GetAtt attributes and attribute types.
97const GETATT_ATTRIBUTES_PATH: &str = "data/getatt_attributes";
98
99/// The [`REGORUS_DATA`] entry holding primary identifiers per type.
100const PRIMARY_IDENTIFIERS_PATH: &str = "data/primary_identifiers";
101
102/// Re-serializes the known-resource-type catalog with `extra_types` appended, or
103/// returns `None` when there is nothing to add so the embedded bytes are used
104/// verbatim.
105fn extend_known_resource_types(extra_types: &[String]) -> anyhow::Result<Option<String>> {
106    if extra_types.is_empty() {
107        return Ok(None);
108    }
109    let mut catalog: KnownResourceTypes = serde_json::from_slice(&embedded::KNOWN_RESOURCE_TYPES_BYTES)
110        .map_err(|e| anyhow::anyhow!("Failed to parse the embedded known_resource_types data: {e}"))?;
111    anyhow::ensure!(!catalog.known_resource_types.is_empty(), "Embedded known_resource_types data must not be empty");
112    for type_name in extra_types {
113        if !catalog.known_resource_types.contains(type_name) {
114            catalog.known_resource_types.push(type_name.clone());
115        }
116    }
117    Ok(Some(serde_json::to_string(&catalog)?))
118}
119
120/// Extends the embedded getatt_attributes data with overlay catalog entries.
121/// Returns `None` when there is nothing to add.
122fn extend_getatt_data(catalog: &OverlayCatalog) -> anyhow::Result<Option<String>> {
123    if catalog.getatt_attributes.is_empty() && catalog.getatt_attribute_types.is_empty() {
124        return Ok(None);
125    }
126    let mut data: serde_json::Value = serde_json::from_slice(&embedded::GETATT_ATTRIBUTES_BYTES)
127        .map_err(|e| anyhow::anyhow!("Failed to parse the embedded getatt_attributes data: {e}"))?;
128
129    // Merge getatt_attributes (sort/dedup after merging)
130    if let Some(attrs_obj) = data.get_mut("getatt_attributes").and_then(|v| v.as_object_mut()) {
131        for (type_name, attrs) in &catalog.getatt_attributes {
132            let entry = attrs_obj.entry(type_name.clone()).or_insert_with(|| serde_json::Value::Array(Vec::new()));
133            if let Some(arr) = entry.as_array_mut() {
134                for attr in attrs {
135                    let val = serde_json::Value::String(attr.clone());
136                    if !arr.contains(&val) {
137                        arr.push(val);
138                    }
139                }
140                arr.sort_by(|a, b| a.as_str().unwrap_or("").cmp(b.as_str().unwrap_or("")));
141                arr.dedup();
142            }
143        }
144    }
145
146    // Merge getatt_attribute_types
147    if let Some(types_obj) = data.get_mut("getatt_attribute_types").and_then(|v| v.as_object_mut()) {
148        for (type_name, attr_types) in &catalog.getatt_attribute_types {
149            let entry =
150                types_obj.entry(type_name.clone()).or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
151            if let Some(obj) = entry.as_object_mut() {
152                for (attr, atype) in attr_types {
153                    obj.insert(attr.clone(), serde_json::Value::String(atype.clone()));
154                }
155            }
156        }
157    }
158
159    Ok(Some(serde_json::to_string(&data)?))
160}
161
162/// Extends the embedded primary_identifiers data with overlay catalog entries.
163/// Returns `None` when there is nothing to add.
164fn extend_primary_identifiers_data(catalog: &OverlayCatalog) -> anyhow::Result<Option<String>> {
165    if catalog.primary_identifiers.is_empty() {
166        return Ok(None);
167    }
168    let mut data: serde_json::Value = serde_json::from_slice(&embedded::PRIMARY_IDENTIFIERS_BYTES)
169        .map_err(|e| anyhow::anyhow!("Failed to parse the embedded primary_identifiers data: {e}"))?;
170
171    if let Some(pids_obj) = data.get_mut("primary_identifiers").and_then(|v| v.as_object_mut()) {
172        for (type_name, pids) in &catalog.primary_identifiers {
173            pids_obj.insert(type_name.clone(), serde_json::json!(pids));
174        }
175    }
176
177    Ok(Some(serde_json::to_string(&data)?))
178}
179
180/// Whether an engine instance loads and evaluates the handwritten built-in
181/// policies, or serves only caller-supplied external rules.
182///
183/// In [`BuiltinRuleMode::ExternalOnly`] the built-in policies are neither loaded
184/// nor advertised through registry metadata, so the engine evaluates only custom
185/// and Guard rules. Embedded data tables, custom builtins, and external-rule
186/// metadata are retained in both modes.
187#[derive(Clone, Copy, PartialEq, Eq)]
188enum BuiltinRuleMode {
189    Enabled,
190    ExternalOnly,
191}
192
193/// Who authored a Rego package, which fixes the contract its rules were written
194/// against: how its diagnostics are attributed and how the resolution builtins
195/// render a reference while it evaluates.
196#[derive(Clone, Copy)]
197enum PolicyPackageKind {
198    /// A handwritten built-in policy shipped with the engine.
199    BuiltIn,
200    /// A caller-supplied custom rule.
201    Custom,
202}
203
204impl PolicyPackageKind {
205    fn source_label(self) -> &'static str {
206        match self {
207            Self::BuiltIn => "Core",
208            Self::Custom => "Custom",
209        }
210    }
211
212    /// The origin stamped on the package's diagnostics; a built-in rule keeps the
213    /// origin the registry records for it.
214    fn rule_origin_override(self) -> Option<&'static RuleOrigin> {
215        match self {
216            Self::BuiltIn => None,
217            Self::Custom => Some(&RuleOrigin::Custom),
218        }
219    }
220
221    /// Built-in policies validate literal content and must never see a logical ID
222    /// where a value belongs. Custom rules keep the logical-ID string they were
223    /// written against, so upgrading the engine does not change what they report.
224    fn reference_rendering(self) -> ReferenceRendering {
225        match self {
226            Self::BuiltIn => ReferenceRendering::Marker,
227            Self::Custom => ReferenceRendering::TargetId,
228        }
229    }
230}
231
232pub struct RegoEngine {
233    base_rego: regorus::Engine,
234    /// Whether the handwritten built-in policies are evaluated, or only the
235    /// caller-supplied external rules.
236    builtin_mode: BuiltinRuleMode,
237    /// Built-in rule metadata from the rules registry only.
238    registry_metadata: HashMap<String, RuleMetadataEntry>,
239    /// Custom rego rule metadata discovered from evaluation output.
240    /// Rego rules embed metadata in their output objects, so it can only
241    /// be extracted after evaluation. May be incomplete if not all rules fired.
242    discovered_custom_metadata: Mutex<HashMap<String, RuleMetadataEntry>>,
243    custom_packages: Vec<String>,
244    /// Guard rules are evaluated by the shared Guard evaluator, not by Rego, so
245    /// every engine reports the same Guard findings.
246    guard_rules: Option<GuardRuleSet>,
247    init_metric: PhaseMetric,
248}
249
250impl RegoEngine {
251    pub fn new(config: EngineConfig) -> anyhow::Result<Self> {
252        let overlay_catalog =
253            config.build_overlay_catalog().map_err(|e| anyhow::anyhow!("Failed to build overlay catalog: {e}"))?;
254        let start = web_time::Instant::now();
255        let schema_metadata = schema_metadata_catalog_with_overlays(&overlay_catalog)?;
256        Self::new_from_parts(config, &overlay_catalog, schema_metadata, BuiltinRuleMode::Enabled, start)
257    }
258
259    /// Constructs the engine reusing metadata from an already-built
260    /// [`SchemaValidator`](schema_validator::SchemaValidator). The validator's
261    /// overlay catalog is treated as authoritative - the engine does not
262    /// re-resolve overlay schemas.
263    ///
264    /// This entry point is intended for language bindings and the CLI, which
265    /// construct a `SchemaValidator` once and share it with the engine. The
266    /// validator's shared schema-metadata catalog is reused rather than rebuilt,
267    /// so every engine built from the same validator shares one catalog rather
268    /// than rebuilding it.
269    #[doc(hidden)]
270    pub fn new_with_schema_validator(config: EngineConfig, validator: &SchemaValidator) -> anyhow::Result<Self> {
271        let start = web_time::Instant::now();
272        let schema_metadata = validator.schema_metadata_catalog()?;
273        Self::new_from_parts(config, validator.overlay_catalog(), schema_metadata, BuiltinRuleMode::Enabled, start)
274    }
275
276    /// Constructs an engine that evaluates only the caller-supplied custom and
277    /// Guard rules, without loading or advertising the handwritten built-in
278    /// policies. Embedded data tables and custom builtins remain available so
279    /// external rules can call them.
280    ///
281    /// This backs the composite engine, whose built-in rules are owned by a
282    /// separate engine; loading them here too would double-evaluate them.
283    pub fn new_external_only(config: EngineConfig) -> anyhow::Result<Self> {
284        let overlay_catalog =
285            config.build_overlay_catalog().map_err(|e| anyhow::anyhow!("Failed to build overlay catalog: {e}"))?;
286        let start = web_time::Instant::now();
287        let schema_metadata = schema_metadata_catalog_with_overlays(&overlay_catalog)?;
288        Self::new_from_parts(config, &overlay_catalog, schema_metadata, BuiltinRuleMode::ExternalOnly, start)
289    }
290
291    /// External-only counterpart to [`RegoEngine::new_with_schema_validator`],
292    /// reusing an already-built validator's overlay catalog and shared
293    /// schema-metadata catalog.
294    #[doc(hidden)]
295    pub fn new_external_only_with_schema_validator(
296        config: EngineConfig,
297        validator: &SchemaValidator,
298    ) -> anyhow::Result<Self> {
299        let start = web_time::Instant::now();
300        let schema_metadata = validator.schema_metadata_catalog()?;
301        Self::new_from_parts(config, validator.overlay_catalog(), schema_metadata, BuiltinRuleMode::ExternalOnly, start)
302    }
303
304    /// Internal constructor that accepts a pre-built overlay catalog and the
305    /// shared schema-metadata catalog resolved for it.
306    fn new_from_parts(
307        config: EngineConfig,
308        overlay_catalog: &OverlayCatalog,
309        schema_metadata: Arc<SchemaMetadataCatalog>,
310        builtin_mode: BuiltinRuleMode,
311        start: web_time::Instant,
312    ) -> anyhow::Result<Self> {
313        let mut rego = regorus::Engine::new();
314        rego.set_strict_builtin_errors(false);
315
316        // Single-pass merge avoids per-file JSON parsing overhead.
317        {
318            // Resource types introduced by an overlay schema are legitimate
319            // targets, so the type catalog the rules consult must include them
320            // rather than reporting them as nonexistent.
321            let overlay_types: Vec<String> = overlay_catalog.type_names.clone();
322            let extended_known_types = extend_known_resource_types(&overlay_types)?;
323
324            // Extend getatt_attributes data with overlay entries
325            let extended_getatt = extend_getatt_data(overlay_catalog)?;
326            // Extend primary_identifiers data with overlay entries
327            let extended_primary_ids = extend_primary_identifiers_data(overlay_catalog)?;
328
329            // Embedded lengths closely size the common no-overlay path; extended
330            // overlay documents can grow the buffer normally when they are larger.
331            let merged_capacity: usize = REGORUS_DATA.iter().map(|(_, json_bytes)| json_bytes.len()).sum();
332            let mut merged = String::with_capacity(merged_capacity);
333            merged.push('{');
334            for (i, (path, json_bytes)) in REGORUS_DATA.iter().enumerate() {
335                let json_str = match (
336                    *path,
337                    extended_known_types.as_deref(),
338                    extended_getatt.as_deref(),
339                    extended_primary_ids.as_deref(),
340                ) {
341                    (KNOWN_RESOURCE_TYPES_PATH, Some(extended), _, _) => extended,
342                    (GETATT_ATTRIBUTES_PATH, _, Some(extended), _) => extended,
343                    (PRIMARY_IDENTIFIERS_PATH, _, _, Some(extended)) => extended,
344                    _ => from_utf8(json_bytes).map_err(|error| {
345                        anyhow::anyhow!("Embedded JSON data '{}' is not valid UTF-8: {}", path, error)
346                    })?,
347                };
348                let inner = json_str
349                    .trim()
350                    .strip_prefix('{')
351                    .and_then(|value| value.strip_suffix('}'))
352                    .ok_or_else(|| anyhow::anyhow!("Embedded JSON data '{}' must be a top-level object", path))?;
353                anyhow::ensure!(!inner.trim().is_empty(), "Embedded JSON data '{}' must not be empty", path);
354                if i > 0 {
355                    merged.push(',');
356                }
357                merged.push_str(inner);
358            }
359            merged.push('}');
360            rego.add_data(regorus::Value::from_json_str(&merged)?)?;
361        }
362
363        // In external-only mode the built-in policies are owned by a separate
364        // engine, so they are neither loaded nor evaluated here. Embedded data,
365        // custom builtins, custom Rego, and Guard rules are still loaded below
366        // regardless of mode.
367        let handwritten_rule_count = match builtin_mode {
368            BuiltinRuleMode::Enabled => {
369                for (path, source) in policies::HANDWRITTEN_REGO_POLICIES {
370                    rego.add_policy(path.to_string(), source.to_string())?;
371                }
372                policies::HANDWRITTEN_REGO_POLICIES.len()
373            }
374            BuiltinRuleMode::ExternalOnly => 0,
375        };
376        debug!("Loaded {} data files, {} handwritten rules", REGORUS_DATA.len(), handwritten_rule_count);
377
378        let guard_rules = GuardRuleSet::compile(&config.guard_rules).map_err(|error| anyhow::anyhow!(error))?;
379
380        for entry in &config.custom_rules {
381            rego.add_policy(entry.name.clone(), entry.content.clone())?;
382        }
383        let mut custom_packages = Vec::new();
384        for entry in &config.custom_rules {
385            for line in entry.content.lines() {
386                let trimmed = line.trim();
387                if let Some(pkg) = trimmed.strip_prefix("package ") {
388                    let eval_path = format!("data.{}.violation", pkg.trim());
389                    if !custom_packages.contains(&eval_path) {
390                        custom_packages.push(eval_path);
391                    }
392                }
393            }
394        }
395
396        // The GetAtt return-type table is the process-wide one the schema store
397        // shares, layered with this engine's overlays; resolving it here keeps the
398        // parse off the first template without giving the engine its own copy.
399        let getatt = getatt_data_with_overlays(overlay_catalog)?;
400        crate::builtins::register_all(&mut rego, schema_metadata, getatt)?;
401
402        // External-only construction advertises no built-in rules; their
403        // metadata belongs to the engine that owns the built-in policies.
404        let registry_metadata = match builtin_mode {
405            BuiltinRuleMode::Enabled => build_rule_metadata_map(),
406            BuiltinRuleMode::ExternalOnly => HashMap::new(),
407        };
408
409        // Every evaluation clones `rego`, and a clone inherits the prepared state
410        // (analysis, scheduling, and loop hoisting of every loaded policy). Preparing
411        // once here keeps that cost out of every evaluation; without it an engine
412        // that loads only external rules would re-analyze the whole custom rule set
413        // for each template. A trivial query prepares the engine without evaluating
414        // any rule body, so it applies equally to both built-in modes. A preparation
415        // failure is not swallowed: the first real evaluation reports it.
416        let _ = rego.eval_query("true".to_string(), false);
417
418        info!(
419            "RegoEngine initialized: {} handwritten rules, {} data files, {} registry + {} Guard metadata entries",
420            handwritten_rule_count,
421            REGORUS_DATA.len(),
422            registry_metadata.len(),
423            guard_rules.as_ref().map_or(0, |guard| guard.rule_metadata().len())
424        );
425        let init_metric = phase_metric(start);
426        Ok(RegoEngine {
427            base_rego: rego,
428            builtin_mode,
429            registry_metadata,
430            discovered_custom_metadata: Mutex::new(HashMap::new()),
431            custom_packages,
432            guard_rules,
433            init_metric,
434        })
435    }
436
437    /// Evaluates a single Rego package and appends its diagnostics to `out`.
438    ///
439    /// The package's [`ReferenceRendering`] is in effect only while its query
440    /// runs: Regorus discards memoized rule and builtin results between queries,
441    /// so a value rendered for one package never reaches the next.
442    ///
443    /// Any evaluation or serialization failure is returned as a structured
444    /// [`ValidationError`] - an exception the caller can handle - and is never
445    /// converted into a diagnostic. A rule that fails to run must surface as an
446    /// error, not masquerade as a finding.
447    fn eval_package_into(
448        &self,
449        rego: &mut regorus::Engine,
450        package: &str,
451        kind: PolicyPackageKind,
452        model: &SemanticModel,
453        out: &mut Vec<Diagnostic>,
454    ) -> Result<(), ValidationError> {
455        let source_label = kind.source_label();
456        let _rendering = ReferenceRenderingScope::enter(kind.reference_rendering());
457        let value = rego.eval_rule(package.to_string()).map_err(|e| {
458            ValidationError::Engine(format!("{source_label} rule package '{package}' failed to evaluate: {e}"))
459        })?;
460        let diagnostics_json = serde_json::to_value(&value).map_err(|e| {
461            ValidationError::Engine(format!(
462                "{source_label} rule package '{package}' produced a result that could not be \
463                 serialized to JSON: {e}"
464            ))
465        })?;
466        extract_diagnostics_from_value(&diagnostics_json, model, out, kind.rule_origin_override())
467            .map_err(ValidationError::from)
468    }
469
470    /// The built-in rule IDs that global filtering proves cannot survive under
471    /// `config`, so their handwritten clauses can stop at the `cfn_rule_active`
472    /// guard before doing any work. Only rules the registry defines are eligible;
473    /// custom and guard rules are never globally suppressed here.
474    fn globally_suppressed_builtin_rules(&self, config: &ValidateConfig) -> Arc<HashSet<String>> {
475        let suppressed: HashSet<String> = self
476            .registry_metadata
477            .iter()
478            .filter(|(rule_id, entry)| {
479                config.filters.globally_suppresses_builtin_rule(
480                    rule_id,
481                    entry.category.as_deref(),
482                    entry.severity,
483                    config.strict,
484                    config.severity_level,
485                )
486            })
487            .map(|(rule_id, _)| rule_id.clone())
488            .collect();
489        Arc::new(suppressed)
490    }
491}
492
493impl ValidationEngine for RegoEngine {
494    fn engine_name(&self) -> &str {
495        "rego"
496    }
497
498    fn evaluate_rules(
499        &self,
500        model: &Arc<SemanticModel>,
501        config: &ValidateConfig,
502    ) -> Result<Vec<Diagnostic>, ValidationError> {
503        let context = EvaluationContext::new(
504            model.clone(),
505            config.pseudo_parameter_overrides.region.clone(),
506            self.globally_suppressed_builtin_rules(config),
507        );
508        let _scope = EvaluationScope::enter(context);
509
510        let mut rego = self.base_rego.clone();
511
512        let input_json = semantic_model_to_input_json(model)?;
513        let input_value = crate::builtins::serde_json_to_rego_value(&input_json);
514        rego.set_input(input_value);
515
516        let mut diagnostics = Vec::new();
517
518        // Core built-in policies run only when this engine owns them and the
519        // caller has not disabled built-ins. The custom and Guard evaluation
520        // below runs unconditionally so external rules are always evaluated.
521        let evaluate_builtins = matches!(self.builtin_mode, BuiltinRuleMode::Enabled) && !config.disable_builtin_rules;
522        if evaluate_builtins {
523            // Every package is evaluated whatever the category filters say. The
524            // packages group rules by implementation area, not by registry
525            // category - security and parameter rules live in `best_practices`
526            // and `structure` - so skipping a package for one excluded category
527            // would drop its rules of every other category. Each clause instead
528            // stops at its `cfn_rule_active` guard, which the evaluation context
529            // above feeds from the registry category of every rule, so an
530            // excluded rule costs one builtin call. The packages share no rules,
531            // so one query per package costs the same as one aggregated query.
532            for package in CORE_PACKAGES {
533                self.eval_package_into(&mut rego, package, PolicyPackageKind::BuiltIn, model, &mut diagnostics)?;
534            }
535        }
536
537        for pkg in &self.custom_packages {
538            self.eval_package_into(&mut rego, pkg, PolicyPackageKind::Custom, model, &mut diagnostics)?;
539        }
540
541        if let Some(guard_rules) = &self.guard_rules {
542            diagnostics.extend(guard_rules.evaluate(model)?);
543        }
544
545        if !self.custom_packages.is_empty() {
546            let mut discovered = self.discovered_custom_metadata.lock().unwrap_or_else(|e| e.into_inner());
547            for d in &diagnostics {
548                if d.source == RuleOrigin::Custom {
549                    discovered.entry(d.rule_id.clone()).or_insert_with(|| RuleMetadataEntry {
550                        category: d.category.clone(),
551                        description: d.message.clone(),
552                        severity: d.severity,
553                        origin: RuleOrigin::Custom,
554                    });
555                }
556            }
557        }
558
559        Ok(diagnostics)
560    }
561
562    fn list_rules(&self) -> Vec<RuleInfo> {
563        build_rule_list(&self.registry_metadata, &self.external_rule_metadata())
564    }
565
566    fn rule_metadata(&self) -> &HashMap<String, RuleMetadataEntry> {
567        &self.registry_metadata
568    }
569
570    /// Returns Guard rule metadata merged with any custom Rego rule metadata
571    /// discovered from prior evaluations. Custom diagnostics already carry their
572    /// current evaluation's rule description, so this accumulated metadata cannot
573    /// overwrite a later report.
574    fn external_rule_metadata(&self) -> HashMap<String, RuleMetadataEntry> {
575        let mut merged = self.guard_rules.as_ref().map(|guard| guard.rule_metadata().clone()).unwrap_or_default();
576        if !self.custom_packages.is_empty() {
577            let discovered = self.discovered_custom_metadata.lock().unwrap_or_else(|e| e.into_inner());
578            merged.extend(discovered.iter().map(|(k, v)| (k.clone(), v.clone())));
579        }
580        merged
581    }
582
583    fn init_metric(&self) -> &PhaseMetric {
584        &self.init_metric
585    }
586}
587
588#[cfg(test)]
589mod tests {
590    use super::*;
591    use diagnostics::DetailLevel;
592    use rules::{Category, FilterConfig, RuleFilterConfig, Severity, lookup_rule};
593    use std::sync::Barrier;
594    use std::thread;
595    use template_model::SemanticModel;
596    use validation_engine::{EngineConfig, ExternalRuleSource, ValidateConfig, ValidationEngine, validate_bytes};
597
598    fn make_engine() -> RegoEngine {
599        RegoEngine::new(EngineConfig::default()).unwrap()
600    }
601
602    fn make_model_from_yaml(yaml: &str) -> Arc<SemanticModel> {
603        let model = SemanticModel::from_bytes(yaml.as_bytes()).unwrap();
604        Arc::new(model)
605    }
606
607    #[test]
608    fn new_default_config_succeeds() {
609        let engine = make_engine();
610        assert_eq!(engine.engine_name(), "rego");
611    }
612
613    #[test]
614    fn list_rules_returns_nonempty() {
615        let engine = make_engine();
616        let rules = engine.list_rules();
617        assert!(!rules.is_empty(), "should have built-in rules");
618    }
619
620    #[test]
621    fn rule_metadata_contains_entries() {
622        let engine = make_engine();
623        assert!(!engine.rule_metadata().is_empty());
624    }
625
626    #[test]
627    fn init_metric_has_positive_duration() {
628        let engine = make_engine();
629        let metric = engine.init_metric();
630        assert!(metric.duration_ms > 0.0, "init duration should be > 0, got {}", metric.duration_ms);
631    }
632
633    #[test]
634    fn evaluate_minimal_template_no_errors() {
635        let engine = make_engine();
636        let model = make_model_from_yaml(
637            r#"
638AWSTemplateFormatVersion: "2010-09-09"
639Resources:
640  MyBucket:
641    Type: AWS::S3::Bucket
642"#,
643        );
644        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
645        assert!(
646            diags.iter().all(|d| d.severity != Severity::Fatal),
647            "rego engine should not produce Fatal diagnostics"
648        );
649    }
650
651    #[test]
652    fn evaluate_empty_resources_does_not_panic() {
653        let engine = make_engine();
654        let model = make_model_from_yaml(
655            r#"
656AWSTemplateFormatVersion: "2010-09-09"
657Resources: {}
658"#,
659        );
660        // CloudFormation rejects templates with empty Resources, so the empty-resources diagnostic is expected.
661        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
662        assert!(
663            diags.iter().any(|d| d.rule_id == "F0001"),
664            "expected F0001 Fatal for empty Resources section, got: {:?}",
665            diags.iter().map(|d| &d.rule_id).collect::<Vec<_>>(),
666        );
667    }
668
669    /// Excluding a category must remove exactly the rules the registry files
670    /// under it. The `best_practices` package also hosts security rules, so a
671    /// package-level skip would wrongly drop them along with the best-practice
672    /// rules; the template fires one of each from that package.
673    #[test]
674    fn evaluate_with_excluded_categories() {
675        let engine = make_engine();
676        let model = make_model_from_yaml(
677            r#"
678AWSTemplateFormatVersion: "2010-09-09"
679Resources:
680  Permission:
681    Type: AWS::Lambda::Permission
682    Properties:
683      Action: lambda:InvokeFunction
684      FunctionName: my-function
685      Principal: sns.amazonaws.com
686      SourceArn: arn:aws:sns:us-east-1:123456789012:my-topic
687"#,
688        );
689        fn rule_ids(diags: &[Diagnostic]) -> HashSet<&str> {
690            diags.iter().map(|d| d.rule_id.as_str()).collect()
691        }
692        let diags_all = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
693        let all_ids = rule_ids(&diags_all);
694        assert!(all_ids.contains("W9002"), "sanity: the best-practice hardcoded-ARN rule fires: {all_ids:?}");
695        assert!(all_ids.contains("W9013"), "sanity: the security hardcoded-account-ID rule fires: {all_ids:?}");
696
697        let excluded = Category::BestPractice;
698        let config = ValidateConfig {
699            filters: FilterConfig::new(
700                RuleFilterConfig::default(),
701                RuleFilterConfig { categories: vec![excluded.as_str().to_string()], ..Default::default() },
702            ),
703            ..Default::default()
704        };
705        let diags_filtered = engine.evaluate_rules(&model, &config).unwrap();
706        let filtered_ids = rule_ids(&diags_filtered);
707
708        let expected_ids: HashSet<&str> =
709            all_ids.iter().copied().filter(|id| lookup_rule(id).is_none_or(|rule| rule.category != excluded)).collect();
710        assert_eq!(filtered_ids, expected_ids, "only rules the registry files under {excluded:?} may disappear");
711        assert!(!filtered_ids.contains("W9002"), "the excluded best-practice rule is gone");
712        assert!(filtered_ids.contains("W9013"), "the security rule hosted in the same package survives");
713    }
714
715    #[test]
716    fn custom_rego_rule_produces_diagnostics() {
717        let custom_rego = r#"
718package custom_test
719import rego.v1
720
721violation contains v if {
722    some name, res in input.resources
723    res.resourceType == "AWS::S3::Bucket"
724    v := {"rule_id": "CUSTOM001", "severity": "error", "message": "Custom rule fired", "resource_id": name}
725}
726"#;
727        let config = EngineConfig {
728            custom_rules: vec![ExternalRuleSource { name: "custom_test.rego".into(), content: custom_rego.into() }],
729            guard_rules: vec![],
730            ..Default::default()
731        };
732        let engine = RegoEngine::new(config).unwrap();
733        let model = make_model_from_yaml(
734            r#"
735AWSTemplateFormatVersion: "2010-09-09"
736Resources:
737  MyBucket:
738    Type: AWS::S3::Bucket
739"#,
740        );
741        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
742        let custom = diags.iter().find(|d| d.rule_id == "CUSTOM001");
743        assert!(custom.is_some(), "custom rule should fire");
744    }
745
746    #[test]
747    fn guard_rule_produces_diagnostics() {
748        let guard_source = r#"
749rule check_bucket_name {
750    AWS::S3::Bucket {
751        Properties.BucketName EXISTS
752        <<BucketName must be specified>>
753    }
754}
755"#;
756        let config = EngineConfig {
757            custom_rules: vec![],
758            guard_rules: vec![ExternalRuleSource { name: "test.guard".into(), content: guard_source.into() }],
759            ..Default::default()
760        };
761        let engine = RegoEngine::new(config).unwrap();
762        let model = make_model_from_yaml(
763            r#"
764AWSTemplateFormatVersion: "2010-09-09"
765Resources:
766  MyBucket:
767    Type: AWS::S3::Bucket
768"#,
769        );
770        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
771        let guard_diag = diags.iter().find(|d| d.rule_id == "check_bucket_name").expect("guard rule fires");
772        assert_eq!(guard_diag.source, RuleOrigin::Guard);
773        assert_eq!(guard_diag.category.as_deref(), Some("guard:test"));
774        assert_eq!(guard_diag.message, "BucketName must be specified");
775        assert_eq!(guard_diag.resource_logical_id(), Some("MyBucket"));
776    }
777
778    #[test]
779    fn guard_rule_exists_check_does_not_fire_when_property_is_present() {
780        let guard_source = r#"
781rule check_bucket_name {
782    AWS::S3::Bucket {
783        Properties.BucketName EXISTS
784        <<BucketName must be specified>>
785    }
786}
787"#;
788        let config = EngineConfig {
789            custom_rules: vec![],
790            guard_rules: vec![ExternalRuleSource { name: "test.guard".into(), content: guard_source.into() }],
791            ..Default::default()
792        };
793        let engine = RegoEngine::new(config).unwrap();
794        let model = make_model_from_yaml(
795            r#"
796AWSTemplateFormatVersion: "2010-09-09"
797Resources:
798  MyBucket:
799    Type: AWS::S3::Bucket
800    Properties:
801      BucketName: my-bucket
802"#,
803        );
804        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
805        let guard_diag = diags.iter().find(|d| d.rule_id == "check_bucket_name");
806        assert!(
807            guard_diag.is_none(),
808            "guard EXISTS must be satisfied when BucketName is present, so the rule must not fire; got: {:?}",
809            diags.iter().map(|d| &d.rule_id).collect::<Vec<_>>()
810        );
811    }
812
813    #[test]
814    fn external_only_engine_evaluates_external_rules_but_skips_builtins() {
815        let custom_rego = r#"
816package external_only_test
817import rego.v1
818
819violation contains v if {
820    v := {"rule_id": "EXT_ONLY", "severity": "error", "message": "external rule fired", "resource_id": ""}
821}
822"#;
823        let config = EngineConfig {
824            custom_rules: vec![ExternalRuleSource {
825                name: "external_only_test.rego".into(),
826                content: custom_rego.into(),
827            }],
828            guard_rules: vec![],
829            ..Default::default()
830        };
831        let engine = RegoEngine::new_external_only(config).unwrap();
832        assert!(engine.rule_metadata().is_empty(), "an external-only engine must advertise no built-in registry rules");
833
834        // An empty Resources section makes a normal engine emit a built-in
835        // structural diagnostic, so its absence proves the built-ins were
836        // skipped rather than simply not triggered.
837        let model = make_model_from_yaml(
838            r#"
839AWSTemplateFormatVersion: "2010-09-09"
840Resources: {}
841"#,
842        );
843        let normal_diags = RegoEngine::new(EngineConfig::default())
844            .unwrap()
845            .evaluate_rules(&model, &ValidateConfig::default())
846            .unwrap();
847        assert!(
848            normal_diags.iter().any(|d| d.rule_id == "F0001"),
849            "a normal engine must emit the built-in F0001 for empty Resources"
850        );
851
852        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
853        let external = diags.iter().find(|d| d.rule_id == "EXT_ONLY").expect("the external rule must still evaluate");
854        assert_eq!(external.severity, Severity::Error);
855        assert_eq!(external.source, RuleOrigin::Custom);
856        assert!(
857            diags.iter().all(|d| d.rule_id == "EXT_ONLY"),
858            "external-only evaluation must produce no built-in diagnostics, got: {:?}",
859            diags.iter().map(|d| &d.rule_id).collect::<Vec<_>>()
860        );
861        assert!(
862            !engine.list_rules().iter().any(|r| r.id == "F0001"),
863            "external-only list_rules must not include built-in rule IDs"
864        );
865    }
866
867    #[test]
868    fn external_only_engine_registers_custom_builtin_helpers() {
869        let custom_rego = r#"
870package external_builtin_test
871import rego.v1
872
873violation contains make_diag("EXT_BUILTINS", "error", name, "custom builtins available") if {
874    some name in resources_of_type("AWS::S3::Bucket")
875    has_property(name, "BucketName")
876    resolve(name, "Properties.BucketName") == "custom-builtins-bucket"
877    "BucketName" in schema_properties("AWS::S3::Bucket")
878}
879"#;
880        let engine = RegoEngine::new_external_only(EngineConfig {
881            custom_rules: vec![ExternalRuleSource {
882                name: "external_builtin_test.rego".into(),
883                content: custom_rego.into(),
884            }],
885            ..Default::default()
886        })
887        .expect("external-only engine must initialize with custom builtins");
888        let model = make_model_from_yaml(
889            r#"
890Resources:
891  Bucket:
892    Type: AWS::S3::Bucket
893    Properties:
894      BucketName: custom-builtins-bucket
895"#,
896        );
897
898        let diagnostics = engine.evaluate_rules(&model, &ValidateConfig::default()).expect("custom rule must evaluate");
899        let finding = diagnostics
900            .iter()
901            .find(|diagnostic| diagnostic.rule_id == "EXT_BUILTINS")
902            .expect("custom rule using resource, resolution, schema, and diagnostic helpers must fire");
903        assert_eq!(finding.source, RuleOrigin::Custom);
904        assert_eq!(finding.resource_logical_id(), Some("Bucket"));
905    }
906
907    #[test]
908    fn evaluate_rules_can_be_called_repeatedly() {
909        let engine = make_engine();
910        let model = make_model_from_yaml(
911            r#"
912AWSTemplateFormatVersion: "2010-09-09"
913Resources:
914  A:
915    Type: AWS::S3::Bucket
916"#,
917        );
918        // The per-thread evaluation context is installed and torn down each call,
919        // so repeated evaluations on one thread neither deadlock nor leak state.
920        let _ = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
921        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
922        assert!(
923            diags.iter().all(|d| d.severity != Severity::Fatal),
924            "rego engine should not produce Fatal diagnostics"
925        );
926    }
927
928    #[test]
929    fn build_rule_metadata_map_returns_entries() {
930        let index = build_rule_metadata_map();
931        assert!(!index.is_empty());
932    }
933
934    const BUILTIN_TEST_TEMPLATE: &str = r#"
935AWSTemplateFormatVersion: "2010-09-09"
936Parameters:
937  Env:
938    Type: String
939    AllowedValues:
940      - prod
941      - dev
942  Port:
943    Type: Number
944Conditions:
945  IsProd:
946    Fn::Equals:
947      - !Ref Env
948      - prod
949Mappings:
950  RegionMap:
951    us-east-1:
952      AMI: ami-12345678
953    us-west-2:
954      AMI: ami-abcdefgh
955Resources:
956  MyBucket:
957    Type: AWS::S3::Bucket
958    Properties:
959      BucketName: my-bucket
960      Tags:
961        - Key: Env
962          Value: !If [IsProd, "production", "development"]
963  MyFunc:
964    Type: AWS::Lambda::Function
965    DependsOn: MyBucket
966    Condition: IsProd
967    Properties:
968      FunctionName: my-func
969      Runtime: python3.12
970      Handler: index.handler
971      Code:
972        S3Bucket: !Ref MyBucket
973        S3Key: code.zip
974      VpcConfig:
975        SecurityGroupIds:
976          - sg-0123456789abcdef0
977        SubnetIds:
978          - !Ref MySubnet
979          - subnet-0123456789abcdef0
980  MyVpc:
981    Type: AWS::EC2::VPC
982    Properties:
983      CidrBlock: 10.0.0.0/16
984  MySubnet:
985    Type: AWS::EC2::Subnet
986    Properties:
987      VpcId: !Ref MyVpc
988      CidrBlock: 10.0.0.0/24
989  MyQueue:
990    Type: AWS::SQS::Queue
991    Properties:
992      QueueName: my-queue
993Transform: AWS::Serverless-2016-10-31
994"#;
995
996    fn eval_builtin_policy(rego_source: &str, rule_id: &str) -> Vec<Diagnostic> {
997        let config = EngineConfig {
998            custom_rules: vec![ExternalRuleSource { name: "builtin_test.rego".into(), content: rego_source.into() }],
999            guard_rules: vec![],
1000            ..Default::default()
1001        };
1002        let engine = RegoEngine::new(config).unwrap();
1003        let model = make_model_from_yaml(BUILTIN_TEST_TEMPLATE);
1004        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
1005        diags.into_iter().filter(|d| d.rule_id == rule_id).collect()
1006    }
1007
1008    #[test]
1009    fn builtin_resolve_returns_property_value() {
1010        let diags = eval_builtin_policy(
1011            r#"
1012package builtin_test
1013import rego.v1
1014violation contains v if {
1015    val := resolve("MyBucket", "BucketName")
1016    val == "my-bucket"
1017    v := {"rule_id": "B_RESOLVE", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1018}
1019"#,
1020            "B_RESOLVE",
1021        );
1022        assert_eq!(diags.len(), 1, "resolve should return 'my-bucket'");
1023    }
1024
1025    #[test]
1026    fn builtin_resolve_all_returns_conditional_values() {
1027        let diags = eval_builtin_policy(
1028            r#"
1029package builtin_test
1030import rego.v1
1031violation contains v if {
1032    vals := resolve_all("MyBucket", "Tags.0.Value")
1033    count(vals) >= 1
1034    v := {"rule_id": "B_RESOLVE_ALL", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1035}
1036"#,
1037            "B_RESOLVE_ALL",
1038        );
1039        assert_eq!(diags.len(), 1, "resolve_all should return at least one value");
1040    }
1041
1042    /// The contract custom rules were written against: `resolve` on a `Ref` or
1043    /// `Fn::GetAtt` yields the target's logical ID as a string, so a rule can look
1044    /// the target up in `input.resources` or compare it with another logical ID.
1045    const LEGACY_REFERENCE_CUSTOM_RULE: &str = r#"
1046package legacy_reference_test
1047import rego.v1
1048
1049violation contains make_diag("LEGACY_LOOKUP", "error", name, sprintf("code bucket is %s", [target])) if {
1050    some name in resources_of_type("AWS::Lambda::Function")
1051    target := resolve(name, "Properties.Code.S3Bucket")
1052    is_string(target)
1053    input.resources[target].resourceType == "AWS::S3::Bucket"
1054}
1055
1056violation contains make_diag("LEGACY_EQUALS", "error", name, "code lives in MyBucket") if {
1057    some name in resources_of_type("AWS::Lambda::Function")
1058    resolve(name, "Properties.Code.S3Bucket") == "MyBucket"
1059}
1060
1061violation contains make_diag("LEGACY_MARKER_SEEN", "error", name, "resolve returned the marker object") if {
1062    some name in resources_of_type("AWS::Lambda::Function")
1063    is_object(resolve(name, "Properties.Code.S3Bucket"))
1064}
1065"#;
1066
1067    fn assert_legacy_reference_contract(diags: &[Diagnostic]) {
1068        let lookup = diags
1069            .iter()
1070            .find(|d| d.rule_id == "LEGACY_LOOKUP")
1071            .expect("resolve() must hand back a logical ID a rule can look up in input.resources");
1072        assert_eq!(lookup.message, "code bucket is MyBucket");
1073        assert_eq!(lookup.resource_logical_id(), Some("MyFunc"));
1074        assert!(
1075            diags.iter().any(|d| d.rule_id == "LEGACY_EQUALS"),
1076            "resolve() must compare equal to the target's logical ID"
1077        );
1078        assert!(
1079            !diags.iter().any(|d| d.rule_id == "LEGACY_MARKER_SEEN"),
1080            "a custom rule must never see the marker object from resolve()"
1081        );
1082    }
1083
1084    #[test]
1085    fn custom_rule_resolve_keeps_the_legacy_target_id_string_for_a_reference() {
1086        let engine = RegoEngine::new(EngineConfig {
1087            custom_rules: vec![ExternalRuleSource {
1088                name: "legacy_reference_test.rego".into(),
1089                content: LEGACY_REFERENCE_CUSTOM_RULE.into(),
1090            }],
1091            ..Default::default()
1092        })
1093        .unwrap();
1094        let model = make_model_from_yaml(BUILTIN_TEST_TEMPLATE);
1095
1096        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
1097
1098        assert_legacy_reference_contract(&diags);
1099    }
1100
1101    #[test]
1102    fn external_only_engine_keeps_the_legacy_target_id_string_for_a_reference() {
1103        let engine = RegoEngine::new_external_only(EngineConfig {
1104            custom_rules: vec![ExternalRuleSource {
1105                name: "legacy_reference_test.rego".into(),
1106                content: LEGACY_REFERENCE_CUSTOM_RULE.into(),
1107            }],
1108            ..Default::default()
1109        })
1110        .unwrap();
1111        let model = make_model_from_yaml(BUILTIN_TEST_TEMPLATE);
1112
1113        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
1114
1115        assert_legacy_reference_contract(&diags);
1116    }
1117
1118    #[test]
1119    fn custom_rule_resolve_all_list_items_keep_the_legacy_target_id_string() {
1120        let diags = eval_builtin_policy(
1121            r#"
1122package builtin_test
1123import rego.v1
1124violation contains make_diag("LEGACY_LIST_ITEM", "error", "MyFunc", sprintf("subnets: %v", [subnets])) if {
1125    some subnets in resolve_all("MyFunc", "Properties.VpcConfig.SubnetIds")
1126    subnets == ["MySubnet", "subnet-0123456789abcdef0"]
1127}
1128"#,
1129            "LEGACY_LIST_ITEM",
1130        );
1131        assert_eq!(diags.len(), 1, "a referenced list item must come back as the target's logical ID");
1132    }
1133
1134    /// Both kinds of package evaluate on one Regorus engine instance, so the
1135    /// rendering must switch per package: the built-in policies fixed to skip a
1136    /// reference they would otherwise judge as a literal must keep doing so while
1137    /// the custom package beside them still receives the legacy string.
1138    #[test]
1139    fn builtin_policies_keep_the_marker_rendering_while_a_custom_rule_gets_the_legacy_string() {
1140        let engine = RegoEngine::new(EngineConfig {
1141            custom_rules: vec![ExternalRuleSource {
1142                name: "legacy_reference_test.rego".into(),
1143                content: LEGACY_REFERENCE_CUSTOM_RULE.into(),
1144            }],
1145            ..Default::default()
1146        })
1147        .unwrap();
1148        let model = make_model_from_yaml(
1149            r#"
1150AWSTemplateFormatVersion: "2010-09-09"
1151Resources:
1152  Store:
1153    Type: AWS::SSM::Parameter
1154    Properties:
1155      Type: String
1156      Value: placeholder
1157  MyBucket:
1158    Type: AWS::S3::Bucket
1159  Distribution:
1160    Type: AWS::CloudFront::Distribution
1161    Properties:
1162      DistributionConfig:
1163        Enabled: true
1164        Aliases:
1165          - !GetAtt Store.Value
1166        DefaultCacheBehavior:
1167          TargetOriginId: primary
1168          ViewerProtocolPolicy: redirect-to-https
1169          ForwardedValues:
1170            QueryString: false
1171        Origins:
1172          - Id: primary
1173            DomainName: origin.example.com
1174            CustomOriginConfig:
1175              OriginProtocolPolicy: https-only
1176  MyFunc:
1177    Type: AWS::Lambda::Function
1178    Properties:
1179      Runtime: python3.12
1180      Handler: index.handler
1181      Role: arn:aws:iam::123456789012:role/lambda-role
1182      Code:
1183        S3Bucket: !Ref MyBucket
1184        S3Key: code.zip
1185"#,
1186        );
1187
1188        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
1189
1190        assert!(
1191            !diags.iter().any(|d| d.rule_id == "E3013"),
1192            "the built-in alias check must not judge the logical ID 'Store' as a domain name: {:?}",
1193            diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
1194        );
1195        assert_legacy_reference_contract(&diags);
1196    }
1197
1198    #[test]
1199    fn builtin_is_dynamic_on_conditional_property() {
1200        let diags = eval_builtin_policy(
1201            r#"
1202package builtin_test
1203import rego.v1
1204violation contains v if {
1205    is_dynamic("MyFunc", "Code.S3Bucket")
1206    v := {"rule_id": "B_IS_DYN", "severity": "error", "message": "ok", "resource_id": "MyFunc"}
1207}
1208"#,
1209            "B_IS_DYN",
1210        );
1211        assert_eq!(diags.len(), 1, "Code.S3Bucket is a Ref → dynamic");
1212    }
1213
1214    #[test]
1215    fn builtin_is_dynamic_false_for_static() {
1216        let diags = eval_builtin_policy(
1217            r#"
1218package builtin_test
1219import rego.v1
1220violation contains v if {
1221    not is_dynamic("MyBucket", "BucketName")
1222    v := {"rule_id": "B_NOT_DYN", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1223}
1224"#,
1225            "B_NOT_DYN",
1226        );
1227        assert_eq!(diags.len(), 1, "BucketName is static");
1228    }
1229
1230    #[test]
1231    fn builtin_resources_of_type() {
1232        let diags = eval_builtin_policy(
1233            r#"
1234package builtin_test
1235import rego.v1
1236violation contains v if {
1237    ids := resources_of_type("AWS::S3::Bucket")
1238    count(ids) == 1
1239    v := {"rule_id": "B_ROT", "severity": "error", "message": "ok", "resource_id": ""}
1240}
1241"#,
1242            "B_ROT",
1243        );
1244        assert_eq!(diags.len(), 1, "should find 1 S3 bucket");
1245    }
1246
1247    #[test]
1248    fn builtin_has_property_true() {
1249        let diags = eval_builtin_policy(
1250            r#"
1251package builtin_test
1252import rego.v1
1253violation contains v if {
1254    has_property("MyBucket", "BucketName")
1255    v := {"rule_id": "B_HAS_P", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1256}
1257"#,
1258            "B_HAS_P",
1259        );
1260        assert_eq!(diags.len(), 1, "MyBucket has BucketName");
1261    }
1262
1263    #[test]
1264    fn builtin_has_property_false() {
1265        let diags = eval_builtin_policy(
1266            r#"
1267package builtin_test
1268import rego.v1
1269violation contains v if {
1270    not has_property("MyBucket", "NonExistent")
1271    v := {"rule_id": "B_NO_P", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1272}
1273"#,
1274            "B_NO_P",
1275        );
1276        assert_eq!(diags.len(), 1, "MyBucket does not have NonExistent");
1277    }
1278
1279    #[test]
1280    fn builtin_has_transform() {
1281        let diags = eval_builtin_policy(
1282            r#"
1283package builtin_test
1284import rego.v1
1285violation contains v if {
1286    has_transform("AWS::Serverless-2016-10-31")
1287    v := {"rule_id": "B_HAS_T", "severity": "error", "message": "ok", "resource_id": ""}
1288}
1289"#,
1290            "B_HAS_T",
1291        );
1292        assert_eq!(diags.len(), 1, "template has Serverless transform");
1293    }
1294
1295    #[test]
1296    fn builtin_param_allowed_values() {
1297        let diags = eval_builtin_policy(
1298            r#"
1299package builtin_test
1300import rego.v1
1301violation contains v if {
1302    vals := param_allowed_values("Env")
1303    count(vals) == 2
1304    v := {"rule_id": "B_PAV", "severity": "error", "message": "ok", "resource_id": ""}
1305}
1306"#,
1307            "B_PAV",
1308        );
1309        assert_eq!(diags.len(), 1, "Env has 2 allowed values");
1310    }
1311
1312    #[test]
1313    fn builtin_param_type() {
1314        let diags = eval_builtin_policy(
1315            r#"
1316package builtin_test
1317import rego.v1
1318violation contains v if {
1319    t := param_type("Port")
1320    t == "Number"
1321    v := {"rule_id": "B_PT", "severity": "error", "message": "ok", "resource_id": ""}
1322}
1323"#,
1324            "B_PT",
1325        );
1326        assert_eq!(diags.len(), 1, "Port param type is Number");
1327    }
1328
1329    #[test]
1330    fn builtin_mapping_value() {
1331        let diags = eval_builtin_policy(
1332            r#"
1333package builtin_test
1334import rego.v1
1335violation contains v if {
1336    val := mapping_value("RegionMap", "us-east-1", "AMI")
1337    val == "ami-12345678"
1338    v := {"rule_id": "B_MAP", "severity": "error", "message": "ok", "resource_id": ""}
1339}
1340"#,
1341            "B_MAP",
1342        );
1343        assert_eq!(diags.len(), 1, "mapping lookup should return ami-12345678");
1344    }
1345
1346    #[test]
1347    fn builtin_resource_condition() {
1348        let diags = eval_builtin_policy(
1349            r#"
1350package builtin_test
1351import rego.v1
1352violation contains v if {
1353    c := resource_condition("MyFunc")
1354    c == "IsProd"
1355    v := {"rule_id": "B_RC", "severity": "error", "message": "ok", "resource_id": "MyFunc"}
1356}
1357"#,
1358            "B_RC",
1359        );
1360        assert_eq!(diags.len(), 1, "MyFunc has condition IsProd");
1361    }
1362
1363    #[test]
1364    fn builtin_resource_condition_null_when_none() {
1365        let diags = eval_builtin_policy(
1366            r#"
1367package builtin_test
1368import rego.v1
1369violation contains v if {
1370    c := resource_condition("MyBucket")
1371    is_null(c)
1372    v := {"rule_id": "B_RC_NULL", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1373}
1374"#,
1375            "B_RC_NULL",
1376        );
1377        assert_eq!(diags.len(), 1, "MyBucket has no condition");
1378    }
1379
1380    #[test]
1381    fn builtin_get_resource() {
1382        let diags = eval_builtin_policy(
1383            r#"
1384package builtin_test
1385import rego.v1
1386violation contains v if {
1387    res := get_resource("MyBucket")
1388    res.resourceType == "AWS::S3::Bucket"
1389    v := {"rule_id": "B_GR", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1390}
1391"#,
1392            "B_GR",
1393        );
1394        assert_eq!(diags.len(), 1, "get_resource should return bucket data");
1395    }
1396
1397    #[test]
1398    fn builtin_depends_on() {
1399        let diags = eval_builtin_policy(
1400            r#"
1401package builtin_test
1402import rego.v1
1403violation contains v if {
1404    depends_on("MyFunc", "MyBucket")
1405    v := {"rule_id": "B_DEP", "severity": "error", "message": "ok", "resource_id": "MyFunc"}
1406}
1407"#,
1408            "B_DEP",
1409        );
1410        assert_eq!(diags.len(), 1, "MyFunc depends on MyBucket");
1411    }
1412
1413    #[test]
1414    fn builtin_ref_targets() {
1415        let diags = eval_builtin_policy(
1416            r#"
1417package builtin_test
1418import rego.v1
1419violation contains v if {
1420    targets := ref_targets("MyFunc")
1421    count(targets) > 0
1422    v := {"rule_id": "B_RT", "severity": "error", "message": "ok", "resource_id": "MyFunc"}
1423}
1424"#,
1425            "B_RT",
1426        );
1427        assert_eq!(diags.len(), 1, "MyFunc should have ref targets (MyBucket)");
1428    }
1429
1430    #[test]
1431    fn builtin_ref_sources() {
1432        let diags = eval_builtin_policy(
1433            r#"
1434package builtin_test
1435import rego.v1
1436violation contains v if {
1437    sources := ref_sources("MyBucket")
1438    count(sources) > 0
1439    v := {"rule_id": "B_RS", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1440}
1441"#,
1442            "B_RS",
1443        );
1444        assert_eq!(diags.len(), 1, "MyBucket should have ref sources (MyFunc)");
1445    }
1446
1447    #[test]
1448    fn builtin_edges_from() {
1449        let diags = eval_builtin_policy(
1450            r#"
1451package builtin_test
1452import rego.v1
1453violation contains v if {
1454    edges := edges_from("MyFunc")
1455    count(edges) > 0
1456    v := {"rule_id": "B_EF", "severity": "error", "message": "ok", "resource_id": "MyFunc"}
1457}
1458"#,
1459            "B_EF",
1460        );
1461        assert_eq!(diags.len(), 1, "MyFunc should have outgoing edges");
1462    }
1463
1464    #[test]
1465    fn builtin_edges_to() {
1466        let diags = eval_builtin_policy(
1467            r#"
1468package builtin_test
1469import rego.v1
1470violation contains v if {
1471    edges := edges_to("MyBucket")
1472    count(edges) > 0
1473    v := {"rule_id": "B_ET", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1474}
1475"#,
1476            "B_ET",
1477        );
1478        assert_eq!(diags.len(), 1, "MyBucket should have incoming edges");
1479    }
1480
1481    #[test]
1482    fn builtin_make_diag_at() {
1483        let diags = eval_builtin_policy(
1484            r#"
1485package builtin_test
1486import rego.v1
1487violation contains v if {
1488    v := make_diag_at("B_MDA", "error", "MyBucket", "BucketName", "test diag at")
1489}
1490"#,
1491            "B_MDA",
1492        );
1493        assert_eq!(diags.len(), 1);
1494        assert_eq!(diags[0].message, "test diag at");
1495    }
1496
1497    #[test]
1498    fn builtin_make_diag_full() {
1499        let diags = eval_builtin_policy(
1500            r#"
1501package builtin_test
1502import rego.v1
1503violation contains v if {
1504    v := make_diag_full("B_MDF", "error", "MyBucket", "BucketName", "full diag", "fix it", "https://example.com")
1505}
1506"#,
1507            "B_MDF",
1508        );
1509        assert_eq!(diags.len(), 1);
1510        assert_eq!(diags[0].message, "full diag");
1511    }
1512
1513    #[test]
1514    fn builtin_schema_properties_known_type() {
1515        let diags = eval_builtin_policy(
1516            r#"
1517package builtin_test
1518import rego.v1
1519violation contains v if {
1520    props := schema_properties("AWS::S3::Bucket")
1521    # Just verify the builtin is callable and returns an array
1522    is_array(props)
1523    v := {"rule_id": "B_SP", "severity": "error", "message": "ok", "resource_id": ""}
1524}
1525"#,
1526            "B_SP",
1527        );
1528        assert_eq!(diags.len(), 1, "schema_properties should be callable and return array");
1529    }
1530
1531    #[test]
1532    fn builtin_schema_required_known_type() {
1533        let diags = eval_builtin_policy(
1534            r#"
1535package builtin_test
1536import rego.v1
1537violation contains v if {
1538    req := schema_required("AWS::Lambda::Function")
1539    is_array(req)
1540    v := {"rule_id": "B_SR", "severity": "error", "message": "ok", "resource_id": ""}
1541}
1542"#,
1543            "B_SR",
1544        );
1545        assert_eq!(diags.len(), 1, "schema_required should be callable and return array");
1546    }
1547
1548    #[test]
1549    fn builtin_conditions_compatible() {
1550        let diags = eval_builtin_policy(
1551            r#"
1552package builtin_test
1553import rego.v1
1554violation contains v if {
1555    conditions_compatible("MyBucket", "MyQueue")
1556    v := {"rule_id": "B_CC", "severity": "error", "message": "ok", "resource_id": ""}
1557}
1558"#,
1559            "B_CC",
1560        );
1561        assert_eq!(diags.len(), 1, "unconditional resources are always compatible");
1562    }
1563
1564    #[test]
1565    fn builtin_resolve_type() {
1566        let diags = eval_builtin_policy(
1567            r#"
1568package builtin_test
1569import rego.v1
1570violation contains v if {
1571    t := resolve_type("MyBucket", "BucketName")
1572    t == "string"
1573    v := {"rule_id": "B_RTYPE", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1574}
1575"#,
1576            "B_RTYPE",
1577        );
1578        assert_eq!(diags.len(), 1, "BucketName should resolve to string type");
1579    }
1580
1581    #[test]
1582    fn region_override_available_to_builtins() {
1583        let custom_rego = r#"
1584package region_test
1585import rego.v1
1586violation contains v if {
1587    r := input_region()
1588    r == "eu-west-1"
1589    v := {"rule_id": "B_REGION", "severity": "error", "message": "ok", "resource_id": ""}
1590}
1591"#;
1592        let config = EngineConfig {
1593            custom_rules: vec![ExternalRuleSource { name: "region_test.rego".into(), content: custom_rego.into() }],
1594            guard_rules: vec![],
1595            ..Default::default()
1596        };
1597        let engine = RegoEngine::new(config).unwrap();
1598        let model = make_model_from_yaml(BUILTIN_TEST_TEMPLATE);
1599        let mut vc = ValidateConfig::default();
1600        vc.pseudo_parameter_overrides.region = Some("eu-west-1".to_string());
1601        let diags = engine.evaluate_rules(&model, &vc).unwrap();
1602        let found = diags.iter().find(|d| d.rule_id == "B_REGION");
1603        assert!(found.is_some(), "input_region() should return eu-west-1");
1604    }
1605
1606    #[test]
1607    fn multiple_custom_packages_all_evaluated() {
1608        let pkg_a = r#"
1609package custom_a
1610import rego.v1
1611violation contains v if {
1612    v := {"rule_id": "PKG_A", "severity": "error", "message": "from A", "resource_id": ""}
1613}
1614"#;
1615        let pkg_b = r#"
1616package custom_b
1617import rego.v1
1618violation contains v if {
1619    v := {"rule_id": "PKG_B", "severity": "error", "message": "from B", "resource_id": ""}
1620}
1621"#;
1622        let config = EngineConfig {
1623            custom_rules: vec![
1624                ExternalRuleSource { name: "a.rego".into(), content: pkg_a.into() },
1625                ExternalRuleSource { name: "b.rego".into(), content: pkg_b.into() },
1626            ],
1627            guard_rules: vec![],
1628            ..Default::default()
1629        };
1630        let engine = RegoEngine::new(config).unwrap();
1631        let model = make_model_from_yaml(BUILTIN_TEST_TEMPLATE);
1632        let diags = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
1633        assert!(diags.iter().any(|d| d.rule_id == "PKG_A"), "package A should fire");
1634        assert!(diags.iter().any(|d| d.rule_id == "PKG_B"), "package B should fire");
1635    }
1636
1637    #[test]
1638    fn duplicate_custom_package_deduplicated() {
1639        let source = r#"
1640package custom_dedup
1641import rego.v1
1642violation contains v if {
1643    v := {"rule_id": "DEDUP1", "severity": "error", "message": "first", "resource_id": ""}
1644}
1645"#;
1646        let config = EngineConfig {
1647            custom_rules: vec![
1648                ExternalRuleSource { name: "a.rego".into(), content: source.into() },
1649                ExternalRuleSource { name: "b.rego".into(), content: source.into() },
1650            ],
1651            guard_rules: vec![],
1652            ..Default::default()
1653        };
1654        let engine = RegoEngine::new(config).unwrap();
1655        assert_eq!(
1656            engine.custom_packages.iter().filter(|p| p.contains("custom_dedup")).count(),
1657            1,
1658            "duplicate package should be deduplicated"
1659        );
1660    }
1661
1662    #[test]
1663    fn builtin_follow_ref_returns_target_resource() {
1664        let diags = eval_builtin_policy(
1665            r#"
1666package builtin_test
1667import rego.v1
1668violation contains v if {
1669    target := follow_ref("MyFunc", "Code.S3Bucket")
1670    target == "MyBucket"
1671    v := {"rule_id": "B_FREF", "severity": "error", "message": "ok", "resource_id": "MyFunc"}
1672}
1673"#,
1674            "B_FREF",
1675        );
1676        assert_eq!(diags.len(), 1, "follow_ref should resolve Ref to MyBucket");
1677    }
1678
1679    #[test]
1680    fn builtin_is_from_parameter_true_for_ref_param() {
1681        let diags = eval_builtin_policy(
1682            r#"
1683package builtin_test
1684import rego.v1
1685violation contains v if {
1686    is_from_parameter("MyBucket", "Tags.0.Value")
1687    v := {"rule_id": "B_IFP", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1688}
1689"#,
1690            "B_IFP",
1691        );
1692        // Tags.0.Value uses Fn::If with a condition based on a parameter, so it's from a parameter
1693        assert!(diags.len() <= 1, "expected at most 1 diagnostic, got {}", diags.len());
1694    }
1695
1696    #[test]
1697    fn builtin_flatten_list_returns_items() {
1698        let diags = eval_builtin_policy(
1699            r#"
1700package builtin_test
1701import rego.v1
1702violation contains v if {
1703    items := flatten_list("MyBucket", "Tags")
1704    count(items) >= 1
1705    v := {"rule_id": "B_FL", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1706}
1707"#,
1708            "B_FL",
1709        );
1710        assert_eq!(diags.len(), 1, "flatten_list should return tag items");
1711    }
1712
1713    #[test]
1714    fn builtin_resolve_scenarios_returns_values() {
1715        let diags = eval_builtin_policy(
1716            r#"
1717package builtin_test
1718import rego.v1
1719violation contains v if {
1720    scenarios := resolve_scenarios("MyBucket", "Tags.0.Value")
1721    count(scenarios) >= 1
1722    v := {"rule_id": "B_RS2", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1723}
1724"#,
1725            "B_RS2",
1726        );
1727        assert_eq!(diags.len(), 1, "resolve_scenarios should return at least one scenario");
1728    }
1729
1730    #[test]
1731    fn builtin_is_satisfiable_with_compatible_assumptions() {
1732        let diags = eval_builtin_policy(
1733            r#"
1734package builtin_test
1735import rego.v1
1736violation contains v if {
1737    is_satisfiable({"IsProd": true})
1738    v := {"rule_id": "B_SAT", "severity": "error", "message": "ok", "resource_id": ""}
1739}
1740"#,
1741            "B_SAT",
1742        );
1743        assert_eq!(diags.len(), 1, "IsProd=true should be satisfiable");
1744    }
1745
1746    #[test]
1747    fn builtin_make_diag_produces_diagnostic() {
1748        let diags = eval_builtin_policy(
1749            r#"
1750package builtin_test
1751import rego.v1
1752violation contains v if {
1753    v := make_diag("B_MD", "error", "MyBucket", "test message")
1754}
1755"#,
1756            "B_MD",
1757        );
1758        assert_eq!(diags.len(), 1);
1759        assert_eq!(diags[0].message, "test message");
1760    }
1761
1762    #[test]
1763    fn builtin_estimated_string_length_bounds_returns_both_bounds() {
1764        // `!If [IsProd, "production", "development"]` - the deployment picks one of
1765        // two known values, so the length is bounded but not fixed.
1766        let diags = eval_builtin_policy(
1767            r#"
1768package builtin_test
1769import rego.v1
1770violation contains v if {
1771    bounds := estimated_string_length_bounds("MyBucket", "Tags.0.Value")
1772    bounds.shortest == 10
1773    bounds.longest == 11
1774    v := {"rule_id": "B_ESL", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1775}
1776"#,
1777            "B_ESL",
1778        );
1779        assert_eq!(diags.len(), 1, "a value chosen between two known strings must report both bounds");
1780    }
1781
1782    #[test]
1783    fn builtin_estimated_string_length_bounds_is_undefined_for_a_literal() {
1784        // Schema validation checks a literal against the constraint, so this rule
1785        // is not given one to estimate.
1786        let diags = eval_builtin_policy(
1787            r#"
1788package builtin_test
1789import rego.v1
1790violation contains v if {
1791    bounds := estimated_string_length_bounds("MyBucket", "BucketName")
1792    v := {"rule_id": "B_ESL_LITERAL", "severity": "error", "message": "ok", "resource_id": "MyBucket"}
1793}
1794"#,
1795            "B_ESL_LITERAL",
1796        );
1797        assert!(diags.is_empty(), "a literal string must yield no bounds, got {diags:?}");
1798    }
1799
1800    #[test]
1801    fn regoengine_is_send_and_sync() {
1802        fn assert_send_sync<T: Send + Sync>() {}
1803        assert_send_sync::<RegoEngine>();
1804    }
1805
1806    #[test]
1807    fn evaluate_rules_isolates_model_and_region_across_threads() {
1808        // One engine, many threads, each with a distinct model and region. The
1809        // probes echo the region and the resource names the thread should see, so
1810        // any leakage between threads' evaluation contexts surfaces as a mismatch.
1811        let probe = r#"
1812package concurrency_probe
1813import rego.v1
1814violation contains v if {
1815    r := input_region()
1816    v := {"rule_id": "REGIONPROBE", "severity": "info", "message": r, "resource_id": ""}
1817}
1818violation contains v if {
1819    some name in resources_of_type("AWS::S3::Bucket")
1820    v := {"rule_id": "MODELPROBE", "severity": "info", "message": name, "resource_id": name}
1821}
1822violation contains v if {
1823    some name, _ in input.resources
1824    v := {"rule_id": "INPUTPROBE", "severity": "info", "message": name, "resource_id": name}
1825}
1826"#;
1827        let config = EngineConfig {
1828            custom_rules: vec![ExternalRuleSource { name: "concurrency_probe.rego".into(), content: probe.into() }],
1829            guard_rules: vec![],
1830            ..Default::default()
1831        };
1832        let engine = Arc::new(RegoEngine::new(config).unwrap());
1833
1834        const THREAD_COUNT: usize = 8;
1835        const ITERATIONS_PER_THREAD: usize = 128;
1836        let barrier = Arc::new(Barrier::new(THREAD_COUNT));
1837        let handles: Vec<_> = (0..THREAD_COUNT)
1838            .map(|i| {
1839                let engine = Arc::clone(&engine);
1840                let barrier = Arc::clone(&barrier);
1841                thread::spawn(move || {
1842                    let region = format!("region-{i}");
1843                    let bucket = format!("Bucket{i}");
1844                    let model = make_model_from_yaml(&format!(
1845                        "AWSTemplateFormatVersion: \"2010-09-09\"\nResources:\n  {bucket}:\n    Type: AWS::S3::Bucket\n"
1846                    ));
1847                    let mut config = ValidateConfig::default();
1848                    config.pseudo_parameter_overrides.region = Some(region.clone());
1849                    // Release every thread at once so their evaluations overlap.
1850                    barrier.wait();
1851                    let mut diagnostics = Vec::new();
1852                    for _ in 0..ITERATIONS_PER_THREAD {
1853                        diagnostics = engine.evaluate_rules(&model, &config).unwrap();
1854                        let observed_regions: Vec<&str> = diagnostics
1855                            .iter()
1856                            .filter(|diagnostic| diagnostic.rule_id == "REGIONPROBE")
1857                            .map(|diagnostic| diagnostic.message.as_str())
1858                            .collect();
1859                        assert_eq!(observed_regions, vec![region.as_str()]);
1860                        let observed_resources: Vec<&str> = diagnostics
1861                            .iter()
1862                            .filter(|diagnostic| diagnostic.rule_id == "MODELPROBE")
1863                            .map(|diagnostic| diagnostic.message.as_str())
1864                            .collect();
1865                        assert_eq!(observed_resources, vec![bucket.as_str()]);
1866                        let observed_input_resources: Vec<&str> = diagnostics
1867                            .iter()
1868                            .filter(|diagnostic| diagnostic.rule_id == "INPUTPROBE")
1869                            .map(|diagnostic| diagnostic.message.as_str())
1870                            .collect();
1871                        assert_eq!(observed_input_resources, vec![bucket.as_str()]);
1872                    }
1873                    (region, bucket, diagnostics)
1874                })
1875            })
1876            .collect();
1877
1878        for handle in handles {
1879            let (region, bucket, diags) = handle.join().unwrap();
1880            let regions: Vec<&str> =
1881                diags.iter().filter(|d| d.rule_id == "REGIONPROBE").map(|d| d.message.as_str()).collect();
1882            assert_eq!(regions, vec![region.as_str()], "a thread must observe only its own region");
1883            let resources: Vec<&str> =
1884                diags.iter().filter(|d| d.rule_id == "MODELPROBE").map(|d| d.message.as_str()).collect();
1885            assert_eq!(resources, vec![bucket.as_str()], "a thread must observe only its own model");
1886            let input_resources: Vec<&str> =
1887                diags.iter().filter(|d| d.rule_id == "INPUTPROBE").map(|d| d.message.as_str()).collect();
1888            assert_eq!(input_resources, vec![bucket.as_str()], "a thread must observe only its own Rego input");
1889        }
1890    }
1891
1892    #[test]
1893    fn shared_engine_keeps_thousand_sequential_reports_template_local() {
1894        const CUSTOM_RULE: &str = r#"
1895package sequential_isolation
1896import rego.v1
1897
1898violation contains v if {
1899    pattern := input.template.description
1900    some name, resource in input.resources
1901    regex.match(pattern, resource.properties.Value)
1902    region := input_region()
1903    message := sprintf("%s/%s", [name, region])
1904    v := {
1905        "rule_id": "SEQUENTIALPROBE",
1906        "severity": "info",
1907        "category": "isolation",
1908        "message": message,
1909        "resource_id": name,
1910    }
1911}
1912"#;
1913        let engine = RegoEngine::new(EngineConfig {
1914            custom_rules: vec![ExternalRuleSource {
1915                name: "sequential_isolation.rego".into(),
1916                content: CUSTOM_RULE.into(),
1917            }],
1918            ..Default::default()
1919        })
1920        .unwrap();
1921        let schema_validator = SchemaValidator::default();
1922
1923        for iteration in 0..1_000 {
1924            let (resource_name, region, pattern, value) = if iteration % 2 == 0 {
1925                ("AlphaResource", "alpha-region", "^alpha+$", "alpha")
1926            } else {
1927                ("BetaResource", "beta-region", "^beta+$", "beta")
1928            };
1929            let template = format!(
1930                r#"{{
1931                    "AWSTemplateFormatVersion": "2010-09-09",
1932                    "Description": "{pattern}",
1933                    "Resources": {{
1934                        "{resource_name}": {{
1935                            "Type": "Custom::Probe",
1936                            "Properties": {{"Value": "{value}"}}
1937                        }}
1938                    }}
1939                }}"#
1940            );
1941            let mut config = ValidateConfig {
1942                detail_level: DetailLevel::Detailed,
1943                severity_level: Severity::Debug,
1944                disable_builtin_rules: true,
1945                ..Default::default()
1946            };
1947            config.pseudo_parameter_overrides.region = Some(region.to_string());
1948
1949            let report = validate_bytes(&engine, &schema_validator, template.as_bytes(), config).unwrap();
1950            let probes: Vec<&Diagnostic> =
1951                report.diagnostics.iter().filter(|diagnostic| diagnostic.rule_id == "SEQUENTIALPROBE").collect();
1952            assert_eq!(probes.len(), 1, "iteration {iteration} must emit exactly one probe diagnostic");
1953            let expected_message = format!("{resource_name}/{region}");
1954            assert_eq!(probes[0].message, expected_message, "the current template supplies the diagnostic message");
1955            assert_eq!(
1956                probes[0].rule_description.as_deref(),
1957                Some(expected_message.as_str()),
1958                "the current template supplies its own detailed rule description"
1959            );
1960            assert_eq!(probes[0].category.as_deref(), Some("isolation"));
1961        }
1962    }
1963
1964    #[test]
1965    fn failed_evaluation_does_not_contaminate_the_next_call() {
1966        const CUSTOM_RULE: &str = r#"
1967package error_cleanup
1968import rego.v1
1969
1970violation contains v if {
1971    input.template.description == "error"
1972    ip_overlaps("not-a-cidr", "10.0.0.0/8")
1973    v := {"rule_id": "UNREACHABLE", "severity": "error", "message": "unreachable"}
1974}
1975
1976violation contains v if {
1977    input.template.description == "ok"
1978    some name in resources_of_type("Custom::Probe")
1979    region := input_region()
1980    v := {
1981        "rule_id": "RECOVERYPROBE",
1982        "severity": "info",
1983        "message": sprintf("%s/%s", [name, region]),
1984        "resource_id": name,
1985    }
1986}
1987"#;
1988        let engine = RegoEngine::new(EngineConfig {
1989            custom_rules: vec![ExternalRuleSource { name: "error_cleanup.rego".into(), content: CUSTOM_RULE.into() }],
1990            ..Default::default()
1991        })
1992        .unwrap();
1993        let error_model =
1994            make_model_from_yaml("Description: error\nResources:\n  ErrorResource:\n    Type: Custom::Probe\n");
1995        let valid_model =
1996            make_model_from_yaml("Description: ok\nResources:\n  ValidResource:\n    Type: Custom::Probe\n");
1997        let mut error_config = ValidateConfig { disable_builtin_rules: true, ..Default::default() };
1998        error_config.pseudo_parameter_overrides.region = Some("error-region".to_string());
1999        assert!(engine.evaluate_rules(&error_model, &error_config).is_err(), "the first evaluation must fail");
2000
2001        let mut valid_config = ValidateConfig { disable_builtin_rules: true, ..Default::default() };
2002        valid_config.pseudo_parameter_overrides.region = Some("valid-region".to_string());
2003        let diagnostics = engine.evaluate_rules(&valid_model, &valid_config).unwrap();
2004        let recovery: Vec<&Diagnostic> =
2005            diagnostics.iter().filter(|diagnostic| diagnostic.rule_id == "RECOVERYPROBE").collect();
2006        assert_eq!(recovery.len(), 1, "the next evaluation must recover after the prior error");
2007        assert_eq!(recovery[0].message, "ValidResource/valid-region");
2008    }
2009
2010    const SUPPRESSION_TEMPLATE: &str = r#"
2011AWSTemplateFormatVersion: "2010-09-09"
2012Resources:
2013  MyInstance:
2014    Type: AWS::EC2::Instance
2015    Properties:
2016      ImageId: ami-12345678
2017      InstanceType: !Sub "t3.micro"
2018"#;
2019
2020    fn exclude_ids(ids: &[&str]) -> ValidateConfig {
2021        ValidateConfig {
2022            filters: FilterConfig::new(
2023                RuleFilterConfig::default(),
2024                RuleFilterConfig { ids: ids.iter().map(|s| s.to_string()).collect(), ..Default::default() },
2025            ),
2026            ..Default::default()
2027        }
2028    }
2029
2030    #[test]
2031    fn exclude_id_suppresses_matching_builtin_and_preserves_other_findings() {
2032        let engine = make_engine();
2033        let model = make_model_from_yaml(SUPPRESSION_TEMPLATE);
2034
2035        let unfiltered = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
2036        assert!(unfiltered.iter().any(|d| d.rule_id == "W9010"), "hardcoded AMI should trigger W9010");
2037        let mut other_findings: Vec<(String, String)> = unfiltered
2038            .iter()
2039            .filter(|d| d.rule_id != "W9010")
2040            .map(|d| (d.rule_id.clone(), d.message.clone()))
2041            .collect();
2042        assert!(!other_findings.is_empty(), "template must also produce a non-W9010 finding worth preserving");
2043        other_findings.sort();
2044
2045        let filtered = engine.evaluate_rules(&model, &exclude_ids(&["W9010"])).unwrap();
2046        assert!(filtered.iter().all(|d| d.rule_id != "W9010"), "the excluded rule must not be emitted");
2047        let mut remaining: Vec<(String, String)> =
2048            filtered.iter().map(|d| (d.rule_id.clone(), d.message.clone())).collect();
2049        remaining.sort();
2050        assert_eq!(remaining, other_findings, "excluding one rule must not alter any other diagnostic");
2051
2052        let unfiltered_again = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
2053        assert!(
2054            unfiltered_again.iter().any(|diagnostic| diagnostic.rule_id == "W9010"),
2055            "a later unfiltered call must not inherit the previous call's suppressed-rule set"
2056        );
2057    }
2058
2059    #[test]
2060    fn include_id_globally_suppresses_every_other_builtin() {
2061        let engine = make_engine();
2062        let model = make_model_from_yaml(SUPPRESSION_TEMPLATE);
2063
2064        let config = ValidateConfig {
2065            filters: FilterConfig::new(
2066                RuleFilterConfig { ids: vec!["W9010".to_string()], ..Default::default() },
2067                RuleFilterConfig::default(),
2068            ),
2069            ..Default::default()
2070        };
2071        let filtered = engine.evaluate_rules(&model, &config).unwrap();
2072        assert!(filtered.iter().any(|d| d.rule_id == "W9010"), "the included rule must still fire");
2073        assert!(
2074            filtered.iter().all(|d| d.rule_id == "W9010"),
2075            "a non-empty include filter must globally suppress every rule it can never admit"
2076        );
2077    }
2078
2079    #[test]
2080    fn severity_level_prunes_lower_severity_builtins() {
2081        let engine = make_engine();
2082        let model = make_model_from_yaml(SUPPRESSION_TEMPLATE);
2083
2084        let default_run = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
2085        assert!(default_run.iter().any(|d| d.rule_id == "W9010"), "W9010 fires at the default Info level");
2086
2087        let config = ValidateConfig { severity_level: Severity::Error, ..Default::default() };
2088        let error_only = engine.evaluate_rules(&model, &config).unwrap();
2089        assert!(
2090            error_only.iter().all(|d| d.severity >= Severity::Error),
2091            "no sub-Error diagnostics should be produced when the level is Error"
2092        );
2093        assert!(
2094            error_only.iter().all(|d| d.rule_id != "W9010"),
2095            "the Warn rule W9010 must be pruned at the Error level"
2096        );
2097    }
2098
2099    #[test]
2100    fn cfn_rule_active_guard_short_circuits_a_suppressed_rule_body() {
2101        // Every built-in clause is shaped like this probe: cfn_rule_active guards
2102        // the body, so a globally suppressed rule stops before its body runs. The
2103        // body here would evaluate regex.match on an invalid pattern if reached;
2104        // the probe diagnostic is the observable signal that the body executed.
2105        let probe = r#"
2106package guard_probe
2107import rego.v1
2108violation contains v if {
2109    cfn_rule_active("W9010")
2110    not regex.match("(unterminated", "anything")
2111    v := {"rule_id": "GUARDPROBE", "severity": "error", "message": "guarded body ran", "resource_id": ""}
2112}
2113"#;
2114        let config = EngineConfig {
2115            custom_rules: vec![ExternalRuleSource { name: "guard_probe.rego".into(), content: probe.into() }],
2116            guard_rules: vec![],
2117            ..Default::default()
2118        };
2119        let engine = RegoEngine::new(config).unwrap();
2120        let model = make_model_from_yaml(
2121            r#"
2122AWSTemplateFormatVersion: "2010-09-09"
2123Resources:
2124  MyBucket:
2125    Type: AWS::S3::Bucket
2126"#,
2127        );
2128
2129        let active = engine.evaluate_rules(&model, &ValidateConfig::default()).unwrap();
2130        assert!(active.iter().any(|d| d.rule_id == "GUARDPROBE"), "an active rule's guarded body must run");
2131
2132        let suppressed = engine.evaluate_rules(&model, &exclude_ids(&["W9010"])).unwrap();
2133        assert!(
2134            suppressed.iter().all(|d| d.rule_id != "GUARDPROBE"),
2135            "a suppressed rule's guarded body - including its invalid regex - must not run"
2136        );
2137    }
2138}