diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 70a929de8..c4d3fe6e4 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -107,3 +107,6 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper ## Score serializers `crates/score` extracts SoundCraft MusicXML and SVG score writing from `crates/engine/src/score.rs` at main `648ed9db9a0e98cc55643babffac381521a556c8`, with per-pitch ties adapted from [SoundCraft #182](https://github.com/storytold/soundcraft/pull/182) at `21cb618d93ec0e8d4771ac534994de8d5996ff10`. Source is MIT OR Apache-2.0. Import commits preserve Brandon Thomas, NetterSilver, Samuel Bacaro and Vikram Bhaskaran as primary authors of their respective changes. The consumer retains session mapping and layout. Shared API wiring, validation and focused tests are subsequent Dylan M. Taylor changes. +## Non-seeking WAV primitives + +`crates/audio/src/wav_stream.rs` is extracted from AniCraft `crates/audio/src/wav.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0). Tanish Manku is retained as the primary import author, from original commit `30c121d269a49d9abe54a3834ed4aa0201542535`. Odd-data padding accounting, shared API documentation and regression tests are subsequent Dylan M. Taylor changes. diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index c7382a973..e4a1c1695 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -775,3 +775,7 @@ mod tests { /// DVD and Blu-ray LPCM packet decoding. pub mod lpcm; + +/// Non-seeking canonical WAV streaming primitives. +#[cfg(feature = "pcm-encode")] +pub mod wav_stream; diff --git a/crates/audio/src/wav_stream.rs b/crates/audio/src/wav_stream.rs new file mode 100644 index 000000000..9da2bdcc9 --- /dev/null +++ b/crates/audio/src/wav_stream.rs @@ -0,0 +1,119 @@ +//! Canonical RIFF/WAVE header and interleaved sample blocks for non-seekable sinks. +//! +//! Extracted from AniCraft's WAV writer, preserving its byte-level compatibility. +//! Unlike `FileEncoder`, these primitives do not require `Seek` and leave final lengths, +//! chunk padding and sink error handling to the caller. The caller must supply a complete +//! frame count and append exactly that many frames. For odd-length data, append a pad byte +//! (the header includes that padding in the RIFF size); current AniCraft output is always stereo (even). +//! Non-finite samples become silence, including float output. This deliberately differs +//! from the general encoder's infinity handling. Prefer `FileEncoder` for new seekable sinks. + +/// Sample formats written. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Bits { + /// Signed 16-bit PCM. + Int16, + /// Signed 24-bit PCM. + Int24, + /// IEEE 754 32-bit float. + Float32, +} + +impl Bits { + fn bytes(self) -> u16 { + match self { + Bits::Int16 => 2, + Bits::Int24 => 3, + Bits::Float32 => 4, + } + } +} + +const PCM: u16 = 1; +const FLOAT: u16 = 3; + +/// A WAV header for `frames` frames of `channels` channels. +/// Returns `None` for zero rate/channels or any size/byte-rate field overflow. +pub fn header(rate: u32, channels: u16, bits: Bits, frames: u64) -> Option> { + if rate == 0 || channels == 0 { + return None; + } + let b = bits.bytes(); + let data = u32::try_from(frames.checked_mul(u64::from(b) * u64::from(channels))?).ok()?; + let riff = data.checked_add(36)?.checked_add(data & 1)?; + let block = channels.checked_mul(b)?; + let byte_rate = rate.checked_mul(u32::from(block))?; + let tag = if bits == Bits::Float32 { FLOAT } else { PCM }; + let mut h = Vec::with_capacity(44); + h.extend_from_slice(b"RIFF"); + h.extend_from_slice(&riff.to_le_bytes()); + h.extend_from_slice(b"WAVEfmt "); + h.extend_from_slice(&16u32.to_le_bytes()); + h.extend_from_slice(&tag.to_le_bytes()); + h.extend_from_slice(&channels.to_le_bytes()); + h.extend_from_slice(&rate.to_le_bytes()); + h.extend_from_slice(&byte_rate.to_le_bytes()); + h.extend_from_slice(&block.to_le_bytes()); + h.extend_from_slice(&(b * 8).to_le_bytes()); + h.extend_from_slice(b"data"); + h.extend_from_slice(&data.to_le_bytes()); + Some(h) +} + +/// Appends samples in `bits` format. Integers are rounded and clipped to range; `x · 32768` +/// for 16-bit, so 16-bit sources read by [`crate::decode`] come back bit-identical. +pub fn append(out: &mut Vec, samples: &[f32], bits: Bits) { + out.reserve(samples.len() * usize::from(bits.bytes())); + for &s in samples { + let s = if s.is_finite() { s } else { 0.0 }; + match bits { + Bits::Int16 => out.extend_from_slice(&((s * 32_768.0).round().clamp(-32_768.0, 32_767.0) as i16).to_le_bytes()), + Bits::Int24 => { + let v = (f64::from(s) * 8_388_608.0).round().clamp(-8_388_608.0, 8_388_607.0) as i32; + out.extend_from_slice(v.to_le_bytes().get(..3).unwrap_or(&[0, 0, 0])); + } + Bits::Float32 => out.extend_from_slice(&s.to_le_bytes()), + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + + #[test] + fn canonical_header_and_odd_padding() { + let h = header(48_000, 2, Bits::Int16, 1).unwrap(); + assert_eq!(h.len(), 44); + assert_eq!(&h[..12], b"RIFF\x28\0\0\0WAVE"); + assert_eq!(&h[28..36], &[0, 238, 2, 0, 4, 0, 16, 0]); + let h = header(8_000, 1, Bits::Int24, 1).unwrap(); + assert_eq!(&h[4..8], &40u32.to_le_bytes()); + assert_eq!(&h[40..44], &3u32.to_le_bytes()); + assert!(header(0, 2, Bits::Int16, 1).is_none()); + assert!(header(48_000, 0, Bits::Int16, 1).is_none()); + assert!(header(u32::MAX, 2, Bits::Int16, 1).is_none()); + assert!(header(48_000, 2, Bits::Float32, u64::MAX).is_none()); + assert!(header(48_000, u16::MAX, Bits::Float32, 0).is_none()); + } + + #[test] + fn samples_preserve_rounding_clipping_silence_and_chunk_boundaries() { + let samples = [-2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY]; + let mut pcm = Vec::new(); + append(&mut pcm, &samples, Bits::Int16); + let expected = [-32768i16, -32768, -16384, 0, 16384, 32767, 32767, 0, 0, 0]; + assert_eq!(pcm, expected.iter().flat_map(|s| s.to_le_bytes()).collect::>()); + for bits in [Bits::Int16, Bits::Int24, Bits::Float32] { + let mut whole = Vec::new(); + append(&mut whole, &samples, bits); + let mut blocks = Vec::new(); + for block in samples.chunks(3) { + append(&mut blocks, block, bits); + } + assert_eq!(whole, blocks); + assert_eq!(&whole[whole.len() - 3 * usize::from(bits.bytes())..], vec![0; 3 * usize::from(bits.bytes())]); + } + } +} diff --git a/crates/odf/src/text/import.rs b/crates/odf/src/text/import.rs index 486e67a26..fcd98b164 100644 --- a/crates/odf/src/text/import.rs +++ b/crates/odf/src/text/import.rs @@ -823,8 +823,8 @@ struct Parsed { kept: super::parts::Kept, /// Hidden form controls, kept for the next save. hidden_controls: Vec, - /// The page background picture's bytes and fill. - page_image: Option<(Vec, &'static str)>, + /// The page background picture's bytes, fill, and optional fill image name. + page_image: Option<(Vec, &'static str, Option)>, } /// Hyphenation is a paragraph's in ODF (`fo:hyphenate`) and the document's in WordCraft (as in @@ -911,8 +911,19 @@ fn parse_tracked(bytes: &[u8], paper: (f32, f32)) -> Result { // A frame may point at any entry, as often as it likes: `Pictures` keeps that bounded. pictures.get(&mut z, path) }; - // The page background picture's bytes. - let page_image = pages.doc.page_image.clone().and_then(|(href, fill)| fetch(&href).map(|b| (b, fill))); + // The page background picture's bytes: modern draw:fill="bitmap" preferred when valid, + // falling back to legacy style:background-image if modern is missing or not an image. + let page_image = { + let modern = pages.doc.page_image.clone().and_then(|(href, fill, name)| { + let bytes = fetch(&href)?; + if model::sniff_image(&bytes).is_some() { Some((bytes, fill, name)) } else { None } + }); + modern.or_else(|| { + let (href, fill) = pages.doc.legacy_image.clone()?; + let bytes = fetch(&href)?; + if model::sniff_image(&bytes).is_some() { Some((bytes, fill, None)) } else { None } + }) + }; let objects = (entries.as_slice(), &manifest); // One `text:s` budget for the headers and footers and then the body. let mut spaces_left = MAX_EXTRA_SPACES; @@ -1096,11 +1107,15 @@ pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result doc.settings.odf = Some(craft_wordmodel::OdfLayout { tabs_from_indent }); doc.settings.sum_paragraph_spacing = sum_spacing; // The page background picture (Design › Page Color › Fill Effects › Picture). - if let Some((bytes, fill)) = page_image + if let Some((bytes, fill, name)) = page_image && let Some(ext) = model::sniff_image(&bytes) { let media = doc.add_media(bytes, ext); - doc.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: fill.to_string(), title: String::new() }); + doc.settings.page_picture = Some(craft_wordmodel::PagePicture { + media, + fill_type: fill.to_string(), + title: name.map(|n| n.chars().take(255).collect()).unwrap_or_default(), + }); } if let Some((fmt, props)) = page_doc.notes[0] { (doc.settings.footnote_format, doc.settings.footnote_pr) = (fmt, props); @@ -1172,9 +1187,11 @@ pub(super) struct Pages { #[derive(Clone, Default)] pub(super) struct PageDoc { pub(super) page_color: Option, - /// The first page style's background picture (§17.3 `style:background-image`): its package - /// path and WordCraft's fill for its repeat (tiled, stretched, or centred at its size). - pub(super) page_image: Option<(String, &'static str)>, + /// The first page style's background picture (§17.3 `style:background-image` or §16.42 + /// `draw:fill-image` with `draw:fill="bitmap"`): package path, fill, and optional fill name. + pub(super) page_image: Option<(String, &'static str, Option)>, + /// Legacy fallback background picture from §17.3 `style:background-image`. + pub(super) legacy_image: Option<(String, &'static str)>, /// Footnotes', then endnotes', number format and options. pub(super) notes: [Option<(craft_wordmodel::section::NumFormat, craft_wordmodel::section::NoteProps)>; 2], } @@ -1248,12 +1265,43 @@ struct Layout { attrs: Attrs, /// Its background picture: package path and fill (see [`PageDoc::page_image`]). image: Option<(String, &'static str)>, + /// Its bitmap fill image name (`draw:fill-image-name`). + image_name: Option, + /// Its legacy background picture: package path and fill (§17.3 `style:background-image`). + legacy_image: Option<(String, &'static str)>, columns: Option, column_specs: Vec, header: Band, footer: Band, } +/// The background fill picture and its fill-image name from `page-layout-properties` +/// attributes `a` when modern `draw:fill="bitmap"` is declared (§16.42). +fn page_layout_fill(a: &super::xml::Attrs, fill_images: &HashMap) -> Option<((String, &'static str), String)> { + if get(a, "draw:fill") != Some("bitmap") { + return None; + } + let name = get(a, "draw:fill-image-name")?; + let href = fill_images.get(name)?; + let fill = match get(a, "style:repeat").map(str::trim) { + Some("no-repeat") => "center", + Some("stretch") => "frame", + _ => "tile", + }; + Some(((href.clone(), fill), name.to_string())) +} + +/// The page background picture and fill from legacy `background-image` attributes `a` (§17.3). +fn legacy_background_fill(a: &super::xml::Attrs) -> Option<(String, &'static str)> { + let href = get(a, "xlink:href").map(str::trim).filter(|h| !h.is_empty() && h.len() <= 1024)?; + let fill = match get(a, "style:repeat").map(str::trim) { + Some("no-repeat") => "center", + Some("stretch") => "frame", + _ => "tile", + }; + Some((href.trim_start_matches("./").to_string(), fill)) +} + /// A page stating nothing, `paper` (width, height) in size: no margins (§20.206–20.209 refer to /// XSL's margins, whose initial value is 0; whether it comes with the reference the standard /// doesn't say). @@ -1271,6 +1319,7 @@ fn unstated_page(paper: (f32, f32)) -> SectionProps { fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { let mut layouts: HashMap = HashMap::new(); + let mut fill_images: HashMap = HashMap::new(); let mut cur: Option = None; // Inside a layout's footer style (else its header style). let mut in_footer = false; @@ -1289,6 +1338,12 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { } } "linenumbering-configuration" if q.starts_with("text:") => lines = line_numbering(&a), + // Modern ODF 1.2/1.3 fill image definitions (§16.42 `draw:fill-image` in `office:styles`). + "fill-image" if q.starts_with("draw:") => { + if let (Some(name), Some(href)) = (get(&a, "draw:name"), get(&a, "xlink:href")) { + fill_images.insert(name.to_string(), href.trim_start_matches("./").to_string()); + } + } "page-layout" if q.starts_with("style:") => { cur = get(&a, "style:name").map(String::from); // A layout stating nothing is still one: the defaults' page. @@ -1300,16 +1355,14 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { } // A page background picture (§17.3, in `style:page-layout-properties`): §20.249 // `style:repeat` (repeat is the default) as WordCraft's tile, stretch, or centre. + // Preserved as a fallback when modern `draw:fill="bitmap"` is missing or non-image. "background-image" if q.starts_with("style:") => { - if let (Some(l), Some(href)) = - (cur.as_ref().and_then(|n| layouts.get_mut(n)), get(&a, "xlink:href").map(str::trim).filter(|h| !h.is_empty() && h.len() <= 1024)) - { - let fill = match get(&a, "style:repeat").map(str::trim) { - Some("no-repeat") => "center", - Some("stretch") => "frame", - _ => "tile", - }; - l.image = Some((href.trim_start_matches("./").to_string(), fill)); + if let Some(l) = cur.as_ref().and_then(|n| layouts.get_mut(n)) { + let leg = legacy_background_fill(&a); + if l.image.is_none() { + l.image = leg.clone(); + } + l.legacy_image = leg; } } // A band whose height isn't stated is LibreOffice's default, 0.5 cm (measured; see @@ -1327,6 +1380,10 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { } "page-layout-properties" => { if let Some(l) = cur.as_ref().and_then(|n| layouts.get_mut(n)) { + if let Some((img, name)) = page_layout_fill(&a, &fill_images) { + l.image = Some(img); + l.image_name = Some(name); + } l.attrs = a; } } @@ -1380,14 +1437,18 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { }); let mut pages = Pages { doc, next: nexts, ..Default::default() }; for (name, layout, header, footer) in masters { - let Some(Layout { attrs: a, columns: cols, column_specs, header: hb, footer: fb, image }) = layouts.get(&layout) else { continue }; + let Some(Layout { attrs: a, columns: cols, column_specs, header: hb, footer: fb, image, image_name, legacy_image }) = layouts.get(&layout) + else { + continue; + }; // What a layout leaves unsaid: the default paper, and no margins. let mut sec = unstated_page(paper); apply_layout(a, &mut sec); sec.line_numbers.clone_from(&lines); if pages.first.is_none() { pages.doc.page_color = get(a, "fo:background-color").and_then(model::parse_color); - pages.doc.page_image.clone_from(image); + pages.doc.page_image = image.as_ref().map(|(href, fill)| (href.clone(), *fill, image_name.clone())); + pages.doc.legacy_image.clone_from(legacy_image); } // ODF starts a header at the page margin and the text after the header's band; Word // measures the header's distance and the text's margin from the edge. How the band's diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index e9efebdec..da49b3054 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -307,7 +307,7 @@ fn with_as_read( /// graphic style (the `Graphics` and `Frame` styles drawings derive from) is the file's: its /// drawings written as read derive from it, and those written from the model derived from it /// when read (what WordCraft models of it is in theirs). -fn drawing_def(xml: &str) -> bool { +pub(super) fn drawing_def(xml: &str) -> bool { xml.split('>').next().unwrap_or("").starts_with(", } /// The package files the file's own definitions refer to, and those the markup written as read -/// links to (`used`), written as read with them (added to `files` and `manifest` where no file -/// `taken` has the path). A picture only an edited paragraph showed isn't written. +/// links to (`w.kept_files_used`, `w.kept_used`), written as read with them (added to `files` and +/// `manifest` where no file `taken` has the path). A picture only an edited paragraph showed isn't written. fn with_kept_files( + doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, - used: &std::collections::BTreeSet, + styles: &str, + w: &Writer, taken: &dyn Fn(&str) -> bool, files: &mut Vec<(String, std::sync::Arc>)>, manifest: &mut String, ) { let Some(k) = kept else { return }; - let mut wanted = used.clone(); - for d in k.defs.values() { + let mut wanted = w.kept_files_used.clone(); + let pages_kept = k.pages_as_read(doc); + let styles_kept = k.styles_as_read(doc); + for (key, d) in &k.defs { + if !pages_kept && (key.starts_with("sauto:") || key.starts_with("master:")) { + continue; + } + if key.starts_with("common:") { + // The file's definition is written back whole (`styles_as_read`, non-`draw:` + // definitions win), or this one is restored for markup naming it. WordCraft's own + // definition takes a drawing definition's place: its href is no longer used. + let written = if styles_kept { + !(super::kept::drawing_def(d) && super::kept::defined(styles, d)) + } else { + key.strip_prefix("common:").is_some_and(|n| w.kept_used.1.contains_key(n)) && !super::kept::defined(styles, d) + }; + if !written { + continue; + } + } super::kept::hrefs(d, &mut wanted); } // A file linked, or one in a folder linked (an object's). @@ -1234,7 +1254,7 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { w.objects.iter().map(|(d, _, _)| d).chain(w.object_dirs.iter().map(|(d, _)| d)).map(|d| format!("{}/", d.trim_end_matches('/'))).collect(); let taken = |p: &str| w.pictures.iter().any(|(n, _, _)| n == p) || dirs.iter().any(|d| p.starts_with(d.as_str())); let mut kept_files: Vec<_> = kept_files.into_iter().filter(|(p, _)| !taken(p)).collect(); - with_kept_files(kept, &w.kept_files_used, &taken, &mut kept_files, &mut manifest); + with_kept_files(doc, kept, &styles, &w, &taken, &mut kept_files, &mut manifest); for (path, mime) in &kept_entries { if (path.ends_with('/') && kept_files.iter().any(|(p, _)| p.starts_with(path.as_str()))) || kept_files.iter().any(|(p, _)| p == path) { manifest.push_str(&format!("\n", x(path), x(mime))); @@ -1384,43 +1404,121 @@ fn variables(doc: &Document) -> std::collections::BTreeSet { out } +/// A `draw:fill-image` definition's name and picture path, when `xml` starts with one. +fn fill_image_of(xml: &str) -> Option<(String, String)> { + let tag = xml.split('>').next()?; + if !tag.trim_start_matches('<').starts_with("draw:fill-image") { + return None; + } + let name = super::kept::raw_attr(tag, "draw:name").map(super::kept::attr_text)?; + let href = super::kept::raw_attr(tag, "xlink:href").map(super::kept::attr_text)?; + Some((name.into_owned(), href.into_owned())) +} + +/// `name` as a `draw:name` (§16.42) may read: an NCName — letters, digits, `-`, `_` and `.`, not +/// starting with `-`, `.` or a digit. Characters outside those are turned into `_`. +fn fill_image_name(name: &str) -> String { + let mut out = String::with_capacity(name.len().min(255)); + for c in name.chars().take(255) { + let ok = c.is_alphanumeric() || c == '-' || c == '_' || c == '.'; + let start_ok = c.is_alphabetic() || c == '_'; + if out.is_empty() { + out.push(if start_ok { c } else { '_' }); + } else { + out.push(if ok { c } else { '_' }); + } + } + if out.is_empty() { "PageBackground".to_string() } else { out } +} + /// `styles` with the page background picture (Design › Page Color › Fill Effects › Picture) in -/// each page layout (§17.3 `style:background-image`, first in `style:page-layout-properties`), -/// the picture written into the package by `w`: tiled, stretched, or centred at its own size -/// (§20.249 `style:repeat`). -fn page_background(doc: &Document, w: &mut Writer, styles: String) -> String { +/// each page layout (§17.3 `style:background-image`, first in `style:page-layout-properties`, and +/// modern ODF 1.2/1.3 §16.42 `draw:fill="bitmap"` with `draw:fill-image`), the picture written +/// into the package by `w`: tiled, stretched, or centred at its own size (§20.249 `style:repeat`). +fn page_background(doc: &Document, w: &mut Writer, mut styles: String) -> String { let Some(pic) = doc.settings.page_picture.as_ref() else { return styles }; let Some(data) = doc.media.get(&pic.media) else { return styles }; let Some(ext) = model::sniff_image(data) else { return styles }; - let name = format!("Pictures/page-background.{ext}"); - if !w.pictures.iter().any(|(n, _, _)| *n == name) { - w.pictures.push((name.clone(), data.clone(), model::mime_of(ext).to_string())); + let kept = doc.kept.of("odt"); + // A kept package file holding these bytes is this picture already: its path is reused, so + // saving what was opened doesn't add a copy on every save. + let same_kept = |path: &str| kept.is_some_and(|k| k.files.get(path).is_some_and(|b| b.as_slice() == data.as_slice())); + let mut name = format!("Pictures/page-background.{ext}"); + let mut pic_n = 1; + while (w.reserved.contains(&name) && !same_kept(&name)) || w.pictures.iter().any(|(n, d, _)| n == &name && d.as_slice() != data.as_slice()) { + name = format!("Pictures/page-background-{pic_n}.{ext}"); + pic_n += 1; } let repeat = match pic.fill_type.to_ascii_lowercase().as_str() { "tile" => "repeat", "center" => "no-repeat", _ => "stretch", }; - let el = format!( + // The fill-image definitions already written, by name, once: renaming looks each up rather + // than scanning every definition for it (a hostile file names thousands alike). + let mut fill_images: std::collections::HashMap = std::collections::HashMap::new(); + for d in w.kept_defs.values() { + if let Some((n, h)) = fill_image_of(d) { + fill_images.insert(n, h); + } + } + for (i, _) in styles.match_indices("", x(&fill_name), x(&name)); + if !super::kept::defined(&styles, &fill_image_def) { + styles = styles.replacen("", &format!("{fill_image_def}"), 1); + } + let bg_el = format!( "", x(&name) ); + let fill_attrs = format!(" draw:fill=\"bitmap\" draw:fill-image-name=\"{}\" style:repeat=\"{repeat}\"", x(&fill_name)); + // After each layout's properties' opening tag. - let mut out = String::with_capacity(styles.len() + el.len() * 4); + let mut out = String::with_capacity(styles.len() + bg_el.len() * 4); let mut rest = styles.as_str(); while let Some(at) = rest.find("')).map(|e| at + e) else { break }; let self_closing = rest.get(end.saturating_sub(1)..end) == Some("/"); if self_closing { - out.push_str(rest.get(..end.saturating_sub(1)).unwrap_or_default()); + let before_slash = end.saturating_sub(1); + out.push_str(rest.get(..tag_start).unwrap_or_default()); + out.push_str(&fill_attrs); + out.push_str(rest.get(tag_start..before_slash).unwrap_or_default()); out.push('>'); - out.push_str(&el); + out.push_str(&bg_el); out.push_str(""); } else { - out.push_str(rest.get(..=end).unwrap_or_default()); - out.push_str(&el); + out.push_str(rest.get(..tag_start).unwrap_or_default()); + out.push_str(&fill_attrs); + out.push_str(rest.get(tag_start..=end).unwrap_or_default()); + out.push_str(&bg_el); } - rest = rest.get(end + 1..).unwrap_or_default(); + rest = rest.get(end.saturating_add(1)..).unwrap_or_default(); } out.push_str(rest); out diff --git a/crates/odf/src/text/tests_more/page_setup.rs b/crates/odf/src/text/tests_more/page_setup.rs index af687bd45..79b74f248 100644 --- a/crates/odf/src/text/tests_more/page_setup.rs +++ b/crates/odf/src/text/tests_more/page_setup.rs @@ -233,3 +233,662 @@ fn a_page_borders_padding_keeps_the_text_where_it_was() { } assert_eq!(s.page_borders.and_then(|b| b.left).map(|b| (b.width, b.space)), Some((3.0, 24.0))); } + +/// An ODT document with a page background and an active header containing a logo +/// preserves the page background (both modern draw:fill and legacy fallback) and the header logo (#5803). +#[test] +fn background_plus_small_header_logo_keeps_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let logo_png = { + let img = image::RgbImage::from_pixel(4, 4, image::Rgb([30, 200, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: "PageBackground".into() }); + let logo_media = d.add_media(logo_png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("Company {}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: logo_media, + w: 50.0, + h: 20.0, + alt: "Logo".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![ + craft_wordmodel::para::Run { len: 8, props: Default::default() }, + craft_wordmodel::para::Run { len: craft_wordmodel::para::OBJ.len_utf8(), props: Default::default() }, + ]; + d.parts.insert( + 1, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + d.last_section.headers.default = Some(1); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + // Verify both draw:fill="bitmap" and style:background-image are emitted consistently + assert!(s.contains("draw:fill=\"bitmap\""), "page layout must declare draw:fill=\"bitmap\": {s}"); + assert!(s.contains("style:background-image"), "legacy background-image fallback must be present: {s}"); + assert!(s.contains(""# + ); + let content = format!( + r#"Cell test"# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/cell-bg.png", &png)]); + let d = import(&pkg).unwrap(); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "cell style background-image must survive on kept path: {s}"); + assert!(s.contains("Pictures/cell-bg.png"), "cell background picture path must survive: {s}"); +} + +/// An ODT document with a text-only header retains its legacy page background image +/// and writes the image into the package archive. +#[test] +fn text_header_keeps_page_background_picture() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = "Header text".into(); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 1, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + d.last_section.headers.default = Some(1); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "page background must be written when header has no picture: {s}"); + assert!(s.contains("Pictures/page-background.png")); +} + +/// Every picture written into the ODT zip archive must be referenced by styles.xml or content.xml (#5803). +#[test] +fn no_unreferenced_images_left_in_package() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let ns = crate::text::tests::NS_T; + let nsd = r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:xlink="http://www.w3.org/1999/xlink""#; + // An imported ODT with modern draw:fill="bitmap" and draw:fill-image + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/original.png", &png)]); + let mut d = import(&pkg).unwrap(); + + // Now insert a header picture into the document, changing page setup + let header_media = d.add_media(png.clone(), "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 50.0, + alt: "Header logo".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 1, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + d.last_section.headers.default = Some(1); + + let saved = export(&d).unwrap(); + let styles_xml = crate::text::tests::entry(&saved, "styles.xml"); + let content_xml = crate::text::tests::entry(&saved, "content.xml"); + + // Verify modern draw:fill bitmap and legacy style:background-image resolve to the same image target + let fill_name = + styles_xml.split("draw:fill-image-name=\"").nth(1).and_then(|s| s.split('"').next()).expect("styles.xml must contain draw:fill-image-name"); + let draw_fill_pattern = format!(" = (0..archive.len()).map(|i| archive.by_index(i).unwrap().name().unwrap().to_string()).collect(); + + let pic_files: Vec<&String> = file_names.iter().filter(|n| n.starts_with("Pictures/")).collect(); + assert!(!pic_files.is_empty(), "package should contain picture files"); + + for pic in pic_files { + let is_referenced = styles_xml.contains(pic.as_str()) || content_xml.contains(pic.as_str()); + assert!(is_referenced, "package image {pic} must be referenced in styles.xml or content.xml: styles={styles_xml}"); + } +} + +/// An inactive header (e.g. `first` when `title_page` is false, or `even` when `even_odd_headers` +/// is false) containing an image does NOT suppress the page background picture (#5803). +#[test] +fn inactive_header_picture_does_not_suppress_page_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + + let header_media = d.add_media(png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 100.0, + alt: "Inactive header picture".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 100, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + + // Point headers.first to the header with picture, but title_page is FALSE. + d.last_section.headers.first = Some(100); + d.last_section.title_page = false; + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "background-image must be preserved when header picture is in an inactive header: {s}"); + assert!(s.contains("Pictures/page-background.png")); +} + +/// A noninitial continuous section header containing a picture does NOT produce a master page +/// and does not suppress the page background (#5803). +#[test] +fn continuous_section_header_picture_does_not_suppress_page_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + + // Body with a first section ending paragraph + let mut p1 = craft_wordmodel::Paragraph::new(); + p1.text = "First paragraph in section 1".into(); + p1.runs = vec![craft_wordmodel::para::Run { len: p1.text.len(), props: Default::default() }]; + p1.section = Some(Box::new(craft_wordmodel::SectionProps::default())); + d.body.push(craft_wordmodel::para_block(p1)); + + // Second section (last_section) is continuous + let header_media = d.add_media(png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 100.0, + alt: "Continuous section header picture".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 200, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + + d.last_section.start = craft_wordmodel::section::SectionStart::Continuous; + d.last_section.headers.default = Some(200); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!( + s.contains("style:background-image"), + "page background must not be suppressed by continuous section header that emits no master page: {s}" + ); + assert!(s.contains("Pictures/page-background.png")); +} + +/// A non-continuous `last_section` without any body blocks following the section break +/// does not produce an exported page and does not suppress the page background (#5803). +#[test] +fn trailing_empty_last_section_header_picture_does_not_suppress_page_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + + // Body with a single paragraph ending section 1 (nothing follows it) + let mut p1 = craft_wordmodel::Paragraph::new(); + p1.text = "Sole paragraph ending section 1".into(); + p1.runs = vec![craft_wordmodel::para::Run { len: p1.text.len(), props: Default::default() }]; + p1.section = Some(Box::new(craft_wordmodel::SectionProps::default())); + d.body.push(craft_wordmodel::para_block(p1)); + + // last_section is NextPage and has a header with a picture, but has no blocks following + let header_media = d.add_media(png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 100.0, + alt: "Unused trailing section header picture".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 300, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + + d.last_section.start = craft_wordmodel::section::SectionStart::NextPage; + d.last_section.headers.default = Some(300); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "page background must not be suppressed by an unexported trailing last_section header: {s}"); + assert!(s.contains("Pictures/page-background.png")); +} + +/// When a page background picture is replaced with a new image while retaining an existing +/// fill-image name that belongs to a graphic style, export allocates a distinct fill name, +/// references it in page layouts, and preserves the retained definition and image (#5803). +#[test] +fn replaced_page_picture_allocates_distinct_fill_name_and_keeps_retained_def() { + let orig_png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([100, 200, 100])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let new_png = { + let img = image::RgbImage::from_pixel(4, 8, image::Rgb([200, 100, 200])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let ns = crate::text::tests::NS_T; + let nsd = "xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\""; + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text"# + ); + let pkg = + crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/original.png", &orig_png)]); + let mut d = import(&pkg).unwrap(); + let new_media = d.add_media(new_png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: new_media, fill_type: "stretch".into(), title: "SharedBg".into() }); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains(r#" Vec { + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut out: Vec = + (0..archive.len()).map(|i| archive.by_index(i).unwrap().name().unwrap().to_string()).filter(|n| n.starts_with("Pictures/")).collect(); + out.sort(); + out +} + +/// Saving a page background picture and opening it again keeps one picture and one fill-image +/// definition: the kept file is reused while its bytes are the document's, not renamed (#5856). +#[test] +fn page_background_round_trips_do_not_grow_the_package() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: "frame".into(), title: "PageBackground".into() }); + let mut current = d; + for generation in 1..=4 { + let saved = export(¤t).unwrap(); + let styles = crate::text::tests::entry(&saved, "styles.xml"); + assert_eq!(styles.matches(""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/original.png", &png)]); + let d = import(&pkg).unwrap(); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert_eq!(s.matches(""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/para.png", &png)]); + let d = import(&pkg).unwrap(); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("Pictures/para.png"), "the style's background reference must stay: {s}"); + assert_eq!(picture_paths(&saved), ["Pictures/para.png"], "the referenced picture must be written"); +} + +/// A DOCX texture name (`o:title`, "Blue tissue paper") is not an XML NCName: the fill image it +/// names is written with one (#5856). +#[test] +fn a_texture_name_is_written_as_an_ncname() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: "frame".into(), title: "Blue tissue paper".into() }); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains(r#""#)); + } + let styles = format!( + r#"{defs}"# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[ + ("content.xml", content.as_bytes()), + ("styles.xml", styles.as_bytes()), + ("Pictures/bg.png", &bg), + ("Pictures/other.png", &other), + ]); + let mut d = import(&pkg).unwrap(); + // The user replaces the picture: its fill-image name now meets every kept name. + let media = d.add_media(replacement, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: "stretch".into(), title: "X".into() }); + let start = std::time::Instant::now(); + let saved = export(&d).unwrap(); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "export took {:?}", start.elapsed()); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains(r#"` if present and valid (#1784). +#[test] +fn legacy_background_fallback_when_modern_bitmap_missing() { + let legacy_png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([10, 150, 20])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let ns = crate::text::tests::NS_T; + let nsd = r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:xlink="http://www.w3.org/1999/xlink""#; + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = + crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/legacy.png", &legacy_png)]); + let d = import(&pkg).unwrap(); + let pic = d.settings.page_picture.as_ref().expect("legacy fallback background picture must be imported"); + assert_eq!(d.media.get(&pic.media).map(|b| b.as_slice()), Some(legacy_png.as_slice())); + assert_eq!(pic.fill_type, "frame"); +} + +/// When modern `draw:fill="bitmap"` references a file with non-image bytes, +/// import falls back to legacy `` if present and valid (#1784). +#[test] +fn legacy_background_fallback_when_modern_bitmap_non_image() { + let legacy_png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([10, 150, 20])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let corrupt_data = b"This is plain text and definitely not a valid image format."; + let ns = crate::text::tests::NS_T; + let nsd = r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:xlink="http://www.w3.org/1999/xlink""#; + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[ + ("content.xml", content.as_bytes()), + ("styles.xml", styles.as_bytes()), + ("Pictures/corrupt.bin", corrupt_data), + ("Pictures/legacy.png", &legacy_png), + ]); + let d = import(&pkg).unwrap(); + let pic = d.settings.page_picture.as_ref().expect("legacy fallback background picture must be imported when modern is non-image"); + assert_eq!(d.media.get(&pic.media).map(|b| b.as_slice()), Some(legacy_png.as_slice())); + assert_eq!(pic.fill_type, "frame"); +} diff --git a/crates/pkcs7/src/cms.rs b/crates/pkcs7/src/cms.rs index 083aa4302..2bccf5099 100644 --- a/crates/pkcs7/src/cms.rs +++ b/crates/pkcs7/src/cms.rs @@ -449,25 +449,55 @@ struct SignedDataInput<'a> { content_digest: &'a [u8], } -fn build(input: SignedDataInput<'_>) -> Result, Error> { - let SignedDataInput { key, cert, chain, alg, content_type, content, content_digest } = input; - let cert_hash = DigestAlg::Sha256.digest(&[&cert.raw]); - let general_names = der::seq(&[&der::explicit(4, &cert.issuer.raw)]); +/// Public certificate material used by the CMS writer. `serial` is the original INTEGER +/// contents, including its sign padding; `issuer_der` and `der` are complete DER encodings. +/// Callers obtain these fields from an already parsed certificate. No private key is held. +#[derive(Clone, Copy, Debug)] +pub struct SigningCertificate<'a> { + pub der: &'a [u8], + pub issuer_der: &'a [u8], + pub serial: &'a [u8], +} + +/// Inputs for a CAdES SignedData envelope. The caller computes `content_digest` using `alg`. +/// `content` is absent for detached signatures, or the bytes to encapsulate for a token. +/// Certificate-chain entries are complete DER certificates; the signer is deduplicated. +#[derive(Clone, Copy, Debug)] +pub struct SigningInput<'a> { + pub cert: SigningCertificate<'a>, + pub chain: &'a [&'a [u8]], + pub alg: DigestAlg, + pub content_type: &'a str, + pub content: Option<&'a [u8]>, + pub content_digest: &'a [u8], + /// Complete DER AlgorithmIdentifier matching the callback's signing operation. + pub signature_algorithm: &'a [u8], +} + +/// Build the same signed attributes and envelope as [`sign_detached`] / [`sign_encapsulated`], +/// signing through a caller-owned key provider. The callback receives the exact DER SET +/// of signed attributes once (not its digest). It must sign those bytes using `alg` and the +/// supplied signature AlgorithmIdentifier. Its error is returned unchanged, without retry. +/// This lets apps retain platform/keychain/token signing without exporting a private key. +pub fn sign_with(input: SigningInput<'_>, sign: impl FnOnce(&[u8]) -> Result, E>) -> Result, E> { + let SigningInput { cert, chain, alg, content_type, content, content_digest, signature_algorithm } = input; + let cert_hash = DigestAlg::Sha256.digest(&[cert.der]); + let general_names = der::seq(&[&der::explicit(4, cert.issuer_der)]); // The serial as the certificate has it: `cert.serial` is the INTEGER's own bytes, so one with // its high bit set gets no leading zero here. - let serial = der::tlv(tag::INTEGER, if cert.serial.is_empty() { &[0] } else { &cert.serial }); + let serial = der::tlv(tag::INTEGER, if cert.serial.is_empty() { &[0] } else { cert.serial }); let ess = der::seq(&[&der::seq(&[&der::seq(&[&der::octets(&cert_hash), &der::seq(&[&general_names, &serial])])])]); let attrs = [attribute(CONTENT_TYPE, &der::oid(content_type)), attribute(MESSAGE_DIGEST, &der::octets(content_digest)), attribute(SIGNING_CERT_V2, &ess)]; let refs: Vec<&[u8]> = attrs.iter().map(Vec::as_slice).collect(); let set = der::set_of(&refs); - let signature = key.sign(alg, &set)?; + let signature = sign(&set)?; let mut signed_attrs = set.clone(); signed_attrs[0] = tag::ctx(0); - let sid = der::seq(&[&cert.issuer.raw, &serial]); - let signer = der::seq(&[&der::int(1), &sid, &alg.algorithm(), &signed_attrs, &key.signature_algorithm(alg), &der::octets(&signature)]); - let mut certs: Vec<&[u8]> = vec![&cert.raw]; - certs.extend(chain.iter().filter(|c| c.raw != cert.raw).map(|c| c.raw.as_slice())); + let sid = der::seq(&[cert.issuer_der, &serial]); + let signer = der::seq(&[&der::int(1), &sid, &alg.algorithm(), &signed_attrs, signature_algorithm, &der::octets(&signature)]); + let mut certs: Vec<&[u8]> = vec![cert.der]; + certs.extend(chain.iter().copied().filter(|c| *c != cert.der)); let encap = match content { Some(c) => der::seq(&[&der::oid(content_type), &der::explicit(0, &der::octets(c))]), None => der::seq(&[&der::oid(content_type)]), @@ -477,10 +507,76 @@ fn build(input: SignedDataInput<'_>) -> Result, Error> { Ok(der::seq(&[&der::oid(SIGNED_DATA), &der::explicit(0, &signed_data)])) } +fn build(input: SignedDataInput<'_>) -> Result, Error> { + let SignedDataInput { key, cert, chain, alg, content_type, content, content_digest } = input; + let chain: Vec<&[u8]> = chain.iter().map(|c| c.raw.as_slice()).collect(); + sign_with( + SigningInput { + cert: SigningCertificate { der: &cert.raw, issuer_der: &cert.issuer.raw, serial: &cert.serial }, + chain: &chain, + alg, + content_type, + content, + content_digest, + signature_algorithm: &key.signature_algorithm(alg), + }, + |attrs| key.sign(alg, attrs), + ) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn callback_signer_matches_builtin_and_returns_provider_error_once() -> Result<(), Box> { + use crate::x509::Name; + let key = PrivateKey::generate_p256()?; + let name = Name::build("Callback signer", "", "", "", ""); + let from = Time { year: 2026, month: 1, day: 1, hour: 0, minute: 0, second: 0 }; + let cert = Certificate::self_signed(&name, &key, from, 1, &[1])?; + let alg = DigestAlg::Sha256; + let bytes = b"content"; + let digest = alg.digest(&[bytes]); + let algorithm = key.signature_algorithm(alg); + let chain = [cert.raw.as_slice()]; + for content in [None, Some(bytes.as_slice())] { + let input = SigningInput { + cert: SigningCertificate { der: &cert.raw, issuer_der: &cert.issuer.raw, serial: &cert.serial }, + chain: &chain, + alg, + content_type: DATA, + content, + content_digest: &digest, + signature_algorithm: &algorithm, + }; + let mut calls = 0; + let via_callback = sign_with(input, |attrs| { + calls += 1; + assert_eq!(Tlv::parse_all(attrs)?.tag, tag::SET); + key.sign(alg, attrs) + })?; + assert_eq!(calls, 1); + let builtin = match content { + Some(c) => sign_encapsulated(&key, &cert, std::slice::from_ref(&cert), alg, DATA, c)?, + None => sign_detached(&key, &cert, std::slice::from_ref(&cert), alg, &digest)?, + }; + assert_eq!(via_callback, builtin); + let parsed = SignedData::parse(&via_callback)?; + assert_eq!(parsed.certificates.len(), 1); + assert!(parsed.verify_signature(&cert, &digest)?); + assert_eq!(parsed.content.as_deref(), content); + let mut calls = 0; + let failed = sign_with(input, |_| { + calls += 1; + Err(42u32) + }); + assert_eq!(failed, Err(42)); + assert_eq!(calls, 1); + } + Ok(()) + } + #[test] fn strip_removes_multiple_leading_zero_bytes() { assert_eq!(strip(&[0, 0, 0, 0x42]), &[0x42]);