Tests: cover the limits and package errors of placing Word documents

Placing a .docx or .doc file had guards that no test reached, so removing
or loosening any of them left every test passing:

- malformed_docx_fails_cleanly now checks the messages for a package with
  no end record, an encrypted part, an unknown compression method and
  ZIP64 end-record values, and that 100,002 empty paragraphs fail with
  "too much text or formatting".
- docx_parts_in_utf16_with_a_byte_order_mark_place_their_text places a
  main part in UTF-16LE and UTF-16BE after a byte-order mark.
- docx_based_on_chains_stop_at_a_cycle_and_after_32_styles places a
  paragraph in a style whose basedOn chain loops, and chains of 32 and 33
  styles where only the last style sets a size.
- docx_run_containers_and_table_rows_nested_past_the_depth_read_are_left_out
  nests runs in smart tags and table rows in content controls 70 and 60
  levels deep.
- malformed_doc_fails_cleanly refuses a .doc WordDocument stream whose
  directory entry gives 64 MB plus one byte.

Each new check fails with the guard it covers broken.
This commit is contained in:
dotCooCoo committed 2026-12-02 21:14:29 -08:00
1 parent 15cc3b048f
commit 7a066e53b8
1 file changed
+88
+88
View File
@@ -489,6 +489,9 @@ fn malformed_docx_fails_cleanly() {
let store = |files: &[(&str, &[u8])]| cmd::fileio::zip::store(files).unwrap();
let document = |body: &str| format!(r#"<w:document xmlns:w="{W_NS}"><w:body>{body}</w:body></w:document>"#);
assert!(place(&mut s, "a.docx", b"Plain words, not a package").is_err(), "a .docx file that isn't a ZIP archive");
// A .docx file that starts with a local file header and has no end record.
let e = place(&mut s, "a.docx", b"PK\x03\x04 and nothing after the first header").unwrap_err();
assert!(e.contains("isn't a ZIP package"), "{e}");
let e = place(&mut s, "a.docx", &store(&[("readme.txt", b"x")])).unwrap_err();
assert!(e.contains("no main document part"), "{e}");
let e = place(&mut s, "a.zip", &store(&[("readme.txt", b"x")])).unwrap_err();
@@ -531,6 +534,29 @@ fn malformed_docx_fails_cleanly() {
longer[central + 20..central + 24].copy_from_slice(&packed.to_le_bytes());
let e = place(&mut s, "a.docx", &longer).unwrap_err();
assert!(e.contains("damaged"), "{e}");
// A file whose directory record sets the encryption flag (bit 0) or names a compression method other than stored
// or deflated, and an end record with the values that mean a ZIP64 record holds the real ones.
let words = || store(&[("word/document.xml", document("<w:p><w:r><w:t>words</w:t></w:r></w:p>").as_bytes())]);
let record = |zip: &[u8]| zip.windows(4).position(|w| w == 0x0201_4b50u32.to_le_bytes()).unwrap();
let mut encrypted = words();
let at = record(&encrypted);
encrypted[at + 8] |= 1;
let e = place(&mut s, "a.docx", &encrypted).unwrap_err();
assert!(e.contains("`word/document.xml` in the Word document is encrypted"), "{e}");
let mut method = words();
let at = record(&method);
method[at + 10..at + 12].copy_from_slice(&99u16.to_le_bytes());
let e = place(&mut s, "a.docx", &method).unwrap_err();
assert!(e.contains("uses compression method 99"), "{e}");
let mut zip64 = words();
let end = zip64.len() - 22;
zip64[end + 10..end + 12].copy_from_slice(&0xFFFFu16.to_le_bytes());
let e = place(&mut s, "a.docx", &zip64).unwrap_err();
assert!(e.contains("uses ZIP64 records"), "{e}");
// One paragraph more than placed type takes: a paragraph is written when the next one starts, so 100,002
// paragraphs write 100,001.
let e = place(&mut s, "a.docx", &store(&[("word/document.xml", document(&"<w:p/>".repeat(100_002)).as_bytes())])).unwrap_err();
assert!(e.contains("too much text or formatting"), "{e}");
// Containers nested past the depth read are skipped, and a part nested deeper still is refused.
let nested = |n: usize| {
let deep = format!("{}<w:p><w:r><w:t>deep</w:t></w:r></w:p>{}", "<w:sdt><w:sdtContent>".repeat(n), "</w:sdtContent></w:sdt>".repeat(n));
@@ -549,6 +575,60 @@ fn malformed_docx_fails_cleanly() {
assert_eq!(s.doc().unwrap().history.undo.len(), 2, "failed places leave no undo step");
}
#[test]
fn docx_parts_in_utf16_with_a_byte_order_mark_place_their_text() {
let mut s = session();
let xml = format!(r#"<w:document xmlns:w="{W_NS}"><w:body><w:p><w:r><w:t>Grüße 東京</w:t></w:r></w:p></w:body></w:document>"#);
for (bom, le) in [([0xFF, 0xFE], true), ([0xFE, 0xFF], false)] {
let part = [&bom[..], &utf16(&xml, le)].concat();
let zip = cmd::fileio::zip::store(&[("word/document.xml", &part[..])]).unwrap();
let r = s.execute("file.place", &json!({"name": "a.docx", "dataBase64": vectorcraft_format::base64_encode(&zip)})).unwrap();
assert_eq!(placed(&s, &r).0, "Grüße 東京", "little-endian: {le}");
}
}
/// A style's `w:basedOn` chain stops at a style already in it, and takes in at most 32 styles.
#[test]
fn docx_based_on_chains_stop_at_a_cycle_and_after_32_styles() {
let mut styles = String::from(concat!(
r#"<w:style w:type="paragraph" w:styleId="A"><w:basedOn w:val="B"/><w:pPr><w:jc w:val="center"/></w:pPr></w:style>"#,
r#"<w:style w:type="paragraph" w:styleId="B"><w:basedOn w:val="A"/><w:rPr><w:sz w:val="40"/></w:rPr></w:style>"#,
));
// S0 is based on S1, S1 on S2, and so on to S32, the only one that sets a size.
for i in 0..32 {
styles += &format!(r#"<w:style w:type="paragraph" w:styleId="S{i}"><w:basedOn w:val="S{}"/></w:style>"#, i + 1);
}
styles += r#"<w:style w:type="paragraph" w:styleId="S32"><w:rPr><w:sz w:val="40"/></w:rPr></w:style>"#;
let para = |style: &str, text: &str| format!(r#"<w:p><w:pPr><w:pStyle w:val="{style}"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#);
let body = [para("A", "cycle"), para("S1", "thirty-two"), para("S0", "thirty-three"), "<w:p><w:r><w:t>plain</w:t></w:r></w:p>".into()].concat();
let mut s = session();
let r = s.execute("file.place", &json!({"name": "styles.docx", "dataBase64": vectorcraft_format::base64_encode(&docx(&body, &styles))})).unwrap();
let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone();
let NodeKind::Text(t) = &n.kind else { panic!("not type") };
let size = |word: &str| t.runs.iter().find(|r| r.text.contains(word)).map(|r| r.style.size);
assert_eq!(t.paragraph_styles()[0].justify, vectorcraft_doc::Justify::Center, "A takes its own alignment");
assert_eq!(size("cycle"), Some(20.0), "A takes the size of B, which is based on A");
assert_eq!(size("thirty-two"), Some(20.0), "a chain of 32 styles takes in the last one");
assert_ne!(size("thirty-three"), Some(20.0), "a chain of 33 styles leaves the last one out");
assert_eq!(size("thirty-three"), size("plain"));
}
/// Run containers and table rows nested more than 64 deep are left out; ones nested 60 deep are placed.
#[test]
fn docx_run_containers_and_table_rows_nested_past_the_depth_read_are_left_out() {
let wrap = |n: usize, open: &str, close: &str, inner: &str| format!("{}{inner}{}", open.repeat(n), close.repeat(n));
let run = |text: &str| format!("<w:r><w:t>{text}</w:t></w:r>");
let tagged = |n: usize, text: &str| wrap(n, "<w:smartTag>", "</w:smartTag>", &run(text));
let row = |n: usize, text: &str| {
let tr = format!("<w:tr><w:tc><w:p>{}</w:p></w:tc></w:tr>", run(text));
format!("<w:tbl>{}</w:tbl>", wrap(n, "<w:sdt><w:sdtContent>", "</w:sdtContent></w:sdt>", &tr))
};
let body = format!("<w:p>{}{}{}</w:p>{}{}", tagged(70, "deep "), tagged(60, "kept "), run("shallow"), row(70, "deep row"), row(60, "kept row"));
let mut s = session();
let r = s.execute("file.place", &json!({"name": "nested.docx", "dataBase64": vectorcraft_format::base64_encode(&docx(&body, ""))})).unwrap();
assert_eq!(placed(&s, &r).0, "kept shallow\nkept row");
}
/// The bytes of the Prls `prls`: each sprm and its operand.
fn prls(prls: &[(u16, &[u8])]) -> Vec<u8> {
prls.iter().flat_map(|(sprm, op)| sprm.to_le_bytes().into_iter().chain(op.iter().copied())).collect()
@@ -927,6 +1007,14 @@ fn malformed_doc_fails_cleanly() {
assert!(e.contains("compound file structure is damaged"), "{e}");
let e = place(&mut s, "a.doc", &compound_file(&[("WordDocument", &[0; 900])])).unwrap_err();
assert!(e.contains("doesn't start with a file information block"), "{e}");
// A WordDocument stream whose directory entry gives one byte more than 64 MB is refused from that length, before
// any of it is read. The stream length is at byte 120 of the entry, which starts with the stream's name.
let mut large = compound_file(&[("WordDocument", &[0; 4096])]);
let name = utf16("WordDocument", true);
let entry = large.windows(name.len()).position(|w| w == name).unwrap();
large[entry + 120..entry + 128].copy_from_slice(&((64u64 << 20) + 1).to_le_bytes());
let e = place(&mut s, "a.doc", &large).unwrap_err();
assert!(e.contains("too large to place (its WordDocument stream holds more than 64 MB)"), "{e}");
let e = place(&mut s, "a.doc", &Word97 { nfib: 0x0065, ..words() }.build()).unwrap_err();
assert!(e.contains("Word 6.0 or Word 95"), "{e}");
let e = place(&mut s, "a.doc", &Word97 { flags: 0x0100, ..words() }.build()).unwrap_err();