From 20835bbf5ba2f35af4c89d624a5fd09abab1f567 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Tue, 3 Nov 2026 22:13:50 +0100 Subject: [PATCH 1/9] fix(xmp): File Info keeps packets with a spaced or re-prefixed RDF end tag --- crates/engine/src/cmd/file_cmds/info.rs | 59 ++++++++++++++++++++++-- crates/engine/src/cmd/file_cmds/tests.rs | 34 ++++++++++++++ 2 files changed, 89 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/info.rs b/crates/engine/src/cmd/file_cmds/info.rs index 3f9436349d..381e0599a9 100644 --- a/crates/engine/src/cmd/file_cmds/info.rs +++ b/crates/engine/src/cmd/file_cmds/info.rs @@ -254,14 +254,61 @@ pub fn camera_data(exif: Option<&[u8]>, xmp: Option<&str>) -> Value { Value::Object(m) } +/// The RDF namespace every XMP packet's core element belongs to. +const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + +/// The byte range of the packet's RDF end tag, or `None` when it has none. XML allows +/// whitespace before a closing tag's `>` (REC-xml 2.4) and RDF allows any prefix — or none — +/// bound for its namespace (RDF XML Syntax 5.1), so ``, `` and `` +/// match just like `` (#11116). +fn rdf_end_tag(x: &str) -> Option<(usize, usize)> { + // Which element names can close the RDF element: `NAME:RDF` for every prefix this packet + // binds to the RDF namespace, plus the bare `RDF` when it is bound as the default. + let mut names: Vec = Vec::new(); + let mut from = 0; + while let Some(rel) = x[from..].find(RDF_NS) { + let at = from + rel; + from = at + RDF_NS.len(); + let head = &x[..at]; + // The URI sits in an attribute value; the declaration is the token before its quote. + let Some(quote) = head.rfind(['"', '\'']) else { continue }; + let before = &head[..quote]; + let decl_start = before.rfind([' ', '\t', '\r', '\n', '<']).map(|k| k + 1).unwrap_or(0); + let Some(decl) = before[decl_start..].strip_suffix('=') else { continue }; + if let Some(p) = decl.strip_prefix("xmlns:").filter(|p| !p.is_empty()) { + let name = format!("{p}:RDF"); + if !names.contains(&name) { + names.push(name); + } + } else if decl == "xmlns" && !names.iter().any(|n| n == "RDF") { + names.push("RDF".to_string()); + } + } + // Rightmost match per candidate name; a well-formed packet has exactly one RDF end tag. + for name in names { + let mut before = x.len(); + while let Some(at) = x[..before].rfind("') { + return Some((at, x.len() - tail.len() + 1)); + } + } + } + None +} + /// Rewrites only changed File Info fields of an XMP packet (creating one when there is none), /// keeping the other properties verbatim. Edited properties move into their own -/// `rdf:Description` (several descriptions per packet are valid XMP). +/// `rdf:Description` (several descriptions per packet are valid XMP). A packet whose RDF element +/// ends in a valid but non-canonical spelling is kept too: the other properties survive a field +/// edit whatever prefix or spacing the producer used (#11116). pub fn write_file_info(xmp: Option<&str>, info: &Value) -> String { let cur = read_file_info(xmp); // The dialog submits all fields, including unchanged language alternatives. let changed = |key: &str| info.get(key).is_some_and(|v| cur.get(key) != Some(v)); - let mut x = xmp.filter(|s| s.contains("")).map(str::to_string).unwrap_or_else(|| { + let mut x = xmp.filter(|s| rdf_end_tag(s).is_some()).map(str::to_string).unwrap_or_else(|| { "\n\n \n \n\n".to_string() }); for (key, prop, _) in INFO_FIELDS.into_iter().chain([("copyrightStatus", "xmpRights:Marked", ""), ("copyrightUrl", "xmpRights:WebStatement", "")]) { @@ -308,10 +355,14 @@ pub fn write_file_info(xmp: Option<&str>, info: &Value) -> String { body.push_str(&format!(" {}\n", xml_escape(u))); } if !body.is_empty() { + // The inserted description uses the `rdf:` prefix, so it must bind it itself unless + // the surrounding packet binds that prefix the same way (#11116). + let packet_binds_rdf = x.contains(&format!("xmlns:rdf=\"{RDF_NS}\"")) || x.contains(&format!("xmlns:rdf='{RDF_NS}'")); let desc = format!( - " \n{body} \n " + " \n{body} \n ", + if packet_binds_rdf { String::new() } else { format!(" xmlns:rdf=\"{RDF_NS}\"") } ); - let at = x.rfind("").unwrap_or(x.len()); + let at = rdf_end_tag(&x).map(|(a, _)| a).unwrap_or(x.len()); x.insert_str(at, &desc); } x diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 804e6a01ca..8c952882d1 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -1251,6 +1251,40 @@ fn file_info_round_trips_through_xmp_and_psd() { assert_eq!(read_file_info(Some(&out))["authorTitle"], "Artist"); } +#[test] +fn file_info_keeps_a_packet_whose_rdf_end_tag_is_spaced_or_prefixed() { + // #11116: only the literal `` retained the imported packet, so the valid + // spellings below — XML allows whitespace before the `>`, RDF allows any declared + // prefix — were replaced by a blank packet and unrelated properties were lost. + const NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + let cases = [ + format!( + r#""# + ), + format!( + r#""# + ), + format!( + r#""# + ), + ]; + for packet in cases { + let out = write_file_info(Some(&packet), &json!({"authorTitle": "Artist"})); + assert!(out.contains("xmp:CreatorTool=\"Other App\""), "the unrelated property survives: {out}"); + assert_eq!(read_file_info(Some(&out))["authorTitle"], "Artist", "the edit landed: {out}"); + // Whatever the packet binds, the inserted description binds every prefix it uses. + let desc = out[out.find(""#); + let out = write_file_info(Some(&selfclosed), &json!({"authorTitle": "Artist"})); + assert!(out.contains(" Vec { photocraft_algo::exif::build(&photocraft_algo::exif::CameraInfo { make: Some("SONY".into()), From dd88455ccb452b82c2632fd25a257617057d0aeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Tue, 3 Nov 2026 22:46:55 +0100 Subject: [PATCH 2/9] fix(xmp): review follow-ups on the RDF end-tag finder Whitespace around the equals in namespace declarations, end tags inside XML comments do not count, one reverse scan for all bound prefixes, and the inserted description binds the rdf prefix unless the RDF start tag binds it above the insertion point. --- crates/engine/src/cmd/file_cmds/info.rs | 63 +++++++++++++++++------- crates/engine/src/cmd/file_cmds/tests.rs | 12 +++++ 2 files changed, 58 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/info.rs b/crates/engine/src/cmd/file_cmds/info.rs index 381e0599a9..d660715829 100644 --- a/crates/engine/src/cmd/file_cmds/info.rs +++ b/crates/engine/src/cmd/file_cmds/info.rs @@ -258,9 +258,10 @@ pub fn camera_data(exif: Option<&[u8]>, xmp: Option<&str>) -> Value { const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; /// The byte range of the packet's RDF end tag, or `None` when it has none. XML allows -/// whitespace before a closing tag's `>` (REC-xml 2.4) and RDF allows any prefix — or none — -/// bound for its namespace (RDF XML Syntax 5.1), so ``, `` and `` -/// match just like `` (#11116). +/// whitespace around a declaration's `=` and before a closing tag's `>` (REC-xml 2.4), and RDF +/// allows any prefix — or none — bound for its namespace (RDF XML Syntax 5.1), so ``, +/// `` and `` match just like `` (#11116). Text inside `` comments +/// never counts as an end tag, so the writer always inserts inside the RDF element. fn rdf_end_tag(x: &str) -> Option<(usize, usize)> { // Which element names can close the RDF element: `NAME:RDF` for every prefix this packet // binds to the RDF namespace, plus the bare `RDF` when it is bound as the default. @@ -272,9 +273,12 @@ fn rdf_end_tag(x: &str) -> Option<(usize, usize)> { let head = &x[..at]; // The URI sits in an attribute value; the declaration is the token before its quote. let Some(quote) = head.rfind(['"', '\'']) else { continue }; - let before = &head[..quote]; + // `xmlns:r = "…"` (whitespace around the `=`) binds as validly as `xmlns:r="…"`, so the + // token ends at the `=` itself, whatever whitespace surrounds it. + let before = head[..quote].trim_end(); + let Some(before) = before.strip_suffix('=').map(str::trim_end) else { continue }; let decl_start = before.rfind([' ', '\t', '\r', '\n', '<']).map(|k| k + 1).unwrap_or(0); - let Some(decl) = before[decl_start..].strip_suffix('=') else { continue }; + let decl = &before[decl_start..]; if let Some(p) = decl.strip_prefix("xmlns:").filter(|p| !p.is_empty()) { let name = format!("{p}:RDF"); if !names.contains(&name) { @@ -284,11 +288,19 @@ fn rdf_end_tag(x: &str) -> Option<(usize, usize)> { names.push("RDF".to_string()); } } - // Rightmost match per candidate name; a well-formed packet has exactly one RDF end tag. - for name in names { - let mut before = x.len(); - while let Some(at) = x[..before].rfind(" !x[open + 4..at].contains("-->"), + None => false, + }; + let mut before = x.len(); + while let Some(at) = x[..before].rfind("') { @@ -299,6 +311,24 @@ fn rdf_end_tag(x: &str) -> Option<(usize, usize)> { None } +/// Whether the RDF element's own start tag binds the `rdf` prefix above `at`, so a description +/// inserted there can inherit the declaration (#11116). A binding only a nested element declares +/// does not reach the insertion point, and neither does one that is merely somewhere in the +/// packet; when in doubt the writer re-declares, which is always valid. +fn rdf_bound_above(x: &str, at: usize) -> bool { + let mut from = 0; + while let Some(rel) = x[from..at].find("') else { break }; + let tag = &x[start..start + end]; + if tag.contains(&format!("xmlns:rdf=\"{RDF_NS}\"")) || tag.contains(&format!("xmlns:rdf='{RDF_NS}'")) { + return true; + } + from = start + 8; + } + false +} + /// Rewrites only changed File Info fields of an XMP packet (creating one when there is none), /// keeping the other properties verbatim. Edited properties move into their own /// `rdf:Description` (several descriptions per packet are valid XMP). A packet whose RDF element @@ -355,14 +385,13 @@ pub fn write_file_info(xmp: Option<&str>, info: &Value) -> String { body.push_str(&format!(" {}\n", xml_escape(u))); } if !body.is_empty() { - // The inserted description uses the `rdf:` prefix, so it must bind it itself unless - // the surrounding packet binds that prefix the same way (#11116). - let packet_binds_rdf = x.contains(&format!("xmlns:rdf=\"{RDF_NS}\"")) || x.contains(&format!("xmlns:rdf='{RDF_NS}'")); - let desc = format!( - " \n{body} \n ", - if packet_binds_rdf { String::new() } else { format!(" xmlns:rdf=\"{RDF_NS}\"") } - ); let at = rdf_end_tag(&x).map(|(a, _)| a).unwrap_or(x.len()); + // The inserted description uses the `rdf:` prefix, so it must bind that prefix itself + // unless the RDF element's own start tag already binds it above the insertion point (#11116). + let bind = if rdf_bound_above(&x, at) { String::new() } else { format!(" xmlns:rdf=\"{RDF_NS}\"") }; + let desc = format!( + " \n{body} \n " + ); x.insert_str(at, &desc); } x diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 8c952882d1..cab4e3af58 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -1267,6 +1267,10 @@ fn file_info_keeps_a_packet_whose_rdf_end_tag_is_spaced_or_prefixed() { format!( r#""# ), + // Whitespace around the declaration's `=` (REC-xml 3.1 allows it) still binds the prefix. + format!( + r#""# + ), ]; for packet in cases { let out = write_file_info(Some(&packet), &json!({"authorTitle": "Artist"})); @@ -1278,6 +1282,14 @@ fn file_info_keeps_a_packet_whose_rdf_end_tag_is_spaced_or_prefixed() { assert!(desc.contains(&format!("xmlns:{p}=\"")) || packet.contains(&format!("xmlns:{p}=\"")), "prefix {p} unbound: {desc}"); } } + // A `` that only appears inside a comment must not be taken as the packet's end + // tag: the edit inserts before the real one, keeping it inside the RDF element (#11116). + let commented = format!( + r#""# + ); + let out = write_file_info(Some(&commented), &json!({"authorTitle": "Artist"})); + assert!(out.find("AuthorsPosition").unwrap() < out.find("` comments -/// never counts as an end tag, so the writer always inserts inside the RDF element. +/// `` and `` match just like ``. One forward pass collects the RDF +/// namespace bindings and the end tag, skipping `` comments and `` sections +/// so nothing inside them is read as markup (#11116). fn rdf_end_tag(x: &str) -> Option<(usize, usize)> { - // Which element names can close the RDF element: `NAME:RDF` for every prefix this packet - // binds to the RDF namespace, plus the bare `RDF` when it is bound as the default. + let b = x.as_bytes(); + // Names that can close the RDF element, learned as the scan goes: `P:RDF` for every prefix + // bound to the RDF namespace, plus the bare `RDF` when it is bound as the default. A prefix + // must be declared before its end tag, so it is known by the time the end tag is reached. let mut names: Vec = Vec::new(); - let mut from = 0; - while let Some(rel) = x[from..].find(RDF_NS) { - let at = from + rel; - from = at + RDF_NS.len(); - let head = &x[..at]; - // The URI sits in an attribute value; the declaration is the token before its quote. - let Some(quote) = head.rfind(['"', '\'']) else { continue }; - // `xmlns:r = "…"` (whitespace around the `=`) binds as validly as `xmlns:r="…"`, so the - // token ends at the `=` itself, whatever whitespace surrounds it. - let before = head[..quote].trim_end(); - let Some(before) = before.strip_suffix('=').map(str::trim_end) else { continue }; - let decl_start = before.rfind([' ', '\t', '\r', '\n', '<']).map(|k| k + 1).unwrap_or(0); - let decl = &before[decl_start..]; - if let Some(p) = decl.strip_prefix("xmlns:").filter(|p| !p.is_empty()) { - let name = format!("{p}:RDF"); - if !names.contains(&name) { - names.push(name); - } - } else if decl == "xmlns" && !names.iter().any(|n| n == "RDF") { - names.push("RDF".to_string()); - } - } - // One reverse pass over every ` !x[open + 4..at].contains("-->"), - None => false, - }; - let mut before = x.len(); - while let Some(at) = x[..before].rfind(" = None; + let mut i = 0usize; + while i < b.len() { + // Skip a comment or CDATA in one step: its contents are character data, never a + // declaration or a real end tag, and a hidden or fake `` inside one must not + // hide the true end tag or trick the writer into inserting there (#11116). + if b[i..].starts_with(b"").map_or(b.len(), |e| i + 7 + e); continue; } - for name in &names { - let Some(after) = x[at + 2..].strip_prefix(name.as_str()) else { continue }; - let tail = after.trim_start_matches([' ', '\t', '\r', '\n']); - if tail.starts_with('>') { - return Some((at, x.len() - tail.len() + 1)); + if b[i..].starts_with(b"").map_or(b.len(), |e| i + 12 + e); + continue; + } + if b[i..].starts_with(b"xmlns") { + if let Some((name, next)) = parse_rdf_xmlns(x, i) { + if let Some(n) = name.filter(|n| !names.contains(n)) { + names.push(n); + } + i = next; + continue; } } + if b[i..].starts_with(b"') { + found = Some((i, x.len() - tail.len() + 1)); + break; + } + } + i += 2; + continue; + } + i += 1; } - None + found +} + +/// Parse the `xmlns[:prefix] = "uri"` namespace declaration starting at `i` in `x` (`x[i..]` is +/// known to begin with `xmlns`). Returns the RDF element name the declaration binds — `P:RDF`, or +/// the bare `RDF` for a default binding — when the URI is the RDF namespace, or `None` when it +/// binds another namespace, together with the byte index just past the declaration. Whitespace +/// around `=` and either quote style are accepted (REC-xml 3.1, 2.3). +fn parse_rdf_xmlns(x: &str, i: usize) -> Option<(Option, usize)> { + let b = x.as_bytes(); + let ws = |j: &mut usize| { + while matches!(b.get(*j), Some(b' ') | Some(b'\t') | Some(b'\r') | Some(b'\n')) { + *j += 1 + } + }; + let mut j = i + "xmlns".len(); + let mut prefix = String::new(); + if b.get(j) == Some(&b':') { + j += 1; + let s = j; + while matches!(b.get(j), Some(c) if c.is_ascii_alphanumeric() || matches!(c, b'.' | b'-' | b'_')) { + j += 1; + } + if j == s { + return None; + } + prefix.push_str(&x[s..j]); + } + ws(&mut j); + if b.get(j) != Some(&b'=') { + return None; + } + j += 1; + ws(&mut j); + let quote = *b.get(j)?; + if quote != b'"' && quote != b'\'' { + return None; + } + j += 1; + let s = j; + while b.get(j).is_some_and(|&c| c != quote) { + j += 1; + } + if b.get(j) != Some("e) { + return None; + } + let uri = &x[s..j]; + j += 1; + if uri != RDF_NS { + return Some((None, j)); + } + Some((Some(if prefix.is_empty() { "RDF".to_string() } else { format!("{prefix}:RDF") }), j)) } /// Whether the RDF element's own start tag binds the `rdf` prefix above `at`, so a description -/// inserted there can inherit the declaration (#11116). A binding only a nested element declares -/// does not reach the insertion point, and neither does one that is merely somewhere in the -/// packet; when in doubt the writer re-declares, which is always valid. +/// inserted there can inherit the declaration (#11116). The start tag is matched by its complete +/// element name (a lookalike like `` is not the RDF element), skipping comments and +/// CDATA. When in doubt the writer re-declares `rdf`, which is always valid. fn rdf_bound_above(x: &str, at: usize) -> bool { - let mut from = 0; - while let Some(rel) = x[from..at].find("') else { break }; - let tag = &x[start..start + end]; - if tag.contains(&format!("xmlns:rdf=\"{RDF_NS}\"")) || tag.contains(&format!("xmlns:rdf='{RDF_NS}'")) { - return true; + let b = x.as_bytes(); + let mut i = 0usize; + while i < at { + if b[i..].starts_with(b"").map_or(at, |e| i + 7 + e); + continue; } - from = start + 8; + if b[i..].starts_with(b"").map_or(at, |e| i + 12 + e); + continue; + } + if b[i..].starts_with(b"`; `'); + if name_ends { + if let Some(end) = x[after..at].find('>') { + let tag = &x[after..after + end]; + if tag.contains(&format!("xmlns:rdf=\"{RDF_NS}\"")) || tag.contains(&format!("xmlns:rdf='{RDF_NS}'")) { + return true; + } + } + } + i = after; + continue; + } + i += 1; } false } diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index cab4e3af58..15d076940f 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -1290,6 +1290,23 @@ fn file_info_keeps_a_packet_whose_rdf_end_tag_is_spaced_or_prefixed() { let out = write_file_info(Some(&commented), &json!({"authorTitle": "Artist"})); assert!(out.find("AuthorsPosition").unwrap() < out.find("` comments and `` sections -/// so nothing inside them is read as markup (#11116). +/// `` and `` match just like ``. One forward pass keeps a stack of the +/// open elements' namespace declarations and resolves each closing tag's prefix in the scope of +/// the element it closes, so a prefix rebound to another namespace (on a sibling or a nested +/// element) never makes a foreign `` the end tag (Namespaces in XML 1.0, section 6). The +/// pass skips `` comments, `` sections, processing instructions and +/// declarations, so nothing inside them is read as markup, and it reads declarations only inside +/// start tags and outside quoted attribute values (#11116). The last RDF end tag wins. fn rdf_end_tag(x: &str) -> Option<(usize, usize)> { let b = x.as_bytes(); - // Names that can close the RDF element, learned as the scan goes: `P:RDF` for every prefix - // bound to the RDF namespace, plus the bare `RDF` when it is bound as the default. A prefix - // must be declared before its end tag, so it is known by the time the end tag is reached. - // Bindings are collected document-wide rather than per element scope: a packet that rebinds - // an RDF prefix to another namespace on a nested element exists in no known producer, and - // the worst that could then happen is the edit inserting before a lookalike end tag of the - // same spelling — a well-formed placement the reader still finds. Per-scope tracking would - // need a full XML parser for a case the admission filter already survives. - let mut names: Vec = Vec::new(); + let is_ws = |c: u8| matches!(c, b' ' | b'\t' | b'\r' | b'\n'); + // One entry per open element: the `(prefix, binds the RDF namespace)` pairs its start tag + // declares; the default namespace is the empty prefix. + let mut scopes: Vec> = Vec::new(); + let resolves_to_rdf = |scopes: &[Vec<(String, bool)>], name: &str| { + let (prefix, local) = name.split_once(':').unwrap_or(("", name)); + local == "RDF" && scopes.iter().rev().flatten().rev().find(|(p, _)| p == prefix).is_some_and(|(_, rdf)| *rdf) + }; let mut found: Option<(usize, usize)> = None; let mut i = 0usize; while i < b.len() { - // Skip a comment or CDATA in one step: its contents are character data, never a - // declaration or a real end tag, and a hidden or fake `` inside one must not - // hide the true end tag or trick the writer into inserting there (#11116). + if b[i] != b'<' { + i += 1; + continue; + } + // Skip a comment, CDATA section, processing instruction or declaration in one step: its + // contents are character data, never a declaration or a real end tag, and a hidden or + // fake `` inside one must not hide the true end tag or trick the writer into + // inserting there (#11116). if b[i..].starts_with(b"").map_or(b.len(), |e| i + 7 + e); continue; @@ -346,68 +354,91 @@ fn rdf_end_tag(x: &str) -> Option<(usize, usize)> { i = x[i + 9..].find("]]>").map_or(b.len(), |e| i + 12 + e); continue; } - if b[i..].starts_with(b"xmlns") - && in_start_tag(x, i) - && let Some((name, next)) = parse_rdf_xmlns(x, i) - { - if let Some(n) = name.filter(|n| !names.contains(n)) { - names.push(n); - } - i = next; + if b[i..].starts_with(b"").map_or(b.len(), |e| i + 4 + e); + continue; + } + if b[i..].starts_with(b"').map_or(b.len(), |e| i + 3 + e); continue; } if b[i..].starts_with(b"') { - found = Some((i, x.len() - tail.len() + 1)); - break; + let name_start = i + 2; + let name_end = x[name_start..].find(|c: char| c.is_ascii() && (is_ws(c as u8) || c == '>')).map_or(b.len(), |e| name_start + e); + let tail = x[name_end..].trim_start_matches([' ', '\t', '\r', '\n']); + if tail.starts_with('>') { + let end = x.len() - tail.len() + 1; + if resolves_to_rdf(&scopes, &x[name_start..name_end]) { + found = Some((i, end)); } + scopes.pop(); + i = end; + } else { + i = name_end.max(i + 2); } - i += 2; continue; } - i += 1; + // A start tag: the element name, then attributes up to the closing `>`. + let name_start = i + 1; + let name_end = x[name_start..].find(|c: char| c.is_ascii() && (is_ws(c as u8) || c == '/' || c == '>')).map_or(b.len(), |e| name_start + e); + if name_end == name_start { + // A lone `<` (not followed by a name) opens nothing. + i += 1; + continue; + } + let mut decls: Vec<(String, bool)> = Vec::new(); + let mut quote: Option = None; + let mut self_closed = false; + let mut closed = false; + let mut j = name_end; + while let Some(&c) = b.get(j) { + match quote { + Some(q) => { + if c == q { + quote = None; + } + j += 1; + } + None if c == b'"' || c == b'\'' => { + quote = Some(c); + j += 1; + } + None if c == b'>' => { + self_closed = b.get(j - 1) == Some(&b'/'); + closed = true; + j += 1; + break; + } + // A declaration starts an attribute: after whitespace, never inside a longer name. + None if b[j..].starts_with(b"xmlns") && b.get(j - 1).is_some_and(|&p| is_ws(p)) => match parse_xmlns(x, j) { + Some((prefix, rdf, next)) => { + decls.push((prefix, rdf)); + j = next; + } + None => j += 1, + }, + None => j += 1, + } + } + if !closed { + // A truncated start tag: nothing after it is markup. + break; + } + if !self_closed { + scopes.push(decls); + } + i = j; } found } - -/// The `xmlns` token at `at` sits inside an element's start tag — not in character data, where a -/// File Info text value could mention `xmlns:x="…"` and bind nothing at all; not in a processing -/// instruction or doctype, whose pseudo-attributes bind nothing either; and not inside another -/// attribute's quoted value, where `xmlns:` is plain text (#11116). -fn in_start_tag(x: &str, at: usize) -> bool { - let Some(lt) = x[..at].rfind('<') else { return false }; - // A start tag's `<` is followed by the element name; ` = None; - for c in x[lt + 1..at].chars() { - match quote { - Some(q) if c == q => quote = None, - Some(_) => {} - None if c == '"' || c == '\'' => quote = Some(c), - None if c == '>' => return false, - None => {} - } - } - // A token still inside quotes is text of an attribute value, not a declaration. - quote.is_none() -} - /// Parse the `xmlns[:prefix] = "uri"` namespace declaration starting at `i` in `x` (`x[i..]` is -/// known to begin with `xmlns`, inside a start tag). Returns the RDF element name the -/// declaration binds — `P:RDF`, or the bare `RDF` for a default binding — when the URI is the -/// RDF namespace, or `None` when it binds another namespace, together with the byte index just -/// past the declaration. Whitespace around `=` and either quote style are accepted (REC-xml 3.1, +/// known to begin with `xmlns`, inside a start tag). Returns the declared prefix (empty for the +/// default namespace), whether the URI is the RDF namespace, and the byte index just past the +/// declaration, or `None` when the text is no declaration. Whitespace around `=` and either quote style are accepted (REC-xml 3.1, /// 2.3); a prefix may contain any XML Name character, Unicode letters included (Namespaces in /// XML 1.0, NCName); and a URI written with character references binds what its decoded form /// names (REC-xml 4.1 attribute-value normalization). -fn parse_rdf_xmlns(x: &str, i: usize) -> Option<(Option, usize)> { +fn parse_xmlns(x: &str, i: usize) -> Option<(String, bool, usize)> { let b = x.as_bytes(); let ws = |j: &mut usize| { while matches!(b.get(*j), Some(b' ') | Some(b'\t') | Some(b'\r') | Some(b'\n')) { @@ -449,10 +480,7 @@ fn parse_rdf_xmlns(x: &str, i: usize) -> Option<(Option, usize)> { } let uri = &x[s..j]; j += 1; - if decode_char_refs(uri).as_deref() != Some(RDF_NS) { - return Some((None, j)); - } - Some((Some(if prefix.is_empty() { "RDF".to_string() } else { format!("{prefix}:RDF") }), j)) + Some((prefix, decode_char_refs(uri).as_deref() == Some(RDF_NS), j)) } /// The value of an attribute after replacing its numeric character references (`#`, `#`) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index a5bd51e399..55fb20b0d5 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2246,6 +2246,37 @@ fn file_info_reads_declarations_the_way_an_xml_reader_does() { assert_eq!(read_file_info(Some(&out))["authorTitle"], "Artist"); } +/// A prefix bound to the RDF namespace in one element and rebound to another namespace in a later +/// sibling is two different names: only the closing tag that resolves to the RDF namespace in its +/// own scope is the RDF end tag, so the edit never lands in the foreign element (#11116). +#[test] +fn file_info_resolves_the_rdf_end_tag_in_namespace_scope() { + const NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + // The prefix is rebound to a foreign namespace on a later sibling `r:RDF`. + let rebound = format!( + r#""# + ); + let out = write_file_info(Some(&rebound), &json!({"authorTitle": "Artist"})); + let (edit, real, foreign) = (out.find("AuthorsPosition").unwrap(), out.find("").unwrap(), out.rfind("").unwrap()); + assert!(edit < real && real < foreign, "the edit sits in the RDF-namespace element, not the foreign one: {out}"); + assert!(out.contains("xmp:CreatorTool=\"Other App\""), "{out}"); + // The same through a default namespace: `` is foreign where `xmlns` is rebound. + let default_rebound = format!( + r#""# + ); + let out = write_file_info(Some(&default_rebound), &json!({"authorTitle": "Artist"})); + let (edit, real) = (out.find("AuthorsPosition").unwrap(), out.find("").unwrap()); + assert!(edit < real, "the edit sits in the RDF-namespace element: {out}"); + // An inner rebinding does not leak out of its element: the outer `r:RDF` still closes the RDF. + let nested = format!( + r#""# + ); + let out = write_file_info(Some(&nested), &json!({"authorTitle": "Artist"})); + let inner = out.find("").unwrap(); + assert!(out.find("AuthorsPosition").unwrap() > inner, "the edit is after the foreign element, in the real RDF: {out}"); + assert!(out.find("AuthorsPosition").unwrap() < out.rfind("").unwrap(), "{out}"); +} + fn camera_exif() -> Vec { photocraft_algo::exif::build(&photocraft_algo::exif::CameraInfo { make: Some("SONY".into()), From d4a437670acbbb84d61af9972ed0e39a34997e55 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 11:36:54 +0100 Subject: [PATCH 8/9] fix(xmp): resolve rdf for the inserted description in the open element scope rdf_bound_above kept the last Option<(usize, usize)> { + rdf_end_scan(x).map(|(a, b, _)| (a, b)) +} + +/// [`rdf_end_tag`]'s range plus whether the `rdf` prefix is bound to the RDF namespace in the scope +/// of the element that range closes, which is the scope a description inserted at its start sits +/// in. The scope is the stack of the elements open at that point, so an earlier `rdf:RDF` that has +/// already closed (or closed on the spot) contributes nothing, and a rebinding of `rdf` to another +/// namespace on that element or an ancestor counts as unbound (#11116). +fn rdf_end_scan(x: &str) -> Option<(usize, usize, bool)> { let b = x.as_bytes(); let is_ws = |c: u8| matches!(c, b' ' | b'\t' | b'\r' | b'\n'); // One entry per open element: the `(prefix, binds the RDF namespace)` pairs its start tag @@ -335,7 +344,7 @@ fn rdf_end_tag(x: &str) -> Option<(usize, usize)> { let (prefix, local) = name.split_once(':').unwrap_or(("", name)); local == "RDF" && scopes.iter().rev().flatten().rev().find(|(p, _)| p == prefix).is_some_and(|(_, rdf)| *rdf) }; - let mut found: Option<(usize, usize)> = None; + let mut found: Option<(usize, usize, bool)> = None; let mut i = 0usize; while i < b.len() { if b[i] != b'<' { @@ -369,7 +378,7 @@ fn rdf_end_tag(x: &str) -> Option<(usize, usize)> { if tail.starts_with('>') { let end = x.len() - tail.len() + 1; if resolves_to_rdf(&scopes, &x[name_start..name_end]) { - found = Some((i, end)); + found = Some((i, end, resolves_to_rdf(&scopes, "rdf:RDF"))); } scopes.pop(); i = end; @@ -509,50 +518,6 @@ fn decode_char_refs(s: &str) -> Option { Some(out) } -/// Whether the open RDF element's start tag binds the `rdf` prefix above `at`, so a description -/// inserted there can inherit the declaration (#11116). The element that closes at `at` is the -/// nearest non-self-closed ` bool { - let b = x.as_bytes(); - let mut open: Option<(usize, usize)> = None; - let mut i = 0usize; - while i < at { - if b[i..].starts_with(b"").map_or(at, |e| i + 7 + e); - continue; - } - if b[i..].starts_with(b"").map_or(at, |e| i + 12 + e); - continue; - } - if b[i..].starts_with(b"`; `'); - if name_ends && let Some(end) = x[after..at].find('>') { - let tag_end = after + end; - // `` closed on the spot: it is not the open element's start tag. - if b.get(tag_end - 1) != Some(&b'/') { - open = Some((after, tag_end)); - } - } - i = after; - continue; - } - i += 1; - } - match open { - Some((start, end)) => { - let tag = &x[start..end]; - tag.contains(&format!("xmlns:rdf=\"{RDF_NS}\"")) || tag.contains(&format!("xmlns:rdf='{RDF_NS}'")) - } - None => false, - } -} - /// Rewrites only changed File Info fields of an XMP packet (creating one when there is none), /// keeping the other properties verbatim. Edited properties move into their own /// `rdf:Description` (several descriptions per packet are valid XMP). A packet whose RDF element @@ -612,10 +577,10 @@ pub fn write_file_info(xmp: Option<&str>, info: &Value) -> String { body.push_str(&format!(" {}\n", xml_escape(u))); } if !body.is_empty() { - let at = rdf_end_tag(&x).map(|(a, _)| a).unwrap_or(x.len()); + let (at, bound) = rdf_end_scan(&x).map_or((x.len(), false), |(a, _, bound)| (a, bound)); // The inserted description uses the `rdf:` prefix, so it must bind that prefix itself - // unless the RDF element's own start tag already binds it above the insertion point (#11116). - let bind = if rdf_bound_above(&x, at) { String::new() } else { format!(" xmlns:rdf=\"{RDF_NS}\"") }; + // unless the elements open at the insertion point already bind it (#11116). + let bind = if bound { String::new() } else { format!(" xmlns:rdf=\"{RDF_NS}\"") }; let desc = format!( " \n{body} \n " ); diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 55fb20b0d5..71bd0191ae 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2246,6 +2246,43 @@ fn file_info_reads_declarations_the_way_an_xml_reader_does() { assert_eq!(read_file_info(Some(&out))["authorTitle"], "Artist"); } +/// The `rdf` prefix of the inserted description is resolved in the scope of the element it lands +/// in, not taken from an earlier `rdf:RDF` that already closed (#11116). Each output is parsed +/// as namespace-aware XML: a description whose `rdf` prefix is unbound reads as a plain +/// `Description`, so two `rdf:Description` elements prove the prefix resolved. +#[test] +fn file_info_binds_rdf_for_the_description_from_the_open_element_scope() { + const NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + let rdf_descriptions = |out: &str| { + let namespaces = [("rdf", NS), ("xmp", "http://ns.adobe.com/xap/1.0/"), ("photoshop", "http://ns.adobe.com/photoshop/1.0/"), ("x", "adobe:ns:meta/")]; + let canonical = craft_xml::Canonical::new(&namespaces); + let doc = craft_xml::Options::canonical(&canonical).parse(out.as_bytes()).expect("the output is well-formed XML"); + let names: Vec = doc.descendants().filter(|e| e.name.ends_with("Description")).map(|e| e.name.clone()).collect(); + names + }; + // An ordinary closed `rdf:RDF` sibling comes first; the edit lands in the later `q:RDF`, which + // does not bind `rdf` at all. + let closed_sibling = format!( + r#""# + ); + let out = write_file_info(Some(&closed_sibling), &json!({"authorTitle": "Artist"})); + assert!(out.contains("xmp:CreatorTool=\"Other App\""), "the later RDF element is kept: {out}"); + assert_eq!(rdf_descriptions(&out), ["rdf:Description", "rdf:Description"], "the inserted description binds rdf: {out}"); + assert_eq!(read_file_info(Some(&out))["authorTitle"], "Artist"); + // The element the edit lands in binds `rdf` to a foreign namespace: re-declare it. + let foreign_rdf = format!( + r#""# + ); + let out = write_file_info(Some(&foreign_rdf), &json!({"authorTitle": "Artist"})); + assert_eq!(rdf_descriptions(&out), ["rdf:Description", "rdf:Description"], "{out}"); + // The canonical case keeps its single declaration: the element binds `rdf` and the inserted + // description does not repeat it. + let canonical = format!(r#""#); + let out = write_file_info(Some(&canonical), &json!({"authorTitle": "Artist"})); + assert_eq!(rdf_descriptions(&out), ["rdf:Description", "rdf:Description"], "{out}"); + assert_eq!(out.matches(&format!("xmlns:rdf=\"{NS}\"")).count(), 1, "{out}"); +} + /// A prefix bound to the RDF namespace in one element and rebound to another namespace in a later /// sibling is two different names: only the closing tag that resolves to the RDF namespace in its /// own scope is the RDF end tag, so the edit never lands in the foreign element (#11116). From f11647cce390ae597eb4bca95725ced2ee26bee5 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Mon, 16 Nov 2026 17:27:19 +0100 Subject: [PATCH 9/9] fix(file-info): resolve a namespace prefix in the innermost scope first rdf_end_scan searched the open scopes with iter().rev().flatten().rev(), which reverses the flattened list a second time, so an outer declaration won over an inner rebinding. An ancestor binding rdf to the RDF namespace then hid an inner xmlns:rdf="urn:other": the inserted rdf:Description landed in the foreign namespace, and a shadowed could be taken for the RDF end tag. Search the scopes innermost first. A parsed-XML regression covers an ancestor binding with an inner rebinding at the insertion point, and a shadowed closing tag in a later element. --- crates/engine/src/cmd/file_cmds/info.rs | 4 ++- crates/engine/src/cmd/file_cmds/tests.rs | 33 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file_cmds/info.rs b/crates/engine/src/cmd/file_cmds/info.rs index 96c8ef1da8..f1c93b0bc4 100644 --- a/crates/engine/src/cmd/file_cmds/info.rs +++ b/crates/engine/src/cmd/file_cmds/info.rs @@ -340,9 +340,11 @@ fn rdf_end_scan(x: &str) -> Option<(usize, usize, bool)> { // One entry per open element: the `(prefix, binds the RDF namespace)` pairs its start tag // declares; the default namespace is the empty prefix. let mut scopes: Vec> = Vec::new(); + // The innermost open element that declares the prefix decides (Namespaces in XML 1.0, + // section 6): search the scopes from the innermost outwards, never the flattened list backwards. let resolves_to_rdf = |scopes: &[Vec<(String, bool)>], name: &str| { let (prefix, local) = name.split_once(':').unwrap_or(("", name)); - local == "RDF" && scopes.iter().rev().flatten().rev().find(|(p, _)| p == prefix).is_some_and(|(_, rdf)| *rdf) + local == "RDF" && scopes.iter().rev().flat_map(|scope| scope.iter().rev()).find(|(p, _)| p == prefix).is_some_and(|(_, rdf)| *rdf) }; let mut found: Option<(usize, usize, bool)> = None; let mut i = 0usize; diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 7100bb2539..4e636e2fbb 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2355,6 +2355,39 @@ fn file_info_binds_rdf_for_the_description_from_the_open_element_scope() { assert_eq!(out.matches(&format!("xmlns:rdf=\"{NS}\"")).count(), 1, "{out}"); } +/// A prefix that an ancestor binds and an inner element rebinds resolves to the INNER binding +/// (Namespaces in XML 1.0, section 6): the innermost open scope is searched first (#11116, +/// review of 952741fe). Both outputs are parsed as namespace-aware XML. +#[test] +fn file_info_resolves_a_prefix_in_the_innermost_scope_that_binds_it() { + const NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + let rdf_descriptions = |out: &str| { + let namespaces = [("rdf", NS), ("xmp", "http://ns.adobe.com/xap/1.0/"), ("photoshop", "http://ns.adobe.com/photoshop/1.0/"), ("x", "adobe:ns:meta/")]; + let canonical = craft_xml::Canonical::new(&namespaces); + let doc = craft_xml::Options::canonical(&canonical).parse(out.as_bytes()).expect("the output is well-formed XML"); + let names: Vec = doc.descendants().filter(|e| e.name.ends_with("Description")).map(|e| e.name.clone()).collect(); + names + }; + // The ancestor binds `rdf` to the RDF namespace, the element the edit lands in rebinds it to a + // foreign one: the inserted description must declare `rdf` itself. + let shadowed = format!( + r#""# + ); + let out = write_file_info(Some(&shadowed), &json!({"authorTitle": "Artist"})); + assert!(out.contains("xmp:CreatorTool=\"Other App\""), "the packet is kept: {out}"); + assert_eq!(rdf_descriptions(&out), ["rdf:Description", "rdf:Description"], "the inserted description belongs to the RDF namespace: {out}"); + assert_eq!(read_file_info(Some(&out))["authorTitle"], "Artist"); + // The ancestor binds `r` to the RDF namespace; a later element rebinds `r` and holds its own + // ``: that closing tag names a foreign element and is not the RDF end tag. + let shadowed_end = format!( + r#""# + ); + let out = write_file_info(Some(&shadowed_end), &json!({"authorTitle": "Artist"})); + let (edit, real, foreign) = (out.find("AuthorsPosition").unwrap(), out.find("").unwrap(), out.rfind("").unwrap()); + assert!(edit < real && real < foreign, "the edit lands in the RDF element, not in the shadowed one: {out}"); + assert_eq!(read_file_info(Some(&out))["authorTitle"], "Artist"); +} + /// A prefix bound to the RDF namespace in one element and rebound to another namespace in a later /// sibling is two different names: only the closing tag that resolves to the RDF namespace in its /// own scope is the RDF end tag, so the edit never lands in the foreign element (#11116).