//! All 3 cases, each run over both committed fixtures, plus the vector table //! and the parser's refusals. //! //! The ranged path is what the phone uses (it never holds the archive in //! memory); the whole-buffer path is what the CLI uses. They share the //! central-directory parser, and this file holds them to identical answers on //! REAL zips produced by the system `zip` tool — the same two fixtures the //! TypeScript reads. //! //! ## The fixtures are read BY PATH, at COMPILE time //! //! `include_bytes!` is the strongest form of the by-path guard the repo's rule //! asks for: a moved fixture is a BUILD failure naming the path it could not //! find, never a test that quietly starts passing over an empty read. It is //! the `?raw` import the site's `handles.test.ts` uses, in Rust. //! //! Both paths are CRATE-LOCAL (step 5, R12). The archives used to be //! `include_bytes!`d out of `packages/import-core/__tests__/fixtures/`, which //! meant the Rust build broke the moment that package was deleted; they were //! copied into this crate's own `tests/fixtures/` first, byte for byte, so the //! deletion is a deletion and not also a fixture move nobody reviews. No read //! under `crates/` reaches outside `crates/` except the allow-listed //! `cotton-tools/src/relay_name_tests.rs`; the sweep that holds that is //! the crate-local reads test. use super::*; use sha2::{Digest, Sha256}; const SAMPLE_ZIP: &[u8] = include_bytes!("../../tests/fixtures/sample-export.zip"); const GROUP_ZIP: &[u8] = include_bytes!("../../tests/fixtures/group-export.zip"); /// A reader that also counts what it was asked for, so the access PATTERN can /// be pinned — the property the phone depends on is "one media file, not the /// archive". struct CountingReader<'a> { bytes: &'a [u8], read: std::cell::Cell, } impl<'a> CountingReader<'a> { fn new(bytes: &'a [u8]) -> Self { Self { bytes, read: std::cell::Cell::new(0), } } fn bytes_read(&self) -> u64 { self.read.get() } } impl ZipRangeReader for CountingReader<'_> { fn size(&self) -> u64 { self.bytes.len() as u64 } fn read(&self, offset: u64, length: u64) -> Result, ZipError> { let end = offset.checked_add(length).ok_or_else(|| { ZipError::Reader(format!("read out of range: {offset}+{length} overflows")) })?; if end > self.bytes.len() as u64 { return Err(ZipError::Reader(format!( "read out of range: {offset}+{length} of {}", self.bytes.len() ))); } self.read.set(self.read.get() + length); Ok(self.bytes[offset as usize..end as usize].to_vec()) } } fn sha256_hex(bytes: &[u8]) -> String { hex::encode(Sha256::digest(bytes)) } fn fixtures() -> [(&'static str, &'static [u8]); 2] { [ ("sample-export.zip", SAMPLE_ZIP), ("group-export.zip", GROUP_ZIP), ] } // ── zip.test.ts, over both fixtures ───────────────────────────────────────── #[test] fn lists_the_same_entries_as_the_whole_buffer_path() { for (name, bytes) in fixtures() { let whole = list_zip_entries(bytes).expect("the fixture is a zip"); let ranged = list_zip_entries_ranged(&CountingReader::new(bytes)).expect("the fixture is a zip"); assert_eq!(ranged, whole, "{name}"); assert!(!whole.is_empty(), "{name}"); } } #[test] fn reads_every_entry_byte_identically_to_the_whole_buffer_path() { for (name, bytes) in fixtures() { let entries = list_zip_entries(bytes).expect("the fixture is a zip"); let reader = CountingReader::new(bytes); for entry in &entries { let whole = read_zip_entry(bytes, entry).expect("the entry reads"); let ranged = read_zip_entry_ranged(&reader, entry).expect("the entry reads"); assert_eq!(ranged, whole, "{name} / {}", entry.name); assert_eq!( ranged.len() as u64, entry.uncompressed_size, "{name} / {}", entry.name ); } } } #[test] fn reads_one_entry_without_touching_the_rest_of_the_archives_data() { for (name, bytes) in fixtures() { let mut entries = list_zip_entries(bytes).expect("the fixture is a zip"); entries.sort_by_key(|entry| entry.compressed_size); let smallest = entries.first().expect("the fixture has entries").clone(); let reader = CountingReader::new(bytes); read_zip_entry_ranged(&reader, &smallest).expect("the entry reads"); // Local header (30) + name/extra slack + the entry itself — never the // file. assert!( reader.bytes_read() < smallest.compressed_size + 4096, "{name}: read {} for a {}-byte entry", reader.bytes_read(), smallest.compressed_size ); } } // ── Node vectors ──────────────────────────────────────────────────────────── // // Every number and digest below was produced by RUNNING // `packages/import-core/src/zip.ts` under Node 22 against the same two // committed fixtures — the central directory as it parses it, the payload // range it computes from each local header, and the SHA-256 of the inflated // bytes. struct EntryVector { name: &'static str, compressed_size: u64, uncompressed_size: u64, method: u16, flags: u16, local_header_offset: u64, stored: bool, content: bool, data_offset: u64, data_length: u64, sha256: &'static str, } /// `sample-export.zip` — a DEFLATED `_chat.txt` beside a STORED image, which /// is what makes it the fixture that proves both branches of `inflate_entry`. const SAMPLE_VECTORS: &[EntryVector] = &[ EntryVector { name: "_chat.txt", compressed_size: 192, uncompressed_size: 284, method: 8, flags: 0, local_header_offset: 0, stored: false, content: true, data_offset: 39, data_length: 192, sha256: "c6d6919c5f748db11946ed7dae447d6ada6b160d73712d0dd822268a844177c0", }, EntryVector { name: "IMG-20250726-WA0001.jpg", compressed_size: 26, uncompressed_size: 26, method: 0, flags: 0, local_header_offset: 231, stored: true, content: true, data_offset: 284, data_length: 26, sha256: "adbe1e98c49f38617253ec9d718c2b3d08032d83ac1306e2e4f55aab424c1457", }, ]; /// `group-export.zip` — three STORED entries, one of them a document. const GROUP_VECTORS: &[EntryVector] = &[ EntryVector { name: "_chat.txt", compressed_size: 1281, uncompressed_size: 1281, method: 0, flags: 0, local_header_offset: 0, stored: true, content: true, data_offset: 39, data_length: 1281, sha256: "f63fd75a04cc6edd7fdf800211497428abb4a4d8ef1f348fb01fba32d1b6dc38", }, EntryVector { name: "00000011-Requirement.docx", compressed_size: 36, uncompressed_size: 36, method: 0, flags: 0, local_header_offset: 1320, stored: true, content: true, data_offset: 1375, data_length: 36, sha256: "e671e1df8f53ce03c3f479a5f8d9954f43f1b1a277b9d716c23256113c5f092c", }, EntryVector { name: "00000012-PHOTO-2026-07-02-09-16-30.jpg", compressed_size: 343, uncompressed_size: 343, method: 0, flags: 0, local_header_offset: 1411, stored: true, content: true, data_offset: 1479, data_length: 343, sha256: "cd5f502d0b6f2ec1ca1201839f5da7d8c242f7a89949a1c999c616e6eee6a778", }, ]; #[test] fn vector_the_whole_central_directory_of_both_fixtures() { for ((name, bytes), expected) in fixtures().into_iter().zip([SAMPLE_VECTORS, GROUP_VECTORS]) { let entries = list_zip_entries(bytes).expect("the fixture is a zip"); assert_eq!(entries.len(), expected.len(), "{name}: entry count"); let reader = CountingReader::new(bytes); for (entry, want) in entries.iter().zip(expected.iter()) { assert_eq!(entry.name, want.name, "{name}: name"); assert_eq!( entry.compressed_size, want.compressed_size, "{name}/{}: compressedSize", want.name ); assert_eq!( entry.uncompressed_size, want.uncompressed_size, "{name}/{}: uncompressedSize", want.name ); assert_eq!(entry.method, want.method, "{name}/{}: method", want.name); assert_eq!(entry.flags, want.flags, "{name}/{}: flags", want.name); assert_eq!( entry.local_header_offset, want.local_header_offset, "{name}/{}: localHeaderOffset", want.name ); assert_eq!( is_stored_entry(entry), want.stored, "{name}/{}: isStoredEntry", want.name ); assert_eq!( is_content_entry(entry), want.content, "{name}/{}: isContentEntry", want.name ); assert_eq!( zip_entry_data_range(&reader, entry).expect("the range resolves"), ZipDataRange { offset: want.data_offset, length: want.data_length, }, "{name}/{}: zipEntryDataRange", want.name ); assert_eq!( sha256_hex(&read_zip_entry(bytes, entry).expect("the entry reads")), want.sha256, "{name}/{}: inflated bytes", want.name ); } } } // ── The refusals ──────────────────────────────────────────────────────────── // // The TypeScript states each of these in prose ("Deliberately NOT supported, // each failing loudly rather than silently") without a test. They are the // behaviour a caller renders to the owner, so they are pinned here. /// Assemble a minimal archive out of already-final payloads. /// /// Synthetic by construction — no real filename or content goes into this tree. fn build_zip(entries: &[(&str, &[u8], u16, u16)], eocd_override: Option<(u32, u16)>) -> Vec { let mut out: Vec = Vec::new(); let mut offsets: Vec = Vec::new(); for (name, data, method, flags) in entries { offsets.push(out.len() as u32); out.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); out.extend_from_slice(&20u16.to_le_bytes()); // version needed out.extend_from_slice(&flags.to_le_bytes()); out.extend_from_slice(&method.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); // time out.extend_from_slice(&0u16.to_le_bytes()); // date out.extend_from_slice(&0u32.to_le_bytes()); // crc (unread) out.extend_from_slice(&(data.len() as u32).to_le_bytes()); out.extend_from_slice(&(data.len() as u32).to_le_bytes()); out.extend_from_slice(&(name.len() as u16).to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); // extra out.extend_from_slice(name.as_bytes()); out.extend_from_slice(data); } let central_offset = out.len() as u32; for ((name, data, method, flags), offset) in entries.iter().zip(offsets.iter()) { out.extend_from_slice(&0x0201_4b50u32.to_le_bytes()); out.extend_from_slice(&20u16.to_le_bytes()); // version made by out.extend_from_slice(&20u16.to_le_bytes()); // version needed out.extend_from_slice(&flags.to_le_bytes()); out.extend_from_slice(&method.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&0u32.to_le_bytes()); out.extend_from_slice(&(data.len() as u32).to_le_bytes()); out.extend_from_slice(&(data.len() as u32).to_le_bytes()); out.extend_from_slice(&(name.len() as u16).to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); // extra out.extend_from_slice(&0u16.to_le_bytes()); // comment out.extend_from_slice(&0u16.to_le_bytes()); // disk out.extend_from_slice(&0u16.to_le_bytes()); // internal attrs out.extend_from_slice(&0u32.to_le_bytes()); // external attrs out.extend_from_slice(&offset.to_le_bytes()); out.extend_from_slice(name.as_bytes()); } let central_size = out.len() as u32 - central_offset; let (eocd_offset, eocd_count) = eocd_override.unwrap_or((central_offset, entries.len() as u16)); out.extend_from_slice(&0x0605_4b50u32.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); // this disk out.extend_from_slice(&0u16.to_le_bytes()); // disk with cd out.extend_from_slice(&eocd_count.to_le_bytes()); out.extend_from_slice(&eocd_count.to_le_bytes()); out.extend_from_slice(¢ral_size.to_le_bytes()); out.extend_from_slice(&eocd_offset.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); // comment length out } fn format_message(error: &ZipError) -> String { match error { ZipError::Format(message) => message.clone(), other => panic!("expected a format refusal, got {other:?}"), } } #[test] fn a_file_with_no_end_record_is_not_a_zip() { let error = list_zip_entries(b"this is not a zip file at all, not even close") .expect_err("a text file is not an archive"); assert_eq!( format_message(&error), "Not a zip file (no end-of-central-directory record found)." ); } /// An empty buffer takes the SAME path as a text file on the whole-archive /// side — the backwards scan simply never runs — but the ranged side refuses /// earlier, with its own sentence, because it can ask the reader for a length /// before it reads anything. #[test] fn an_empty_archive_is_refused_on_both_paths_with_their_own_sentences() { assert_eq!( format_message(&list_zip_entries(&[]).expect_err("empty is not an archive")), "Not a zip file (no end-of-central-directory record found)." ); let error = list_zip_entries_ranged(&CountingReader::new(&[])).expect_err("empty is not an archive"); assert_eq!( format_message(&error), "Not a zip file (too small to hold an end-of-central-directory record)." ); } /// The ZIP64 refusal is an INSTRUCTION to the owner, and it must survive the /// port word for word. #[test] fn a_zip64_archive_is_refused_with_the_instruction_verbatim() { let zip = build_zip( &[("_chat.txt", b"hello", 0, 0)], Some((0xffff_ffff, 1)), // the ZIP64 sentinel in the central-directory offset ); let error = list_zip_entries(&zip).expect_err("ZIP64 is refused"); assert_eq!( format_message(&error), "This is a ZIP64 archive, which this reader does not support. Unzip it yourself and point the importer at the extracted folder instead." ); // The sentinel in the ENTRY COUNT refuses the same way. let by_count = build_zip(&[("_chat.txt", b"hello", 0, 0)], Some((0, 0xffff))); assert_eq!( format_message(&list_zip_entries(&by_count).expect_err("ZIP64 is refused")), format_message(&error) ); } #[test] fn an_encrypted_entry_names_itself_in_the_refusal() { let zip = build_zip(&[("_chat.txt", b"hello", 0, 0x0001)], None); let entries = list_zip_entries(&zip).expect("the directory still parses"); assert_eq!(entries[0].flags & 0x0001, 0x0001); assert_eq!( format_message(&read_zip_entry(&zip, &entries[0]).expect_err("encrypted is refused")), "\"_chat.txt\" is encrypted; this reader cannot open it." ); // The ranged path refuses at the same point, before it reads a byte. let reader = CountingReader::new(&zip); assert_eq!( format_message( &zip_entry_data_range(&reader, &entries[0]).expect_err("encrypted is refused") ), "\"_chat.txt\" is encrypted; this reader cannot open it." ); assert_eq!(reader.bytes_read(), 0); } #[test] fn an_unsupported_compression_method_names_itself_and_its_number() { // 12 is BZIP2 — legal ZIP, not something a WhatsApp export ever writes. let zip = build_zip(&[("_chat.txt", b"hello", 12, 0)], None); let entries = list_zip_entries(&zip).expect("the directory still parses"); assert_eq!( format_message(&read_zip_entry(&zip, &entries[0]).expect_err("method 12 is refused")), "\"_chat.txt\" uses compression method 12, which this reader does not support." ); } #[test] fn a_central_directory_that_starts_past_its_own_end_record_is_corrupt() { let zip = build_zip(&[("_chat.txt", b"hello", 0, 0)], None); let broken = build_zip( &[("_chat.txt", b"hello", 0, 0)], Some((zip.len() as u32, 1)), ); assert_eq!( format_message(&list_zip_entries(&broken).expect_err("a forward offset is corrupt")), "Corrupt central directory (starts past its own end record)." ); // The ranged path has its own sentence for the same class of damage. assert_eq!( format_message( &list_zip_entries_ranged(&CountingReader::new(&broken)) .expect_err("a forward offset is corrupt") ), "Corrupt central directory (does not sit before its own end record)." ); } /// An entry count larger than the directory holds is named, with the index it /// failed at and the count it was promised — which is what makes a truncated /// download distinguishable from a file that was never a zip. #[test] fn a_directory_short_of_its_promised_entry_count_names_the_entry() { let zip = build_zip(&[("_chat.txt", b"hello", 0, 0)], None); let mut lying = zip.clone(); // Rewrite both entry counts in the EOCD (offsets 8 and 10 from its start). let eocd = lying.len() - 22; lying[eocd + 8..eocd + 10].copy_from_slice(&3u16.to_le_bytes()); lying[eocd + 10..eocd + 12].copy_from_slice(&3u16.to_le_bytes()); assert_eq!( format_message(&list_zip_entries(&lying).expect_err("the second entry is not there")), "Corrupt central directory at entry 2 of 3." ); } /// The whole-buffer and ranged paths agree on a synthetic archive too, not /// only on the committed fixtures — including a DEFLATED entry built here /// rather than by the system `zip` tool. #[test] fn the_two_paths_agree_on_a_synthetic_archive() { let body = b"POLL:\nWhich day?\nOPTION: Thursday (3 votes)\nOPTION: Friday (1 vote)\n"; let deflated = miniz_oxide::deflate::compress_to_vec(body, 6); let zip = build_zip( &[ ("_chat.txt", &deflated, 8, 0), ( "IMG-00000001-WA0001.jpg", b"\xff\xd8\xff\xe0 synthetic", 0, 0, ), ], None, ); // The builder writes the DEFLATED length as both sizes, which the reader // trusts for its inflate ceiling; the payload is smaller than that, so the // limit is generous either way. let entries = list_zip_entries(&zip).expect("the synthetic archive parses"); let ranged = list_zip_entries_ranged(&CountingReader::new(&zip)).expect("and ranged too"); assert_eq!(entries, ranged); let reader = CountingReader::new(&zip); assert_eq!( read_zip_entry(&zip, &entries[0]).expect("inflates"), body.to_vec() ); assert_eq!( read_zip_entry_ranged(&reader, &entries[0]).expect("inflates"), body.to_vec() ); assert_eq!( read_zip_entry_ranged(&reader, &entries[1]).expect("stored"), b"\xff\xd8\xff\xe0 synthetic".to_vec() ); } // ── isContentEntry ────────────────────────────────────────────────────────── /// Directory entries and macOS resource forks are never content. /// /// The `._` rule is checked on the BASE name, not the whole path, so a resource /// fork inside a folder is still skipped; `__MACOSX/` is checked on the whole /// path, because that folder is only ever at the root. #[test] fn content_entries_exclude_directories_and_macos_forks() { let cases: &[(&str, bool)] = &[ ("_chat.txt", true), ("IMG-20250726-WA0001.jpg", true), ("media/", false), ("media/IMG-20250726-WA0002.jpg", true), ("__MACOSX/._chat.txt", false), ("__MACOSX/", false), ("._chat.txt", false), ("media/._IMG-20250726-WA0002.jpg", false), (".DS_Store", false), ("media/.DS_Store", false), ("media/.DS_Store_backup", true), ("", true), ]; for (name, expected) in cases { let entry = ZipEntry { name: name.to_string(), compressed_size: 0, uncompressed_size: 0, method: 0, flags: 0, local_header_offset: 0, }; assert_eq!( is_content_entry(&entry), *expected, "isContentEntry({name:?})" ); } } /// A zero-length entry is never handed to the reader at all — the TypeScript /// short-circuits it, because asking a phone's file layer for zero bytes is a /// request some of them answer with an error. #[test] fn a_zero_length_entry_is_never_read_from_the_reader() { let zip = build_zip(&[("empty.txt", b"", 0, 0)], None); let entries = list_zip_entries(&zip).expect("the archive parses"); let reader = CountingReader::new(&zip); assert_eq!( read_zip_entry_ranged(&reader, &entries[0]).expect("an empty entry reads"), Vec::::new() ); // Only the 30-byte local header was fetched, twice over: once by the range // resolution, and never again for the payload. assert_eq!(reader.bytes_read(), 30); }