From 1a0d5d607859a2e529851482de09b8e53aaeec3e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 09:58:00 -0500 Subject: [PATCH] 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()); + } +}