From 91eb2fc2ab70c34daed8520efd49b06ddfe306f3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 20:01:32 -0500 Subject: [PATCH 1/2] Read Penpot archives through craft-zip --- crates/format/Cargo.toml | 4 +- crates/format/src/penpot.rs | 112 ++++++++++++--------- crates/format/src/penpot/embedded_fonts.rs | 17 ++-- 3 files changed, 73 insertions(+), 60 deletions(-) diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 2a0101b04..bf00e6aeb 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -14,7 +14,6 @@ figcraft-pathops = { workspace = true } figcraft-layout = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } -zip = { workspace = true } flate2 = { workspace = true } ruzstd = { workspace = true } sha1 = { workspace = true } @@ -28,3 +27,6 @@ craft-figcraft-format = { workspace = true } craft-figma-rest = { workspace = true } craft-jpeg = { workspace = true } craft-image-codecs = { workspace = true } + +[dev-dependencies] +zip = { workspace = true } diff --git a/crates/format/src/penpot.rs b/crates/format/src/penpot.rs index c47b55b18..16a873d6a 100644 --- a/crates/format/src/penpot.rs +++ b/crates/format/src/penpot.rs @@ -8,6 +8,8 @@ use std::collections::{BTreeMap, BTreeSet}; use std::io::{self, Cursor, Read}; +use crate::{FormatError, add_image}; +use craft_zip::{SeekableArchive, SeekableLimits}; use figcraft_doc::color::{BlendMode, Color, ColorStop, Gradient, GradientKind, ImageScaleMode, Paint, PaintKind}; use figcraft_doc::geom::{Affine, BezPath, Shape}; use figcraft_doc::{ @@ -17,9 +19,8 @@ use figcraft_doc::{ Variable, VariableType, VariableValue, VectorNetwork, }; use serde_json::Value; -use zip::ZipArchive; -use crate::{FormatError, add_image}; +type PenpotArchive<'a> = SeekableArchive>; mod embedded_fonts; mod export; @@ -135,11 +136,12 @@ impl Read for BudgetReader<'_, R> { } /// Read a JSON archive member within the per-member decompression limit. -fn json(z: &mut ZipArchive>, path: &str, budget: &mut InflateBudget) -> Result { - let entry = z.by_name(path).map_err(|e| corrupt(format!("{path}: {e}")))?; - if entry.size() > MAX_JSON { +fn json(z: &mut PenpotArchive<'_>, path: &str, budget: &mut InflateBudget) -> Result { + let declared = z.declared_size(path).ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?; + if declared > MAX_JSON { return Err(corrupt(format!("JSON member too large: {path}"))); } + let entry = z.open_entry(path, MAX_JSON).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?; let mut data = Vec::new(); BudgetReader { inner: entry, budget }.take(MAX_JSON + 1).read_to_end(&mut data).map_err(|e| corrupt(e.to_string()))?; if data.len() as u64 > MAX_JSON { @@ -149,14 +151,15 @@ fn json(z: &mut ZipArchive>, path: &str, budget: &mut InflateBudge } /// Read a shape JSON member within member and per-page decompression limits. -fn shape_json(z: &mut ZipArchive>, path: &str, budget: &mut InflateBudget, page_budget: &mut u64) -> Result { - let entry = z.by_name(path).map_err(|e| corrupt(format!("{path}: {e}")))?; - if entry.size() > MAX_JSON { +fn shape_json(z: &mut PenpotArchive<'_>, path: &str, budget: &mut InflateBudget, page_budget: &mut u64) -> Result { + let declared = z.declared_size(path).ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?; + if declared > MAX_JSON { return Err(corrupt(format!("JSON member too large: {path}"))); } - if entry.size() > *page_budget { + if declared > *page_budget { return Err(corrupt("page shapes exceed byte budget")); } + let entry = z.open_entry(path, MAX_JSON).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?; let mut data = Vec::new(); let max_read = (MAX_JSON + 1).min(*page_budget + 1); BudgetReader { inner: entry, budget }.take(max_read).read_to_end(&mut data).map_err(|e| corrupt(e.to_string()))?; @@ -360,29 +363,35 @@ fn finish_masked_group(doc: &mut Document, group: NodeId, source: &Value, warnin } } +fn open_archive(bytes: &[u8]) -> Result, FormatError> { + let limits = SeekableLimits { + max_entries: MAX_ENTRIES as u64, + max_metadata_bytes: MAX_ARCHIVE as u64, + // The Penpot budget also charges partial reads (embedded font signatures) and + // remembers an overflow that an optional-member caller might otherwise swallow. + max_total_bytes: u64::MAX, + }; + let z = SeekableArchive::open(Cursor::new(bytes), limits).map_err(|e| match e { + craft_zip::Error::TooManyEntries { .. } => corrupt("too many ZIP members"), + _ => corrupt(format!("invalid ZIP: {e}")), + })?; + if let Some(name) = z.duplicate_names().next() { + return Err(corrupt(format!("duplicate ZIP member: {}", name.chars().take(200).collect::()))); + } + Ok(z) +} + /// Read one exported `.penpot` archive without touching the filesystem or running a converter. /// Returns native, editable FigCraft nodes plus notes about unsupported features. pub fn import(bytes: &[u8]) -> Result<(Document, Vec), FormatError> { if bytes.len() > MAX_ARCHIVE { return Err(corrupt("archive exceeds 512 MiB")); } - let mut z = ZipArchive::new(Cursor::new(bytes)).map_err(|e| corrupt(format!("invalid ZIP: {e}")))?; - if z.len() > MAX_ENTRIES { - return Err(corrupt("too many ZIP members")); - } - // Reject oversized logical archives before decoding any JSON. This guards against ZIP bombs - // whose compressed size is innocuous but whose advertised uncompressed size is enormous. + let mut z = open_archive(bytes)?; + // Check declared totals and member paths before decoding any JSON. let mut expanded = 0_u64; - let mut names = BTreeSet::new(); for index in 0..z.len() { - let member = z.by_index(index).map_err(|e| corrupt(e.to_string()))?; - // An importer never extracts members to disk, but ambiguous ZIP names can - // cause one member to be inspected and another member to be read by name. - // Reject duplicates and traversal instead of guessing which version is real. - let name = member.name(); - if !names.insert(name.to_owned()) { - return Err(corrupt(format!("duplicate ZIP member: {}", name.chars().take(200).collect::()))); - } + let name = z.entry_name(index).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?; if name.starts_with('/') || name.contains('\\') || name.split('/').any(|part| part == "." || part == "..") @@ -390,10 +399,14 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec), FormatError> { { return Err(corrupt("unsafe ZIP member path")); } - expanded = expanded.saturating_add(member.size()); + let (size, _) = z.entry_sizes(index).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?; + expanded = expanded.saturating_add(size); if expanded > MAX_DECOMPRESSED { return Err(corrupt("ZIP contents exceed 1 GiB")); } + // The old indexing pass also rejected entries the decoder could not open, + // even when mapping the document would never request those members. + z.open_entry_index(index, MAX_DECOMPRESSED).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?; } let mut inflate_budget = InflateBudget::new(); let manifest = json(&mut z, "manifest.json", &mut inflate_budget)?; @@ -447,12 +460,12 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec), FormatError> { // The page index files are peers of the directories containing their layers. let prefix = format!("{base}/pages/"); let page_names: Vec = z - .file_names() + .names() .filter(|name| { name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid)) }) .take(501) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect(); if page_names.len() > 500 { return Err(corrupt("too many pages")); @@ -508,13 +521,13 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec), FormatError> { } let page_prefix = format!("{prefix}{page_id}/"); let paths: Vec = z - .file_names() + .names() .filter(|name| { name.strip_prefix(&page_prefix) .is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid)) }) .take(MAX_LAYERS + 1) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect(); if paths.len() > MAX_LAYERS { return Err(corrupt("too many layers on a page")); @@ -1439,13 +1452,13 @@ fn bind_applied_tokens(doc: &mut Document, active_modes: &BTreeMap>, base: &str, doc: &mut Document, warnings: &mut Vec, budget: &mut InflateBudget) { +fn import_document_colors(z: &mut PenpotArchive<'_>, base: &str, doc: &mut Document, warnings: &mut Vec, budget: &mut InflateBudget) { let prefix = format!("{base}/colors/"); let paths = z - .file_names() + .names() .filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid))) .take(2049) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect::>(); if paths.len() > 2048 { warn(warnings, "Penpot color library exceeds 2048 swatches; truncated".into()); @@ -1483,7 +1496,7 @@ fn import_document_colors(z: &mut ZipArchive>, base: &str, doc: &m /// Keep original values on the text nodes: attaching a shared style automatically /// would override local formatting unless the source explicitly links it. fn import_typography_styles( - z: &mut ZipArchive>, + z: &mut PenpotArchive<'_>, base: &str, doc: &mut Document, warnings: &mut Vec, @@ -1492,10 +1505,10 @@ fn import_typography_styles( let mut custom_refs = Vec::new(); let prefix = format!("{base}/typographies/"); let paths: Vec = z - .file_names() + .names() .filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid))) .take(2049) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect(); if paths.len() > 2048 { warn(warnings, "Penpot typography library exceeds 2048 entries; truncated".into()); @@ -2359,7 +2372,7 @@ fn import_themed_tokens( /// Import supported scalar tokens and retain their original source. fn import_token_variables( - z: &mut ZipArchive>, + z: &mut PenpotArchive<'_>, base: &str, doc: &mut Document, active_modes: &mut BTreeMap, @@ -2367,7 +2380,9 @@ fn import_token_variables( budget: &mut InflateBudget, ) -> Option { let path = format!("{base}/tokens.json"); - z.index_for_name(&path)?; + if !z.contains(&path) { + return None; + } let value = match json(z, &path, budget) { Ok(v) => v, Err(_) => { @@ -2501,16 +2516,16 @@ fn report_design_system_limits(doc: &Document, warnings: &mut Vec) { /// that original into a native FigCraft component. Copies are still independent layers until the /// Penpot override/source graph can be translated safely (see docs). fn component_masters( - z: &mut ZipArchive>, + z: &mut PenpotArchive<'_>, base: &str, budget: &mut InflateBudget, ) -> (BTreeMap, BTreeMap, BTreeMap) { let prefix = format!("{base}/components/"); let paths = z - .file_names() + .names() .filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid))) .take(10001) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect::>(); let mut result = BTreeMap::new(); let mut variant_names = BTreeMap::new(); @@ -2971,7 +2986,7 @@ fn svg_paint_ref(text: &str) -> Option<&str> { /// What importing a page's layers shares from layer to layer: the archive and the page's shapes, /// and the document, budgets and warnings they add to. struct LayerImport<'a, 'b> { - z: &'a mut ZipArchive>, + z: &'a mut PenpotArchive<'b>, base: &'a str, shapes: &'a BTreeMap, children_by_parent: &'a BTreeMap>, @@ -4135,7 +4150,7 @@ fn effects(v: &Value, warnings: &mut Vec) -> Vec { /// Resolve a Penpot image fill through `media/.json` -> `objects/.png|jpg`. fn paints( - z: &mut ZipArchive>, + z: &mut PenpotArchive<'_>, base: &str, shape: &Value, key: &str, @@ -4170,10 +4185,7 @@ fn paints( }; if let Some(obj) = object_id { let p = format!("objects/{obj}.{extension}"); - let data = z.by_name(&p).ok().and_then(|f| { - if f.size() > MAX_IMAGE { - return None; - } + let data = z.open_entry(&p, MAX_IMAGE).ok().flatten().and_then(|f| { let mut bytes = Vec::new(); BudgetReader { inner: f, budget: &mut *budget }.take(MAX_IMAGE + 1).read_to_end(&mut bytes).ok()?; if bytes.len() as u64 > MAX_IMAGE || bytes.len() > MAX_TOTAL_IMAGES.saturating_sub(*image_bytes) { @@ -4385,7 +4397,7 @@ mod tests { writer.write_all(b"[0,0]").unwrap(); } let bytes = writer.finish().unwrap().into_inner(); - let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let mut archive = open_archive(&bytes).unwrap(); let mut budget = InflateBudget { json_values: 6, ..InflateBudget::new() }; let mut page_bytes = MAX_PAGE_SHAPES_BYTES; assert_eq!(json(&mut archive, "tokens.json", &mut budget).unwrap(), serde_json::json!([0, 0])); @@ -4493,14 +4505,14 @@ mod tests { z.start_file("shape.json", SimpleFileOptions::default()).unwrap(); z.write_all(br#"{"id":"00000000-0000-0000-0000-000000000001","type":"rect"}"#).unwrap(); let bytes = z.finish().unwrap().into_inner(); - let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let mut archive = open_archive(&bytes).unwrap(); let mut inflate_budget = InflateBudget::new(); let mut page_budget = 10u64; // Too small for the shape JSON (~60 bytes) let res = shape_json(&mut archive, "shape.json", &mut inflate_budget, &mut page_budget); assert!(res.is_err()); - let mut archive2 = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let mut archive2 = open_archive(&bytes).unwrap(); let mut inflate_budget2 = InflateBudget::new(); let mut page_budget2 = 1000u64; let res2 = shape_json(&mut archive2, "shape.json", &mut inflate_budget2, &mut page_budget2); @@ -4508,7 +4520,7 @@ mod tests { assert!(page_budget2 < 1000); } use std::io::Write; - use zip::write::SimpleFileOptions; + use zip::{ZipArchive, write::SimpleFileOptions}; fn archive_with_shapes(shapes: &[(&str, Value)]) -> Vec { archive_with_components(shapes, &[]) diff --git a/crates/format/src/penpot/embedded_fonts.rs b/crates/format/src/penpot/embedded_fonts.rs index d09896804..bba87462b 100644 --- a/crates/format/src/penpot/embedded_fonts.rs +++ b/crates/format/src/penpot/embedded_fonts.rs @@ -1,20 +1,19 @@ //! Embedded font detection without decoding or retaining unsupported binaries. -use super::{BudgetReader, InflateBudget, MAX_ENTRIES, warn}; -use std::io::{Cursor, Read}; -use zip::ZipArchive; +use super::{BudgetReader, InflateBudget, MAX_ENTRIES, PenpotArchive, warn}; +use std::io::Read; /// Identify unsupported fonts from signatures without decoding their payloads. -pub(super) fn report(z: &mut ZipArchive>, warnings: &mut Vec, budget: &mut InflateBudget) { +pub(super) fn report(z: &mut PenpotArchive<'_>, warnings: &mut Vec, budget: &mut InflateBudget) { let names: Vec = z - .file_names() + .names() .filter(|n| n.starts_with("objects/") || n.starts_with("fonts/") || n.starts_with("assets/fonts/")) .take(MAX_ENTRIES) - .map(str::to_owned) + .map(std::borrow::Cow::into_owned) .collect(); let mut count = 0; for name in names { - let Ok(member) = z.by_name(&name) else { continue }; + let Ok(Some(member)) = z.open_entry(&name, u64::MAX) else { continue }; let mut header = [0; 4]; if (BudgetReader { inner: member, budget }).read_exact(&mut header).is_ok() && (matches!(&header, b"OTTO" | b"true" | b"ttcf" | b"wOFF" | b"wOF2") || header == [0, 1, 0, 0]) @@ -35,7 +34,7 @@ pub(super) fn report(z: &mut ZipArchive>, warnings: &mut Vec Date: Mon, 23 Nov 2026 20:06:52 -0500 Subject: [PATCH 2/2] Use ZIP 9.8.2 for FigCraft test fixtures Covers the dependency bump from #1602 using current fixture APIs and adds a normal CP437 ancillary-member regression. --- Cargo.lock | 89 ++++++++------------- Cargo.toml | 2 +- apps/figcraft-server/src/hardening_tests.rs | 2 +- crates/engine/src/jam_open_tests.rs | 4 +- crates/format/src/fig/export_tests.rs | 3 +- crates/format/src/fig/interop_tests.rs | 2 +- crates/format/src/image_budget_tests.rs | 2 +- crates/format/src/image_tests.rs | 18 +++-- crates/format/src/library_tests.rs | 2 +- crates/format/src/penpot.rs | 25 +++++- crates/format/src/penpot/export_tests.rs | 6 +- 11 files changed, 80 insertions(+), 75 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b56684fec..633b613d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -249,15 +249,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arboard" version = "3.7.0" @@ -935,6 +926,15 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -1106,7 +1106,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "zip 9.1.1", + "zip", ] [[package]] @@ -1448,7 +1448,7 @@ dependencies = [ "verifysign", "winreg", "winsafe", - "zip 9.1.1", + "zip", ] [[package]] @@ -1504,7 +1504,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=a49329e71e32ad93794ab5 dependencies = [ "flate2", "thiserror 2.0.21", - "zip 9.1.1", + "zip", ] [[package]] @@ -1641,17 +1641,6 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" -[[package]] -name = "derive_arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - [[package]] name = "deunicode" version = "1.6.2" @@ -2265,7 +2254,7 @@ dependencies = [ "thiserror 2.0.21", "wat", "web-time", - "zip 2.6.1", + "zip", ] [[package]] @@ -2290,7 +2279,7 @@ dependencies = [ "serde_json", "sha1", "sha2", - "zip 2.6.1", + "zip", ] [[package]] @@ -2408,7 +2397,7 @@ dependencies = [ "toml", "tungstenite", "wat", - "zip 2.6.1", + "zip", ] [[package]] @@ -7466,6 +7455,20 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -7506,33 +7509,21 @@ dependencies = [ [[package]] name = "zip" -version = "2.6.1" +version = "9.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" -dependencies = [ - "arbitrary", - "crc32fast", - "crossbeam-utils", - "flate2", - "indexmap", - "memchr", - "zopfli", -] - -[[package]] -name = "zip" -version = "9.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "518b847fd864440c379748ad684c449f293af68978a485a4ff16f7c901c1f7c4" +checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" dependencies = [ + "constant_time_eq", "crc32fast", "flate2", "getrandom 0.4.3", "indexmap", + "libc", "memchr", "nix", "typed-path", "windows-sys 0.61.2", + "zeroize", ] [[package]] @@ -7547,18 +7538,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zopfli" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index c891c0ef4..af4f7c060 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -110,7 +110,7 @@ icu_segmenter = { version = "2.3", default-features = false, features = ["compil # dependencies, BSD-3-Clause, no_std so the web build keeps it too). deunicode = "1.6" linesweeper = "0.4" -zip = { version = "2", default-features = false, features = ["deflate"] } +zip = { version = "=9.8.2", default-features = false, features = ["deflate-flate2"] } # `.fig` import: raw deflate chunks (already built for zip) and zstd chunks (pure Rust, MIT, wasm-safe). flate2 = { version = "1", default-features = false, features = ["rust_backend"] } ruzstd = { version = "0.9.1", default-features = false, features = ["std"] } diff --git a/apps/figcraft-server/src/hardening_tests.rs b/apps/figcraft-server/src/hardening_tests.rs index 186b8d9c0..119a8dc4b 100644 --- a/apps/figcraft-server/src/hardening_tests.rs +++ b/apps/figcraft-server/src/hardening_tests.rs @@ -47,7 +47,7 @@ pub(crate) fn archive(bomb: usize, padding: usize) -> Vec { let mut out = zip::ZipWriter::new(Cursor::new(Vec::new())); for i in 0..src.len() { let f = src.by_index_raw(i).unwrap(); - if bomb > 0 && f.name() == "library/document.json" { + if bomb > 0 && f.name().expect("ZIP member name") == "library/document.json" { continue; } out.raw_copy_file(f).unwrap(); diff --git a/crates/engine/src/jam_open_tests.rs b/crates/engine/src/jam_open_tests.rs index 682bc2346..cdad20bfb 100644 --- a/crates/engine/src/jam_open_tests.rs +++ b/crates/engine/src/jam_open_tests.rs @@ -20,11 +20,11 @@ fn jam_file(tag: &str) -> std::path::PathBuf { let mut member = from.by_index(i).unwrap(); let mut bytes = Vec::new(); member.read_to_end(&mut bytes).unwrap(); - if member.name() == "canvas.fig" { + if member.name().expect("ZIP member name") == "canvas.fig" { assert!(bytes.starts_with(b"fig-kiwi")); bytes.splice(..8, *b"fig-jam."); } - to.start_file(member.name(), zip::write::SimpleFileOptions::default()).unwrap(); + to.start_file(member.name().expect("ZIP member name"), zip::write::SimpleFileOptions::default()).unwrap(); to.write_all(&bytes).unwrap(); } let path = std::env::temp_dir().join(format!("figcraft-jam-{tag}-{}.jam", std::process::id())); diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 9cb417078..306a82e49 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -1380,7 +1380,8 @@ fn images_are_named_by_the_sha1_of_their_bytes() { assert_eq!(export::sha1_hex(&vec![b'a'; 1_000_000]), "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); let (bytes, _) = export(&generate(3), None).unwrap(); let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap(); - let names: Vec = z.file_names().filter(|n| n.starts_with("images/")).map(str::to_string).collect(); + let names: Vec = + z.file_names().map(|name| name.expect("ZIP member name")).filter(|n| n.starts_with("images/")).map(std::borrow::Cow::into_owned).collect(); assert!(!names.is_empty()); for name in names { let data = crate::read_member(&mut z, &name, 1 << 26).unwrap(); diff --git a/crates/format/src/fig/interop_tests.rs b/crates/format/src/fig/interop_tests.rs index 4ad81cebc..c43b61c21 100644 --- a/crates/format/src/fig/interop_tests.rs +++ b/crates/format/src/fig/interop_tests.rs @@ -364,7 +364,7 @@ fn mask_types_round_trip() { fn the_archive_lists_its_members_and_describes_the_file() { let (bytes, _) = export(&sample(), Some(&super::tests::png())).unwrap(); let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap(); - let names: Vec = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect(); + let names: Vec = (0..z.len()).map(|i| z.by_index(i).unwrap().name().expect("ZIP member name").into_owned()).collect(); assert_eq!(names, ["canvas.fig", "thumbnail.png", "meta.json"]); let meta: serde_json::Value = serde_json::from_slice(&crate::read_member(&mut z, "meta.json", 1 << 20).unwrap()).unwrap(); assert_eq!(meta["file_name"], "Interop"); diff --git a/crates/format/src/image_budget_tests.rs b/crates/format/src/image_budget_tests.rs index 8e10cd714..51aee7609 100644 --- a/crates/format/src/image_budget_tests.rs +++ b/crates/format/src/image_budget_tests.rs @@ -31,7 +31,7 @@ fn file_with_images(n: u8) -> (Vec, Vec, u64) { /// `bytes` with one more member, `name` holding `data`. fn with_member(bytes: &[u8], name: &str, data: &[u8]) -> Vec { let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let names: Vec = z.file_names().map(str::to_string).collect(); + let names: Vec = z.file_names().map(|name| name.expect("ZIP member name")).map(std::borrow::Cow::into_owned).collect(); let mut buf = std::io::Cursor::new(Vec::new()); let mut w = zip::ZipWriter::new(&mut buf); let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); diff --git a/crates/format/src/image_tests.rs b/crates/format/src/image_tests.rs index b885fc20c..6a8b72477 100644 --- a/crates/format/src/image_tests.rs +++ b/crates/format/src/image_tests.rs @@ -25,7 +25,7 @@ fn doc_with_image() -> (Document, String) { /// The archive of `d` rebuilt with `edit` applied to each member (None drops it). fn rebuild(bytes: &[u8], edit: impl Fn(&str, Vec) -> Option>) -> Vec { let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let names: Vec = z.file_names().map(str::to_string).collect(); + let names: Vec = z.file_names().map(|name| name.expect("ZIP member name")).map(std::borrow::Cow::into_owned).collect(); let mut buf = std::io::Cursor::new(Vec::new()); let mut w = zip::ZipWriter::new(&mut buf); for n in names { @@ -109,7 +109,11 @@ fn image_members_with_path_like_names_are_dropped_and_not_saved_back() { assert!(!loaded.issues.is_empty()); let saved = save_bytes_with_history(&loaded.doc, None, &loaded.versions, &loaded.branches).unwrap(); let z = zip::ZipArchive::new(std::io::Cursor::new(saved)).unwrap(); - assert!(z.file_names().all(|n| !n.contains("..") && n.matches('/').count() <= 1), "{:?}", z.file_names().collect::>()); + assert!( + z.file_names().map(|name| name.expect("ZIP member name")).all(|n| !n.contains("..") && n.matches('/').count() <= 1), + "{:?}", + z.file_names().map(|name| name.expect("ZIP member name")).collect::>() + ); let _ = hash; } @@ -128,11 +132,15 @@ fn a_path_like_rest_image_ref_never_names_an_archive_member() { assert!(doc.images.contains_key("rest-image-missing"), "the shared placeholder stores it instead: {:?}", doc.images.keys().collect::>()); let bytes = save_bytes(&doc, None).unwrap(); let z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); - assert!(z.file_names().all(|n| !n.contains("..") && n.matches('/').count() <= 1), "{:?}", z.file_names().collect::>()); assert!( - z.file_names().any(|n| n == "images/rest-image-missing"), + z.file_names().map(|name| name.expect("ZIP member name")).all(|n| !n.contains("..") && n.matches('/').count() <= 1), + "{:?}", + z.file_names().map(|name| name.expect("ZIP member name")).collect::>() + ); + assert!( + z.file_names().map(|name| name.expect("ZIP member name")).any(|n| n == "images/rest-image-missing"), "the placeholder is saved under its own name: {:?}", - z.file_names().collect::>() + z.file_names().map(|name| name.expect("ZIP member name")).collect::>() ); } diff --git a/crates/format/src/library_tests.rs b/crates/format/src/library_tests.rs index b1f26b0c5..1a43014bb 100644 --- a/crates/format/src/library_tests.rs +++ b/crates/format/src/library_tests.rs @@ -81,7 +81,7 @@ fn replace_member(zip_bytes: &[u8], name: &str, bytes: Option<&[u8]>) -> Vec let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); for i in 0..src.len() { let mut f = src.by_index(i).unwrap(); - let n = f.name().to_string(); + let n = f.name().expect("ZIP member name").to_string(); let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); let data = if n == name { bytes.map(<[u8]>::to_vec) } else { Some(data) }; diff --git a/crates/format/src/penpot.rs b/crates/format/src/penpot.rs index 16a873d6a..40238ffb0 100644 --- a/crates/format/src/penpot.rs +++ b/crates/format/src/penpot.rs @@ -4446,8 +4446,8 @@ mod tests { assert!(dense.len() < MAX_JSON as usize); for index in 0..source.len() { let mut member = source.by_index(index).unwrap(); - writer.start_file(member.name(), crate::json_options()).unwrap(); - if member.name().ends_with(&format!("/{id}.json")) { + writer.start_file(member.name().expect("ZIP member name"), crate::json_options()).unwrap(); + if member.name().expect("ZIP member name").ends_with(&format!("/{id}.json")) { writer.write_all(dense.as_bytes()).unwrap(); } else { io::copy(&mut member, &mut writer).unwrap(); @@ -4558,6 +4558,23 @@ mod tests { z.finish().unwrap().into_inner() } + #[test] + fn import_allows_a_legacy_encoded_ancillary_zip_member() { + let id = "cccccccc-cccc-cccc-cccc-cccccccccccc"; + let bytes = archive_with_shapes(&[(id, serde_json::json!({"id":id,"type":"rect","name":"Imported rectangle","width":40,"height":25}))]); + let mut writer = zip::ZipWriter::new_append(Cursor::new(bytes)).unwrap(); + // Unflagged CP437, as written by legacy ZIP tools: 0x82 is é. + writer.start_file_with_options(SimpleFileOptions::default().name(b"caf\x82.txt")).unwrap(); + writer.write_all(b"Ancillary archive note").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + + let mut archive = open_archive(&bytes).unwrap(); + assert!((0..archive.len()).any(|i| archive.entry_name(i).unwrap().as_deref() == Some("café.txt"))); + let (doc, warnings) = import(&bytes).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(doc.nodes().any(|node| node.name == "Imported rectangle")); + } + #[test] fn raw_svg_from_export_is_preserved_for_native_svg_expansion() { let id = "cccccccc-cccc-cccc-cccc-cccccccccccc"; @@ -4941,12 +4958,12 @@ mod tests { let mut e = z.by_index(i).unwrap(); let mut content = Vec::new(); e.read_to_end(&mut content).unwrap(); - if e.name().ends_with(&format!("/{ROOT_ID}.json")) { + if e.name().expect("ZIP member name").ends_with(&format!("/{ROOT_ID}.json")) { let mut v: Value = serde_json::from_slice(&content).unwrap(); v["shapes"] = serde_json::json!([one]); content = serde_json::to_vec(&v).unwrap(); } - members.push((e.name().to_string(), content)); + members.push((e.name().expect("ZIP member name").to_string(), content)); } drop(z); let cursor = Cursor::new(Vec::new()); diff --git a/crates/format/src/penpot/export_tests.rs b/crates/format/src/penpot/export_tests.rs index e3ad744ef..c16f43e82 100644 --- a/crates/format/src/penpot/export_tests.rs +++ b/crates/format/src/penpot/export_tests.rs @@ -18,7 +18,7 @@ fn entries(bytes: &[u8]) -> BTreeMap { let mut out = BTreeMap::new(); for i in 0..z.len() { let mut f = z.by_index(i).unwrap(); - let name = f.name().to_owned(); + let name = f.name().expect("ZIP member name").into_owned(); if name.ends_with(".json") { let mut text = String::new(); f.read_to_string(&mut text).unwrap(); @@ -684,7 +684,7 @@ fn imported_penpot_tokens_are_written_back_verbatim() { doc.node_mut(p).unwrap().plugin_data.insert("penpot.fp.tokens".into(), fp); let (bytes, warnings) = export(&doc).unwrap(); let mut z = zip::ZipArchive::new(Cursor::new(&bytes[..])).unwrap(); - let path = z.file_names().find(|n| n.ends_with("tokens.json")).unwrap().to_owned(); + let path = z.file_names().map(|name| name.expect("ZIP member name")).find(|n| n.ends_with("tokens.json")).unwrap().into_owned(); let mut text = String::new(); z.by_name(&path).unwrap().read_to_string(&mut text).unwrap(); assert_eq!(text, source); @@ -1033,7 +1033,7 @@ fn shared_writer_keeps_manifest_first_and_deflated_members() { let doc = Document::new("Shared container"); let (bytes, _) = export(&doc).unwrap(); let mut zip = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); - assert_eq!(zip.by_index(0).unwrap().name(), "manifest.json"); + assert_eq!(zip.by_index(0).unwrap().name().expect("ZIP member name"), "manifest.json"); for index in 0..zip.len() { assert_eq!(zip.by_index(index).unwrap().compression(), zip::CompressionMethod::Deflated); }