From b3535875c87f681e048d436a17660b7f8a8333a1 Mon Sep 17 00:00:00 2001 From: Giuseppe Taverniti Date: Wed, 11 Nov 2026 10:35:15 +0100 Subject: [PATCH 1/3] feat(expression): evaluation budget (max steps, max interval length) New EXPRESSION_CONFIG in zen-expression, re-exported by zen-engine, with two global limits that default to 0 (no limit, the historical behaviour): - max_steps: VM instructions executed by one evaluation; loops run a few instructions per element, so this bounds the time and the memory a map/filter/... can take; - max_interval_length: elements an interval [a..b] may be expanded to when it is iterated. Membership tests (x in [a..b]) do not expand the interval and are not affected. When a limit is exceeded the evaluation fails with VMError::BudgetExceeded. Exposed in the Node and uniffi bindings as expressionMaxSteps and expressionMaxIntervalLength. Refs #561 --- bindings/nodejs/src/config.rs | 16 ++++++++++- bindings/uniffi/src/config.rs | 16 ++++++++++- core/engine/README.md | 6 +++++ core/engine/src/lib.rs | 1 + core/expression/README.md | 17 ++++++++++++ core/expression/src/config.rs | 28 +++++++++++++++++++ core/expression/src/lib.rs | 2 ++ core/expression/src/vm/error.rs | 3 +++ core/expression/src/vm/interval.rs | 13 ++++++++- core/expression/src/vm/vm.rs | 43 +++++++++++++++++++++++++----- core/expression/tests/isolate.rs | 33 +++++++++++++++++++++++ 11 files changed, 168 insertions(+), 10 deletions(-) create mode 100644 core/expression/src/config.rs diff --git a/bindings/nodejs/src/config.rs b/bindings/nodejs/src/config.rs index dfdb0515d..d9d770cba 100644 --- a/bindings/nodejs/src/config.rs +++ b/bindings/nodejs/src/config.rs @@ -1,12 +1,14 @@ use napi_derive::napi; use std::sync::atomic::Ordering; -use zen_engine::ZEN_CONFIG; +use zen_engine::{EXPRESSION_CONFIG, ZEN_CONFIG}; #[napi(object)] pub struct ZenConfig { pub nodes_in_context: Option, pub function_timeout_millis: Option, pub http_auth: Option, + pub expression_max_steps: Option, + pub expression_max_interval_length: Option, } #[allow(dead_code)] @@ -25,4 +27,16 @@ pub fn override_config(config: ZenConfig) { if let Some(val) = config.http_auth { ZEN_CONFIG.http_auth.store(val, Ordering::Relaxed); } + + if let Some(val) = config.expression_max_steps { + EXPRESSION_CONFIG + .max_steps + .store(val as u64, Ordering::Relaxed); + } + + if let Some(val) = config.expression_max_interval_length { + EXPRESSION_CONFIG + .max_interval_length + .store(val as u64, Ordering::Relaxed); + } } diff --git a/bindings/uniffi/src/config.rs b/bindings/uniffi/src/config.rs index 9c8d379b1..850192e6f 100644 --- a/bindings/uniffi/src/config.rs +++ b/bindings/uniffi/src/config.rs @@ -1,11 +1,13 @@ use std::sync::atomic::Ordering; -use zen_engine::ZEN_CONFIG; +use zen_engine::{EXPRESSION_CONFIG, ZEN_CONFIG}; #[derive(uniffi::Record)] pub struct ZenConfig { pub nodes_in_context: Option, pub function_timeout_millis: Option, pub http_auth: Option, + pub expression_max_steps: Option, + pub expression_max_interval_length: Option, } #[uniffi::export] @@ -23,4 +25,16 @@ pub fn override_config(config: ZenConfig) { if let Some(val) = config.http_auth { ZEN_CONFIG.http_auth.store(val, Ordering::Relaxed); } + + if let Some(val) = config.expression_max_steps { + EXPRESSION_CONFIG + .max_steps + .store(val as u64, Ordering::Relaxed); + } + + if let Some(val) = config.expression_max_interval_length { + EXPRESSION_CONFIG + .max_interval_length + .store(val as u64, Ordering::Relaxed); + } } diff --git a/core/engine/README.md b/core/engine/README.md index 6fea3f303..3f1f4e0af 100644 --- a/core/engine/README.md +++ b/core/engine/README.md @@ -59,6 +59,12 @@ async fn main() { } ``` +### Limits for expressions + +Decision tables, expression and switch nodes evaluate expressions with `zen-expression`, whose two global limits +are re-exported here as `EXPRESSION_CONFIG` (`max_steps`, `max_interval_length`; default 0 = no limit). See the +`zen-expression` README. + ### Loaders Attach a loader to serve decisions by key. Build one declaratively from `LoaderConfig` (`Static`, `Filesystem`, `Zip`), or construct the loader structs in `zen_engine::loader` directly. With a configuration, decisions are pre-loaded and pre-compiled for faster evaluations. diff --git a/core/engine/src/lib.rs b/core/engine/src/lib.rs index c66d9d3b0..10213c60c 100644 --- a/core/engine/src/lib.rs +++ b/core/engine/src/lib.rs @@ -147,3 +147,4 @@ pub use engine::{ pub use error::{CompileFailure, ContentKindError, EvaluationError}; pub use workspace::Workspace; pub use zen_expression::Variable; +pub use zen_expression::{ExpressionConfig, EXPRESSION_CONFIG}; diff --git a/core/expression/README.md b/core/expression/README.md index 9dfd7c317..823e3a6f2 100644 --- a/core/expression/README.md +++ b/core/expression/README.md @@ -23,6 +23,23 @@ fn main() { Reusable expressions compile once via `compile_expression` and evaluate repeatedly against different contexts. +## Evaluation budget + +By default an expression can run for as long as it needs and expand an interval to any size, which is fine +for trusted expressions. When expressions come from untrusted sources, two global limits bound one evaluation +(`0` = no limit, the default): + +```rust +use std::sync::atomic::Ordering; +use zen_expression::EXPRESSION_CONFIG; + +EXPRESSION_CONFIG.max_steps.store(1_000_000, Ordering::Relaxed); // VM instructions per evaluation +EXPRESSION_CONFIG.max_interval_length.store(100_000, Ordering::Relaxed); // elements of an expanded `[a..b]` +``` + +When a limit is exceeded the evaluation fails with `VMError::BudgetExceeded`. Membership tests such as +`x in [1..10000]` do not expand the interval and are not affected by `max_interval_length`. + ## Resources - [ZEN Expression Language reference](https://docs.gorules.io/learn/zen-language/syntax) - syntax, [operators](https://docs.gorules.io/learn/zen-language/operators), [built-in functions](https://docs.gorules.io/learn/zen-language/functions) and [date operations](https://docs.gorules.io/learn/zen-language/dates) diff --git a/core/expression/src/config.rs b/core/expression/src/config.rs new file mode 100644 index 000000000..5f155b0bb --- /dev/null +++ b/core/expression/src/config.rs @@ -0,0 +1,28 @@ +//! Global limits for expression evaluation. +//! +//! Both limits default to `0`, which means "no limit" and keeps the historical behaviour. Set them once at +//! startup when expressions come from untrusted or unreviewed sources: a single expression can otherwise +//! allocate without bound (for example by materializing a huge interval) and take the whole process down. +use once_cell::sync::Lazy; +use std::sync::atomic::AtomicU64; + +#[derive(Debug)] +pub struct ExpressionConfig { + /// Maximum number of VM instructions executed by one expression evaluation; 0 = no limit. + /// Loops (`map`, `filter`, `some`, ...) execute a few instructions per element, so this bounds both the + /// time and the memory a loop can take. + pub max_steps: AtomicU64, + /// Maximum number of elements an interval (`[a..b]`) may be expanded to when it is iterated; 0 = no limit. + pub max_interval_length: AtomicU64, +} + +impl Default for ExpressionConfig { + fn default() -> Self { + Self { + max_steps: AtomicU64::new(0), + max_interval_length: AtomicU64::new(0), + } + } +} + +pub static EXPRESSION_CONFIG: Lazy = Lazy::new(Default::default); diff --git a/core/expression/src/lib.rs b/core/expression/src/lib.rs index a5eff1eb9..f046874c4 100644 --- a/core/expression/src/lib.rs +++ b/core/expression/src/lib.rs @@ -60,6 +60,7 @@ mod isolate; pub mod compiler; +pub mod config; mod dates; mod exports; pub mod expression; @@ -78,6 +79,7 @@ pub use exports::{ compile_expression, compile_unary_expression, evaluate_expression, evaluate_unary_expression, }; pub use expression::{Expression, ExpressionKind, OpcodeCache}; +pub use config::{ExpressionConfig, EXPRESSION_CONFIG}; pub use isolate::{Isolate, IsolateError}; pub use scope::Scope; pub use variable::Variable; diff --git a/core/expression/src/vm/error.rs b/core/expression/src/vm/error.rs index 289b2ee28..dc711cf53 100644 --- a/core/expression/src/vm/error.rs +++ b/core/expression/src/vm/error.rs @@ -16,6 +16,9 @@ pub enum VMError { #[error("Number conversion error")] NumberConversionError, + + #[error("Evaluation budget exceeded: {budget} over {limit}")] + BudgetExceeded { budget: &'static str, limit: u64 }, } pub(crate) type VMResult = Result; diff --git a/core/expression/src/vm/interval.rs b/core/expression/src/vm/interval.rs index 5d0ccb24d..7755f8130 100644 --- a/core/expression/src/vm/interval.rs +++ b/core/expression/src/vm/interval.rs @@ -32,7 +32,13 @@ impl DynamicVariable for VmInterval { } impl VmInterval { - pub fn to_array(&self) -> Option> { + /// Number of elements `to_array` would produce, if the interval is a numeric one. + pub fn len(&self) -> Option { + let (start, end) = self.bounds()?; + Some(end.checked_sub(start)?.checked_add(1)? as u64) + } + + fn bounds(&self) -> Option<(i64, i64)> { let (left, right) = match (&self.left, &self.right) { (VmIntervalData::Number(l), VmIntervalData::Number(r)) => (*l, *r), _ => return None, @@ -50,6 +56,11 @@ impl VmInterval { _ => return None, }; + Some((start, end)) + } + + pub fn to_array(&self) -> Option> { + let (start, end) = self.bounds()?; let list = (start..=end) .map(|n| Variable::Number(Decimal::from(n))) .collect::>(); diff --git a/core/expression/src/vm/vm.rs b/core/expression/src/vm/vm.rs index 22ed6e5a4..f16a8af39 100644 --- a/core/expression/src/vm/vm.rs +++ b/core/expression/src/vm/vm.rs @@ -1,4 +1,5 @@ use crate::compiler::{Compare, FetchFastTarget, Jump, Opcode}; +use crate::config::EXPRESSION_CONFIG; use crate::functions::arguments::Arguments; use crate::functions::registry::FunctionRegistry; use crate::functions::{internal, MethodRegistry}; @@ -13,6 +14,7 @@ use crate::vm::VmDate; use rust_decimal::prelude::{FromPrimitive, ToPrimitive}; use rust_decimal::{Decimal, MathematicalOps}; use std::rc::Rc; +use std::sync::atomic::Ordering; use std::string::String as StdString; use zen_types::symbol::Symbol; @@ -85,7 +87,21 @@ impl<'arena, 'parent_ref, 'bytecode_ref> VMInner<'parent_ref, 'bytecode_ref> { self.ip = 0; } + let max_steps = EXPRESSION_CONFIG.max_steps.load(Ordering::Relaxed); + let max_interval_length = EXPRESSION_CONFIG.max_interval_length.load(Ordering::Relaxed); + let mut steps: u64 = 0; + while self.ip < self.bytecode.len() as u32 { + if max_steps > 0 { + steps += 1; + if steps > max_steps { + return Err(BudgetExceeded { + budget: "steps", + limit: max_steps, + }); + } + } + let op = self .bytecode .get(self.ip as usize) @@ -978,14 +994,27 @@ impl<'arena, 'parent_ref, 'bytecode_ref> VMInner<'parent_ref, 'bytecode_ref> { iter: 0, }) } - _ => match var.dynamic::().map(|s| s.to_array()).flatten() { + _ => match var.dynamic::() { + Some(interval) => { + if max_interval_length > 0 { + if let Some(len) = interval.len() { + if len > max_interval_length { + return Err(BudgetExceeded { + budget: "interval length", + limit: max_interval_length, + }); + } + } + } + + interval.to_array().map(|arr| LoopScope { + len: arr.len(), + array: Variable::from_array(arr), + count: 0, + iter: 0, + }) + } None => None, - Some(arr) => Some(LoopScope { - len: arr.len(), - array: Variable::from_array(arr), - count: 0, - iter: 0, - }), }, }; diff --git a/core/expression/tests/isolate.rs b/core/expression/tests/isolate.rs index 0412ca00e..deed6605a 100644 --- a/core/expression/tests/isolate.rs +++ b/core/expression/tests/isolate.rs @@ -1046,3 +1046,36 @@ fn string_index_at_usize_max_returns_null() { let result = isolate.run_standard("s[i]").unwrap(); assert_eq!(result, Variable::Null); } + +#[test] +fn evaluation_budget_limits_steps_and_intervals() { + use std::sync::atomic::Ordering; + use zen_expression::EXPRESSION_CONFIG; + + let mut isolate = Isolate::new(); + + // No limit by default + assert!(isolate.run_standard("len(map([1..10000], # * 2))").is_ok()); + + EXPRESSION_CONFIG.max_steps.store(5_000, Ordering::Relaxed); + let err = isolate + .run_standard("len(map([1..10000], # * 2))") + .unwrap_err() + .to_string(); + assert!(err.contains("budget exceeded") && err.contains("steps"), "{err}"); + assert!(isolate.run_standard("len(map([1..100], # * 2))").is_ok()); + EXPRESSION_CONFIG.max_steps.store(0, Ordering::Relaxed); + + EXPRESSION_CONFIG + .max_interval_length + .store(1_000, Ordering::Relaxed); + let err = isolate + .run_standard("len(map([1..10000], # * 2))") + .unwrap_err() + .to_string(); + assert!(err.contains("budget exceeded") && err.contains("interval"), "{err}"); + // Membership tests on intervals do not expand them + assert!(isolate.run_standard("5 in [1..10000]").is_ok()); + assert!(isolate.run_standard("len(map([1..1000], # * 2))").is_ok()); + EXPRESSION_CONFIG.max_interval_length.store(0, Ordering::Relaxed); +} From ebdae038b477f0b2cf19c5199711b11f408471cd Mon Sep 17 00:00:00 2001 From: Giuseppe Taverniti Date: Wed, 11 Nov 2026 11:00:23 +0100 Subject: [PATCH 2/3] fix(engine): keep the reason in the error of an expression node "Failed to evaluate expression: ..." dropped the underlying VM error, so a caller could not tell a budget error (or any other evaluation error) from a malformed expression. The reason is now appended, as the other nodes already do with node_context_message. --- core/engine/src/nodes/expression/mod.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/core/engine/src/nodes/expression/mod.rs b/core/engine/src/nodes/expression/mod.rs index 40fd46ed4..e002344ae 100644 --- a/core/engine/src/nodes/expression/mod.rs +++ b/core/engine/src/nodes/expression/mod.rs @@ -36,8 +36,12 @@ impl NodeHandler for ExpressionNodeHandler { let value = isolate .run_standard(&expression.value) - .with_node_context(&ctx, |_| { - format!(r#"Failed to evaluate expression: "{}""#, &expression.value) + .with_node_context(&ctx, |err| { + format!( + r#"Failed to evaluate expression: "{}": {}"#, + &expression.value, + err.into() + ) })?; let value = match expression.value.contains('$') { true => value.deep_clone(), From 24918891c8feb6c43f6ef05afcde4202e9bb52a3 Mon Sep 17 00:00:00 2001 From: Giuseppe Taverniti Date: Wed, 11 Nov 2026 11:02:37 +0100 Subject: [PATCH 3/3] fix(engine): IsolateError is Display, no conversion needed --- core/engine/src/nodes/expression/mod.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/core/engine/src/nodes/expression/mod.rs b/core/engine/src/nodes/expression/mod.rs index e002344ae..521cace27 100644 --- a/core/engine/src/nodes/expression/mod.rs +++ b/core/engine/src/nodes/expression/mod.rs @@ -38,9 +38,8 @@ impl NodeHandler for ExpressionNodeHandler { .run_standard(&expression.value) .with_node_context(&ctx, |err| { format!( - r#"Failed to evaluate expression: "{}": {}"#, - &expression.value, - err.into() + r#"Failed to evaluate expression: "{}": {err}"#, + &expression.value ) })?; let value = match expression.value.contains('$') {