SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Opening: validate the document once when a model cache is present (#10501)
kaltenbrunnermarkus16f00d4cf9c7
diff --git a/crates/io/src/design.rs b/crates/io/src/design.rsindex 3a293b8cb5..9e3a040e2c 100644--- a/crates/io/src/design.rs+++ b/crates/io/src/design.rs@@ -734,6 +734,12 @@ impl<R: Read + Seek> DesignContainerReader<R> {pub fn read_document(mut self) -> Result<Document> {read_document(&mut self.reader)}++ /// [`Self::geometry`] when [`Self::read_document`] follows: it validates the document.+ fn geometry_before_document(&mut self) -> Option<solidcraft_doc::SavedModel> {+ let document = self.reader.document(16 << 20).ok()?;+ native_cache::read_geometry_before_document(&mut self.reader, &document).ok()+ }}pub(super) fn read(bytes: &[u8]) -> Result<Document> {@@ -750,7 +756,7 @@ pub fn read_design_file(path: &str, notify: Option<impl FnOnce(DesignPreview)>)if is_container_source(&mut source)? {let mut reader = DesignContainerReader::new(source)?;// A design with its model opens without a picture first: the model is the session.- let model = reader.geometry();+ let model = reader.geometry_before_document();if let Some(notify) = notify&& model.is_none()&& let Ok(preview) = read_preview(&mut reader.reader)@@ -1280,6 +1286,45 @@ mod tests {assert!(read_design_geometry(&bytes).is_some());}+ /// Opening a design with its model validates its document once, where the document is read+ /// (`read_document`); reading the model first validated it a second time, a whole parse and+ /// validation of a large design. A broken document still fails the open, as it did.+ #[test]+ fn opening_with_a_model_cache_validates_the_document_once() {+ let validated = || native_cache::VALIDATED.with(std::cell::Cell::get);+ let doc = document();+ let bytes = write_design_container_with_cache(&doc, DesignCompression::Fast, None, Some(&native_geometry())).unwrap();+ let before = validated();+ let alone = DesignContainerReader::new(Cursor::new(&bytes)).unwrap().geometry().unwrap();+ assert_eq!(validated(), before + 1, "the model alone checks its document");+ let mut reader = DesignContainerReader::new(Cursor::new(&bytes)).unwrap();+ let model = reader.geometry_before_document().unwrap();+ assert_eq!(validated(), before + 1, "opening leaves it to read_document");+ assert_eq!(reader.read_document().unwrap().to_json(), doc.to_json());+ assert_eq!(model.records, alone.records);+ assert_eq!(model.bodies.len(), alone.bodies.len());++ // A broken document whose cache is signed for it: the open fails with read_document's+ // error, as when the model was read with the document validated (and so missed).+ let entries = parts(&bytes);+ let mut manifest: Value = serde_json::from_slice(&entries["cache/model.json"]).unwrap();+ let mut metadata: Value = serde_json::from_slice(&entries["document.json"]).unwrap();+ metadata["features"] = json!(5);+ let truncated = entries["document.json"][..entries["document.json"].len() / 2].to_vec();+ for broken in [serde_json::to_vec(&metadata).unwrap(), truncated] {+ let mut entries = entries.clone();+ manifest["document"] = json!(digest(&broken));+ entries.insert("cache/model.json".into(), serde_json::to_vec(&manifest).unwrap());+ entries.insert("document.json".into(), broken);+ let bytes = package(&entries);+ assert!(DesignContainerReader::new(Cursor::new(&bytes)).unwrap().geometry().is_none());+ let expected = read(&bytes).unwrap_err().to_string();+ let mut reader = DesignContainerReader::new(Cursor::new(&bytes)).unwrap();+ let _ = reader.geometry_before_document();+ assert_eq!(reader.read_document().unwrap_err().to_string(), expected);+ }+ }+/// A saved model of four features (5, 50, 20 and 1 ms) whose states each hold the eight/// bodies all of them share and eight of their own (a body each feature replaces). No/// document evaluated it.diff --git a/crates/io/src/design/native_cache.rs b/crates/io/src/design/native_cache.rsindex 9f4c2b1970..dfc3e84263 100644--- a/crates/io/src/design/native_cache.rs+++ b/crates/io/src/design/native_cache.rs@@ -348,6 +348,12 @@ fn current(manifest: &Value, document: &[u8]) -> bool {&& source_trusted(env!("SOLIDCRAFT_EVALUATION_SOURCE"), cfg!(any(test, feature = "trust-unknown-source")))}+#[cfg(test)]+thread_local! {+ /// How often reading a model cache validated its document (tests count it).+ pub(super) static VALIDATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+}+/// A build of unknown source (no git) never trusts a cache, unless `in_tests`: test builds/// trust it so the cache tests also pass in a source tarball (the `trust-unknown-source`/// feature is only enabled by dev-dependencies).@@ -356,6 +362,17 @@ pub(super) fn source_trusted(commit: &str, in_tests: bool) -> bool {}pub(super) fn read_geometry_with<R: Read + Seek>(reader: &mut PackageReader<R>, document: &[u8]) -> Result<SavedModel> {+ read_geometry(reader, document, true)+}++/// [`read_geometry_with`] for a reader whose document is read next: reading it runs the same+/// migrations and validation and fails the open when they fail, so validating it here as well+/// parsed and validated a large design twice (the model is dropped with the failed open).+pub(super) fn read_geometry_before_document<R: Read + Seek>(reader: &mut PackageReader<R>, document: &[u8]) -> Result<SavedModel> {+ read_geometry(reader, document, false)+}++fn read_geometry<R: Read + Seek>(reader: &mut PackageReader<R>, document: &[u8], validate: bool) -> Result<SavedModel> {let container: Value = serde_json::from_slice(&reader.limited_part("container.json", 4096)?).map_err(invalid)?;if container.get("format").and_then(Value::as_str) != Some(VERSION) {return Err(invalid("container version"));@@ -365,7 +382,11 @@ pub(super) fn read_geometry_with<R: Read + Seek>(reader: &mut PackageReader<R>,return Err(invalid("model cache key"));}// Validate the small parametric metadata before decoding any geometry.- Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?;+ if validate {+ #[cfg(test)]+ VALIDATED.with(|n| n.set(n.get() + 1));+ Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?;+ }let data = reader.limited_part(PAYLOAD, max_design())?;if manifest.get("payload").and_then(Value::as_str) != Some(digest(&data).as_str()) {return Err(invalid("model cache payload key"));