#786: fuzz expressions; fix the overflows, hangs and panic it found

Problem: expression text is input we don't control, and nothing fuzzed the
expression parser and evaluator. A seeded mutation fuzzer found stack
overflows (a few hundred `?:`/`=>`/`if`, a few thousand `.`/`<`/`()` links,
75 nested template substitutions or regex groups, a chain inside one
template), hangs (an expression reading its own layer's transform nested
2^16 times; fanning-out reads; 10M-iteration loops re-run per read; loops
calling looping functions), an i64 overflow panic in wiggle noise, and NaN
path vertices tripping the rasterizer's clipping assertion.

Fix: a dependency-free seeded fuzzer (crates/expr/src/tests/fuzz.rs: real
AE-style seeds, char/token mutations, worker thread with a 2 MiB stack,
catch_unwind, deadline, env vars for long runs); a weighted nesting
estimate covering chains without brackets and template/regex insides;
cycle detection per (property, time, text); a per-evaluation budget of
20 000 script runs and 5 s (runs are interrupted through boa's budgeted
evaluation; native only); loop limit 1M; wrapping noise lattice indices;
non-finite path results rejected. Each fix has a regression test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76
2026-10-11 14:40:03 +02:00
co-authored by Claude Opus 5.5
parent 9a7d3e7699
commit 9da66d9063
6 changed files with 820 additions and 28 deletions
+49 -4
View File
@@ -22,7 +22,10 @@
//! `seedRandom`), so frames render identically on every thread and platform.
//! * **Runtime**: one boa `Context` per thread with compiled scripts cached by text. Scripts read
//! the project through memoized host requests (see [`host`]), so nothing borrowed ever enters
//! the JS heap. Expressions reading each other nest up to [`MAX_DEPTH`] levels.
//! the JS heap. Expressions reading each other nest up to [`MAX_DEPTH`] levels; one that needs
//! its own value fails at once, and one evaluation (reads included) runs at most [`MAX_RUNS`]
//! scripts for at most [`MAX_TIME`]. Text nested deeper than the parser's stack allows is refused
//! ([`rewrite::MAX_NESTING`]); a seeded fuzzer (`tests/fuzz.rs`) keeps all of this honest.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -38,12 +41,39 @@ use effectcraft_render::{EvalCtx, ExprHost};
use effectcraft_time::Tick;
use host::{Own, Req, Resolver, prop_dims, value_resp};
use runtime::{Begin, FRAMES, Frame, Run};
use runtime::{Begin, FRAMES, Frame, Owner, RUNS, Run};
/// Maximum nesting of expressions that read other expressions (cycles stop here).
pub const MAX_DEPTH: usize = 16;
/// Maximum script re-runs while answering host requests.
const MAX_PASSES: usize = 2000;
/// Maximum script runs for one outermost evaluation, the expressions it reads included: reads
/// that fan out (an expression reading two values whose expressions each read two more…) grow
/// exponentially with [`MAX_DEPTH`] and would hang the frame.
pub const MAX_RUNS: usize = 20_000;
/// Longest one outermost evaluation may take (its script runs and the expressions it reads),
/// checked between runs and while a script runs: endless or very long loops, and a script that
/// loops a while and then reads many values (re-running the loop once per value), stop here.
/// Native builds only (the web build has no clock here; loops stop at the loop limit there).
pub const MAX_TIME: std::time::Duration = std::time::Duration::from_secs(5);
/// Start the work budget of an outermost evaluation.
fn budget_start() {
RUNS.with(|r| r.set(0));
#[cfg(not(target_arch = "wasm32"))]
runtime::STARTED.with(|s| s.set(Some(std::time::Instant::now())));
}
/// An error once the outermost evaluation has used up its runs or its time.
fn budget_left() -> Result<(), String> {
if RUNS.with(|r| r.get()) >= MAX_RUNS {
return Err("Error: expression reads too many other expressions' values (circular or fanning-out references?)".into());
}
if runtime::out_of_time() {
return Err(runtime::TIMED_OUT.into());
}
Ok(())
}
/// The expression engine (stateless; runtimes are per thread).
#[derive(Clone, Copy, Debug, Default)]
@@ -111,10 +141,23 @@ fn evaluate_out(
text_sel: [f64; 2],
selector: [f64; 3],
) -> Result<runtime::Out, String> {
let depth = FRAMES.with(|f| f.borrow().len());
let owner = Owner { comp: ctx.comp_id.0, layer: layer.id.0, uid: prop.uid, time: ctx.time, text: text.to_string() };
let (depth, cycle) = FRAMES.with(|f| {
let f = f.borrow();
(f.len(), f.iter().any(|fr| fr.owner.as_ref() == Some(&owner)))
});
if depth == 0 {
budget_start();
}
if cycle {
// Needs its own result: fails at once (the reader falls back to the keyframed value)
// instead of nesting to `MAX_DEPTH` once per read on the way.
return Err("Error: circular expression reference (the expression needs its own value)".into());
}
if depth >= MAX_DEPTH {
return Err("Error: expressions reference each other too deeply (circular reference?)".into());
}
budget_left()?;
let ctx = EvalCtx { project: ctx.project, comp_id: ctx.comp_id, comp: ctx.comp, time: ctx.time, expr: Some(host), footage: ctx.footage };
let comp = ctx.comp_id.0;
let path = layer.props.path_of(prop.uid).unwrap_or_else(|| format!("@{}", prop.uid));
@@ -133,7 +176,7 @@ fn evaluate_out(
selector,
};
// Answer the requests nearly every expression makes up front.
let mut frame = Frame::default();
let mut frame = Frame { owner: Some(owner), ..Frame::default() };
for req in [Req::CompInfo { comp }, Req::LayerInfo { comp, layer: layer.id.0 }, Req::PropInfo { comp, layer: layer.id.0, path: path.clone() }] {
let r = resolver.resolve(&req);
frame.memo.insert(req, r);
@@ -141,6 +184,8 @@ fn evaluate_out(
FRAMES.with(|f| f.borrow_mut().push(frame));
let _guard = FrameGuard;
for _ in 0..MAX_PASSES {
budget_left()?;
RUNS.with(|r| r.set(r.get().saturating_add(1)));
match runtime::run(text, &begin) {
Run::Done(r) => return r,
Run::Pending => {