From 0fcb49aab536a18de34c1107a823cec57877d7b5 Mon Sep 17 00:00:00 2001 From: kavishkashehan726-sudo <260480244+kavishkashehan726-sudo@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:01:15 +0000 Subject: [PATCH] fix(engine): validate signed XFA forms as the file was read (#2759) Opening an XFA form appends PdfCraft's own revisions to the working file: the dynamic layout, the field values taken from the XFA data, and what the open scripts change. Signatures were then validated against that working file, so a certified (DocMDP P=2) form opened untouched was reported invalid, "altered since signed (pages added or removed, comments)", before the user had changed anything. This is the symptom the IRCC IMM forms show. Keep the file as read for a signed document whose opening appended revisions, and validate the signatures against it while the working state is still just the opened one: on open, on trust changes, after undo back to it, and after Revert. Once the user edits or saves, the file Save writes is judged as before, open-time revisions included, so the verdict never hides what saving will write. Part of storytold/pdfcraft#2759: the false "altered" on open. The trust lists and TSA trust it also asks for are separate problems. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AFWmxuUvJ4qW6tMcBHs1XJ --- crates/engine/src/lib.rs | 54 +++++++++++++++++++++++++------ crates/engine/src/tests.rs | 63 ++++++++++++++++++++++++++++++++++++ parity/acrobat-features.toml | 4 +-- 3 files changed, 109 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3432cd868e..79513a0108 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -315,6 +315,17 @@ struct Editor { appearances: AppearanceCache, /// The text blocks last computed for one page, reused while the document is unchanged. text_blocks: TextBlocksCache, + /// A signed file that opening appended revisions to (an XFA form's layout, the values from + /// its data, its open scripts): the file as it was read, which the signatures are validated + /// against until the user changes something or saves (#2759). + as_opened: Option, +} + +/// The file as read, before opening appended PdfCraft's own revisions to it. +#[derive(Clone)] +struct AsOpened { + cos: pdfcraft_cos::Document, + bytes: Arc>, } /// One page's text blocks ([`pdfcraft_edit::text_blocks`]) and the unmodified document state they @@ -3211,9 +3222,16 @@ fn xfa_values_from_datasets(doc: &mut pdfcraft_cos::Document) -> Result Vec { - pdfcraft_sign::pdf::list_cached(cos, bytes, trust, cache) +/// Validate the signature fields of the editor's working state (written as `bytes`). While that +/// state is still the file as opened plus only what opening appended, the file as read is +/// validated instead: PdfCraft's own open-time revisions are not changes made since signing. +fn signatures_of(editor: &Editor, bytes: &[u8], trust: &TrustStore, cache: &pdfcraft_sign::DigestCache) -> Vec { + match &editor.as_opened { + Some(o) if !editor.cos.is_modified() && Arc::ptr_eq(editor.cos.bytes(), &editor.saved) => { + pdfcraft_sign::pdf::list_cached(&o.cos, &o.bytes, trust, cache) + } + _ => pdfcraft_sign::pdf::list_cached(&editor.cos, bytes, trust, cache), + } } impl Session { @@ -3351,6 +3369,11 @@ impl Session { } Err(e) => return Err(e), }; + // The file as read, for its signatures: opening an XFA form may append revisions below. + let as_read = match (&info.xfa, &cos) { + (Some(_), Ok(Ok(c))) => Some(AsOpened { cos: c.clone(), bytes: bytes.clone() }), + _ => None, + }; // A dynamic XFA form is a shell around an XML template; lay the template out into real // pages and fields so the rest of the engine works on it. The original bytes stay: the // laid-out form is one appended revision. @@ -3491,7 +3514,8 @@ impl Session { }; // XFA notes survive the document being re-read after edits. let xfa_warnings: Vec = if info.xfa.is_some() { info.warnings.clone() } else { Vec::new() }; - let mut document = Self::build_document(&context.trust, name, path, bytes, info, cos, render_password, password, xfa); + let as_opened = as_read.filter(|o| !Arc::ptr_eq(&o.bytes, &bytes)); + let mut document = Self::build_document(&context.trust, name, path, bytes, info, cos, render_password, password, xfa, as_opened); // A script that ran away on open turns the form's scripts off for this document. document.xfa_template = if ran_away { None } else { xfa_template }; document.js_output.append(script_output); @@ -3515,6 +3539,7 @@ impl Session { render_password: Option, password: Option<&str>, xfa: Option, + as_opened: Option, ) -> Document { let config = RenderConfig { password: render_password.as_deref().map(Arc::from), ..Default::default() }; let (mut editor, read_only_reason) = match cos { @@ -3531,6 +3556,7 @@ impl Session { keys, appearances: AppearanceCache::default(), text_blocks: TextBlocksCache::default(), + as_opened, }), None, ) @@ -3539,7 +3565,13 @@ impl Session { Err(_) => (None, Some("the document structure could not be read for editing".into())), }; let sig_cache = Arc::new(pdfcraft_sign::DigestCache::default()); - let signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, trust, &sig_cache)).unwrap_or_default(); + let signatures = editor.as_ref().map(|e| signatures_of(e, &bytes, trust, &sig_cache)).unwrap_or_default(); + // Only a signed file needs keeping as it was read. + if !signatures.iter().any(|s| s.signed) + && let Some(e) = editor.as_mut() + { + e.as_opened = None; + } let display = display_bytes(editor.as_mut(), &bytes); let renderer = RenderPool::new(display.clone(), render_threads(), config.clone()); let (form, adopted) = editor @@ -3875,7 +3907,7 @@ impl Session { doc.info.producer = info("Producer"); doc.info.file_size = bytes.len(); if !doc.signatures.is_empty() { - let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache); + let signatures = signatures_of(editor, &bytes, &doc.trust, &doc.sig_cache); doc.signatures = Arc::new(signatures); } doc.bytes = bytes; @@ -3919,7 +3951,7 @@ impl Session { } doc.info.file_size = bytes.len(); doc.form = form; - let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) }; + let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(editor, &bytes, &doc.trust, &doc.sig_cache) }; doc.display = display_bytes(Some(editor), &bytes); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone()); @@ -3964,7 +3996,7 @@ impl Session { doc.marker_scan = OnceLock::new(); } doc.info.file_size = bytes.len(); - let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) }; + let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(editor, &bytes, &doc.trust, &doc.sig_cache) }; doc.display = display_bytes(Some(editor), &bytes); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone()); @@ -4039,7 +4071,7 @@ impl Session { if invalidate_links { doc.links = OnceLock::new(); } - let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache); + let signatures = signatures_of(editor, &bytes, &doc.trust, &doc.sig_cache); doc.display = display_bytes(Some(editor), &bytes); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone()); @@ -4108,6 +4140,8 @@ impl Session { pdfcraft_cos::Document::open_with_password(bytes.clone(), keys.reopen.as_deref()).map_err(|e| EditError::Reopen(e.to_string()))?; editor.saved = bytes; editor.saved_keys = keys; + // The saved file holds what opening appended: from now on it is the file. + editor.as_opened = None; } if let Some(p) = path { doc.name = std::path::Path::new(&p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.clone()); @@ -4783,7 +4817,7 @@ impl Session { let Some(editor) = doc.editor.as_mut() else { continue }; // Keep verdict refresh and renderer refresh together. Viewer caches are // invalidated by the UI trust path; trust alone changes no document artwork. - let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &doc.bytes, &doc.trust, &doc.sig_cache) }; + let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(editor, &doc.bytes, &doc.trust, &doc.sig_cache) }; doc.display = display_bytes(Some(editor), &doc.bytes); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ec305b1ca5..9cb4181d7f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5801,3 +5801,66 @@ fn cropping_an_existing_image_clips_it_and_moves_with_it() { // No area, or a box off the image, is refused. assert!(s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Crop([10.0, 10.0, 10.0, 50.0]) }).is_err()); } + +/// A certified (DocMDP P=2) form, as a certifying application leaves it: signed over the whole +/// file, with nothing appended. +fn certified_xfa(original: &[u8]) -> Arc> { + let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap(); + let id = sign::pkcs12::open(&p12, "test").unwrap(); + let cos = pdfcraft_cos::Document::open(Arc::new(original.to_vec())).unwrap(); + let opts = SignOptions { certify: Some(2), date: "D:20270115080000Z".into(), ..SignOptions::default() }; + Arc::new(sign::sign(&cos, &id, &opts).unwrap()) +} + +/// What opening an XFA form writes (its layout, the values from its data, its open scripts) is +/// PdfCraft's own working revision, not a change to the file: a certified government form +/// opened untouched is not "altered since it was signed" (#2759). Once the user changes it, or +/// saves, the file Save writes is what is judged, open-time revisions included. +#[test] +fn certified_xfa_forms_open_unaltered() { + let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap(); + let signer = sign::pkcs12::open(&p12, "test").unwrap().certificate; + let forms = [ + // Laying the template out adds pages: a change the certification doesn't permit. + ("dynamic", pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::template(3)), "familyName", sign::kind::PAGES), + // Taking the values from the data fills the fields: a permitted change. + ( + "static", + pdfcraft_xfa::fixtures::static_shell("Ada1"), + "form1[0].page1[0].name[0]", + sign::kind::FORM_FILL, + ), + ]; + for (what, form, field, saved_kind) in forms { + let certified = certified_xfa(&form); + let mut s = Session::new().with_clock(|| 1_800_000_000); + let id = s.open("imm.pdf", None, certified.clone(), None).expect("opens"); + let doc = s.get(id).unwrap(); + assert!(doc.bytes.len() > certified.len() && !doc.dirty, "{what}: opening wrote a working revision, not an edit"); + let verdict = |s: &Session| { + let sig = s.get(id).unwrap().signatures[0].clone(); + (sig.status, sig.modification) + }; + assert_eq!(s.get(id).unwrap().signatures[0].certify, Some(2), "{what}"); + assert_eq!(verdict(&s), (SignatureStatus::Unknown, sign::Modification::None), "{what}: {:?}", s.get(id).unwrap().signatures[0].details); + // Trusting the signer revalidates the file as opened too. + s.set_trusted_certificates(vec![signer.clone()]); + assert_eq!(verdict(&s), (SignatureStatus::Valid, sign::Modification::None), "{what}"); + // An edit is judged with everything Save would write; undoing it is the file as opened. + s.apply(id, Edit::SetFieldValue { name: field.into(), value: FieldValue::Text("Singh".into()) }).unwrap(); + assert_ne!(verdict(&s).1, sign::Modification::None, "{what}"); + s.undo(id).unwrap(); + assert_eq!(verdict(&s), (SignatureStatus::Valid, sign::Modification::None), "{what}"); + s.revert(id).unwrap(); + assert_eq!(verdict(&s), (SignatureStatus::Valid, sign::Modification::None), "{what}"); + // Saved, the open-time revision is part of the file. + let saved = s.save_bytes(id).unwrap(); + s.mark_saved(id, saved, None).unwrap(); + let (_, modification) = verdict(&s); + let kinds = match &modification { + sign::Modification::Allowed(k) | sign::Modification::Disallowed(k) => k.clone(), + sign::Modification::None => Vec::new(), + }; + assert!(kinds.contains(&saved_kind), "{what}: {modification:?}"); + } +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index c3d319f94f..4eeda60fb0 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -6188,8 +6188,8 @@ milestone = "M9" status = "shipped" commands = ["sign.validate"] tools = ["sign_list"] -evidence = ["crates/sign/tests/pdf.rs::signing_then_validating_with_and_without_trust", "crates/automation/tests/automation.rs::digital_ids_signing_and_validation_through_tools", "crates/sign/tests/chain.rs::a_trusted_signer_whose_certificate_may_not_sign_is_not_valid"] -notes = "The signer's key usage, extended key usage and critical extensions are checked; name constraints are not" +evidence = ["crates/sign/tests/pdf.rs::signing_then_validating_with_and_without_trust", "crates/automation/tests/automation.rs::digital_ids_signing_and_validation_through_tools", "crates/sign/tests/chain.rs::a_trusted_signer_whose_certificate_may_not_sign_is_not_valid", "crates/engine/src/tests.rs::certified_xfa_forms_open_unaltered"] +notes = "The signer's key usage, extended key usage and critical extensions are checked; name constraints are not. A signed XFA form is validated as the file was read: the revisions opening appends (dynamic layout, values from the data, open scripts) are not counted as changes until the user edits or saves (#2759). Still missing: saving a certified dynamic XFA form writes PdfCraft's page layout into the file, which the certification does not permit, so an edited or saved one reports pages added; there are no AATL/EUTL trust lists, so publicly issued signers and timestamp authorities stay unknown until their roots are trusted by hand" [[feature]] id = "sign.signatures-panel"