Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

PSD: cap the layer tree for psd_to_document; layered TIFF checks group depth (#2940) (#2975)

Valentin Kleinfd351918e52f
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 3cccdff03..53900fdbd 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -245,11 +245,9 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, m
}
if is_psd(bytes) {
let file = PsdFile::from_bytes(bytes)?;
- // Nesting past the document model's cap could never be saved (.pcraft refuses it) and
- // would overflow the importer's recursion; reject the file with the actionable limit.
- if psd_import::group_depth(&file) > photocraft_doc::MAX_GROUP_DEPTH {
- return Err(IoError::Unsupported(format!("layer groups nested deeper than {}", photocraft_doc::MAX_GROUP_DEPTH)));
- }
+ // Nesting past the document model's cap could never be saved; reject the file with the
+ // actionable limit.
+ psd_import::check_group_depth(&file)?;
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(0.05);
let (mut document, warnings) = psd_import::psd_to_document_with(&file, ctl).ok_or(IoError::Cancelled)?;
diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs
index 58487ced9..da483c04d 100644
--- a/crates/io/src/psd_import.rs
+++ b/crates/io/src/psd_import.rs
@@ -482,6 +482,15 @@ fn apply_link_groups(nodes: &[LayerNode], layers: &mut [Layer], ids: &[u16]) {
rec(nodes, layers, ids, 0);
}
+/// Rejects a file whose groups nest deeper than the document model's cap, with the actionable
+/// limit error. Nesting past the cap could never be saved (.pcraft refuses it).
+pub(crate) fn check_group_depth(file: &PsdFile) -> Result<(), crate::IoError> {
+ if group_depth(file) > photocraft_doc::MAX_GROUP_DEPTH {
+ return Err(crate::IoError::Unsupported(format!("layer groups nested deeper than {}", photocraft_doc::MAX_GROUP_DEPTH)));
+ }
+ Ok(())
+}
+
/// Deepest group nesting of the file's layer records (a layer inside this many groups is the
/// deepest), computed like `layer_tree`'s stack — iteratively, so no file can make it recurse.
pub(crate) fn group_depth(file: &PsdFile) -> usize {
@@ -690,7 +699,9 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)
cx.warn(format!("Multichannel documents have no layers: {} layer records were not imported", file.layers().len()));
}
} else if layered {
- let tree = file.layer_tree();
+ // Capped like `build` (#2940): a group past the document's nesting cap keeps no children,
+ // so no file can make this tree, or anything walking or dropping it, recurse deeper.
+ let tree = file.layer_tree_max_depth(photocraft_doc::MAX_GROUP_DEPTH);
doc.layers = cx.build(&tree, 0);
// Layer › Link Layers: resource 1026 holds one group id per layer record (0 = unlinked).
if let Some(Ok(photocraft_psd::resources::ResourceData::LayerGroupInfo(groups))) =
diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs
index 20032ebba..e716c2287 100644
--- a/crates/io/src/tiff_layers.rs
+++ b/crates/io/src/tiff_layers.rs
@@ -105,6 +105,8 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8]) -> Result<I
let data = planar_big_endian(&img, color_channels, mode == PsdMode::Cmyk)?;
let image_data = ImageData { compression: Compression::Raw, data };
let file = isd.into_psd(header, resources, image_data);
+ // The same nesting limit as opening a PSD (#2940).
+ crate::psd_import::check_group_depth(&file)?;
let (mut doc, w) = psd_to_document(&file);
warnings.extend(w);
doc.name = name.to_string();
diff --git a/crates/io/tests/tiff_layers.rs b/crates/io/tests/tiff_layers.rs
index b893cfca0..913ab2f39 100644
--- a/crates/io/tests/tiff_layers.rs
+++ b/crates/io/tests/tiff_layers.rs
@@ -360,3 +360,31 @@ fn default_export_options_write_a_flat_tiff() {
assert_eq!(tags(&r.bytes), (None, None));
assert_eq!(import("x.tif", &r.bytes).unwrap().document.layers.len(), 1);
}
+
+/// #2940: layered TIFF data whose groups nest past the document's cap is rejected with the same
+/// limit error as a PSD, instead of being converted.
+#[test]
+fn layered_tiff_nested_past_the_cap_is_rejected() {
+ use photocraft_psd::{GroupSpec, LayerSpec, PixelData, PsdBuilder, PsdFile};
+ let tiff_nested = |levels: usize| {
+ let mut b = PsdBuilder::new(4, 4);
+ for _ in 0..levels {
+ b.begin_group(GroupSpec::new("g"));
+ }
+ b.push_layer(LayerSpec::new("deep", 0, 0, 1, 1, PixelData::Rgba8(vec![1, 2, 3, 4])));
+ for _ in 0..levels {
+ b.end_group().unwrap();
+ }
+ let file = PsdFile::from_bytes(&b.to_bytes().unwrap()).unwrap();
+ let order = if photocraft_codecs::tiff_writes_little_endian() { ByteOrder::Little } else { ByteOrder::Big };
+ let layers = ImageSourceData::from_psd(&file).to_bytes(order).unwrap().0;
+ let d = gen_doc(ColorMode::Rgb, SampleType::U8, Features::PIXELS);
+ let mut img = photocraft_codecs::decode(&tiff(&d, false).bytes).unwrap();
+ img.meta.photoshop_layers = Some(layers);
+ photocraft_codecs::encode(&img, photocraft_codecs::Format::Tiff, &photocraft_codecs::EncodeOptions::default()).unwrap()
+ };
+ let err = import("deep.tif", &tiff_nested(101)).unwrap_err();
+ assert!(err.to_string().contains("nested deeper than 100"), "{err}");
+ let r = import("hundred.tif", &tiff_nested(100)).unwrap();
+ assert_eq!(r.document.max_group_depth(), 100);
+}
diff --git a/crates/psd/README.md b/crates/psd/README.md
index c3721edf2..7de552995 100644
--- a/crates/psd/README.md
+++ b/crates/psd/README.md
@@ -28,6 +28,7 @@ PsdFile::layers() -> &[LayerRecord] // file order = bottom-most first
PsdFile::layers_mut() -> &mut Vec<LayerRecord>
PsdFile::layer(i) -> Option<Layer<'_>>; iter_layers()
PsdFile::layer_tree() -> Vec<LayerNode> // nested groups, children bottom-to-top
+PsdFile::layer_tree_max_depth(n) -> Vec<LayerNode> // same, groups nested n deep keep no children
PsdFile::decode_merged() -> Result<Vec<u8>> // planar big-endian samples
PsdFile::composite_rgba8() -> Result<RgbaImage>
PsdFile::resource(id), global_block(key), icc_profile(), resolution(),
diff --git a/crates/psd/src/tree.rs b/crates/psd/src/tree.rs
index 02682ef84..75ea750e6 100644
--- a/crates/psd/src/tree.rs
+++ b/crates/psd/src/tree.rs
@@ -58,23 +58,38 @@ impl PsdFile {
/// Malformed nesting is tolerated: a folder without a matching divider
/// becomes an empty group; unclosed dividers at the end are dropped and
/// their children are hoisted to the enclosing level.
+ ///
+ /// The tree can be as deep as the file nests its groups (up to ~16000
+ /// levels). Code that walks it recursively should use
+ /// [`layer_tree_max_depth`](Self::layer_tree_max_depth).
pub fn layer_tree(&self) -> Vec<LayerNode> {
- // Stack of (divider index, children).
+ self.layer_tree_max_depth(usize::MAX)
+ }
+
+ /// [`layer_tree`](Self::layer_tree) with at most `max_depth` levels of
+ /// groups: a group nested `max_depth` or more groups deep (a root node is
+ /// at depth 0) keeps its node but not its children. Built iteratively, so
+ /// no file can make it recurse, and the result is no deeper than
+ /// `max_depth + 1` levels, so walking or dropping it recursively is bounded.
+ pub fn layer_tree_max_depth(&self, max_depth: usize) -> Vec<LayerNode> {
+ // Stack of (divider index, children); frame `k` holds the nodes at depth `k`. Frames
+ // past `max_depth` are tracked (to match dividers to folders) but collect nothing.
let mut stack: Vec<(Option<usize>, Vec<LayerNode>)> = vec![(None, Vec::new())];
+ let push = |stack: &mut Vec<(Option<usize>, Vec<LayerNode>)>, node: LayerNode| {
+ if stack.len() <= max_depth.saturating_add(1)
+ && let Some(top) = stack.last_mut()
+ {
+ top.1.push(node);
+ }
+ };
for (i, rec) in self.layers().iter().enumerate() {
match rec.section_type() {
SectionType::BoundingDivider => stack.push((Some(i), Vec::new())),
SectionType::OpenFolder | SectionType::ClosedFolder => {
let (divider, children) = if stack.len() > 1 { stack.pop().unwrap_or_default() } else { (None, Vec::new()) };
- if let Some(top) = stack.last_mut() {
- top.1.push(LayerNode::Group { index: i, divider, children });
- }
- }
- _ => {
- if let Some(top) = stack.last_mut() {
- top.1.push(LayerNode::Layer { index: i });
- }
+ push(&mut stack, LayerNode::Group { index: i, divider, children });
}
+ _ => push(&mut stack, LayerNode::Layer { index: i }),
}
}
while stack.len() > 1 {
diff --git a/crates/psd/tests/tree.rs b/crates/psd/tests/tree.rs
index 7e4239431..ea4eaeec2 100644
--- a/crates/psd/tests/tree.rs
+++ b/crates/psd/tests/tree.rs
@@ -123,6 +123,20 @@ fn deeply_nested() {
assert_eq!(depth, 51);
}
+/// #2940: the capped tree keeps a group at the cap but not its children, so its depth is bounded
+/// whatever the file nests.
+#[test]
+fn layer_tree_max_depth_drops_deeper_children() {
+ let mut v = vec![rec("</Layer group>", END), rec("</Layer group>", END), rec("</Layer group>", END), rec("x", None)];
+ v.extend([rec("g2", OPEN), rec("g1", OPEN), rec("g0", OPEN), rec("top", None)]);
+ let f = file_with(v);
+ assert_eq!(names(&f, &f.layer_tree()), "g0[g1[g2[x]]],top");
+ assert_eq!(names(&f, &f.layer_tree_max_depth(usize::MAX)), "g0[g1[g2[x]]],top");
+ assert_eq!(names(&f, &f.layer_tree_max_depth(2)), "g0[g1[g2[]]],top");
+ assert_eq!(names(&f, &f.layer_tree_max_depth(1)), "g0[g1[]],top");
+ assert_eq!(names(&f, &f.layer_tree_max_depth(0)), "g0[],top");
+}
+
#[test]
fn folder_without_divider_is_empty_group() {
let f = file_with(vec![rec("a", None), rec("G", OPEN), rec("b", None)]);