From 10a585c3e2f7486b8bbd179edb6dc167e0eaea99 Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 16 Nov 2026 17:14:31 +0100 Subject: [PATCH] fix(psd): preserve consumer resource limits (#786) --- crates/psd/src/descriptor.rs | 60 ++++++++++++++++++----- crates/psd/src/float.rs | 28 ++++++++--- crates/psd/src/smart.rs | 7 ++- crates/psd/tests/resource_limits.rs | 76 +++++++++++++++++++++++++++++ 4 files changed, 153 insertions(+), 18 deletions(-) create mode 100644 crates/psd/tests/resource_limits.rs diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index 96ad47a7b..1a6f2000e 100644 --- a/crates/psd/src/descriptor.rs +++ b/crates/psd/src/descriptor.rs @@ -12,6 +12,26 @@ mod lookup; /// Maximum nesting depth accepted when parsing (fuzz safety). pub const MAX_DEPTH: usize = 64; +/// Per-container limits for parsing descriptor trees. +/// +/// Limits apply to every nested descriptor and `VlLs` list, before allocation. +/// They are not a total memory budget; byte strings and other value types retain +/// their existing input-length checks. Defaults preserve the unrestricted counts +/// accepted by the original API. Nesting remains bounded by [`MAX_DEPTH`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ParseLimits { + /// Maximum key/value pairs in each descriptor. + pub max_descriptor_items: u32, + /// Maximum values in each `VlLs` list. + pub max_list_items: u32, +} + +impl Default for ParseLimits { + fn default() -> Self { + Self { max_descriptor_items: u32::MAX, max_list_items: u32::MAX } + } +} + /// A Photoshop Unicode string: UTF-16 code units, preserved exactly /// (including any trailing NUL and unpaired surrogates). #[derive(Debug, Clone, PartialEq, Eq, Default, Hash)] @@ -309,6 +329,14 @@ impl Descriptor { Ok((d, r.pos())) } + /// Parses a descriptor prefix with explicit per-container limits. + /// Returns the descriptor and bytes consumed, allowing trailing data. + pub fn parse_prefix_with_limits(data: &[u8], limits: ParseLimits) -> Result<(Self, usize)> { + let mut r = Reader::new(data); + let d = Self::read_with_limits(&mut r, limits)?; + Ok((d, r.pos())) + } + /// Serializes the descriptor. pub fn to_bytes(&self) -> Vec { let mut v = Vec::new(); @@ -317,7 +345,11 @@ impl Descriptor { } pub(crate) fn read(r: &mut Reader<'_>) -> Result { - read_descriptor(r, 0) + Self::read_with_limits(r, ParseLimits::default()) + } + + pub(crate) fn read_with_limits(r: &mut Reader<'_>, limits: ParseLimits) -> Result { + read_descriptor(r, 0, limits) } pub(crate) fn write(&self, out: &mut Vec) { @@ -391,33 +423,36 @@ pub(crate) fn vec_for_count(n: u32) -> Vec { Vec::with_capacity((n as usize).min(MAX_PREALLOC)) } -fn read_descriptor(r: &mut Reader<'_>, depth: usize) -> Result { +fn read_descriptor(r: &mut Reader<'_>, depth: usize, limits: ParseLimits) -> Result { if depth > MAX_DEPTH { return Err(PsdError::LimitExceeded("descriptor nesting too deep")); } let name = UnicodeString::read(r)?; let class_id = Id::read(r)?; let n = r.u32()?; + if n > limits.max_descriptor_items { + return Err(PsdError::LimitExceeded("too many descriptor items")); + } // Each item needs at least 5 (1-byte string key) + 4 (type) + 1 (bool). r.check_count(u64::from(n), 10)?; let mut items = vec_for_count(n); for _ in 0..n { let key = Id::read(r)?; - let v = read_value(r, depth + 1)?; + let v = read_value(r, depth + 1, limits)?; items.push((key, v)); } Ok(Descriptor { name, class_id, items }) } -fn read_value(r: &mut Reader<'_>, depth: usize) -> Result { +fn read_value(r: &mut Reader<'_>, depth: usize, limits: ParseLimits) -> Result { if depth > MAX_DEPTH { return Err(PsdError::LimitExceeded("descriptor nesting too deep")); } let ty = r.array::<4>()?; - read_typed_value(r, &ty, depth) + read_typed_value(r, &ty, depth, limits) } -fn read_typed_value(r: &mut Reader<'_>, ty: &[u8; 4], depth: usize) -> Result { +fn read_typed_value(r: &mut Reader<'_>, ty: &[u8; 4], depth: usize, limits: ParseLimits) -> Result { Ok(match ty { b"obj " => { let n = r.u32()?; @@ -428,14 +463,17 @@ fn read_typed_value(r: &mut Reader<'_>, ty: &[u8; 4], depth: usize) -> Result Value::Descriptor(read_descriptor(r, depth + 1)?), - b"GlbO" => Value::GlobalObject(read_descriptor(r, depth + 1)?), + b"Objc" => Value::Descriptor(read_descriptor(r, depth + 1, limits)?), + b"GlbO" => Value::GlobalObject(read_descriptor(r, depth + 1, limits)?), b"VlLs" => { let n = r.u32()?; + if n > limits.max_list_items { + return Err(PsdError::LimitExceeded("too many descriptor list items")); + } r.check_count(u64::from(n), 4)?; let mut items = vec_for_count(n); for _ in 0..n { - items.push(read_value(r, depth + 1)?); + items.push(read_value(r, depth + 1, limits)?); } Value::List(items) } @@ -472,7 +510,7 @@ fn read_typed_value(r: &mut Reader<'_>, ty: &[u8; 4], depth: usize) -> Result { let prefix = r.u32()?; - Value::ObjectArray(ObjectArray { prefix, body: read_descriptor(r, depth + 1)? }) + Value::ObjectArray(ObjectArray { prefix, body: read_descriptor(r, depth + 1, limits)? }) } other => { return Err(PsdError::Unsupported(format!("descriptor OSType {:?}", String::from_utf8_lossy(other)))); @@ -625,7 +663,7 @@ mod tests { data.extend_from_slice(b"bool\x01"); } let mut r = Reader::new(&data); - match read_typed_value(&mut r, b"VlLs", 0).unwrap() { + match read_typed_value(&mut r, b"VlLs", 0, ParseLimits::default()).unwrap() { Value::List(v) => assert_eq!(v.len(), n as usize), other => panic!("expected list, got {other:?}"), } diff --git a/crates/psd/src/float.rs b/crates/psd/src/float.rs index 6e26cd75b..658538bc2 100644 --- a/crates/psd/src/float.rs +++ b/crates/psd/src/float.rs @@ -436,8 +436,22 @@ impl SmartObject { /// exceed [`MAX_BAKE_PIXELS`], or the mesh needs more rasterising work than eight times the /// output allows (a hostile mesh whose triangles each cover the whole output). pub fn render_placed(&self, content: &FloatImage, k: f64, size: Option<(u32, u32)>) -> Option<(FloatImage, [f64; 2])> { - let (cw, ch) = (f64::from(content.width), f64::from(content.height)); - if content.width == 0 || content.height == 0 { + self.render_placed_pixels(content.width, content.height, &content.data, k, size) + } + + /// Bakes borrowed straight RGBA pixels without copying the source image. + /// Uses the same placement, output and work limits as [`Self::render_placed`]. + /// Missing pixels in a short slice read as transparent; extra pixels are ignored. + pub fn render_placed_pixels( + &self, + width: u32, + height: u32, + data: &[[f32; 4]], + k: f64, + size: Option<(u32, u32)>, + ) -> Option<(FloatImage, [f64; 2])> { + let (cw, ch) = (f64::from(width), f64::from(height)); + if width == 0 || height == 0 { return None; } // The quad is solved once for the bounds, the size and the whole grid. @@ -464,7 +478,7 @@ impl SmartObject { let mut out: Vec<[f32; 4]> = Vec::new(); out.try_reserve_exact(count).ok()?; out.resize(count, [0.0; 4]); - let sampler = Sampler { content, cw, ch }; + let sampler = Sampler { width, height, data, cw, ch }; let idx = |i: usize, j: usize| j * (n + 1) + i; // A sane mesh's triangles each span about one grid cell (ow/n by oh/n), rounded out to // whole pixels. A thin output (16384×1) stacks every grid row onto the same pixel row, so @@ -498,7 +512,9 @@ impl SmartObject { /// Bilinear, premultiplied sampling of the content at content-pixel coordinates. struct Sampler<'a> { - content: &'a FloatImage, + width: u32, + height: u32, + data: &'a [[f32; 4]], cw: f64, ch: f64, } @@ -506,14 +522,14 @@ struct Sampler<'a> { impl Sampler<'_> { fn at(&self, x: usize, y: usize) -> [f32; 4] { // `data` is a public field: a short one reads as transparent. - let p = self.content.data.get(y * self.content.width as usize + x).copied().unwrap_or([0.0; 4]); + let p = y.checked_mul(self.width as usize).and_then(|row| row.checked_add(x)).and_then(|i| self.data.get(i)).copied().unwrap_or([0.0; 4]); [p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]] } fn sample(&self, x: f64, y: f64) -> [f32; 4] { let (fx, fy) = ((x - 0.5).clamp(0.0, self.cw - 1.0), (y - 0.5).clamp(0.0, self.ch - 1.0)); let (x0, y0) = (fx.floor() as usize, fy.floor() as usize); - let (x1, y1) = ((x0 + 1).min(self.content.width as usize - 1), (y0 + 1).min(self.content.height as usize - 1)); + let (x1, y1) = ((x0 + 1).min(self.width as usize - 1), (y0 + 1).min(self.height as usize - 1)); let (a, b) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32); let (p00, p10, p01, p11) = (self.at(x0, y0), self.at(x1, y0), self.at(x0, y1), self.at(x1, y1)); std::array::from_fn(|c| (p00[c] * (1.0 - a) + p10[c] * a) * (1.0 - b) + (p01[c] * (1.0 - a) + p11[c] * a) * b) diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index a2195bf5d..d4d98c695 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -259,11 +259,16 @@ pub struct SmartObject { impl SmartObject { /// Reads the data of a `SoLd` / `SoLE` block. pub fn from_placed_layer_data(data: &[u8]) -> Result { + Self::from_placed_layer_data_with_limits(data, crate::descriptor::ParseLimits::default()) + } + + /// Reads a `SoLd` / `SoLE` block with explicit descriptor container limits. + pub fn from_placed_layer_data_with_limits(data: &[u8], limits: crate::descriptor::ParseLimits) -> Result { let mut r = Reader::new(data); let _kind = r.array::<4>()?; let _version = r.u32()?; let _descriptor_version = r.u32()?; - let d = Descriptor::read(&mut r)?; + let d = Descriptor::read_with_limits(&mut r, limits)?; let uuid = d.get_text("Idnt").unwrap_or_default(); let t = eight(&d, "Trnf").unwrap_or([0.0; 8]); // The non-affine transform when present (perspective), else the transform. diff --git a/crates/psd/tests/resource_limits.rs b/crates/psd/tests/resource_limits.rs new file mode 100644 index 000000000..624aaf287 --- /dev/null +++ b/crates/psd/tests/resource_limits.rs @@ -0,0 +1,76 @@ +use craft_psd::descriptor::{Descriptor, ObjectArray, ParseLimits, Value}; +use craft_psd::float::FloatImage; +use craft_psd::smart::SmartObject; + +#[test] +fn descriptor_limits_apply_at_boundary_and_through_every_nested_container() { + let limits = ParseLimits { max_descriptor_items: 1, max_list_items: 1 }; + let one = Descriptor::new("test").with("one", Value::Boolean(true)); + let two = one.clone().with("two", Value::Boolean(false)); + assert!(Descriptor::parse_prefix_with_limits(&one.to_bytes(), limits).is_ok()); + assert!(Descriptor::parse_prefix_with_limits(&two.to_bytes(), limits).is_err()); + assert!(Descriptor::parse_prefix(&two.to_bytes()).is_ok()); + for nested in [ + Value::Descriptor(two.clone()), + Value::GlobalObject(two.clone()), + Value::ObjectArray(ObjectArray { prefix: 0, body: two.clone() }), + Value::List(vec![Value::Descriptor(two.clone())]), + ] { + let bytes = Descriptor::new("test").with("nest", nested).to_bytes(); + assert!(Descriptor::parse_prefix_with_limits(&bytes, limits).is_err()); + assert!(Descriptor::parse_prefix(&bytes).is_ok()); + } + for n in [0, 1, 2] { + let d = Descriptor::new("test").with("list", Value::List(vec![Value::Boolean(true); n])); + assert_eq!(Descriptor::parse_prefix_with_limits(&d.to_bytes(), limits).is_ok(), n <= 1); + } + let nested_list = Descriptor::new("test").with("list", Value::List(vec![Value::List(vec![Value::Boolean(true); 2])])); + assert!(Descriptor::parse_prefix_with_limits(&nested_list.to_bytes(), limits).is_err()); + let mut bytes = one.to_bytes(); + let used = bytes.len(); + bytes.extend_from_slice(b"tail"); + assert_eq!(Descriptor::parse_prefix_with_limits(&bytes, limits).unwrap().1, used); + let zero = ParseLimits { max_descriptor_items: 0, max_list_items: 0 }; + assert!(Descriptor::parse_prefix_with_limits(&Descriptor::new("test").to_bytes(), zero).is_ok()); + assert!(Descriptor::parse_prefix_with_limits(&one.to_bytes(), zero).is_err()); +} + +#[test] +fn count_limits_reject_before_reading_declared_elements() { + let limits = ParseLimits { max_descriptor_items: 1, max_list_items: 1 }; + let mut bytes = Descriptor::new("test").to_bytes(); + let end = bytes.len(); + bytes[end - 4..].copy_from_slice(&2u32.to_be_bytes()); + assert!(matches!(Descriptor::parse_prefix_with_limits(&bytes, limits), Err(craft_psd::PsdError::LimitExceeded(_)))); + let mut bytes = Descriptor::new("test").with("list", Value::List(vec![])).to_bytes(); + let end = bytes.len(); + bytes[end - 4..].copy_from_slice(&2u32.to_be_bytes()); + assert!(matches!(Descriptor::parse_prefix_with_limits(&bytes, limits), Err(craft_psd::PsdError::LimitExceeded(_)))); +} + +#[test] +fn placed_layer_data_honors_descriptor_limits() { + let d = Descriptor::new("test").with("one", Value::Boolean(true)).with("two", Value::Boolean(false)); + let mut bytes = b"soLD".to_vec(); + bytes.extend_from_slice(&4u32.to_be_bytes()); + bytes.extend_from_slice(&16u32.to_be_bytes()); + bytes.extend_from_slice(&d.to_bytes()); + assert!(SmartObject::from_placed_layer_data(&bytes).is_ok()); + assert!(SmartObject::from_placed_layer_data_with_limits(&bytes, ParseLimits { max_descriptor_items: 1, max_list_items: 1 }).is_err()); +} + +#[test] +fn borrowed_pixels_match_owned_render_and_preserve_short_slice_behavior() { + let smart = SmartObject { uuid: String::new(), quad: [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]], size: None, warp: None }; + for data in [vec![], vec![[1.0, 0.5, 0.25, 0.5]], vec![[1.0, 0.5, 0.25, 0.5]; 4]] { + let image = FloatImage { width: 2, height: 2, data }; + let owned = smart.render_placed(&image, 1.0, Some((2, 2))); + let borrowed = smart.render_placed_pixels(2, 2, &image.data, 1.0, Some((2, 2))); + assert!(owned.is_some()); + assert_eq!(owned, borrowed); + } + assert!(smart.render_placed_pixels(0, 2, &[], 1.0, None).is_none()); + assert!(smart.render_placed_pixels(u32::MAX, u32::MAX, &[], 1.0, Some((u32::MAX, u32::MAX))).is_none()); + // A short source remains safely transparent even with enormous declared dimensions. + assert!(smart.render_placed_pixels(u32::MAX, u32::MAX, &[], 1.0, Some((1, 1))).is_some()); +}