FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
security(render): bound embedded LUT resolution (#2901)
Earl Coa70cac4c234a
diff --git a/crates/engine/src/color.rs b/crates/engine/src/color.rsindex 71261bca5..d25270ad5 100644--- a/crates/engine/src/color.rs+++ b/crates/engine/src/color.rs@@ -85,6 +85,9 @@ pub(crate) fn commands() -> Vec<CommandSpec> {fn import_lut(s: &mut Session, path: &str, name: Option<&str>) -> Result<(String, Value)> {let text = std::fs::read_to_string(path).map_err(|e| bad("lut.import", format!("{path}: {e}")))?;+ if text.len() > filmcraft_project::MAX_LUT_TEXT_BYTES {+ return Err(bad("lut.import", format!("{path}: LUT source exceeds the {} byte limit", filmcraft_project::MAX_LUT_TEXT_BYTES)));+ }let fmt = LutFormat::from_path(path).ok_or_else(|| bad("lut.import", "expected a .cube or .3dl file"))?;let lut = Lut::parse(&text, Some(fmt)).map_err(|e| bad("lut.import", format!("{path}: {e}")))?;let stem = std::path::Path::new(path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "LUT".into());diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rsindex 9ecd10aab..6ee6e8043 100644--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@ -216,6 +216,17 @@ pub fn decode(bytes: &[u8]) -> Result<Loaded, FormatError> {/// Refuse only values that would overflow or exhaust memory later (`Sequence::check_bounds`);/// structural rules such as overlaps are left to the editor, so projects that open today still open.fn validate_loaded(mut loaded: Loaded) -> Result<Loaded, FormatError> {+ // Embedded LUT text is rendered on the hot path. Drop oversize entries at load time so a+ // hostile project cannot retain an unrenderable multi-megabyte source or repeatedly offer it+ // to renderers. Clips that refer to one simply have no LUT, like a deleted library entry.+ let max_lut = filmcraft_project::MAX_LUT_TEXT_BYTES;+ loaded.project.luts.retain(|lut| {+ let keep = lut.text.len() <= max_lut;+ if !keep {+ log::warn!("LUT `{}`: {} bytes, dropping entry above {max_lut} byte limit", lut.name, lut.text.len());+ }+ keep+ });// Out-of-range audio stream data is repaired, not refused: failing the load would lose the// whole project over one bad index. A media item keeps its first `MAX_AUDIO_STREAMS` streams; a// clip pointing past that plays stream 0.@@ -434,6 +445,20 @@ mod tests {}}+ #[test]+ fn oversized_embedded_luts_are_dropped_on_load() {+ let mut p = Project::new("LUT limit");+ p.luts.push(filmcraft_project::ProjectLut {+ id: "huge".into(),+ name: "huge".into(),+ source_path: None,+ format: "cube".into(),+ text: "#".repeat(filmcraft_project::MAX_LUT_TEXT_BYTES + 1).into(),+ });+ let loaded = decode(&encode(&p, false)).unwrap();+ assert!(loaded.project.luts.is_empty());+ }+/// What is open is stored beside the project. A file without it, or with one that cannot be/// read, opens all the same.#[test]diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rsindex 5b21cdaec..b37d82687 100644--- a/crates/project/src/lib.rs+++ b/crates/project/src/lib.rs@@ -1324,6 +1324,9 @@ impl ProjectView {}/// A LUT imported into the project (`lut.import`). Lumetri refers to it as `lib:<id>`.+/// Largest embedded LUT source accepted from a project or import (8 MiB).+pub const MAX_LUT_TEXT_BYTES: usize = 8 << 20;+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]pub struct ProjectLut {pub id: String,diff --git a/crates/render/src/luts.rs b/crates/render/src/luts.rsindex aa2c29632..c7afe3cda 100644--- a/crates/render/src/luts.rs+++ b/crates/render/src/luts.rs@@ -10,10 +10,11 @@//! Parsed LUTs are cached by content, so a library LUT is parsed once however many clips use it.use std::collections::HashMap;+use std::hash::{Hash, Hasher};use std::sync::{Arc, Mutex, OnceLock};use filmcraft_color::{ColorSpace, Lut, Lut3d, LutFormat, Range};-use filmcraft_project::Project;+use filmcraft_project::{MAX_LUT_TEXT_BYTES, Project};/// A built-in LUT: id, label, and how it is made.pub struct Builtin {@@ -80,12 +81,38 @@ impl Builtin {}}-fn cache() -> &'static Mutex<HashMap<String, Arc<Lut>>> {- static C: OnceLock<Mutex<HashMap<String, Arc<Lut>>>> = OnceLock::new();+/// Identity of immutable project LUT text. Pointer equality is intentional: an `Arc<str>` changes+/// identity whenever a project edit replaces its text, while clones of an unchanged project share+/// it. Keeping the Arc in the cache also prevents allocator-address reuse from aliasing old LUTs.+#[derive(Clone, Debug)]+struct LutText(Arc<str>);++impl PartialEq for LutText {+ fn eq(&self, other: &Self) -> bool {+ Arc::ptr_eq(&self.0, &other.0)+ }+}++impl Eq for LutText {}++impl Hash for LutText {+ fn hash<H: Hasher>(&self, state: &mut H) {+ (Arc::as_ptr(&self.0) as *const ()).hash(state);+ }+}++#[derive(Clone, Debug, PartialEq, Eq, Hash)]+enum CacheKey {+ Builtin(String),+ Library { text: LutText, format: String },+}++fn cache() -> &'static Mutex<HashMap<CacheKey, Arc<Lut>>> {+ static C: OnceLock<Mutex<HashMap<CacheKey, Arc<Lut>>>> = OnceLock::new();C.get_or_init(Default::default)}-fn cached(key: String, make: impl FnOnce() -> Option<Lut>) -> Option<Arc<Lut>> {+fn cached(key: CacheKey, make: impl FnOnce() -> Option<Lut>) -> Option<Arc<Lut>> {if let Some(l) = cache().lock().unwrap_or_else(|e| e.into_inner()).get(&key) {return Some(l.clone());}@@ -103,25 +130,18 @@ pub fn resolve(project: Option<&Project>, spec: &str) -> Option<Arc<Lut>> {let spec = spec.trim();if let Some(id) = spec.strip_prefix("builtin:") {let b = builtins().iter().find(|b| b.id == id)?;- return cached(format!("builtin:{id}"), || Some(b.generate()));+ return cached(CacheKey::Builtin(id.to_string()), || Some(b.generate()));}let id = spec.strip_prefix("lib:")?;let entry = project?.luts.iter().find(|l| l.id == id)?;- let key = format!("lib:{:016x}", hash(&entry.text));+ if entry.text.len() > MAX_LUT_TEXT_BYTES {+ return None;+ }+ let key = CacheKey::Library { text: LutText(entry.text.clone()), format: entry.format.clone() };let fmt = LutFormat::from_path(&format!("x.{}", entry.format));cached(key, || Lut::parse(&entry.text, fmt).ok())}-fn hash(s: &str) -> u64 {- // FNV-1a- let mut h = 0xcbf2_9ce4_8422_2325u64;- for b in s.as_bytes() {- h ^= *b as u64;- h = h.wrapping_mul(0x100_0000_01b3);- }- h ^ s.len() as u64-}-/// Human-readable name of a LUT reference (for panels).pub fn label(project: Option<&Project>, spec: &str) -> String {if spec.is_empty() {@@ -169,4 +189,31 @@ mod tests {assert_eq!(label(Some(&p), "lib:lut1"), "Swap");assert_eq!(label(Some(&p), "lib:x"), "x (missing)");}++ #[test]+ fn library_cache_uses_retained_text_identity_without_rehashing_source() {+ let text: Arc<str> = Lut::from_cube(Lut3d::from_fn(3, |c| c)).to_cube().into();+ let a = CacheKey::Library { text: LutText(text.clone()), format: "cube".into() };+ let b = CacheKey::Library { text: LutText(text), format: "cube".into() };+ let c = CacheKey::Library { text: LutText(Arc::<str>::from(a_match_source_but_not_identity())), format: "cube".into() };+ assert_eq!(a, b, "unchanged project snapshots share their LUT identity");+ assert_ne!(a, c, "replacement text gets a new cache identity even when bytes match");+ }++ fn a_match_source_but_not_identity() -> String {+ Lut::from_cube(Lut3d::from_fn(3, |c| c)).to_cube()+ }++ #[test]+ fn oversized_embedded_lut_is_not_parsed() {+ let mut p = Project::new("t");+ p.luts.push(filmcraft_project::ProjectLut {+ id: "too-big".into(),+ name: "too-big".into(),+ source_path: None,+ format: "cube".into(),+ text: "#".repeat(MAX_LUT_TEXT_BYTES + 1).into(),+ });+ assert!(resolve(Some(&p), "lib:too-big").is_none());+ }}