diff --git a/Cargo.lock b/Cargo.lock
index cf0e0bd47..c60c92eeb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1710,6 +1710,7 @@ version = "0.1.0"
dependencies = [
"craft-xml",
"proptest",
+ "roxmltree 0.21.2",
"serde",
"serde_json",
]
diff --git a/crates/docx/src/flat.rs b/crates/docx/src/flat.rs
index c257932cf..7c91f5516 100644
--- a/crates/docx/src/flat.rs
+++ b/crates/docx/src/flat.rs
@@ -448,7 +448,13 @@ fn one_element(s: &str) -> bool {
r.config_mut().check_comments = true;
let (mut depth, mut roots) = (0usize, 0usize);
loop {
- let attrs_ok = |e: &BytesStart| e.attributes().all(|a| a.is_ok());
+ // Each attribute parses and its value unescapes: an undeclared entity (`x="&no;"`) isn't
+ // well-formed, and the reader would keep it raw (#6072).
+ // Names must be XML names too: the reader takes `` and `x?="1"` without complaint.
+ let attrs_ok = |e: &BytesStart| {
+ is_qname(e.name().as_ref())
+ && e.attributes().all(|a| a.is_ok_and(|a| is_qname(a.key.as_ref()) && a.normalized_value(quick_xml::XmlVersion::Explicit1_0).is_ok()))
+ };
match r.read_event() {
Ok(Event::Start(e)) => {
if !attrs_ok(&e) || (depth == 0 && roots > 0) {
@@ -480,6 +486,28 @@ fn one_element(s: &str) -> bool {
}
}
+/// Whether `name` is an XML name with at most one colon, neither first nor last: a qualified name
+/// in Namespaces in XML 1.0 (§4), with the name characters of XML 1.0 (Fifth Edition) §2.3.
+fn is_qname(name: &[u8]) -> bool {
+ fn start(c: char) -> bool {
+ matches!(c, 'A'..='Z' | '_' | 'a'..='z' | '\u{C0}'..='\u{D6}' | '\u{D8}'..='\u{F6}' | '\u{F8}'..='\u{2FF}' | '\u{370}'..='\u{37D}'
+ | '\u{37F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}' | '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}'
+ | '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{EFFFF}')
+ }
+ fn more(c: char) -> bool {
+ start(c) || matches!(c, '-' | '.' | '0'..='9' | '\u{B7}' | '\u{300}'..='\u{36F}' | '\u{203F}'..='\u{2040}')
+ }
+ let ncname = |p: &str| {
+ let mut cs = p.chars();
+ cs.next().is_some_and(start) && cs.all(more)
+ };
+ let Ok(name) = std::str::from_utf8(name) else { return false };
+ match name.split_once(':') {
+ Some((prefix, local)) => ncname(prefix) && ncname(local),
+ None => ncname(name),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -587,6 +615,12 @@ mod tests {
"",
"",
"",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
] {
assert!(xml_fragment(ct, bad.as_bytes()).is_none(), "{bad}");
}
diff --git a/crates/docx/tests/it/kept_omml_check.rs b/crates/docx/tests/it/kept_omml_check.rs
new file mode 100644
index 000000000..e382cdb1b
--- /dev/null
+++ b/crates/docx/tests/it/kept_omml_check.rs
@@ -0,0 +1,98 @@
+//! An equation's kept source OMML is written back verbatim only when it is exactly one well-formed
+//! `m:oMath` (#6072). `Math::omml` also comes from `.json` documents, so anything else must not
+//! reach `document.xml`: it is written from the equation's nodes instead.
+
+use craft_math::math::{MNode, MRun, Math};
+use craft_wordmodel::para::{InlineObject, OBJ};
+use craft_wordmodel::props::CharProps;
+use craft_wordmodel::{Document, Paragraph, para_block};
+
+/// Save a one-equation document whose equation keeps `omml` and has the nodes `NODES`.
+fn save(omml: &str, display: bool) -> (String, Document) {
+ let math = Math { nodes: vec![MNode::Run(MRun::new("NODES"))], omml: omml.into(), ..Default::default() };
+ let mut p = Paragraph::new();
+ p.insert_object(0, InlineObject::Equation { linear: "NODES".into(), display, math }, &CharProps::default()).unwrap();
+ let mut doc = Document::new();
+ doc.body = vec![para_block(p)];
+ let bytes = craft_docx::write(&doc).unwrap();
+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
+ let mut xml = String::new();
+ std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
+ // The saved file must open again (the main part is read strictly).
+ let back = craft_docx::read(&bytes).unwrap_or_else(|e| panic!("{omml:?} doesn't reopen: {e}"));
+ (xml, back)
+}
+
+/// The text of the reopened document's equations and paragraphs.
+fn texts(doc: &Document) -> Vec {
+ let mut out = Vec::new();
+ for b in &doc.body {
+ let Some(p) = b.as_para() else { continue };
+ for o in &p.objects {
+ if let InlineObject::Equation { math, .. } = o {
+ out.push(craft_math::math::to_linear(&math.nodes));
+ }
+ }
+ let text: String = p.text.chars().filter(|c| *c != OBJ).collect();
+ if !text.trim().is_empty() {
+ out.push(text);
+ }
+ }
+ out
+}
+
+#[test]
+fn well_formed_kept_omml_is_written_back_unchanged() {
+ let kept = "KEPT";
+ let (xml, back) = save(kept, false);
+ assert!(xml.contains(kept), "{xml}");
+ assert_eq!(texts(&back), vec!["KEPT".to_string()]);
+}
+
+#[test]
+fn malformed_kept_omml_is_written_from_the_nodes() {
+ for kept in [
+ // Unclosed, mismatched, an undefined entity.
+ "",
+ "",
+ "&bad;",
+ // Markup after the element, text after it, a second element.
+ "INJECTED",
+ "INJECTED",
+ "INJECTED",
+ // Not an m:oMath.
+ "INJECTED",
+ // An m:oMath in another namespace, and an unknown entity in an attribute.
+ "INJECTED",
+ "INJECTED",
+ // Names that aren't XML names, and prefixes that aren't declared.
+ "INJECTED",
+ "INJECTED",
+ "INJECTED",
+ "INJECTED",
+ "INJECTED",
+ // Two attributes with one expanded name (Namespaces in XML §6.3).
+ "INJECTED",
+ // A `<` in an attribute value, `]]>` in text.
+ "INJECTED",
+ "INJECTED]]>",
+ // Characters XML 1.0 doesn't allow, as references or as they are.
+ "INJECTED",
+ "INJECTED",
+ "INJECTED",
+ "INJECTED",
+ "INJECTED\u{1}",
+ ] {
+ let (xml, back) = save(kept, false);
+ assert!(!xml.contains("INJECTED") && !xml.contains("&bad;"), "{kept:?} was written: {xml}");
+ assert_eq!(texts(&back), vec!["NODES".to_string()], "{kept:?}");
+ }
+}
+
+#[test]
+fn a_kept_omath_para_is_not_nested_in_another() {
+ let kept = "P";
+ let (xml, back) = save(kept, true);
+ assert!(!xml.contains(""), "{xml}");
+ assert_eq!(texts(&back), vec!["NODES".to_string()]);
+}
diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs
index 726010a7a..1e57e583c 100644
--- a/crates/docx/tests/it/main.rs
+++ b/crates/docx/tests/it/main.rs
@@ -20,6 +20,7 @@ mod emphasis_marks;
mod fixtures;
mod glossary;
mod heading_levels;
+mod kept_omml_check;
mod legacy_forms;
mod ligatures;
mod line_numbering;
diff --git a/crates/math/Cargo.toml b/crates/math/Cargo.toml
index 6cbc3251e..d7e4786ec 100644
--- a/crates/math/Cargo.toml
+++ b/crates/math/Cargo.toml
@@ -12,6 +12,9 @@ workspace = true
[dependencies]
craft-xml = { workspace = true }
+# A conforming XML parser (names, namespaces, characters), for checking kept OMML before it is
+# written verbatim; already in the lock as a dependency of other crates.
+roxmltree = "0.21"
serde = { workspace = true }
[dev-dependencies]
diff --git a/crates/math/src/omml.rs b/crates/math/src/omml.rs
index 99024ec8b..dbcdc0cfd 100644
--- a/crates/math/src/omml.rs
+++ b/crates/math/src/omml.rs
@@ -58,9 +58,27 @@ fn parse_kept(xml: &str) -> Option {
Options { ns_decls: false, ..Options::default() }.with_limits(limits).parse(xml.as_bytes()).ok()
}
-/// Is `xml` (kept OMML) well-formed enough to write back as it is?
+/// Whether `xml` (kept OMML) can be written back as it is: exactly one well-formed `m:oMath` (not
+/// `m:oMathPara`), with nothing around it. The writer copies it verbatim into the host document,
+/// and [`Math::omml`] also comes from documents saved as JSON, so anything else (an unclosed or
+/// mismatched tag, an unknown entity, markup or text after the element, an `m:oMathPara` that
+/// would be nested in a second one) is written from the nodes instead (wordcraft#6072).
+///
+/// The strict [`craft_xml`] read bounds the nesting and rejects bad tags, entities and trailing
+/// content, but it is lenient about the rest of XML: names that aren't XML names, undeclared
+/// prefixes, two attributes with one expanded name, a `<` in an attribute value, `]]>` in text,
+/// characters XML 1.0 doesn't allow. A conforming parser rejects all of those, so it runs last,
+/// with only the canonical prefixes of kept OMML declared (`m:`, `w:`, `mc:`, as the host
+/// document's root declares them): any other prefix is undeclared there. The element must be
+/// `m:oMath` by namespace, so an `m:` bound to another URI isn't one.
fn is_well_formed(xml: &str) -> bool {
- xml.starts_with("") || xml.starts_with("{xml}");
+ let Ok(doc) = roxmltree::Document::parse(&wrapped) else { return false };
+ let mut nodes = doc.root_element().children();
+ matches!((nodes.next(), nodes.next()), (Some(e), None) if e.tag_name().namespace() == Some(MATH_NS) && e.tag_name().name() == "oMath")
}
/// An equation from OMML text ([`parse`]): an `m:oMathPara`'s first `m:oMath` with the
diff --git a/crates/math/src/omml/write.rs b/crates/math/src/omml/write.rs
index 046c4499a..4d8f2dd0c 100644
--- a/crates/math/src/omml/write.rs
+++ b/crates/math/src/omml/write.rs
@@ -44,7 +44,7 @@ pub fn write_equation(w: &mut W, linear: &str, display: bool, math: &Math, color
w.close("m:oMathParaPr");
}
}
- if !math.omml.is_empty() && math.omml.starts_with("