From 3bff138d23c8837db913e465276b5b39c7e05be1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:28:42 -0800 Subject: [PATCH 1/2] metadata: the XMP scan tests count work instead of timing paths_are_not_built_past_the_key_budget passed only when parse_xmp finished within 10 s, and many_attributes_scan_in_linear_time compared the fastest of three timed scans at two sizes. Both now count the work with test-only counters. - A counter records the bytes of each property path collect_description and collect_property build. The key budget test checks that they stay within twice the budget plus one byte per struct. With the path checked against the budget only after it is built, 24,029,441,397 bytes are built and the test fails. - A field attribute whose path did not fit the budget, under an element whose own path still did, left the budget unchanged after its element and struct paths had been built, so each sibling copied the long ancestor path again. collect_property now builds a struct's paths only after charging its key, and checks a field path against the budget before building it, as collect_description does for a description's attributes. A new test, field_paths_past_the_key_budget_are_not_built_for_each_sibling, puts 20,000 such siblings under a 200,000-byte struct name. Without the field check it builds 4,001,308,570 bytes of paths and fails. - A counter records each name scan() looks up in its set of a tag's attribute names. The attributes test checks one lookup per attribute at 20,000 and 80,000 attributes, and that a repeated name is reported by that set. With quick-xml's own duplicate check turned on, the repeat is reported as quick-xml's error and the test fails. --- crates/metadata/src/xmp.rs | 52 +++++++++++++++++++++++--------- crates/metadata/src/xmp/tests.rs | 34 +++++++++++++++++++-- crates/metadata/src/xmp_merge.rs | 40 ++++++++++++------------ 3 files changed, 91 insertions(+), 35 deletions(-) diff --git a/crates/metadata/src/xmp.rs b/crates/metadata/src/xmp.rs index 9730bfdd0d..c09489237f 100644 --- a/crates/metadata/src/xmp.rs +++ b/crates/metadata/src/xmp.rs @@ -567,7 +567,7 @@ fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap = const { std::cell::Cell::new(0) }; +} + +#[inline] +fn build_path(path: String) -> String { + #[cfg(test)] + PATH_BYTES.with(|bytes| bytes.set(bytes.get().saturating_add(path.len()))); + path +} + /// Charge one flattened key's length to the key budget; `false` when the budget is spent (the /// property is then left out, like other elements a limit has cut) and the map is marked partial. fn take_key_bytes(key: &str, budget: &mut usize, dropped: &mut bool) -> bool { @@ -596,8 +610,11 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap = arr .children .iter() @@ -614,32 +631,39 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap = p.attrs.iter().filter(|(k, _)| !is_rdf_meta_attr(k)).collect(); if !field_attrs.is_empty() && p.children.is_empty() && p.text.trim().is_empty() { for (k, v) in field_attrs { - let full = format!("{struct_prefix}{k}"); + // the budget is checked before the path is built, as for a description's attributes + if *budget < prefix.len().saturating_add(p.name.len()).saturating_add(1).saturating_add(k.len()) { + *truncated = true; + continue; + } + let full = build_path(format!("{prefix}{}/{k}", p.name)); if take_key_bytes(&full, budget, truncated) { props.entry(full).or_default().push(v.clone()); } } return; } + let key = path(); let v = p.attr("rdf:resource").map(str::to_string).unwrap_or_else(|| p.text.trim().to_string()); if take_key_bytes(&key, budget, truncated) { props.entry(key).or_default().push(v); diff --git a/crates/metadata/src/xmp/tests.rs b/crates/metadata/src/xmp/tests.rs index c3c3181c9e..1440741f30 100644 --- a/crates/metadata/src/xmp/tests.rs +++ b/crates/metadata/src/xmp/tests.rs @@ -886,9 +886,39 @@ fn paths_are_not_built_past_the_key_budget() { doc.push_str(&format!("")); } doc.push_str(""); - let t = std::time::Instant::now(); + PATH_BYTES.with(|bytes| bytes.set(0)); let _ = parse_xmp(&doc); - assert!(t.elapsed().as_secs() < 10, "took {:?}", t.elapsed()); + // Each path built is charged to the budget, or is a charged struct path and its "/". + let built = PATH_BYTES.with(std::cell::Cell::get); + let structs = 100_004; + assert!(built <= 2 * MAX_KEY_BYTES + structs, "{built} bytes of paths built"); +} + +/// A field attribute whose path no longer fits the budget, while its element's own path still +/// does, left the budget as it was: each of its siblings then copied the long ancestor path again. +#[test] +fn field_paths_past_the_key_budget_are_not_built_for_each_sibling() { + // One struct of n letters, then a field that spends the budget down to n + 10 bytes: room for + // the path of `lc:e` under the struct (n + 8 bytes) but not for that of its field `lc:f` + // (n + 13). + let n = 200_000; + let level = "n".repeat(n); + let drain = "a".repeat(MAX_KEY_BYTES - 3 * n - 25); + let mut doc = format!( + "", + LC.uri + ); + for _ in 0..20_000 { + doc.push_str(""); + } + doc.push_str(&format!("")); + PATH_BYTES.with(|bytes| bytes.set(0)); + let data = parse_xmp(&doc).unwrap_or_else(|e| panic!("{e}")); + assert!(data.properties_truncated); + assert!(data.properties.contains_key(&format!("lc:{level}/lc:d/lc:{drain}"))); + assert!(!data.properties.contains_key(&format!("lc:{level}/lc:e/lc:f"))); + let built = PATH_BYTES.with(std::cell::Cell::get); + assert!(built <= 2 * MAX_KEY_BYTES, "{built} bytes of paths built"); } /// The caller's namespace is declared where the read-only `crs` sits in the table, is known to the diff --git a/crates/metadata/src/xmp_merge.rs b/crates/metadata/src/xmp_merge.rs index 76759f680f..ac8fbe22fe 100644 --- a/crates/metadata/src/xmp_merge.rs +++ b/crates/metadata/src/xmp_merge.rs @@ -97,6 +97,12 @@ fn pos(r: &quick_xml::Reader<&[u8]>) -> usize { usize::try_from(r.buffer_position()).unwrap_or(usize::MAX) } +// Each attribute name `scan` looks up in its set of the tag's names, on this thread. +#[cfg(test)] +std::thread_local! { + static NAME_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Locate the descriptions, their top-level properties and `` in a packet. fn scan(s: &str, extra: &[XmpNamespace]) -> Result { let mut reader = quick_xml::Reader::from_reader(s.as_bytes()); @@ -124,6 +130,8 @@ fn scan(s: &str, extra: &[XmpNamespace]) -> Result { for a in e.attributes().with_checks(false) { let a = a.map_err(|e| XmpError::Xml(e.to_string()))?; let k = String::from_utf8_lossy(a.key.as_ref()).into_owned(); + #[cfg(test)] + NAME_CHECKS.with(|checks| checks.set(checks.get().saturating_add(1))); if !seen.insert(k.clone()) { return Err(XmpError::Xml(format!("repeated attribute {k}"))); } @@ -490,11 +498,10 @@ mod tests { #[test] fn many_attributes_scan_in_linear_time() { - // quick-xml's duplicate-name check compares each attribute with all earlier ones: 200 000 attributes on - // one description took over 20 s to scan, about 30 ms with the set. Four times the attributes must take - // about four times as long, not sixteen. A ratio of the fastest runs holds on a loaded machine, where - // a fixed bound does not. - let packet = |n: usize| { + // A duplicate-name check that compares each attribute with all earlier ones took over 20 s for + // 200 000 attributes on one description. The scan looks each name up once in a set of the tag's + // names, and leaves quick-xml's own check off. + let packet = |n: usize, repeat: &str| { let mut s = String::from( "\ "); s }; - let run = |s: &str, n: usize| { - let t = std::time::Instant::now(); - let found = scan(s, &[]).unwrap(); - let took = t.elapsed(); + for n in [20_000, 80_000] { + NAME_CHECKS.with(|checks| checks.set(0)); + let found = scan(&packet(n, ""), &[]).unwrap(); assert_eq!(found.descs[0].attrs.len(), n + 2, "every attribute is read"); - took - }; - let (n, small_packet, large_packet) = (20_000, packet(20_000), packet(80_000)); - // interleaved, so a burst of load slows both sizes rather than one; the fastest run of each counts - let (mut small, mut large) = (std::time::Duration::MAX, std::time::Duration::MAX); - for _ in 0..3 { - small = small.min(run(&small_packet, n)); - large = large.min(run(&large_packet, 4 * n)); + // one lookup for each attribute of the three tags: xmlns:x, xmlns:rdf, rdf:about, xmlns:foo and the n + assert_eq!(NAME_CHECKS.with(std::cell::Cell::get), n + 4); + // the set, not quick-xml, finds a name given twice + let repeated = scan(&packet(n, " foo:a0=\"again\""), &[]).map(|_| ()).unwrap_err(); + assert_eq!(repeated, XmpError::Xml("repeated attribute foo:a0".into())); } - let ratio = large.as_secs_f64() / small.as_secs_f64().max(1e-6); - assert!(ratio < 10.0, "4x the attributes took {ratio:.1}x as long ({small:?}, then {large:?})"); } #[test] From 6fc0cf18842577eb257d7cb21190828b194b58a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 19:19:18 -0800 Subject: [PATCH 2/2] metadata: count the bytes the XMP resolution search reads The search of a packet for repeated property text was covered only by a timed call in craft-image-codecs' resolution tests. A test-only counter now records the bytes xmp_values searches for a key or a closing quote, and repeated_property_text_is_searched_once_for_each_property checks that 50,000 copies of " tiff:ResolutionUnit>" are searched at most once for each of the three resolution properties. With the search continuing past a value that never closes, it reads 26,250,525,000 bytes of the 1,050,000-byte packet and the test fails. --- crates/metadata/src/edit/resolution.rs | 43 +++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/metadata/src/edit/resolution.rs b/crates/metadata/src/edit/resolution.rs index 450ea4a25d..4da5521dc3 100644 --- a/crates/metadata/src/edit/resolution.rs +++ b/crates/metadata/src/edit/resolution.rs @@ -419,6 +419,7 @@ fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> { let mut out = Vec::new(); let mut from = 0; while let Some(k) = xmp.get(from..).and_then(|s| s.find(key)).map(|k| k + from) { + searched(k + key.len() - from); from = k + key.len(); // An attribute or an opening tag of exactly this name (not ``, not `xkey`). if !xmp.get(..k).and_then(|h| h.chars().next_back()).is_some_and(|c| c == '<' || c.is_ascii_whitespace()) { @@ -443,13 +444,34 @@ fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> { // attribute re-ran this full-suffix `find(close)` for every occurrence, which is // quadratic in the packet size. A missing close means the value is unterminated, so // no later value can parse either; stop scanning in that case. - let Some(len) = value.find(close) else { break }; + let Some(len) = value.find(close) else { + // the search read the rest of the packet, and no key search follows + searched(value.len()); + from = xmp.len(); + break; + }; + searched(len + close.len_utf8()); out.push((start, start + len)); from = start + len + close.len_utf8(); } + searched(xmp.len().saturating_sub(from)); out } +// The bytes of the packet `xmp_values` searches for a key or a closing quote, on this thread. +#[cfg(test)] +std::thread_local! { + static SEARCHED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[inline] +fn searched(count: usize) { + #[cfg(test)] + SEARCHED.with(|searched| searched.set(searched.get().saturating_add(count))); + #[cfg(not(test))] + let _ = count; +} + /// An XMP rational (`300/1`) or plain number. fn xmp_number(s: &str) -> Option { let s = s.trim(); @@ -780,3 +802,22 @@ pub fn resolution(exif: Option<&[u8]>, xmp: Option<&str>) -> Option<(f32, f32)> #[cfg(test)] mod complexity_tests; + +#[cfg(test)] +mod xmp_scan_tests { + use super::*; + + /// Property-like text repeated through a packet is searched once: each property's values are + /// found in one pass, not a search of the rest of the packet from every occurrence. + #[test] + fn repeated_property_text_is_searched_once_for_each_property() { + let decoys = " tiff:ResolutionUnit>".repeat(50_000); + for key in [XMP_X, XMP_Y, XMP_UNIT] { + SEARCHED.with(|searched| searched.set(0)); + let _ = xmp_values(&decoys, key); + let read = SEARCHED.with(std::cell::Cell::get); + assert!(read <= decoys.len(), "{key}: {read} bytes searched in {}", decoys.len()); + } + assert_eq!(xmp_resolution(&decoys), None); + } +}