Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

test(autoindex): regression cover both docx zip-bomb guards (#78)

xerj-org3bc188e33993
diff --git a/engine/crates/xerj-autoindex/src/extract/docx.rs b/engine/crates/xerj-autoindex/src/extract/docx.rs
index cef0b370d..f048641bf 100644
--- a/engine/crates/xerj-autoindex/src/extract/docx.rs
+++ b/engine/crates/xerj-autoindex/src/extract/docx.rs
@@ -9,7 +9,32 @@ use quick_xml::Reader;
use std::io::BufReader;
use std::path::Path;
+// SECURITY: bound the DECOMPRESSED read. `word/document.xml` inflates from
+// the zip at whatever ratio the author chose — a ~400 KB docx can expand to
+// hundreds of MB, and a single 400 MB `<w:t>` text run makes quick-xml
+// allocate that whole run for one event (measured 1.68 GB RSS from an 815 KB
+// file). Reading through a `Take` caps peak memory no matter the ratio; a
+// real document's document.xml is far below this. Past the cap the reader
+// hits EOF and the loop ends; quick-xml reports that as `Eof`, not an error,
+// so the paragraphs read so far are emitted and the remainder is dropped
+// silently — truncation is not counted as junk.
+const MAX_DECOMPRESSED_BYTES: u64 = 72 << 20;
+
+/// Extraction body cap (also bounds any single paragraph — see the Text arm).
+const MAX_BODY_BYTES: usize = 64 << 20;
+
pub fn extract(path: &Path, sink: Sink) -> Result<ExtractStats> {
+ extract_bounded(path, sink, MAX_DECOMPRESSED_BYTES, MAX_BODY_BYTES)
+}
+
+/// Both caps are parameters so the truncation boundaries can be exercised with
+/// kilobyte fixtures; production always passes the two constants above.
+fn extract_bounded(
+ path: &Path,
+ sink: Sink,
+ max_decompressed_bytes: u64,
+ max_body_bytes: usize,
+) -> Result<ExtractStats> {
let mut stats = ExtractStats::default();
let f = std::fs::File::open(path)?;
let mut z = zip::ZipArchive::new(f).context("open docx container")?;
@@ -20,20 +45,10 @@ pub fn extract(path: &Path, sink: Sink) -> Result<ExtractStats> {
return Ok(stats);
}
};
- // SECURITY: bound the DECOMPRESSED read. `word/document.xml` inflates from
- // the zip at whatever ratio the author chose — a ~400 KB docx can expand to
- // hundreds of MB, and a single 400 MB `<w:t>` text run makes quick-xml
- // allocate that whole run for one event (measured 1.68 GB RSS from an 815 KB
- // file). Reading through a `Take` caps peak memory no matter the ratio; a
- // real document's document.xml is far below this. Past the cap the reader
- // hits EOF and the loop ends (a truncated tag is handled as junk below).
- const MAX_DECOMPRESSED_BYTES: u64 = 72 << 20;
- let capped = std::io::Read::take(entry, MAX_DECOMPRESSED_BYTES);
+ let capped = std::io::Read::take(entry, max_decompressed_bytes);
let mut reader = Reader::from_reader(BufReader::new(capped));
reader.config_mut().trim_text(false);
- // Extraction body cap (also bounds any single paragraph — see the Text arm).
- const MAX_BODY_BYTES: usize = 64 << 20;
let mut body = String::new();
let mut headings: Vec<String> = Vec::new();
let mut para = String::new();
@@ -67,7 +82,7 @@ pub fn extract(path: &Path, sink: Sink) -> Result<ExtractStats> {
// without bound: measured 1.68 GB RSS from that 815 KB input.
// Stop appending once one paragraph reaches the body cap; the
// per-paragraph text a real document holds is far below it.
- if para.len() < MAX_BODY_BYTES {
+ if para.len() < max_body_bytes {
para.push_str(&t.unescape().unwrap_or_default());
}
}
@@ -93,7 +108,7 @@ pub fn extract(path: &Path, sink: Sink) -> Result<ExtractStats> {
}
}
buf.clear();
- if body.len() > MAX_BODY_BYTES {
+ if body.len() > max_body_bytes {
break;
}
}
@@ -115,3 +130,231 @@ pub fn extract(path: &Path, sink: Sink) -> Result<ExtractStats> {
emit_document(&title, &headings, body, sink, &mut stats);
Ok(stats)
}
+
+#[cfg(test)]
+mod tests {
+ use super::{extract_bounded, ExtractStats};
+ use std::io::Write;
+ use std::path::Path;
+
+ const XML_HEAD: &str = concat!(
+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"#,
+ r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>"#
+ );
+ const XML_TAIL: &str = "</w:body></w:document>";
+
+ /// A docx is a zip; the extractor only ever looks at `word/document.xml`,
+ /// so fixtures name their members explicitly.
+ fn write_container(path: &Path, members: &[(&str, &str)]) {
+ let mut z = zip::ZipWriter::new(std::fs::File::create(path).unwrap());
+ let opts = zip::write::SimpleFileOptions::default()
+ .compression_method(zip::CompressionMethod::Deflated);
+ for (name, content) in members {
+ z.start_file(*name, opts).unwrap();
+ z.write_all(content.as_bytes()).unwrap();
+ }
+ z.finish().unwrap();
+ }
+
+ fn write_docx(path: &Path, document_xml: &str) {
+ write_container(path, &[("word/document.xml", document_xml)]);
+ }
+
+ /// Section bodies in emission order, plus the stats the run reported.
+ fn extract_sections(
+ path: &Path,
+ max_decompressed_bytes: u64,
+ max_body_bytes: usize,
+ ) -> (Vec<String>, ExtractStats) {
+ let mut sections = Vec::new();
+ let stats = extract_bounded(
+ path,
+ &mut |r| {
+ sections.push(r.fields["body"].as_str().unwrap().to_string());
+ true
+ },
+ max_decompressed_bytes,
+ max_body_bytes,
+ )
+ .unwrap();
+ (sections, stats)
+ }
+
+ /// Every paragraph carries a distinct fixed-width marker, so "was this byte
+ /// range read?" is answerable exactly rather than by size heuristics.
+ fn marker(i: usize) -> String {
+ format!("m{i:06}")
+ }
+
+ #[test]
+ fn a_document_inflating_past_the_decompression_cap_is_truncated_at_the_byte_boundary() {
+ const PARAS: usize = 20_000;
+ // Repetitive filler is what gives a docx its inflation ratio; the
+ // per-paragraph marker keeps every paragraph the same width.
+ let para = |i: usize| {
+ format!(
+ "<w:p><w:r><w:t>{} {}</w:t></w:r></w:p>",
+ marker(i),
+ "filler ".repeat(24)
+ )
+ };
+ let xml = format!(
+ "{XML_HEAD}{}{XML_TAIL}",
+ (0..PARAS).map(para).collect::<String>()
+ );
+
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("bomb.docx");
+ write_docx(&path, &xml);
+
+ // The bomb shape: a small file on disk that inflates by orders of
+ // magnitude. Without the cap the whole inflated stream is resident.
+ let on_disk = std::fs::metadata(&path).unwrap().len();
+ assert!(
+ xml.len() as u64 > on_disk * 20,
+ "fixture is not a compression bomb: {} inflated from {on_disk} on disk",
+ xml.len()
+ );
+
+ const CAP: u64 = 16 << 10;
+ let (sections, stats) = extract_sections(&path, CAP, 64 << 20);
+
+ // Paragraphs are fixed width, so the last one wholly inside the cap is
+ // arithmetic: the next one is at best half-read, never closes, and so
+ // can never reach `body`.
+ let last_whole = (CAP as usize - XML_HEAD.len()) / para(0).len();
+ assert!(last_whole > 0 && last_whole < PARAS);
+ assert!(stats.records > 0, "nothing was extracted before the cap");
+ // Cutting the stream mid-tag reads as EOF to quick-xml, so truncation
+ // is silent: the caller sees a clean document, just a shorter one.
+ assert_eq!(stats.junk, 0);
+ for present in [marker(0), marker(last_whole - 1)] {
+ assert!(
+ sections.iter().any(|s| s.contains(&present)),
+ "{present} sits inside the cap but was not extracted"
+ );
+ }
+ for absent in [marker(last_whole), marker(PARAS - 1)] {
+ assert!(
+ sections.iter().all(|s| !s.contains(&absent)),
+ "{absent} sits past the {CAP}-byte cap but was still read"
+ );
+ }
+ let extracted: usize = sections.iter().map(|s| s.len()).sum();
+ assert!(
+ extracted < xml.len() / 100,
+ "extracted {extracted} bytes of a {}-byte stream: it was read whole",
+ xml.len()
+ );
+ }
+
+ #[test]
+ fn a_single_paragraph_stops_absorbing_text_at_the_body_cap() {
+ const CAP: usize = 8 << 10;
+ const RUNS: usize = 4_000;
+ // Fixed-width runs with no whitespace between them: the paragraph
+ // buffer holds exactly `i * run_bytes` before run `i` is considered.
+ let run = |i: usize| format!("<w:r><w:t>{}{}</w:t></w:r>", marker(i), "x".repeat(57));
+ let run_bytes = marker(0).len() + 57;
+ let xml = format!(
+ "{XML_HEAD}<w:p>{}</w:p>{XML_TAIL}",
+ (0..RUNS).map(run).collect::<String>()
+ );
+
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("one-huge-paragraph.docx");
+ write_docx(&path, &xml);
+
+ let (sections, stats) = extract_sections(&path, 64 << 20, CAP);
+ assert!(stats.records > 0);
+
+ // A lone paragraph is only ever cut mid-paragraph, never overlapped, so
+ // the sections concatenate back into exactly what the buffer held.
+ let buffered = sections.concat();
+ assert!(
+ buffered.len() <= CAP + run_bytes,
+ "paragraph buffer reached {} bytes against a {CAP}-byte cap",
+ buffered.len()
+ );
+ let last_accepted = CAP / run_bytes - 1;
+ assert!(buffered.contains(&marker(last_accepted)));
+ assert!(!buffered.contains(&marker(last_accepted + 1)));
+ assert!(!buffered.contains(&marker(RUNS - 1)));
+ }
+
+ #[test]
+ fn a_never_closed_paragraph_ends_extraction_instead_of_growing_without_bound() {
+ // `para` only drains at `</w:p>`, so a paragraph that never closes is
+ // the shape that drove RSS to 1.68 GB. Its buffer is not observable
+ // from outside — what is observable is that the run ends, reports the
+ // unterminated document as junk, and emits nothing.
+ let run = |i: usize| format!("<w:r><w:t>{}{}</w:t></w:r>", marker(i), "x".repeat(57));
+ let xml = format!("{XML_HEAD}<w:p>{}", (0..4_000).map(run).collect::<String>());
+
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("unterminated.docx");
+ write_docx(&path, &xml);
+
+ let (sections, stats) = extract_sections(&path, 64 << 20, 8 << 10);
+ assert!(sections.is_empty());
+ assert_eq!(stats.records, 0);
+ assert_eq!(stats.junk, 1);
+ }
+
+ #[test]
+ fn a_well_formed_document_keeps_its_paragraphs_and_pstyle_headings() {
+ let xml = format!(
+ "{XML_HEAD}\
+ <w:p><w:pPr><w:pStyle w:val=\"Heading1\"/></w:pPr><w:r><w:t>Quarterly Report</w:t></w:r></w:p>\
+ <w:p><w:r><w:t>Subscription revenue</w:t></w:r><w:r><w:t> grew again.</w:t></w:r></w:p>\
+ <w:p><w:pPr><w:pStyle w:val=\"Heading2\"/></w:pPr><w:r><w:t>Outlook</w:t></w:r></w:p>\
+ <w:p><w:r><w:t>Cash flow supports investment.</w:t></w:r></w:p>\
+ {XML_TAIL}"
+ );
+
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("report.docx");
+ write_docx(&path, &xml);
+
+ let mut records = Vec::new();
+ let stats = extract_bounded(
+ &path,
+ &mut |r| {
+ records.push(r);
+ true
+ },
+ super::MAX_DECOMPRESSED_BYTES,
+ super::MAX_BODY_BYTES,
+ )
+ .unwrap();
+
+ assert_eq!(stats.junk, 0);
+ assert_eq!(records.len(), 1);
+ let fields = &records[0].fields;
+ assert_eq!(fields["title"], "Quarterly Report");
+ assert_eq!(
+ fields["headings"],
+ serde_json::json!(["Quarterly Report", "Outlook"])
+ );
+ let body = fields["body"].as_str().unwrap();
+ assert_eq!(
+ body,
+ "Quarterly Report\n\nSubscription revenue grew again.\n\nOutlook\n\nCash flow supports investment."
+ );
+ }
+
+ #[test]
+ fn a_container_without_word_document_xml_is_counted_as_junk_not_an_error() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("not-a-docx.docx");
+ write_container(
+ &path,
+ &[("[Content_Types].xml", "<Types/>"), ("xl/workbook.xml", "")],
+ );
+
+ let (sections, stats) = extract_sections(&path, super::MAX_DECOMPRESSED_BYTES, 64 << 20);
+ assert!(sections.is_empty());
+ assert_eq!(stats.records, 0);
+ assert_eq!(stats.junk, 1);
+ }
+}