From 380a2f79f6a195c090a5372e819cbcda2b703c09 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 23:40:51 -0500 Subject: [PATCH] craft-sbs: share SBS package/schema read/write, sniffing, URI resolution, and embedded codec (#2496) * sbs: add craft-sbs crate for SBS package/schema read/write * craft-sbs: fix roxmltree 0.21 ParsingOptions and test imports --- Cargo.lock | 12 +++ Cargo.toml | 1 + crates/sbs/Cargo.toml | 19 ++++ crates/sbs/src/embedded.rs | 114 ++++++++++++++++++++++ crates/sbs/src/lib.rs | 193 +++++++++++++++++++++++++++++++++++++ crates/sbs/src/uri.rs | 60 ++++++++++++ crates/sbs/src/value.rs | 69 +++++++++++++ crates/sbs/src/xml.rs | 80 +++++++++++++++ 8 files changed, 548 insertions(+) create mode 100644 crates/sbs/Cargo.toml create mode 100644 crates/sbs/src/embedded.rs create mode 100644 crates/sbs/src/lib.rs create mode 100644 crates/sbs/src/uri.rs create mode 100644 crates/sbs/src/value.rs create mode 100644 crates/sbs/src/xml.rs diff --git a/Cargo.lock b/Cargo.lock index 3c7c6a1e9..715ce97d3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3164,6 +3164,18 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-sbs" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "craft-mime", + "craft-xml", + "flate2", + "roxmltree 0.21.2", + "thiserror 2.0.21", +] + [[package]] name = "craft-score" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 7ef038f99..328724f73 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,6 +83,7 @@ craft-doc-binary = { path = "crates/doc-binary" } craft-docx = { path = "crates/docx" } craft-document-bundle = { path = "crates/document-bundle" } craft-mcmat = { path = "crates/mcmat" } +craft-sbs = { path = "crates/sbs" } craft-deckcraft-format = { path = "crates/deckcraft-format" } craft-designcraft-format = { path = "crates/designcraft-format" } craft-dxf = { path = "crates/dxf" } diff --git a/crates/sbs/Cargo.toml b/crates/sbs/Cargo.toml new file mode 100644 index 000000000..5b989836f --- /dev/null +++ b/crates/sbs/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-sbs" +description = "Bounded SBS package/schema XML parsing, sniffing, embedded resource codecs, and envelope writing" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +base64 = "0.23" +craft-mime = { workspace = true } +craft-xml = { workspace = true } +flate2 = { version = "1", default-features = false, features = ["rust_backend"] } +roxmltree = "0.21" +thiserror = { workspace = true } diff --git a/crates/sbs/src/embedded.rs b/crates/sbs/src/embedded.rs new file mode 100644 index 000000000..e12d56c32 --- /dev/null +++ b/crates/sbs/src/embedded.rs @@ -0,0 +1,114 @@ +//! Embedded binary resource codec (4-byte big-endian length + zlib + standard Base64). + +use crate::MAX_RESOURCE_BYTES; +use base64::Engine as _; +use std::{ + cell::Cell, + io::{self, Read, Write}, +}; + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum EmbeddedError { + #[error("{0}")] + Damaged(String), + #[error("embedded resource exceeds the remaining material resource budget")] + Budget, + #[error("embedded resource exceeds the material inflation work budget")] + WorkBudget, +} + +impl From for EmbeddedError { + fn from(message: String) -> Self { + Self::Damaged(message) + } +} + +impl From<&str> for EmbeddedError { + fn from(message: &str) -> Self { + Self::Damaged(message.into()) + } +} + +fn base64_engine() -> base64::engine::GeneralPurpose { + base64::engine::general_purpose::STANDARD +} + +pub fn decode(strdata: &str) -> Result, String> { + decode_bounded(strdata, MAX_RESOURCE_BYTES, MAX_RESOURCE_BYTES, &Cell::new(MAX_RESOURCE_BYTES + 1)).map_err(|error| error.to_string()) +} + +pub fn decode_bounded(strdata: &str, max_bytes: u64, remaining_bytes: u64, inflation_work: &Cell) -> Result, EmbeddedError> { + let work_before = inflation_work.get(); + if work_before == 0 { + return Err(EmbeddedError::WorkBudget); + } + + let raw = match strdata.split_once(char::is_whitespace) { + Some((prefix, rest)) => base64_engine().decode(std::iter::once(prefix).chain(rest.split_whitespace()).collect::()), + None => base64_engine().decode(strdata), + } + .map_err(|error| format!("bad base64: {error}"))?; + let (length, compressed) = raw.split_at_checked(4).ok_or("too short")?; + let declared_bytes = u64::from(u32::from_be_bytes([length[0], length[1], length[2], length[3]])); + if declared_bytes > max_bytes { + return Err("embedded resource exceeds the 256 MiB limit".into()); + } + + // Read one probe byte beyond the tighter bound to detect overruns + let probe_limit = declared_bytes.min(remaining_bytes) + 1; + let mut decoder = flate2::read::ZlibDecoder::new(compressed); + let mut limited = decoder.by_ref().take(probe_limit.min(work_before)); + let mut output = Vec::new(); + let result = if declared_bytes > remaining_bytes || declared_bytes >= work_before { + // Discard probe output that cannot become a retained asset + io::copy(&mut limited, &mut io::sink()) + } else { + limited.read_to_end(&mut output).map(|bytes| bytes as u64) + }; + + // Charge every emitted byte, including output produced before a checksum error + inflation_work.set(work_before.saturating_sub(decoder.total_out())); + let actual_bytes = result.map_err(|error| format!("bad compressed data: {error}"))?; + if actual_bytes > declared_bytes { + return Err(format!("{actual_bytes} bytes where {declared_bytes} were declared").into()); + } + + if work_before < probe_limit && actual_bytes == work_before { + return Err(EmbeddedError::WorkBudget); + } + + if actual_bytes > remaining_bytes { + return Err(EmbeddedError::Budget); + } + + if actual_bytes != declared_bytes { + return Err(format!("{actual_bytes} bytes where {declared_bytes} were declared").into()); + } + + output.shrink_to_fit(); + Ok(output) +} + +pub fn encode(bytes: &[u8]) -> Result { + let length = u32::try_from(bytes.len()).map_err(|_| String::from("resource too large"))?; + let mut encoder = flate2::write::ZlibEncoder::new(length.to_be_bytes().to_vec(), flate2::Compression::default()); + encoder.write_all(bytes).map_err(|e| e.to_string())?; + let raw = encoder.finish().map_err(|e| e.to_string())?; + + Ok(craft_mime::transfer::base64(&raw)) +} + +#[cfg(test)] +mod tests { + use super::{EmbeddedError, MAX_RESOURCE_BYTES, decode, decode_bounded, encode}; + use std::cell::Cell; + + #[test] + fn roundtrips_and_enforces_budgets() { + let encoded = encode(b"four").expect("encode"); + assert_eq!(decode(&encoded).expect("decode"), b"four"); + assert_eq!(decode_bounded(&encoded, MAX_RESOURCE_BYTES, 3, &Cell::new(16)), Err(EmbeddedError::Budget)); + assert_eq!(decode_bounded(&encoded, MAX_RESOURCE_BYTES, 4, &Cell::new(16)), Ok(b"four".to_vec())); + assert_eq!(decode_bounded(&encoded, MAX_RESOURCE_BYTES, 4, &Cell::new(0)), Err(EmbeddedError::WorkBudget)); + } +} diff --git a/crates/sbs/src/lib.rs b/crates/sbs/src/lib.rs new file mode 100644 index 000000000..9662603f9 --- /dev/null +++ b/crates/sbs/src/lib.rs @@ -0,0 +1,193 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Bounded SBS package/schema XML parsing, sniffing, embedded resource codecs, and envelope writing. +//! +//! Applications interpret material graph semantics locally on top of the parsed XML tree. + +pub mod embedded; +pub mod uri; +pub mod value; +pub mod xml; + +use std::fmt::Write as _; + +pub const SBS_EXT: &str = "sbs"; +pub const MAX_SBS_BYTES: u64 = 256 << 20; +pub const MAX_XML_NODES: u32 = 8_000_000; +pub const MAX_RESOURCE_BYTES: u64 = 256 << 20; +pub const SNIFF_BYTES: usize = 4096; +pub const SELF_DEPENDENCY: &str = "?himself"; +pub const FIRST_UID: u64 = 1_000_000_000; + +/// Why an SBS package XML document could not be parsed. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Error { + #[error("the SBS file is {actual} bytes, over the {limit} byte limit")] + TooLarge { actual: u64, limit: u64 }, + #[error("the SBS file is not UTF-8 text: {0}")] + InvalidUtf8(#[from] std::str::Utf8Error), + #[error("the SBS file is not valid XML: {0}")] + InvalidXml(#[from] roxmltree::Error), + #[error("not an SBS package (the root element is not )")] + NotPackage, +} + +/// Sniff whether `bytes` begins with an SBS `` XML document. +pub fn is_sbs(bytes: &[u8]) -> bool { + let head = String::from_utf8_lossy(&bytes[..bytes.len().min(SNIFF_BYTES)]); + let mut rest = head.trim_start_matches('\u{feff}'); + + // Skip the XML declaration and comments before the root element + loop { + rest = rest.trim_start(); + let (skip_open, skip_close) = if rest.starts_with("") + } else if rest.starts_with("") + } else { + break; + }; + + match rest[skip_open.len()..].find(skip_close) { + Some(end) => rest = &rest[skip_open.len() + end + skip_close.len()..], + None => return false, + } + } + + rest.strip_prefix("' || c == '/' || c.is_whitespace())) +} + +/// A validated SBS XML `` document. +pub struct PackageDocument<'input> { + document: roxmltree::Document<'input>, +} + +impl<'input> PackageDocument<'input> { + /// Parse borrowed input with the default byte, XML-node, and DTD limits. + pub fn parse(bytes: &'input [u8]) -> Result { + Self::parse_with_limits(bytes, MAX_SBS_BYTES, MAX_XML_NODES) + } + + /// Parse borrowed input with explicit byte and XML-node limits. + pub fn parse_with_limits(bytes: &'input [u8], max_bytes: u64, max_xml_nodes: u32) -> Result { + let actual = bytes.len() as u64; + if actual > max_bytes { + return Err(Error::TooLarge { actual, limit: max_bytes }); + } + + let text = std::str::from_utf8(bytes)?; + let text = text.trim_start_matches('\u{feff}'); + let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: max_xml_nodes, ..roxmltree::ParsingOptions::default() }; + let document = roxmltree::Document::parse_with_options(text, options)?; + + if document.root_element().tag_name().name() != "package" { + return Err(Error::NotPackage); + } + + Ok(Self { document }) + } + + pub fn document(&self) -> &roxmltree::Document<'input> { + &self.document + } + + pub fn root(&self) -> roxmltree::Node<'_, 'input> { + self.document.root_element() + } + + pub fn text(&self) -> &'input str { + self.document.input_text() + } + + pub fn identifier(&self) -> Option<&str> { + xml::child_value(self.root(), "identifier") + } + + pub fn format_version(&self) -> Option<&str> { + xml::child_value(self.root(), "formatVersion") + } + + pub fn content(&self) -> Option> { + xml::child_element(self.root(), "content") + } + + /// Resolve the display package name from `` or `fallback_name`. + pub fn package_name(&self, fallback_name: &str) -> String { + let file_stem = fallback_name.rsplit(['/', '\\']).next().unwrap_or(fallback_name); + let file_stem = file_stem.rsplit_once('.').map_or(file_stem, |(stem, _)| stem).trim(); + match self.identifier().map(str::trim) { + Some(id) if !id.is_empty() && id != "Unsaved Package" => id.to_string(), + _ if !file_stem.is_empty() => file_stem.to_string(), + _ => "Untitled package".to_string(), + } + } + + /// Iterate `(uid, filename)` pairs from ``. + pub fn dependencies(&self) -> impl Iterator { + xml::child_element(self.root(), "dependencies") + .into_iter() + .flat_map(|d| xml::children_named(d, "dependency")) + .filter_map(|dep| Some((xml::child_value(dep, "uid")?, xml::child_value(dep, "filename")?))) + } +} + +/// Write an SBS `` XML envelope around serialized `...` XML. +pub fn write_package<'a>( + identifier: &str, + format_version: &str, + updater_version: &str, + dependencies: impl IntoIterator, + content_xml: &str, +) -> Vec { + let mut out = String::with_capacity(content_xml.len() + 4096); + let _ = write!( + out, + "", + xml::xml_escape(identifier), + xml::xml_escape(format_version), + xml::xml_escape(updater_version), + ); + for (file, uid) in dependencies { + let _ = write!( + out, + "", + xml::xml_escape(file), + ); + } + out.push_str(""); + out.push_str(content_xml); + out.push_str("\n"); + out.into_bytes() +} + +#[cfg(test)] +mod tests { + use super::{Error, FIRST_UID, PackageDocument, SELF_DEPENDENCY, is_sbs, write_package}; + + #[test] + fn sniffs_sbs_with_bom_declaration_and_comments() { + assert!(is_sbs(b"\xef\xbb\xbf")); + assert!(is_sbs(b"")); + assert!(!is_sbs(b"")); + assert!(!is_sbs(b"")); + assert!(!is_sbs(b"