diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f24f4e7b..ddc1e5941 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,19 @@ 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. +* 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. + `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 ac6d459b9..617c9a9ec 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 @@ -78,8 +78,54 @@ 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. + +`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, 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))` 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 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. 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 +221,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; `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/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/compact.rs b/src/hyperlight_host/src/sandbox/snapshot/compact.rs index 51d74fd1b..4fd5cba60 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/compact.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/compact.rs @@ -18,6 +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. + /// 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. @@ -158,9 +162,13 @@ impl Snapshot { if data_len > 0 { layers.push(blob.clone()); } + let mut memory = SnapshotMemory::new(layers.into_boxed_slice(), blob)?; + if let Some(base) = base { + memory.inherit_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..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 @@ -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, @@ -1110,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")] @@ -1160,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 4454a7ff4..c30e1aad5 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) } @@ -579,6 +601,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() } @@ -709,6 +733,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(), }) } @@ -749,9 +781,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`]. @@ -779,7 +818,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 @@ -798,13 +837,85 @@ 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. + /// 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 + /// 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))?; @@ -829,7 +940,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 {}", @@ -839,9 +950,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 )); } } @@ -870,6 +982,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 { @@ -952,14 +1084,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); @@ -977,6 +1101,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)?; @@ -991,18 +1120,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)| { - Ok(Arc::new(SnapshotBlob::new( - map_snapshot_blob(file, desc, layer.data_len)?, + .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)?, layer.gpa_start, layer.page_table_len, scratch_base, - )?)) + )?; + if !verify_blobs { + blob.declared_sha256 = Some(digest); + } + let blob = Arc::new(blob); + snap_files.push(Some(file)); + Ok(blob) }) .collect::>>()?; let page_tables = blobs[cfg.page_table_layer].clone(); @@ -1011,14 +1164,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 ba5844957..d06b308b5 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.inherit_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() { @@ -188,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(); @@ -208,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 { @@ -479,14 +546,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::>(); @@ -708,6 +775,362 @@ 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 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(); + 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"); + }); + 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(); + 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(); + 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 base = Snapshot::load(dir.path(), tag.clone()).unwrap(); + 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() }) + ); + + 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(); + } + 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(); + 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 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()); + 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(); + 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 359fd2ef7..13824ac6b 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]>, @@ -57,6 +62,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 +104,7 @@ impl SnapshotBlob { gpa_start, page_table_len, sha256: OnceLock::new(), + declared_sha256: None, }) } @@ -166,11 +173,19 @@ impl SnapshotMemory { } Ok(Self { + id: uuid::Uuid::new_v4(), + bases: Vec::new(), layers, page_tables, }) } + 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 /// 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..33696bb72 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.inherit_base(memory_view.snapshot().snapshot_memory()); + let memory = Arc::new(memory); Ok(Self { state: Arc::new(SnapshotState { 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";