f-office-opc 0.3.0

Open Packaging Conventions container: ZIP package and relationships, with input limits.
Documentation
//! Tests of the package writer, on packages of the ZIP crate's writer and on ZIP files made by
//! hand with what a copy of the bytes must keep: a data descriptor, extra fields that differ
//! between the local header and the central record, a name in UTF-8, external attributes,
//! comments and bytes between the entries.

use std::io::Cursor;

use super::{LayoutFault, PartChange, WriteError, write_package};
use crate::{Limits, Package, testing};

/// An entry of a ZIP file made by hand, stored as it is.
#[derive(Clone, Copy)]
struct Raw<'a> {
    name: &'a str,
    data: &'a [u8],
    /// The flag that the name is in UTF-8.
    utf8: bool,
    /// The CRC and the sizes follow the data, after the signature of a data descriptor.
    descriptor: bool,
    local_extra: &'a [u8],
    central_extra: &'a [u8],
    comment: &'a [u8],
    external: u32,
}

const PLAIN: Raw<'static> = Raw {
    name: "",
    data: b"",
    utf8: false,
    descriptor: false,
    local_extra: b"",
    central_extra: b"",
    comment: b"",
    external: 0,
};

/// The DOS time and date of each entry made by hand: 2024-05-06 07:08:10.
const TIME: u16 = (7 << 11) | (8 << 5) | 5;
const DATE: u16 = ((2024 - 1980) << 9) | (5 << 5) | 6;

fn push16(out: &mut Vec<u8>, values: &[u16]) {
    for value in values {
        out.extend_from_slice(&value.to_le_bytes());
    }
}

fn push32(out: &mut Vec<u8>, values: &[u32]) {
    for value in values {
        out.extend_from_slice(&value.to_le_bytes());
    }
}

fn length(bytes: &[u8]) -> u16 {
    u16::try_from(bytes.len()).unwrap()
}

fn crc32(data: &[u8]) -> u32 {
    let mut crc = flate2::Crc::new();
    crc.update(data);
    crc.sum()
}

/// A ZIP file of `entries`, each followed by `gap`, with the comment `comment`, as a writer
/// other than the ZIP crate's may write it: version made by 3.0 on Unix.
fn raw_zip(entries: &[Raw<'_>], gap: &[u8], comment: &[u8]) -> Vec<u8> {
    let (mut out, mut central) = (Vec::new(), Vec::new());
    for entry in entries {
        let offset = u32::try_from(out.len()).unwrap();
        let (crc, size) = (crc32(entry.data), u32::try_from(entry.data.len()).unwrap());
        let flags = u16::from(entry.utf8) << 11 | u16::from(entry.descriptor) << 3;
        let (local_crc, local_size) = if entry.descriptor {
            (0, 0)
        } else {
            (crc, size)
        };
        push32(&mut out, &[0x0403_4b50]);
        push16(&mut out, &[10, flags, 0, TIME, DATE]);
        push32(&mut out, &[local_crc, local_size, local_size]);
        push16(
            &mut out,
            &[length(entry.name.as_bytes()), length(entry.local_extra)],
        );
        out.extend_from_slice(entry.name.as_bytes());
        out.extend_from_slice(entry.local_extra);
        out.extend_from_slice(entry.data);
        if entry.descriptor {
            push32(&mut out, &[0x0807_4b50, crc, size, size]);
        }
        out.extend_from_slice(gap);
        push32(&mut central, &[0x0201_4b50]);
        push16(&mut central, &[0x031E, 10, flags, 0, TIME, DATE]);
        push32(&mut central, &[crc, size, size]);
        let lengths = [
            entry.name.len(),
            entry.central_extra.len(),
            entry.comment.len(),
        ];
        push16(&mut central, &lengths.map(|n| u16::try_from(n).unwrap()));
        push16(&mut central, &[0, 0]);
        push32(&mut central, &[entry.external, offset]);
        central.extend_from_slice(entry.name.as_bytes());
        central.extend_from_slice(entry.central_extra);
        central.extend_from_slice(entry.comment);
    }
    let (start, size) = (out.len(), central.len());
    out.extend_from_slice(&central);
    push32(&mut out, &[0x0605_4b50]);
    let count = u16::try_from(entries.len()).unwrap();
    push16(&mut out, &[0, 0, count, count]);
    push32(
        &mut out,
        &[u32::try_from(size).unwrap(), u32::try_from(start).unwrap()],
    );
    push16(&mut out, &[length(comment)]);
    out.extend_from_slice(comment);
    out
}

/// A package made by hand: a part with a data descriptor and extra fields, a part with a name
/// in UTF-8 and external attributes, and a third part; a gap after each entry and a comment.
fn hand_made() -> Vec<u8> {
    raw_zip(
        &[
            Raw {
                name: "[Content_Types].xml",
                data: b"<Types/>",
                descriptor: true,
                local_extra: &[0xFE, 0xCA, 2, 0, 1, 2],
                central_extra: &[0xFE, 0xCA, 0, 0],
                comment: b"types",
                ..PLAIN
            },
            Raw {
                name: "word/m\u{e9}dia.xml",
                data: b"<media/>",
                utf8: true,
                external: 0o100_644 << 16,
                ..PLAIN
            },
            Raw {
                name: "word/document.xml",
                data: b"<document/>",
                ..PLAIN
            },
        ],
        b"gap",
        b"package comment",
    )
}

/// The bytes of the first entry of [`hand_made`]: its local header, name, extra field, data and
/// data descriptor.
const FIRST_ENTRY: usize = 30 + "[Content_Types].xml".len() + 6 + b"<Types/>".len() + 16;

/// The parts of a package, by name, as the reader reads them.
fn parts(bytes: &[u8]) -> Vec<(String, Vec<u8>)> {
    let package = Package::open(bytes, &Limits::default()).unwrap();
    package
        .part_names()
        .map(|name| (name.to_owned(), package.part(name).unwrap().to_vec()))
        .collect()
}

/// Whether `needle` occurs in `haystack`.
fn holds(haystack: &[u8], needle: &[u8]) -> bool {
    haystack
        .windows(needle.len())
        .any(|window| window == needle)
}

#[test]
fn keeps_every_byte_of_a_package_with_no_change() {
    let written = testing::zip([
        ("[Content_Types].xml".to_owned(), b"<Types/>".to_vec()),
        ("word/document.xml".to_owned(), b"<w:document/>".repeat(100)),
    ])
    .unwrap();
    for original in [written, hand_made()] {
        let saved = write_package(&original, &[], &Limits::default()).unwrap();
        assert_eq!(saved, original);
    }
}

#[test]
fn the_zip_writer_does_not_keep_the_bytes() {
    // A copy of each entry with the ZIP crate's raw copy gives the same parts in other bytes,
    // so the package writer splices the original's bytes itself.
    let original = hand_made();
    let mut archive = zip::ZipArchive::new(Cursor::new(&original)).unwrap();
    let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
    for index in 0..archive.len() {
        writer
            .raw_copy_file(archive.by_index_raw(index).unwrap())
            .unwrap();
    }
    let copied = writer.finish().unwrap().into_inner();
    assert_eq!(parts(&copied), parts(&original));
    assert_ne!(copied, original);
    // Not even the first entry's local header, data and data descriptor stay as they were.
    let first_entry = original.get(..FIRST_ENTRY).unwrap();
    assert!(holds(&original, first_entry));
    assert!(!holds(&copied, first_entry));
}

/// The package made by hand and the package with its part in UTF-8 replaced. The name compares
/// as a part name: its ASCII letters in any case; the other letter does not change its case.
fn replaced_media() -> (Vec<u8>, Vec<u8>) {
    let original = hand_made();
    let changes = [PartChange::Replace {
        name: "/WORD/m\u{e9}dia.XML",
        data: b"<media changed='yes'/>",
    }];
    let saved = write_package(&original, &changes, &Limits::default()).unwrap();
    (original, saved)
}

#[test]
fn replaces_a_part_and_keeps_the_bytes_of_the_others() {
    let (original, saved) = replaced_media();
    let read = parts(&saved);
    let names: Vec<&str> = read.iter().map(|(name, _)| name.as_str()).collect();
    assert_eq!(
        names,
        [
            "[Content_Types].xml",
            "word/document.xml",
            "word/m\u{e9}dia.xml"
        ]
    );
    assert_eq!(read[2].1, b"<media changed='yes'/>");
    assert_eq!(read[..2], parts(&original)[..2]);
    // The first entry, with its data descriptor, and the gap after it stay as they were.
    let kept = FIRST_ENTRY + b"gap".len();
    assert_eq!(saved.get(..kept), original.get(..kept));
    assert!(holds(&saved, b"package comment"));
    assert!(holds(&saved, b"types"));
}

#[test]
fn keeps_the_name_time_and_attributes_of_a_replaced_entry() {
    let (_, saved) = replaced_media();
    let mut archive = zip::ZipArchive::new(Cursor::new(&saved)).unwrap();
    let entry = archive.by_index_raw(1).unwrap();
    assert_eq!(entry.name_raw(), "word/m\u{e9}dia.xml".as_bytes());
    assert_eq!(entry.external_attributes(), 0o100_644 << 16);
    let modified = entry.last_modified().unwrap();
    let date = (modified.year(), modified.month(), modified.day());
    let time = (modified.hour(), modified.minute(), modified.second());
    assert_eq!((date, time), ((2024, 5, 6), (7, 8, 10)));
    assert_eq!(entry.compression(), zip::CompressionMethod::Stored);
    // Its local header has no data descriptor flag, and only the flag that its name is in UTF-8.
    let flags = usize::try_from(entry.header_start()).unwrap() + 6;
    let utf8_only = (1_u16 << 11).to_le_bytes();
    assert_eq!(saved.get(flags..flags + 2), Some(&utf8_only[..]));
}

#[test]
fn deflates_a_replaced_part_that_was_deflated() {
    let original = testing::zip([("word/document.xml".to_owned(), b"<w:p/>".repeat(50))]).unwrap();
    let data = b"<w:p>text</w:p>".repeat(200);
    let changes = [PartChange::Replace {
        name: "word/document.xml",
        data: &data,
    }];
    let saved = write_package(&original, &changes, &Limits::default()).unwrap();
    assert_eq!(
        parts(&saved),
        [("word/document.xml".to_owned(), data.clone())]
    );
    let mut archive = zip::ZipArchive::new(Cursor::new(&saved)).unwrap();
    let entry = archive.by_index_raw(0).unwrap();
    assert_eq!(entry.compression(), zip::CompressionMethod::Deflated);
    assert!(entry.compressed_size() < 200, "{}", entry.compressed_size());
}

#[test]
fn adds_a_part_after_the_last_entry_and_changes_no_other() {
    let original = hand_made();
    let changes = [PartChange::Add {
        name: "/word/added.xml",
        data: b"<added/>",
    }];
    let saved = write_package(&original, &changes, &Limits::default()).unwrap();
    let before = parts(&original);
    let after = parts(&saved);
    assert_eq!(after.len(), before.len() + 1);
    assert!(after.contains(&("word/added.xml".to_owned(), b"<added/>".to_vec())));
    assert!(before.iter().all(|part| after.contains(part)));
    // Every local entry of the original, and the bytes after the last one, stay in place.
    let central = original.len() - (22 + 15) - central_size(&original);
    assert_eq!(saved.get(..central), original.get(..central));
    let mut archive = zip::ZipArchive::new(Cursor::new(&saved)).unwrap();
    let added = archive.by_name("word/added.xml").unwrap();
    let date = added.last_modified().unwrap();
    assert_eq!((date.year(), date.month(), date.day()), (1980, 1, 1));
}

/// The size of the central directory of a ZIP file without ZIP64 and with a comment of 15
/// bytes.
fn central_size(bytes: &[u8]) -> usize {
    let end = bytes.len() - 22 - 15;
    let size = bytes.get(end + 12..end + 16).unwrap();
    usize::try_from(u32::from_le_bytes(size.try_into().unwrap())).unwrap()
}

#[test]
fn refuses_changes_that_do_not_fit_the_package() {
    let original = hand_made();
    let limits = Limits::default();
    let write = |changes: &[PartChange<'_>]| write_package(&original, changes, &limits);
    let replace = |name| PartChange::Replace { name, data: b"x" };
    let add = |name| PartChange::Add { name, data: b"x" };
    assert_eq!(
        write(&[replace("word/missing.xml")]),
        Err(WriteError::NoSuchPart("word/missing.xml".to_owned()))
    );
    assert_eq!(
        write(&[add("/WORD/Document.xml")]),
        Err(WriteError::PartExists("/WORD/Document.xml".to_owned()))
    );
    assert_eq!(
        write(&[replace("word/document.xml"), replace("/Word/Document.XML")]),
        Err(WriteError::ChangedTwice("/Word/Document.XML".to_owned()))
    );
    assert_eq!(
        write(&[add("word/new.xml"), add("word/NEW.xml")]),
        Err(WriteError::ChangedTwice("word/NEW.xml".to_owned()))
    );
    let small = Limits {
        max_written_size: 100,
        ..Limits::default()
    };
    assert_eq!(
        write_package(&original, &[], &small),
        Err(WriteError::TooLarge)
    );
}

#[test]
fn refuses_a_package_that_it_does_not_read() {
    let limits = Limits::default();
    let write = |bytes: &[u8]| write_package(bytes, &[], &limits).map(|_| ());
    assert_eq!(
        write(b"not a ZIP file at all"),
        Err(WriteError::Layout(LayoutFault::NoEndRecord))
    );
    let original = hand_made();
    let mut moved = original.clone();
    // The end record names a central directory one byte later than it is.
    let end = moved.len() - 22 - 15;
    moved[end + 16] += 1;
    assert_eq!(
        write(&moved),
        Err(WriteError::Layout(LayoutFault::CentralDirectory))
    );
    let mut wide = zip::ZipWriter::new(Cursor::new(Vec::new()));
    let options = zip::write::SimpleFileOptions::default().large_file(true);
    wide.start_file("word/document.xml", options).unwrap();
    let wide = wide.finish().unwrap().into_inner();
    assert_eq!(write(&wide), Err(WriteError::Zip64));
}

#[test]
fn replaces_the_first_of_two_entries_with_equivalent_names() {
    let original = raw_zip(
        &[
            Raw {
                name: "word/document.xml",
                data: b"<first/>",
                ..PLAIN
            },
            Raw {
                name: "WORD/document.xml",
                data: b"<second/>",
                ..PLAIN
            },
        ],
        b"",
        b"",
    );
    let changes = [PartChange::Replace {
        name: "word/document.xml",
        data: b"<new/>",
    }];
    let saved = write_package(&original, &changes, &Limits::default()).unwrap();
    let package = Package::open(&saved, &Limits::default()).unwrap();
    assert_eq!(package.part("word/document.xml"), Some(&b"<new/>"[..]));
    assert!(holds(&saved, b"<second/>"));
}