Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion bindings/nodejs/src/config.rs
Original file line number Diff line number Diff line change
@@ -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<bool>,
pub function_timeout_millis: Option<u32>,
pub http_auth: Option<bool>,
pub expression_max_steps: Option<u32>,
pub expression_max_interval_length: Option<u32>,
}

#[allow(dead_code)]
Expand All @@ -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);
}
}
16 changes: 15 additions & 1 deletion bindings/uniffi/src/config.rs
Original file line number Diff line number Diff line change
@@ -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<bool>,
pub function_timeout_millis: Option<u32>,
pub http_auth: Option<bool>,
pub expression_max_steps: Option<u32>,
pub expression_max_interval_length: Option<u32>,
}

#[uniffi::export]
Expand All @@ -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);
}
}
6 changes: 6 additions & 0 deletions core/engine/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions core/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
7 changes: 5 additions & 2 deletions core/engine/src/nodes/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,11 @@ 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: "{}": {err}"#,
&expression.value
)
})?;
let value = match expression.value.contains('$') {
true => value.deep_clone(),
Expand Down
17 changes: 17 additions & 0 deletions core/expression/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
28 changes: 28 additions & 0 deletions core/expression/src/config.rs
Original file line number Diff line number Diff line change
@@ -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<ExpressionConfig> = Lazy::new(Default::default);
2 changes: 2 additions & 0 deletions core/expression/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
mod isolate;

pub mod compiler;
pub mod config;
mod dates;
mod exports;
pub mod expression;
Expand All @@ -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;
3 changes: 3 additions & 0 deletions core/expression/src/vm/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> = Result<T, VMError>;
13 changes: 12 additions & 1 deletion core/expression/src/vm/interval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,13 @@ impl DynamicVariable for VmInterval {
}

impl VmInterval {
pub fn to_array(&self) -> Option<Vec<Variable>> {
/// Number of elements `to_array` would produce, if the interval is a numeric one.
pub fn len(&self) -> Option<u64> {
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,
Expand All @@ -50,6 +56,11 @@ impl VmInterval {
_ => return None,
};

Some((start, end))
}

pub fn to_array(&self) -> Option<Vec<Variable>> {
let (start, end) = self.bounds()?;
let list = (start..=end)
.map(|n| Variable::Number(Decimal::from(n)))
.collect::<Vec<_>>();
Expand Down
43 changes: 36 additions & 7 deletions core/expression/src/vm/vm.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand All @@ -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;

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -978,14 +994,27 @@ impl<'arena, 'parent_ref, 'bytecode_ref> VMInner<'parent_ref, 'bytecode_ref> {
iter: 0,
})
}
_ => match var.dynamic::<VmInterval>().map(|s| s.to_array()).flatten() {
_ => match var.dynamic::<VmInterval>() {
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,
}),
},
};

Expand Down
33 changes: 33 additions & 0 deletions core/expression/tests/isolate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}