Skip to content

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

Affinity: bound compound geometry expansion and reject cycles (#6486)

Perchenko Antonbf321f0f5e1b
diff --git a/crates/affinity/README.md b/crates/affinity/README.md
index e881352c8..535c3736c 100644
--- a/crates/affinity/README.md
+++ b/crates/affinity/README.md
@@ -144,6 +144,13 @@ stops; `photocraft-io` adds 300 000 pixels a side per document and 64 megapixels
canvas. Every archive entry's CRC-32 and size must match. Malformed input returns an `Error`; the
crate has no panics outside tests.
+Compound outlines have a separate active-reference cycle check and a depth cap of 64. Across
+the document, geometry expansion admits at most 500 000 combined outline calls and operand-slot
+visits (including nulls and non-object values), and four million points created or copied into
+compounds. Operand slots are charged before filtering, without first collecting an operand list.
+A compound that crosses a limit or contains a cycle is omitted
+with a warning as a whole; ordinary shared operands remain valid and keep each occurrence's transform.
+
## Privacy
Affinity documents can hold the folder they were saved in, user names, original image paths and
diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs
index 08554134d..6c8ea602c 100644
--- a/crates/affinity/src/geometry.rs
+++ b/crates/affinity/src/geometry.rs
@@ -6,10 +6,103 @@ use crate::stream::{ObjId, Tag, Value};
/// Nodes per curve object.
const MAX_NODES: usize = 4_000_000;
+const MAX_COMPOUND_DEPTH: usize = 64;
+const MAX_OUTLINE_VISITS: usize = 500_000;
+const MAX_OUTLINE_POINTS: usize = 4_000_000;
+
+/// Geometry is expanded per occurrence, since parametric outlines can depend on their world
+/// transform. Bound work across the entire document instead of memoizing by object id alone.
+pub(crate) struct Budget {
+ visits_left: usize,
+ points_left: usize,
+}
+
+impl Default for Budget {
+ fn default() -> Self {
+ Self { visits_left: MAX_OUTLINE_VISITS, points_left: MAX_OUTLINE_POINTS }
+ }
+}
+
+impl Budget {
+ /// Charge an outline call or a raw compound operand slot before inspecting it.
+ fn visit(&mut self) -> Result<(), &'static str> {
+ self.visits_left = self.visits_left.checked_sub(1).ok_or("compound geometry budget exhausted")?;
+ Ok(())
+ }
+
+ /// Charge both leaf geometry and each copy into a compound before allocating that copy.
+ fn path(&mut self, path: &Path) -> Result<(), &'static str> {
+ let points = path.subpaths.iter().fold(0usize, |n, s| n.saturating_add(1).saturating_add(s.segments.len().saturating_mul(3)));
+ let Some(left) = self.points_left.checked_sub(points) else {
+ // Do not rebuild an expensive leaf for every subsequent root after exhaustion.
+ self.visits_left = 0;
+ return Err("compound geometry budget exhausted");
+ };
+ self.points_left = left;
+ Ok(())
+ }
+}
/// The node-space outline of a curve, shape or compound node, and whether it fills even-odd.
/// Instances (master-page or symbol copies) take the geometry of their master.
pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> {
+ match outline_inner(r, id, class, world, &mut Vec::new()) {
+ Ok(path) => path,
+ Err(reason) => {
+ r.warn(reason);
+ None
+ }
+ }
+}
+
+fn outline_inner(r: &mut Reader, id: ObjId, class: Tag, world: Affine, active: &mut Vec<ObjId>) -> Result<Option<(Path, bool)>, &'static str> {
+ r.geometry_budget.visit()?;
+ if active.contains(&id) {
+ return Err("cyclic compound shape");
+ }
+ // Independent of the layer-tree limit: Comp operands do not pass through Reader::node.
+ if active.len() >= MAX_COMPOUND_DEPTH {
+ return Err("compound depth exceeds 64 levels");
+ }
+ if class != Tag::of(b"Comp") {
+ let path = leaf_outline(r, id, class, world);
+ if let Some((path, _)) = &path {
+ r.geometry_budget.path(path)?;
+ }
+ return Ok(path);
+ }
+ active.push(id);
+ let result = compound(r, id, world, active);
+ active.pop();
+ result
+}
+
+fn compound(r: &mut Reader, id: ObjId, world: Affine, active: &mut Vec<ObjId>) -> Result<Option<(Path, bool)>, &'static str> {
+ let s = r.s;
+ // One path of all operands' contours, filled even-odd, as before. A safety failure rejects
+ // the whole outline: a partial add/subtract shape could silently change its meaning.
+ let mut path = Path::default();
+ // Charge every slot before filtering nulls or malformed values. Stream::objs would scan
+ // and allocate the whole list first, repeating uncharged work for each shared occurrence.
+ let children = if let Some(Value::Array(children)) = s.field(id, b"Chld") { children.as_slice() } else { &[] };
+ for child in children {
+ r.geometry_budget.visit()?;
+ let Value::Obj(Some(c)) = child else { continue };
+ let c = *c;
+ let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
+ let Some(class) = s.class(c) else { return Ok(None) };
+ if s.enumeration(c, b"ComO").is_some_and(|(op, _)| op != 0 && op != 2) {
+ r.warn("compound shapes that intersect or exclude (imported as add)");
+ }
+ if let Some((p, _)) = outline_inner(r, c, class, local.then(world), active)? {
+ r.geometry_budget.path(&p)?;
+ path.subpaths.extend(p.transformed(local).subpaths);
+ }
+ }
+ Ok(Some((path, true)))
+}
+
+fn leaf_outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> {
let s = r.s;
match &class.0.to_be_bytes() {
b"PCrv" | b"TxtC" => {
@@ -18,23 +111,6 @@ pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> O
let multi = path.subpaths.len() > 1;
Some((path, multi))
}
- b"Comp" => {
- // One path of all the operands' contours in the compound's space, filled even-odd: this
- // matches add and subtract operands in every public sample; a true union of overlapping
- // added operands would differ.
- let mut path = Path::default();
- for c in s.objs(id, b"Chld") {
- let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
- let class = s.class(c)?;
- if s.enumeration(c, b"ComO").is_some_and(|(op, _)| op != 0 && op != 2) {
- r.warn("compound shapes that intersect or exclude (imported as add)");
- }
- if let Some((p, _)) = outline(r, c, class, local.then(world)) {
- path.subpaths.extend(p.transformed(local).subpaths);
- }
- }
- Some((path, true))
- }
_ => {
let (shape, box_owner) = match s.obj(id, b"Shpe") {
Some(sh) => (sh, id),
diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs
index 7fba5a459..7c0507241 100644
--- a/crates/affinity/src/model.rs
+++ b/crates/affinity/src/model.rs
@@ -298,6 +298,7 @@ pub(crate) struct Reader<'s, 'a, 'b> {
warnings: BTreeMap<String, usize>,
nodes: usize,
active: HashSet<ObjId>,
+ pub(crate) geometry_budget: crate::geometry::Budget,
/// Decoded pixels still available ([`Limits::max_pixel_bytes`] less what the layers read so
/// far hold).
pixels_left: usize,
@@ -305,7 +306,16 @@ pub(crate) struct Reader<'s, 'a, 'b> {
impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
fn new(s: &'s Stream, archive: &'b mut Archive<'a>, limits: Limits) -> Self {
- Self { s, archive, dpi: 72.0, warnings: BTreeMap::new(), nodes: 0, active: HashSet::new(), pixels_left: limits.max_pixel_bytes }
+ Self {
+ s,
+ archive,
+ dpi: 72.0,
+ warnings: BTreeMap::new(),
+ nodes: 0,
+ active: HashSet::new(),
+ geometry_budget: crate::geometry::Budget::default(),
+ pixels_left: limits.max_pixel_bytes,
+ }
}
/// Admit a layer's decoded pixels before they are allocated (#4960). `rgba` is the layer's
diff --git a/crates/affinity/tests/compound_limits.rs b/crates/affinity/tests/compound_limits.rs
new file mode 100644
index 000000000..76f2e6e4a
--- /dev/null
+++ b/crates/affinity/tests/compound_limits.rs
@@ -0,0 +1,212 @@
+//! #6423: compound operands form a graph, not necessarily a tree.
+#![cfg(feature = "synth")]
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+use photocraft_affinity::model::{Document, Kind};
+use photocraft_affinity::synth::{self, F, Method, tag};
+use photocraft_affinity::{Limits, read};
+use std::time::{Duration, Instant};
+
+fn compound(id: u32, children: Vec<F>) -> F {
+ F::Def(id, vec![tag(b"Comp")], vec![(tag(b"Chld"), F::Shared(children))])
+}
+
+fn rectangle() -> F {
+ F::Def(100, vec![tag(b"ShpN")], vec![(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 10.0, 20.0])), (tag(b"Shpe"), F::Def(101, vec![tag(b"ShNR")], vec![]))])
+}
+
+fn document_bytes(definitions: Vec<F>, roots: Vec<F>) -> Vec<u8> {
+ let data = synth::stream(&[
+ (tag(b"Defs"), F::Shared(definitions)),
+ (
+ tag(b"DocR"),
+ F::Def(
+ 1,
+ vec![tag(b"DocN")],
+ vec![(
+ tag(b"Chld"),
+ F::Shared(vec![F::Def(
+ 2,
+ vec![tag(b"Sprd")],
+ vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(roots))],
+ )]),
+ )],
+ ),
+ ),
+ ]);
+ synth::container(&[("doc.dat", &data, Method::Zlib)], None)
+}
+
+fn document(definitions: Vec<F>, roots: Vec<F>) -> Document {
+ read(&document_bytes(definitions, roots), Limits::default()).unwrap()
+}
+
+// A stack overflow aborts rather than unwinds. Keep that failure (and an exponential hang)
+// inside a child process, so the regression fails without killing the entire test runner.
+fn isolated(name: &str, check: impl FnOnce()) {
+ if std::env::var("PHOTOCRAFT_COMPOUND_CASE").as_deref() == Ok(name) {
+ check();
+ return;
+ }
+ let mut child = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", name, "--nocapture"])
+ .env("PHOTOCRAFT_COMPOUND_CASE", name)
+ .spawn()
+ .unwrap();
+ let start = Instant::now();
+ loop {
+ if let Some(status) = child.try_wait().unwrap() {
+ assert!(status.success(), "compound import failed: {status}");
+ break;
+ }
+ if start.elapsed() > Duration::from_secs(10) {
+ child.kill().unwrap();
+ child.wait().unwrap();
+ panic!("compound import exceeded ten seconds");
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+}
+
+fn unsupported(doc: &Document, warning: &str) {
+ assert!(matches!(doc.spreads[0].nodes[0].kind, Kind::Unsupported));
+ assert!(doc.warnings.iter().any(|w| w.contains(warning)), "{:?}", doc.warnings);
+}
+
+#[test]
+fn self_referencing_compound_is_reported_without_aborting() {
+ isolated("self_referencing_compound_is_reported_without_aborting", || {
+ let doc = document(vec![], vec![compound(10, vec![F::Ref(10)]), rectangle()]);
+ unsupported(&doc, "cyclic compound");
+ assert!(matches!(doc.spreads[0].nodes[1].kind, Kind::Shape { .. }), "a cycle must not poison unrelated shapes");
+ });
+}
+
+#[test]
+fn indirectly_cyclic_compound_is_not_imported_as_a_partial_shape() {
+ isolated("indirectly_cyclic_compound_is_not_imported_as_a_partial_shape", || {
+ let doc = document(vec![rectangle()], vec![compound(10, vec![F::Ref(100), compound(11, vec![F::Ref(10)])])]);
+ unsupported(&doc, "cyclic compound");
+ });
+}
+
+fn nested(levels: u32, repeated: bool) -> Document {
+ // Flat definitions bypass the stream parser's nesting cap: only references form the depth.
+ let mut definitions = vec![rectangle()];
+ let mut previous = 100;
+ for id in 200..200 + levels {
+ let children = if repeated { vec![F::Ref(previous), F::Ref(previous)] } else { vec![F::Ref(previous)] };
+ definitions.push(compound(id, children));
+ previous = id;
+ }
+ document(definitions, vec![F::Ref(previous)])
+}
+
+#[test]
+fn deep_compound_graph_is_bounded_on_a_small_stack() {
+ isolated("deep_compound_graph_is_bounded_on_a_small_stack", || {
+ std::thread::Builder::new().stack_size(512 * 1024).spawn(|| unsupported(&nested(1000, false), "compound depth")).unwrap().join().unwrap();
+ });
+}
+
+#[test]
+fn shared_operands_cannot_expand_exponentially() {
+ isolated("shared_operands_cannot_expand_exponentially", || unsupported(&nested(40, true), "compound geometry budget"));
+}
+
+#[test]
+fn shared_empty_operands_also_have_a_work_limit() {
+ isolated("shared_empty_operands_also_have_a_work_limit", || {
+ let mut definitions = vec![compound(100, vec![])];
+ let mut previous = 100;
+ for id in 200..240 {
+ definitions.push(compound(id, vec![F::Ref(previous), F::Ref(previous)]));
+ previous = id;
+ }
+ unsupported(&document(definitions, vec![F::Ref(previous)]), "compound geometry budget");
+ });
+}
+
+#[test]
+fn geometry_budget_is_shared_across_layer_roots() {
+ isolated("geometry_budget_is_shared_across_layer_roots", || {
+ let mut definitions = vec![rectangle()];
+ let mut previous = 100;
+ for id in 200..214 {
+ definitions.push(compound(id, vec![F::Ref(previous), F::Ref(previous)]));
+ previous = id;
+ }
+ let mut roots = vec![F::Ref(previous); 12];
+ roots.push(F::Ref(100));
+ let doc = document(definitions, roots);
+ let nodes = &doc.spreads[0].nodes;
+ assert!(matches!(nodes[0].kind, Kind::Shape { .. }), "a modest shared graph still imports");
+ assert!(matches!(nodes.last().unwrap().kind, Kind::Unsupported), "later roots cannot reset the exhausted budget");
+ assert!(doc.warnings.iter().any(|w| w.contains("compound geometry budget")));
+ });
+}
+
+#[test]
+fn ordinary_shared_operands_keep_both_transformed_copies() {
+ let mut translated = compound(201, vec![F::Ref(100)]);
+ let F::Def(_, _, fields) = &mut translated else { unreachable!() };
+ fields.push((tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, 30.0, 0.0, 1.0, 40.0])));
+ let doc = document(vec![rectangle(), compound(200, vec![F::Ref(100)]), translated], vec![compound(202, vec![F::Ref(200), F::Ref(201)])]);
+ assert!(doc.warnings.is_empty(), "{:?}", doc.warnings);
+ let Kind::Shape { path, .. } = &doc.spreads[0].nodes[0].kind else { panic!("expected compound outline") };
+ assert_eq!(path.subpaths.len(), 2);
+ for (a, b) in path.subpaths[0].segments.iter().flatten().zip(path.subpaths[1].segments.iter().flatten()) {
+ assert_eq!(b.x, a.x + 30.0);
+ assert_eq!(b.y, a.y + 40.0);
+ }
+}
+
+#[test]
+fn null_operand_slots_cannot_bypass_geometry_budget() {
+ isolated("null_operand_slots_cannot_bypass_geometry_budget", || {
+ let bytes = document_bytes(vec![compound(10, vec![F::Null; 1_000_000])], vec![F::Ref(10); 20_000]);
+ let start = Instant::now();
+ let doc = read(&bytes, Limits::default()).unwrap();
+ eprintln!("one million nulls / 20,000 placements: {} bytes, read {:.3}s", bytes.len(), start.elapsed().as_secs_f64());
+ unsupported(&doc, "compound geometry budget");
+ assert_eq!(doc.spreads[0].nodes.len(), 20_000);
+ assert!(doc.spreads[0].nodes.iter().all(|n| matches!(n.kind, Kind::Unsupported)));
+ });
+}
+
+#[test]
+fn null_operand_slots_share_budget_across_layer_roots() {
+ isolated("null_operand_slots_share_budget_across_layer_roots", || {
+ let doc = document(vec![compound(10, vec![F::Null; 1_000])], vec![F::Ref(10); 1_000]);
+ assert!(matches!(doc.spreads[0].nodes[0].kind, Kind::Shape { .. }), "a small empty compound remains valid");
+ assert!(matches!(doc.spreads[0].nodes.last().unwrap().kind, Kind::Unsupported));
+ assert!(doc.warnings.iter().any(|w| w.contains("compound geometry budget")));
+ });
+}
+
+#[test]
+fn null_operand_slots_cannot_leave_a_partial_shape() {
+ isolated("null_operand_slots_cannot_leave_a_partial_shape", || {
+ let mut slots = vec![F::Ref(100)];
+ slots.extend(vec![F::Null; 1_000_000]);
+ let doc = document(vec![rectangle(), compound(10, slots)], vec![F::Ref(10)]);
+ unsupported(&doc, "compound geometry budget");
+ });
+}
+
+#[test]
+fn non_object_operand_slots_also_consume_budget() {
+ isolated("non_object_operand_slots_also_consume_budget", || {
+ let comp = F::Def(10, vec![tag(b"Comp")], vec![(tag(b"Chld"), F::U8s(vec![0; 1_000_000]))]);
+ unsupported(&document(vec![comp], vec![F::Ref(10)]), "compound geometry budget");
+ });
+}
+
+#[test]
+fn ordinary_null_operand_slots_preserve_shared_contours() {
+ let doc = document(vec![rectangle(), compound(10, vec![F::Null, F::Ref(100), F::Null, F::Ref(100), F::Null])], vec![F::Ref(10)]);
+ assert!(doc.warnings.is_empty(), "{:?}", doc.warnings);
+ let Kind::Shape { path, .. } = &doc.spreads[0].nodes[0].kind else { panic!("expected compound outline") };
+ assert_eq!(path.subpaths.len(), 2);
+ assert_eq!(path.subpaths[0], path.subpaths[1]);
+}