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
This commit is contained in:
Dylan M. Taylor
2026-11-19 23:40:51 -05:00
committed by GitHub
parent a7c6c9d61c
commit 380a2f79f6
8 changed files with 548 additions and 0 deletions
Generated
+12
View File
@@ -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"
+1
View File
@@ -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" }
+19
View File
@@ -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 }
+114
View File
@@ -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<String> 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<Vec<u8>, 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<u64>) -> Result<Vec<u8>, 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::<String>()),
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<String, String> {
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));
}
}
+193
View File
@@ -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 <package>)")]
NotPackage,
}
/// Sniff whether `bytes` begins with an SBS `<package>` 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("<package").is_some_and(|after| after.starts_with(|c: char| c == '>' || c == '/' || c.is_whitespace()))
}
/// A validated SBS XML `<package>` 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, Error> {
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<Self, Error> {
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<roxmltree::Node<'_, 'input>> {
xml::child_element(self.root(), "content")
}
/// Resolve the display package name from `<identifier>` 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 `<dependencies><dependency>`.
pub fn dependencies(&self) -> impl Iterator<Item = (&str, &str)> {
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 `<package>` XML envelope around serialized `<content>...</content>` XML.
pub fn write_package<'a>(
identifier: &str,
format_version: &str,
updater_version: &str,
dependencies: impl IntoIterator<Item = (&'a str, u64)>,
content_xml: &str,
) -> Vec<u8> {
let mut out = String::with_capacity(content_xml.len() + 4096);
let _ = write!(
out,
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><package><identifier v=\"{}\"/><formatVersion v=\"{}\"/><updaterVersion v=\"{}\"/><fileUID v=\"0\"/><versionUID v=\"0\"/><dependencies>",
xml::xml_escape(identifier),
xml::xml_escape(format_version),
xml::xml_escape(updater_version),
);
for (file, uid) in dependencies {
let _ = write!(
out,
"<dependency><filename v=\"{}\"/><uid v=\"{uid}\"/><type v=\"package\"/><fileUID v=\"0\"/><versionUID v=\"0\"/></dependency>",
xml::xml_escape(file),
);
}
out.push_str("</dependencies>");
out.push_str(content_xml);
out.push_str("</package>\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<?xml version=\"1.0\"?><!-- note --><package><content/></package>"));
assert!(is_sbs(b"<package/>"));
assert!(!is_sbs(b"<packaged/>"));
assert!(!is_sbs(b"<other/>"));
assert!(!is_sbs(b"<!-- unclosed <package>"));
}
#[test]
fn parses_package_metadata_and_dependencies() {
let xml = write_package("Wood", "1.1", "0.4.1", [(SELF_DEPENDENCY, FIRST_UID + 1), ("sbs://noise.sbs", FIRST_UID + 2)], "<content/>");
let doc = PackageDocument::parse(&xml).expect("valid package");
assert_eq!(doc.package_name("fallback.sbs"), "Wood");
assert_eq!(doc.format_version(), Some("1.1"));
let deps: Vec<_> = doc.dependencies().collect();
assert_eq!(deps, vec![("1000000001", "?himself"), ("1000000002", "sbs://noise.sbs")]);
}
#[test]
fn rejects_malformed_or_non_package_xml() {
for bytes in [b"<package>".as_slice(), b"<other/>", b"\xff", b"<!DOCTYPE package [<!ENTITY x 'x'>]><package/>"] {
assert!(PackageDocument::parse(bytes).is_err());
}
assert!(matches!(PackageDocument::parse_with_limits(b"<package/>", 4, 100), Err(Error::TooLarge { actual: 10, limit: 4 })));
}
}
+60
View File
@@ -0,0 +1,60 @@
//! Portable `sbs://` library URI validation and relative path resolution.
/// Validate an `sbs://` alias path without allowing traversal outside the library root.
pub fn relative_path(uri: &str) -> Result<&str, String> {
let path = uri.strip_prefix("sbs://").ok_or("not an SBS library alias")?;
if path.is_empty()
|| path.len() > 4096
|| path.contains(['\\', ':', '?', '#', '%', '\0'])
|| path.split('/').any(|part| part.is_empty() || matches!(part, "." | ".."))
{
return Err("invalid SBS library path".into());
}
Ok(path)
}
/// Resolve a package-relative resource or dependency without leaving the library root.
pub fn resolve(owner: &str, reference: &str) -> Result<String, String> {
let owner = relative_path(owner)?;
if reference.starts_with("sbs://") {
relative_path(reference)?;
return Ok(reference.into());
}
let reference = reference.trim().replace('\\', "/");
if reference.is_empty() || reference.len() > 4096 || reference.starts_with('/') || reference.contains([':', '?', '#', '%', '\0']) {
return Err("invalid relative SBS library path".into());
}
let mut parts: Vec<_> = owner.split('/').collect();
parts.pop();
for part in reference.split('/') {
match part {
"" | "." => {}
".." => {
if parts.pop().is_none() {
return Err("SBS reference escapes its library directory".into());
}
}
part => parts.push(part),
}
}
let uri = format!("sbs://{}", parts.join("/"));
relative_path(&uri)?;
Ok(uri)
}
#[cfg(test)]
mod tests {
use super::{relative_path, resolve};
#[test]
fn resolves_relative_and_rejects_escapes() {
assert_eq!(resolve("sbs://filters/blur.sbs", "../noises/perlin.sbs").as_deref(), Ok("sbs://noises/perlin.sbs"));
assert!(resolve("sbs://blur.sbs", "../escape.sbs").is_err());
assert!(relative_path("sbs://../bad.sbs").is_err());
}
}
+69
View File
@@ -0,0 +1,69 @@
//! SBS `<constantValue*>` XML scalar/vector value representation.
use crate::xml::{parse_floats, parse_ints};
use roxmltree::Node as XmlNode;
#[derive(Clone, Debug, PartialEq)]
pub enum SbsValue {
Floats(Vec<f32>),
Ints(Vec<i32>),
Bool(bool),
Text(String),
}
impl SbsValue {
pub fn float(&self, i: usize) -> f32 {
match self {
SbsValue::Floats(v) => v.get(i).or(v.first()).copied().unwrap_or(0.0),
SbsValue::Ints(v) => v.get(i).or(v.first()).copied().unwrap_or(0) as f32,
SbsValue::Bool(b) => f32::from(u8::from(*b)),
SbsValue::Text(_) => 0.0,
}
}
pub fn int(&self, i: usize) -> i32 {
match self {
SbsValue::Ints(v) => v.get(i).or(v.first()).copied().unwrap_or(0),
SbsValue::Floats(v) => v.get(i).or(v.first()).copied().unwrap_or(0.0).round() as i32,
SbsValue::Bool(b) => i32::from(*b),
SbsValue::Text(_) => 0,
}
}
pub fn truthy(&self) -> bool {
match self {
SbsValue::Bool(b) => *b,
SbsValue::Text(s) => s == "1" || s.eq_ignore_ascii_case("true"),
_ => self.float(0) != 0.0,
}
}
pub fn component_count(&self) -> usize {
match self {
SbsValue::Floats(v) => v.len(),
SbsValue::Ints(v) => v.len(),
_ => 1,
}
}
}
pub fn sbs_constant(holder: XmlNode) -> Option<SbsValue> {
sbs_constant_element(holder.children().find(|child| child.is_element())?)
}
pub fn sbs_constant_element(element: XmlNode) -> Option<SbsValue> {
let text = element.attribute("v").unwrap_or("");
let tag = element.tag_name().name();
if tag == "constantValueBool" {
Some(SbsValue::Bool(parse_ints(text).first().is_some_and(|b| *b != 0) || text.trim().eq_ignore_ascii_case("true")))
} else if tag == "constantValueString" {
Some(SbsValue::Text(text.to_string()))
} else if tag.starts_with("constantValueFloat") {
Some(SbsValue::Floats(parse_floats(text)))
} else if tag.starts_with("constantValueInt") {
Some(SbsValue::Ints(parse_ints(text)))
} else {
None
}
}
+80
View File
@@ -0,0 +1,80 @@
//! SBS XML attribute escaping, number parsing, and element traversal helpers.
use roxmltree::Node as XmlNode;
pub fn parse_floats(text: &str) -> Vec<f32> {
text.split_whitespace().take(16).map(|t| t.parse::<f32>().ok().filter(|v| v.is_finite()).unwrap_or(0.0)).collect()
}
pub fn parse_ints(text: &str) -> Vec<i32> {
let parse =
|t: &str| t.parse::<i64>().map(|v| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32).or_else(|_| t.parse::<f64>().map(|v| v as i32));
text.split_whitespace().take(16).map(|t| parse(t).unwrap_or(0)).collect()
}
pub fn format_float(v: f32) -> String {
if v.is_finite() { format!("{v}") } else { "0".into() }
}
pub fn child_element<'a, 'input>(node: XmlNode<'a, 'input>, tag: &str) -> Option<XmlNode<'a, 'input>> {
node.children().find(|c| c.is_element() && c.tag_name().name() == tag)
}
pub fn children_named<'a, 'input: 'a>(node: XmlNode<'a, 'input>, tag: &'a str) -> impl Iterator<Item = XmlNode<'a, 'input>> + 'a {
node.children().filter(move |c| c.is_element() && c.tag_name().name() == tag)
}
pub fn child_value<'a>(node: XmlNode<'a, '_>, tag: &str) -> Option<&'a str> {
child_element(node, tag).and_then(|c| c.attribute("v"))
}
pub fn xml_escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
// SBS historically escapes apostrophes too, although attributes are double quoted.
// Keep that byte-level policy while sharing XML validity/attribute escaping.
for (i, part) in text.split('\'').enumerate() {
if i != 0 {
out.push_str("&apos;");
}
craft_xml::push_esc_attr(&mut out, part);
}
out
}
pub fn is_parameters_element(xml: &str) -> bool {
validate_preserved_element(xml, "parameters", (16 << 20) - 1, 1_000_000).is_some()
}
pub fn validate_preserved_element<'a>(xml: &'a str, expected_tag: &str, max_bytes: usize, max_nodes: u32) -> Option<&'a str> {
if xml.len() > max_bytes {
return None;
}
let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: max_nodes, ..roxmltree::ParsingOptions::default() };
let document = roxmltree::Document::parse_with_options(xml, options).ok()?;
let root = document.root_element();
if root.tag_name().name() != expected_tag {
return None;
}
xml.get(root.range())
}
#[cfg(test)]
mod tests {
use super::xml_escape;
#[test]
fn sbs_attribute_wire_spelling_is_preserved() {
assert_eq!(xml_escape("&<>\"'\t\n\r"), "&amp;&lt;&gt;&quot;&apos;&#9;&#10;&#13;");
assert_eq!(xml_escape("\0\u{1f}\u{fffe}\u{ffff}é😀"), "é😀");
assert_eq!(xml_escape("''"), "&apos;&apos;");
assert_eq!(xml_escape(""), "");
}
#[test]
fn written_attribute_roundtrips_valid_unicode_and_whitespace() {
let value = "élan 😀 ' \" & < >\t\n\r";
let xml = format!("<value v=\"{}\"/>", xml_escape(value));
let doc = roxmltree::Document::parse(&xml).expect("valid xml");
assert_eq!(doc.root_element().attribute("v"), Some(value));
}
}