diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f814df88..f6d46ab98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - *(rvm)* Package values such as `data.pkg` omit undefined rules and include subpackages that have no rules (as `{}`), matching OPA and the interpreter. +- *(interpreter)* a package without rules no longer fails with `internal error: make: not an object` when base data has a non-object value at or above its path. As in OPA, the base data value wins, and the package still reads as an empty object below that value, including through variable indexes, imports and iteration over a string, number, boolean or null. Two shapes fail with a "not supported" error instead: iterating over an array or set in data that has such a package below it (or over a non-object value read below an iterated `_`), and an undefined read below an iterated `_` (such as `data.a[_].b`) when such a package may be at or below it. Where OPA binds an iterated key or `_` once for the base value and once more for such a package below it, regorus binds it once, so `[v | v := data.a[k].c]` returns `[{}]` where OPA returns `[{}, {}]`. As in OPA, reading such a package fails with "rule ... conflicts with a value in base data" when a rule is below a non-object value in base data, or has a dynamic key below any value in base data. ## [0.15.0](https://github.com/microsoft/regorus/compare/regorus-v0.14.1...regorus-v0.15.0) - 2026-11-07 diff --git a/src/engine.rs b/src/engine.rs index fd834b65c..3eba2dc7d 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -1541,17 +1541,6 @@ impl Engine { self.apply_effective_execution_timer_config(); self.interpreter.clean_internal_evaluation_state(); - // Ensure that empty modules are created. - for m in self.modules.iter().filter(|m| m.policy.is_empty()) { - let path = Parser::get_static_string_path_components(&m.package.refr)?; - let path: Vec<&str> = path.iter().map(String::as_str).collect(); - let vref = - Interpreter::make_or_get_value_mut(self.interpreter.get_data_mut(), &path[..])?; - if *vref == Value::Undefined { - *vref = Value::new_object(); - } - } - self.interpreter.check_default_rules()?; for module in self.modules.clone().iter() { for rule in &module.policy { @@ -1571,11 +1560,11 @@ impl Engine { for m in self.modules.iter() { let path = Parser::get_static_string_path_components(&m.package.refr)?; let path: Vec<&str> = path.iter().map(String::as_str).collect(); - let vref = - Interpreter::make_or_get_value_mut(self.interpreter.get_data_mut(), &path[..])?; - if *vref == Value::Undefined { - *vref = Value::new_object(); - } + Interpreter::ensure_package_value( + self.interpreter.get_data_mut(), + &path, + !m.policy.is_empty(), + )?; } self.interpreter.create_rule_prefixes()?; Ok(self.interpreter.get_data_mut().clone()) diff --git a/src/interpreter.rs b/src/interpreter.rs index 80b90eb94..5b350c6cd 100644 --- a/src/interpreter.rs +++ b/src/interpreter.rs @@ -160,6 +160,10 @@ const MAX_NATIVE_EVALUATION_DEPTH: usize = 64; #[error("native evaluation nesting exceeds limit {MAX_NATIVE_EVALUATION_DEPTH}")] struct NativeEvaluationDepthExceeded; +// A path component that stands for the unknown key of `_` in a read of data. A data key equal +// to it is also treated as unknown. +const ANY_KEY: &str = "\u{0}_"; + pub fn is_evaluation_limit_error(error: &anyhow::Error) -> bool { error .downcast_ref::() @@ -231,6 +235,12 @@ pub struct Interpreter { builtins_cache: BTreeMap<(&'static str, Vec), Value>, no_rules_lookup: bool, execution_timer: ExecutionTimer, + // Packages without rules below a non-object value in base data. Computed once per evaluation. + packages_below_non_object: Option>>>, + // A rule that conflicts with base data, found with packages_below_non_object. + rule_below_non_object: Option, + // Paths in data of dynamic collections of loops, by module and expression index. + collection_paths: BTreeMap<(u32, u32), Option>>, } impl Default for Interpreter { @@ -281,6 +291,9 @@ impl Clone for Interpreter { module: None, no_rules_lookup: false, execution_timer: ExecutionTimer::new(self.execution_timer.config()), + packages_below_non_object: None, + rule_below_non_object: None, + collection_paths: BTreeMap::new(), } } } @@ -364,6 +377,9 @@ impl Interpreter { gather_prints: false, prints: Vec::default(), execution_timer: ExecutionTimer::new(None), + packages_below_non_object: None, + rule_below_non_object: None, + collection_paths: BTreeMap::new(), } } @@ -418,6 +434,9 @@ impl Interpreter { compiled_policy: compiled_policy.clone(), init_data, execution_timer: ExecutionTimer::new(None), + packages_below_non_object: None, + rule_below_non_object: None, + collection_paths: BTreeMap::new(), } } @@ -565,6 +584,8 @@ impl Interpreter { self.rule_values.clear(); self.builtins_cache.clear(); self.reset_execution_timer_state(); + self.packages_below_non_object = None; + self.collection_paths.clear(); } #[cfg(all(feature = "allocator-memory-limits", not(miri)))] @@ -707,19 +728,81 @@ impl Interpreter { Ok(Value::Undefined) } - fn eval_chained_ref_dot_or_brack(&mut self, mut expr: &ExprRef) -> Result { + fn eval_chained_ref_dot_or_brack(&mut self, expr: &ExprRef) -> Result { + Ok(self.eval_chained_ref(expr, false)?.0) + } + + /// Evaluates a chained reference. Also returns the path in `data` (starting with `data`) + /// that the reference reads if it is undefined or if `want_path` is set. + fn eval_chained_ref( + &mut self, + mut expr: &ExprRef, + want_path: bool, + ) -> Result<(Value, Option>)> { // Collect a chaing of '.field' or '["field"]' let mut path = vec![]; loop { if let Some(v) = self.get_loop_var_value(expr)? { path.reverse(); - return Ok(Self::get_value_chained(v.clone(), &path[..])); + let v = Self::get_value_chained(v.clone(), &path[..]); + // An undefined read below an iterated value of data may reach a package below a + // non-object value in base data. Evaluate it as a reference with its index then. + if ((v != Value::Undefined || path.is_empty()) && !want_path) + || self.data_root_path(&get_root_var(expr)?)?.is_none() + || self.packages_below_non_object()?.is_empty() + { + return Ok((v, None)); + } + let Expr::RefBrack { refr, index, .. } = expr.as_ref() else { + return Ok((v, None)); + }; + // Packages have string keys, which compound key patterns do not match. + if !matches!(index.as_ref(), Expr::Var { .. }) { + return Ok((v, None)); + } + // The key of `_` is unknown: it matches any package name in the path. + let wildcard = + matches!(index.as_ref(), Expr::Var { span, .. } if span.text() == "_"); + let key_value = match wildcard { + true => Value::from(ANY_KEY), + false => self.eval_expr(index)?, + }; + if key_value == Value::Undefined { + return Ok((v, None)); + } + // Reuse the path of a dynamic collection instead of evaluating it again. + let key = (self.current_module_index, refr.eidx()); + let collection_path = self.collection_paths.get(&key).cloned(); + if wildcard || collection_path.is_some() { + let refr_path = match collection_path { + Some(collection_path) => collection_path, + None => self.data_path(refr)?, + }; + let (Some(mut data_path), Value::String(key_name)) = (refr_path, key_value) + else { + return Ok((v, None)); + }; + data_path.push(key_name.as_ref().to_string()); + data_path.extend(path.iter().map(|component| (*component).to_string())); + return Ok((self.or_package_value(v, &data_path)?, Some(data_path))); + } + path.reverse(); } match expr.as_ref() { // Stop path collection upon encountering the leading variable. Expr::Var { span, .. } => { path.reverse(); - return self.lookup_var(span, &path[..], false); + let value = self.lookup_var(span, &path[..], false)?; + if (value != Value::Undefined && !want_path) + || self.data_root_path(&span.source_str())?.is_none() + || self.packages_below_non_object()?.is_empty() + { + return Ok((value, None)); + } + let mut data_path = + self.data_root_path(&span.source_str())?.unwrap_or_default(); + data_path.extend(path.iter().map(|component| (*component).to_string())); + return Ok((self.or_package_value(value, &data_path)?, Some(data_path))); } // Accumulate chained . field accesses. Expr::RefDot { refr, field, .. } => { @@ -738,12 +821,12 @@ impl Interpreter { path.reverse(); let index = self.eval_expr(index)?; + let static_components = + Parser::get_static_string_path_components(refr).ok(); // Handle indexing into data. if index != Value::Undefined { - if let Ok(ref_components) = - Parser::get_static_string_path_components(refr) - { + if let Some(ref_components) = &static_components { if ref_components.first().map(String::as_str) == Some("data") { let ref_component_refs: Vec<&str> = ref_components.iter().map(String::as_str).collect(); @@ -796,25 +879,61 @@ impl Interpreter { } } - let obj = self.eval_expr(refr)?; + let refr_root = get_root_var(refr)?; + let root_path = self.data_root_path(&refr_root)?; + let has_packages = + root_path.is_some() && !self.packages_below_non_object()?.is_empty(); + let (obj, dynamic_refr_path) = + if static_components.is_none() && has_packages { + self.with_native_depth(|this| this.eval_chained_ref(refr, true))? + } else { + (self.eval_expr(refr)?, None) + }; let mut v = obj[&index].clone(); + // A number that selects an element of data is not a package name. + let selected_by_number = + v != Value::Undefined && matches!(index, Value::Number(_)); // Qualified references starting with data (e.g data.p.q) can // be indexed using numbers. The number will be converted to string // if a matching key exists. if v == Value::Undefined && matches!(index, Value::Number(_)) - && get_root_var(refr)?.text() == "data" + && refr_root.text() == "data" { let index = index.to_string(); v = obj[index].clone(); } - return Ok(Self::get_value_chained(v, &path[..])); + let v = Self::get_value_chained(v, &path[..]); + if (v != Value::Undefined && !want_path) + || selected_by_number + || !has_packages + { + return Ok((v, None)); + } + let refr_path = static_components.map_or(dynamic_refr_path, |components| { + root_path.map(|mut refr_path| { + refr_path.extend(components.into_iter().skip(1)); + refr_path + }) + }); + let index_component = match &index { + Value::String(value) => value.as_ref().to_string(), + Value::Number(_) => index.to_string(), + _ => return Ok((v, None)), + }; + let Some(mut data_path) = refr_path else { + return Ok((v, None)); + }; + data_path.push(index_component); + data_path.extend(path.iter().map(|component| (*component).to_string())); + return Ok((self.or_package_value(v, &data_path)?, Some(data_path))); } }, _ => { path.reverse(); - return Ok(Self::get_value_chained(self.eval_expr(expr)?, &path[..])); + let v = Self::get_value_chained(self.eval_expr(expr)?, &path[..]); + return Ok((v, None)); } } } @@ -1691,13 +1810,95 @@ impl Interpreter { }; self.eval_call_impl(span, collection_expr, fcn, params_slice) } else { - self.eval_expr(collection_expr) + self.eval_collection(collection_expr) } })(); self.restore_state(saved_state)?; result } + /// Evaluates the collection of a loop. As in OPA, iterating over a scalar value in base data + /// visits the packages without rules below it. Iterating over an array or set, or over a + /// non-object value read below `_`, with such packages below it is not supported. + fn eval_collection(&mut self, expr: &ExprRef) -> Result { + if self.data_root_path(&get_root_var(expr)?)?.is_none() + || self.packages_below_non_object()?.is_empty() + { + return self.eval_expr(expr); + } + // Evaluate a dynamic reference into data once, along with its path. Reads of static + // fields below an iterated value have no side effects: find their path only if needed. + let key = (self.current_module_index, expr.eidx()); + let (value, path) = if matches!(expr.as_ref(), Expr::RefDot { .. } | Expr::RefBrack { .. }) + && !self.is_static_below_loop_var(expr)? + && Parser::get_static_string_path_components(expr).is_err() + { + let (value, path) = self.with_native_depth(|this| this.eval_chained_ref(expr, true))?; + self.collection_paths.insert(key, path.clone()); + (value, Some(path)) + } else { + self.collection_paths.remove(&key); + (self.eval_expr(expr)?, None) + }; + if matches!(value, Value::Object(_) | Value::Undefined) { + return Ok(value); + } + let Some(path) = (match path { + Some(path) => path, + None => self.data_path(expr)?, + }) else { + return Ok(value); + }; + // As in OPA, iterating over a non-object value read below `_` may visit packages. + if matches!(value, Value::Array(_) | Value::Set(_)) || path.iter().any(|f| f == ANY_KEY) { + let mut below = path.get(1..).unwrap_or_default().to_vec(); + below.push(ANY_KEY.to_string()); + if self.has_package_below_non_object(&below)? { + bail!(expr.span().error( + "iterating over a collection in data with packages below it is not supported" + )); + } + return Ok(value); + } + match self.package_value_below_non_object(path.get(1..).unwrap_or_default())? { + Value::Undefined => Ok(value), + packages => Ok(packages), + } + } + + /// Returns true if `expr` is a loop-bound reference or reads static fields below one. + fn is_static_below_loop_var(&self, mut expr: &ExprRef) -> Result { + loop { + if self.get_loop_var_value(expr)?.is_some() { + return Ok(true); + } + match expr.as_ref() { + Expr::RefDot { refr, .. } => expr = refr, + Expr::RefBrack { refr, index, .. } + if matches!(index.as_ref(), Expr::String { .. }) => + { + expr = refr; + } + _ => return Ok(false), + } + } + } + + /// The path in `data` (starting with `data`) that a reference rooted at `data` or at an + /// import of a path in `data` reads, if known. + fn data_path(&mut self, expr: &ExprRef) -> Result>> { + let Some(mut root_path) = self.data_root_path(&get_root_var(expr)?)? else { + return Ok(None); + }; + if let Ok(components) = Parser::get_static_string_path_components(expr) { + root_path.extend(components.into_iter().skip(1)); + return Ok(Some(root_path)); + } + Ok(self + .with_native_depth(|this| this.eval_chained_ref(expr, true))? + .1) + } + fn reset_statement_iteration(&mut self, frame: &StatementLoop<'_>) -> Result<()> { if let Some(scope) = &frame.saved_scope { self.current_scope_mut()?.clone_from(scope); @@ -2107,7 +2308,8 @@ impl Interpreter { .ok_or_else(|| anyhow!("internal error: expected loop info"))?; let mut result = false; let loop_target_expr = Self::loop_assignment_expr(loop_info); - match self.eval_expr(Self::loop_collection_expr(loop_info))? { + let collection = Self::loop_collection_expr(loop_info); + match self.eval_collection(collection)? { Value::Array(items) => { for v in items.iter() { self.set_loop_var_value(loop_target_expr, v.clone())?; @@ -2259,7 +2461,7 @@ impl Interpreter { else { bail!("internal error: missing binding plan for some..in expression"); }; - let value = self.eval_expr(collection)?; + let value = self.eval_collection(collection)?; if !matches!( value, Value::Array(_) | Value::Set(_) | Value::Object(_) | Value::Undefined @@ -3375,9 +3577,12 @@ impl Interpreter { continue; } - let vref = Self::make_or_get_value_mut(&mut self.data, &module_value_components)?; - if *vref == Value::Undefined { - *vref = Value::new_object(); + if !Self::ensure_package_value( + &mut self.data, + &module_value_components, + !module.policy.is_empty(), + )? { + continue; } for rule in &module.policy { @@ -3525,6 +3730,203 @@ impl Interpreter { Ok(false) } + /// `value`, or if undefined, the packages without rules at `data_path` (starting with `data`). + fn or_package_value(&mut self, value: Value, data_path: &[String]) -> Result { + let fields = data_path.get(1..).unwrap_or_default(); + match value { + Value::Undefined if fields.iter().any(|f| f == ANY_KEY) => { + if self.has_package_below_non_object(fields)? { + bail!("reading below a value of `_` is not supported when packages are below non-object values in data"); + } + Ok(Value::Undefined) + } + Value::Undefined => self.package_value_below_non_object(fields), + value => Ok(value), + } + } + + fn lookup_data(&mut self, fields: &[&str]) -> Result { + match Self::get_value_chained(self.data.clone(), fields) { + Value::Undefined => self.package_value_below_non_object(fields), + value => Ok(value), + } + } + + /// The path in `data` (starting with `data`) of the root variable of a reference: `data` + /// itself or an import of a path in `data`, unless a local variable shadows it. + fn data_root_path(&self, name: &SourceStr) -> Result>> { + if name.text() == "input" || self.lookup_local_var(name).is_some() { + return Ok(None); + } + if name.text() == "data" { + return Ok(Some(vec!["data".to_string()])); + } + let Some(module) = &self.module else { + return Ok(None); + }; + // Cheap check before formatting the import key. + if !module + .imports + .iter() + .any(|import| match (&import.r#as, import.refr.as_ref()) { + (Some(alias), _) => alias.text() == name.text(), + (None, Expr::RefDot { field, .. }) => field.0.text() == name.text(), + (None, Expr::RefBrack { index, .. }) => matches!( + index.as_ref(), + Expr::String { value, .. } if *value == Value::from(name.text()) + ), + _ => false, + }) + { + return Ok(None); + } + let import_key = append_path_component(&self.current_module_path, name.text())?; + // As in lookup_var, a rule of the module named like the import shadows it. + if self.compiled_policy.rules.contains_key(&import_key) + || self.compiled_policy.default_rules.contains_key(&import_key) + { + return Ok(None); + } + Ok(self + .compiled_policy + .imports + .get(&import_key) + .and_then(|imported| Parser::get_static_string_path_components(imported).ok()) + .filter(|components| components.first().map(String::as_str) == Some("data"))) + } + + /// The packages without rules below a non-object value in base data. + fn packages_below_non_object(&mut self) -> Result>>> { + if let Some(packages) = &self.packages_below_non_object { + return Ok(packages.clone()); + } + let mut packages = vec![]; + let compiled_policy = self.compiled_policy.clone(); + for module in compiled_policy.modules.iter() { + self.check_execution_time()?; + if module.policy.is_empty() { + let package = Parser::get_static_string_path_components(&module.package.refr)?; + if package.split_last().is_some_and(|(_, parent)| { + Self::has_non_object_on_path(&self.init_data, parent) + }) { + packages.push(package); + self.memory_check()?; + } + } + } + self.rule_below_non_object = None; + for module in compiled_policy.modules.iter() { + for rule in &module.policy { + if packages.is_empty() || self.rule_below_non_object.is_some() { + break; + } + self.check_execution_time()?; + self.rule_below_non_object = Self::rule_conflict(&self.init_data, module, rule)?; + } + } + let packages = Rc::new(packages); + self.packages_below_non_object = Some(packages.clone()); + Ok(packages) + } + + /// The path of a rule or function that OPA rejects for base data: below a non-object value, + /// or with a dynamic key below any value. A rule at a value is overridden by it. Keys are + /// Some(Some(key)) for a string, Some(None) for a dynamic key and None for another literal. + fn rule_conflict(mut data: &Value, module: &Module, rule: &Rule) -> Result> { + let mut keys = vec![]; + for mut refr in [Self::get_rule_refr(rule), &module.package.refr] { + loop { + keys.push(match refr.as_ref() { + Expr::Var { span, .. } => Some(Some(span.text())), + Expr::RefDot { field, .. } => Some(Some(field.0.text())), + Expr::RefBrack { index, .. } => match index.as_ref() { + Expr::String { value, .. } | Expr::RawString { value, .. } => { + Some(Some(value.as_string()?.as_ref())) + } + Expr::UnaryExpr { expr, .. } if Self::is_simple_literal(expr)? => None, + _ if Self::is_simple_literal(index)? => None, + _ => Some(None), + }, + _ => return Ok(None), + }); + match refr.as_ref() { + Expr::RefDot { refr: parent, .. } | Expr::RefBrack { refr: parent, .. } => { + refr = parent; + } + _ => break, + } + } + } + // A legacy set rule `p.q { ... }` stores the member q in a set at p. + let member = match rule { + Rule::Spec { head, .. } => matches!(head, RuleHead::Set { key: None, .. }), + _ => false, + }; + let keys: Vec<_> = keys.into_iter().skip(usize::from(member)).rev().collect(); + // As in OPA, a non-string literal key before any dynamic key exempts the rule. + let exempt = keys.iter().find(|k| !matches!(k, Some(Some(_)))) == Some(&None); + for key in &keys { + match (key, data) { + (_, Value::Undefined) => return Ok(None), + (Some(Some(key)), Value::Object(_)) => data = &data[*key], + _ if exempt => return Ok(None), + _ => { + let path: Vec<_> = keys.iter().map_while(|k| k.flatten()).collect(); + return Ok(Some(path.join("."))); + } + } + } + Ok(None) + } + + /// Returns true if a package without rules is below a non-object value in base data, at or + /// below `fields`, in which `ANY_KEY` matches any key. + fn has_package_below_non_object>(&mut self, fields: &[S]) -> Result { + for package in self.packages_below_non_object()?.iter() { + self.check_execution_time()?; + if package.len() >= fields.len() + && package + .iter() + .zip(fields) + .all(|(p, f)| p == f.as_ref() || f.as_ref() == ANY_KEY) + { + let package: Vec<&str> = package.iter().map(String::as_str).collect(); + if !self.has_explicit_data_with_override_ancestor(&package)? { + return Ok(true); + } + } + } + Ok(false) + } + + /// A package without rules below a non-object value in base data is not stored in `data`, + /// but, as in OPA, it reads as an empty object when read below that value. + fn package_value_below_non_object>(&mut self, fields: &[S]) -> Result { + let mut value = Value::Undefined; + let packages = self.packages_below_non_object()?; + if packages.is_empty() || !Self::has_non_object_on_path(&self.init_data, fields) { + return Ok(value); + } + for package in packages.iter() { + self.check_execution_time()?; + let package: Vec<&str> = package.iter().map(String::as_str).collect(); + if package.len() >= fields.len() + && package.iter().zip(fields).all(|(p, f)| *p == f.as_ref()) + && !self.has_explicit_data_with_override_ancestor(&package)? + { + let rest: Vec<&str> = package.iter().skip(fields.len()).copied().collect(); + Self::ensure_package_value(&mut value, &rest, true)?; + self.memory_check()?; + } + } + if value != Value::Undefined { + if let Some(rule_path) = &self.rule_below_non_object { + bail!("rule {rule_path} conflicts with a value in base data"); + } + } + Ok(value) + } + fn lookup_var(&mut self, span: &Span, fields: &[&str], no_error: bool) -> Result { let name = span.source_str(); @@ -3549,7 +3951,7 @@ impl Interpreter { // Ensure that rules are evaluated if name.text() == "data" { if self.is_processed(fields)? { - return Ok(Self::get_value_chained(self.data.clone(), fields)); + return self.lookup_data(fields); } // If "data" is used in a query, without any fields, then evaluate all the modules. @@ -3585,7 +3987,7 @@ impl Interpreter { } } - Ok(Self::get_value_chained(self.data.clone(), fields)) + self.lookup_data(fields) } else if !self.compiled_policy.modules.is_empty() { let module = self.current_module()?; let mut module_var_path = @@ -3961,6 +4363,42 @@ impl Interpreter { obj } + /// Returns true if `data` holds a value other than an object at or above `path`. + fn has_non_object_on_path>(data: &Value, path: &[S]) -> bool { + let mut value = data; + for component in path { + match value { + Value::Object(fields) => { + match fields.get(&Value::String(component.as_ref().into())) { + Some(v) => value = v, + None => return false, + } + } + Value::Undefined => return false, + _ => return true, + } + } + !matches!(value, Value::Object(_) | Value::Undefined) + } + + /// Ensures that `data` has an object at the package `path`. Returns false, leaving `data` + /// unchanged, for a package without rules when `data` holds a non-object value at or above + /// `path`: as in OPA, such a package does not conflict with that value, which wins. + pub(crate) fn ensure_package_value( + data: &mut Value, + path: &[&str], + has_rules: bool, + ) -> Result { + if !has_rules && Self::has_non_object_on_path(data, path) { + return Ok(false); + } + let vref = Self::make_or_get_value_mut(data, path)?; + if *vref == Value::Undefined { + *vref = Value::new_object(); + } + Ok(true) + } + #[inline] pub fn make_or_get_value_mut<'a>(obj: &'a mut Value, paths: &[&str]) -> Result<&'a mut Value> { let (first, tail) = match paths.split_first() { diff --git a/src/tests/interpreter/mod.rs b/src/tests/interpreter/mod.rs index 46c0ea419..9f8298d25 100644 --- a/src/tests/interpreter/mod.rs +++ b/src/tests/interpreter/mod.rs @@ -1483,3 +1483,161 @@ computed := data.base.foo.a + data.base.foo.b Ok(()) } + +#[test] +fn test_eval_rule_package_without_rules_beside_rules_below_base_string() -> Result<()> { + let mut engine = Engine::new(); + engine.add_data(Value::from_json_str(r#"{ "a" : "str" }"#)?)?; + engine.add_policy("c.rego".to_string(), "package a.b.c".to_string())?; + engine.add_policy("d.rego".to_string(), "package a.b.d\np := 1".to_string())?; + engine.add_policy( + "q.rego".to_string(), + "package q\nx := data.a.b.c".to_string(), + )?; + + // OPA rejects these policies; the package must not read as an empty object. + let error = engine.eval_rule("data.q.x".to_string()).unwrap_err(); + assert!( + error.to_string().contains("rule a.b.d.p conflicts"), + "{error}" + ); + + Ok(()) +} + +#[test] +fn test_eval_rule_package_without_rules_beside_rule_path_below_base_string() -> Result<()> { + let mut engine = Engine::new(); + engine.add_data(Value::from_json_str( + r#"{ "a" : "str", "z": { "b": "str" } }"#, + )?)?; + engine.add_policy("c.rego".to_string(), "package a.c".to_string())?; + engine.add_policy("z.rego".to_string(), "package z\nb.p := 1".to_string())?; + engine.add_policy("q.rego".to_string(), "package q\nx := data.a.c".to_string())?; + + // OPA rejects the rule z.b.p below the string at z.b, so a.c must not read as `{}`. + let error = engine.eval_rule("data.q.x".to_string()).unwrap_err(); + assert!( + error.to_string().contains("rule z.b.p conflicts"), + "{error}" + ); + + Ok(()) +} + +#[test] +fn test_eval_rule_package_without_rules_beside_legacy_set_at_base_number() -> Result<()> { + let mut engine = Engine::new(); + engine.set_rego_v0(true); + engine.add_data(Value::from_json_str(r#"{ "a" : "str", "z": { "b": 0 } }"#)?)?; + engine.add_policy("c.rego".to_string(), "package a.c".to_string())?; + engine.add_policy("z.rego".to_string(), "package z\nb.p { true }".to_string())?; + engine.add_policy("q.rego".to_string(), "package q\nx := data.a.c".to_string())?; + + // The legacy set rule stores the member p in a set at z.b, overridden by the number there. + assert_eq!( + engine.eval_rule("data.q.x".to_string())?, + Value::new_object() + ); + + Ok(()) +} + +#[test] +fn test_eval_rule_package_without_rules_beside_partial_object_at_base_string() -> Result<()> { + for (b, rule, conflicts) in [ + (r#""str""#, "b[k] := 1 if k := \"p\"", true), + (r#""str""#, "b[k] contains 1 if k := \"p\"", true), + (r#""str""#, "b[1] := 1", false), + (r#""str""#, "b[true] := 1", false), + (r#""str""#, "b[- 1] contains 1", false), + (r#""str""#, "b[1].p := 1", false), + (r#"{ "1": "str" }"#, "b[1].p := 1", false), + (r#"{ "p": "str" }"#, "b[k].r := 1 if k := \"p\"", true), + (r#"{ "x": 1 }"#, "b[k] := 1 if k := \"p\"", true), + (r#"{ "x": 1 }"#, "b[k][1] := 1 if k := \"p\"", true), + (r#"{ "x": 1 }"#, "b[1][k] := 1 if k := \"p\"", false), + (r#""str""#, "b.p[1] := 1", false), + (r#""str""#, "b.p[k] := 1 if k := 1", true), + (r#""str""#, "b[-k] := 1 if k := 1", true), + ] { + let mut engine = Engine::new(); + engine.add_data(Value::from_json_str(&format!( + r#"{{ "a" : "str", "z": {{ "b": {b} }} }}"# + ))?)?; + engine.add_policy("c.rego".to_string(), "package a.c".to_string())?; + engine.add_policy( + "z.rego".to_string(), + format!("package z\nimport rego.v1\n{rule}"), + )?; + engine.add_policy("q.rego".to_string(), "package q\nx := data.a.c".to_string())?; + + // As in OPA, a rule with a dynamic key below a value at z.b conflicts, and a rule with + // a non-string literal key before any dynamic key does not. + let result = engine.eval_rule("data.q.x".to_string()); + if conflicts { + let error = result.unwrap_err(); + assert!( + error.to_string().starts_with("rule z.b") + && error + .to_string() + .contains("conflicts with a value in base data"), + "{rule}: {error}" + ); + } else { + assert_eq!(result?, Value::new_object(), "{rule}"); + } + } + + Ok(()) +} + +#[test] +fn test_eval_rule_dynamic_collection_with_packages_below_evaluated_once() -> Result<()> { + use alloc::sync::Arc; + use core::sync::atomic::{AtomicUsize, Ordering}; + + let calls = Arc::new(AtomicUsize::new(0)); + let extension_calls = calls.clone(); + let index_calls = calls.clone(); + let mut engine = Engine::new(); + engine.add_extension( + "key".to_string(), + 0, + Box::new(move |_| { + extension_calls.fetch_add(1, Ordering::SeqCst); + Ok(Value::from("k")) + }), + )?; + engine.add_extension( + "index".to_string(), + 0, + Box::new(move |_| { + index_calls.fetch_add(1, Ordering::SeqCst); + Ok(Value::from(0)) + }), + )?; + engine.add_data(Value::from_json_str( + r#"{ "a" : { "k": "str" }, "b": [ { "x": {} } ] }"#, + )?)?; + engine.add_policy("p.rego".to_string(), "package a.k.p".to_string())?; + engine.add_policy( + "q.rego".to_string(), + "package q\nimport rego.v1\nx := [k | some k, _ in data.a[key()]]\ny := [k | data.a[key()][k]]\nz := [v | v := data.a[key()][_].r]\nw := [v | v := data.b[index()][_].r]\nu := [v | v := data.a[key()][k].r]".to_string(), + )?; + + for (rule, want) in [ + ("x", r#"["p"]"#), + ("y", r#"["p"]"#), + ("z", "[]"), + ("w", "[]"), + ("u", "[]"), + ] { + calls.store(0, Ordering::SeqCst); + let value = engine.eval_rule(format!("data.q.{rule}"))?; + assert_eq!(value, Value::from_json_str(want)?, "{rule}"); + assert_eq!(calls.load(Ordering::SeqCst), 1, "{rule}"); + } + + Ok(()) +} diff --git a/tests/interpreter/cases/data/empty_packages.yaml b/tests/interpreter/cases/data/empty_packages.yaml new file mode 100644 index 000000000..d582a346f --- /dev/null +++ b/tests/interpreter/cases/data/empty_packages.yaml @@ -0,0 +1,248 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +cases: + - note: empty packages read via data + data: + b: + v: 1 + modules: + - | + package e + - | + package e.f + - | + package p + + x := 1 + - | + package p.g + query: data + want_result: + b: + v: 1 + e: + f: {} + p: + g: {} + x: 1 + + - note: empty packages listed first, read via data + data: + b: + v: 1 + modules: + - | + package e.f + - | + package p.g + - | + package e + - | + package p + + x := 1 + query: data + want_result: + b: + v: 1 + e: + f: {} + p: + g: {} + x: 1 + + - note: empty package read directly + modules: + - | + package e + - | + package e.f + - | + package p + + x := 1 + query: data.e + want_result: + f: {} + + - note: nested empty package read directly + modules: + - | + package e.f + - | + package e + - | + package p + + x := 1 + query: data.e.f + want_result: {} + + - note: empty package below a package with rules + modules: + - | + package p.g + - | + package p + + x := 1 + query: data.p + want_result: + g: {} + x: 1 + + - note: empty packages read from another package + modules: + - | + package q + import rego.v1 + + e := data.e + ef := data.e.f + p := data.p + pg := data.p.g + ce := count(data.e) + kp := sort(object.keys(data.p)) + ek := sort({k | data.e[k]}) + pk := sort({k | data.p[k]}) + - | + package e + - | + package e.f + - | + package p + + x := 1 + - | + package p.g + query: data.q + want_result: + ce: 1 + e: + f: {} + ef: {} + ek: [f] + kp: [g, x] + p: + g: {} + x: 1 + pg: {} + pk: [g, x] + + - note: empty packages read from another package listed last + modules: + - | + package e + - | + package e.f + - | + package p + + x := 1 + - | + package p.g + - | + package q + import rego.v1 + + e := data.e + ef := data.e.f + p := data.p + pg := data.p.g + ce := count(data.e) + kp := sort(object.keys(data.p)) + ek := sort({k | data.e[k]}) + pk := sort({k | data.p[k]}) + query: data.q + want_result: + ce: 1 + e: + f: {} + ef: {} + ek: [f] + kp: [g, x] + p: + g: {} + x: 1 + pg: {} + pk: [g, x] + + - note: empty package shadowed by base data + data: + e: + k: 1 + modules: + - | + package e + - | + package e.f + query: data.e + want_result: + f: {} + k: 1 + + - note: nested empty package shadowed by base data + data: + e: + f: + z: 1 + modules: + - | + package e + - | + package e.f + query: data + want_result: + e: + f: + z: 1 + + - note: empty packages shadowed by base data read from another package + data: + e: + k: 1 + f: + z: 1 + p: + y: 2 + modules: + - | + package q + import rego.v1 + + e := data.e + ef := data.e.f + p := data.p + pg := data.p.g + ce := count(data.e) + kp := sort(object.keys(data.p)) + ek := sort({k | data.e[k]}) + pk := sort({k | data.p[k]}) + - | + package e + - | + package e.f + - | + package p + + x := 1 + - | + package p.g + query: data.q + want_result: + ce: 2 + e: + f: + z: 1 + k: 1 + ef: + z: 1 + ek: [f, k] + kp: [g, x, y] + p: + g: {} + x: 1 + y: 2 + pg: {} + pk: [g, x, y] diff --git a/tests/interpreter/cases/data/package_over_non_object.yaml b/tests/interpreter/cases/data/package_over_non_object.yaml new file mode 100644 index 000000000..43971197e --- /dev/null +++ b/tests/interpreter/cases/data/package_over_non_object.yaml @@ -0,0 +1,704 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +cases: + - note: package without rules below a string in base data + data: + a: str + modules: + - | + package a.b + - | + package q + + p := data.a + r := data.a.b + query: data.q + want_result: + p: str + r: {} + + - note: package without rules two levels below a string in base data + data: + a: + b: str + modules: + - | + package a.b.c + - | + package q + + p := data.a + r := data.a.b + c := data.a.b.c + query: data.q + want_result: + p: + b: str + r: str + c: {} + + - note: packages without rules below a string in base data merge when read + data: + a: str + modules: + - | + package a.b.c + - | + package a.b.d + - | + package q + import rego.v1 + + r := data.a.b + k := v if { + x := "b" + v := data.a[x] + } + w := v if { + v := data.a.b with data.a as "x" + } + n := data.a.b.c.e + wz := v if { + v := data.a.b with data.z as 1 + } + ks := {key | some key; data.a.b[key]} + query: data.q + want_result: + r: + c: {} + d: {} + k: + c: {} + d: {} + wz: + c: {} + d: {} + ks: + set!: [c, d] + + - note: package without rules below a string in base data, read via data + data: + a: str + modules: + - | + package a.b.c + query: data + want_result: + a: str + + - note: package without rules three levels below a string in base data + data: + a: + b: str + modules: + - | + package a.b.c.d + - | + package q + + p := data.a + r := data.a.b + c := data.a.b.c + d := data.a.b.c.d + query: data.q + want_result: + p: + b: str + r: str + c: + d: {} + d: {} + + - note: package without rules below an array in base data, read from query + data: + a: [1] + modules: + - | + package a.b + query: data.a + want_result: [1] + + - note: package without rules at a string in base data + data: + a: + b: str + modules: + - | + package a.b + query: data.a + want_result: + b: str + + - note: package without rules below an object in base data + data: + a: + x: 1 + modules: + - | + package a.b.c + query: data.a + want_result: + b: + c: {} + x: 1 + + - note: package without rules below missing base data + data: {} + modules: + - | + package a.b.c + query: data.a + want_result: + b: + c: {} + + - note: package with rules below an object in base data + data: + a: + x: 1 + modules: + - | + package a.b + + x := 1 + query: data.a + want_result: + b: + x: 1 + x: 1 + + - note: package with rules below a string in base data + data: + a: str + modules: + - | + package a.b + + x := 1 + query: data.a + error: not an object + + - note: package with only functions below a string in base data + data: + a: str + modules: + - | + package a.b + + f(v) := v + query: data.a + error: not an object + + - note: package with rules at a string in base data + data: + a: + b: str + modules: + - | + package a.b + + x := 1 + query: data.a + error: not an object + + - note: package without rules below a string produced by a rule + input: + x: str + modules: + - | + package a + + b := input.x + - | + package a.b.c + - | + package q + + x := data.a + y := data.a.b.c + query: data.q + want_result: + x: + b: str + + - note: package without rules below a set produced by a rule + modules: + - | + package a + import rego.v1 + + s contains "x" + - | + package a.s.t + - | + package q + + x := data.a + y := data.a.s.t + query: data.q + want_result: + x: + s: + set!: [x] + + + - note: package without rules below a string in base data, read through two variable indexes + data: + a: str + input: + k1: a + k2: b + modules: + - | + package a.b + query: data[input.k1][input.k2] + want_result: {} + + - note: iteration over a string in base data visits packages without rules below it + data: + a: str + modules: + - | + package a.b.c + - | + package a.b.d + - | + package q + import rego.v1 + + ks := [k | data.a[k]] + n := count([1 | data.a[_]]) + kv := [[k, v] | some k, v in data.a] + query: data.q + want_result: + ks: [b] + n: 1 + kv: + - - b + - c: {} + d: {} + + - note: iteration over an array in base data with a package without rules below it, a key variable + data: + a: [7] + modules: + - | + package a.b + query: "[k | data.a[k]]" + error: iterating over a collection in data with packages below it is not supported + + - note: iteration over an array in base data with a package without rules below it, some in + data: + a: [7] + modules: + - | + package a.b + - | + package q + import rego.v1 + + values := [v | some v in data.a] + query: data.q.values + error: iterating over a collection in data with packages below it is not supported + + - note: iteration over an array in base data with a package without rules below it, an output expression + data: + a: [7] + modules: + - | + package a.b + query: "[data.a[_] | true]" + error: iterating over a collection in data with packages below it is not supported + + - note: iteration over an array in base data with a package without rules below it, a wildcard below a package + data: + a: [7] + modules: + - | + package a.b.c + query: "[v | v := data.a[_]]" + error: iterating over a collection in data with packages below it is not supported + + - note: iteration over an array in base data with a package without rules below it, some with a number-string package + data: + n: + - x: 1 + modules: + - | + package n["0"].b + - | + package q + import rego.v1 + + pairs := [[k, v] | some k, v in data.n] + query: data.q.pairs + error: iterating over a collection in data with packages below it is not supported + + - note: iteration over an array in data that a with override puts above a package without rules + data: + a: [7] + s: 1 + modules: + - | + package a.b + - | + package s.b + - | + package q + import rego.v1 + + a := x if x := [v | v := data.a[_]] with data.a as [8] + s := x if x := [v | some v in data.s] with data.s as [7] + c := x if x := [v | v := data.a[_].c] with data.a as {"x": {"c": 5}} + query: data.q + want_result: + a: [8] + s: [7] + c: [5] + + - note: iteration over scalars other than strings in base data visits packages without rules below them + data: + a: 7 + n: null + f: false + modules: + - | + package a.x + - | + package n.x + - | + package f.x + query: "[[k | data.a[k]], [k | data.n[k]], [k | data.f[k]], [v | v := data.a[_].missing]]" + want_result: [[x], [x], [x], []] + + - note: iteration over an array in base data at a package without rules + data: + a: [7] + e: [] + modules: + - | + package a + - | + package e + - | + package q + import rego.v1 + + a := [v | v := data.a[_]] + e := [v | v := data.e[_]] + query: data.q + want_result: + a: [7] + e: [] + + - note: iteration over a string in base data in an output expression + data: + a: str + modules: + - | + package a.b + query: "[data.a[_] | true]" + want_result: [{}] + + - note: package without rules below a string in base data, unrelated read below an iterated wildcard + data: + a: str + rows: [{}] + modules: + - | + package a.b + - | + package q + import rego.v1 + + missing := [v | v := data.rows[_].missing] + rows := [v | some v in data.rows] + wildcard := [data.rows[_] | true] + query: data.q + want_result: + missing: [] + rows: [{}] + wildcard: [{}] + + # OPA 1.2.0 returns [{}, {}]: it binds k to "b" once for base data and once for the package. + - note: package without rules below a string in base data, read through iterated and variable indexes + data: + a: + b: str + input: + key: c + modules: + - | + package a.b.c + query: "[v | v := data.a[k][input.key]]" + want_result: [{}] + + - note: package without rules below a string in base data, read below an iterated value + data: + a: + b: str + modules: + - | + package a.b.c + - | + package q + import rego.v1 + + ks := {k | data.a[k].c} + kb := [k | data.a.b[k]] + query: data.q + want_result: + ks: + set!: [b] + kb: [c] + + - note: package without rules below a string in base data, read below an iterated wildcard + data: + a: + b: str + modules: + - | + package a.b.c + query: "[v | v := data.a[_].c]" + error: not supported + + - note: package without rules below a string in base data, read through an import + data: + a: str + modules: + - | + package a.b + - | + package q + import rego.v1 + import data.a + + x := a.b + k := "b" + z := a[k] + allow if not a.b + query: data.q + want_result: + x: {} + k: b + z: {} + + - note: package without rules below a string in base data, read through a bracket import + data: + a: str + modules: + - | + package a.b + - | + package q + import rego.v1 + import data["a"] + + x := a.b + query: data.q + want_result: + x: {} + + - note: package without rules below a string in base data, local data variable + data: + a: str + input: + s: local + modules: + - | + package a.b + - | + package q + + allow { + data := {"a": input.s} + k := "b" + data.a[k] == {} + } + query: data.q + want_result: {} + + - note: package without rules below an array in base data, read through a number + data: + a: + - x: 1 + modules: + - | + package a["0"].b + - | + package q + import rego.v1 + + x := data.a[0].b + y := data.a["0"].b + z := v if { + i := 0 + v := data.a[i].b + } + query: data.q + want_result: + y: {} + + - note: package without rules beside a rule below a string in base data + data: + a: str + z: + b: str + modules: + - | + package a.c + - | + package z + import rego.v1 + + b.p := 1 + - | + package q + + x := data.a.c + query: data.q.x + error: rule z.b.p conflicts with a value in base data + + - note: package without rules beside a rule overridden by base data + data: + a: str + z: + b: 0 + modules: + - | + package a.c + - | + package z + + b := 1 + - | + package q + + x := data.a.c + y := data.z.b + query: data.q + want_result: + x: {} + y: 0 + + - note: rules named like an import shadow it + data: + a: str + modules: + - | + package a.b + - | + package q + + import data.a as alias + + alias := "local" + + r := alias.b + - | + package q2 + + import data.a as alias + + alias.x := 1 + + r := alias.b + query: "[object.get(data.q, \"r\", \"undefined\"), object.get(data.q2, \"r\", \"undefined\")]" + want_result: ["undefined", "undefined"] + + - note: iterating an object read below a value of `_` with packages deeper below it + data: + a: + s: + k: + o: str + modules: + - | + package a.s.k.o.p + - | + package q + import rego.v1 + + x := [v | some v in data.a[_].k] + y := [k | data.a[_].k[k]] + query: data.q + want_result: + x: [str] + y: [o] + + # OPA 1.2.0 binds each `_` once for base data and once for the package, so it repeats the + # values: x is [5, 5] and y is [5, 5, 5, 5]. + - note: reading through a variable index below a value of `_` with packages deeper below it + data: + a: + s: + k: + o: str + q: 5 + input: + x: q + modules: + - | + package a.s.k.o.p + - | + package q + import rego.v1 + + x := [v | v := data.a[_].k[input.x]] + y := [v | v := data.a[_][_][input.x]] + z := [v | v := data.a[_].k[input.x].p] + query: data.q + want_result: + x: [5] + y: [5] + z: [] + + - note: reading a package through a variable index below a value of `_` + data: + a: + s: + k: + o: str + input: + x: o + modules: + - | + package a.s.k.o.p + query: "[v | v := data.a[_].k[input.x].p]" + error: not supported + + - note: iterating over a scalar read below a value of `_` with packages below it + data: + a: + s: + k: + o: str + input: + x: o + modules: + - | + package a.s.k.o.p + - | + package q + import rego.v1 + + x := [k | some k, _ in data.a[_].k[input.x]] + query: data.q.x + error: not supported + + - note: reading below a value of a compound key pattern with packages below non-object data + data: + a: str + modules: + - | + package a.b + - | + package q + import rego.v1 + + obj := {[1]: {"x": 1}} + r := [v | v := data.q.obj[[_]].r] + s := [k | data.q.obj[[k]].r] + query: "[data.q.r, data.q.s]" + want_result: [[], []] diff --git a/tests/rvm/rego/package_value_differential.rs b/tests/rvm/rego/package_value_differential.rs index b02107552..6e5f1dece 100644 --- a/tests/rvm/rego/package_value_differential.rs +++ b/tests/rvm/rego/package_value_differential.rs @@ -100,15 +100,14 @@ fn eval_rvm(engine: &mut Engine, query: &str, input: &Value, mode: ExecutionMode } fn check(modules: &[&str], cases: &[(&str, &str, Option<&str>)]) -> Result<()> { - check_with_data(modules, "{}", true, cases) + check_with_data(modules, "{}", cases) } /// Requires `query` on `input` with base `data` to produce `want` (`None` for -/// undefined) in both RVM modes and, if `interpreter` is set, in the interpreter. +/// undefined) in the interpreter and in both RVM modes. fn check_with_data( modules: &[&str], data: &str, - interpreter: bool, cases: &[(&str, &str, Option<&str>)], ) -> Result<()> { let mut engine = Engine::new(); @@ -122,10 +121,7 @@ fn check_with_data( let input_value = Value::from_json_str(input)?; engine.set_input(input_value.clone()); - let mut results = Vec::new(); - if interpreter { - results.push(("interpreter", engine.eval_rule(query.to_string()))); - } + let mut results = vec![("interpreter", engine.eval_rule(query.to_string()))]; for (name, mode) in [ ("run-to-completion", ExecutionMode::RunToCompletion), ("suspendable", ExecutionMode::Suspendable), @@ -252,7 +248,7 @@ fn base_data_merges_with_packages_without_rules() -> Result<()> { let str_ab = r#"{"a": {"b": "str"}}"#; let p_str_ab = ("data.q.p", EMPTY, Some(r#"{"b": "str"}"#)); let r_str = ("data.q.r", EMPTY, Some(r#""str""#)); - check_with_data(&["package a.b", reads], str_ab, true, &[p_str_ab, r_str])?; + check_with_data(&["package a.b", reads], str_ab, &[p_str_ab, r_str])?; check_with_data( &[ "package a\nx := 1", @@ -261,7 +257,6 @@ fn base_data_merges_with_packages_without_rules() -> Result<()> { reads, ], r#"{"a": {"b": {"k": 1}}}"#, - true, &[ ( "data.q.p", @@ -271,11 +266,9 @@ fn base_data_merges_with_packages_without_rules() -> Result<()> { ("data.q.r", EMPTY, Some(r#"{"k": 1}"#)), ], )?; - // The interpreter fails on these ("make: not an object"). check_with_data( &["package a.b", reads], r#"{"a": "str"}"#, - false, &[ ("data.q.p", EMPTY, Some(r#""str""#)), ("data.q.r", EMPTY, Some("{}")), @@ -284,7 +277,53 @@ fn base_data_merges_with_packages_without_rules() -> Result<()> { check_with_data( &["package a.b.c", reads], str_ab, - false, &[p_str_ab, r_str, ("data.q.c", EMPTY, Some("{}"))], ) } + +#[test] +fn packages_without_rules_at_or_below_base_arrays() -> Result<()> { + // Some shapes in the interpreter YAML cases, such as iterating over a non-object value + // with packages below it, still differ in the RVM. + check_with_data( + &[ + r#"package n["0"].b"#, + "package q\nx := data.n[0].b\ny := data.n[\"0\"].b", + ], + r#"{"n": [{"x": 1}]}"#, + &[("data.q.x", EMPTY, None), ("data.q.y", EMPTY, Some("{}"))], + )?; + check_with_data( + &[ + "package a", + "package e", + "package q\nvalues := [v | v := data.a[_]]\nempty := [v | v := data.e[_]]", + ], + r#"{"a": [7], "e": []}"#, + &[ + ("data.q.values", EMPTY, Some("[7]")), + ("data.q.empty", EMPTY, Some("[]")), + ], + ) +} + +#[test] +fn packages_without_rules_below_base_strings_on_iterated_paths() -> Result<()> { + check_with_data( + &[ + "package a.b", + "package q\nmissing := [v | v := data.rows[_].missing]", + ], + r#"{"a": "str", "rows": [{}]}"#, + &[("data.q.missing", EMPTY, Some("[]"))], + )?; + // OPA 1.2.0 returns [{}, {}]: it binds k to "b" once for base data and once for the package. + check_with_data( + &[ + "package a.b.c", + "package q\nvalues := [v | v := data.a[k][input.key]]", + ], + r#"{"a": {"b": "str"}}"#, + &[("data.q.values", r#"{"key": "c"}"#, Some("[{}]"))], + ) +}