From 65e3eb9d114bdc05ad20b13c6c593763fe03ed0d Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 18:56:54 -0800 Subject: [PATCH] fix(model): harden parser recursion, non-finite boundaries, and serializer parity --- crates/model/src/comp.rs | 9 +- crates/model/src/comp/eval.rs | 24 +- crates/model/src/comp/load.rs | 47 ++- crates/model/src/comp/math.rs | 53 ++- crates/model/src/comp/save.rs | 69 ++-- crates/model/src/expr.rs | 3 + crates/model/src/lua_value.rs | 50 ++- crates/model/src/spline.rs | 41 ++- crates/model/tests/hardening_model.rs | 447 ++++++++++++++++++++++++++ 9 files changed, 637 insertions(+), 106 deletions(-) create mode 100644 crates/model/tests/hardening_model.rs diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index a7dbeaa13aee34cd811ee011b1729308e58bf081..78701bbe6d8c3647bc138e809f22ccfa24b3c03a 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -232,7 +232,7 @@ impl SaverSpec { /// - `render.png` -> `render{frame:04}.png` (4-digit default when no trailing digits exist) pub fn frame_path(&self, frame: i64) -> PathBuf { let effective_frame = if let Some(start) = self.sequence_start { - start + (frame - self.range[0]) + start.saturating_add(frame.saturating_sub(self.range[0])) } else { frame }; @@ -246,11 +246,8 @@ impl SaverSpec { None => (fname, ""), }; - let digit_start = stem - .rfind(|c: char| !c.is_ascii_digit()) - .map_or(0, |idx| idx + 1); - let prefix = &stem[..digit_start]; - let digits = &stem[digit_start..]; + let prefix = stem.trim_end_matches(|c: char| c.is_ascii_digit()); + let digits = &stem[prefix.len()..]; let width = if digits.is_empty() { 4 } else { digits.len() }; let formatted_num = if effective_frame < 0 { diff --git a/crates/model/src/comp/eval.rs b/crates/model/src/comp/eval.rs index 1a3fe76e6a928ba6b6da51b64bdde5f0babc6ea4..847e684841e2f9b0558b0d2e7e3ef50f9b61912a 100644 --- a/crates/model/src/comp/eval.rs +++ b/crates/model/src/comp/eval.rs @@ -88,7 +88,7 @@ impl Comp { if kfs.is_empty() { return None; } - if kfs.len() == 1 || time <= kfs[0].0 { + if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 { return Some(kfs[0].1.clone()); } if time >= kfs[kfs.len() - 1].0 { @@ -261,7 +261,9 @@ impl Comp { } if let Some(expr) = &binding.expression { if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) { - return p; + if p[0].is_finite() && p[1].is_finite() { + return p; + } } } if let Some(src) = &binding.source_op { @@ -329,7 +331,12 @@ impl Comp { } fn eval_shake_axis(&self, sh: &ShakeModifier, axis: u32, time: f64, expr_engine: &ExprEngine) -> f64 { - let smoothness = self.eval_shake_input(sh, "Smoothness", time, 1.0, expr_engine).max(0.01); + let smoothness_raw = self.eval_shake_input(sh, "Smoothness", time, 1.0, expr_engine); + let smoothness = if smoothness_raw.is_finite() { + smoothness_raw.max(0.01) + } else { + 1.0 + }; let seed = self.eval_shake_input(sh, "RandomSeed", time, 0.0, expr_engine).round() as i64; let lock_xy = self.eval_shake_input(sh, "LockXY", time, 1.0, expr_engine) > 0.5; let (min_v, max_v) = if axis == 0 || lock_xy { @@ -345,6 +352,9 @@ impl Comp { }; // Smooth Catmull-Rom interpolation over seeded lattice points spaced by `smoothness` frames let u = time / smoothness; + if !u.is_finite() || u.abs() >= 4.5e15 { + return min_v; + } let k = u.floor() as i64; let f = u - k as f64; let hash01 = |i: i64| -> f64 { @@ -356,10 +366,10 @@ impl Comp { x ^= x >> 31; (x >> 11) as f64 / (1u64 << 53) as f64 }; - let p0 = hash01(k - 1); + let p0 = hash01(k.wrapping_sub(1)); let p1 = hash01(k); - let p2 = hash01(k + 1); - let p3 = hash01(k + 2); + let p2 = hash01(k.wrapping_add(1)); + let p3 = hash01(k.wrapping_add(2)); let f2 = f * f; let f3 = f2 * f; let cr = 0.5 * ((2.0 * p1) @@ -788,7 +798,7 @@ impl Comp { if kfs.is_empty() { return None; } - if kfs.len() == 1 || time <= kfs[0].0 { + if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 { return Some(kfs[0].1.clone()); } let last = &kfs[kfs.len() - 1]; diff --git a/crates/model/src/comp/load.rs b/crates/model/src/comp/load.rs index b682db0ee04d4ab5595ed382a52881833d4ea981..08eb490ae221fbc637fc5c09bf73128114d911ba 100644 --- a/crates/model/src/comp/load.rs +++ b/crates/model/src/comp/load.rs @@ -30,19 +30,19 @@ impl Comp { }); }; - let current_time = root.get_f64("CurrentTime").unwrap_or(0.0); + let current_time = root.get_f64("CurrentTime").filter(|t| t.is_finite()).unwrap_or(0.0); let global_range = root .get_table("GlobalRange") .and_then(read_vec2) - .map(|[a, b]| [a as i64, b as i64]) + .and_then(normalize_frame_range) .unwrap_or([0, 1000]); let render_range = root .get_table("RenderRange") .and_then(read_vec2) - .map(|[a, b]| [a as i64, b as i64]) + .and_then(normalize_frame_range) .unwrap_or(global_range); let audio_filename = root.get_str("AudioFilename").map(str::to_owned); - let audio_offset = root.get_f64("AudioOffset").unwrap_or(0.0); + let audio_offset = root.get_f64("AudioOffset").filter(|t| t.is_finite()).unwrap_or(0.0); // Extract FrameFormat from Prefs.Comp.FrameFormat (default 1920x1080 @ 30fps, Int8) let mut width = 1920u32; @@ -55,20 +55,22 @@ impl Comp { .and_then(|p| p.get_table("Comp")) .and_then(|c| c.get_table("FrameFormat")) { - if let Some(w) = ff.get_f64("Width") { - width = w.round().max(1.0) as u32; + if let Some(w) = ff.get_f64("Width").and_then(normalize_frame_dim) { + width = w; explicit_size = true; } - if let Some(h) = ff.get_f64("Height") { - height = h.round().max(1.0) as u32; + if let Some(h) = ff.get_f64("Height").and_then(normalize_frame_dim) { + height = h; explicit_size = true; } - if let Some(r) = ff.get_f64("Rate") { - if r > 0.0 { - fps = r; - } + if let Some(r) = ff.get_f64("Rate").filter(|r| r.is_finite() && *r > 0.0) { + fps = r; } - if let Some(d) = ff.get_f64("DepthFull").and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) { + if let Some(d) = ff + .get_f64("DepthFull") + .filter(|v| v.is_finite()) + .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) + { depth_full = d; } } @@ -263,9 +265,9 @@ impl Comp { for n in &nodes { if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") { if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) { - if w >= 64.0 && h >= 64.0 { - width = w as u32; - height = h as u32; + if w.is_finite() && h.is_finite() && w >= 64.0 && h >= 64.0 { + width = normalize_frame_dim(w).unwrap_or(width); + height = normalize_frame_dim(h).unwrap_or(height); break; } } @@ -304,6 +306,19 @@ impl Comp { } +pub(super) fn normalize_frame_dim(v: f64) -> Option { + v.is_finite() + .then(|| v.round().clamp(1.0, 65536.0) as u32) +} + +fn normalize_frame_range([a, b]: [f64; 2]) -> Option<[i64; 2]> { + (a.is_finite() && b.is_finite()).then(|| { + let lo = i32::MIN as f64; + let hi = i32::MAX as f64; + [a.round().clamp(lo, hi) as i64, b.round().clamp(lo, hi) as i64] + }) +} + /// Fusion resolves a macro-internal `SourceOp` only within the macro's own scope (itself, its /// enclosing macros, its nested macros) or at top level; a name that only exists inside an /// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was diff --git a/crates/model/src/comp/math.rs b/crates/model/src/comp/math.rs index e62ecb1dc17403f5e3d64db644f552f729fa4d18..55d6efe410c8a32b21041488b6455f6e1b7e295a 100644 --- a/crates/model/src/comp/math.rs +++ b/crates/model/src/comp/math.rs @@ -30,7 +30,11 @@ impl GridMesh { if tbl.tag.as_deref() != Some("Mesh") { return None; } - let cols = tbl.get_f64("Col")?.round().max(2.0) as usize; + let cols_f = tbl.get_f64("Col")?; + if !cols_f.is_finite() { + return None; + } + let cols = cols_f.round().clamp(2.0, 65536.0) as usize; let pts_tbl = tbl.get_table("Points")?; let mut points = Vec::new(); for pval in pts_tbl.positional_values() { @@ -48,7 +52,7 @@ impl GridMesh { b_cy: pt.get_f64("B_CY"), }); } - if points.len() < cols * 2 { + if points.len() < cols.checked_mul(2)? { return None; } let rows = points.len() / cols; @@ -148,7 +152,7 @@ impl Comp { } if !kfs.is_empty() { kfs.sort_by(|a, b| a.0.total_cmp(&b.0)); - if kfs.len() == 1 || time <= kfs[0].0 { + if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 { return Some(kfs[0].1.clone()); } if time >= kfs[kfs.len() - 1].0 { @@ -182,13 +186,25 @@ impl Comp { /// Evaluates a Fusion `Expression` modifier math formula (C-like Fusion math DSL) to an `f64`. /// Returns `None` if syntax is not recognized so callers can fall back to Lua `ExprEngine`. pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap) -> Option { + const MAX_EXPR_DEPTH: usize = 64; + struct Parser<'a> { bytes: &'a [u8], pos: usize, vars: &'a HashMap, + depth: usize, } impl<'a> Parser<'a> { + fn with_depth(&mut self, f: impl FnOnce(&mut Self) -> Option) -> Option { + if self.depth >= MAX_EXPR_DEPTH { + return None; + } + self.depth += 1; + let res = f(self); + self.depth -= 1; + res + } fn skip_ws(&mut self) { while self.pos < self.bytes.len() { let b = self.bytes[self.pos]; @@ -220,17 +236,19 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap) -> O } fn parse_or(&mut self) -> Option { - let mut v = self.parse_and()?; - loop { - self.skip_ws(); - if self.eat_str("||") || self.eat_str("|") { - let r = self.parse_and()?; - v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 }; - } else { - break; + self.with_depth(|p| { + let mut v = p.parse_and()?; + loop { + p.skip_ws(); + if p.eat_str("||") || p.eat_str("|") { + let r = p.parse_and()?; + v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 }; + } else { + break; + } } - } - Some(v) + Some(v) + }) } fn parse_and(&mut self) -> Option { @@ -322,7 +340,7 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap) -> O let base = self.parse_unary()?; if self.peek() == Some(b'^') { self.pos += 1; - let exp = self.parse_pow()?; + let exp = self.with_depth(Self::parse_pow)?; Some(if base > 0.0 { base.powf(exp) } else if base == 0.0 { @@ -342,15 +360,15 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap) -> O match self.peek() { Some(b'-') => { self.pos += 1; - Some(-self.parse_unary()?) + Some(-self.with_depth(Self::parse_unary)?) } Some(b'+') => { self.pos += 1; - self.parse_unary() + self.with_depth(Self::parse_unary) } Some(b'!') => { self.pos += 1; - let v = self.parse_unary()?; + let v = self.with_depth(Self::parse_unary)?; Some(if v == 0.0 { 1.0 } else { 0.0 }) } _ => self.parse_primary(), @@ -509,6 +527,7 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap) -> O bytes: src.as_bytes(), pos: 0, vars, + depth: 0, }; let val = p.parse_or()?; p.skip_ws(); diff --git a/crates/model/src/comp/save.rs b/crates/model/src/comp/save.rs index 73cfb0abf5e9561fa677d37601cd9ef9735c5cc4..080b4e9fd2722b03a265a24e9f0c8fd66509cca2 100644 --- a/crates/model/src/comp/save.rs +++ b/crates/model/src/comp/save.rs @@ -1,4 +1,4 @@ -use super::load::{parse_input_binding, parse_param_value}; +use super::load::{normalize_frame_dim, parse_input_binding, parse_param_value}; use super::math::find_raw_tool_mut; use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type}; use crate::lua_value::{ @@ -92,30 +92,8 @@ impl Comp { } // Update Prefs.Comp.FrameFormat (Width, Height, Rate, DepthFull) - { - let prefs = ensure_table_mut(&mut root, "Prefs", None); - let comp_prefs = ensure_table_mut(prefs, "Comp", None); - let ff = ensure_table_mut(comp_prefs, "FrameFormat", None); - if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) { - ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64)); - } - if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) { - ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64)); - } - if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) { - ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps)); - } - let existing_depth = ff - .get_f64("DepthFull") - .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) - .unwrap_or(BitDepth::Int8); - if existing_depth != self.depth_full { - ff.set( - LuaKey::Str("DepthFull".to_owned()), - LuaValue::Number((self.depth_full as i32) as f64), - ); - } - } + let prefs = ensure_table_mut(&mut root, "Prefs", None); + self.patch_prefs_table(prefs); // Sync Tools let tools = ensure_table_mut(&mut root, "Tools", Some("ordered")); @@ -533,17 +511,21 @@ impl Comp { else { return true; }; - if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) { + if ff.get_f64("Width").and_then(normalize_frame_dim) != Some(self.width) { return true; } - if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) { + if ff.get_f64("Height").and_then(normalize_frame_dim) != Some(self.height) { return true; } - if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) { + if ff + .get_f64("Rate") + .is_none_or(|r| !r.is_finite() || (r - self.fps).abs() > 1e-9) + { return true; } let existing_depth = ff .get_f64("DepthFull") + .filter(|v| v.is_finite()) .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) .unwrap_or(BitDepth::Int8); existing_depth != self.depth_full @@ -552,17 +534,21 @@ impl Comp { fn patch_prefs_table(&self, prefs: &mut LuaTable) { let comp_prefs = ensure_table_mut(prefs, "Comp", None); let ff = ensure_table_mut(comp_prefs, "FrameFormat", None); - if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) { + if ff.get_f64("Width").and_then(normalize_frame_dim) != Some(self.width) { ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64)); } - if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) { + if ff.get_f64("Height").and_then(normalize_frame_dim) != Some(self.height) { ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64)); } - if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) { + if ff + .get_f64("Rate") + .is_none_or(|r| !r.is_finite() || (r - self.fps).abs() > 1e-9) + { ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps)); } let existing_depth = ff .get_f64("DepthFull") + .filter(|v| v.is_finite()) .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) .unwrap_or(BitDepth::Int8); if existing_depth != self.depth_full { @@ -933,6 +919,9 @@ impl Comp { if !remaining_splines.is_empty() { for (k, v) in &inner_tools.entries { let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) { + continue; + } if !top_level_spline_names.contains(name.as_str()) && !claimed_splines.contains(name.as_str()) { @@ -1116,7 +1105,10 @@ fn commit_inner_tools_verbatim<'a>( // (matching `sync_existing_splines_in_tools` top-down order). if !remaining_splines.is_empty() { for (k, v) in &inner_tools.entries { - let (LuaKey::Str(name), Some(_)) = (k, v.as_table()) else { continue }; + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) { + continue; + } if !top_level_spline_names.contains(name.as_str()) { remaining_splines.remove(name.as_str()); if remaining_splines.is_empty() { @@ -1157,6 +1149,9 @@ fn nested_splines_verbatim<'a, 'b>( } for (k, v) in &tools.entries { let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) { + continue; + } if !top_level_spline_names.contains(name.as_str()) && !claimed_splines.contains(name.as_str()) { @@ -1192,7 +1187,10 @@ fn consume_nested_splines( return; } for (k, v) in &tools.entries { - let (LuaKey::Str(name), Some(_)) = (k, v.as_table()) else { continue }; + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) { + continue; + } if !top_level_spline_names.contains(name.as_str()) { remaining_splines.remove(name.as_str()); if remaining_splines.is_empty() { @@ -1220,7 +1218,7 @@ fn sync_existing_splines_in_tools_excluding( } for (k, v) in &mut tools.entries { let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue }; - if excluded.contains(name.as_str()) { + if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) || excluded.contains(name.as_str()) { continue; } if let Some(spline) = remaining.remove(name.as_str()) { @@ -1799,6 +1797,9 @@ fn sync_existing_splines_in_tools(tools: &mut LuaTable, remaining: &mut HashMap< } for (k, v) in &mut tools.entries { let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue }; + if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) { + continue; + } if let Some(spline) = remaining.remove(name.as_str()) { sync_spline_table(name, spline, tbl); if remaining.is_empty() { diff --git a/crates/model/src/expr.rs b/crates/model/src/expr.rs index 76663e86e1c3f889f4198b0220dce2cd88b77ae5..367144748162a1e2d3b04520591ce3511c20dd25 100644 --- a/crates/model/src/expr.rs +++ b/crates/model/src/expr.rs @@ -715,6 +715,9 @@ mod pure { let mut toks = Vec::new(); let mut i = 0; while i < chars.len() { + if toks.len() >= MAX_TOKENS { + return None; + } let c = chars[i]; if c.is_whitespace() { i += 1; diff --git a/crates/model/src/lua_value.rs b/crates/model/src/lua_value.rs index e9ecbeb5a7366ee68bd26550482642e7a6681a9b..9e894387a52152a5c4797d72739c1b99b30665ba 100644 --- a/crates/model/src/lua_value.rs +++ b/crates/model/src/lua_value.rs @@ -182,9 +182,12 @@ pub fn parse_lua(input: &str) -> Result { Ok(val) } +const MAX_PARSE_DEPTH: usize = 128; + struct Parser<'a> { src: &'a [u8], pos: usize, + depth: usize, } impl<'a> Parser<'a> { @@ -194,7 +197,17 @@ impl<'a> Parser<'a> { if input.as_bytes().starts_with(&[0xEF, 0xBB, 0xBF]) { pos = 3; } - Self { src: input.as_bytes(), pos } + Self { src: input.as_bytes(), pos, depth: 0 } + } + + fn with_depth(&mut self, f: impl FnOnce(&mut Self) -> Result) -> Result { + if self.depth >= MAX_PARSE_DEPTH { + return Err(self.err(format!("maximum nesting depth ({MAX_PARSE_DEPTH}) exceeded"))); + } + self.depth += 1; + let res = f(self); + self.depth -= 1; + res } fn err(&self, msg: impl Into) -> ParseError { @@ -387,22 +400,25 @@ impl<'a> Parser<'a> { // Handle calls like `ordered() { ... }` or `FuID("...")` or `Clip(...)` if self.peek() == Some(b'(') { self.pos += 1; - let mut args = Vec::new(); - self.skip_ws_and_comments()?; - if self.peek() != Some(b')') { - loop { - args.push(self.parse_value()?); - self.skip_ws_and_comments()?; - if self.peek() == Some(b',') { - self.pos += 1; - } else { - break; + let args = self.with_depth(|p| { + let mut args = Vec::new(); + p.skip_ws_and_comments()?; + if p.peek() != Some(b')') { + loop { + args.push(p.parse_value()?); + p.skip_ws_and_comments()?; + if p.peek() == Some(b',') { + p.pos += 1; + } else { + break; + } } } - } - if self.bump() != Some(b')') { - return Err(self.err(format!("expected ')' after {ident}(..."))); - } + if p.bump() != Some(b')') { + return Err(p.err(format!("expected ')' after {ident}(..."))); + } + Ok(args) + })?; self.skip_ws_and_comments()?; if self.peek() == Some(b'{') { let mut table = self.parse_table(Some(ident))?; @@ -438,6 +454,10 @@ impl<'a> Parser<'a> { } fn parse_table(&mut self, tag: Option) -> Result { + self.with_depth(|p| p.parse_table_inner(tag)) + } + + fn parse_table_inner(&mut self, tag: Option) -> Result { if self.bump() != Some(b'{') { return Err(self.err("expected '{'")); } diff --git a/crates/model/src/spline.rs b/crates/model/src/spline.rs index b64281919b99f47768ea53c683fe7cdae50c506d..a63ab8e988a109787c147c5fef091f1f7715ecfd 100644 --- a/crates/model/src/spline.rs +++ b/crates/model/src/spline.rs @@ -83,10 +83,19 @@ impl BezierSpline { LuaKey::Number(n) => *n, _ => continue, }; + if !time.is_finite() { + continue; + } let Some(kt) = v.as_table() else { continue }; let value = kt.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0); - let lh = kt.get_table("LH").and_then(read_vec2); - let rh = kt.get_table("RH").and_then(read_vec2); + if !value.is_finite() { + continue; + } + let finite_vec2 = |t: &LuaTable| { + read_vec2(t).filter(|[x, y]| x.is_finite() && y.is_finite()) + }; + let lh = kt.get_table("LH").and_then(finite_vec2); + let rh = kt.get_table("RH").and_then(finite_vec2); let mut flags = KeyFlags::default(); if let Some(ft) = kt.get_table("Flags") { flags.linear = ft.get_bool("Linear").unwrap_or(false); @@ -133,17 +142,19 @@ impl BezierSpline { let last = &kfs[kfs.len() - 1]; // Fusion never loops backwards before the first keyframe (`Loop` / `LoopRel` / `PingPong` all clamp). - if t <= first.time { + if t.is_nan() || t <= first.time { return first.value; } // In Fusion, `Loop` / `LoopRel` requires at least two loop-flagged keyframes (`loop_start < loop_end`). // The loop repeats `[loop_start, loop_end]` for `t >= loop_end.time` up to the next keyframe (if any). let is_loop_key = |k: &Keyframe| k.flags.loop_after || k.flags.loop_rel; - let loop_pair = kfs.iter().position(is_loop_key).and_then(|s| { - let e = kfs.iter().rposition(is_loop_key)?; - (s < e).then_some((s, e)) - }); + let loop_pair = t.is_finite().then(|| { + kfs.iter().position(is_loop_key).and_then(|s| { + let e = kfs.iter().rposition(is_loop_key)?; + (s < e).then_some((s, e)) + }) + }).flatten(); let mut t = t; let mut value_offset = 0.0_f64; @@ -230,13 +241,14 @@ pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] { let p3 = [k1.time, k1.value]; let dt = k1.time - k0.time; let dv = k1.value - k0.value; - // Keys can be transiently unsorted mid-drag; `f64::clamp` would panic on `lo > hi`. + // Keys can be transiently unsorted mid-drag; `f64::clamp` would panic on `lo > hi` or `NaN`. let (t_lo, t_hi) = (k0.time.min(k1.time), k0.time.max(k1.time)); + let clamp_t = |x: f64| if t_lo <= t_hi { x.clamp(t_lo, t_hi) } else { x }; let p1 = if k1.flags.linear && k0.rh.is_none() { [k0.time + dt / 3.0, k0.value + dv / 3.0] } else if let Some(rh) = k0.rh { - [rh[0].clamp(t_lo, t_hi), rh[1]] + [clamp_t(rh[0]), rh[1]] } else { [k0.time + dt / 3.0, k0.value + dv / 3.0] }; @@ -244,7 +256,7 @@ pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] { let p2 = if k1.flags.linear && k1.lh.is_none() { [k1.time - dt / 3.0, k1.value - dv / 3.0] } else if let Some(lh) = k1.lh { - [lh[0].clamp(t_lo, t_hi), lh[1]] + [clamp_t(lh[0]), lh[1]] } else { [k1.time - dt / 3.0, k1.value - dv / 3.0] }; @@ -428,9 +440,16 @@ impl PolyPath { } } - if cum_len <= 1e-12 { + if cum_len <= 1e-12 || displacement.is_nan() { return samples[0].1; } + if !displacement.is_finite() { + return if displacement.is_sign_positive() { + samples[samples.len() - 1].1 + } else { + samples[0].1 + }; + } // Extrapolate smoothly along end/start tangent when displacement is outside [0, 1] if displacement > 1.0 && samples.len() >= 2 { let (l0, v0) = samples[samples.len() - 2]; diff --git a/crates/model/tests/hardening_model.rs b/crates/model/tests/hardening_model.rs new file mode 100644 index 0000000000000000000000000000000000000000..b638efd75c328ab4dfc76a5d26e62c468da51742 --- /dev/null +++ b/crates/model/tests/hardening_model.rs @@ -0,0 +1,447 @@ +use model::comp::{BitDepth, Comp, NodeId, ParamValue, SaverSpec}; +use model::edit::CompHistory; +use model::expr::ExprEngine; +use model::lua_value::{LuaTable, parse_lua}; +use model::spline::{BezierSpline, HandleMode, KeyFlags, Keyframe, PolyPath, PolyPoint, segment_control_points}; +use std::collections::HashMap; + +fn ast_fusion_string(comp: &Comp) -> String { + let mut s = comp.sync_to_raw_ast().to_fusion_string(); + if !s.ends_with('\n') { + s.push('\n'); + } + s +} + +fn assert_save_equivalence_and_reparse(comp: &Comp) { + let streamed = comp.to_fusion_string(); + let ast = ast_fusion_string(comp); + assert_eq!(streamed, ast, "streaming vs AST save divergence"); + Comp::from_fusion_str(&streamed).expect("saved comp must re-parse cleanly"); +} + +#[test] +fn lua_parser_bounds_deep_nesting_without_stack_overflow() { + for depth in [200, 500, 5000] { + let open_tables = "{".repeat(depth); + assert!(parse_lua(&open_tables).is_err(), "unclosed tables depth {depth}"); + + let closed_tables = format!("{}1{}", "{".repeat(depth), "}".repeat(depth)); + assert!(parse_lua(&closed_tables).is_err(), "closed tables depth {depth}"); + + let nested_calls = format!("{}1{}", "Foo(".repeat(depth), ")".repeat(depth)); + assert!(parse_lua(&nested_calls).is_err(), "nested calls depth {depth}"); + + let nested_keys = format!("{}1{}", "{[".repeat(depth), "]=1}".repeat(depth)); + assert!(parse_lua(&nested_keys).is_err(), "nested keys depth {depth}"); + + let nested_groups = format!( + "Composition {{ Tools = ordered() {{ {} }} }}", + "G = GroupOperator { Tools = ordered() { ".repeat(depth / 2) + + &"} } ".repeat(depth / 2) + ); + assert!(Comp::from_fusion_str(&nested_groups).is_err(), "nested groups depth {depth}"); + } + + // Legitimate Fusion-like nesting well under the cap still parses cleanly. + let ok = format!("{}42{}", "{".repeat(32), "}".repeat(32)); + assert!(parse_lua(&ok).is_ok()); +} + +#[test] +fn malformed_comp_prefixes_escapes_nul_brackets_and_huge_numbers_never_panic() { + let sample = r#"Composition { + CurrentTime = 10, + GlobalRange = { 0, 100 }, + RenderRange = { 0, 100 }, + Prefs = { Comp = { FrameFormat = { Width = 1920, Height = 1080, Rate = 24 } } }, + Tools = ordered() { + BG1 = Background { Inputs = { Width = Input { Value = 1920 } } }, + Blur1 = Blur { Inputs = { Input = Input { SourceOp = "BG1", Source = "Output" } } }, + }, + }"#; + + // Every UTF-8 prefix truncation must return Ok or Err without panicking or hanging. + for (idx, _) in sample.char_indices() { + let _ = Comp::from_fusion_str(&sample[..idx]); + } + + // Deterministic byte/char mutations over a representative comp never panic or hang. + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let mut next_u32 = || -> u32 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 16) as u32 + }; + let sample_bytes = sample.as_bytes(); + for _ in 0..256 { + let mut buf = sample_bytes.to_vec(); + let edits = 1 + (next_u32() as usize % 6); + for _ in 0..edits { + let pos = next_u32() as usize % buf.len(); + match next_u32() % 3 { + 0 => buf[pos] = next_u32() as u8, + 1 if buf.len() > 1 => { + buf.remove(pos); + } + _ => buf.insert(pos, next_u32() as u8), + } + } + let mutated = String::from_utf8_lossy(&buf); + if let Ok(comp) = Comp::from_fusion_str(&mutated) { + let _ = comp.to_fusion_string(); + } + } + + // Bad escapes, unterminated strings/long brackets/comments, bare NUL bytes. + for bad in [ + "", + " -- just a comment", + "\0", + "Composition { \0 }", + r#"Composition { Name = "unterminated"#, + r#"Composition { Name = "bad\x" }"#, + r#"Composition { Name = "bad\xZZ" }"#, + r#"Composition { Name = [===[unterminated ]==] }"#, + r#"--[===[unterminated comment ]==] Composition {}"#, + "12345", + "nil", + "\"not a table\"", + ] { + assert!(Comp::from_fusion_str(bad).is_err(), "expected Err for {bad:?}"); + } + + // NUL inside quoted strings/long brackets/comments and huge numbers survive roundtrip. + let weird = concat!( + "-- comment with \0 nul\n", + "Composition {\n", + "\tTools = ordered() {\n", + "\t\tN1 = Note { Inputs = { Comments = Input { Value = \"a\0b\\255\" } } },\n", + "\t\tN2 = Note { Inputs = { Comments = Input { Value = [=[x\0y]=] } } },\n", + "\t\tB1 = Blur { Inputs = { XBlurSize = Input { Value = 1e9999 } } },\n", + "\t\tB2 = Blur { Inputs = { XBlurSize = Input { Value = -1e9999 } } },\n", + "\t\tB3 = Blur {},\n", + "\t},\n", + "}\n" + ); + let comp = Comp::from_fusion_str(weird).expect("weird valid comp parses"); + assert_save_equivalence_and_reparse(&comp); +} + +#[test] +fn non_finite_and_degenerate_metadata_normalizes_and_saves_equivalently() { + let weird_meta = r#"Composition { + CurrentTime = nan, + AudioOffset = 1e9999, + GlobalRange = { nan, 1e9999 }, + RenderRange = { -1e9999, nan }, + Prefs = { Comp = { FrameFormat = { Width = 1e9999, Height = nan, Rate = 1e9999, DepthFull = nan } } }, + Tools = ordered() { + A = Blur {}, + B = Blur {}, + C = Blur {}, + D = Blur {}, + E = Blur {}, + }, + }"#; + let comp = Comp::from_fusion_str(weird_meta).expect("parses comp with non-finite metadata"); + assert_eq!(comp.width, 1920); + assert_eq!(comp.height, 1080); + assert_eq!(comp.fps, 30.0); + assert_eq!(comp.depth_full, BitDepth::Int8); + assert_eq!(comp.current_time, 0.0); + assert_eq!(comp.audio_offset, 0.0); + assert_eq!(comp.global_range, [0, 1000]); + assert_eq!(comp.render_range, [0, 1000]); + assert_save_equivalence_and_reparse(&comp); + + // Non-table Prefs / Tools, empty Tools, and inferred huge Background sizes. + for src in [ + "Composition { Prefs = 123, Tools = 123 }", + "Composition { Prefs = { Comp = 123 }, Tools = {} }", + "Composition { Tools = ordered() {} }", + "Composition { Prefs = { Comp = { FrameFormat = { Width = 1e20, Height = 1e20, Rate = nan } } }, Tools = ordered() { A = Blur {}, B = Blur {}, C = Blur {}, D = Blur {}, E = Blur {} } }", + "Composition { Tools = ordered() { BG = Background { Inputs = { Width = Input { Value = 1e9999 }, Height = Input { Value = 1e9999 } } } } }", + ] { + let c = Comp::from_fusion_str(src).expect(src); + assert!(c.width <= 65536 && c.height <= 65536); + assert!(c.fps.is_finite() && c.fps > 0.0); + assert_save_equivalence_and_reparse(&c); + } + + // Duplicate flow + modifier name in Tools must not diverge between streaming and AST save. + let dup_name = r#"Composition { + Tools = ordered() { + Foo = Blur {}, + Foo = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } } }, + B = Blur {}, + C = Blur {}, + D = Blur {}, + }, + }"#; + let mut comp = Comp::from_fusion_str(dup_name).expect("dup name parses"); + comp.splines.get_mut("Foo").unwrap().keyframes[0].value = 2.5; + assert_save_equivalence_and_reparse(&comp); +} + +#[test] +fn cyclic_source_op_and_grid_mesh_overflow_and_utf8_saver_path_do_not_panic() { + let cyclic = r#"Composition { + Tools = ordered() { + A = ColorCorrector { SourceOp = "B", Inputs = { MasterRGBGain = Input { Value = 2 } } }, + B = ColorCorrector { SourceOp = "A" }, + SelfInst = ColorCorrector { SourceOp = "SelfInst" }, + GW = GridWarp { + Inputs = { + SrcMesh = Input { + Value = Mesh { + Col = 1e9999, + Points = { + { X = 0, Y = 0 }, { X = 1, Y = 0 }, + { X = 0, Y = 1 }, { X = 1, Y = 1 }, + }, + }, + }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(cyclic).expect("cyclic SourceOp parses"); + let gw = comp.node(comp.find_node("GW").unwrap()); + assert!(comp.eval_grid_mesh(gw, "SrcMesh", 0.0).is_none()); + assert!(comp.eval_grid_mesh(gw, "SrcMesh", f64::NAN).is_none()); + + // Multi-byte UTF-8 Saver stem + extreme range must never slice mid-char or overflow i64. + for filename in ["render_é.png", "出力.exr", "frame_é001.exr", "plain.png"] { + let spec = SaverSpec { + node_id: NodeId(0), + name: "S".to_owned(), + upstream: None, + filename: filename.to_owned(), + range: [i64::MIN, i64::MAX], + sequence_start: Some(10), + }; + let p = spec.frame_path(100); + assert!(!p.as_os_str().is_empty()); + } +} + +#[test] +fn expression_engine_math_dsl_and_shake_handle_cycles_depth_and_non_finite_time() { + let expr = ExprEngine::new(); + + // Non-finite times & expressions never panic in Lua or format_number. + let empty_nums = HashMap::new(); + let empty_pts = HashMap::new(); + let empty_nodes = HashMap::new(); + for t in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0] { + let _ = expr.eval_number("time + 1", t, &empty_nums, &empty_pts, &empty_nodes); + let _ = expr.eval_string("tostring(time)", t, &empty_nums, &empty_pts, &empty_nodes); + let _ = expr.eval_point("Point(time, 0/0)", t, &empty_nums, &empty_pts, &empty_nodes); + } + assert_eq!( + expr.eval_string("0/0", 0.0, &empty_nums, &empty_pts, &empty_nodes).as_deref(), + Some("nan") + ); + assert_eq!( + expr.eval_string("1/0", 0.0, &empty_nums, &empty_pts, &empty_nodes).as_deref(), + Some("inf") + ); + assert_eq!( + expr.eval_string("-1/0", 0.0, &empty_nums, &empty_pts, &empty_nodes).as_deref(), + Some("-inf") + ); + + // Deeply nested expressions in ExpressionModifier math DSL & Lua must not overflow stack. + let deep_parens = format!("{}1{}", "(".repeat(4000), ")".repeat(4000)); + let deep_unary = format!("{}1", "-".repeat(4000)); + let deep_pow = format!("{}2", "2^".repeat(4000)); + let src = format!( + r#"Composition {{ + Tools = ordered() {{ + A = Transform {{ + Inputs = {{ + Size = Input {{ Expression = "B.Size", }}, + Angle = Input {{ SourceOp = "Shk", Source = "X", }}, + Width = Input {{ SourceOp = "EM1", Source = "NumberResult", }}, + Height = Input {{ SourceOp = "EM2", Source = "NumberResult", }}, + Edges = Input {{ SourceOp = "EM3", Source = "NumberResult", }}, + }}, + }}, + B = Transform {{ + Inputs = {{ + Size = Input {{ Expression = "A.Size", }}, + }}, + }}, + Shk = Shake {{ + Inputs = {{ + Smoothness = Input {{ Value = 0.01 }}, + XMinimum = Input {{ Value = 0 }}, + XMaximum = Input {{ Value = 10 }}, + }}, + }}, + EM1 = Expression {{ Inputs = {{ NumberExpression = Input {{ Value = "{deep_parens}" }} }} }}, + EM2 = Expression {{ Inputs = {{ NumberExpression = Input {{ Value = "{deep_unary}" }} }} }}, + EM3 = Expression {{ Inputs = {{ NumberExpression = Input {{ Value = "{deep_pow}" }} }} }}, + }}, + }}"# + ); + let comp = Comp::from_fusion_str(&src).expect("comp parses"); + let a = comp.node(comp.find_node("A").unwrap()); + + for t in [0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e20, -1e20] { + // Cyclic NodeA.P <-> NodeB.P terminates cleanly. + assert_eq!(comp.eval_number(a, "Size", t, 42.0, &expr), 42.0); + // Shake at huge / non-finite times never panics with i64 overflow. + let shk = comp.eval_number(a, "Angle", t, -1.0, &expr); + assert!(shk.is_finite()); + // Deep ExpressionModifier formulas don't overflow stack. + assert_eq!(comp.eval_number(a, "Width", t, 7.0, &expr), 7.0); + assert_eq!(comp.eval_number(a, "Height", t, 7.0, &expr), 7.0); + assert_eq!(comp.eval_number(a, "Edges", t, 7.0, &expr), 7.0); + } +} + +#[test] +fn splines_and_polypaths_survive_degenerate_keys_nan_and_inf() { + // Empty & 1-key splines + let empty_sp = BezierSpline { + name: "e".to_owned(), + color: [0, 0, 0], + keyframes: vec![], + }; + assert_eq!(empty_sp.eval(f64::NAN), 0.0); + assert_eq!(empty_sp.eval(f64::INFINITY), 0.0); + + // Manually constructed NaN-timed keyframes with handles must not panic in segment_control_points. + let mut k0 = Keyframe::new(f64::NAN, 1.0); + k0.rh = Some([1.0, 2.0]); + let mut k1 = Keyframe::new(f64::NAN, 3.0); + k1.lh = Some([2.0, 4.0]); + let _ = segment_control_points(&k0, &k1); + + // Loop spline evaluated at NaN / Inf / -Inf must stay finite (no inf - inf = NaN). + let lp = KeyFlags { + linear: true, + loop_after: true, + ..Default::default() + }; + let mut sp = BezierSpline { + name: "loop".to_owned(), + color: [255, 255, 255], + keyframes: vec![ + Keyframe { time: 20.0, value: 2.0, lh: None, rh: None, flags: lp, handle_mode: HandleMode::Vector }, + Keyframe { time: 10.0, value: 1.0, lh: None, rh: None, flags: lp, handle_mode: HandleMode::Vector }, + Keyframe { time: 10.0, value: 1.5, lh: None, rh: None, flags: lp, handle_mode: HandleMode::Vector }, + ], + }; + sp.sort(); + for t in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 10.0, 15.0, 25.0] { + assert!(sp.eval(t).is_finite(), "non-finite eval at t={t}"); + } + + // Malformed KeyFrames table with nan/inf keys & handles filters non-finite entries cleanly. + let sp_tbl = parse_lua( + r#"BezierSpline { + KeyFrames = { + [nan] = { 1, LH = { nan, 0 }, RH = { inf, 0 } }, + [inf] = { 2 }, + [0] = { nan }, + [5] = { 0.5, LH = { nan, 1 } }, + [10] = { 1.5 }, + }, + }"#, + ) + .unwrap(); + let parsed_sp = BezierSpline::from_lua("s".to_owned(), sp_tbl.as_table().unwrap()); + assert_eq!(parsed_sp.keyframes.len(), 2); + assert!(parsed_sp.keyframes[0].lh.is_none()); + assert!(parsed_sp.eval(f64::NAN).is_finite()); + + // PolyPath at NaN / Inf / -Inf stays finite. + let pp = PolyPath { + name: "p".to_owned(), + displacement_op: None, + displacement_value: 0.0, + closed: false, + points: vec![ + PolyPoint { x: 0.0, y: 0.0, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true }, + PolyPoint { x: 0.5, y: 0.0, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true }, + ], + }; + for d in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let p = pp.eval_center(d); + assert!(p[0].is_finite() && p[1].is_finite(), "non-finite PolyPath at d={d}"); + } +} + +#[test] +fn comp_history_and_edits_handle_stale_ids_and_rapid_roundtrips() { + let mut comp = Comp::from_fusion_str("Composition { Tools = ordered() {} }").unwrap(); + let mut history = CompHistory::with_max_depth(8); + history.mark_saved(&comp); + + let stale = NodeId(999); + assert!(comp.set_keyframe(stale, "Gain", 0.0, 1.0).is_err()); + assert!(!comp.delete_keyframe("MissingSpline", 0.0)); + assert!(comp.rename_node(stale, "ValidName").is_err()); + assert!(comp.connect_output(stale, "Output", stale, "Input").is_err()); + assert!(!comp.disconnect(stale, "Input")); + assert!(comp.splice_node_into_pipe(stale, stale, stale, "Input").is_err()); + assert!(!comp.set_input_value(stale, "Gain", ParamValue::Number(1.0))); + assert!(!comp.set_input_expression(stale, "Gain", Some("1".to_owned()))); + assert!(!comp.toggle_passthrough(stale)); + comp.set_node_pos(stale, [1.0, 2.0]); + assert!(comp.delete_nodes(&[stale]).is_empty()); + assert!(comp.node_splines(stale).is_empty()); + assert!(history.paste_fusion_clipboard(&mut comp, "{{{{{", (0.0, 0.0)).is_err()); + assert!(!history.undo(&mut comp)); + assert!(!history.redo(&mut comp)); + + // Rapid add -> wire -> keyframe -> rename -> splice -> delete -> undo -> redo sequence. + history.push_snapshot(&comp, "Add BG"); + let bg = comp.add_node("Background", None, [0.0, 0.0]); + assert!(comp.rename_node(bg, "123bad").is_err()); + assert!(comp.rename_node(bg, "end").is_err()); + assert!(comp.rename_node(bg, "").is_err()); + + history.push_snapshot(&comp, "Add Merge"); + let merge = comp.add_node("Merge", None, [200.0, 0.0]); + comp.connect_output(bg, "Output", merge, "Background").unwrap(); + + history.push_snapshot(&comp, "Keyframe & Splice"); + let sp = comp.set_keyframe(merge, "Blend", 10.0, 0.5).unwrap(); + assert!(comp.set_keyframe(merge, "Blend", f64::NAN, 1.0).is_err()); + let blur = comp.add_node("Blur", None, [100.0, 0.0]); + comp.splice_node_into_pipe(blur, bg, merge, "Background").unwrap(); + assert_save_equivalence_and_reparse(&comp); + + history.push_snapshot(&comp, "Rename & Delete key"); + comp.rename_node(blur, "SoftBlur").unwrap(); + assert!(comp.delete_keyframe(&sp, 10.0)); + assert!(!comp.delete_keyframe(&sp, f64::NAN)); + assert_save_equivalence_and_reparse(&comp); + + history.push_snapshot(&comp, "Delete Blur"); + comp.delete_nodes(&[blur]); + assert_save_equivalence_and_reparse(&comp); + + // Undo everything back to empty and redo everything forward. + while history.undo(&mut comp) { + assert_save_equivalence_and_reparse(&comp); + } + assert!(comp.nodes.is_empty()); + while history.redo(&mut comp) { + assert_save_equivalence_and_reparse(&comp); + } + + // Cancel and commit group edge cases. + assert!(!history.commit_group(&comp)); + assert!(!history.cancel_group(&mut comp)); + history.begin_group(&comp, "Canceled"); + let _tmp = comp.add_node("Note", None, [0.0, 0.0]); + assert!(history.cancel_group(&mut comp)); + assert_save_equivalence_and_reparse(&comp); + let _ = LuaTable::default(); +} -- 2.54.1