From 1a0d5d607859a2e529851482de09b8e53aaeec3e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 09:58:00 -0500 Subject: [PATCH 1/7] Extract XFA namespace-aware XML DOM without layout policy --- ATTRIBUTION.md | 4 + Cargo.lock | 7 + Cargo.toml | 1 + crates/xfa/Cargo.toml | 14 ++ crates/xfa/README.md | 9 + crates/xfa/src/lib.rs | 6 + crates/xfa/src/xml.rs | 428 ++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 469 insertions(+) create mode 100644 crates/xfa/Cargo.toml create mode 100644 crates/xfa/README.md create mode 100644 crates/xfa/src/lib.rs create mode 100644 crates/xfa/src/xml.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 4c86afd61..6caa0fd33 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -132,3 +132,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## JSONC span-preserving editing `crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported. + +## XFA XML DOM + +`crates/xfa/src/xml.rs` is extracted from PDFCraft at `271e479c53723b1b294c866d5cb2f27604601b29`, originally by Dylan M. Taylor (`eead4541`, `7d44e654`), MIT OR Apache-2.0. Only visibility and module boundaries change; PDF/layout/form policy remains in the app. diff --git a/Cargo.lock b/Cargo.lock index 9fa1f4401..7bf961c6b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3380,6 +3380,13 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xfa" +version = "0.1.0" +dependencies = [ + "craft-xml", +] + [[package]] name = "craft-xfl" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 50ec3c917..d9094ba20 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-xfa = { path = "crates/xfa" } craft-jsonc = { path = "crates/jsonc" } craft-palette = { path = "crates/palette" } craft-score = { path = "crates/score" } diff --git a/crates/xfa/Cargo.toml b/crates/xfa/Cargo.toml new file mode 100644 index 000000000..7dca38e84 --- /dev/null +++ b/crates/xfa/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-xfa" +description = "Namespace-aware source-span XML DOM for XFA adapters; no PDF or layout policy" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-xml = { workspace = true } diff --git a/crates/xfa/README.md b/crates/xfa/README.md new file mode 100644 index 000000000..e4ed85e08 --- /dev/null +++ b/crates/xfa/README.md @@ -0,0 +1,9 @@ +# craft-xfa + +Scoped namespace-aware XML DOM extracted unchanged from PDFCraft xfa/xml.rs at 271e479c. This is not a complete XFA implementation: template interpretation, packets, data binding, scripts, layout, fonts and PDF generation remain app-owned. + +Preserves source byte ranges, coalesced text, namespace shadowing and document-local node identities. Uses craft-xml strict events with DTD rejection by default, depth 1024 and caller node count. Other event-reader defaults remain in force. Namespace snapshots are copied per element as before; this is not a new total-memory bound or a full XML namespaces conformance claim. + +Original source by Dylan M. Taylor (eead4541, 7d44e654), MIT OR Apache-2.0. + +Compatibility delta versus the original app XML pin e2dc681a3: current strict craft-xml rejects duplicate raw or expanded attribute names. This deliberately preserves shared security hardening; valid-document DOM behavior is unchanged, but malformed acceptance and errors are not promised byte-identical. Regression tests cover both duplicate forms. diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs new file mode 100644 index 000000000..61640dbf6 --- /dev/null +++ b/crates/xfa/src/lib.rs @@ -0,0 +1,6 @@ +//! XFA XML infrastructure, extracted from PDFCraft. Layout and application policy stay local. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +/// Compatibility depth limit for XFA XML documents. +pub const MAX_XML_DEPTH: usize = 1024; +pub mod xml; diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs new file mode 100644 index 000000000..0840170e6 --- /dev/null +++ b/crates/xfa/src/xml.rs @@ -0,0 +1,428 @@ +//! Lightweight namespace-aware XML DOM with source byte ranges, backed by `craft_xml`. + +use std::ops::Range; + +const XML_NS: &str = "http://www.w3.org/XML/1998/namespace"; +const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct NodeId(pub usize); + +#[derive(Clone, Debug)] +pub struct ParsingOptions { + pub allow_dtd: bool, + pub nodes_limit: u32, +} + +impl Default for ParsingOptions { + fn default() -> Self { + Self { allow_dtd: false, nodes_limit: u32::MAX } + } +} + +#[derive(Clone, Debug)] +struct AttrData { + ns: Option, + name: String, + value: String, +} + +#[derive(Clone, Debug)] +enum NodeKind { + Element { + ns: Option, + name: String, + attrs: Vec, + /// In-scope `(prefix, uri)` bindings at this element (`""` for default namespace). + namespaces: Vec<(String, String)>, + range: Range, + }, + Text(String), +} + +#[derive(Clone, Debug)] +struct NodeData { + kind: NodeKind, + children: Vec, +} + +pub struct Document { + nodes: Vec, + root: usize, +} + +#[derive(Clone, Copy)] +pub struct Node<'a> { + doc: &'a Document, + id: usize, +} + +impl PartialEq for Node<'_> { + fn eq(&self, other: &Self) -> bool { + self.id == other.id && std::ptr::eq(self.doc, other.doc) + } +} + +impl Eq for Node<'_> {} + +#[derive(Clone, Copy)] +pub struct ExpandedName<'a> { + ns: Option<&'a str>, + name: &'a str, +} + +impl<'a> ExpandedName<'a> { + pub fn name(&self) -> &'a str { + self.name + } + + pub fn namespace(&self) -> Option<&'a str> { + self.ns + } +} + +pub trait AttributeKey { + fn matches(&self, ns: Option<&str>, name: &str) -> bool; +} + +impl AttributeKey for &str { + fn matches(&self, ns: Option<&str>, name: &str) -> bool { + ns.is_none() && name == *self + } +} + +impl AttributeKey for (&str, &str) { + fn matches(&self, ns: Option<&str>, name: &str) -> bool { + ns == Some(self.0) && name == self.1 + } +} + +#[derive(Clone, Copy)] +pub struct Attribute<'a> { + attr: &'a AttrData, +} + +impl<'a> Attribute<'a> { + pub fn name(&self) -> &'a str { + &self.attr.name + } + + pub fn namespace(&self) -> Option<&'a str> { + self.attr.ns.as_deref() + } + + pub fn value(&self) -> &'a str { + &self.attr.value + } +} + +#[derive(Clone, Copy)] +pub struct Namespace<'a> { + prefix: &'a str, + uri: &'a str, +} + +impl<'a> Namespace<'a> { + pub fn name(&self) -> Option<&'a str> { + (!self.prefix.is_empty()).then_some(self.prefix) + } + + pub fn uri(&self) -> &'a str { + self.uri + } +} + +fn split_qname(qname: &str) -> (&str, &str) { + match qname.split_once(':') { + Some((p, l)) => (p, l), + None => ("", qname), + } +} + +fn resolve_ns(scope: &[(String, String)], prefix: &str, is_attr: bool) -> Result, String> { + if prefix == "xml" { + return Ok(Some(XML_NS.to_string())); + } + if prefix == "xmlns" { + return Ok(Some(XMLNS_NS.to_string())); + } + if prefix.is_empty() { + if is_attr { + return Ok(None); + } + return Ok(scope.iter().rev().find(|(p, _)| p.is_empty()).and_then(|(_, u)| (!u.is_empty()).then(|| u.clone()))); + } + match scope.iter().rev().find(|(p, _)| p == prefix) { + Some((_, u)) if !u.is_empty() => Ok(Some(u.clone())), + _ => Err(format!("undeclared namespace prefix: {prefix}")), + } +} + +impl Document { + pub fn parse(text: &str) -> Result { + Self::parse_with_options(text, ParsingOptions::default()) + } + + pub fn parse_with_options(text: &str, options: ParsingOptions) -> Result { + let mut opts = craft_xml::Options { + strict: true, + doctype: if options.allow_dtd { craft_xml::Doctype::Ignore } else { craft_xml::Doctype::Reject }, + ..Default::default() + }; + opts.limits.max_nodes = options.nodes_limit as usize; + opts.limits.max_depth = crate::MAX_XML_DEPTH; + + let mut events = opts.events(text.as_bytes()); + let mut nodes: Vec = Vec::new(); + let mut open: Vec<(usize, usize)> = Vec::new(); // (node_id, scope_len_before) + let mut scope: Vec<(String, String)> = Vec::new(); + let mut root: Option = None; + + while let Some(ev) = events.next().map_err(|e| e.to_string())? { + let span = events.span(); + match ev { + craft_xml::Event::Start { name, attrs } => { + if nodes.len() >= options.nodes_limit as usize { + return Err("nodes limit reached".to_string()); + } + let scope_mark = scope.len(); + for (k, v) in &attrs { + if k == "xmlns" { + scope.push((String::new(), v.clone())); + } else if let Some(prefix) = k.strip_prefix("xmlns:") { + scope.push((prefix.to_string(), v.clone())); + } + } + let (el_prefix, el_local) = split_qname(&name); + let el_ns = resolve_ns(&scope, el_prefix, false)?; + let mut el_attrs = Vec::new(); + for (k, v) in attrs { + if k == "xmlns" || k.starts_with("xmlns:") { + continue; + } + let (ap, al) = split_qname(&k); + let ans = resolve_ns(&scope, ap, true)?; + el_attrs.push(AttrData { ns: ans, name: al.to_string(), value: v }); + } + // Deduplicate in-scope namespace bindings, keeping the innermost binding per prefix. + let mut namespaces: Vec<(String, String)> = Vec::new(); + for (p, u) in scope.iter().rev() { + if !namespaces.iter().any(|(ep, _)| ep == p) { + namespaces.push((p.clone(), u.clone())); + } + } + namespaces.retain(|(_, u)| !u.is_empty()); + let id = nodes.len(); + nodes.push(NodeData { + kind: NodeKind::Element { ns: el_ns, name: el_local.to_string(), attrs: el_attrs, namespaces, range: span.start..span.end }, + children: Vec::new(), + }); + if let Some(&(parent, _)) = open.last() { + nodes[parent].children.push(id); + } else if root.is_none() { + root = Some(id); + } + open.push((id, scope_mark)); + } + craft_xml::Event::End { .. } => { + if let Some((id, scope_mark)) = open.pop() { + if let NodeKind::Element { range, .. } = &mut nodes[id].kind { + range.end = span.end; + } + scope.truncate(scope_mark); + } + } + craft_xml::Event::Text(t) | craft_xml::Event::CData(t) => { + if let Some(&(parent, _)) = open.last() { + if let Some(&last_child) = nodes[parent].children.last() + && let NodeKind::Text(existing) = &mut nodes[last_child].kind + { + existing.push_str(&t); + continue; + } + if nodes.len() >= options.nodes_limit as usize { + return Err("nodes limit reached".to_string()); + } + let id = nodes.len(); + nodes.push(NodeData { kind: NodeKind::Text(t), children: Vec::new() }); + nodes[parent].children.push(id); + } + } + craft_xml::Event::Pi { .. } | craft_xml::Event::Comment(_) => {} + } + } + + let Some(root) = root else { + return Err("empty XML document".to_string()); + }; + Ok(Self { nodes, root }) + } + + pub fn root_element(&self) -> Node<'_> { + Node { doc: self, id: self.root } + } + + pub fn get_node(&self, id: NodeId) -> Option> { + (id.0 < self.nodes.len()).then_some(Node { doc: self, id: id.0 }) + } + + pub fn descendants(&self) -> Descendants<'_> { + Descendants { doc: self, stack: vec![self.root] } + } +} + +pub struct Descendants<'a> { + doc: &'a Document, + stack: Vec, +} + +impl<'a> Iterator for Descendants<'a> { + type Item = Node<'a>; + + fn next(&mut self) -> Option { + let id = self.stack.pop()?; + let children = &self.doc.nodes[id].children; + for &c in children.iter().rev() { + self.stack.push(c); + } + Some(Node { doc: self.doc, id }) + } +} + +impl<'a> Node<'a> { + pub fn id(&self) -> NodeId { + NodeId(self.id) + } + + pub fn document(&self) -> &'a Document { + self.doc + } + + pub fn is_element(&self) -> bool { + matches!(self.doc.nodes[self.id].kind, NodeKind::Element { .. }) + } + + pub fn is_text(&self) -> bool { + matches!(self.doc.nodes[self.id].kind, NodeKind::Text(_)) + } + + pub fn tag_name(&self) -> ExpandedName<'a> { + match &self.doc.nodes[self.id].kind { + NodeKind::Element { ns, name, .. } => ExpandedName { ns: ns.as_deref(), name }, + NodeKind::Text(_) => ExpandedName { ns: None, name: "" }, + } + } + + pub fn attribute(&self, key: K) -> Option<&'a str> { + match &self.doc.nodes[self.id].kind { + NodeKind::Element { attrs, .. } => attrs.iter().find(|a| key.matches(a.ns.as_deref(), &a.name)).map(|a| a.value.as_str()), + NodeKind::Text(_) => None, + } + } + + pub fn attributes(&self) -> impl ExactSizeIterator> + use<'a> { + let attrs = match &self.doc.nodes[self.id].kind { + NodeKind::Element { attrs, .. } => attrs.as_slice(), + NodeKind::Text(_) => &[], + }; + attrs.iter().map(|attr| Attribute { attr }) + } + + pub fn namespaces(&self) -> impl ExactSizeIterator> + use<'a> { + let ns = match &self.doc.nodes[self.id].kind { + NodeKind::Element { namespaces, .. } => namespaces.as_slice(), + NodeKind::Text(_) => &[], + }; + ns.iter().map(|(p, u)| Namespace { prefix: p, uri: u }) + } + + pub fn lookup_prefix(&self, uri: &str) -> Option<&'a str> { + if uri == XML_NS { + return Some("xml"); + } + match &self.doc.nodes[self.id].kind { + NodeKind::Element { namespaces, .. } => namespaces.iter().find(|(_, u)| u == uri).map(|(p, _)| p.as_str()), + NodeKind::Text(_) => None, + } + } + + pub fn lookup_namespace_uri(&self, prefix: Option<&str>) -> Option<&'a str> { + if prefix == Some("xml") { + return Some(XML_NS); + } + if prefix == Some("xmlns") { + return Some(XMLNS_NS); + } + let target = prefix.unwrap_or(""); + match &self.doc.nodes[self.id].kind { + NodeKind::Element { namespaces, .. } => namespaces.iter().find(|(p, _)| p == target).map(|(_, u)| u.as_str()), + NodeKind::Text(_) => None, + } + } + + pub fn children(&self) -> impl Iterator> + use<'a> { + let doc = self.doc; + doc.nodes[self.id].children.iter().map(move |&id| Node { doc, id }) + } + + pub fn descendants(&self) -> Descendants<'a> { + Descendants { doc: self.doc, stack: vec![self.id] } + } + + pub fn text(&self) -> Option<&'a str> { + match &self.doc.nodes[self.id].kind { + NodeKind::Text(t) => Some(t.as_str()), + NodeKind::Element { .. } => self.doc.nodes[self.id].children.first().and_then(|&cid| match &self.doc.nodes[cid].kind { + NodeKind::Text(t) => Some(t.as_str()), + _ => None, + }), + } + } + + pub fn range(&self) -> Range { + match &self.doc.nodes[self.id].kind { + NodeKind::Element { range, .. } => range.clone(), + NodeKind::Text(_) => 0..0, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn namespace_shadowing_attributes_text_and_source_ranges() { + let text = "onethree"; + let doc = Document::parse(text).unwrap(); + let root = doc.root_element(); + assert_eq!(root.tag_name().namespace(), Some("urn:outer")); + assert_eq!(root.attribute("a"), Some("v")); + let child = root.children().next().unwrap(); + assert_eq!(child.tag_name().namespace(), Some("urn:p")); + assert_eq!(child.attribute(("urn:p", "a")), Some("x")); + assert_eq!(child.lookup_namespace_uri(None), Some("urn:inner")); + assert_eq!(child.text(), Some("onetwothree")); + assert_eq!(child.children().count(), 1); + assert!(text[child.range()].starts_with("")); + assert!(doc.get_node(child.id()).unwrap() == child); + assert_eq!(root.children().nth(1).unwrap().tag_name().namespace(), None); + assert_eq!(root.range(), 0..text.len()); + } + + #[test] + fn malformed_dtd_and_resource_limits_are_preserved() { + // Current shared XML rejects duplicate attributes, unlike the older app pin. + assert!(Document::parse("").is_err()); + assert!(Document::parse("").is_err()); + assert!(Document::parse("").is_err()); + assert!(Document::parse("").is_err()); + assert!(Document::parse_with_options("", ParsingOptions { allow_dtd: true, nodes_limit: 8 }).is_ok()); + assert!(Document::parse_with_options("text", ParsingOptions { allow_dtd: false, nodes_limit: 1 }).is_err()); + assert!(Document::parse_with_options("", ParsingOptions { allow_dtd: false, nodes_limit: 0 }).is_err()); + let text = format!("{}{}", "".repeat(1025), "".repeat(1025)); + assert!(Document::parse(&text).is_err()); + assert!(Document::parse("").is_err()); + } +} From c50eb61065846fc6d4feca3438ffa691dc855313 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 10:11:04 -0500 Subject: [PATCH 2/7] Document and test inherited namespace declaration budget --- crates/xfa/README.md | 2 ++ crates/xfa/src/xml.rs | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/crates/xfa/README.md b/crates/xfa/README.md index e4ed85e08..a3548c2d1 100644 --- a/crates/xfa/README.md +++ b/crates/xfa/README.md @@ -7,3 +7,5 @@ Preserves source byte ranges, coalesced text, namespace shadowing and document-l Original source by Dylan M. Taylor (eead4541, 7d44e654), MIT OR Apache-2.0. Compatibility delta versus the original app XML pin e2dc681a3: current strict craft-xml rejects duplicate raw or expanded attribute names. This deliberately preserves shared security hardening; valid-document DOM behavior is unchanged, but malformed acceptance and errors are not promised byte-identical. Regression tests cover both duplicate forms. + +The updated strict reader also bounds aggregate active namespace declarations to 1024 across ancestor elements, not just attributes per tag. The old app path could accept more inherited declarations. The exact boundary and one-over case are tested; this intentional tighter resource admission is retained. diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index 0840170e6..2f4a49db8 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -411,6 +411,23 @@ mod tests { assert_eq!(root.range(), 0..text.len()); } + #[test] + fn inherited_namespace_declarations_have_an_aggregate_budget() { + use std::fmt::Write; + let mut xml = String::from(""); + assert!(Document::parse(&accepted).is_ok()); + let rejected = format!("{xml} xmlns:extra='extra'/>"); + assert!(Document::parse(&rejected).is_err()); + } + #[test] fn malformed_dtd_and_resource_limits_are_preserved() { // Current shared XML rejects duplicate attributes, unlike the older app pin. From 9799e3be701c0b135ee4283facdf0ad978effcd3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 12:10:30 -0500 Subject: [PATCH 3/7] Split XFA accessor regressions without weakening assertions --- crates/xfa/src/xml.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index 2bed07bbf..b76f4d755 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -433,6 +433,13 @@ mod tests { let namespaces: Vec<_> = root.namespaces().map(|n| (n.name(), n.uri())).collect(); assert!(namespaces.contains(&(None, "urn:r"))); assert!(namespaces.contains(&(Some("p"), "urn:p"))); + } + + #[test] + fn descendants_and_text_nodes_preserve_identity_and_empty_accessors() { + let doc = + Document::parse("firstsecondlast").unwrap(); + let root = doc.root_element(); let all: Vec<_> = doc.descendants().collect(); assert_eq!(all.len(), 5); assert!(all.iter().zip(root.descendants()).all(|(a, b)| *a == b)); From 72d8ac7c6cfe846cb848a3938d08a1474d4260c9 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:17:29 +0700 Subject: [PATCH 4/7] fix(xfa): bound retained namespace copies before allocation (#2122) Co-authored-by: FredApps --- crates/xfa/README.md | 4 ++-- crates/xfa/src/xml.rs | 50 ++++++++++++++++++++++++++++++++++++------- 2 files changed, 44 insertions(+), 10 deletions(-) diff --git a/crates/xfa/README.md b/crates/xfa/README.md index a3548c2d1..21620cbb9 100644 --- a/crates/xfa/README.md +++ b/crates/xfa/README.md @@ -1,8 +1,8 @@ # craft-xfa -Scoped namespace-aware XML DOM extracted unchanged from PDFCraft xfa/xml.rs at 271e479c. This is not a complete XFA implementation: template interpretation, packets, data binding, scripts, layout, fonts and PDF generation remain app-owned. +Scoped namespace-aware XML DOM extracted from PDFCraft xfa/xml.rs at 271e479c. This is not a complete XFA implementation: template interpretation, packets, data binding, scripts, layout, fonts and PDF generation remain app-owned. -Preserves source byte ranges, coalesced text, namespace shadowing and document-local node identities. Uses craft-xml strict events with DTD rejection by default, depth 1024 and caller node count. Other event-reader defaults remain in force. Namespace snapshots are copied per element as before; this is not a new total-memory bound or a full XML namespaces conformance claim. +Preserves source byte ranges, coalesced text, namespace shadowing and document-local node identities. Uses craft-xml strict events with DTD rejection by default, depth 1024 and caller node count. Other event-reader defaults remain in force. Namespace snapshots are copied per element as before, with a 64 MiB cumulative pre-allocation budget for snapshot entry headers, prefix/URI bytes and resolved element/attribute namespace URI copies. Excess returns an error. This intentionally tightens resource admission; it is not a total DOM memory bound or a full XML namespaces conformance claim. Original source by Dylan M. Taylor (eead4541, 7d44e654), MIT OR Apache-2.0. diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index b76f4d755..70fe5d580 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -2,6 +2,7 @@ use std::ops::Range; +const MAX_NAMESPACE_BYTES: usize = 64 << 20; const XML_NS: &str = "http://www.w3.org/XML/1998/namespace"; const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/"; @@ -139,31 +140,49 @@ fn split_qname(qname: &str) -> (&str, &str) { } } -fn resolve_ns(scope: &[(String, String)], prefix: &str, is_attr: bool) -> Result, String> { +// One long inherited URI otherwise gets copied into every descendant. Charge retained +// namespace strings and snapshot entry headers before copying, across the whole document. +fn charge_namespace(bytes: &mut usize, amount: usize) -> Result<(), String> { + *bytes = bytes.checked_sub(amount).ok_or_else(|| "namespace retention budget exceeded".to_string())?; + Ok(()) +} + +fn copy_namespace(uri: &str, bytes: &mut usize) -> Result, String> { + charge_namespace(bytes, uri.len())?; + Ok(Some(uri.to_string())) +} + +fn resolve_ns(scope: &[(String, String)], prefix: &str, is_attr: bool, bytes: &mut usize) -> Result, String> { if prefix == "xml" { - return Ok(Some(XML_NS.to_string())); + return copy_namespace(XML_NS, bytes); } if prefix == "xmlns" { - return Ok(Some(XMLNS_NS.to_string())); + return copy_namespace(XMLNS_NS, bytes); } if prefix.is_empty() { if is_attr { return Ok(None); } - return Ok(scope.iter().rev().find(|(p, _)| p.is_empty()).and_then(|(_, u)| (!u.is_empty()).then(|| u.clone()))); + return match scope.iter().rev().find(|(p, _)| p.is_empty()) { + Some((_, u)) if !u.is_empty() => copy_namespace(u, bytes), + _ => Ok(None), + }; } match scope.iter().rev().find(|(p, _)| p == prefix) { - Some((_, u)) if !u.is_empty() => Ok(Some(u.clone())), + Some((_, u)) if !u.is_empty() => copy_namespace(u, bytes), _ => Err(format!("undeclared namespace prefix: {prefix}")), } } - impl Document { pub fn parse(text: &str) -> Result { Self::parse_with_options(text, ParsingOptions::default()) } pub fn parse_with_options(text: &str, options: ParsingOptions) -> Result { + Self::parse_with_namespace_budget(text, options, MAX_NAMESPACE_BYTES) + } + + fn parse_with_namespace_budget(text: &str, options: ParsingOptions, mut namespace_bytes: usize) -> Result { let mut opts = craft_xml::Options { strict: true, doctype: if options.allow_dtd { craft_xml::Doctype::Ignore } else { craft_xml::Doctype::Reject }, @@ -194,20 +213,23 @@ impl Document { } } let (el_prefix, el_local) = split_qname(&name); - let el_ns = resolve_ns(&scope, el_prefix, false)?; + let el_ns = resolve_ns(&scope, el_prefix, false, &mut namespace_bytes)?; let mut el_attrs = Vec::new(); for (k, v) in attrs { if k == "xmlns" || k.starts_with("xmlns:") { continue; } let (ap, al) = split_qname(&k); - let ans = resolve_ns(&scope, ap, true)?; + let ans = resolve_ns(&scope, ap, true, &mut namespace_bytes)?; el_attrs.push(AttrData { ns: ans, name: al.to_string(), value: v }); } // Deduplicate in-scope namespace bindings, keeping the innermost binding per prefix. let mut namespaces: Vec<(String, String)> = Vec::new(); for (p, u) in scope.iter().rev() { if !namespaces.iter().any(|(ep, _)| ep == p) { + charge_namespace(&mut namespace_bytes, std::mem::size_of::<(String, String)>())?; + charge_namespace(&mut namespace_bytes, p.len())?; + charge_namespace(&mut namespace_bytes, u.len())?; namespaces.push((p.clone(), u.clone())); } } @@ -391,6 +413,18 @@ impl<'a> Node<'a> { mod tests { use super::*; + #[test] + fn inherited_namespace_copies_obey_aggregate_byte_admission() { + let uri = format!("urn:{}", "x".repeat(124)); + let snapshot = std::mem::size_of::<(String, String)>() + 1 + uri.len(); + for (child, expanded_copies) in [("", 0), ("", 1), ("", 1), ("", 2)] { + let input = format!("{}", child.repeat(8)); + let needed = 9 * snapshot + 8 * expanded_copies * uri.len(); + assert!(Document::parse_with_namespace_budget(&input, ParsingOptions::default(), needed).is_ok()); + assert!(Document::parse_with_namespace_budget(&input, ParsingOptions::default(), needed - 1).is_err()); + assert!(Document::parse_with_namespace_budget(&input, ParsingOptions::default(), 0).is_err()); + } + } #[test] fn namespace_shadowing_attributes_text_and_source_ranges() { let text = "onethree"; From aa423ded8095ce5a92e1590aee31a6625f54febe Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:36:07 +0100 Subject: [PATCH 5/7] docs(xfa): distinguish extracted baseline from later hardening --- ATTRIBUTION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 63061b638..eb9a55eeb 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -145,7 +145,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## XFA XML DOM -`crates/xfa/src/xml.rs` is extracted from PDFCraft at `271e479c53723b1b294c866d5cb2f27604601b29`, originally by Dylan M. Taylor (`eead4541`, `7d44e654`), MIT OR Apache-2.0. Only visibility and module boundaries change; PDF/layout/form policy remains in the app. +`crates/xfa/src/xml.rs` is extracted from PDFCraft at `271e479c53723b1b294c866d5cb2f27604601b29`, originally by Dylan M. Taylor (`eead4541`, `7d44e654`), MIT OR Apache-2.0. The initial extraction changes visibility and module boundaries; subsequent namespace-retention budget hardening intentionally tightens resource admission. PDF/layout/form policy remains in the app. ## Java class inspection From 80f1cedd4bc66b927a6fd8fbc979ca9995523bd9 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:39:50 +0700 Subject: [PATCH 6/7] fix(xfa): retain original source ranges after UTF-8 BOM (#2160) * test(xfa): reproduce BOM-relative source ranges * fix(xfa): translate BOM-stripped spans to original input --- crates/xfa/src/xml.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index 70fe5d580..7afab7600 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -191,7 +191,11 @@ impl Document { opts.limits.max_nodes = options.nodes_limit as usize; opts.limits.max_depth = crate::MAX_XML_DEPTH; - let mut events = opts.events(text.as_bytes()); + // quick-xml excludes a leading UTF-8 BOM from its buffer positions. + // Parse it explicitly so every stored range still addresses the original input. + let input = text.strip_prefix('\u{feff}').unwrap_or(text); + let source_offset = text.len() - input.len(); + let mut events = opts.events(input.as_bytes()); let mut nodes: Vec = Vec::new(); let mut open: Vec<(usize, usize)> = Vec::new(); // (node_id, scope_len_before) let mut scope: Vec<(String, String)> = Vec::new(); @@ -199,6 +203,7 @@ impl Document { while let Some(ev) = events.next().map_err(|e| e.to_string())? { let span = events.span(); + let span = span.start + source_offset..span.end + source_offset; match ev { craft_xml::Event::Start { name, attrs } => { if nodes.len() >= options.nodes_limit as usize { @@ -413,6 +418,23 @@ impl<'a> Node<'a> { mod tests { use super::*; + #[test] + fn element_ranges_slice_original_input_with_utf8_bom() { + for prefix in ["", "\u{feff}", "\u{feff}"] { + for child_xml in ["<é/>", "<é>text"] { + let root_xml = format!("{child_xml}"); + let input = format!("{prefix}{root_xml}"); + let doc = Document::parse(&input).unwrap(); + let root = doc.root_element(); + let child = root.children().next().unwrap(); + assert_eq!(input.get(root.range()), Some(root_xml.as_str())); + assert_eq!(input.get(child.range()), Some(child_xml)); + assert_eq!(root.range(), prefix.len()..input.len()); + assert_eq!(child.range(), prefix.len() + 3..prefix.len() + 3 + child_xml.len()); + } + } + } + #[test] fn inherited_namespace_copies_obey_aggregate_byte_admission() { let uri = format!("urn:{}", "x".repeat(124)); From c03ba68ab363bcf337a5f2c9548ead0b941b427f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:36:07 +0700 Subject: [PATCH 7/7] fix(xfa): reject repeated leading BOM before parsing spans (#2176) --- crates/xfa/src/xml.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index 7afab7600..7d6dd8193 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -194,6 +194,10 @@ impl Document { // quick-xml excludes a leading UTF-8 BOM from its buffer positions. // Parse it explicitly so every stored range still addresses the original input. let input = text.strip_prefix('\u{feff}').unwrap_or(text); + // A second U+FEFF is content outside the root, not another encoding marker. + if input.starts_with('\u{feff}') { + return Err("multiple leading XML byte-order marks".to_string()); + } let source_offset = text.len() - input.len(); let mut events = opts.events(input.as_bytes()); let mut nodes: Vec = Vec::new(); @@ -435,6 +439,15 @@ mod tests { } } + #[test] + fn repeated_leading_bom_is_rejected_before_event_parsing() { + for prefix in ["\u{feff}\u{feff}", "\u{feff}\u{feff}\u{feff}"] { + for body in ["<é/>", "<é>text"] { + assert!(Document::parse(&format!("{prefix}{body}")).is_err()); + } + } + } + #[test] fn inherited_namespace_copies_obey_aggregate_byte_admission() { let uri = format!("urn:{}", "x".repeat(124));