diff --git a/Cargo.lock b/Cargo.lock index 7b8dc02d7d..0c7bea84af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1566,6 +1566,33 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "craft-xfa" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1a0d5d607859a2e529851482de09b8e53aaeec3e#1a0d5d607859a2e529851482de09b8e53aaeec3e" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1a0d5d607859a2e529851482de09b8e53aaeec3e)", +] + +[[package]] +name = "craft-xfdf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72#e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72)", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1a0d5d607859a2e529851482de09b8e53aaeec3e#1a0d5d607859a2e529851482de09b8e53aaeec3e" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -1575,6 +1602,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72#e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -5171,6 +5208,7 @@ version = "0.21.1" dependencies = [ "base64 0.23.1", "craft-image-codecs", + "craft-xfa", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "pdfcraft-cos", "pdfcraft-fonts", @@ -5184,6 +5222,7 @@ version = "0.21.1" dependencies = [ "base64 0.23.1", "craft-csv", + "craft-xfdf", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "pdfcraft-annot", "pdfcraft-cos", diff --git a/crates/annot/tests/malformed.rs b/crates/annot/tests/malformed.rs index 64fc241baf..6b8f007de7 100644 --- a/crates/annot/tests/malformed.rs +++ b/crates/annot/tests/malformed.rs @@ -294,15 +294,20 @@ fn reference_loops_terminate_and_a_delete_takes_the_cycle_with_it() { // ── wrong types where the reader wants a number or a name ───────────────────────────────────── /// Values of the wrong type in flag, opacity and colour entries: the reader falls back to its -/// defaults instead of panicking. NOTE on opacity: reading does **not** clamp, so `/CA 7.5` comes -/// back as 7.5 and would hand a nonsense value to a 0–1 slider; writing clamps (`add_annotation` -/// refuses non-finite and clamps the range). The asymmetry is recorded here, not endorsed. +/// defaults instead of panicking. Opacity is clamped on read to the supported 0-1 range; +/// the original malformed dictionary remains unchanged. #[test] fn wrong_typed_flag_opacity_and_colour_entries_fall_back_without_panicking() { let doc = one_annot(b"<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /CA 7.5 /F /NotAnInt /C [1 2] >>"); read_everything(&doc); let p = props(&doc, 0, 0).expect("still a comment"); - assert_eq!(p.opacity, 7.5, "the out-of-range opacity is passed through as written"); + assert_eq!(p.opacity, 1.0, "the out-of-range opacity is clamped on read"); + // Exercise both clamp edges and an unchanged interior value, not just a constant fallback. + for (raw, expected) in [("-0.5", 0.0), ("0.4", 0.4), ("1.5", 1.0)] { + let bytes = format!("<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /CA {raw} >>"); + let probe = one_annot(bytes.as_bytes()); + assert_eq!(props(&probe, 0, 0).expect("still a comment").opacity, expected, "opacity {raw}"); + } assert!(!p.locked, "a name where /F belongs reads as no flags at all"); assert_eq!(p.color, None, "/C with two components is not a colour"); let listed = summaries(&doc); @@ -382,7 +387,8 @@ fn a_link_area_that_is_too_small_or_broken_is_refused_before_it_is_written() { ]; for (label, rect, want_in_message) in cases { let mut doc = blank(2); - let e = links::add(&mut doc, 0, rect, &links::LinkAction::Page(1), &links::LinkStyle::default()).err(); + let e = + links::add(&mut doc, 0, rect, &links::LinkAction::Page { page: 1, zoom: links::LinkZoom::FitPage }, &links::LinkStyle::default()).err(); let msg = match &e { Some(AnnotError::Invalid(m)) => m.clone(), other => panic!("{label}: expected Invalid, got {other:?}"), @@ -440,10 +446,10 @@ fn non_finite_builder_input_is_refused_and_leaves_the_document_untouched() { } for (label, style) in [ - ("nan opacity", Style { color: [0.0, 0.0, 0.0], opacity: f64::NAN, width: 1.0, fill: None }), - ("infinite opacity", Style { color: [0.0, 0.0, 0.0], opacity: f64::INFINITY, width: 1.0, fill: None }), - ("nan colour", Style { color: [f64::NAN, 0.0, 0.0], opacity: 1.0, width: 1.0, fill: None }), - ("nan width", Style { color: [0.0, 0.0, 0.0], opacity: 1.0, width: f64::NAN, fill: None }), + ("nan opacity", Style { color: [0.0, 0.0, 0.0], opacity: f64::NAN, width: 1.0, fill: None, ..Style::default() }), + ("infinite opacity", Style { color: [0.0, 0.0, 0.0], opacity: f64::INFINITY, width: 1.0, fill: None, ..Style::default() }), + ("nan colour", Style { color: [f64::NAN, 0.0, 0.0], opacity: 1.0, width: 1.0, fill: None, ..Style::default() }), + ("nan width", Style { color: [0.0, 0.0, 0.0], opacity: 1.0, width: f64::NAN, fill: None, ..Style::default() }), ] { let mut doc = blank(1); let e = add_annotation( @@ -593,7 +599,14 @@ fn unvalidated_stamp_size_and_signature_contours_are_rewritten_silently_in_the_f &mut doc, &NewAnnotation { page: 0, - shape: Shape::CustomStamp { rect: [10.0, 20.0, 60.0, 50.0], name: "Sig".into(), picture, image: true, size: (1e300, f64::NAN) }, + shape: Shape::CustomStamp { + rect: [10.0, 20.0, 60.0, 50.0], + name: "Sig".into(), + picture, + image: true, + size: (1e300, f64::NAN), + line: None, + }, style: Style::default(), contents: String::new(), author: "A".into(), @@ -656,7 +669,7 @@ fn a_nan_fill_is_accepted_on_create_and_refused_on_edit() { &NewAnnotation { page: 0, shape: Shape::Rectangle { rect: [10.0, 20.0, 60.0, 40.0] }, - style: Style { color: [0.9, 0.1, 0.1], opacity: 1.0, width: 2.0, fill: Some(nan) }, + style: Style { color: [0.9, 0.1, 0.1], opacity: 1.0, width: 2.0, fill: Some(nan), ..Style::default() }, contents: String::new(), author: "A".into(), }, @@ -842,7 +855,7 @@ fn the_same_huge_fill_is_accepted_on_create_and_refused_on_edit() { &NewAnnotation { page: 0, shape: Shape::Rectangle { rect: [10.0, 20.0, 60.0, 40.0] }, - style: Style { color: [0.9, 0.1, 0.1], opacity: 1.0, width: 2.0, fill: Some(probe) }, + style: Style { color: [0.9, 0.1, 0.1], opacity: 1.0, width: 2.0, fill: Some(probe), ..Style::default() }, contents: String::new(), author: "A".into(), }, diff --git a/crates/annot/tests/properties.rs b/crates/annot/tests/properties.rs index 8efb6b7046..53a37cf067 100644 --- a/crates/annot/tests/properties.rs +++ b/crates/annot/tests/properties.rs @@ -165,7 +165,7 @@ proptest! { #[test] fn opacity_and_flags_follow_their_rules(opacity in any::()) { let mut doc = blank(1); - let added = add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: [10.0, 10.0, 60.0, 40.0] }, Style { color: [0.5, 0.25, 0.75], opacity, width: 1.0, fill: None }, String::new(), "Ada".into()), &meta("c".into())); + let added = add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: [10.0, 10.0, 60.0, 40.0] }, Style { color: [0.5, 0.25, 0.75], opacity, width: 1.0, fill: None, ..Style::default() }, String::new(), "Ada".into()), &meta("c".into())); if !opacity.is_finite() { prop_assert!(added.is_err(), "a non-finite opacity ({:?}) must be refused, not written", opacity); return Ok(()); @@ -243,7 +243,7 @@ proptest! { 2 => -0.5, _ => 0.0, }; - add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: *r }, Style { color: [0.9, 0.1, 0.1], opacity, width: 2.0, fill: None }, format!("c{i}"), "Ada".into()), &meta(format!("k{i}"))) + add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: *r }, Style { color: [0.9, 0.1, 0.1], opacity, width: 2.0, fill: None, ..Style::default() }, format!("c{i}"), "Ada".into()), &meta(format!("k{i}"))) .expect("adds"); want_rects.push(norm(*r)); } @@ -333,7 +333,7 @@ proptest! { #[test] fn width_and_fill_are_written_as_they_were_given(width in -4.0f64..12.0, fill in prop::option::of(prop::array::uniform3(0.0f64..1.0))) { let mut doc = blank(1); - add_annotation(&mut doc, &comment(0, Shape::Oval { rect: [5.0, 5.0, 65.0, 35.0] }, Style { color: [1.0, 0.0, 0.0], opacity: 1.0, width, fill }, String::new(), "Ada".into()), &meta("f".into())) + add_annotation(&mut doc, &comment(0, Shape::Oval { rect: [5.0, 5.0, 65.0, 35.0] }, Style { color: [1.0, 0.0, 0.0], opacity: 1.0, width, fill, ..Style::default() }, String::new(), "Ada".into()), &meta("f".into())) .expect("adds"); for path in [Save::Incremental, Save::FullTable] { let (file, reopened) = save_and_reopen(&doc, path); @@ -360,7 +360,7 @@ proptest! { fn a_line_keeps_its_endpoints_and_its_rectangle_spans_them(from in prop::array::uniform2(coord()), dx in 1.0f64..300.0, dy in -300.0f64..300.0, width in 0.5f64..8.0) { let to = [(from[0] + dx).min(450.0), from[1] + dy]; let mut doc = blank(1); - add_annotation(&mut doc, &comment(0, Shape::Line { from, to, start: LineEnding::None, end: LineEnding::OpenArrow }, Style { color: [0.0, 0.0, 0.0], opacity: 1.0, width, fill: None }, String::new(), "Ada".into()), &meta("l".into())) + add_annotation(&mut doc, &comment(0, Shape::Line { from, to, start: LineEnding::None, end: LineEnding::OpenArrow }, Style { color: [0.0, 0.0, 0.0], opacity: 1.0, width, fill: None, ..Style::default() }, String::new(), "Ada".into()), &meta("l".into())) .expect("adds"); let span = bounds_of(&[from, to]); for path in [Save::Incremental, Save::FullTable, Save::FullStreams] { diff --git a/crates/annot/tests/round_trip.rs b/crates/annot/tests/round_trip.rs index 3e60601498..dde7f8ebc1 100644 --- a/crates/annot/tests/round_trip.rs +++ b/crates/annot/tests/round_trip.rs @@ -33,8 +33,8 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions}; use support::bytes; use support::fixture::{ - ALL_SAVES, FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, FLAG_READONLY, Save, annot_entries, blank, blank_with_indirect_annots, dict_of, name_of, - num, nums, page_object_numbers, pdf, save_and_reopen, str_of, + ALL_SAVES, FLAG_HIDDEN, FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, FLAG_READONLY, Save, annot_entries, blank, blank_with_indirect_annots, dict_of, + name_of, num, nums, page_object_numbers, pdf, save_and_reopen, str_of, }; /// A deterministic `/M` date and `/NM` id, so nothing here depends on the clock. @@ -48,7 +48,7 @@ fn ann(page: usize, shape: Shape, contents: &str) -> NewAnnotation { } fn styled(page: usize, shape: Shape, contents: &str, color: [f64; 3], opacity: f64, width: f64, fill: Option<[f64; 3]>) -> NewAnnotation { - NewAnnotation { page, shape, style: Style { color, opacity, width, fill }, contents: contents.into(), author: "Ada".into() } + NewAnnotation { page, shape, style: Style { color, opacity, width, fill, ..Style::default() }, contents: contents.into(), author: "Ada".into() } } /// The dictionary of the `k`-th `/Annots` entry of a page. @@ -658,8 +658,9 @@ fn reply_threads_and_the_delete_cascade_survive_every_save_path() { assert_eq!(str_of(&reopened, &st, b"State").as_deref(), Some("Accepted"), "{path:?}"); assert_eq!(str_of(&reopened, &st, b"StateModel").as_deref(), Some("Review"), "{path:?}"); assert_eq!(str_of(&reopened, &st, b"Subj").as_deref(), Some("Status"), "{path:?}"); - // Replies are printed but keep the icon flags of a comment; no Hidden bit here. - assert_eq!(st.int(b"F"), Some(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE), "{path:?}"); + // Review-state records are hidden; ordinary text replies retain their visible comment flags. + assert_eq!(st.int(b"F"), Some(FLAG_HIDDEN | FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE), "{path:?}"); + assert_eq!(annot_at(&reopened, 0, 2, path).int(b"F"), Some(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE), "{path:?}: ordinary reply"); let listed = summaries(&reopened); assert_eq!(listed.iter().filter(|s| s.in_reply_to.as_deref() == Some("p1")).count(), 2, "{path:?}: both replies name the parent's /NM"); assert_eq!(listed.iter().filter(|s| s.state.as_deref() == Some("Accepted")).count(), 1, "{path:?}"); @@ -714,7 +715,7 @@ fn links_keep_page_targets_uri_and_dash_structure_across_renumbering() { &mut doc, 0, [120.0, 700.0, 240.0, 720.0], - &links::LinkAction::Page(2), + &links::LinkAction::Page { page: 2, zoom: links::LinkZoom::FitPage }, &links::LinkStyle { visible: true, width: 2.0, dashed: true, ..Default::default() }, ) .expect("links to page 3"); @@ -735,7 +736,7 @@ fn links_keep_page_targets_uri_and_dash_structure_across_renumbering() { .into_iter() .map(|l| { let a = match l.action { - links::LinkAction::Page(p) => format!("page {p}"), + links::LinkAction::Page { page: p, zoom: _ } => format!("page {p}"), links::LinkAction::Uri(u) => u, links::LinkAction::Other(o) => format!("other:{o}"), }; @@ -770,7 +771,14 @@ fn links_keep_page_targets_uri_and_dash_structure_across_renumbering() { fn removing_all_links_keeps_comments() { let mut doc = blank(2); add_annotation(&mut doc, &ann(0, Shape::Note { at: [50.0, 700.0], icon: NoteIcon::Help }, "note"), &meta("n")).expect("adds"); - links::add(&mut doc, 0, [200.0, 700.0, 300.0, 715.0], &links::LinkAction::Page(0), &links::LinkStyle::default()).expect("links"); + links::add( + &mut doc, + 0, + [200.0, 700.0, 300.0, 715.0], + &links::LinkAction::Page { page: 0, zoom: links::LinkZoom::FitPage }, + &links::LinkStyle::default(), + ) + .expect("links"); let removed = links::remove_all(&mut doc, None).expect("removes all links"); assert_eq!(removed, 1); @@ -980,7 +988,7 @@ fn a_full_rewrite_into_object_streams_describes_the_same_comments_as_a_plain_tab assert_eq!(summaries(&plain).len(), summaries(&packed).len()); // The plain-table output is bigger here: object streams compress, which is the point of them. - let opts = SaveOptions { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: true, drop_unlinked: false }; + let opts = SaveOptions { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: true, drop_unlinked: false, id_entropy: None }; let packed_bytes = pdfcraft_cos::write_full(&doc, &opts).expect("writes"); assert!( packed_bytes.len() < pdfcraft_cos::write_full(&doc, &SaveOptions { object_streams: false, ..opts }).expect("writes").len(), diff --git a/crates/annot/tests/support/fixture.rs b/crates/annot/tests/support/fixture.rs index 69567b34e9..1b466c4a54 100644 --- a/crates/annot/tests/support/fixture.rs +++ b/crates/annot/tests/support/fixture.rs @@ -118,7 +118,13 @@ pub fn save_and_reopen(doc: &Document, path: Save) -> (Vec, Document) { /// Save with the path's options. `/Info /ModDate` is left unset so a full save adds nothing that /// would make byte comparisons depend on the clock. pub fn save(doc: &Document, path: Save) -> Vec { - let opts = SaveOptions { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: path == Save::FullStreams, drop_unlinked: false }; + let opts = SaveOptions { + mod_date: None, + id_seed: 0x5052_494E_5443_5241, + object_streams: path == Save::FullStreams, + drop_unlinked: false, + id_entropy: None, + }; match path { Save::Incremental => write_incremental(doc, &opts), Save::FullTable | Save::FullStreams => write_full(doc, &opts), diff --git a/crates/sign/src/revocation.rs b/crates/sign/src/revocation.rs index 93f338f89c..085170a1b3 100644 --- a/crates/sign/src/revocation.rs +++ b/crates/sign/src/revocation.rs @@ -66,6 +66,21 @@ pub struct CertificateList { impl CertificateList { pub fn parse(bytes: &[u8]) -> Result { + let parsed = craft_pkcs7::revocation::CertificateList::parse(bytes).map_err(crate::der::app_error)?.into_parts(); + Ok(Self { + tbs: parsed.tbs, + sig_alg: parsed.sig_alg, + signature: parsed.signature, + issuer_raw: parsed.issuer_raw, + this_update: parsed.this_update, + next_update: parsed.next_update, + revoked: parsed.revoked, + }) + } + + // Retained parity oracle: original CRL parser by Justin John (4d0078aeff). + #[cfg(test)] + fn parse_legacy(bytes: &[u8]) -> Result { if bytes.is_empty() || bytes.len() > MAX_EVIDENCE { return Err(bad("CRL is empty or exceeds the 2 MiB limit")); } @@ -415,3 +430,44 @@ mod shared_ocsp_tests { compare(&der::seq(&[&der::tlv(tag::ENUMERATED, &[1])])); } } + +#[cfg(test)] +mod shared_crl_tests { + use super::*; + use crate::der; + + #[test] + fn shared_crl_parser_matches_retained_app_reader() { + let date = Time { year: 2026, month: 6, day: 15, hour: 12, minute: 0, second: 0 }; + let algorithm = DigestAlg::Sha256.algorithm(); + let tbs = der::seq(&[ + &der::int(1), + &algorithm, + &der::seq(&[]), + &date.encode(), + &date.encode(), + &der::seq(&[&der::seq(&[&der::uint(&[0x80]), &date.encode()])]), + ]); + let valid = der::seq(&[&tbs, &algorithm, &der::bit_string(&[1, 2, 3])]); + let compare = |bytes: &[u8]| match (CertificateList::parse(bytes), CertificateList::parse_legacy(bytes)) { + (Ok(a), Ok(b)) => { + assert_eq!( + (a.tbs, a.sig_alg, a.signature, a.issuer_raw, a.this_update, a.next_update, a.revoked), + (b.tbs, b.sig_alg, b.signature, b.issuer_raw, b.this_update, b.next_update, b.revoked) + ); + } + (Err(a), Err(b)) => assert_eq!(format!("{a:?}"), format!("{b:?}")), + _ => panic!("shared and retained CRL parsers disagree"), + }; + for end in 0..=valid.len() { + compare(&valid[..end]); + } + for i in 0..valid.len() { + let mut mutated = valid.clone(); + mutated[i] ^= 0x80; + compare(&mutated); + } + compare(&vec![0; MAX_EVIDENCE]); + compare(&vec![0; MAX_EVIDENCE + 1]); + } +} diff --git a/crates/sign/src/timestamp.rs b/crates/sign/src/timestamp.rs index 01c17221ac..d9530b68b4 100644 --- a/crates/sign/src/timestamp.rs +++ b/crates/sign/src/timestamp.rs @@ -14,6 +14,7 @@ use crate::{SignError, Time}; const TST_INFO: &str = "1.2.840.113549.1.9.16.1.4"; const MAX_RESPONSE: usize = 4 * 1024 * 1024; const MAX_TOKEN: usize = 2 * 1024 * 1024; +#[cfg(test)] const MAX_REQUEST: usize = 1024 * 1024; /// RFC 3161 request data. `nonce` is optional but recommended for online requests. @@ -106,27 +107,24 @@ fn bad(message: impl Into) -> SignError { /// Decode a `TimeStampReq` as [`TimestampQuery::encode`] wrote it. pub fn parse_request(bytes: &[u8]) -> Result { - if bytes.is_empty() || bytes.len() > MAX_REQUEST { - return Err(bad("request is empty or exceeds the 1 MiB limit")); - } - let fields = Tlv::parse_all(bytes)?.expect(tag::SEQUENCE, "TimeStampReq")?.children()?; - let mut it = fields.into_iter(); - let _version = it.next().ok_or_else(|| bad("missing version"))?.u64()?; - let imprint = it.next().ok_or_else(|| bad("missing message imprint"))?.children()?; - let alg_oid = - imprint.first().ok_or_else(|| bad("missing imprint algorithm"))?.children()?.first().ok_or_else(|| bad("missing algorithm OID"))?.oid()?; - let digest = DigestAlg::from_oid(&alg_oid).ok_or_else(|| bad("unsupported imprint digest algorithm"))?; - let hash = imprint.get(1).ok_or_else(|| bad("missing imprint digest"))?.expect(tag::OCTET_STRING, "imprint digest")?.value.to_vec(); - let mut q = TimestampQuery::new(digest, hash)?; - for f in it { - match f.tag { - tag::OID => q.policy = Some(f.oid()?), - tag::INTEGER => q.nonce = Some(f.u64()?), - tag::BOOLEAN => q.certificate_request = f.value.first() == Some(&0xFF), - _ => {} - } - } - Ok(q) + let query = craft_pkcs7::timestamp::parse_request(bytes).map_err(der::app_error)?; + // Exhaustive mapping preserves the app's digest identity without reparsing or copying. + use craft_pkcs7::DigestAlg as Shared; + let digest = match query.digest { + Shared::Sha1 => DigestAlg::Sha1, + Shared::Sha224 => DigestAlg::Sha224, + Shared::Sha256 => DigestAlg::Sha256, + Shared::Sha384 => DigestAlg::Sha384, + Shared::Sha512 => DigestAlg::Sha512, + Shared::Sha512_224 => DigestAlg::Sha512_224, + Shared::Sha512_256 => DigestAlg::Sha512_256, + Shared::Sha3_224 => DigestAlg::Sha3_224, + Shared::Sha3_256 => DigestAlg::Sha3_256, + Shared::Sha3_384 => DigestAlg::Sha3_384, + Shared::Sha3_512 => DigestAlg::Sha3_512, + Shared::Ripemd160 => DigestAlg::Ripemd160, + }; + Ok(TimestampQuery { digest, imprint: query.imprint, policy: query.policy, nonce: query.nonce, certificate_request: query.certificate_request }) } /// Parse and validate a token (a bare CMS `ContentInfo`): TSTInfo content, bounded size, the @@ -251,3 +249,69 @@ mod tests { assert!(parse_request(&vec![0; MAX_REQUEST + 1]).is_err()); } } + +#[cfg(test)] +mod request_parity { + use super::*; + // Original request reader: Justin John; algorithm support: Thorsten Hirsch. + // Retained as an independent higher-level parser oracle (MIT OR Apache-2.0). + fn legacy_request(bytes: &[u8]) -> Result { + if bytes.is_empty() || bytes.len() > MAX_REQUEST { + return Err(bad("request is empty or exceeds the 1 MiB limit")); + } + let fields = Tlv::parse_all(bytes)?.expect(tag::SEQUENCE, "TimeStampReq")?.children()?; + let mut it = fields.into_iter(); + let _version = it.next().ok_or_else(|| bad("missing version"))?.u64()?; + let imprint = it.next().ok_or_else(|| bad("missing message imprint"))?.children()?; + let alg_oid = imprint + .first() + .ok_or_else(|| bad("missing imprint algorithm"))? + .children()? + .first() + .ok_or_else(|| bad("missing algorithm OID"))? + .oid()?; + let digest = DigestAlg::from_oid(&alg_oid).ok_or_else(|| bad("unsupported imprint digest algorithm"))?; + let hash = imprint.get(1).ok_or_else(|| bad("missing imprint digest"))?.expect(tag::OCTET_STRING, "imprint digest")?.value.to_vec(); + let mut q = TimestampQuery::new(digest, hash)?; + for f in it { + match f.tag { + tag::OID => q.policy = Some(f.oid()?), + tag::INTEGER => q.nonce = Some(f.u64()?), + tag::BOOLEAN => q.certificate_request = f.value.first() == Some(&0xFF), + _ => {} + } + } + Ok(q) + } + + fn compare(bytes: &[u8]) { + match (legacy_request(bytes), parse_request(bytes)) { + (Ok(a), Ok(b)) => assert_eq!(a, b), + (Err(a), Err(b)) => assert_eq!(format!("{a:?}"), format!("{b:?}")), + other => panic!("request parity mismatch: {other:?}"), + } + } + #[test] + fn shared_request_preserves_algorithms_fields_errors_and_limits() { + for digest in DigestAlg::ALL { + let mut query = TimestampQuery::new(digest, digest.digest(&[b"fixture"])).unwrap(); + query.policy = Some("1.2.3.4".into()); + query.nonce = Some(u64::MAX); + for cert in [false, true] { + query.certificate_request = cert; + let bytes = query.encode().unwrap(); + compare(&bytes); + for len in 0..bytes.len() { + compare(&bytes[..len]); + } + for pos in 0..bytes.len() { + let mut changed = bytes.clone(); + changed[pos] ^= 255; + compare(&changed); + } + } + } + compare(&vec![0; MAX_REQUEST]); + compare(&vec![0; MAX_REQUEST + 1]); + } +} diff --git a/crates/xfa/Cargo.toml b/crates/xfa/Cargo.toml index ca7c3475e0..73e02252b4 100644 --- a/crates/xfa/Cargo.toml +++ b/crates/xfa/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true workspace = true [dependencies] +craft-xfa = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1a0d5d607859a2e529851482de09b8e53aaeec3e" } pdfcraft-cos = { workspace = true } pdfcraft-fonts = { workspace = true } craft-xml = { workspace = true } diff --git a/crates/xfa/src/proto.rs b/crates/xfa/src/proto.rs index ae1505804e..99dc18b689 100644 --- a/crates/xfa/src/proto.rs +++ b/crates/xfa/src/proto.rs @@ -74,6 +74,7 @@ pub(crate) fn expand(template: Node) -> (Option, Vec) { soms: HashMap::new(), search: MAX_SEARCH, work: MAX_WORK, + child_counts: HashMap::new(), active: HashMap::new(), missing: false, external: false, @@ -124,6 +125,8 @@ struct Writer<'a> { search: usize, /// Children, attributes and namespaces left to look at while merging layers. work: usize, + /// Bounded memoization only; each use still pays the full child count. + child_counts: HashMap, /// The elements being written around the current one: inheriting from one is a loop. active: HashMap, missing: bool, @@ -132,6 +135,22 @@ struct Writer<'a> { layers_cut: bool, } +/// Counting a reused prototype must not itself repeatedly walk its descendants. +/// Cache only complete direct-child counts, and cap the optimization's memory. +/// Truncated counts are not exact and must never be cached. Budget charging is unchanged. +fn child_count(node: Node<'_>, work: usize, cache: &mut HashMap) -> usize { + const MAX_CACHED_COUNTS: usize = 4_096; + let stop = work.saturating_add(1); + if let Some(count) = cache.get(&node.id()) { + return (*count).min(stop); + } + let count = node.children().take(stop).count(); + if count < stop && cache.len() < MAX_CACHED_COUNTS { + cache.insert(node.id(), count); + } + count +} + fn escape(s: &str, attribute: bool, out: &mut String) { for c in s.chars() { match c { @@ -439,7 +458,7 @@ impl<'a> Writer<'a> { // further than the budget left), attributes and namespaces, and the scope around it. let mut cost = scope.len().saturating_add(layers.len()); for l in &layers { - let children = l.children().take(self.work.saturating_add(1)).count(); + let children = child_count(*l, self.work, &mut self.child_counts); cost = cost.saturating_add(children).saturating_add(l.attributes().len()).saturating_add(l.namespaces().len()); } if self.failed.is_some() || !self.charge(cost) { diff --git a/crates/xfa/src/proto/tests.rs b/crates/xfa/src/proto/tests.rs index ba7f6f8316..efbec768a0 100644 --- a/crates/xfa/src/proto/tests.rs +++ b/crates/xfa/src/proto/tests.rs @@ -399,3 +399,63 @@ fn a_som_expression_past_its_length_limit_is_not_followed() { assert_eq!(field(&t, "long").common.h, None); assert!(close(field(&t, "short").common.h, 2.0 * MM)); } + +#[test] +fn cached_child_counts_preserve_truncation_and_charge_when_budget_shrinks() { + let doc = crate::xml::Document::parse("").unwrap(); + let node = doc.root_element(); + let mut cache = std::collections::HashMap::new(); + assert_eq!(super::child_count(node, 1, &mut cache), 2); + assert!(cache.is_empty(), "truncated counts are not reusable"); + assert_eq!(super::child_count(node, 10, &mut cache), 3); + assert_eq!(cache.get(&node.id()), Some(&3)); + for remaining in 0..=5 { + assert_eq!(super::child_count(node, remaining, &mut cache), node.children().take(remaining + 1).count()); + } + assert_eq!(super::child_count(node, 10, &mut cache), 3, "a cached use is still charged"); +} + +#[test] +fn child_count_memoization_has_a_fixed_entry_limit() { + let doc = crate::xml::Document::parse(&format!("{}", "".repeat(5_000))).unwrap(); + let mut cache = std::collections::HashMap::new(); + for node in doc.root_element().children() { + assert_eq!(super::child_count(node, 1, &mut cache), 0); + } + assert_eq!(cache.len(), 4_096); +} + +#[test] +fn cached_layers_still_subtract_work_and_stop_at_the_budget() { + let doc = crate::xml::Document::parse("").unwrap(); + let node = doc.root_element(); + let mut writer = super::Writer { + template: node, + out: String::new(), + limit: super::MAX_OUTPUT, + failed: None, + ids: None, + refs: std::collections::HashMap::new(), + soms: std::collections::HashMap::new(), + search: super::MAX_SEARCH, + work: 100, + child_counts: std::collections::HashMap::new(), + active: std::collections::HashMap::new(), + missing: false, + external: false, + looped: false, + layers_cut: false, + }; + writer.element(&[node], &super::Scope::new(), 0); + assert!(writer.failed.is_none()); + let first_cost = 100 - writer.work; + assert!(first_cost > 0); + assert!(!writer.child_counts.is_empty()); + let before = writer.work; + writer.element(&[node], &super::Scope::new(), 0); + assert!(writer.failed.is_none()); + assert_eq!(before - writer.work, first_cost, "cached layers pay the same work charge"); + writer.work = 0; + writer.element(&[node], &super::Scope::new(), 0); + assert!(writer.failed.as_ref().is_some_and(|why| why.contains("children, attributes and namespaces"))); +} diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index 7cc755f3f2..93b017fad8 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -1,389 +1,18 @@ -//! Lightweight namespace-aware XML DOM with source byte ranges, backed by `craft_xml`. +//! Namespace-aware XFA DOM delegated to the shared implementation. +pub(crate) use craft_xfa::xml::*; -use std::ops::Range; +#[cfg(test)] +mod tests { + use super::*; -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(crate) struct NodeId(pub(crate) usize); - -#[derive(Clone, Debug)] -pub(crate) struct ParsingOptions { - pub(crate) allow_dtd: bool, - pub(crate) 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(crate) struct Document { - nodes: Vec, - root: usize, -} - -#[derive(Clone, Copy)] -pub(crate) 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(crate) struct ExpandedName<'a> { - ns: Option<&'a str>, - name: &'a str, -} - -impl<'a> ExpandedName<'a> { - pub(crate) fn name(&self) -> &'a str { - self.name - } - - pub(crate) fn namespace(&self) -> Option<&'a str> { - self.ns - } -} - -pub(crate) 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(crate) struct Attribute<'a> { - attr: &'a AttrData, -} - -impl<'a> Attribute<'a> { - pub(crate) fn name(&self) -> &'a str { - &self.attr.name - } - - pub(crate) fn namespace(&self) -> Option<&'a str> { - self.attr.ns.as_deref() - } - - pub(crate) fn value(&self) -> &'a str { - &self.attr.value - } -} - -#[derive(Clone, Copy)] -pub(crate) struct Namespace<'a> { - prefix: &'a str, - uri: &'a str, -} - -impl<'a> Namespace<'a> { - pub(crate) fn name(&self) -> Option<&'a str> { - (!self.prefix.is_empty()).then_some(self.prefix) - } - - pub(crate) 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 { - #[cfg(test)] - pub(crate) fn parse(text: &str) -> Result { - Self::parse_with_options(text, ParsingOptions::default()) - } - - pub(crate) 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(crate) fn root_element(&self) -> Node<'_> { - Node { doc: self, id: self.root } - } - - pub(crate) fn get_node(&self, id: NodeId) -> Option> { - (id.0 < self.nodes.len()).then_some(Node { doc: self, id: id.0 }) - } - - pub(crate) fn descendants(&self) -> Descendants<'_> { - Descendants { doc: self, stack: vec![self.root] } - } -} - -pub(crate) 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(crate) fn id(&self) -> NodeId { - NodeId(self.id) - } - - pub(crate) fn document(&self) -> &'a Document { - self.doc - } - - pub(crate) fn is_element(&self) -> bool { - matches!(self.doc.nodes[self.id].kind, NodeKind::Element { .. }) - } - - pub(crate) fn is_text(&self) -> bool { - matches!(self.doc.nodes[self.id].kind, NodeKind::Text(_)) - } - - pub(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) fn children(&self) -> impl Iterator> + use<'a> { - let doc = self.doc; - doc.nodes[self.id].children.iter().map(move |&id| Node { doc, id }) - } - - pub(crate) fn descendants(&self) -> Descendants<'a> { - Descendants { doc: self.doc, stack: vec![self.id] } - } - - pub(crate) 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(crate) fn range(&self) -> Range { - match &self.doc.nodes[self.id].kind { - NodeKind::Element { range, .. } => range.clone(), - NodeKind::Text(_) => 0..0, - } + #[test] + fn shared_dom_keeps_depth_policy_and_rejects_duplicate_attributes() { + assert_eq!(crate::MAX_XML_DEPTH, craft_xfa::MAX_XML_DEPTH); + assert!(Document::parse("").is_err()); + assert!(Document::parse("").is_err()); + let doc = Document::parse("value").unwrap(); + let field = doc.root_element().children().next().unwrap(); + assert_eq!(field.tag_name().namespace(), Some("u")); + assert_eq!(field.text(), Some("value")); } } diff --git a/crates/xfdf/Cargo.toml b/crates/xfdf/Cargo.toml index d1e005ddc9..826c1835e7 100644 --- a/crates/xfdf/Cargo.toml +++ b/crates/xfdf/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true workspace = true [dependencies] +craft-xfdf = { git = "https://github.com/storytold/craft-libs", rev = "e5f00f5bf658ef2cce7bf96fbbd769a6fff5bc72", version = "0.1.0" } pdfcraft-cos = { workspace = true } pdfcraft-annot = { workspace = true } pdfcraft-forms = { workspace = true } diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs index a8bcab60c3..a96affa9ee 100644 --- a/crates/xfdf/src/lib.rs +++ b/crates/xfdf/src/lib.rs @@ -27,7 +27,7 @@ mod xfdf; #[cfg(test)] use common::{MAX_DEPTH, MAX_XML_DEPTH, arr, nums_of, parse_hex, text_of, xml_nesting_depth}; -use common::{check_form_xml_depth, el_text, esc, parse_form_xml, walk_xfdf, xml_name}; +use common::{check_form_xml_depth, el_text, esc, parse_form_xml, xml_name}; pub use fdf::export_fdf; use fdf::{ImportBudget, fdf_body, import_fdf, walk_fdf}; #[cfg(test)] @@ -183,18 +183,10 @@ pub fn data_values(bytes: &[u8]) -> Result)>, DataError }) .collect()); } - let text = String::from_utf8_lossy(bytes); - let t = text.trim_start_matches('\u{feff}').trim_start(); - check_form_xml_depth(t)?; - let root = parse_form_xml(t).map_err(|_| DataError::UnknownFormat)?; - if root.local() != "xfdf" { - return Err(DataError::UnknownFormat); - } - let mut values = Vec::new(); - if let Some(fields) = root.child(craft_xml::Local("fields")) { - walk_xfdf(fields, "", &mut values, 0, &mut 0)?; - } - Ok(values) + craft_xfdf::read_fields(bytes).map_err(|error| match error { + craft_xfdf::Error::UnknownFormat => DataError::UnknownFormat, + craft_xfdf::Error::Malformed(message) => DataError::Malformed(message), + }) } /// Merge Data Files into Spreadsheet: one CSV row per file, one column per field name (in the diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rs index f9e97cf3bf..d427bade73 100644 --- a/crates/xfdf/src/tests.rs +++ b/crates/xfdf/src/tests.rs @@ -4,6 +4,7 @@ use pdfcraft_annot::{Markup, Meta, NewAnnotation, Shape, Style, TextReplacement, use pdfcraft_cos::{SaveOptions, write_full, write_incremental}; use pdfcraft_forms::{NewField, add_field, fields, set_value}; +use super::common::walk_xfdf; use super::xfdf::PDFCRAFT_NS; use super::*; @@ -2762,3 +2763,29 @@ fn merge_csv_keeps_first_repeated_value() { let rows = vec![("Name".into(), vec!["first".into()]), ("Name".into(), vec!["second".into()])]; assert_eq!(merge_csv(&[rows]), "Name\nfirst\n"); } + +#[test] +fn shared_xfdf_fields_match_retained_reader() -> Result<(), Box> { + // Independent retained app walker remains used by annotation imports. + for xml in [ + "", + "abcskiplast", + "v", + ] { + let root = parse_form_xml(xml)?; + let mut expected = Vec::new(); + if let Some(fields) = root.child(craft_xml::Local("fields")) { + walk_xfdf(fields, "", &mut expected, 0, &mut 0)?; + } + assert_eq!(data_values(xml.as_bytes())?, expected); + } + assert!(matches!(data_values(b""), Err(DataError::UnknownFormat))); + assert!(matches!(data_values(b""), Err(DataError::UnknownFormat))); + let deep = format!("{}{}", "".repeat(65), "".repeat(65)); + assert!(matches!(data_values(deep.as_bytes()), Err(DataError::Malformed(_)))); + assert_eq!( + data_values(b"\xef\xbb\xbf \xff")?, + vec![("n".into(), vec!["\u{fffd}".into()])] + ); + Ok(()) +}