Skip to main content

docx_templating/package/
zip_source.rs

1//! ZIP-backed `PackageSource` implementation.
2
3use std::io::Read;
4use std::path::Path;
5
6use zip::ZipArchive;
7
8use crate::Result;
9use crate::package::validation::is_safe_part_name;
10use crate::package::{PackageError, PackageSource};
11
12/// Maximum uncompressed size (in bytes) allowed per ZIP entry.
13///
14/// Entries whose declared uncompressed size exceeds this value are rejected
15/// before decompression begins, preventing decompression-bomb attacks.
16/// Current limit: 100 MiB.
17pub const MAX_ENTRY_BYTES: u64 = 100 * 1024 * 1024;
18
19/// A DOCX package backed by a ZIP archive.
20///
21/// Constructed via [`from_path`], [`from_reader`], or [`from_bytes`].
22/// All three constructors eagerly build the part-name index so that any
23/// malformed archive or unsafe entry is detected immediately (fail-fast).
24///
25/// [`from_path`]: ZipPackageSource::from_path
26/// [`from_reader`]: ZipPackageSource::from_reader
27/// [`from_bytes`]: ZipPackageSource::from_bytes
28pub struct ZipPackageSource {
29    /// Validated, sorted list of safe entry names.
30    part_names: Vec<String>,
31    /// Raw bytes of the archive, kept for re-reading individual parts.
32    data: Vec<u8>,
33}
34
35impl std::fmt::Debug for ZipPackageSource {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        f.debug_struct("ZipPackageSource")
38            .field("part_count", &self.part_names.len())
39            .finish()
40    }
41}
42
43impl ZipPackageSource {
44    /// Open a DOCX file from the file system.
45    ///
46    /// # Errors
47    ///
48    /// Returns an error if the file cannot be read, is not a valid ZIP
49    /// archive, or contains unsafe entry names.
50    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
51        let data = std::fs::read(path)?;
52        Self::from_bytes(data)
53    }
54
55    /// Parse a DOCX package from a `Read + Seek` source.
56    ///
57    /// The entire stream is read into memory so that individual parts can be
58    /// re-read on demand without requiring the caller to keep the reader alive.
59    pub fn from_reader<R: Read>(mut reader: R) -> Result<Self> {
60        let mut data = Vec::new();
61        reader.read_to_end(&mut data)?;
62        Self::from_bytes(data)
63    }
64
65    /// Parse a DOCX package from raw bytes.
66    pub fn from_bytes(data: Vec<u8>) -> Result<Self> {
67        let cursor = std::io::Cursor::new(&data);
68        let mut archive = ZipArchive::new(cursor).map_err(|_| PackageError::MalformedArchive)?;
69
70        let mut part_names = Vec::with_capacity(archive.len());
71        for i in 0..archive.len() {
72            let entry = archive
73                .by_index_raw(i)
74                .map_err(|_| PackageError::MalformedArchive)?;
75
76            let name = entry
77                .name()
78                .map_err(|_| PackageError::MalformedArchive)?
79                .into_owned();
80
81            // Skip directory entries (they end with '/')
82            if name.ends_with('/') {
83                continue;
84            }
85
86            if !is_safe_part_name(&name) {
87                return Err(PackageError::UnsupportedEntry(name).into());
88            }
89
90            part_names.push(name);
91        }
92
93        part_names.sort();
94
95        Ok(Self { part_names, data })
96    }
97}
98
99impl PackageSource for ZipPackageSource {
100    fn part_names(&self) -> Result<Vec<String>> {
101        Ok(self.part_names.clone())
102    }
103
104    fn contains_part(&self, name: &str) -> Result<bool> {
105        Ok(self.part_names.binary_search(&name.to_owned()).is_ok())
106    }
107
108    fn read_part(&self, name: &str) -> Result<Option<Vec<u8>>> {
109        self.read_part_with_limit(name, MAX_ENTRY_BYTES)
110    }
111
112    fn raw_archive_bytes(&self) -> Option<&[u8]> {
113        Some(&self.data)
114    }
115}
116
117impl ZipPackageSource {
118    // Extracted so tests can supply a small limit without allocating 100 MiB.
119    fn read_part_with_limit(&self, name: &str, limit: u64) -> Result<Option<Vec<u8>>> {
120        if self.part_names.binary_search(&name.to_owned()).is_err() {
121            return Ok(None);
122        }
123
124        let cursor = std::io::Cursor::new(&self.data);
125        let mut archive = ZipArchive::new(cursor).map_err(|_| PackageError::MalformedArchive)?;
126
127        let mut entry = archive
128            .by_name(name)
129            .map_err(|_| PackageError::MalformedArchive)?;
130
131        if entry.size() > limit {
132            return Err(PackageError::EntrySizeExceeded {
133                name: name.to_owned(),
134                size: entry.size(),
135                limit,
136            }
137            .into());
138        }
139
140        let mut buf = Vec::with_capacity(entry.size() as usize);
141        entry.read_to_end(&mut buf)?;
142        Ok(Some(buf))
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
149
150    use super::*;
151    use crate::package::writer::PackageWriter;
152    use crate::package::zip_writer::ZipPackageWriter;
153
154    /// Build a minimal valid DOCX in memory and return its bytes.
155    pub fn build_minimal_docx() -> Vec<u8> {
156        let buf = Vec::new();
157        let cursor = std::io::Cursor::new(buf);
158        let mut writer = ZipPackageWriter::new(cursor);
159
160        writer.write_part("[Content_Types].xml", b"<ct/>").unwrap();
161        writer.write_part("_rels/.rels", b"<rels/>").unwrap();
162        writer.write_part("word/document.xml", b"<doc/>").unwrap();
163        writer.write_part("word/styles.xml", b"<styles/>").unwrap();
164
165        let cursor = writer.finish_into_inner().unwrap();
166        cursor.into_inner()
167    }
168
169    #[test]
170    fn from_bytes_lists_parts() {
171        let docx = build_minimal_docx();
172        let src = ZipPackageSource::from_bytes(docx).unwrap();
173        let names = src.part_names().unwrap();
174        assert!(names.contains(&"[Content_Types].xml".to_owned()));
175        assert!(names.contains(&"word/document.xml".to_owned()));
176        assert!(names.contains(&"word/styles.xml".to_owned()));
177    }
178
179    #[test]
180    fn contains_part_true_for_known() {
181        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
182        assert!(src.contains_part("word/document.xml").unwrap());
183        assert!(src.contains_part("[Content_Types].xml").unwrap());
184    }
185
186    #[test]
187    fn contains_part_false_for_unknown() {
188        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
189        assert!(!src.contains_part("word/header1.xml").unwrap());
190    }
191
192    #[test]
193    fn read_part_returns_bytes() {
194        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
195        let bytes = src.read_part("word/document.xml").unwrap().unwrap();
196        assert_eq!(bytes, b"<doc/>");
197    }
198
199    #[test]
200    fn read_part_returns_none_for_unknown() {
201        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
202        assert!(src.read_part("word/missing.xml").unwrap().is_none());
203    }
204
205    #[test]
206    fn part_names_are_sorted() {
207        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
208        let names = src.part_names().unwrap();
209        let mut sorted = names.clone();
210        sorted.sort();
211        assert_eq!(names, sorted);
212    }
213
214    #[test]
215    fn corrupt_bytes_returns_error() {
216        let result = ZipPackageSource::from_bytes(b"not a zip".to_vec());
217        assert!(result.is_err());
218        let msg = result.unwrap_err().to_string();
219        assert!(msg.contains("malformed") || msg.contains("invalid DOCX"));
220    }
221
222    #[test]
223    fn read_part_within_size_limit_succeeds() {
224        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
225        assert!(src.read_part("word/document.xml").unwrap().is_some());
226    }
227
228    #[test]
229    fn read_part_exceeding_limit_returns_error() {
230        // Use a tiny limit (5 bytes) so the test doesn't need to allocate 100 MiB.
231        // word/document.xml contains b"<doc/>" (6 bytes uncompressed) — exceeds 5.
232        let src = ZipPackageSource::from_bytes(build_minimal_docx()).unwrap();
233        let err = src
234            .read_part_with_limit("word/document.xml", 5)
235            .unwrap_err();
236        let msg = err.to_string();
237        assert!(
238            msg.contains("word/document.xml"),
239            "error should name the entry: {msg}"
240        );
241        assert!(
242            msg.contains("limit") || msg.contains("bytes"),
243            "error should describe the size violation: {msg}"
244        );
245    }
246}