From ee7e544fa68f9653bf62c1c5353af452b9421fd0 Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Thu, 26 Nov 2026 12:28:25 +0000 Subject: [PATCH 1/9] Reuse declared memory digests on ordinary snapshot saves Keep asserted layer digests separate from computed or verified hashes. Ordinary load/save avoids rehashing trusted memory, while checked_save continues to verify and repair content. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jorge Prendes --- CHANGELOG.md | 3 ++ docs/snapshot-oci-format.md | 12 ++++- .../src/sandbox/snapshot/file/mod.rs | 19 +++++-- .../src/sandbox/snapshot/file_tests.rs | 54 +++++++++++++++++++ .../src/sandbox/snapshot/memory/mod.rs | 2 + 5 files changed, 85 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f24f4e7b..91622d4ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). * Add ARM64 Linux MSHV support by @cshung in https://github.com/hyperlight-dev/hyperlight/pull/1626 ### Changed +* `Snapshot::load` retains declared memory-layer digests for ordinary saves + instead of hashing the loaded bytes on first save. Incorrect declarations + are preserved; use `checked_load` or `checked_save` for content consistency. * `hyperlight-host` requires Rust 1.95. * `Snapshot::save` caches memory-layer hashes and trusts existing same-length regular blobs by their content-addressed filenames without verifying their diff --git a/docs/snapshot-oci-format.md b/docs/snapshot-oci-format.md index ac6d459b9..1e4808993 100644 --- a/docs/snapshot-oci-format.md +++ b/docs/snapshot-oci-format.md @@ -78,8 +78,15 @@ blob files with the expected length are trusted by their content-addressed filenames without reading or hashing their contents, even at a new destination. There is no backing-file cache. Missing blobs are written atomically; symlinks and wrong-length files are replaced. -`Snapshot::checked_load` seeds the digest cache during verification; unchecked -`load` does not. Metadata blobs retain their normal write path. +`Snapshot::checked_load` seeds the verified digest cache; ordinary `load` +retains declared digests separately for reuse on save without hashing memory. +Metadata blobs retain their normal write path. + +`Snapshot::load` trusts declared memory digests without reading memory to verify +them. Ordinary saves preserve those declarations instead of computing digests +from actual bytes, including when the declared digest is incorrect. Declared +hashes are stored separately from computed or verified hashes; checked saving +still hashes every layer. Structural validation remains enabled. Callers must keep loaded and published memory blobs immutable for the lifetime of these snapshots and outside writable guest mounts. Host-side mutation and @@ -175,6 +182,7 @@ podman), `go-containerregistry` (crane), and `regclient`. `Snapshot::load(path, reference)` reads a snapshot. It does not check the manifest, config, or data blobs against their sha256 digests. +It retains declared memory digests for ordinary saves. `reference` is an [`OciReference`], either a tag that matches the `org.opencontainers.image.ref.name` annotation or the manifest diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs index 4454a7ff4..82990a4aa 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs @@ -579,6 +579,8 @@ impl Snapshot { let bytes = blob.memory().as_slice(); let digest = if verify_blobs { Digest256::from_bytes(bytes) + } else if let Some(hex) = blob.sha256.get().or(blob.declared_sha256.as_ref()) { + Digest256 { hex: hex.clone() } } else { let hex = blob.sha256.get_or_init(|| Digest256::from_bytes(bytes).hex); Digest256 { hex: hex.clone() } @@ -749,9 +751,16 @@ impl Snapshot { /// /// # Verification /// - /// This method does not check the manifest, config, memory, or transport + /// This method does not check the manifest, config, or memory /// blobs against their recorded sha256 digests. Load only from a /// layout you trust. + /// Declared memory-layer digests are retained and reused by ordinary + /// [`Snapshot::save`] without hashing the mapped bytes. Incorrect declarations + /// can therefore publish bytes under incorrect filenames; use checked loading + /// or [`Snapshot::checked_save`] when content consistency is required. + /// Structural validation remains enabled. Declared hashes are kept separate + /// from computed or verified hashes, so checked APIs do not treat them as + /// established content identity. /// /// To check the digests on load at the expense of some /// performance, use [`Snapshot::checked_load`]. @@ -997,12 +1006,16 @@ impl Snapshot { .zip(data_descs) .zip(&snap_files) .map(|((layer, desc), file)| { - Ok(Arc::new(SnapshotBlob::new( + let mut blob = SnapshotBlob::new( map_snapshot_blob(file, desc, layer.data_len)?, layer.gpa_start, layer.page_table_len, scratch_base, - )?)) + )?; + if !verify_blobs { + blob.declared_sha256 = Some(parse_oci_digest(desc.digest())?); + } + Ok(Arc::new(blob)) }) .collect::>>()?; let page_tables = blobs[cfg.page_table_layer].clone(); diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index ba5844957..9ff7e0a6c 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -708,6 +708,60 @@ fn save_reuses_hashes_across_saves_and_checked_loads() { assert_eq!(sandbox.call::("GetStatic", ()).unwrap(), 0); } +#[test] +fn load_reuses_declared_digests_without_promoting_them_to_verified() { + let snapshot = create_snapshot(); + let dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + snapshot.save(dir.path(), &tag).unwrap(); + let memory_bytes: usize = snapshot + .snapshot_memory() + .blobs() + .map(|blob| blob.memory().as_slice().len()) + .sum(); + let before = super::file::test_hashed_bytes(); + let loaded = Snapshot::load(dir.path(), tag.clone()).unwrap(); + assert!(super::file::test_hashed_bytes() - before < memory_bytes); + assert!( + loaded + .snapshot_memory() + .blobs() + .all(|blob| blob.sha256.get().is_none() && blob.declared_sha256.is_some()) + ); + let other = tempfile::tempdir().unwrap(); + let before = super::file::test_hashed_bytes(); + loaded.save(other.path(), &tag).unwrap(); + assert!(super::file::test_hashed_bytes() - before < memory_bytes); + let checked_dir = tempfile::tempdir().unwrap(); + let before = super::file::test_hashed_bytes(); + loaded.checked_save(checked_dir.path(), &tag).unwrap(); + assert!(super::file::test_hashed_bytes() - before >= memory_bytes); + Snapshot::checked_load(checked_dir.path(), tag).unwrap(); +} + +#[test] +fn load_accepts_wrong_content_digest_but_rejects_wrong_size() { + let snapshot = create_snapshot(); + let dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + snapshot.save(dir.path(), &tag).unwrap(); + let path = find_snapshot_blob(dir.path()); + let mut bytes = std::fs::read(&path).unwrap(); + bytes[0] ^= 1; + std::fs::write(&path, &bytes).unwrap(); + assert!(Snapshot::checked_load(dir.path(), tag.clone()).is_err()); + let trusted = Snapshot::load(dir.path(), tag.clone()).unwrap(); + let output = tempfile::tempdir().unwrap(); + trusted.save(output.path(), &tag).unwrap(); + assert!(Snapshot::checked_load(output.path(), tag.clone()).is_err()); + trusted.checked_save(output.path(), &tag).unwrap(); + Snapshot::checked_load(output.path(), tag.clone()).unwrap(); + drop(trusted); + bytes.pop(); + std::fs::write(path, bytes).unwrap(); + assert!(Snapshot::load(dir.path(), tag).is_err()); +} + #[test] fn save_trusts_replaced_files_and_writes_new_destinations() { let snapshot = create_snapshot(); diff --git a/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs index 359fd2ef7..a41cb0daa 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs @@ -57,6 +57,7 @@ pub(crate) struct SnapshotBlob { gpa_start: u64, page_table_len: usize, pub(super) sha256: OnceLock, + pub(super) declared_sha256: Option, } impl SnapshotBlob { @@ -98,6 +99,7 @@ impl SnapshotBlob { gpa_start, page_table_len, sha256: OnceLock::new(), + declared_sha256: None, }) } From 4cec72d15d3481ba7b11e97832186a745c03e9e7 Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Thu, 26 Nov 2026 12:28:45 +0000 Subject: [PATCH 2/9] Add provenance-validated snapshot overlay loading Add load_overlay and checked_load_overlay methods that require a declared whole-snapshot base and reuse matching immutable layers. Persist snapshot IDs and inherit provenance through capture and compaction without retaining unused layers or adding memory-manager bookkeeping. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jorge Prendes --- CHANGELOG.md | 5 + docs/snapshot-oci-format.md | 44 ++- .../src/sandbox/snapshot/compact.rs | 10 +- .../src/sandbox/snapshot/file/config.rs | 20 ++ .../src/sandbox/snapshot/file/mod.rs | 158 +++++++-- .../src/sandbox/snapshot/file_tests.rs | 302 +++++++++++++++++- .../src/sandbox/snapshot/memory/backing.rs | 4 + .../src/sandbox/snapshot/memory/mod.rs | 15 + .../src/sandbox/snapshot/mod.rs | 4 +- 9 files changed, 531 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91622d4ab..dd1923558 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). * `Snapshot::load` retains declared memory-layer digests for ordinary saves instead of hashing the loaded bytes on first save. Incorrect declarations are preserved; use `checked_load` or `checked_save` for content consistency. + `base.load_overlay` and `base.checked_load_overlay` resolve matching layers from + a caller-authorized, declared whole-snapshot base, keeping declared and + verified digests separate. Persisted snapshot IDs and inherited base + declarations support both compacted and uncompacted descendants without + retaining unused base layers. * `hyperlight-host` requires Rust 1.95. * `Snapshot::save` caches memory-layer hashes and trusts existing same-length regular blobs by their content-addressed filenames without verifying their diff --git a/docs/snapshot-oci-format.md b/docs/snapshot-oci-format.md index 1e4808993..604092527 100644 --- a/docs/snapshot-oci-format.md +++ b/docs/snapshot-oci-format.md @@ -82,11 +82,44 @@ and wrong-length files are replaced. retains declared digests separately for reuse on save without hashing memory. Metadata blobs retain their normal write path. +`base.checked_load_overlay(path, reference)` resolves memory layers from an existing base +when their cached SHA-256, size, GPA and data/page-table geometry match. It shares +the base's layer objects without opening or reading those files from the new +layout; the matching files may be omitted. Other blobs are verified normally. +This is explicit content resolution from the supplied base, not validation of +an on-disk copy of a reused blob. Retaining the same objects through restore, +capture and base-preserving compaction avoids both byte comparisons and repeated +hashing of immutable base memory. + `Snapshot::load` trusts declared memory digests without reading memory to verify -them. Ordinary saves preserve those declarations instead of computing digests -from actual bytes, including when the declared digest is incorrect. Declared -hashes are stored separately from computed or verified hashes; checked saving -still hashes every layer. Structural validation remains enabled. +them. Ordinary saves preserve those declarations, and +`base.load_overlay(path, reference)` resolves matching layers +by digest and geometry. Declared hashes are stored separately from computed or +verified hashes: checked base loading never reuses a mere declaration, and +checked saving still hashes every layer. This changes prior ordinary +`load`-then-`save` behavior: it preserves declared digests instead of computing +them from actual bytes, including when the declared digest is incorrect. +Structural validation remains enabled in all modes. A declaration is neither +content authentication nor permission to read another actor's memory; callers +must restrict base sharing to authorized, immutable objects. Incorrect digests +can substitute guest state or publish bytes under an incorrect name. + +Both overlay methods require persisted provenance declaring the supplied whole +snapshot as a base; a matching memory layer alone is insufficient. Each new VM +snapshot has a stable UUID stored as `snapshot_id` in the OCI config, with +ancestor IDs in `bases`. Metadata-only copies retain the VM snapshot's ID. +Restore/capture inherits the restored snapshot and its bases, including without +compaction. `compact(Some(base))` also records the specified base and its bases; +`compact(None)` preserves ancestry. Neither operation retains unused layers +merely to establish provenance. +Provenance is carried by the whole `SnapshotMemory` object, not individual +blobs, so capture inherits it directly from the existing memory backing. + +These IDs are trusted declarations, not content digests or cryptographic proofs +of ancestry, even with checked loading. Legacy configs without provenance still +load standalone, receiving a new in-memory ID. Save that base to persist its ID +before relying on independently loaded copies for overlay. A layout without a +matching base declaration cannot be overlaid. Callers must keep loaded and published memory blobs immutable for the lifetime of these snapshots and outside writable guest mounts. Host-side mutation and @@ -182,7 +215,8 @@ podman), `go-containerregistry` (crane), and `regclient`. `Snapshot::load(path, reference)` reads a snapshot. It does not check the manifest, config, or data blobs against their sha256 digests. -It retains declared memory digests for ordinary saves. +It retains declared memory digests for ordinary saves; `load_overlay` also +shares matching layers from an explicitly supplied, authorized base. `reference` is an [`OciReference`], either a tag that matches the `org.opencontainers.image.ref.name` annotation or the manifest diff --git a/src/hyperlight_host/src/sandbox/snapshot/compact.rs b/src/hyperlight_host/src/sandbox/snapshot/compact.rs index 51d74fd1b..7657d9f6d 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/compact.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/compact.rs @@ -18,6 +18,9 @@ impl Snapshot { /// layers and unreferenced pages in merged layers are discarded, except /// for minimal padding required by the snapshot format. Retained base /// layers are kept whole. + /// The result records this snapshot and the specified base as ancestors, + /// including their inherited bases, for [`Snapshot::load_overlay`]. Provenance + /// does not require retaining any otherwise unused layer. /// /// Registers, metadata, transport state, generation, and page-table roots /// are preserved. The result uses the existing snapshot file format. @@ -158,9 +161,14 @@ impl Snapshot { if data_len > 0 { layers.push(blob.clone()); } + let mut memory = SnapshotMemory::new(layers.into_boxed_slice(), blob)?; + memory.record_base(self.snapshot_memory()); + if let Some(base) = base { + memory.record_base(base.snapshot_memory()); + } Ok(Arc::new(Self { state: Arc::new(SnapshotState { - memory: Arc::new(SnapshotMemory::new(layers.into_boxed_slice(), blob)?), + memory: Arc::new(memory), ..(*self.state).clone() }), metadata: self.metadata.clone(), diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/config.rs b/src/hyperlight_host/src/sandbox/snapshot/file/config.rs index 9db9e83af..ca632c3b8 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/config.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/config.rs @@ -213,6 +213,10 @@ pub(super) struct OciSnapshotConfig { /// `SCRATCH_TOP_SNAPSHOT_GENERATION_OFFSET` is continuous across /// save/load. pub(super) snapshot_generation: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) snapshot_id: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(super) bases: Vec, /// Application-owned metadata keyed by namespace. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(super) metadata: BTreeMap, @@ -430,6 +434,20 @@ impl OciSnapshotConfig { } pub(super) fn validate_for_load(&self) -> crate::Result<()> { + if self.snapshot_id.is_none() && !self.bases.is_empty() { + return Err(crate::new_error!("snapshot bases require a snapshot ID")); + } + let mut ids = std::collections::HashSet::new(); + for id in self.snapshot_id.iter().chain(&self.bases) { + let id = uuid::Uuid::parse_str(id) + .map_err(|e| crate::new_error!("invalid snapshot provenance ID: {}", e))?; + if id.is_nil() { + return Err(crate::new_error!("snapshot provenance ID must not be nil")); + } + if !ids.insert(id) { + return Err(crate::new_error!("duplicate snapshot provenance ID")); + } + } if self.arch != Arch::current() { return Err(crate::new_error!( "snapshot architecture mismatch: file is {:?}, current host is {:?} \ @@ -808,6 +826,8 @@ mod tests { /// gating checks under test short-circuit before reading it. fn gating_config() -> OciSnapshotConfig { OciSnapshotConfig { + snapshot_id: None, + bases: Vec::new(), hyperlight_version: "test".to_string(), arch: Arch::current(), abi_version: SNAPSHOT_ABI_VERSION, diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs index 82990a4aa..6ceadb4d8 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs @@ -711,6 +711,14 @@ impl Snapshot { .ok_or_else(|| crate::new_error!("snapshot page-table blob is missing"))?, host_functions, snapshot_generation: self.state.snapshot_generation, + snapshot_id: Some(self.state.memory.id.to_string()), + bases: self + .state + .memory + .bases + .iter() + .map(ToString::to_string) + .collect(), metadata: self.metadata.clone(), }) } @@ -788,7 +796,7 @@ impl Snapshot { /// # } /// ``` pub fn load(path: impl AsRef, reference: impl Into) -> crate::Result { - Self::load_inner(path.as_ref(), &reference.into(), false) + Self::load_inner(path.as_ref(), &reference.into(), false, None) } /// Loads a snapshot like [`Snapshot::load`]. See its rustdoc for @@ -807,13 +815,83 @@ impl Snapshot { path: impl AsRef, reference: impl Into, ) -> crate::Result { - Self::load_inner(path.as_ref(), &reference.into(), true) + Self::load_inner(path.as_ref(), &reference.into(), true, None) + } + + /// Loads and verifies a descendant snapshot, sharing matching memory blobs with `self`. + /// + /// Unlike [`Snapshot::load`], this method requires a declared base relationship + /// with `self`, can reuse its memory layers instead of loading their files + /// from `path`, and verifies content digests. See [`Snapshot::load_overlay`] + /// for how base sharing differs from loading a self-contained snapshot. + /// + /// Layers with the same geometry and a matching cached SHA-256 digest are + /// shared with `self` without opening or reading their files in `path`. + /// These files may be omitted from the layout. Other blobs are loaded and + /// verified as in [`Snapshot::checked_load`]. A base with an incompatible + /// memory layout is rejected. + /// + /// Only computed or verified digests are reused. Ordinary loading retains + /// declarations, which ordinary saving does not promote to verified identity. + /// Layers without computed or verified digests are not reused. Keep the base's backing + /// files immutable for the lifetime of the returned snapshot and any derived + /// sandboxes, as described in [`Snapshot::load`]. + /// The persisted provenance must declare `self` as a base, as recorded by + /// compaction or restore/capture. This declaration is trusted, not a proof + /// of ancestry; digest verification only checks content consistency. + pub fn checked_load_overlay( + &self, + path: impl AsRef, + reference: impl Into, + ) -> crate::Result { + Self::load_inner(path.as_ref(), &reference.into(), true, Some(self)) + } + + /// Loads a descendant snapshot like [`Snapshot::load`], sharing memory with `self`. + /// + /// Unlike [`Snapshot::load`], which loads every memory layer from `path` + /// without requiring a base relationship, this method uses `self` as the + /// declared base and can reuse its matching layers when their files are + /// absent from `path`. Both methods trust declared content digests. + /// + /// The saved snapshot supplies the complete target state, including its + /// registers, metadata, and layer list. This method reuses backing memory; + /// it does not merge state or append otherwise unused layers from `self`. + /// + /// The persisted provenance must declare `self` as a base. Compaction with + /// an explicit base and capture after restoration record this relationship, + /// including inherited bases, without retaining unused memory layers. + /// + /// Matching layers are shared by digest and geometry without opening their + /// files, which may be omitted from the layout. A base with an incompatible + /// memory layout is rejected. Ordinary saves reuse declared digests without + /// hashing memory, as with [`Snapshot::load`]. + /// + /// # Trust + /// + /// A declared digest is not verified content identity or authorization. + /// Only supply bases the caller is allowed to read; do not admit these + /// declarations into a cross-actor content cache. Keep backing files + /// immutable as required by [`Snapshot::load`]. Incorrect declarations may + /// substitute guest state or publish blobs under incorrect filenames. + /// + /// Declared digests remain separate from verified digest caches: + /// [`Snapshot::checked_load_overlay`] does not reuse them, and + /// [`Snapshot::checked_save`] still verifies all memory bytes. + /// Base provenance is also a trusted declaration, not a proof of ancestry. + pub fn load_overlay( + &self, + path: impl AsRef, + reference: impl Into, + ) -> crate::Result { + Self::load_inner(path.as_ref(), &reference.into(), false, Some(self)) } fn load_inner( path: &Path, reference: &OciReference, verify_blobs: bool, + base: Option<&Snapshot>, ) -> crate::Result { let meta = std::fs::metadata(path) .map_err(|e| crate::new_error!("load failed to stat {:?}: {}", path, e))?; @@ -879,6 +957,26 @@ impl Snapshot { // Validate the ABI before interpreting the layer layout. let cfg = load_config(&blobs_dir, cfg_desc, verify_blobs)?; + let id = cfg + .snapshot_id + .as_deref() + .map(uuid::Uuid::parse_str) + .transpose() + .map_err(|e| crate::new_error!("invalid snapshot ID: {}", e))? + .unwrap_or_else(uuid::Uuid::new_v4); + let bases = cfg + .bases + .iter() + .map(|id| uuid::Uuid::parse_str(id)) + .collect::, _>>() + .map_err(|e| crate::new_error!("invalid snapshot base ID: {}", e))?; + if let Some(base) = base + && !bases.contains(&base.state.memory.id) + { + return Err(crate::new_error!( + "snapshot does not declare the supplied snapshot as a base" + )); + } let data_descs = manifest.layers(); for snap_desc in data_descs { @@ -961,14 +1059,6 @@ impl Snapshot { })?; } - // 5. snapshot blobs: open each once, hash and mmap the same - // handle so an attacker cannot swap the file between - // verification and mapping. - let mut snap_files = data_descs - .iter() - .map(|desc| open_snapshot_blob(&blobs_dir, desc)) - .collect::>>()?; - // 6. Reconstruct layout. let mut sbox_cfg = crate::sandbox::SandboxConfiguration::default(); sbox_cfg.set_scratch_size(cfg.layout.scratch_size); @@ -986,6 +1076,11 @@ impl Snapshot { }; layout.set_code_gva(code_gva)?; layout.ensure_page_tables_fit(cfg.layers[cfg.page_table_layer].page_table_len)?; + if base.is_some_and(|base| base.state.layout != layout) { + return Err(crate::new_error!( + "snapshot base has an incompatible memory layout" + )); + } let virtq = VirtqSnapshot::bootstrap(&layout)?; @@ -1000,22 +1095,42 @@ impl Snapshot { // next layer and with `map_file_cow` regions installed // immediately after the snapshot in guest PA space. let scratch_base = hyperlight_common::layout::scratch_base_gpa(layout.get_scratch_size()); + let mut snap_files = Vec::with_capacity(data_descs.len()); let blobs = cfg .layers .iter() .zip(data_descs) - .zip(&snap_files) - .map(|((layer, desc), file)| { + .map(|(layer, desc)| { + let digest = parse_oci_digest(desc.digest())?; + let shared = base.and_then(|base| { + base.state.memory.blobs().find(|blob| { + blob.gpa_start() == layer.gpa_start + && blob.data_len() == layer.data_len + && blob.page_table_len() == layer.page_table_len + && blob.memory().as_slice().len() as u64 == desc.size() + && (blob.sha256.get() == Some(&digest) + || (!verify_blobs + && blob.declared_sha256.as_ref() == Some(&digest))) + }) + }); + if let Some(blob) = shared { + snap_files.push(None); + return Ok(blob.clone()); + } + // Verify and map the same handle; never reopen by pathname. + let file = open_snapshot_blob(&blobs_dir, desc)?; let mut blob = SnapshotBlob::new( - map_snapshot_blob(file, desc, layer.data_len)?, + map_snapshot_blob(&file, desc, layer.data_len)?, layer.gpa_start, layer.page_table_len, scratch_base, )?; if !verify_blobs { - blob.declared_sha256 = Some(parse_oci_digest(desc.digest())?); + blob.declared_sha256 = Some(digest); } - Ok(Arc::new(blob)) + let blob = Arc::new(blob); + snap_files.push(Some(file)); + Ok(blob) }) .collect::>>()?; let page_tables = blobs[cfg.page_table_layer].clone(); @@ -1024,14 +1139,19 @@ impl Snapshot { .filter(|blob| blob.data_len() > 0) .cloned() .collect(); - let memory = Arc::new(SnapshotMemory::new(data_layers, page_tables)?); + let mut memory = SnapshotMemory::new(data_layers, page_tables)?; + memory.id = id; + memory.bases = bases; + let memory = Arc::new(memory); // Hash after validating the layers so malformed snapshots fail // cheaply. if verify_blobs { for ((desc, file), blob) in data_descs.iter().zip(&mut snap_files).zip(&blobs) { - let digest = parse_oci_digest(desc.digest())?; - verify_blob_file("snapshot", file, &digest)?; - blob.sha256.get_or_init(|| digest); + if let Some(file) = file { + let digest = parse_oci_digest(desc.digest())?; + verify_blob_file("snapshot", file, &digest)?; + blob.sha256.get_or_init(|| digest); + } } } diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index 9ff7e0a6c..eeb10d7d3 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -29,6 +29,25 @@ fn create_c_test_sandbox() -> Sandbox { SandboxBuilder::from_file(path).build().unwrap() } +fn snapshot_with_shared_blobs(snapshot: &Snapshot, base: Option<&Snapshot>) -> Snapshot { + let source = snapshot.snapshot_memory(); + let mut memory = SnapshotMemory::new( + source.layers().to_vec().into_boxed_slice(), + source.page_table_blob().clone(), + ) + .unwrap(); + if let Some(base) = base { + memory.record_base(base.snapshot_memory()); + } + Snapshot { + state: Arc::new(super::SnapshotState { + memory: Arc::new(memory), + ..(*snapshot.state).clone() + }), + metadata: snapshot.metadata.clone(), + } +} + /// Startup replies survive release in the source guest, restore, and OCI loading. #[test] fn retained_initial_data_survives_snapshots() { @@ -708,6 +727,134 @@ fn save_reuses_hashes_across_saves_and_checked_loads() { assert_eq!(sandbox.call::("GetStatic", ()).unwrap(), 0); } +#[test] +fn overlay_requires_whole_base_provenance_without_retaining_unused_layers() { + let base = create_snapshot(); + let unrelated = snapshot_with_shared_blobs(&base, None); + let dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + unrelated.save(dir.path(), &tag).unwrap(); + for checked in [false, true] { + let result = if checked { + base.checked_load_overlay(dir.path(), tag.clone()) + } else { + base.load_overlay(dir.path(), tag.clone()) + }; + assert!( + result + .err() + .unwrap() + .to_string() + .contains("does not declare") + ); + } + + let packed = unrelated.compact(None).unwrap(); + let overlay = packed.compact(Some(&base)).unwrap(); + assert!(overlay.snapshot_memory().blobs().all(|blob| { + !base + .snapshot_memory() + .blobs() + .any(|base| Arc::ptr_eq(blob, base)) + })); + overlay.save(dir.path(), &tag).unwrap(); + base.load_overlay(dir.path(), tag.clone()).unwrap(); + base.checked_load_overlay(dir.path(), tag.clone()).unwrap(); + + rewrite_config(dir.path(), |config| { + config.as_object_mut().unwrap().remove("bases"); + }); + assert!(base.load_overlay(dir.path(), tag.clone()).is_err()); + assert!(base.checked_load_overlay(dir.path(), tag).is_err()); +} + +#[test] +fn overlay_preserves_saved_base_identity_through_uncompacted_captures() { + let mut sandbox = create_test_sandbox(); + let base = sandbox.snapshot().unwrap(); + let base_dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + base.save(base_dir.path(), &tag).unwrap(); + let loaded_base = Snapshot::checked_load(base_dir.path(), tag.clone()).unwrap(); + let mut restored = SandboxBuilder::from_snapshot(base.clone()).build().unwrap(); + let mut directories = Vec::new(); + for value in 1..=3 { + assert_eq!(restored.call::("AddToStatic", 1i32).unwrap(), value); + let captured = restored.snapshot().unwrap(); + let dir = tempfile::tempdir().unwrap(); + captured.save(dir.path(), &tag).unwrap(); + let ordinary = loaded_base.load_overlay(dir.path(), tag.clone()).unwrap(); + let checked = loaded_base + .checked_load_overlay(dir.path(), tag.clone()) + .unwrap(); + assert_eq!(ordinary.snapshot_memory().id, captured.snapshot_memory().id); + assert_eq!(checked.snapshot_memory().id, captured.snapshot_memory().id); + restored.restore(Arc::new(checked)).unwrap(); + directories.push(dir); + } + assert_eq!(restored.call::("GetStatic", ()).unwrap(), 3); + drop(restored); + drop(directories); + + let mut previous = base; + for value in 1..=3 { + assert_eq!(sandbox.call::("AddToStatic", 1i32).unwrap(), value); + let captured = sandbox.snapshot().unwrap(); + let dir = tempfile::tempdir().unwrap(); + captured.save(dir.path(), &tag).unwrap(); + loaded_base.load_overlay(dir.path(), tag.clone()).unwrap(); + previous + .checked_load_overlay(dir.path(), tag.clone()) + .unwrap(); + previous = captured; + } +} + +#[test] +fn malformed_snapshot_provenance_is_rejected_and_legacy_layouts_load() { + let snapshot = create_snapshot(); + let dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + for (id, bases) in [ + (serde_json::json!("not-an-id"), serde_json::json!([])), + ( + serde_json::json!(uuid::Uuid::nil().to_string()), + serde_json::json!([]), + ), + ( + serde_json::json!(snapshot.snapshot_memory().id.to_string()), + serde_json::json!([snapshot.snapshot_memory().id.to_string()]), + ), + ( + serde_json::Value::Null, + serde_json::json!([snapshot.snapshot_memory().id.to_string()]), + ), + ] { + snapshot.save(dir.path(), &tag).unwrap(); + rewrite_config(dir.path(), |config| { + config["snapshot_id"] = id; + config["bases"] = bases; + }); + assert!(Snapshot::load(dir.path(), tag.clone()).is_err()); + assert!(Snapshot::checked_load(dir.path(), tag.clone()).is_err()); + } + snapshot.save(dir.path(), &tag).unwrap(); + rewrite_config(dir.path(), |config| { + config.as_object_mut().unwrap().remove("snapshot_id"); + config.as_object_mut().unwrap().remove("bases"); + }); + let legacy = Snapshot::checked_load(dir.path(), tag.clone()).unwrap(); + assert!(snapshot.load_overlay(dir.path(), tag.clone()).is_err()); + legacy.save(dir.path(), &tag).unwrap(); + assert_eq!( + Snapshot::load(dir.path(), tag) + .unwrap() + .snapshot_memory() + .id, + legacy.snapshot_memory().id + ); +} + #[test] fn load_reuses_declared_digests_without_promoting_them_to_verified() { let snapshot = create_snapshot(); @@ -720,18 +867,40 @@ fn load_reuses_declared_digests_without_promoting_them_to_verified() { .map(|blob| blob.memory().as_slice().len()) .sum(); let before = super::file::test_hashed_bytes(); - let loaded = Snapshot::load(dir.path(), tag.clone()).unwrap(); + let base = Snapshot::load(dir.path(), tag.clone()).unwrap(); assert!(super::file::test_hashed_bytes() - before < memory_bytes); assert!( - loaded - .snapshot_memory() + base.snapshot_memory() .blobs() - .all(|blob| blob.sha256.get().is_none() && blob.declared_sha256.is_some()) + .all(|blob| { blob.sha256.get().is_none() && blob.declared_sha256.is_some() }) ); + let other = tempfile::tempdir().unwrap(); let before = super::file::test_hashed_bytes(); - loaded.save(other.path(), &tag).unwrap(); + let derived = snapshot_with_shared_blobs(&base, Some(&base)); + derived.save(other.path(), &tag).unwrap(); assert!(super::file::test_hashed_bytes() - before < memory_bytes); + for blob in base.snapshot_memory().blobs() { + std::fs::remove_file( + other + .path() + .join("blobs/sha256") + .join(blob.declared_sha256.as_ref().unwrap()), + ) + .unwrap(); + } + assert!( + base.checked_load_overlay(other.path(), tag.clone()) + .is_err() + ); + let loaded = base.load_overlay(other.path(), tag.clone()).unwrap(); + for (layer, base) in loaded + .snapshot_memory() + .blobs() + .zip(base.snapshot_memory().blobs()) + { + assert!(Arc::ptr_eq(layer, base)); + } let checked_dir = tempfile::tempdir().unwrap(); let before = super::file::test_hashed_bytes(); loaded.checked_save(checked_dir.path(), &tag).unwrap(); @@ -751,6 +920,14 @@ fn load_accepts_wrong_content_digest_but_rejects_wrong_size() { std::fs::write(&path, &bytes).unwrap(); assert!(Snapshot::checked_load(dir.path(), tag.clone()).is_err()); let trusted = Snapshot::load(dir.path(), tag.clone()).unwrap(); + let derived = snapshot_with_shared_blobs(&trusted, Some(&trusted)); + let derived_dir = tempfile::tempdir().unwrap(); + derived.save(derived_dir.path(), &tag).unwrap(); + assert!( + trusted + .checked_load_overlay(derived_dir.path(), tag.clone()) + .is_err() + ); let output = tempfile::tempdir().unwrap(); trusted.save(output.path(), &tag).unwrap(); assert!(Snapshot::checked_load(output.path(), tag.clone()).is_err()); @@ -762,6 +939,121 @@ fn load_accepts_wrong_content_digest_but_rejects_wrong_size() { assert!(Snapshot::load(dir.path(), tag).is_err()); } +#[test] +fn checked_overlay_resolves_missing_blobs_without_rehashing() { + let snapshot = create_snapshot(); + let dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + snapshot.save(dir.path(), &tag).unwrap(); + let base = Snapshot::checked_load(dir.path(), tag.clone()).unwrap(); + let uncached = Snapshot::load(dir.path(), tag.clone()).unwrap(); + let other = tempfile::tempdir().unwrap(); + let derived = snapshot_with_shared_blobs(&snapshot, Some(&snapshot)); + derived.save(other.path(), &tag).unwrap(); + let memory_bytes: usize = base + .snapshot_memory() + .blobs() + .map(|blob| { + std::fs::remove_file( + other + .path() + .join("blobs/sha256") + .join(blob.sha256.get().unwrap()), + ) + .unwrap(); + blob.memory().as_slice().len() + }) + .sum(); + + assert!(Snapshot::checked_load(other.path(), tag.clone()).is_err()); + assert!( + uncached + .checked_load_overlay(other.path(), tag.clone()) + .is_err() + ); + let before = super::file::test_hashed_bytes(); + let loaded = base + .checked_load_overlay(other.path(), tag.clone()) + .unwrap(); + assert!(super::file::test_hashed_bytes() - before < memory_bytes); + for (loaded, base) in loaded + .snapshot_memory() + .blobs() + .zip(base.snapshot_memory().blobs()) + { + assert!(Arc::ptr_eq(loaded, base)); + } + let before = super::file::test_hashed_bytes(); + loaded.save(other.path(), &tag).unwrap(); + assert!(super::file::test_hashed_bytes() - before < memory_bytes); + let mut sandbox = SandboxBuilder::from_snapshot(Arc::new(loaded)) + .build() + .unwrap(); + assert_eq!(sandbox.call::("AddToStatic", 1i32).unwrap(), 1); +} + +#[test] +#[cfg(not(unshared_snapshot_mem))] +fn checked_overlay_retains_shared_layers_and_verifies_new_memory() { + let mut sandbox = create_test_sandbox(); + let base = sandbox.snapshot().unwrap(); + let base_dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + base.save(base_dir.path(), &tag).unwrap(); + let base = Arc::new(Snapshot::checked_load(base_dir.path(), tag.clone()).unwrap()); + sandbox.restore(base.clone()).unwrap(); + let mut last_dir = None; + for value in 1..=3 { + assert_eq!(sandbox.call::("AddToStatic", 1i32).unwrap(), value); + let captured = sandbox.snapshot().unwrap(); + assert!(captured.snapshot_memory().layers().iter().any(|layer| { + base.snapshot_memory() + .layers() + .iter() + .any(|base| Arc::ptr_eq(layer, base)) + })); + let compacted = captured.compact(Some(&base)).unwrap(); + let dir = tempfile::tempdir().unwrap(); + compacted.save(dir.path(), &tag).unwrap(); + let loaded = Arc::new(base.checked_load_overlay(dir.path(), tag.clone()).unwrap()); + assert!(loaded.snapshot_memory().layers().iter().any(|layer| { + base.snapshot_memory() + .layers() + .iter() + .any(|base| Arc::ptr_eq(layer, base)) + })); + assert!( + loaded.snapshot_memory().layers().len() <= base.snapshot_memory().layers().len() + 1 + ); + sandbox.restore(loaded).unwrap(); + last_dir = Some(dir); + } + assert_eq!(sandbox.call::("GetStatic", ()).unwrap(), 3); + drop(sandbox); + let dir = last_dir.unwrap(); + let loaded = base.checked_load_overlay(dir.path(), tag.clone()).unwrap(); + let new_blob = loaded + .snapshot_memory() + .blobs() + .find(|blob| { + !base + .snapshot_memory() + .blobs() + .any(|base| Arc::ptr_eq(blob, base)) + }) + .unwrap(); + let path = dir + .path() + .join("blobs/sha256") + .join(new_blob.sha256.get().unwrap()); + drop(loaded); + let mut bytes = std::fs::read(&path).unwrap(); + bytes[0] ^= 1; + std::fs::write(path, bytes).unwrap(); + let error = base.checked_load_overlay(dir.path(), tag).err().unwrap(); + assert!(error.to_string().contains("digest mismatch"), "{error}"); +} + #[test] fn save_trusts_replaced_files_and_writes_new_destinations() { let snapshot = create_snapshot(); diff --git a/src/hyperlight_host/src/sandbox/snapshot/memory/backing.rs b/src/hyperlight_host/src/sandbox/snapshot/memory/backing.rs index 68be2c1bc..f9c632a3d 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/memory/backing.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/memory/backing.rs @@ -88,6 +88,10 @@ impl SnapshotMemoryBacking { } impl SnapshotMemoryBacking { + pub(crate) fn snapshot_memory(&self) -> &SnapshotMemory { + &self.memory + } + #[cfg(all(test, not(unshared_snapshot_mem)))] pub(crate) fn layers(&self) -> &[Arc] { self.memory.layers() diff --git a/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs index a41cb0daa..ab3e96548 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs @@ -38,6 +38,11 @@ pub(crate) const MAX_SNAPSHOT_LAYERS: usize = 30; /// Layer ranges never overlap. #[derive(Debug)] pub(crate) struct SnapshotMemory { + /// Identity of the whole snapshot, not any individual blob. Metadata-only + /// copies share this object and retain the same identity. + pub(super) id: uuid::Uuid, + /// Trusted whole-snapshot ancestor IDs, independent of retained layers. + pub(super) bases: Vec, /// Blobs with guest data, sorted by start GPA, which lookups binary /// search. layers: Box<[Arc]>, @@ -168,11 +173,21 @@ impl SnapshotMemory { } Ok(Self { + id: uuid::Uuid::new_v4(), + bases: Vec::new(), layers, page_tables, }) } + pub(super) fn record_base(&mut self, base: &Self) { + for id in base.bases.iter().copied().chain(std::iter::once(base.id)) { + if id != self.id && !self.bases.contains(&id) { + self.bases.push(id); + } + } + } + /// Builds a one-layer snapshot from `memory`, which holds guest data /// followed by `page_table_len` bytes of page tables. pub(crate) fn from_flat( diff --git a/src/hyperlight_host/src/sandbox/snapshot/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/mod.rs index 7fe5d814a..50e4ccb68 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/mod.rs @@ -982,7 +982,9 @@ impl Snapshot { layers.push(blob.clone()); } // Validates the layer limit. - let memory = Arc::new(SnapshotMemory::new(layers.into_boxed_slice(), blob)?); + let mut memory = SnapshotMemory::new(layers.into_boxed_slice(), blob)?; + memory.record_base(memory_view.snapshot().snapshot_memory()); + let memory = Arc::new(memory); Ok(Self { state: Arc::new(SnapshotState { From 3bee09c9d32d1c9d18588aa668911b6ba0212d1d Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Thu, 26 Nov 2026 13:00:23 +0000 Subject: [PATCH 3/9] Version snapshot provenance configs and retain v6 loading Emit config v7 with explicit loader dispatch and require its snapshot ID. Keep strict v6 loading without provenance, update schema and ABI tripwires, and cover legacy and mislabeled layouts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jorge Prendes --- CHANGELOG.md | 2 ++ docs/snapshot-oci-format.md | 2 +- docs/snapshot-versioning.md | 10 ++++-- .../src/sandbox/snapshot/file/config.rs | 10 ++++-- .../src/sandbox/snapshot/file/media_types.rs | 4 ++- .../src/sandbox/snapshot/file/mod.rs | 31 +++++++++++++++--- .../src/sandbox/snapshot/file_tests.rs | 32 +++++++++++++++++-- .../src/sandbox/snapshot/tripwires.rs | 2 +- 8 files changed, 79 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dd1923558..1dc9f7ca4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). * Add ARM64 Linux MSHV support by @cshung in https://github.com/hyperlight-dev/hyperlight/pull/1626 ### Changed +* Snapshot writers emit config v7 with provenance. Config v6 remains readable + without provenance; the guest ABI and memory-layer encoding are unchanged. * `Snapshot::load` retains declared memory-layer digests for ordinary saves instead of hashing the loaded bytes on first save. Incorrect declarations are preserved; use `checked_load` or `checked_save` for content consistency. diff --git a/docs/snapshot-oci-format.md b/docs/snapshot-oci-format.md index 604092527..9c2cdf991 100644 --- a/docs/snapshot-oci-format.md +++ b/docs/snapshot-oci-format.md @@ -50,7 +50,7 @@ Three blob kinds per tag: * **manifest** (`application/vnd.oci.image.manifest.v1+json`). Tiny JSON pointer record selected via `index.json`. References one config and the snapshot blobs by digest. -* **config** (`application/vnd.hyperlight.snapshot.config.v6+json`). The +* **config** (`application/vnd.hyperlight.snapshot.config.v7+json`). The snapshot descriptor: arch, hypervisor, CPU vendor, ABI version, resume address and captured registers, memory and transport layout, registered host functions, the start address, data length, and page-table diff --git a/docs/snapshot-versioning.md b/docs/snapshot-versioning.md index f82159e08..6f88f7c2d 100644 --- a/docs/snapshot-versioning.md +++ b/docs/snapshot-versioning.md @@ -23,8 +23,8 @@ A snapshot carries three independently evolvable version markers: `MT_SNAPSHOT_CURRENT`. This is the on-wire format of the snapshot blob: framing, section ordering, alignment, dirty/zero-page elision, anything about how the bytes are packed inside the OCI layer. -* **Config schema**, `MT_CONFIG_V6` - (`application/vnd.hyperlight.snapshot.config.v6+json`), aliased as +* **Config schema**, `MT_CONFIG_V7` + (`application/vnd.hyperlight.snapshot.config.v7+json`), aliased as `MT_CONFIG_CURRENT`. This is the JSON shape of the config blob: field names, types, required vs optional, the descriptors the loader needs in order to reconstruct the sandbox (memory sizes, buffer @@ -33,6 +33,9 @@ A snapshot carries three independently evolvable version markers: bumps this constant. Version 4 describes snapshot blobs, the blob with the page tables, and transport geometry. Version 5 drops the heap size. Version 6 contains code and scratch geometry without init-data fields. + Version 7 adds a required snapshot ID and optional inherited base IDs. + Version 6 remains readable without provenance; existing v6 readers reject + v7 by media type rather than interpreting a changed v6 schema. Config v1 to v5 are incompatible with the current ABI. ABI 6 requires checkpoint readiness after guest initialization and permits @@ -81,6 +84,9 @@ Writers omit an empty map, and readers treat a missing field as empty. Record compatibility paths here when a future hard snapshot break can remove them. +Config v6 loading supplies no base provenance and assigns an in-memory snapshot +ID. The next hard snapshot break may remove this compatibility path. + ## Enforcement The format is large and easy to change by accident. Three mechanisms diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/config.rs b/src/hyperlight_host/src/sandbox/snapshot/file/config.rs index ca632c3b8..8de27fe70 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/config.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/config.rs @@ -163,7 +163,7 @@ impl CpuVendor { /// Top-level Hyperlight snapshot config JSON. Lives at /// `blobs/sha256/` with media type -/// `application/vnd.hyperlight.snapshot.config.v6+json`. +/// `application/vnd.hyperlight.snapshot.config.v7+json`, with defaults for v6. /// /// In OCI terms this is the "image config" blob that the manifest's /// `config` descriptor points to. It describes the accompanying @@ -1130,7 +1130,9 @@ mod schema_pin { "return_type": "void" } ], - "snapshot_generation": 42 + "snapshot_generation": 42, + "snapshot_id": "00000000-0000-0000-0000-000000000001", + "bases": ["00000000-0000-0000-0000-000000000002"] }"#; #[cfg(target_arch = "aarch64")] @@ -1180,7 +1182,9 @@ mod schema_pin { "return_type": "void" } ], - "snapshot_generation": 42 + "snapshot_generation": 42, + "snapshot_id": "00000000-0000-0000-0000-000000000001", + "bases": ["00000000-0000-0000-0000-000000000002"] }"#; const PINNED_ARCH: &str = r#"[ diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs b/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs index a28d4ff33..b9f4f84e7 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs @@ -16,7 +16,9 @@ pub(in crate::sandbox::snapshot) const MT_CONFIG_V5: &str = "application/vnd.hyperlight.snapshot.config.v5+json"; pub(in crate::sandbox::snapshot) const MT_CONFIG_V6: &str = "application/vnd.hyperlight.snapshot.config.v6+json"; -pub(in crate::sandbox::snapshot) const MT_CONFIG_CURRENT: &str = MT_CONFIG_V6; +pub(in crate::sandbox::snapshot) const MT_CONFIG_V7: &str = + "application/vnd.hyperlight.snapshot.config.v7+json"; +pub(in crate::sandbox::snapshot) const MT_CONFIG_CURRENT: &str = MT_CONFIG_V7; pub(in crate::sandbox::snapshot) const MT_SNAPSHOT_V2: &str = "application/vnd.hyperlight.snapshot.memory.v2"; pub(in crate::sandbox::snapshot) const MT_SNAPSHOT_CURRENT: &str = MT_SNAPSHOT_V2; diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs index 6ceadb4d8..882bf5cfd 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs @@ -29,7 +29,7 @@ use self::media_types::{ }; pub(super) use self::media_types::{ MT_CONFIG_CURRENT, MT_CONFIG_V1, MT_CONFIG_V2, MT_CONFIG_V3, MT_CONFIG_V4, MT_CONFIG_V5, - MT_CONFIG_V6, MT_SNAPSHOT_CURRENT, MT_SNAPSHOT_V2, SNAPSHOT_ABI_VERSION, + MT_CONFIG_V6, MT_CONFIG_V7, MT_SNAPSHOT_CURRENT, MT_SNAPSHOT_V2, SNAPSHOT_ABI_VERSION, }; use self::reference::{OciDigest, OciReference, OciTag}; use super::memory::{MAX_SNAPSHOT_LAYERS, host_page_size}; @@ -230,6 +230,28 @@ fn load_config( )?; let cfg: OciSnapshotConfig = serde_json::from_slice(&cfg_bytes) .map_err(|e| crate::new_error!("failed to parse Hyperlight config JSON: {}", e))?; + match cfg_desc.media_type().to_string().as_str() { + MT_CONFIG_V6 => { + let value: serde_json::Value = serde_json::from_slice(&cfg_bytes) + .map_err(|e| crate::new_error!("failed to parse legacy config JSON: {}", e))?; + if value.get("snapshot_id").is_some() || value.get("bases").is_some() { + return Err(crate::new_error!( + "config v6 cannot contain snapshot provenance" + )); + } + } + MT_CONFIG_V7 => { + if cfg.snapshot_id.is_none() { + return Err(crate::new_error!("config v7 requires a snapshot ID")); + } + } + other => { + return Err(crate::new_error!( + "unsupported snapshot config media type {:?}", + other + )); + } + } cfg.validate_for_load()?; Ok(cfg) } @@ -916,7 +938,7 @@ impl Snapshot { // Loader dispatch on config media type. let cfg_media = cfg_desc.media_type().to_string(); match cfg_media.as_str() { - MT_CONFIG_V6 => {} + MT_CONFIG_V6 | MT_CONFIG_V7 => {} MT_CONFIG_V1 | MT_CONFIG_V2 | MT_CONFIG_V3 | MT_CONFIG_V4 | MT_CONFIG_V5 => { return Err(crate::new_error!( "snapshot config media type {:?} is incompatible with snapshot ABI {}", @@ -926,9 +948,10 @@ impl Snapshot { } other => { return Err(crate::new_error!( - "unexpected config media type {:?} (supported: {:?})", + "unexpected config media type {:?} (supported: {:?}, {:?})", other, - MT_CONFIG_V6 + MT_CONFIG_V6, + MT_CONFIG_V7 )); } } diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index eeb10d7d3..3b81c66d8 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -498,14 +498,14 @@ fn layered_writer_preserves_blobs_and_transport_geometry() { let layers = manifest["layers"].as_array().unwrap(); assert_eq!( manifest["config"]["mediaType"], - "application/vnd.hyperlight.snapshot.config.v6+json" + "application/vnd.hyperlight.snapshot.config.v7+json" ); // `artifactType` mirrors `config.mediaType` so registries that surface // the distribution-spec referrers API report a useful type, and tooling // that falls back to `config.mediaType` sees the same value. assert_eq!( manifest["artifactType"], - "application/vnd.hyperlight.snapshot.config.v6+json" + "application/vnd.hyperlight.snapshot.config.v7+json" ); assert_eq!(config["abi_version"], 12); let blobs = snapshot.snapshot_memory().blobs().collect::>(); @@ -810,6 +810,28 @@ fn overlay_preserves_saved_base_identity_through_uncompacted_captures() { } } +#[test] +fn config_v6_rejects_provenance_fields() { + let snapshot = create_snapshot(); + let dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + snapshot.save(dir.path(), &tag).unwrap(); + rewrite_manifest(dir.path(), |manifest| { + manifest["config"]["mediaType"] = super::file::MT_CONFIG_V6.into(); + manifest["artifactType"] = super::file::MT_CONFIG_V6.into(); + }); + for checked in [false, true] { + let error = if checked { + Snapshot::checked_load(dir.path(), tag.clone()) + } else { + Snapshot::load(dir.path(), tag.clone()) + } + .err() + .unwrap(); + assert!(error.to_string().contains("v6 cannot contain"), "{error}"); + } +} + #[test] fn malformed_snapshot_provenance_is_rejected_and_legacy_layouts_load() { let snapshot = create_snapshot(); @@ -843,6 +865,12 @@ fn malformed_snapshot_provenance_is_rejected_and_legacy_layouts_load() { config.as_object_mut().unwrap().remove("snapshot_id"); config.as_object_mut().unwrap().remove("bases"); }); + assert!(Snapshot::load(dir.path(), tag.clone()).is_err()); + rewrite_manifest(dir.path(), |manifest| { + manifest["config"]["mediaType"] = super::file::MT_CONFIG_V6.into(); + manifest["artifactType"] = super::file::MT_CONFIG_V6.into(); + }); + Snapshot::load(dir.path(), tag.clone()).unwrap(); let legacy = Snapshot::checked_load(dir.path(), tag.clone()).unwrap(); assert!(snapshot.load_overlay(dir.path(), tag.clone()).is_err()); legacy.save(dir.path(), &tag).unwrap(); diff --git a/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs b/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs index fef1018c7..db5d05650 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs @@ -19,7 +19,7 @@ use super::file::{ }; const EXPECTED_ABI_VERSION: u32 = 12; -const EXPECTED_MT_CONFIG: &str = "application/vnd.hyperlight.snapshot.config.v6+json"; +const EXPECTED_MT_CONFIG: &str = "application/vnd.hyperlight.snapshot.config.v7+json"; const EXPECTED_MT_SNAPSHOT: &str = "application/vnd.hyperlight.snapshot.memory.v2"; const EXPECTED_OCI_LAYOUT_VERSION: &str = "1.0.0"; From 0e424572a580b394ad210e90dda8771db97416a8 Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Thu, 26 Nov 2026 13:02:40 +0000 Subject: [PATCH 4/9] Reset compaction ancestry and inherit bases in linear time Clear base provenance when compacting without a base. With a base, replace target ancestry with that base inherited list and ID. Copy the validated ordered list directly instead of quadratic membership scans, and cover config-limit recovery and repeated checkpoint cycles. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jorge Prendes --- CHANGELOG.md | 3 ++ docs/snapshot-oci-format.md | 14 ++++-- .../src/sandbox/snapshot/compact.rs | 10 ++-- .../src/sandbox/snapshot/file/mod.rs | 2 + .../src/sandbox/snapshot/file_tests.rs | 50 ++++++++++++++++++- .../src/sandbox/snapshot/memory/mod.rs | 10 ++-- .../src/sandbox/snapshot/mod.rs | 2 +- 7 files changed, 74 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dc9f7ca4..ddc1e5941 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed * Snapshot writers emit config v7 with provenance. Config v6 remains readable without provenance; the guest ABI and memory-layer encoding are unchanged. +* Compaction replaces ancestry with the specified base's inherited list and ID, + or clears it without a base. This resets accumulated checkpoint history; + provenance inheritance copies the validated list in linear time. * `Snapshot::load` retains declared memory-layer digests for ordinary saves instead of hashing the loaded bytes on first save. Incorrect declarations are preserved; use `checked_load` or `checked_save` for content consistency. diff --git a/docs/snapshot-oci-format.md b/docs/snapshot-oci-format.md index 9c2cdf991..617c9a9ec 100644 --- a/docs/snapshot-oci-format.md +++ b/docs/snapshot-oci-format.md @@ -109,14 +109,20 @@ snapshot as a base; a matching memory layer alone is insufficient. Each new VM snapshot has a stable UUID stored as `snapshot_id` in the OCI config, with ancestor IDs in `bases`. Metadata-only copies retain the VM snapshot's ID. Restore/capture inherits the restored snapshot and its bases, including without -compaction. `compact(Some(base))` also records the specified base and its bases; -`compact(None)` preserves ancestry. Neither operation retains unused layers -merely to establish provenance. +compaction. `compact(Some(base))` replaces the target's history with the specified +base's inherited bases plus the base itself; `compact(None)` clears all bases. +Neither operation retains unused layers merely to establish provenance. Provenance is carried by the whole `SnapshotMemory` object, not individual blobs, so capture inherits it directly from the existing memory backing. +Uncompacted captures can grow ancestry even without adding memory layers. +Periodically compact without a base to reset it, or compact against a fixed +base with a short ancestry list to retain that base without accumulating the +target's checkpoint history. Both operations can recover save capacity after +ancestry exceeds the config JSON size limit. + These IDs are trusted declarations, not content digests or cryptographic proofs -of ancestry, even with checked loading. Legacy configs without provenance still +of ancestry, even with checked loading. Legacy v6 configs without provenance still load standalone, receiving a new in-memory ID. Save that base to persist its ID before relying on independently loaded copies for overlay. A layout without a matching base declaration cannot be overlaid. diff --git a/src/hyperlight_host/src/sandbox/snapshot/compact.rs b/src/hyperlight_host/src/sandbox/snapshot/compact.rs index 7657d9f6d..4fd5cba60 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/compact.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/compact.rs @@ -18,9 +18,10 @@ impl Snapshot { /// layers and unreferenced pages in merged layers are discarded, except /// for minimal padding required by the snapshot format. Retained base /// layers are kept whole. - /// The result records this snapshot and the specified base as ancestors, - /// including their inherited bases, for [`Snapshot::load_overlay`]. Provenance - /// does not require retaining any otherwise unused layer. + /// With a base, the result inherits that base's declared ancestors and records + /// the base itself for [`Snapshot::load_overlay`], discarding this snapshot's + /// previous ancestry. Without a base, the result clears all base provenance. + /// Provenance does not require retaining any otherwise unused layer. /// /// Registers, metadata, transport state, generation, and page-table roots /// are preserved. The result uses the existing snapshot file format. @@ -162,9 +163,8 @@ impl Snapshot { layers.push(blob.clone()); } let mut memory = SnapshotMemory::new(layers.into_boxed_slice(), blob)?; - memory.record_base(self.snapshot_memory()); if let Some(base) = base { - memory.record_base(base.snapshot_memory()); + memory.inherit_base(base.snapshot_memory()); } Ok(Arc::new(Self { state: Arc::new(SnapshotState { diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs index 882bf5cfd..c30e1aad5 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs @@ -883,6 +883,8 @@ impl Snapshot { /// The persisted provenance must declare `self` as a base. Compaction with /// an explicit base and capture after restoration record this relationship, /// including inherited bases, without retaining unused memory layers. + /// Compaction replaces provenance with the chosen base's inherited list + /// and ID; compaction without a base clears provenance entirely. /// /// Matching layers are shared by digest and geometry without opening their /// files, which may be omitted from the layout. A base with an incompatible diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index 3b81c66d8..3781f7169 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -37,7 +37,7 @@ fn snapshot_with_shared_blobs(snapshot: &Snapshot, base: Option<&Snapshot>) -> S ) .unwrap(); if let Some(base) = base { - memory.record_base(base.snapshot_memory()); + memory.inherit_base(base.snapshot_memory()); } Snapshot { state: Arc::new(super::SnapshotState { @@ -207,6 +207,48 @@ fn compact_sparse_memory_round_trips_with_both_loaders() { } } +#[test] +fn compaction_resets_ancestry_and_can_recover_config_save_capacity() { + let root = create_snapshot(); + let selected = snapshot_with_shared_blobs(&root, Some(&root)); + let mut bloated = snapshot_with_shared_blobs(&root, None); + Arc::get_mut(&mut Arc::get_mut(&mut bloated.state).unwrap().memory) + .unwrap() + .bases = (1..=30_000).map(uuid::Uuid::from_u128).collect(); + let directory = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + for checked in [false, true] { + let error = if checked { + bloated.checked_save(directory.path(), &tag) + } else { + bloated.save(directory.path(), &tag) + } + .unwrap_err(); + assert!(error.to_string().contains("config blob"), "{error}"); + assert!( + error.to_string().contains("1048576 byte maximum"), + "{error}" + ); + } + + let cleared = bloated.compact(None).unwrap(); + assert!(cleared.snapshot_memory().bases.is_empty()); + cleared.save(directory.path(), &tag).unwrap(); + cleared.checked_save(directory.path(), &tag).unwrap(); + assert!(root.load_overlay(directory.path(), tag.clone()).is_err()); + + let anchored = bloated.compact(Some(&selected)).unwrap(); + let mut expected = selected.snapshot_memory().bases.clone(); + expected.push(selected.snapshot_memory().id); + assert_eq!(anchored.snapshot_memory().bases, expected); + anchored.save(directory.path(), &tag).unwrap(); + root.load_overlay(directory.path(), tag.clone()).unwrap(); + selected + .checked_load_overlay(directory.path(), tag.clone()) + .unwrap(); + assert!(bloated.load_overlay(directory.path(), tag).is_err()); +} + #[test] fn compact_round_trip_preserves_base_blobs_and_execution_state() { let mut sandbox = create_test_sandbox(); @@ -227,6 +269,12 @@ fn compact_round_trip_preserves_base_blobs_and_execution_state() { .with_metadata("compact-test", &value) .unwrap(); let compacted = captured.compact(preserve.then_some(&loaded_base)).unwrap(); + let mut expected_bases = Vec::new(); + if preserve { + expected_bases.clone_from(&loaded_base.snapshot_memory().bases); + expected_bases.push(loaded_base.snapshot_memory().id); + } + assert_eq!(compacted.snapshot_memory().bases, expected_bases); let limit = if preserve { base.snapshot_memory().layers().len() + 1 } else { diff --git a/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs index ab3e96548..13824ac6b 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs @@ -180,12 +180,10 @@ impl SnapshotMemory { }) } - pub(super) fn record_base(&mut self, base: &Self) { - for id in base.bases.iter().copied().chain(std::iter::once(base.id)) { - if id != self.id && !self.bases.contains(&id) { - self.bases.push(id); - } - } + pub(super) fn inherit_base(&mut self, base: &Self) { + // Validated bases are unique and exclude the base's own ID. + self.bases.clone_from(&base.bases); + self.bases.push(base.id); } /// Builds a one-layer snapshot from `memory`, which holds guest data diff --git a/src/hyperlight_host/src/sandbox/snapshot/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/mod.rs index 50e4ccb68..33696bb72 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/mod.rs @@ -983,7 +983,7 @@ impl Snapshot { } // Validates the layer limit. let mut memory = SnapshotMemory::new(layers.into_boxed_slice(), blob)?; - memory.record_base(memory_view.snapshot().snapshot_memory()); + memory.inherit_base(memory_view.snapshot().snapshot_memory()); let memory = Arc::new(memory); Ok(Self { From 1a3ac97bfe443359897138195189c6e1a1b98115 Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Thu, 26 Nov 2026 13:59:14 +0000 Subject: [PATCH 5/9] Release shared snapshot mappings before truncating test blobs Drop the derived snapshot as well as the trusted base before shortening their shared blob. Windows rejects truncation while either snapshot retains the mapped section. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jorge Prendes --- src/hyperlight_host/src/sandbox/snapshot/file_tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index 3781f7169..d06b308b5 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -1009,6 +1009,7 @@ fn load_accepts_wrong_content_digest_but_rejects_wrong_size() { assert!(Snapshot::checked_load(output.path(), tag.clone()).is_err()); trusted.checked_save(output.path(), &tag).unwrap(); Snapshot::checked_load(output.path(), tag.clone()).unwrap(); + drop(derived); drop(trusted); bytes.pop(); std::fs::write(path, bytes).unwrap(); From f76111043fce2e0acbf391bf42037aab72c5f307 Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Fri, 27 Nov 2026 12:48:30 +0000 Subject: [PATCH 6/9] Enforce snapshot provenance and fail-closed blob verification Require declared ancestors for base-preserving compaction. Encapsulate digest trust in BlobHash with terminal atomic invalidation and byte/file verification. Reject inconsistent existing memory blobs without repair, and document and test the updated policies. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jorge Prendes --- CHANGELOG.md | 9 +- docs/snapshot-oci-format.md | 35 ++- .../src/sandbox/snapshot/compact.rs | 59 +++- .../src/sandbox/snapshot/file/config.rs | 5 + .../src/sandbox/snapshot/file/digest.rs | 142 ++++++++- .../src/sandbox/snapshot/file/fsutil.rs | 87 ++++-- .../src/sandbox/snapshot/file/mod.rs | 82 +++-- .../src/sandbox/snapshot/file_tests.rs | 290 ++++++++++++++---- .../src/sandbox/snapshot/memory/mod.rs | 10 +- 9 files changed, 583 insertions(+), 136 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ddc1e5941..e6a26c775 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed * Snapshot writers emit config v7 with provenance. Config v6 remains readable without provenance; the guest ABI and memory-layer encoding are unchanged. -* Compaction replaces ancestry with the specified base's inherited list and ID, +* Snapshot saving rejects detected memory-layer digest inconsistencies rather + than repairing them. Checked saves reject corrupted existing blobs; both + save modes reject wrong-length blobs and nonfiles without replacing them. + A detected layer hash mismatch also prevents subsequent shared-layer reuse. +* Compaction requires a supplied base to be declared in the target's provenance. + It replaces ancestry with the specified base's inherited list and ID, or clears it without a base. This resets accumulated checkpoint history; provenance inheritance copies the validated list in linear time. * `Snapshot::load` retains declared memory-layer digests for ordinary saves @@ -29,7 +34,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). regular blobs by their content-addressed filenames without verifying their contents. Callers must keep blobs immutable. Use the new `Snapshot::checked_save` to recompute hashes, verify existing blobs, and - atomically repair mismatched contents. + reject mismatched contents without modifying existing memory blobs or the index. * **Breaking:** Snapshots use ABI 12. Guests must be rebuilt and existing snapshots regenerated. Capture and restore provide full H2G bootstrap capacity before guest entry, independent of retained buffers. Snapshot diff --git a/docs/snapshot-oci-format.md b/docs/snapshot-oci-format.md index 617c9a9ec..4c65a8cba 100644 --- a/docs/snapshot-oci-format.md +++ b/docs/snapshot-oci-format.md @@ -76,8 +76,9 @@ across tags are stored once. `Snapshot::save` caches each shared memory layer's SHA-256. Existing regular blob files with the expected length are trusted by their content-addressed filenames without reading or hashing their contents, even at a new destination. -There is no backing-file cache. Missing blobs are written atomically; symlinks -and wrong-length files are replaced. +There is no backing-file cache. Missing blobs are written atomically without +overwriting a concurrently published blob. Symlinks, other nonfiles, and +wrong-length files are rejected in both save modes. `Snapshot::checked_load` seeds the verified digest cache; ordinary `load` retains declared digests separately for reuse on save without hashing memory. Metadata blobs retain their normal write path. @@ -94,8 +95,22 @@ hashing of immutable base memory. `Snapshot::load` trusts declared memory digests without reading memory to verify them. Ordinary saves preserve those declarations, and `base.load_overlay(path, reference)` resolves matching layers -by digest and geometry. Declared hashes are stored separately from computed or -verified hashes: checked base loading never reuses a mere declaration, and +by digest and geometry. `BlobHash` stores one immutable digest with an atomic +status. `get()` reconstructs `Unknown`, `Declared(&str)`, or `Verified(&str)`; +permanent invalidation is returned as an error. +`HashState::as_digest()` returns an owned digest for declared or verified states, +or `None` for unknown. +Constructors are `unknown()`, +`declared(digest)`, and `verified(digest)`; the caller must have computed or verified +the digest against the blob's bytes before using `verified`. `Default` initializes +unknown. `verify_bytes(bytes)` +and `verify_file(file)` always hash the supplied bytes or open file before +checking and updating the state. Recording a computed digest is private. +Computing a hash that differs +from the declaration or a previous computation is an error, not a correction. +Once such a mismatch is detected, all later hash access through that shared +layer fails, including ordinary saves and overlay matching. Checked base loading +never reuses a mere declaration, and checked saving still hashes every layer. This changes prior ordinary `load`-then-`save` behavior: it preserves declared digests instead of computing them from actual bytes, including when the declared digest is incorrect. @@ -109,8 +124,11 @@ snapshot as a base; a matching memory layer alone is insufficient. Each new VM snapshot has a stable UUID stored as `snapshot_id` in the OCI config, with ancestor IDs in `bases`. Metadata-only copies retain the VM snapshot's ID. Restore/capture inherits the restored snapshot and its bases, including without -compaction. `compact(Some(base))` replaces the target's history with the specified +compaction. `compact(Some(base))` requires that base's ID to already appear in +the target's `bases`; matching memory alone is insufficient, and the target +cannot use itself as a base. It replaces the target's history with the specified base's inherited bases plus the base itself; `compact(None)` clears all bases. +Once cleared, compaction cannot reintroduce a discarded base. Neither operation retains unused layers merely to establish provenance. Provenance is carried by the whole `SnapshotMemory` object, not individual blobs, so capture inherits it directly from the existing memory backing. @@ -135,8 +153,11 @@ persisted contents explicitly. `Snapshot::checked_save` takes the fully verifying path: it recomputes all memory-layer digests without using the cache and hashes existing memory blob -files before reusing them. Mismatched contents are atomically replaced from -the snapshot's memory. It otherwise has the same layout and tag semantics as +files before reusing them. Digest or existing-content mismatches are errors; +neither copy is presumed trustworthy. Existing memory blobs and the published +index remain unchanged on these errors, though earlier newly written blobs +may remain unreferenced. Recovery requires a trusted source or a fresh capture, +not automatic repair. It otherwise has the same layout and tag semantics as `save`. This is not protection against concurrent modification of loaded backing files, which must remain immutable while snapshots use them. diff --git a/src/hyperlight_host/src/sandbox/snapshot/compact.rs b/src/hyperlight_host/src/sandbox/snapshot/compact.rs index 4fd5cba60..b07cc8b63 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/compact.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/compact.rs @@ -18,6 +18,7 @@ impl Snapshot { /// layers and unreferenced pages in merged layers are discarded, except /// for minimal padding required by the snapshot format. Retained base /// layers are kept whole. + /// A supplied base must already appear in this snapshot's provenance. /// With a base, the result inherits that base's declared ancestors and records /// the base itself for [`Snapshot::load_overlay`], discarding this snapshot's /// previous ancestry. Without a base, the result clears all base provenance. @@ -28,7 +29,8 @@ impl Snapshot { /// /// # Errors /// - /// Returns an error if the base has a different memory layout, allocation + /// Returns an error if the base is not declared in this snapshot's provenance, + /// the base has a different memory layout, allocation /// fails, or the compacted memory cannot fit within the address-space or /// layer limits. #[instrument(err(Debug), skip_all, parent = Span::current(), level = "Trace")] @@ -40,6 +42,13 @@ impl Snapshot { "compaction base has an incompatible memory layout" )); } + if let Some(base) = base + && !self.state.memory.bases.contains(&base.state.memory.id) + { + return Err(crate::new_error!( + "snapshot does not declare the supplied snapshot as a compaction base" + )); + } let memory = &self.state.memory; let preserve: Vec = memory @@ -263,12 +272,49 @@ mod tests { } } + fn descendant(base: &Snapshot) -> Snapshot { + let mut memory = SnapshotMemory::new( + base.state.memory.layers().to_vec().into_boxed_slice(), + base.state.memory.page_table_blob().clone(), + ) + .unwrap(); + memory.inherit_base(base.snapshot_memory()); + Snapshot { + state: Arc::new(SnapshotState { + memory: Arc::new(memory), + ..(*base.state).clone() + }), + metadata: base.metadata.clone(), + } + } + + #[test] + fn compact_requires_declared_base_even_with_identical_memory() { + let base = layered_snapshot(); + let unrelated = layered_snapshot(); + for target in [&unrelated, &base] { + let error = target.compact(Some(&base)).err().unwrap(); + assert!(error.to_string().contains("does not declare"), "{error}"); + } + unrelated.compact(None).unwrap(); + + let child = descendant(&base); + let grandchild = descendant(&child); + grandchild.compact(Some(&base)).unwrap(); + grandchild.compact(Some(&child)).unwrap(); + + let cleared = grandchild.compact(None).unwrap(); + let error = cleared.compact(Some(&base)).err().unwrap(); + assert!(error.to_string().contains("does not declare"), "{error}"); + } + #[test] fn compact_packs_live_pages_and_preserves_aliases_and_permissions() { - let original = layered_snapshot(); + let base = layered_snapshot(); + let original = descendant(&base); let start = SandboxMemoryLayout::BASE_ADDRESS as u64; for preserve in [false, true] { - let compacted = original.compact(preserve.then_some(&original)).unwrap(); + let compacted = original.compact(preserve.then_some(&base)).unwrap(); let memory = &compacted.state.memory; assert_eq!(memory.layers().len(), if preserve { 2 } else { 1 }); assert_eq!( @@ -323,8 +369,10 @@ mod tests { .unwrap(), ..(*original.state).clone() }); + let base = original; + let original = descendant(&base); for preserve in [false, true] { - let compacted = original.compact(preserve.then_some(&original)).unwrap(); + let compacted = original.compact(preserve.then_some(&base)).unwrap(); let memory = &compacted.state.memory; assert_eq!(memory.layers().len(), if preserve { 3 } else { 1 }); assert!(memory.gpa_span_len() >= 10 * alignment); @@ -399,6 +447,9 @@ mod tests { ), ..(*current.state).clone() }); + Arc::get_mut(&mut Arc::get_mut(&mut current.state).unwrap().memory) + .unwrap() + .inherit_base(base.snapshot_memory()); let compacted = current.compact(Some(&base)).unwrap(); let layers = compacted.state.memory.layers(); assert_eq!(layers.len(), 2); diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/config.rs b/src/hyperlight_host/src/sandbox/snapshot/file/config.rs index 8de27fe70..289e2d07a 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/config.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/config.rs @@ -213,8 +213,13 @@ pub(super) struct OciSnapshotConfig { /// `SCRATCH_TOP_SNAPSHOT_GENERATION_OFFSET` is continuous across /// save/load. pub(super) snapshot_generation: u64, + /// Persisted UUID of the whole snapshot, required in v7 and absent in v6. + /// Overlay loading uses this identity rather than matching memory blobs alone. #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) snapshot_id: Option, + /// Trusted ancestor snapshot UUIDs eligible as overlay bases. + /// Capture inherits the source history; compaction replaces it with the + /// chosen base's history and ID, or clears it when no base is chosen. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(super) bases: Vec, /// Application-owned metadata keyed by namespace. diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/digest.rs b/src/hyperlight_host/src/sandbox/snapshot/file/digest.rs index 80ca6d66d..13fb11441 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/digest.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/digest.rs @@ -2,6 +2,8 @@ // Copyright 2025 The Hyperlight Authors. use std::io::{Read, Seek, SeekFrom}; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU32, Ordering}; use oci_spec::image::Digest; use sha2::{Digest as _, Sha256}; @@ -36,6 +38,122 @@ impl Digest256 { } } +/// A blob's declared and computed digests must agree whenever both are known. +/// +/// The digest is written once; only its trust state changes. A mismatch is +/// terminal for all owners sharing this hash: neither the stored digest nor +/// the current bytes are assumed authoritative. +#[derive(Debug)] +pub(crate) struct BlobHash { + hash: OnceLock, + state: AtomicU32, +} + +// States only advance; the failure sentinel must exceed every valid state. +const INVALID_HASH_STATE: u32 = u32::MAX; +const UNKNOWN_HASH_STATE: u32 = 0; +const DECLARED_HASH_STATE: u32 = 1; +const VERIFIED_HASH_STATE: u32 = 2; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum HashState<'a> { + Unknown, + Declared(&'a str), + Verified(&'a str), +} + +impl HashState<'_> { + pub(crate) fn as_digest(&self) -> Option { + match *self { + Self::Unknown => None, + Self::Declared(digest) | Self::Verified(digest) => Some(digest.to_owned()), + } + } +} + +impl Default for BlobHash { + fn default() -> Self { + Self::unknown() + } +} + +impl BlobHash { + fn decode(&self, state: u32) -> crate::Result> { + match state { + UNKNOWN_HASH_STATE => Ok(HashState::Unknown), + DECLARED_HASH_STATE => Ok(HashState::Declared( + self.hash.get().expect("declared hash must be initialized"), + )), + VERIFIED_HASH_STATE => Ok(HashState::Verified( + self.hash.get().expect("verified hash must be initialized"), + )), + INVALID_HASH_STATE => Err(crate::new_error!( + "snapshot blob digest mismatch: hash is invalid" + )), + _ => unreachable!("invalid internal blob hash state"), + } + } + + pub(crate) fn unknown() -> Self { + Self { + hash: OnceLock::new(), + state: AtomicU32::new(UNKNOWN_HASH_STATE), + } + } + + pub(crate) fn declared(digest: String) -> Self { + Self { + state: AtomicU32::new(DECLARED_HASH_STATE), + ..Self::verified(digest) + } + } + + /// The caller must have computed or verified this digest against the blob's bytes. + pub(crate) fn verified(digest: String) -> Self { + Self { + hash: OnceLock::from(digest), + state: AtomicU32::new(VERIFIED_HASH_STATE), + } + } + + pub(crate) fn get(&self) -> crate::Result> { + // This is a point-in-time state, not a lease against later invalidation + // or a fresh check of the blob's bytes. + self.decode(self.state.load(Ordering::Acquire)) + } + + /// Always hash the bytes and validate consistency with any previously known digest. + pub(crate) fn verify_bytes(&self, bytes: &[u8]) -> crate::Result> { + self.record_computed(Digest256::from_bytes(bytes).hex) + } + + /// Verify the same open file that backs the blob, restoring its position to the start. + pub(crate) fn verify_file(&self, file: &mut std::fs::File) -> crate::Result> { + self.record_computed(hash_blob_file("snapshot", file)?.hex) + } + + /// Record a computed or verified digest, rejecting inconsistent immutable bytes. + fn record_computed(&self, digest: String) -> crate::Result> { + self.get()?; + // For an unknown hash, concurrent verifiers agree on the first stored + // digest or invalidate it; they never replace one another's digest. + let expected = self.hash.get_or_init(|| digest.clone()); + if expected != &digest { + self.state.fetch_max(INVALID_HASH_STATE, Ordering::AcqRel); + return Err(crate::new_error!( + "snapshot blob digest mismatch: expected sha256:{}, computed sha256:{}", + expected, + digest + )); + } + // Publish the initialized digest without reviving an invalid hash. + // Inspect the previous state to catch invalidation racing with get(). + let previous = self.state.fetch_max(VERIFIED_HASH_STATE, Ordering::AcqRel); + self.decode(previous)?; + Ok(HashState::Verified(expected)) + } +} + /// Build an `oci_spec::image::Digest` from a [`Digest256`]. pub(super) fn oci_digest(d: &Digest256) -> crate::Result { Digest::try_from(format!("sha256:{}", d.hex)) @@ -83,6 +201,19 @@ pub(super) fn verify_blob_file( file: &mut std::fs::File, expected_hex: &str, ) -> crate::Result<()> { + let actual = hash_blob_file(label, file)?; + if actual.hex != expected_hex { + return Err(crate::new_error!( + "{} blob digest mismatch: descriptor declares sha256:{}, file hashes to sha256:{}", + label, + expected_hex, + actual.hex + )); + } + Ok(()) +} + +fn hash_blob_file(label: &str, file: &mut std::fs::File) -> crate::Result { file.seek(SeekFrom::Start(0)) .map_err(|e| crate::new_error!("failed to seek {} blob: {}", label, e))?; let mut hasher = Sha256::new(); @@ -101,14 +232,5 @@ pub(super) fn verify_blob_file( file.seek(SeekFrom::Start(0)) .map_err(|e| crate::new_error!("failed to rewind {} blob: {}", label, e))?; let arr: [u8; 32] = hasher.finalize().into(); - let actual = Digest256::from_digest_array(arr); - if actual.hex != expected_hex { - return Err(crate::new_error!( - "{} blob digest mismatch: descriptor declares sha256:{}, file hashes to sha256:{}", - label, - expected_hex, - actual.hex - )); - } - Ok(()) + Ok(Digest256::from_digest_array(arr)) } diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/fsutil.rs b/src/hyperlight_host/src/sandbox/snapshot/file/fsutil.rs index 59f7f38d4..232838a29 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/fsutil.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/fsutil.rs @@ -40,7 +40,8 @@ pub(super) fn put_blob(blobs_dir: &Path, digest: &Digest256, bytes: &[u8]) -> cr /// existing regular file at `blobs_dir/` if it has the expected /// length. Unless `verify_existing` is set, the content-addressed /// filename is trusted without reading the file. With verification, -/// mismatched contents are replaced. Callers must keep published blobs +/// mismatched contents are rejected. Existing nonfiles or wrong-length +/// files are rejected in either mode. Callers must keep published blobs /// immutable while snapshots use them. pub(super) fn put_blob_if_absent( blobs_dir: &Path, @@ -49,34 +50,70 @@ pub(super) fn put_blob_if_absent( verify_existing: bool, ) -> crate::Result<()> { let target = blobs_dir.join(&digest.hex); - match std::fs::symlink_metadata(&target) { - Ok(meta) if meta.is_file() && meta.len() == bytes.len() as u64 => { - if !verify_existing { - return Ok(()); - } - let mut file = open_no_follow(&target)?; - match verify_blob_file("existing snapshot", &mut file, &digest.hex) { - Ok(()) => return Ok(()), - Err(error) => { - tracing::warn!( - ?target, - %error, - "Replacing snapshot blob after failed content verification" - ); - } + if check_existing_blob(&target, digest, bytes.len(), verify_existing)? { + return Ok(()); + } + let mut tmp = NamedTempFile::new_in(blobs_dir) + .map_err(|e| crate::new_error!("failed to create snapshot blob temporary file: {}", e))?; + tmp.write_all(bytes) + .map_err(|e| crate::new_error!("failed to write snapshot blob {:?}: {}", target, e))?; + // Another writer may publish after our absence check. Never overwrite its + // blob; validate and reuse the winner under the same policy instead. + match tmp.persist_noclobber(&target) { + Ok(_) => Ok(()), + Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => { + if check_existing_blob(&target, digest, bytes.len(), verify_existing)? { + Ok(()) + } else { + Err(crate::new_error!( + "snapshot blob {:?} disappeared during publication", + target + )) } } - Ok(_) => {} - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => { - return Err(crate::new_error!( - "failed to stat snapshot blob {:?}: {}", - target, - error - )); + Err(error) => Err(crate::new_error!( + "failed to publish snapshot blob {:?}: {}", + target, + error + )), + } +} + +fn check_existing_blob( + target: &Path, + digest: &Digest256, + expected_len: usize, + verify_existing: bool, +) -> crate::Result { + match std::fs::symlink_metadata(target) { + Ok(meta) => { + if !meta.is_file() { + return Err(crate::new_error!( + "snapshot blob {:?} is not a regular file", + target + )); + } + if meta.len() != expected_len as u64 { + return Err(crate::new_error!( + "snapshot blob {:?} size mismatch: expected {}, found {}", + target, + expected_len, + meta.len() + )); + } + if verify_existing { + let mut file = open_no_follow(target)?; + verify_blob_file("existing snapshot", &mut file, &digest.hex)?; + } + Ok(true) } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(crate::new_error!( + "failed to stat snapshot blob {:?}: {}", + target, + error + )), } - replace_file_atomic(&target, bytes) } /// Reject a path that is a symbolic link. diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs index c30e1aad5..31c35aa3b 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs @@ -5,7 +5,7 @@ //! `docs/snapshot-oci-format.md` for the on-disk format. mod config; -mod digest; +pub(super) mod digest; mod fsutil; mod media_types; pub(crate) mod reference; @@ -22,7 +22,10 @@ use oci_spec::image::{ use self::config::{ Arch, CpuVendor, HostFunction, Hypervisor, MemoryLayout, OciSnapshotConfig, OciSnapshotLayer, }; -use self::digest::{Digest256, oci_digest, parse_oci_digest, verify_blob_bytes, verify_blob_file}; +use self::digest::{ + BlobHash, Digest256, HashState, oci_digest, parse_oci_digest, verify_blob_bytes, + verify_blob_file, +}; use self::fsutil::{put_blob, put_blob_if_absent, read_bounded, replace_file_atomic}; use self::media_types::{ ANNOTATION_ARCH, ANNOTATION_CPU, ANNOTATION_HYPERVISOR, ANNOTATION_REF_NAME, @@ -364,6 +367,7 @@ impl Snapshot { /// Memory-layer digests are cached across snapshots sharing those layers. /// Existing regular blob files with the expected length are trusted by /// their content-addressed filenames without reading or hashing them. + /// Existing nonfiles and wrong-length blobs are rejected, not replaced. /// /// The caller must keep loaded and saved memory blobs immutable for the /// lifetime of these snapshots and outside writable guest mounts. Saving @@ -423,8 +427,12 @@ impl Snapshot { /// existing blob contents before reuse. /// /// Unlike [`Self::save`], this method bypasses the memory-layer digest - /// cache and hashes existing memory blob files. Blobs with mismatched - /// contents are atomically replaced with the snapshot's memory contents. + /// cache and hashes existing memory blob files. A digest differing from + /// the layer's declaration or cached computation is an error, as are + /// mismatched existing blob contents. No repair is attempted; existing + /// memory blobs and the published index remain unchanged on these errors. + /// A rejected layer hash cannot subsequently be reused by ordinary saves + /// or overlay loading through snapshots sharing that layer. /// It uses the same layout, tag semantics, durability guarantees and return /// value as [`Self::save`]; it does not sync files or directories. /// @@ -599,14 +607,19 @@ impl Snapshot { .blobs() .map(|blob| { let bytes = blob.memory().as_slice(); - let digest = if verify_blobs { - Digest256::from_bytes(bytes) - } else if let Some(hex) = blob.sha256.get().or(blob.declared_sha256.as_ref()) { - Digest256 { hex: hex.clone() } - } else { - let hex = blob.sha256.get_or_init(|| Digest256::from_bytes(bytes).hex); - Digest256 { hex: hex.clone() } - }; + if blob.hash.get()? == HashState::Unknown || verify_blobs { + // Checked saves rehash even verified blobs to detect mutation + // since the last verification. + blob.hash.verify_bytes(bytes)?; + } + let hex = blob + .hash + .get()? + .as_digest() + // Verification resolves Unknown; states never revert to it. + // Concurrent invalidation is returned by get()? above. + .expect("save must resolve a blob digest"); + let digest = Digest256 { hex }; put_blob_if_absent(&blobs_dir, &digest, bytes, verify_blobs)?; blob_descriptor(MT_SNAPSHOT_CURRENT, &digest, bytes.len()) }) @@ -1101,7 +1114,9 @@ impl Snapshot { }; layout.set_code_gva(code_gva)?; layout.ensure_page_tables_fit(cfg.layers[cfg.page_table_layer].page_table_len)?; - if base.is_some_and(|base| base.state.layout != layout) { + if let Some(base) = base + && base.state.layout != layout + { return Err(crate::new_error!( "snapshot base has an incompatible memory layout" )); @@ -1127,20 +1142,31 @@ impl Snapshot { .zip(data_descs) .map(|(layer, desc)| { let digest = parse_oci_digest(desc.digest())?; - let shared = base.and_then(|base| { - base.state.memory.blobs().find(|blob| { - blob.gpa_start() == layer.gpa_start + let mut shared = None; + if let Some(base) = base { + for blob in base.state.memory.blobs() { + if blob.gpa_start() == layer.gpa_start && blob.data_len() == layer.data_len && blob.page_table_len() == layer.page_table_len && blob.memory().as_slice().len() as u64 == desc.size() - && (blob.sha256.get() == Some(&digest) - || (!verify_blobs - && blob.declared_sha256.as_ref() == Some(&digest))) - }) - }); + { + // A checked overlay may skip reading a base blob + // only if its immutable bytes were already verified. + let hash = match blob.hash.get()? { + HashState::Verified(hex) => Some(hex), + HashState::Declared(hex) if !verify_blobs => Some(hex), + _ => None, + }; + if hash == Some(digest.as_str()) { + shared = Some(blob.clone()); + break; + } + } + } + } if let Some(blob) = shared { snap_files.push(None); - return Ok(blob.clone()); + return Ok(blob); } // Verify and map the same handle; never reopen by pathname. let file = open_snapshot_blob(&blobs_dir, desc)?; @@ -1150,9 +1176,9 @@ impl Snapshot { layer.page_table_len, scratch_base, )?; - if !verify_blobs { - blob.declared_sha256 = Some(digest); - } + // Checked loading must compare the file with this declaration, + // then promote it before exposing the snapshot to the caller. + blob.hash = BlobHash::declared(digest); let blob = Arc::new(blob); snap_files.push(Some(file)); Ok(blob) @@ -1171,11 +1197,9 @@ impl Snapshot { // Hash after validating the layers so malformed snapshots fail // cheaply. if verify_blobs { - for ((desc, file), blob) in data_descs.iter().zip(&mut snap_files).zip(&blobs) { + for (file, blob) in snap_files.iter_mut().zip(&blobs) { if let Some(file) = file { - let digest = parse_oci_digest(desc.digest())?; - verify_blob_file("snapshot", file, &digest)?; - blob.sha256.get_or_init(|| digest); + blob.hash.verify_file(file)?; } } } diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index d06b308b5..187ec0e23 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -12,6 +12,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use sha2::{Digest as _, Sha256}; +use super::file::digest::HashState; use crate::func::Registerable; use crate::mem::shared_mem::{ReadonlySharedMemory, SharedMemory as _}; use crate::sandbox::snapshot::{ @@ -214,9 +215,14 @@ fn compaction_resets_ancestry_and_can_recover_config_save_capacity() { let mut bloated = snapshot_with_shared_blobs(&root, None); Arc::get_mut(&mut Arc::get_mut(&mut bloated.state).unwrap().memory) .unwrap() - .bases = (1..=30_000).map(uuid::Uuid::from_u128).collect(); + .bases = (1..=30_000) + .map(uuid::Uuid::from_u128) + .chain(std::iter::once(selected.snapshot_memory().id)) + .collect(); let directory = tempfile::tempdir().unwrap(); let tag = OciTag::new("latest").unwrap(); + + // Ancestry can exceed the config size limit even without adding memory layers. for checked in [false, true] { let error = if checked { bloated.checked_save(directory.path(), &tag) @@ -231,12 +237,14 @@ fn compaction_resets_ancestry_and_can_recover_config_save_capacity() { ); } + // Standalone compaction recovers save capacity but invalidates prior bases. let cleared = bloated.compact(None).unwrap(); assert!(cleared.snapshot_memory().bases.is_empty()); cleared.save(directory.path(), &tag).unwrap(); cleared.checked_save(directory.path(), &tag).unwrap(); assert!(root.load_overlay(directory.path(), tag.clone()).is_err()); + // Base-relative compaction retains only the chosen base's ancestry and ID. let anchored = bloated.compact(Some(&selected)).unwrap(); let mut expected = selected.snapshot_memory().bases.clone(); expected.push(selected.snapshot_memory().id); @@ -298,10 +306,14 @@ fn compact_round_trip_preserves_base_blobs_and_execution_state() { #[cfg(not(unshared_snapshot_mem))] if preserve && value == 1 { let blobs: Vec<_> = compacted.snapshot_memory().blobs().collect(); - assert!(blobs.iter().any(|blob| blob.sha256.get().is_some())); + assert!( + blobs + .iter() + .any(|blob| matches!(blob.hash.get().unwrap(), HashState::Verified(_))) + ); let uncached_bytes: usize = blobs .iter() - .filter(|blob| blob.sha256.get().is_none()) + .filter(|blob| !matches!(blob.hash.get().unwrap(), HashState::Verified(_))) .map(|blob| blob.memory().as_slice().len()) .sum(); let before = super::file::test_hashed_bytes(); @@ -734,22 +746,121 @@ fn checked_save_rehashes_memory_and_existing_blobs() { } #[test] -fn checked_save_repairs_same_length_wrong_content_snapshot_blob() { +fn computed_blob_hash_mismatch_blocks_all_later_access() { + let hash = super::file::digest::BlobHash::verified(hex::encode(Sha256::digest( + b"original immutable bytes", + ))); + let error = hash.verify_bytes(b"different bytes").unwrap_err(); + assert!(error.to_string().contains("digest mismatch"), "{error}"); + assert!(hash.get().is_err()); + assert!(hash.verify_bytes(b"original immutable bytes").is_err()); +} + +#[test] +fn blob_hash_verifies_open_file_once_and_rejects_later_corruption() { + use super::file::digest::BlobHash; + use std::io::{Seek, SeekFrom, Write}; + + let bytes = b"immutable file bytes"; + let digest = hex::encode(Sha256::digest(bytes)); + let hash = BlobHash::declared(digest.clone()); + let mut file = tempfile::tempfile().unwrap(); + file.write_all(bytes).unwrap(); + let before = super::file::test_hashed_bytes(); + assert_eq!( + hash.verify_file(&mut file).unwrap(), + HashState::Verified(digest.as_str()) + ); + assert_eq!(super::file::test_hashed_bytes() - before, bytes.len()); + assert_eq!(file.stream_position().unwrap(), 0); + + file.write_all(b"corrupted file bytes").unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + let error = hash.verify_file(&mut file).unwrap_err(); + assert!(error.to_string().contains("digest mismatch"), "{error}"); + assert!(hash.get().is_err()); + assert_eq!(file.stream_position().unwrap(), 0); +} + +#[test] +fn concurrent_blob_hash_verification_cannot_revive_invalid_hash() { + use super::file::digest::BlobHash; + + let expected = hex::encode(Sha256::digest(b"immutable bytes")); + for declared in [false, true] { + let hash = if declared { + BlobHash::declared(expected.clone()) + } else { + BlobHash::unknown() + }; + let barrier = std::sync::Barrier::new(8); + std::thread::scope(|scope| { + for index in 0..8 { + let hash = &hash; + let barrier = &barrier; + let bytes: &[u8] = if index % 2 == 0 { + b"immutable bytes" + } else { + b"corrupted bytes" + }; + scope.spawn(move || { + barrier.wait(); + for _ in 0..16 { + let _ = hash.verify_bytes(bytes); + } + }); + } + }); + assert!(hash.get().is_err()); + assert!(hash.verify_bytes(b"immutable bytes").is_err()); + } +} + +#[test] +fn concurrent_checked_saves_reuse_identical_blobs() { + let snapshot = create_snapshot(); + let dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + let barrier = std::sync::Barrier::new(4); + let digests = std::thread::scope(|scope| { + let tasks: Vec<_> = (0..4) + .map(|_| { + scope.spawn(|| { + barrier.wait(); + snapshot.checked_save(dir.path(), &tag).unwrap() + }) + }) + .collect(); + tasks + .into_iter() + .map(|task| task.join().unwrap()) + .collect::>() + }); + assert!(digests.iter().all(|digest| *digest == digests[0])); + Snapshot::checked_load(dir.path(), tag).unwrap(); +} + +#[test] +fn checked_save_rejects_corrupt_destination_without_changing_files_or_index() { let snapshot = create_snapshot(); let dir = tempfile::tempdir().unwrap(); let tag = OciTag::new("latest").unwrap(); - let digest = snapshot.checked_save(dir.path(), &tag).unwrap(); + snapshot.checked_save(dir.path(), &tag).unwrap(); + let index = std::fs::read(dir.path().join("index.json")).unwrap(); let path = find_snapshot_blob(dir.path()); let len = std::fs::metadata(&path).unwrap().len() as usize; - std::fs::write(&path, vec![0xAAu8; len]).unwrap(); - - assert_eq!(snapshot.checked_save(dir.path(), &tag).unwrap(), digest); - let loaded = Arc::new(Snapshot::checked_load(dir.path(), tag).unwrap()); - let mut sandbox = Sandbox::from_snapshot(loaded, HostFunctions::default(), None).unwrap(); - assert_eq!( - sandbox.call::("Echo", "hello".to_string()).unwrap(), - "hello" - ); + let new_tag = OciTag::new("must-not-publish").unwrap(); + for size in [len, len - 1] { + let corrupt = vec![0xAAu8; size]; + std::fs::write(&path, &corrupt).unwrap(); + let error = snapshot.checked_save(dir.path(), &new_tag).unwrap_err(); + assert!(error.to_string().contains("mismatch"), "{error}"); + if size != len { + assert!(snapshot.save(dir.path(), &new_tag).is_err()); + } + assert_eq!(std::fs::read(&path).unwrap(), corrupt); + assert_eq!(std::fs::read(dir.path().join("index.json")).unwrap(), index); + } } #[test] @@ -782,6 +893,8 @@ fn overlay_requires_whole_base_provenance_without_retaining_unused_layers() { let dir = tempfile::tempdir().unwrap(); let tag = OciTag::new("latest").unwrap(); unrelated.save(dir.path(), &tag).unwrap(); + + // Identical shared blobs do not make an unrelated snapshot a valid overlay. for checked in [false, true] { let result = if checked { base.checked_load_overlay(dir.path(), tag.clone()) @@ -797,8 +910,13 @@ fn overlay_requires_whole_base_provenance_without_retaining_unused_layers() { ); } + // Clearing ancestry prevents compaction from reintroducing an unrelated base. let packed = unrelated.compact(None).unwrap(); - let overlay = packed.compact(Some(&base)).unwrap(); + assert!(packed.compact(Some(&base)).is_err()); + + // A declared base remains eligible even when none of its blobs are retained. + let descendant = snapshot_with_shared_blobs(&packed, Some(&base)); + let overlay = descendant.compact(Some(&base)).unwrap(); assert!(overlay.snapshot_memory().blobs().all(|blob| { !base .snapshot_memory() @@ -809,6 +927,7 @@ fn overlay_requires_whole_base_provenance_without_retaining_unused_layers() { base.load_overlay(dir.path(), tag.clone()).unwrap(); base.checked_load_overlay(dir.path(), tag.clone()).unwrap(); + // Removing provenance must revoke eligibility despite compatible memory. rewrite_config(dir.path(), |config| { config.as_object_mut().unwrap().remove("bases"); }); @@ -826,6 +945,8 @@ fn overlay_preserves_saved_base_identity_through_uncompacted_captures() { let loaded_base = Snapshot::checked_load(base_dir.path(), tag.clone()).unwrap(); let mut restored = SandboxBuilder::from_snapshot(base.clone()).build().unwrap(); let mut directories = Vec::new(); + + // Restore/capture descendants remain eligible against a separately loaded base. for value in 1..=3 { assert_eq!(restored.call::("AddToStatic", 1i32).unwrap(), value); let captured = restored.snapshot().unwrap(); @@ -844,6 +965,7 @@ fn overlay_preserves_saved_base_identity_through_uncompacted_captures() { drop(restored); drop(directories); + // Repeated live-source captures also inherit ancestry without an explicit restore. let mut previous = base; for value in 1..=3 { assert_eq!(sandbox.call::("AddToStatic", 1i32).unwrap(), value); @@ -944,26 +1066,27 @@ fn load_reuses_declared_digests_without_promoting_them_to_verified() { .sum(); let before = super::file::test_hashed_bytes(); let base = Snapshot::load(dir.path(), tag.clone()).unwrap(); + + // Ordinary loading retains declared digests without hashing memory or verifying them. assert!(super::file::test_hashed_bytes() - before < memory_bytes); assert!( base.snapshot_memory() .blobs() - .all(|blob| { blob.sha256.get().is_none() && blob.declared_sha256.is_some() }) + .all(|blob| { matches!(blob.hash.get().unwrap(), HashState::Declared(_)) }) ); + // Omit the base files: ordinary overlay loading can reuse declarations, + // whereas checked loading requires verified digests. let other = tempfile::tempdir().unwrap(); let before = super::file::test_hashed_bytes(); let derived = snapshot_with_shared_blobs(&base, Some(&base)); derived.save(other.path(), &tag).unwrap(); assert!(super::file::test_hashed_bytes() - before < memory_bytes); for blob in base.snapshot_memory().blobs() { - std::fs::remove_file( - other - .path() - .join("blobs/sha256") - .join(blob.declared_sha256.as_ref().unwrap()), - ) - .unwrap(); + let HashState::Declared(digest) = blob.hash.get().unwrap() else { + panic!("ordinary load must retain a declared hash"); + }; + std::fs::remove_file(other.path().join("blobs/sha256").join(digest)).unwrap(); } assert!( base.checked_load_overlay(other.path(), tag.clone()) @@ -977,10 +1100,16 @@ fn load_reuses_declared_digests_without_promoting_them_to_verified() { { assert!(Arc::ptr_eq(layer, base)); } + // Checked saving must hash the shared memory rather than trust its declarations. let checked_dir = tempfile::tempdir().unwrap(); let before = super::file::test_hashed_bytes(); loaded.checked_save(checked_dir.path(), &tag).unwrap(); assert!(super::file::test_hashed_bytes() - before >= memory_bytes); + assert!( + base.snapshot_memory() + .blobs() + .all(|blob| matches!(blob.hash.get().unwrap(), HashState::Verified(_))) + ); Snapshot::checked_load(checked_dir.path(), tag).unwrap(); } @@ -991,6 +1120,8 @@ fn load_accepts_wrong_content_digest_but_rejects_wrong_size() { let tag = OciTag::new("latest").unwrap(); snapshot.save(dir.path(), &tag).unwrap(); let path = find_snapshot_blob(dir.path()); + + // Corrupt content without changing its size or declared digest. let mut bytes = std::fs::read(&path).unwrap(); bytes[0] ^= 1; std::fs::write(&path, &bytes).unwrap(); @@ -1004,11 +1135,20 @@ fn load_accepts_wrong_content_digest_but_rejects_wrong_size() { .checked_load_overlay(derived_dir.path(), tag.clone()) .is_err() ); + // Ordinary save preserves the declaration; checked save rejects the mismatch. let output = tempfile::tempdir().unwrap(); trusted.save(output.path(), &tag).unwrap(); assert!(Snapshot::checked_load(output.path(), tag.clone()).is_err()); - trusted.checked_save(output.path(), &tag).unwrap(); - Snapshot::checked_load(output.path(), tag.clone()).unwrap(); + let index = std::fs::read(output.path().join("index.json")).unwrap(); + let error = trusted.checked_save(output.path(), &tag).unwrap_err(); + assert!(error.to_string().contains("digest mismatch"), "{error}"); + assert_eq!( + std::fs::read(output.path().join("index.json")).unwrap(), + index + ); + + // Release all shared mappings before truncation (required on Windows). + // Unlike a content mismatch, a size mismatch must fail even ordinary loading. drop(derived); drop(trusted); bytes.pop(); @@ -1016,6 +1156,47 @@ fn load_accepts_wrong_content_digest_but_rejects_wrong_size() { assert!(Snapshot::load(dir.path(), tag).is_err()); } +#[test] +fn checked_save_rejects_bad_declaration_and_blocks_shared_reuse() { + let snapshot = create_snapshot(); + let base_dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + snapshot.save(base_dir.path(), &tag).unwrap(); + + // Load bytes whose actual digest differs from the unchanged declaration. + let path = find_snapshot_blob(base_dir.path()); + let mut bytes = std::fs::read(&path).unwrap(); + bytes[0] ^= 1; + std::fs::write(path, bytes).unwrap(); + let base = Snapshot::load(base_dir.path(), tag.clone()).unwrap(); + let derived = snapshot_with_shared_blobs(&base, Some(&base)); + let declared_dir = tempfile::tempdir().unwrap(); + derived.save(declared_dir.path(), &tag).unwrap(); + for blob in base.snapshot_memory().blobs() { + let HashState::Declared(digest) = blob.hash.get().unwrap() else { + panic!("ordinary load must retain a declared hash"); + }; + std::fs::remove_file(declared_dir.path().join("blobs/sha256").join(digest)).unwrap(); + } + + // Verification must fail without publishing a corrected snapshot. + let output = tempfile::tempdir().unwrap(); + let error = base.checked_save(output.path(), &tag).unwrap_err(); + assert!(error.to_string().contains("digest mismatch"), "{error}"); + assert!(!output.path().join("index.json").exists()); + + // Shared references must not fall back to trusting the rejected declaration. + let error = derived.save(output.path(), &tag).unwrap_err(); + assert!(error.to_string().contains("digest mismatch"), "{error}"); + assert!(base.load_overlay(declared_dir.path(), tag.clone()).is_err()); + assert!( + base.checked_load_overlay(declared_dir.path(), tag.clone()) + .is_err() + ); + + assert!(!output.path().join("index.json").exists()); +} + #[test] fn checked_overlay_resolves_missing_blobs_without_rehashing() { let snapshot = create_snapshot(); @@ -1027,17 +1208,16 @@ fn checked_overlay_resolves_missing_blobs_without_rehashing() { let other = tempfile::tempdir().unwrap(); let derived = snapshot_with_shared_blobs(&snapshot, Some(&snapshot)); derived.save(other.path(), &tag).unwrap(); + + // Remove base blobs from the descendant so only a verified base can supply them. let memory_bytes: usize = base .snapshot_memory() .blobs() .map(|blob| { - std::fs::remove_file( - other - .path() - .join("blobs/sha256") - .join(blob.sha256.get().unwrap()), - ) - .unwrap(); + let HashState::Verified(digest) = blob.hash.get().unwrap() else { + panic!("checked load must verify the blob hash"); + }; + std::fs::remove_file(other.path().join("blobs/sha256").join(digest)).unwrap(); blob.memory().as_slice().len() }) .sum(); @@ -1048,6 +1228,8 @@ fn checked_overlay_resolves_missing_blobs_without_rehashing() { .checked_load_overlay(other.path(), tag.clone()) .is_err() ); + + // Reuse the verified base without rehashing, then restore the complete target state. let before = super::file::test_hashed_bytes(); let loaded = base .checked_load_overlay(other.path(), tag.clone()) @@ -1079,6 +1261,8 @@ fn checked_overlay_retains_shared_layers_and_verifies_new_memory() { base.save(base_dir.path(), &tag).unwrap(); let base = Arc::new(Snapshot::checked_load(base_dir.path(), tag.clone()).unwrap()); sandbox.restore(base.clone()).unwrap(); + + // Each checkpoint shares the verified base while preserving newly changed state. let mut last_dir = None; for value in 1..=3 { assert_eq!(sandbox.call::("AddToStatic", 1i32).unwrap(), value); @@ -1107,6 +1291,8 @@ fn checked_overlay_retains_shared_layers_and_verifies_new_memory() { } assert_eq!(sandbox.call::("GetStatic", ()).unwrap(), 3); drop(sandbox); + + // New layers are not covered by the base's verification and must be checked. let dir = last_dir.unwrap(); let loaded = base.checked_load_overlay(dir.path(), tag.clone()).unwrap(); let new_blob = loaded @@ -1119,10 +1305,10 @@ fn checked_overlay_retains_shared_layers_and_verifies_new_memory() { .any(|base| Arc::ptr_eq(blob, base)) }) .unwrap(); - let path = dir - .path() - .join("blobs/sha256") - .join(new_blob.sha256.get().unwrap()); + let HashState::Verified(digest) = new_blob.hash.get().unwrap() else { + panic!("checked overlay must verify the new blob hash"); + }; + let path = dir.path().join("blobs/sha256").join(digest); drop(loaded); let mut bytes = std::fs::read(&path).unwrap(); bytes[0] ^= 1; @@ -3866,7 +4052,7 @@ fn symlink_config_blob_rejected() { #[test] #[cfg(unix)] -fn save_replaces_symlink_snapshot_blob_with_regular_file() { +fn save_rejects_symlink_snapshot_blob_without_replacing_it() { let snapshot = create_snapshot(); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("snap"); @@ -3882,23 +4068,19 @@ fn save_replaces_symlink_snapshot_blob_with_regular_file() { std::fs::rename(&blob, &real).unwrap(); std::os::unix::fs::symlink(&real, &blob).unwrap(); - // Re-save. `put_blob_if_absent` sees the path is a symlink, not a - // regular file, and rewrites it via an atomic rename. - snapshot - .save(&path, &OciTag::new("latest").unwrap()) - .unwrap(); - - let meta = std::fs::symlink_metadata(&blob).unwrap(); - assert!( - meta.file_type().is_file() && !meta.file_type().is_symlink(), - "expected the snapshot blob to be a regular file after re-save" - ); - - let loaded = Snapshot::checked_load(&path, OciTag::new("latest").unwrap()).unwrap(); - let mut sbox = - Sandbox::from_snapshot(Arc::new(loaded), HostFunctions::default(), None).unwrap(); - let result: String = sbox.call("Echo", "hello\n".to_string()).unwrap(); - assert_eq!(result, "hello\n"); + let index = std::fs::read(path.join("index.json")).unwrap(); + let bytes = std::fs::read(&real).unwrap(); + let tag = OciTag::new("must-not-publish").unwrap(); + for result in [ + snapshot.save(&path, &tag), + snapshot.checked_save(&path, &tag), + ] { + let error = result.unwrap_err(); + assert!(error.to_string().contains("not a regular file"), "{error}"); + } + assert_eq!(std::fs::read_link(&blob).unwrap(), real); + assert_eq!(std::fs::read(&real).unwrap(), bytes); + assert_eq!(std::fs::read(path.join("index.json")).unwrap(), index); } /// A blob file whose size differs from its descriptor is rejected before diff --git a/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs index 13824ac6b..4b5f1f5c7 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs @@ -17,7 +17,7 @@ //! ``` use std::ops::Range; -use std::sync::{Arc, OnceLock}; +use std::sync::Arc; use hyperlight_common::vmem::PAGE_SIZE; @@ -25,6 +25,8 @@ use crate::mem::layout::SandboxMemoryLayout; use crate::mem::shared_mem::{ReadonlySharedMemory, SharedMemory}; use crate::{Result, new_error}; +use super::file::digest::BlobHash; + mod backing; pub(crate) use backing::SnapshotMemoryBacking; @@ -61,8 +63,7 @@ pub(crate) struct SnapshotBlob { memory: ReadonlySharedMemory, gpa_start: u64, page_table_len: usize, - pub(super) sha256: OnceLock, - pub(super) declared_sha256: Option, + pub(super) hash: BlobHash, } impl SnapshotBlob { @@ -103,8 +104,7 @@ impl SnapshotBlob { memory, gpa_start, page_table_len, - sha256: OnceLock::new(), - declared_sha256: None, + hash: BlobHash::default(), }) } From 4c00c28b3405b45dbaaf6e846bdee0fe1378f7ee Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Fri, 27 Nov 2026 12:57:17 +0000 Subject: [PATCH 7/9] Fix snapshot import grouping for nightly rustfmt Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jorge Prendes --- src/hyperlight_host/src/sandbox/snapshot/file_tests.rs | 3 ++- src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs | 3 +-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index 187ec0e23..f223298b2 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -758,9 +758,10 @@ fn computed_blob_hash_mismatch_blocks_all_later_access() { #[test] fn blob_hash_verifies_open_file_once_and_rejects_later_corruption() { - use super::file::digest::BlobHash; use std::io::{Seek, SeekFrom, Write}; + use super::file::digest::BlobHash; + let bytes = b"immutable file bytes"; let digest = hex::encode(Sha256::digest(bytes)); let hash = BlobHash::declared(digest.clone()); diff --git a/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs index 4b5f1f5c7..8ff50fd7a 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/memory/mod.rs @@ -21,12 +21,11 @@ use std::sync::Arc; use hyperlight_common::vmem::PAGE_SIZE; +use super::file::digest::BlobHash; use crate::mem::layout::SandboxMemoryLayout; use crate::mem::shared_mem::{ReadonlySharedMemory, SharedMemory}; use crate::{Result, new_error}; -use super::file::digest::BlobHash; - mod backing; pub(crate) use backing::SnapshotMemoryBacking; From bf542bea5aff6f7e5c466235300f822d4d4ae38f Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Fri, 27 Nov 2026 14:58:38 +0000 Subject: [PATCH 8/9] Remove unused snapshot file verification import Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jorge Prendes --- src/hyperlight_host/src/sandbox/snapshot/file/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs index 31c35aa3b..9e47f422a 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/mod.rs @@ -24,7 +24,6 @@ use self::config::{ }; use self::digest::{ BlobHash, Digest256, HashState, oci_digest, parse_oci_digest, verify_blob_bytes, - verify_blob_file, }; use self::fsutil::{put_blob, put_blob_if_absent, read_bounded, replace_file_atomic}; use self::media_types::{ From 51dd92758a6cc7f03e1da187c0da06babcbee6b3 Mon Sep 17 00:00:00 2001 From: Jorge Prendes Date: Fri, 27 Nov 2026 14:58:38 +0000 Subject: [PATCH 9/9] Test concurrent blob publication without racing metadata replacement Exercise checked no-clobber publication directly on every platform. The whole-save test also raced metadata replacement, which can fail with access denied on Windows and was outside the publication behavior under test. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jorge Prendes --- .../src/sandbox/snapshot/file/fsutil.rs | 36 ++++++++++++++++--- .../src/sandbox/snapshot/file_tests.rs | 24 ------------- 2 files changed, 31 insertions(+), 29 deletions(-) diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/fsutil.rs b/src/hyperlight_host/src/sandbox/snapshot/file/fsutil.rs index 232838a29..9886abe37 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/fsutil.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/fsutil.rs @@ -202,16 +202,42 @@ pub(super) fn read_bounded(path: &Path, max_size: u64) -> crate::Result> Ok(buf) } -#[cfg(all(test, unix))] +#[cfg(test)] mod tests { - use std::ffi::CString; - use std::os::unix::ffi::OsStrExt; - use std::os::unix::fs::OpenOptionsExt; - use super::*; + #[test] + fn concurrent_blob_publication_reuses_identical_bytes() { + let dir = tempfile::tempdir().unwrap(); + let bytes = vec![0x5a; 256 * 1024]; + let digest = Digest256::from_bytes(&bytes); + let barrier = std::sync::Barrier::new(4); + // Race memory-blob publication only, not the separate metadata/index + // replacement path used by whole saves to the same layout. + std::thread::scope(|scope| { + let tasks: Vec<_> = (0..4) + .map(|_| { + scope.spawn(|| { + barrier.wait(); + put_blob_if_absent(dir.path(), &digest, &bytes, true).unwrap(); + }) + }) + .collect(); + for task in tasks { + task.join().unwrap(); + } + }); + assert_eq!(std::fs::read(dir.path().join(&digest.hex)).unwrap(), bytes); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + + #[cfg(unix)] #[test] fn open_no_follow_rejects_fifo() { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::OpenOptionsExt; + let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("fifo"); let c_path = CString::new(path.as_os_str().as_bytes()).unwrap(); diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index f223298b2..711e21fa2 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -817,30 +817,6 @@ fn concurrent_blob_hash_verification_cannot_revive_invalid_hash() { } } -#[test] -fn concurrent_checked_saves_reuse_identical_blobs() { - let snapshot = create_snapshot(); - let dir = tempfile::tempdir().unwrap(); - let tag = OciTag::new("latest").unwrap(); - let barrier = std::sync::Barrier::new(4); - let digests = std::thread::scope(|scope| { - let tasks: Vec<_> = (0..4) - .map(|_| { - scope.spawn(|| { - barrier.wait(); - snapshot.checked_save(dir.path(), &tag).unwrap() - }) - }) - .collect(); - tasks - .into_iter() - .map(|task| task.join().unwrap()) - .collect::>() - }); - assert!(digests.iter().all(|digest| *digest == digests[0])); - Snapshot::checked_load(dir.path(), tag).unwrap(); -} - #[test] fn checked_save_rejects_corrupt_destination_without_changing_files_or_index() { let snapshot = create_snapshot();