docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! ZIP-backed `PackageSource` implementation.

use std::io::Read;
use std::path::Path;

use zip::ZipArchive;

use crate::Result;
use crate::package::validation::is_safe_part_name;
use crate::package::{PackageError, PackageSource};

/// Maximum uncompressed size (in bytes) allowed per ZIP entry.
///
/// Entries whose declared uncompressed size exceeds this value are rejected
/// before decompression begins, preventing decompression-bomb attacks.
/// Current limit: 100 MiB.
pub const MAX_ENTRY_BYTES: u64 = 100 * 1024 * 1024;

/// A DOCX package backed by a ZIP archive.
///
/// Constructed via [`from_path`], [`from_reader`], or [`from_bytes`].
/// All three constructors eagerly build the part-name index so that any
/// malformed archive or unsafe entry is detected immediately (fail-fast).
///
/// [`from_path`]: ZipPackageSource::from_path
/// [`from_reader`]: ZipPackageSource::from_reader
/// [`from_bytes`]: ZipPackageSource::from_bytes
pub struct ZipPackageSource {
    /// Validated, sorted list of safe entry names.
    part_names: Vec<String>,
    /// Raw bytes of the archive, kept for re-reading individual parts.
    data: Vec<u8>,
}

impl std::fmt::Debug for ZipPackageSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ZipPackageSource")
            .field("part_count", &self.part_names.len())
            .finish()
    }
}

impl ZipPackageSource {
    /// Open a DOCX file from the file system.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read, is not a valid ZIP
    /// archive, or contains unsafe entry names.
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
        let data = std::fs::read(path)?;
        Self::from_bytes(data)
    }

    /// Parse a DOCX package from a `Read + Seek` source.
    ///
    /// The entire stream is read into memory so that individual parts can be
    /// re-read on demand without requiring the caller to keep the reader alive.
    pub fn from_reader<R: Read>(mut reader: R) -> Result<Self> {
        let mut data = Vec::new();
        reader.read_to_end(&mut data)?;
        Self::from_bytes(data)
    }

    /// Parse a DOCX package from raw bytes.
    pub fn from_bytes(data: Vec<u8>) -> Result<Self> {
        let cursor = std::io::Cursor::new(&data);
        let mut archive = ZipArchive::new(cursor).map_err(|_| PackageError::MalformedArchive)?;

        let mut part_names = Vec::with_capacity(archive.len());
        for i in 0..archive.len() {
            let entry = archive
                .by_index_raw(i)
                .map_err(|_| PackageError::MalformedArchive)?;

            let name = entry
                .name()
                .map_err(|_| PackageError::MalformedArchive)?
                .into_owned();

            // Skip directory entries (they end with '/')
            if name.ends_with('/') {
                continue;
            }

            if !is_safe_part_name(&name) {
                return Err(PackageError::UnsupportedEntry(name).into());
            }

            part_names.push(name);
        }

        part_names.sort();

        Ok(Self { part_names, data })
    }
}

impl PackageSource for ZipPackageSource {
    fn part_names(&self) -> Result<Vec<String>> {
        Ok(self.part_names.clone())
    }

    fn contains_part(&self, name: &str) -> Result<bool> {
        Ok(self.part_names.binary_search(&name.to_owned()).is_ok())
    }

    fn read_part(&self, name: &str) -> Result<Option<Vec<u8>>> {
        self.read_part_with_limit(name, MAX_ENTRY_BYTES)
    }

    fn raw_archive_bytes(&self) -> Option<&[u8]> {
        Some(&self.data)
    }
}

impl ZipPackageSource {
    // Extracted so tests can supply a small limit without allocating 100 MiB.
    fn read_part_with_limit(&self, name: &str, limit: u64) -> Result<Option<Vec<u8>>> {
        if self.part_names.binary_search(&name.to_owned()).is_err() {
            return Ok(None);
        }

        let cursor = std::io::Cursor::new(&self.data);
        let mut archive = ZipArchive::new(cursor).map_err(|_| PackageError::MalformedArchive)?;

        let mut entry = archive
            .by_name(name)
            .map_err(|_| PackageError::MalformedArchive)?;

        if entry.size() > limit {
            return Err(PackageError::EntrySizeExceeded {
                name: name.to_owned(),
                size: entry.size(),
                limit,
            }
            .into());
        }

        let mut buf = Vec::with_capacity(entry.size() as usize);
        entry.read_to_end(&mut buf)?;
        Ok(Some(buf))
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

    use super::*;
    use crate::package::writer::PackageWriter;
    use crate::package::zip_writer::ZipPackageWriter;

    /// Build a minimal valid DOCX in memory and return its bytes.
    pub fn build_minimal_docx() -> Vec<u8> {
        let buf = Vec::new();
        let cursor = std::io::Cursor::new(buf);
        let mut writer = ZipPackageWriter::new(cursor);

        writer.write_part("[Content_Types].xml", b"<ct/>").unwrap();
        writer.write_part("_rels/.rels", b"<rels/>").unwrap();
        writer.write_part("word/document.xml", b"<doc/>").unwrap();
        writer.write_part("word/styles.xml", b"<styles/>").unwrap();

        let cursor = writer.finish_into_inner().unwrap();
        cursor.into_inner()
    }

    #[test]
    fn from_bytes_lists_parts() {
        let docx = build_minimal_docx();
        let src = ZipPackageSource::from_bytes(docx).unwrap();
        let names = src.part_names().unwrap();
        assert!(names.contains(&"[Content_Types].xml".to_owned()));
        assert!(names.contains(&"word/document.xml".to_owned()));
        assert!(names.contains(&"word/styles.xml".to_owned()));
    }

    #[test]
    fn contains_part_true_for_known() {
        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
        assert!(src.contains_part("word/document.xml").unwrap());
        assert!(src.contains_part("[Content_Types].xml").unwrap());
    }

    #[test]
    fn contains_part_false_for_unknown() {
        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
        assert!(!src.contains_part("word/header1.xml").unwrap());
    }

    #[test]
    fn read_part_returns_bytes() {
        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
        let bytes = src.read_part("word/document.xml").unwrap().unwrap();
        assert_eq!(bytes, b"<doc/>");
    }

    #[test]
    fn read_part_returns_none_for_unknown() {
        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
        assert!(src.read_part("word/missing.xml").unwrap().is_none());
    }

    #[test]
    fn part_names_are_sorted() {
        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
        let names = src.part_names().unwrap();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted);
    }

    #[test]
    fn corrupt_bytes_returns_error() {
        let result = ZipPackageSource::from_bytes(b"not a zip".to_vec());
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("malformed") || msg.contains("invalid DOCX"));
    }

    #[test]
    fn read_part_within_size_limit_succeeds() {
        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
        assert!(src.read_part("word/document.xml").unwrap().is_some());
    }

    #[test]
    fn read_part_exceeding_limit_returns_error() {
        // Use a tiny limit (5 bytes) so the test doesn't need to allocate 100 MiB.
        // word/document.xml contains b"<doc/>" (6 bytes uncompressed) — exceeds 5.
        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
        let err = src
            .read_part_with_limit("word/document.xml", 5)
            .unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("word/document.xml"),
            "error should name the entry: {msg}"
        );
        assert!(
            msg.contains("limit") || msg.contains("bytes"),
            "error should describe the size violation: {msg}"
        );
    }
}