diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 9ce402e1c2..3204e8795c 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -116,6 +116,21 @@ pub(crate) fn signatures_of( pdfcraft_sign::pdf::list_cached(cos, bytes, trust, cache) } +/// Validate the signature fields of `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. +pub(crate) fn editor_signatures( + editor: &crate::history::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) => signatures_of(&o.cos, &o.bytes, trust, cache), + _ => signatures_of(&editor.cos, bytes, trust, cache), + } +} + /// What Optimize PDF did. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct OptimizeReport { diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 393c233297..7df69f0ac0 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -150,6 +150,17 @@ pub(crate) struct Editor { pub(crate) field_appearances: pdfcraft_forms::FieldAppearanceCache, /// The text blocks last computed for one page, reused while the document is unchanged. pub(crate) 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). + pub(crate) as_opened: Option, +} + +/// The file as read, before opening appended PdfCraft's own revisions to it. +#[derive(Clone)] +pub(crate) struct AsOpened { + pub(crate) cos: pdfcraft_cos::Document, + pub(crate) bytes: Arc>, } /// One page's text blocks ([`pdfcraft_edit::text_blocks`]) and the document state they were read diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6ba67b2b65..fcfc5e6c7c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -192,7 +192,7 @@ pub use pdfcraft_edit::ArrangeOrder; use clock::{local_utc_offset, parse_ymd}; pub use doc_state::{DocId, ImageEdit, OptimizeReport, RecoverySnapshot, SplitPart, guard, merge_data_files}; -use doc_state::{LOW_RESOLUTION_PRINT_DPI, render_threads, renderer_password, signatures_of, writable}; +use doc_state::{LOW_RESOLUTION_PRINT_DPI, editor_signatures, render_threads, renderer_password, signatures_of, writable}; /// The configuration of the pool that draws the viewer: the document's own, plus installed CJK /// fonts for fonts a PDF does not embed (`pdfcraft_render::RenderConfig::system_fonts`). Exports, diff --git a/crates/engine/src/open.rs b/crates/engine/src/open.rs index e5fdc65079..88f894502f 100644 --- a/crates/engine/src/open.rs +++ b/crates/engine/src/open.rs @@ -5,11 +5,11 @@ use std::sync::{Arc, OnceLock}; use pdfcraft_cos::{SaveOptions, write_incremental}; use pdfcraft_render::{DocInfo, OpenError, RenderConfig, RenderPool, inspect}; -use crate::history::{Editor, Keys, TextBlocksCache}; +use crate::history::{AsOpened, Editor, Keys, TextBlocksCache}; use crate::{ - AppearanceCache, DocId, Document, Session, StatusCaptions, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, guard, - info_fields, js, note_warnings, print_preview_layers, recovered_render_password, render_threads, same_pages, signatures_of, xfa, xfa_layout, - xfa_values_from_datasets, + AppearanceCache, DocId, Document, Session, StatusCaptions, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, + editor_signatures, guard, info_fields, js, note_warnings, print_preview_layers, recovered_render_password, render_threads, same_pages, xfa, + xfa_layout, xfa_values_from_datasets, }; /// Immutable session state needed while a document is prepared away from its owning thread. @@ -37,6 +37,8 @@ struct DocumentOpenData<'a> { render_password: Option, password: Option<&'a str>, xfa: Option, + /// The file as read, when opening appended revisions to it ([`crate::history::AsOpened`]). + as_opened: Option, } impl OpenContext { @@ -152,6 +154,11 @@ impl Session { } Ok((new_bytes, new_info, new_cos)) }; + // 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, + }; let (bytes, info, cos, xfa) = match (info.xfa, cos) { (Some(pdfcraft_render::Xfa::Dynamic), Ok(Ok(cos))) if pdfcraft_xfa::existing_layout(&cos).is_none() => { let mut work = cos.clone(); @@ -286,8 +293,9 @@ 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 as_opened = as_read.filter(|o| !Arc::ptr_eq(&o.bytes, &bytes)); let mut document = - Self::build_document(context, DocumentOpenData { name, path, bytes, info, structure: cos, render_password, password, xfa }); + Self::build_document(context, DocumentOpenData { name, path, bytes, info, structure: 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); @@ -301,7 +309,7 @@ impl Session { /// The last step of opening: build the document record and register it. fn build_document(context: &OpenContext, data: DocumentOpenData<'_>) -> Document { - let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa } = data; + let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa, as_opened } = data; let mut config = RenderConfig { password: render_password.as_deref().map(Arc::from), ..Default::default() }; let (mut editor, read_only_reason) = match cos { Ok(Ok(cos)) => { @@ -319,6 +327,7 @@ impl Session { appearances: AppearanceCache::default(), field_appearances: pdfcraft_forms::FieldAppearanceCache::default(), text_blocks: TextBlocksCache::default(), + as_opened, }), None, ) @@ -327,7 +336,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 mut signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, &context.trust, &sig_cache)).unwrap_or_default(); + let mut signatures = editor.as_ref().map(|e| editor_signatures(e, &bytes, &context.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; + } // The inspection reads only `/Info`; a file stating its title or author only in XMP still // shows them (#2373). if let Some(e) = &editor { diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 187cc217d8..8b084c728b 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -13,9 +13,9 @@ use crate::{ BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hairlines, HairlinesFixed, Hidden, ImageResolution, LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, StatusCaptions, SummarySort, TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, carry_verdict_marks, comment_list, - comment_summary, decode_text, display_bytes, display_config, guard, info_fields, js, local_utc_offset, note_warnings, office_to_pdf, open_source, - open_source_with, optimize, outline_rows, parse_ymd, print, print_layer_states, print_raster, render_threads, scan_colours, - set_default_layer_state, shown_under_redactions, signatures_of, source_kind, sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa, + comment_summary, decode_text, display_bytes, display_config, editor_signatures, guard, info_fields, js, local_utc_offset, note_warnings, + office_to_pdf, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_layer_states, print_raster, render_threads, + scan_colours, set_default_layer_state, shown_under_redactions, source_kind, sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa, xfa_sync_datasets, }; diff --git a/crates/engine/src/session/editing.rs b/crates/engine/src/session/editing.rs index 07e62a5f9e..fe46013205 100644 --- a/crates/engine/src/session/editing.rs +++ b/crates/engine/src/session/editing.rs @@ -2,9 +2,9 @@ use super::check_refresh_panic; use super::{ Arc, DocId, Document, Edit, EditCtx, EditError, Label, MAX_UNDO, ObjectKind, OnceLock, RenderPool, SaveOptions, Scope, Session, - XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, carry_verdict_marks, check_permission, comment_list, display_bytes, display_config, guard, info_fields, - inspect, js, keys_after, note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, signatures_of, sync_xfa_state, - undrawn_notices, uses_scripts, write_incremental, xfa, xfa_sync_datasets, + XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, carry_verdict_marks, check_permission, comment_list, display_bytes, display_config, editor_signatures, + guard, info_fields, inspect, js, keys_after, note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, + sync_xfa_state, undrawn_notices, uses_scripts, write_incremental, xfa, xfa_sync_datasets, }; use crate::{EditNotice, MarkKind, print_preview_layers}; @@ -533,7 +533,7 @@ impl Session { #[cfg(test)] check_refresh_panic(); if !doc.signatures.is_empty() { - let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache); + let mut signatures = editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache); // The display copy is kept for a metadata edit, and so are its marks, unless the // edit changed a verdict (a certification can forbid it): the page then draws the // new one. @@ -584,7 +584,7 @@ impl Session { } doc.info.file_size = bytes.len(); doc.form = form; - let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) }; + let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache) }; doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config)); @@ -649,7 +649,7 @@ impl Session { doc.marker_scan = OnceLock::new(); } doc.info.file_size = bytes.len(); - let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) }; + let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache) }; doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config)); @@ -757,7 +757,7 @@ impl Session { if invalidate_links { doc.links = OnceLock::new(); } - let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache); + let mut signatures = editor_signatures(editor, &bytes, &doc.trust, &doc.sig_cache); doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config)); diff --git a/crates/engine/src/session/save.rs b/crates/engine/src/session/save.rs index eceec23c2c..a8770bc007 100644 --- a/crates/engine/src/session/save.rs +++ b/crates/engine/src/session/save.rs @@ -1,6 +1,6 @@ use super::{ Arc, DocId, Document, EditError, Keys, OpenError, RecoverySnapshot, RenderPool, SaveOptions, Session, SignOptions, StatusCaptions, TrustStore, - display_bytes, display_config, guard, render_threads, signatures_of, writable, write_full, write_incremental, xfa_sync_datasets, + display_bytes, display_config, editor_signatures, guard, render_threads, writable, write_full, write_incremental, xfa_sync_datasets, }; impl Session { @@ -90,6 +90,8 @@ impl Session { editor.saved = bytes; editor.saved_keys = keys; editor.unsaved_file = false; + // 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()); @@ -269,7 +271,7 @@ impl Session { return; } let Some(editor) = doc.editor.as_mut() else { return }; - let mut signatures = signatures_of(&editor.cos, &doc.bytes, &doc.trust, &doc.sig_cache); + let mut signatures = editor_signatures(editor, &doc.bytes, &doc.trust, &doc.sig_cache); doc.display = display_bytes(Some(editor), &doc.bytes, &mut signatures, &doc.captions); doc.signatures = Arc::new(signatures); doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b0b995bf07..21a6231f9d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -11942,6 +11942,71 @@ fn cropping_an_existing_image_clips_it_and_moves_with_it() { 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, SignatureStatus::Invalid), + // 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, + SignatureStatus::Valid, + ), + ]; + for (what, form, field, saved_kind, saved_status) 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 (status, modification) = verdict(&s); + assert_eq!(status, saved_status, "{what}: {modification:?}"); + 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:?}"); + } +} + /// Convert colours re-encodes pictures too (RGB → gray, the JPEG staying JPEG) and is one undo /// step; a document with nothing to convert refuses rather than leaving an empty step. #[test] diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index e9e777c706..ee64e978b8 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -6433,8 +6433,8 @@ milestone = "M9" status = "shipped" commands = ["sign.validate"] tools = ["sign_list"] -evidence = ["crates/sign/tests/it/pdf.rs::signing_then_validating_with_and_without_trust", "crates/automation/tests/it/automation.rs::digital_ids_signing_and_validation_through_tools", "crates/sign/tests/it/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/it/pdf.rs::signing_then_validating_with_and_without_trust", "crates/automation/tests/it/automation.rs::digital_ids_signing_and_validation_through_tools", "crates/sign/tests/it/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"