Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

forms: clear typed XFA password field values from datasets on save (#3944) (#4506)

jonathanwxh-cell24edde656349
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index f195b10cc..f11671bf8 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -3070,16 +3070,24 @@ fn renderer_password(bytes: &[u8]) -> String {
}
}
-/// The document as it may be written to a file (#3926): a copy without the values of text fields
-/// with the Password flag, or `cos` itself when it holds none. ISO 32000-2 §12.7.5.3, Table 231
-/// (a note to the Password flag): "it is imperative that PDF processors never store the value of
-/// the text field in the PDF file if this flag is set". The open document keeps them in memory.
+/// The document as it may be written to a file (#3926, #3944): a copy without the values of text
+/// fields with the Password flag (or XFA `<passwordEdit/>` fields in the datasets), or `cos`
+/// itself when it holds none. ISO 32000-2 §12.7.5.3, Table 231 (a note to the Password flag):
+/// "it is imperative that PDF processors never store the value of the text field in the PDF file
+/// if this flag is set". The open document keeps them in memory.
fn writable(cos: &pdfcraft_cos::Document) -> Result<std::borrow::Cow<'_, pdfcraft_cos::Document>, EditError> {
- if !pdfcraft_forms::has_password_values(cos) {
+ let has_form_pw = pdfcraft_forms::has_password_values(cos);
+ let has_xfa_pw = pdfcraft_xfa::has_password_values(cos);
+ if !has_form_pw && !has_xfa_pw {
return Ok(std::borrow::Cow::Borrowed(cos));
}
let mut copy = cos.clone();
- pdfcraft_forms::clear_password_values(&mut copy).map_err(|e| EditError::Write(e.to_string()))?;
+ if has_form_pw {
+ pdfcraft_forms::clear_password_values(&mut copy).map_err(|e| EditError::Write(e.to_string()))?;
+ }
+ if has_xfa_pw {
+ pdfcraft_xfa::clear_password_values(&mut copy).map_err(|e| EditError::Write(e.to_string()))?;
+ }
Ok(std::borrow::Cow::Owned(copy))
}
@@ -4516,11 +4524,15 @@ impl Session {
// An encrypted file needs the password it is protected with now (the owner
// password when known, so saving never downgrades this session's rights).
let keys = editor.keys.clone();
- // The saved file carries no Password-field values (#3943); the open document keeps them.
+ // The saved file carries no Password-field values (#3943, #3944); the open document keeps them.
let typed = pdfcraft_forms::password_values(&editor.cos);
editor.cos =
pdfcraft_cos::Document::open_with_password(bytes.clone(), keys.reopen.as_deref()).map_err(|e| EditError::Reopen(e.to_string()))?;
pdfcraft_forms::restore_password_values(&mut editor.cos, &typed).map_err(|e| EditError::Reopen(e.to_string()))?;
+ if !typed.is_empty() && doc.info.xfa.is_some() {
+ let mut datasets = None;
+ let _ = xfa_sync_datasets(&mut editor.cos, doc.xfa_template.as_deref(), &mut datasets);
+ }
editor.saved = bytes;
editor.saved_keys = keys;
editor.unsaved_file = false;
@@ -5125,17 +5137,18 @@ impl Session {
let mut out = Vec::new();
for d in &mut self.docs {
if d.dirty && d.generation != d.snapshot_generation {
- // The working bytes hold typed Password-field values (#3926): a recovery file is
- // written from a copy without them, and none is written if that copy fails.
- let bytes = match d.editor.as_ref().filter(|e| pdfcraft_forms::has_password_values(&e.cos)) {
- Some(e) => match writable(&e.cos)
- .and_then(|c| write_incremental(&c, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string())))
- {
- Ok(b) => Arc::new(b),
- Err(_) => continue,
- },
- None => d.bytes.clone(),
- };
+ // The working bytes hold typed Password-field values (#3926, #3944): a recovery file
+ // is written from a copy without them, and none is written if that copy fails.
+ let bytes =
+ match d.editor.as_ref().filter(|e| pdfcraft_forms::has_password_values(&e.cos) || pdfcraft_xfa::has_password_values(&e.cos)) {
+ Some(e) => match writable(&e.cos)
+ .and_then(|c| write_incremental(&c, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string())))
+ {
+ Ok(b) => Arc::new(b),
+ Err(_) => continue,
+ },
+ None => d.bytes.clone(),
+ };
d.snapshot_generation = d.generation;
out.push(RecoverySnapshot {
doc: d.id,
diff --git a/crates/engine/src/optimizer.rs b/crates/engine/src/optimizer.rs
index a3becf514..42af737ba 100644
--- a/crates/engine/src/optimizer.rs
+++ b/crates/engine/src/optimizer.rs
@@ -87,8 +87,9 @@ impl OptimizeJob {
fn work(self, progress: &mut dyn FnMut(OptimizeStage) -> bool) -> Result<Optimized, EditError> {
let OptimizeJob { mut cos, settings, discard, opts } = self;
- // Like every file written, without the values of Password-flag fields (#3926).
+ // Like every file written, without the values of Password-flag fields (#3926, #3944).
pdfcraft_forms::clear_password_values(&mut cos).map_err(|e| EditError::Write(e.to_string()))?;
+ pdfcraft_xfa::clear_password_values(&mut cos).map_err(|e| EditError::Write(e.to_string()))?;
let mut step = |stage| if progress(stage) { Ok(()) } else { Err(EditError::Cancelled) };
step(OptimizeStage::Discarding)?;
let discarded = if discard.is_empty() { Vec::new() } else { pdfcraft_redact::sanitize::remove_hidden(&mut cos, &discard)? };
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index c87b7cbc7..ba6f2c1c7 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -2284,6 +2284,82 @@ fn a_signed_file_carries_no_password_field_value() {
assert!(!appears_in_pdf(&signed, "*******"), "nor the typed length");
}
+/// #3944: a value typed into an XFA `<passwordEdit/>` field stays in the open document (both the
+/// widget and the live XFA datasets, even across multiple edits and across Save + `mark_saved`),
+/// but is written to no file — neither on the widget nor in the XFA datasets stream.
+#[test]
+fn xfa_password_field_values_are_not_saved_in_datasets_or_widgets() {
+ let xfa_pdf = pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::fields_template(""));
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("xfa.pdf", None, Arc::new(xfa_pdf), None).unwrap();
+ let pin_name = s.get(id).unwrap().form.iter().find(|f| f.name.contains("pin")).unwrap().name.clone();
+
+ // Edit the password twice so an earlier edit's datasets stream could not linger in the overlay.
+ s.apply(id, Edit::SetFieldValue { name: pin_name.clone(), value: FieldValue::Text("secret1".into()) }).unwrap();
+ s.apply(id, Edit::SetFieldValue { name: pin_name.clone(), value: FieldValue::Text("hunter2".into()) }).unwrap();
+
+ let field = s.get(id).unwrap().form.iter().find(|f| f.name == pin_name).cloned().unwrap();
+ assert!(field.has(pdfcraft_forms::flags::PASSWORD));
+ assert_eq!(field.value, vec!["hunter2".to_string()], "the open document keeps the value");
+ assert!(appears_in_pdf(&s.get(id).unwrap().bytes, "hunter2"), "the working bytes hold the live datasets");
+ assert!(!appears_in_pdf(&s.get(id).unwrap().bytes, "secret1"), "the first edit's datasets stream was replaced in place");
+
+ let saved = s.save_bytes(id).unwrap();
+ for leak in ["hunter2", "secret1", "*******"] {
+ assert!(!appears_in_pdf(&saved, leak), "Save leaked {leak}");
+ assert!(!appears_in_pdf(&s.save_full_bytes(id).unwrap(), leak), "save_full_bytes leaked {leak}");
+ assert!(!appears_in_pdf(&s.reduced_bytes(id).unwrap().0, leak), "reduced_bytes leaked {leak}");
+ }
+ let snaps = s.autosave_snapshots();
+ assert_eq!(snaps.len(), 1);
+ for leak in ["hunter2", "secret1", "*******"] {
+ assert!(!appears_in_pdf(&snaps[0].bytes, leak), "autosave snapshot leaked {leak}");
+ }
+
+ // Reopening the saved file in a new session leaves the password field empty (it does not
+ // repopulate from the XFA datasets on open).
+ let mut t = Session::new();
+ let reopened = t.open("saved.pdf", None, saved.clone(), None).unwrap();
+ assert!(
+ t.get(reopened).unwrap().form.iter().find(|f| f.name == pin_name).unwrap().value.iter().all(|v| v.is_empty()),
+ "reopened XFA form must have an empty password field"
+ );
+
+ // Recording the save keeps the typed password in the open document (and its live datasets),
+ // while a subsequent save still omits it.
+ s.mark_saved(id, saved, Some("saved.pdf".into())).unwrap();
+ assert_eq!(s.get(id).unwrap().form.iter().find(|f| f.name == pin_name).unwrap().value, ["hunter2"]);
+ assert!(!s.get(id).unwrap().dirty);
+ for leak in ["hunter2", "secret1", "*******"] {
+ assert!(!appears_in_pdf(&s.save_bytes(id).unwrap(), leak), "save after mark_saved leaked {leak}");
+ }
+
+ // Undo past `mark_saved` and edit again: the datasets stream in the restored overlay is
+ // overwritten in place rather than left behind.
+ s.undo(id).unwrap();
+ s.apply(id, Edit::SetFieldValue { name: pin_name.clone(), value: FieldValue::Text("secret3".into()) }).unwrap();
+ let saved_after_undo = s.save_bytes(id).unwrap();
+ for leak in ["hunter2", "secret1", "secret3", "*******"] {
+ assert!(!appears_in_pdf(&saved_after_undo, leak), "save after undo leaked {leak}");
+ }
+
+ // A relayout (`rerender`) after typing a password frees the replaced generated widget and its
+ // masked appearance stream so neither remains in the overlay when saving.
+ let relayout_xml = pdfcraft_xfa::fixtures::fields_template("").replace(
+ r#"<subform name="page1" layout="tb">"#,
+ r#"<subform name="page1" layout="tb"><field name="grow" w="2in"><ui><textEdit multiLine="1"/></ui></field>"#,
+ );
+ let id2 = s.open("relayout.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&relayout_xml)), None).unwrap();
+ let pin2 = s.get(id2).unwrap().form.iter().find(|f| f.name.contains("pin")).unwrap().name.clone();
+ let grow2 = s.get(id2).unwrap().form.iter().find(|f| f.name.contains("grow")).unwrap().name.clone();
+ s.apply(id2, Edit::SetFieldValue { name: pin2, value: FieldValue::Text("s3cr3t!".into()) }).unwrap();
+ s.apply(id2, Edit::SetFieldValue { name: grow2, value: FieldValue::Text("line1\nline2\nline3\nline4\nline5".into()) }).unwrap();
+ let saved_relayout = s.save_bytes(id2).unwrap();
+ for leak in ["s3cr3t!", "*******"] {
+ assert!(!appears_in_pdf(&saved_relayout, leak), "save after relayout leaked {leak}");
+ }
+}
+
/// A value its field's font can't draw is kept, and the edit that drew it reports it in
/// `edit_notices` (the interface shows it, tools return it): not a later unrelated edit, not a
/// failed one, and not a value that can be drawn. The form (an inline AcroForm here) asks other
diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs
index fc10e30eb..2354d69f6 100644
--- a/crates/forms/src/lib.rs
+++ b/crates/forms/src/lib.rs
@@ -1253,6 +1253,7 @@ fn redraw(doc: &mut Document, f: &Field, values: &[String], scripts: &mut dyn Sc
[one] if matches!(f.kind, FieldKind::Text | FieldKind::Combo) => scripting::formatted(doc, f, one, scripts),
_ => None,
};
+ let in_place = f.kind == FieldKind::Text && f.has(flags::PASSWORD);
let mut undrawn = false;
for w in &f.widgets {
let (stream, missing) = match &shown {
@@ -1260,7 +1261,23 @@ fn redraw(doc: &mut Document, f: &Field, values: &[String], scripts: &mut dyn Sc
None => appearance::field_appearance_drawn(doc, f, w, values, true),
};
undrawn |= missing.is_some();
- let ap = doc.add(Object::Stream(stream));
+ let existing_ap = in_place
+ .then(|| {
+ doc.get(w.obj)
+ .as_dict()
+ .and_then(|d| d.get(b"AP").map(|a| doc.resolve(a)))
+ .and_then(|a| a.as_dict().and_then(|a| a.get(b"N").cloned()))
+ .and_then(|n| n.as_ref())
+ .filter(|r| doc.is_edited(r.num) && matches!(&*doc.get(*r), Object::Stream(_)))
+ })
+ .flatten();
+ let ap = match existing_ap {
+ Some(r) => {
+ doc.set(r, Object::Stream(stream));
+ r
+ }
+ None => doc.add(Object::Stream(stream)),
+ };
let mut fresh = Dict::new();
fresh.set(b"N".to_vec(), Object::Ref(ap));
let apd = merged_appearance(doc, w.obj, &fresh);
diff --git a/crates/xfa/src/data.rs b/crates/xfa/src/data.rs
index 95f59a44b..eac2f20bf 100644
--- a/crates/xfa/src/data.rs
+++ b/crates/xfa/src/data.rs
@@ -12,7 +12,7 @@ use std::collections::HashMap;
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};
use crate::XfaError;
-use crate::model::{Field, Node, SomIndices, Template};
+use crate::model::{Field, Node, SomIndices, Template, Ui};
use crate::packets::{Encoding, encode};
const XFA_DATA_NS: &str = "http://www.xfa.org/schema/xfa-data/1.0/";
@@ -1630,11 +1630,11 @@ pub fn write_data_ops(doc: &mut Document, ops: &[DataOp], reuse: Option<ObjRef>)
}
/// Put `bytes` in the document as a datasets stream: in place of `old` when that is the stream
-/// `reuse`, else as a new object.
+/// `reuse` or already an unsaved overlay stream of `doc`, else as a new object.
fn put_stream(doc: &mut Document, old: Option<&Object>, reuse: Option<ObjRef>, bytes: &[u8]) -> ObjRef {
let stream = Object::Stream(Stream::flate(Dict::new(), bytes));
- match (old.and_then(Object::as_ref), reuse) {
- (Some(r), Some(keep)) if r == keep => {
+ match old.and_then(Object::as_ref) {
+ Some(r) if reuse == Some(r) || doc.is_edited(r.num) => {
doc.set(r, stream);
r
}
@@ -1794,3 +1794,210 @@ pub fn is_on(text: &str, on: &str) -> bool {
}
!matches!(t.to_ascii_lowercase().as_str(), "" | "0" | "off" | "false" | "no") && on.trim().is_empty()
}
+
+/// The datasets stream's object reference in `doc` (the `datasets` item in the `/XFA` array, or
+/// the single `/XFA` stream), when `doc` has one.
+fn datasets_stream_ref(doc: &Document) -> Option<ObjRef> {
+ let root = doc.root()?;
+ let catalog = doc.get(root);
+ let acro = catalog.as_dict()?.get(b"AcroForm").map(|a| doc.resolve(a))?;
+ let xfa = acro.as_dict()?.get(b"XFA")?;
+ match &*doc.resolve(xfa) {
+ Object::Array(items) => {
+ let at = (0..items.len())
+ .step_by(2)
+ .find(|&i| items.get(i).and_then(|n| n.as_string()).is_some_and(|s| s.to_text() == "datasets") && i + 1 < items.len())?;
+ items.get(at + 1)?.as_ref()
+ }
+ Object::Stream(_) => xfa.as_ref(),
+ _ => None,
+ }
+}
+
+/// The SOM path and default value of every AcroForm text field with the Password flag (bit 14,
+/// `1 << 13`) in `doc`, for static XFA forms whose password fields set the flag in the AcroForm
+/// dictionary.
+fn acro_password_fields(doc: &Document) -> Vec<(String, String)> {
+ const PASSWORD_FLAG: i64 = 1 << 13;
+ let Some(root) = doc.root() else { return Vec::new() };
+ let catalog = doc.get(root);
+ let Some(acro) = catalog.as_dict().and_then(|c| c.get(b"AcroForm")).map(|a| doc.resolve(a)) else { return Vec::new() };
+ let Some(top) = acro.as_dict().and_then(|a| a.get(b"Fields")).map(|f| doc.resolve(f)).and_then(|f| f.as_array().cloned()) else {
+ return Vec::new();
+ };
+ struct AcroWalk<'a> {
+ doc: &'a Document,
+ seen: std::collections::HashSet<ObjRef>,
+ out: Vec<(String, String)>,
+ }
+ impl AcroWalk<'_> {
+ fn walk(
+ &mut self,
+ items: &[Object],
+ parent_name: &str,
+ inherited_ft: Option<&[u8]>,
+ inherited_ff: i64,
+ inherited_dv: Option<&str>,
+ depth: usize,
+ ) {
+ if depth > 32 {
+ return;
+ }
+ for item in items {
+ let Some(r) = item.as_ref() else { continue };
+ if !self.seen.insert(r) {
+ continue;
+ }
+ let obj = self.doc.get(r);
+ let Some(d) = obj.as_dict() else { continue };
+ let ft = d.name(b"FT").or(inherited_ft);
+ let ff = d.int(b"Ff").unwrap_or(inherited_ff);
+ let dv_own = text_of(self.doc, d, b"DV");
+ let dv = dv_own.as_deref().or(inherited_dv);
+ let t = text_of(self.doc, d, b"T");
+ let full_name = match (&t, parent_name.is_empty()) {
+ (Some(seg), true) => seg.clone(),
+ (Some(seg), false) => format!("{parent_name}.{seg}"),
+ (None, _) => parent_name.to_string(),
+ };
+ let kids = d.get(b"Kids").map(|k| self.doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default();
+ let has_named_kid = kids.iter().filter_map(Object::as_ref).any(|kr| self.doc.get(kr).as_dict().is_some_and(|kd| kd.contains(b"T")));
+ if !has_named_kid && ft == Some(b"Tx") && (ff & PASSWORD_FLAG) != 0 {
+ let som = text_of(self.doc, d, crate::pdf::SOM_KEY).unwrap_or_else(|| full_name.clone());
+ if !som.is_empty() {
+ self.out.push((som, dv.unwrap_or_default().to_string()));
+ }
+ }
+ if !kids.is_empty() {
+ self.walk(&kids, &full_name, ft, ff, dv, depth + 1);
+ }
+ }
+ }
+ }
+ let mut w = AcroWalk { doc, seen: std::collections::HashSet::new(), out: Vec::new() };
+ w.walk(&top, "", None, 0, None, 0);
+ w.out
+}
+
+/// The `Want` entries needed to restore password fields in `doc`'s datasets packet to their
+/// defaults (or empty when they have no default).
+fn password_dataset_wants(doc: &Document) -> Vec<Want> {
+ if datasets_stream_ref(doc).is_none() {
+ return Vec::new();
+ }
+ let Ok(Some(packet)) = datasets_packet(doc) else { return Vec::new() };
+ let Some(data) = parse_datasets(&packet) else { return Vec::new() };
+ with_template(doc, None, |tpl| {
+ let mut candidates: Vec<(String, DataPath, String)> = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ if let Some(t) = tpl {
+ struct Walk<'a> {
+ tpl: &'a Template,
+ data: &'a DataNode,
+ nodes: usize,
+ seen: &'a mut std::collections::HashSet<DataPath>,
+ out: &'a mut Vec<(String, DataPath, String)>,
+ }
+ impl Walk<'_> {
+ fn child_som(parent: &str, name: Option<&str>, index: usize) -> String {
+ match name {
+ Some(n) if !parent.is_empty() => format!("{parent}.{n}[{index}]"),
+ Some(n) => format!("{n}[{index}]"),
+ None => parent.to_string(),
+ }
+ }
+ fn walk(&mut self, children: &[Node], parent_som: &str, depth: usize) {
+ if depth > MAX_DEPTH || self.nodes >= crate::script::MAX_FORM_NODES {
+ return;
+ }
+ let sibs = SomIndices::of(children);
+ for (i, n) in children.iter().enumerate() {
+ if self.nodes >= crate::script::MAX_FORM_NODES {
+ break;
+ }
+ self.nodes += 1;
+ let sib = sibs.at(i);
+ match n {
+ Node::Subform(sf) => {
+ let from_data = match &sf.common.name {
+ Some(name) if sf.occur.max != Some(1) => self.data.count(&data_path(self.tpl, parent_som), name),
+ _ => 0,
+ };
+ let instances = crate::layout::instance_count(&sf.occur, from_data).max(from_data);
+ for k in 0..instances {
+ if k > 0 {
+ if self.nodes >= crate::script::MAX_FORM_NODES {
+ break;
+ }
+ self.nodes += 1;
+ }
+ let som = Self::child_som(parent_som, sf.common.name.as_deref(), sib + k);
+ self.walk(&sf.children, &som, depth + 1);
+ }
+ }
+ Node::Area(a) => {
+ let som = Self::child_som(parent_som, a.common.name.as_deref(), sib);
+ self.walk(&a.children, &som, depth + 1);
+ }
+ Node::Field(f) if f.ui == Ui::PasswordEdit => {
+ let som = Self::child_som(parent_som, f.common.name.as_deref().or(Some("field")), sib);
+ let path = data_path(self.tpl, &som);
+ if !path.is_empty() && self.seen.insert(path.clone()) {
+ let default = f.value.plain().map(|v| f.saved_value(v.trim())).unwrap_or_default();
+ self.out.push((som, path, default));
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+ let root = Node::Subform(Box::new(t.root.clone()));
+ let mut w = Walk { tpl: t, data: &data, nodes: 0, seen: &mut seen, out: &mut candidates };
+ w.walk(std::slice::from_ref(&root), "", 0);
+ if let Some(ps) = &t.root.page_set {
+ for (i, area) in ps.areas.iter().enumerate() {
+ let som = area.name.clone().map(|n| format!("{n}[0]")).unwrap_or_else(|| format!("#pageArea[{i}]"));
+ w.walk(&area.items, &som, 1);
+ }
+ }
+ }
+ for (som, default) in acro_password_fields(doc) {
+ let path = path_of(tpl, &som);
+ if !path.is_empty() && seen.insert(path.clone()) {
+ candidates.push((som, path, default));
+ }
+ }
+ candidates
+ .into_iter()
+ .filter_map(|(som, path, default)| {
+ let cur = data.value_at(&path)?;
+ (!cur.is_empty() && cur != default).then_some(Want { som, path, text: default, ensure: false })
+ })
+ .collect()
+ })
+}
+
+/// Whether any XFA password field (`<passwordEdit/>` or an AcroForm text field with the Password
+/// flag) holds a value in `doc`'s datasets packet beyond its default (#3944).
+pub fn has_password_values(doc: &Document) -> bool {
+ !password_dataset_wants(doc).is_empty()
+}
+
+/// Clear typed password values from `doc`'s XFA datasets packet (restoring a template default
+/// where the field has one, else emptying the element), replacing the datasets stream in place
+/// (#3944). Returns how many password fields were cleared in the datasets.
+pub fn clear_password_values(doc: &mut Document) -> Result<usize, XfaError> {
+ let wants = password_dataset_wants(doc);
+ if wants.is_empty() {
+ return Ok(0);
+ }
+ let count = wants.len();
+ let reuse = datasets_stream_ref(doc);
+ let report = rewrite(doc, &[Op::Values(&wants)], reuse)?;
+ if !report.written || !password_dataset_wants(doc).is_empty() {
+ let reason = report.warnings.first().map_or("the XFA datasets password values could not be cleared", String::as_str);
+ return Err(XfaError::Malformed(reason.to_string()));
+ }
+ Ok(count)
+}
diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs
index 7fe372d53..41a250a54 100644
--- a/crates/xfa/src/lib.rs
+++ b/crates/xfa/src/lib.rs
@@ -92,9 +92,9 @@ pub(crate) fn xml_nesting_depth(text: &str) -> usize {
pub use data::{DataImport, ImportNode, export_data, import_data, parse_data_file, write_data_image};
pub use data::{
- DataNode, DataOp, DataPath, DatasetsWrite, FieldData, FieldDatum, add_data_instances, build_data, data_path, iso_to_pattern, parse_datasets,
- pattern_to_iso, read_values, read_values_with, remove_data_instance, som_to_path, write_data_ops, write_data_value, write_datasets,
- write_datasets_reusing, write_datasets_with,
+ DataNode, DataOp, DataPath, DatasetsWrite, FieldData, FieldDatum, add_data_instances, build_data, clear_password_values, data_path,
+ has_password_values, iso_to_pattern, parse_datasets, pattern_to_iso, read_values, read_values_with, remove_data_instance, som_to_path,
+ write_data_ops, write_data_value, write_datasets, write_datasets_reusing, write_datasets_with,
};
pub use layout::{Action, BorderShape, Form, Item, MAX_PAGES, Page, Widget, WidgetKind, formatted_value, layout};
pub use packets::{Encoding, Packets, decode as decode_packet, encode as encode_packet, read_packets};
diff --git a/crates/xfa/src/script.rs b/crates/xfa/src/script.rs
index d330c2a64..80fb1db33 100644
--- a/crates/xfa/src/script.rs
+++ b/crates/xfa/src/script.rs
@@ -586,12 +586,44 @@ pub fn rerender(doc: &mut Document, tpl: &Template) -> Result<Report, XfaError>
if form.pages.is_empty() {
return Err(XfaError::Malformed("the template laid out to no pages".into()));
}
- // The AcroForm keeps only the fields PdfCraft did not generate.
+ // The AcroForm keeps only the fields PdfCraft did not generate. Any generated fields edited in
+ // this overlay (along with their appearance streams and widget kids) are freed so a replaced
+ // password widget's value or masked appearance cannot stay in the overlay.
let Some(root) = doc.root() else { return Err(XfaError::NotXfa) };
if let Some((acro_ref, mut acro)) = acroform(doc) {
let fields = acro.get(b"Fields").map(|f| doc.resolve(f)).and_then(|f| f.as_array().cloned()).unwrap_or_default();
- let kept: Vec<Object> =
- fields.into_iter().filter(|f| f.as_ref().is_none_or(|r| doc.get(r).as_dict().is_none_or(|d| !d.contains(crate::pdf::SOM_KEY)))).collect();
+ let mut kept = Vec::new();
+ let free_ap = |doc: &mut Document, d: &Dict| {
+ if let Some(ap) = d.get(b"AP").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned())
+ && let Some(n) = ap.get(b"N").and_then(Object::as_ref)
+ && doc.is_edited(n.num)
+ {
+ doc.free(n);
+ }
+ };
+ for f in fields {
+ if let Some(r) = f.as_ref()
+ && let Some(d) = doc.get(r).as_dict().cloned()
+ && d.contains(crate::pdf::SOM_KEY)
+ {
+ free_ap(doc, &d);
+ if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) {
+ for k in kids.iter().filter_map(Object::as_ref) {
+ if let Some(kd) = doc.get(k).as_dict().cloned() {
+ free_ap(doc, &kd);
+ }
+ if doc.is_edited(k.num) {
+ doc.free(k);
+ }
+ }
+ }
+ if doc.is_edited(r.num) {
+ doc.free(r);
+ }
+ } else {
+ kept.push(f);
+ }
+ }
acro.set(b"Fields".to_vec(), Object::Array(kept));
match acro_ref {
Some(r) => doc.set(r, Object::Dict(acro)),
diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs
index f0e6816c2..cb106de84 100644
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@ -3791,3 +3791,69 @@ fn faces_measure_text_at_their_standard_14_widths() {
let condensed = text::Face { h_scale: 0.8, ..face(text::Family::Times, true, false) };
assert!((condensed.width(sample) - 0.8 * Std14::TimesBold.text_width(sample, 10.0)).abs() < 1e-9);
}
+
+/// #3944: clearing XFA password values removes values typed into `<passwordEdit/>` fields from the
+/// datasets packet (including across repeating subforms), restores a field's template default
+/// `<value><text>…</text></value>` when it has one, and replaces the datasets stream in place so
+/// the typed password is not left in an unreferenced stream in the overlay.
+#[test]
+fn clear_password_values_removes_typed_passwords_from_datasets_in_place() {
+ let xdp = r#"<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
+<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
+<subform name="form" layout="tb">
+ <pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
+ <subform name="page1" layout="tb">
+ <field name="user" w="2in" h="0.3in"><ui><textEdit/></ui></field>
+ <field name="pin" w="2in" h="0.3in"><ui><passwordEdit/></ui></field>
+ <field name="preset" w="2in" h="0.3in"><ui><passwordEdit/></ui><value><text>0000</text></value></field>
+ <subform name="row" layout="lr-tb"><occur min="1" max="-1"/>
+ <field name="secret" w="2in" h="0.3in"><ui><passwordEdit/></ui></field>
+ </subform>
+ </subform>
+</subform>
+</template>
+<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
+<xfa:data><form><page1><user>Ada</user><pin>hunter2</pin><preset>9999</preset><row><secret>first</secret></row><row><secret>second</secret></row></page1></form></xfa:data>
+</xfa:datasets>
+</xdp:xdp>"#;
+ let mut doc = Document::open(Arc::new(shell(xdp))).unwrap();
+ render_into(&mut doc).unwrap();
+ assert!(has_password_values(&doc));
+ let cleared = clear_password_values(&mut doc).unwrap();
+ assert_eq!(cleared, 4);
+ assert!(!has_password_values(&doc), "only default and non-password values remain");
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 0);
+
+ let packets = read_packets(&doc).unwrap().unwrap();
+ assert!(packets.xdp.contains("<user>Ada</user>"), "non-password fields stay: {}", packets.xdp);
+ assert!(packets.xdp.contains("<preset>0000</preset>"), "template default restored: {}", packets.xdp);
+ for secret in ["hunter2", "9999", "first", "second"] {
+ assert!(!packets.xdp.contains(secret), "{secret} still in datasets: {}", packets.xdp);
+ }
+ let written = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ let reopened = Document::open(Arc::new(written)).unwrap();
+ for num in reopened.object_numbers() {
+ if let Object::Stream(st) = &*reopened.get(pdfcraft_cos::ObjRef::new(num, 0)) {
+ let decoded = st.decoded().unwrap_or_default();
+ let text = String::from_utf8_lossy(&decoded);
+ for secret in ["hunter2", "9999", "first", "second"] {
+ assert!(!text.contains(secret), "object {num} still holds {secret}: {text}");
+ }
+ }
+ }
+}
+
+/// #3944: a static XFA form whose AcroForm field sets the Password flag (`/Ff 8192`) also has its
+/// typed value cleared from the datasets packet.
+#[test]
+fn clear_password_values_clears_static_xfa_password_fields() {
+ let pdf = String::from_utf8(static_shell("<form1><page1><name>hunter2</name></page1></form1>"))
+ .unwrap()
+ .replace("/T (name[0])", "/T (name[0]) /Ff 8192");
+ let mut doc = Document::open(Arc::new(pdf.into_bytes())).unwrap();
+ assert!(has_password_values(&doc));
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 1);
+ assert!(!has_password_values(&doc));
+ let packets = read_packets(&doc).unwrap().unwrap();
+ assert!(!packets.xdp.contains("hunter2"), "{}", packets.xdp);
+}