diff --git a/README.md b/README.md index 62baaf6..cadbe2e 100644 --- a/README.md +++ b/README.md @@ -48,8 +48,12 @@ The guest has no network device. ## The vendored driver `vendor/openshell` holds one crate: OpenShell's VM driver (`openshell-driver-vm`), taken from -NVIDIA/OpenShell `main` at commit `f16795b` (after `v0.1.9`; not a release; pinned in [`driver/UPSTREAM.env`](driver/UPSTREAM.env)) and -trimmed. It is its own cargo workspace. The other OpenShell crates it uses (`openshell-core` +the `patched` branch of the fork [mr-miles/OpenShell](https://github.com/mr-miles/OpenShell) at commit +`36761e1` (pinned in [`driver/UPSTREAM.env`](driver/UPSTREAM.env)) and trimmed. That branch is OpenShell +`main` at `f16795b` (after `v0.1.9`; not a release) plus fixes not yet merged upstream: the L7 +proxy keeps percent-encoded path bytes and signs S3 paths as AWS does, and the VM driver +perf changes of ai-openshell/openshell#6056 and #6057 (fewer `debugfs` runs, hashes and worker +processes per launch). It is its own cargo workspace. The other OpenShell crates it uses (`openshell-core` and friends) are **git dependencies on the same commit**, not copies, so building needs network access to GitHub. The changes from upstream are listed in [its README](vendor/openshell/crates/openshell-driver-vm/README.md): image `ENV` and @@ -61,8 +65,9 @@ pinned commit when a release is made. `mise run driver:check-pin` fails if the r ### Compatibility The supervisor protocol is not stable across OpenShell revisions, so the gateway must come -from a revision compatible with the one in `driver/UPSTREAM.env`, currently `main` -at `f16795b`, which is not a release: build the gateway from that commit. Released gateways, +from a revision compatible with the one in `driver/UPSTREAM.env`, currently the fork's `patched` +branch at `36761e1`, which is not a release: build the gateway from that commit (or from upstream +`f16795b`, its base; the stack changes no gateway protocol). Released gateways, `v0.1.9` included, have not been checked against it. `install.sh` prints the commit the installed driver was built from and the gateway's reported version, and leaves the comparison to you. diff --git a/driver/UPSTREAM.env b/driver/UPSTREAM.env index fd131d0..492846b 100644 --- a/driver/UPSTREAM.env +++ b/driver/UPSTREAM.env @@ -7,8 +7,8 @@ # protocol is not stable across revisions. To move to another revision, re-vendor the # driver crate from it (see crates/openshell-driver-vm/README.md), then change the commit here # and the `rev` in vendor/openshell/Cargo.toml. -OPENSHELL_REPO=https://github.com/NVIDIA/OpenShell -OPENSHELL_COMMIT=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9 +OPENSHELL_REPO=https://github.com/mr-miles/OpenShell +OPENSHELL_COMMIT=36761e1a7b6d67a6a10417a5a56674d629594092 OPENSHELL_TAG= # Optional: build the embedded runtime (host supervisor, guest sandbox, guest init) from diff --git a/vendor/openshell/Cargo.lock b/vendor/openshell/Cargo.lock index bceac5f..85270d1 100644 --- a/vendor/openshell/Cargo.lock +++ b/vendor/openshell/Cargo.lock @@ -2466,7 +2466,7 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "openshell-core" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=36761e1a7b6d67a6a10417a5a56674d629594092#36761e1a7b6d67a6a10417a5a56674d629594092" dependencies = [ "async-trait", "base64 0.22.1", @@ -2508,7 +2508,7 @@ dependencies = [ [[package]] name = "openshell-crypto" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=36761e1a7b6d67a6a10417a5a56674d629594092#36761e1a7b6d67a6a10417a5a56674d629594092" dependencies = [ "aws-lc-rs", "jsonwebtoken", @@ -2576,7 +2576,7 @@ dependencies = [ [[package]] name = "openshell-extension-core" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=36761e1a7b6d67a6a10417a5a56674d629594092#36761e1a7b6d67a6a10417a5a56674d629594092" dependencies = [ "hyper-util", "serde", @@ -2589,7 +2589,7 @@ dependencies = [ [[package]] name = "openshell-isolation-interface" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=36761e1a7b6d67a6a10417a5a56674d629594092#36761e1a7b6d67a6a10417a5a56674d629594092" dependencies = [ "openshell-core", "serde", @@ -2601,7 +2601,7 @@ dependencies = [ [[package]] name = "openshell-ocsf" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=36761e1a7b6d67a6a10417a5a56674d629594092#36761e1a7b6d67a6a10417a5a56674d629594092" dependencies = [ "chrono", "serde", @@ -2615,7 +2615,7 @@ dependencies = [ [[package]] name = "openshell-otel" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=36761e1a7b6d67a6a10417a5a56674d629594092#36761e1a7b6d67a6a10417a5a56674d629594092" dependencies = [ "async-trait", "bytes", @@ -2647,7 +2647,7 @@ dependencies = [ [[package]] name = "openshell-otel-test-support" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=36761e1a7b6d67a6a10417a5a56674d629594092#36761e1a7b6d67a6a10417a5a56674d629594092" dependencies = [ "bytes", "http", @@ -2671,7 +2671,7 @@ dependencies = [ [[package]] name = "openshell-policy-schema" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=36761e1a7b6d67a6a10417a5a56674d629594092#36761e1a7b6d67a6a10417a5a56674d629594092" dependencies = [ "miette", "noyalib", @@ -2684,7 +2684,7 @@ dependencies = [ [[package]] name = "openshell-sandbox-backend" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=36761e1a7b6d67a6a10417a5a56674d629594092#36761e1a7b6d67a6a10417a5a56674d629594092" dependencies = [ "async-trait", "bytes", @@ -2716,7 +2716,7 @@ dependencies = [ [[package]] name = "openshell-spiffe" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=36761e1a7b6d67a6a10417a5a56674d629594092#36761e1a7b6d67a6a10417a5a56674d629594092" dependencies = [ "async-trait", "base64 0.22.1", diff --git a/vendor/openshell/Cargo.toml b/vendor/openshell/Cargo.toml index 74e9217..b6c34f9 100644 --- a/vendor/openshell/Cargo.toml +++ b/vendor/openshell/Cargo.toml @@ -17,13 +17,13 @@ repository = "https://github.com/NVIDIA/OpenShell" # The rest of OpenShell, from the revision driver/UPSTREAM.env names (keep the two in sync: # `mise run driver:check-pin` checks). The host supervisor and guest binaries the driver # embeds are built from that revision too. -openshell-core = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9", default-features = false } -openshell-isolation-interface = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-sandbox-backend = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-otel = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-otel-test-support = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-spiffe = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-crypto = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9", default-features = false, features = ["aws-lc"] } +openshell-core = { git = "https://github.com/mr-miles/OpenShell", rev = "36761e1a7b6d67a6a10417a5a56674d629594092", default-features = false } +openshell-isolation-interface = { git = "https://github.com/mr-miles/OpenShell", rev = "36761e1a7b6d67a6a10417a5a56674d629594092" } +openshell-sandbox-backend = { git = "https://github.com/mr-miles/OpenShell", rev = "36761e1a7b6d67a6a10417a5a56674d629594092" } +openshell-otel = { git = "https://github.com/mr-miles/OpenShell", rev = "36761e1a7b6d67a6a10417a5a56674d629594092" } +openshell-otel-test-support = { git = "https://github.com/mr-miles/OpenShell", rev = "36761e1a7b6d67a6a10417a5a56674d629594092" } +openshell-spiffe = { git = "https://github.com/mr-miles/OpenShell", rev = "36761e1a7b6d67a6a10417a5a56674d629594092" } +openshell-crypto = { git = "https://github.com/mr-miles/OpenShell", rev = "36761e1a7b6d67a6a10417a5a56674d629594092", default-features = false, features = ["aws-lc"] } # Async runtime tokio = { version = "1.53.3", features = ["full"] } diff --git a/vendor/openshell/crates/openshell-driver-vm/Cargo.toml b/vendor/openshell/crates/openshell-driver-vm/Cargo.toml index 37c2dc6..796ae73 100644 --- a/vendor/openshell/crates/openshell-driver-vm/Cargo.toml +++ b/vendor/openshell/crates/openshell-driver-vm/Cargo.toml @@ -118,6 +118,8 @@ defaults-without-telemetry = ["compute-driver"] [build-dependencies] # Generates the SPIFFE Workload API server stub without protoc. tonic-build = { version = "0.14", optional = true } +# The guest runtime identity is hashed once, at build time (build.rs). +sha2 = { workspace = true } [dev-dependencies] spiffe = { workspace = true } diff --git a/vendor/openshell/crates/openshell-driver-vm/README.md b/vendor/openshell/crates/openshell-driver-vm/README.md index 7e11538..c16a432 100644 --- a/vendor/openshell/crates/openshell-driver-vm/README.md +++ b/vendor/openshell/crates/openshell-driver-vm/README.md @@ -58,6 +58,13 @@ Changes from upstream: `off`) and `OPENSHELL_VM_LOCAL_IMAGE_SOURCE_SOCKET` choose the engine. `DOCKER_HOST`, `OPENSHELL_PODMAN_SOCKET` and `podman info` are no longer consulted. See `src/local_images.rs`. +- **Launch bookkeeping (from the fork's `patched` branch, ai-openshell/openshell#6056 and + #6057, not yet upstream).** A launch writes its overlay files in one `debugfs` run, the guest + runtime identity is hashed at build time, a cached host supervisor is re-hashed only when the + file changes, and a cached digest-pinned bootstrap image is resolved without a preparation + worker. Adapted here: no mount manifest is written (bind mounts are refused), and the + worker is skipped only for a name with a registry host, since those never consult a local + engine (see Image sources), so no engine is probed. - **Removed.** libkrun and its embedded runtime, QEMU, GPU passthrough and `openshell-vfio`, virtiofs bind mounts, and the backend negotiation in the lifecycle extension API. A sandbox that asks for a GPU or bind mounts is rejected. diff --git a/vendor/openshell/crates/openshell-driver-vm/build.rs b/vendor/openshell/crates/openshell-driver-vm/build.rs index d4bbfbc..d3ed3b8 100644 --- a/vendor/openshell/crates/openshell-driver-vm/build.rs +++ b/vendor/openshell/crates/openshell-driver-vm/build.rs @@ -7,6 +7,7 @@ //! artifacts it needs to prepare images and run sandboxes without a separate //! runtime download. The VMM is an external launcher, so no VMM is embedded. +use sha2::{Digest, Sha256}; use std::path::{Path, PathBuf}; use std::{env, fs}; @@ -22,10 +23,45 @@ fn main() { return; } - println!("cargo:rerun-if-env-changed=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR"); - let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set")); generate_workload_api_server(&out_dir); + embed_runtime_artifacts(&out_dir); + write_guest_runtime_identity(&out_dir); +} + +/// The guest runtime identity (`rootfs::sandbox_guest_runtime_identity`): +/// SHA-256 over the embedded sandbox, vm-init and umoci blobs and the guest +/// init script, exactly the bytes the crate embeds. It keys the image +/// cache, so a changed guest runtime invalidates cached root disks. Hashed +/// here once instead of in every image preparation worker, a fresh process +/// per sandbox launch. +fn write_guest_runtime_identity(out_dir: &Path) { + const GUEST_INIT_SCRIPT: &str = "scripts/openshell-vm-sandbox-init.sh"; + println!("cargo:rerun-if-changed={GUEST_INIT_SCRIPT}"); + let manifest_dir = + PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set")); + let mut hasher = Sha256::new(); + for path in [ + out_dir.join("openshell-sandbox.zst"), + out_dir.join("openshell-vm-init.zst"), + out_dir.join("umoci.zst"), + manifest_dir.join(GUEST_INIT_SCRIPT), + ] { + let bytes = fs::read(&path).unwrap_or_else(|e| { + panic!( + "read {} for the guest runtime identity: {e}", + path.display() + ) + }); + hasher.update(&bytes); + } + let identity = format!("{:x}", hasher.finalize()); + let path = out_dir.join("guest-runtime-identity"); + fs::write(&path, identity).unwrap_or_else(|e| panic!("write {}: {e}", path.display())); +} + +fn embed_runtime_artifacts(out_dir: &Path) { + println!("cargo:rerun-if-env-changed=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR"); let Ok(dir) = env::var("OPENSHELL_VM_RUNTIME_COMPRESSED_DIR") else { // Lint, check and test builds (the debug profile) never run the embedded @@ -35,7 +71,7 @@ fn main() { println!("cargo:warning=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR not set"); println!("cargo:warning=Stage the compressed runtime artifacts and point it at them"); } - generate_stub_resources(&out_dir); + generate_stub_resources(out_dir); return; }; let compressed_dir = PathBuf::from(dir); diff --git a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs index 86432b4..1dfc454 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs @@ -20,12 +20,11 @@ use crate::lifecycle::{ extension_state_dir, }; use crate::rootfs::{ - clone_or_copy_sparse_file, create_ext4_image_from_dir_with_size, create_rootfs_image_from_dir, - ext4_image_has_directory, extract_host_supervisor, extract_rootfs_archive_to, - prepare_sandbox_rootfs_from_image_root, recover_rootfs_image, remove_rootfs_image_file, + RootfsImageBatch, clone_or_copy_sparse_file, create_ext4_image_from_dir_with_size, + create_rootfs_image_from_dir, ext4_image_has_directory, extract_host_supervisor, + extract_rootfs_archive_to, prepare_sandbox_rootfs_from_image_root, recover_rootfs_image, sandbox_guest_init_path, sandbox_guest_runtime_identity, sandbox_guest_user_ids_from_image, - sandbox_guest_user_ids_from_overlay_image, set_rootfs_image_file_mode, - validate_host_supervisor, write_rootfs_image_file, + sandbox_guest_user_ids_from_overlay_image, validate_host_supervisor, }; use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; use bollard::Docker; @@ -2389,7 +2388,7 @@ impl VmDriver { } } - if let Err(err) = inject_guest_init_dropins(&overlay_disk, &plan.guest_init_dropins) { + if let Err(err) = prepare_guest_overlay(&overlay_disk, &plan.guest_init_dropins) { self.lifecycle_extensions .after_launch_failed(&sandbox, &state_dir, LaunchAbortReason::GuestPrepareFailed) .await; @@ -3581,6 +3580,23 @@ impl VmDriver { rootfs_tar: Option<&Path>, bootstrap_only: bool, ) -> Result { + self.prepare_images(sandbox_id, image_ref, rootfs_tar, bootstrap_only) + .await + } + + async fn prepare_images( + &self, + sandbox_id: &str, + image_ref: &str, + rootfs_tar: Option<&Path>, + bootstrap_only: bool, + ) -> Result { + if let Some(plan) = self + .cached_digest_pinned_image_plan(sandbox_id, image_ref, rootfs_tar, bootstrap_only) + .await + { + return Ok(plan); + } match self .run_preparation_in_worker(sandbox_id, image_ref, rootfs_tar, bootstrap_only, None) .await? @@ -3592,6 +3608,90 @@ impl VmDriver { } } + /// The image plan of a launch whose root disk is the bootstrap image, + /// pinned by digest and already cached, resolved in this process. + /// + /// The worker writes nothing for such a launch: the name has a registry + /// host, so it skips the local engine, and answers from the cache without + /// a registry call (`ensure_cached_registry_rootfs_image`). Answering here + /// spares the worker process (an exec of the driver binary and its exit + /// poll) on every such launch, with the same logs and events. Anything + /// else returns `None` before any log or event, and the worker prepares, + /// reports and fails exactly as before: a rootfs tar, a workload image + /// other than the bootstrap image, a tag, a name without a registry host + /// (local engine images), a cache miss, a registry credential + /// error, a missing bootstrap image, or a sandbox that is gone or + /// already preparing. + async fn cached_digest_pinned_image_plan( + &self, + sandbox_id: &str, + image_ref: &str, + rootfs_tar: Option<&Path>, + bootstrap_only: bool, + ) -> Option { + if rootfs_tar.is_some() { + return None; + } + let bootstrap_image_ref = self.bootstrap_image_ref().ok()?; + let resolved_ref = if bootstrap_only { + image_ref + } else if image_ref.trim() == bootstrap_image_ref.trim() { + bootstrap_image_ref.as_str() + } else { + return None; + }; + { + let registry = self.registry.lock().await; + let record = registry.get(sandbox_id)?; + if record.deleting || record.preparation.is_some() { + return None; + } + } + // A name without a registry host comes only from the local engine. + if !crate::local_images::image_ref_has_registry_host(resolved_ref) { + return None; + } + let digest = parse_registry_reference(resolved_ref) + .ok()? + .digest()? + .to_owned(); + let image_identity = bootstrap_image_cache_identity(&digest); + let image_path = image_cache_rootfs_image(&self.config.state_dir, &image_identity); + if tokio::fs::metadata(&image_path).await.is_err() || registry_auth(resolved_ref).is_err() { + return None; + } + + let span = tracing::info_span!( + "vm.resolve_bootstrap_image", + otel.name = "vm.resolve_bootstrap_image", + otel.status_code = tracing::field::Empty, + sandbox.id = %sandbox_id, + image.ref = %bootstrap_image_ref, + ); + async { + debug!( + image_ref = %resolved_ref, + "vm driver: image names a registry host, skipping the local engine" + ); + info!(image_ref = %resolved_ref, "vm driver: ensuring cached root disk image (registry)"); + info!( + image_identity = %image_identity, + image_path = %image_path.display(), + "vm driver: root disk image cache hit (digest-pinned, no registry call)" + ); + self.publish_registry_cache_hit(sandbox_id, resolved_ref, &image_identity, &image_path) + .await; + } + .instrument(span) + .await; + Some(RuntimeImagePlan { + root_disk: image_path, + image_disk: None, + image_identity: image_identity.clone(), + bootstrap_image_identity: image_identity, + }) + } + #[tracing::instrument( name = "vm.prepare_overlay", skip(self), @@ -7589,17 +7689,15 @@ async fn remove_runtime_generation_material(state_dir: &Path) -> Result<(), Stri let generation_for_cleanup = generation.clone(); tokio::task::spawn_blocking(move || { let tls = guest_boundary_tls_paths(&generation_for_cleanup); + let mut batch = RootfsImageBatch::new(&overlay); for guest_path in [ PathBuf::from(guest_boundary_config_path(&generation_for_cleanup)), tls.certificate_chain_path, tls.private_key_path, ] { - remove_rootfs_image_file( - &overlay, - &overlay_upper_path(&guest_path.to_string_lossy()), - )?; + batch.remove_file(&overlay_upper_path(&guest_path.to_string_lossy()))?; } - Ok::<(), String>(()) + batch.commit() }) .await .map_err(|error| format!("guest authentication cleanup task failed: {error}"))??; @@ -7803,8 +7901,9 @@ fn inject_guest_boundary_bundle( .encode() .map_err(|error| format!("encode VM boundary configuration: {error}"))?; let config_path = overlay_upper_path(guest_path); - write_rootfs_image_file(overlay_disk, &config_path, &encoded_config)?; - set_rootfs_image_file_mode(overlay_disk, &config_path, 0o600)?; + let mut batch = RootfsImageBatch::new(overlay_disk); + batch.write_file(&config_path, &encoded_config)?; + batch.set_file_mode(&config_path, 0o600)?; for (guest_path, contents) in [ ( tls.certificate_chain_path, @@ -7813,10 +7912,37 @@ fn inject_guest_boundary_bundle( (tls.private_key_path, material.private_key_pem.as_bytes()), ] { let path = overlay_upper_path(guest_path.to_string_lossy().as_ref()); - write_rootfs_image_file(overlay_disk, &path, contents)?; - set_rootfs_image_file_mode(overlay_disk, &path, 0o600)?; + batch.write_file(&path, contents)?; + batch.set_file_mode(&path, 0o600)?; } - Ok(()) + batch.commit() +} + +/// Write the launch's guest overlay files: the init drop-ins and their +/// manifest. Every file is staged first and the overlay is written by one +/// debugfs run ([`RootfsImageBatch`]), so a staging failure writes nothing. +/// (Upstream also writes a mount manifest here; this driver refuses bind +/// mounts and its guest init reads no manifest.) +#[allow(clippy::result_large_err)] +#[tracing::instrument( + name = "vm.prepare_guest", + skip(dropins), + fields( + otel.name = "vm.prepare_guest", + otel.status_code = tracing::field::Empty, + overlay.path = %overlay_disk.display(), + dropin.count = dropins.len(), + ) +)] +fn prepare_guest_overlay(overlay_disk: &Path, dropins: &[GuestInitDropin]) -> Result<(), Status> { + let span_status = openshell_otel::ErrorStatusGuard::current(); + let mut batch = RootfsImageBatch::new(overlay_disk); + let result = inject_guest_init_dropins(&mut batch, dropins).and_then(|()| { + batch + .commit() + .map_err(|error| Status::internal(format!("write VM guest overlay files: {error}"))) + }); + span_status.finish(result) } fn guest_boundary_config_path(generation: &str) -> String { @@ -7835,21 +7961,10 @@ fn guest_boundary_tls_paths(generation: &str) -> SandboxTlsServerConfig { } #[allow(clippy::result_large_err)] -#[tracing::instrument( - name = "vm.prepare_guest", - skip(dropins), - fields( - otel.name = "vm.prepare_guest", - otel.status_code = tracing::field::Empty, - overlay.path = %overlay_disk.display(), - dropin.count = dropins.len(), - ) -)] fn inject_guest_init_dropins( - overlay_disk: &Path, + batch: &mut RootfsImageBatch, dropins: &[GuestInitDropin], ) -> Result<(), Status> { - let span_status = openshell_otel::ErrorStatusGuard::current(); validate_guest_init_dropins(dropins).map_err(Status::failed_precondition)?; // Drop-ins are *executed* in a child shell by run_openshell_init_dropins @@ -7858,13 +7973,15 @@ fn inject_guest_init_dropins( // contract drop-in authors should rely on. for dropin in dropins { let guest_path = overlay_upper_path(&format!("{GUEST_INIT_DROPIN_DIR}/{}", dropin.name)); - write_rootfs_image_file(overlay_disk, &guest_path, &dropin.contents).map_err(|err| { - Status::internal(format!( - "write VM guest init drop-in '{}' failed: {err}", - dropin.name - )) - })?; - set_rootfs_image_file_mode(overlay_disk, &guest_path, 0o755).map_err(|err| { + batch + .write_file(&guest_path, &dropin.contents) + .map_err(|err| { + Status::internal(format!( + "write VM guest init drop-in '{}' failed: {err}", + dropin.name + )) + })?; + batch.set_file_mode(&guest_path, 0o755).map_err(|err| { Status::internal(format!( "set VM guest init drop-in '{}' executable failed: {err}", dropin.name @@ -7877,8 +7994,7 @@ fn inject_guest_init_dropins( // injected — so the guest always fails closed: only names the driver // explicitly injected this launch are eligible to run, and a guest // image cannot smuggle in extra `init.d` entries. - write_guest_init_dropin_manifest(overlay_disk, dropins)?; - span_status.finish(Ok(())) + write_guest_init_dropin_manifest(batch, dropins) } /// Build the corporate upstream-proxy arguments passed to host control. @@ -7944,17 +8060,17 @@ fn render_guest_init_dropin_manifest(dropins: &[GuestInitDropin]) -> Vec { #[allow(clippy::result_large_err)] fn write_guest_init_dropin_manifest( - overlay_disk: &Path, + batch: &mut RootfsImageBatch, dropins: &[GuestInitDropin], ) -> Result<(), Status> { let guest_path = overlay_upper_path(GUEST_INIT_DROPIN_MANIFEST); let contents = render_guest_init_dropin_manifest(dropins); - write_rootfs_image_file(overlay_disk, &guest_path, &contents).map_err(|err| { + batch.write_file(&guest_path, &contents).map_err(|err| { Status::internal(format!( "write VM guest init drop-in manifest failed: {err}" )) })?; - set_rootfs_image_file_mode(overlay_disk, &guest_path, 0o644).map_err(|err| { + batch.set_file_mode(&guest_path, 0o644).map_err(|err| { Status::internal(format!( "set VM guest init drop-in manifest mode failed: {err}" )) @@ -9646,7 +9762,7 @@ mod tests { ); let invalid_dropin = GuestInitDropin::new("../invalid", Vec::new()); assert!( - inject_guest_init_dropins(Path::new("/unused"), &[invalid_dropin]).is_err(), + prepare_guest_overlay(Path::new("/unused"), &[invalid_dropin]).is_err(), "an invalid drop-in should fail after creating its span" ); } @@ -11283,6 +11399,234 @@ mod tests { task.abort(); } + /// A driver whose image preparation worker records each run in + /// `worker-runs` and answers with `plan`, and a registered sandbox `id`. + async fn cached_image_test_driver( + root: &Path, + bootstrap_image: &str, + id: &str, + plan: &RuntimeImagePlan, + ) -> VmDriver { + use std::os::unix::fs::PermissionsExt as _; + + let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); + driver.config.state_dir = root.to_path_buf(); + driver.config.bootstrap_image = bootstrap_image.to_string(); + driver.launcher_bin = root.join("worker"); + let complete = + preparation::Message::Complete(Ok(preparation::Output::Images(plan.clone()))); + fs::write( + root.join("images.json"), + serde_json::to_vec(&complete).unwrap(), + ) + .unwrap(); + fs::write( + &driver.launcher_bin, + "#!/bin/sh\ncontrol=$(dirname \"$0\")\necho run >> \"$control/worker-runs\"\ncat \"$control/images.json\"\nprintf '\\n'\n", + ) + .unwrap(); + fs::set_permissions(&driver.launcher_bin, fs::Permissions::from_mode(0o700)).unwrap(); + let state_dir = sandboxes_root_dir(root).join(id); + create_private_dir_all(&state_dir).await.unwrap(); + driver.registry.lock().await.insert( + id.to_string(), + SandboxRecord { + snapshot: Sandbox { + id: id.to_string(), + ..Default::default() + }, + state_dir, + process: None, + provisioning_task: None, + preparation: None, + deleting: false, + }, + ); + driver + } + + fn platform_event_reasons( + events: &mut broadcast::Receiver, + ) -> Vec { + let mut reasons = Vec::new(); + while let Ok(event) = events.try_recv() { + if let Some(watch_sandboxes_event::Payload::PlatformEvent(value)) = event.payload + && let Some(event) = value.event + { + reasons.push(event.reason); + } + } + reasons + } + + #[tokio::test] + async fn cached_digest_pinned_image_plan_skips_the_worker_only_on_a_digest_cache_hit() { + #[allow(clippy::struct_excessive_bools)] + struct Case<'a> { + name: &'static str, + bootstrap_ref: &'a str, + image_ref: &'a str, + rootfs_tar: bool, + cached: bool, + bootstrap_only: bool, + /// Answered without the worker. + fast: bool, + } + const DIGEST: &str = + "sha256:6c70a5370000000000000000000000000000000000000000000000000000beef"; + let pinned = format!("registry.example.com/sandbox:1@{DIGEST}"); + let tag = "registry.example.com/sandbox:1"; + let other = "registry.example.com/other@sha256:00"; + let local_pinned = format!("localhost/sandbox@{DIGEST}"); + let identity = bootstrap_image_cache_identity(DIGEST); + + let hit = Case { + name: "bootstrap-only hit", + bootstrap_ref: &pinned, + image_ref: &pinned, + rootfs_tar: false, + cached: true, + bootstrap_only: true, + fast: true, + }; + let cases = [ + Case { + name: "workload is the bootstrap image", + bootstrap_only: false, + ..hit + }, + Case { + name: "cache miss", + cached: false, + fast: false, + ..hit + }, + Case { + name: "tag", + bootstrap_ref: tag, + image_ref: tag, + fast: false, + ..hit + }, + Case { + name: "other workload image", + image_ref: other, + bootstrap_only: false, + fast: false, + ..hit + }, + Case { + name: "rootfs tar", + rootfs_tar: true, + bootstrap_only: false, + fast: false, + ..hit + }, + Case { + name: "no registry host (local engine image)", + bootstrap_ref: &local_pinned, + image_ref: &local_pinned, + fast: false, + ..hit + }, + Case { + name: "locally built image", + bootstrap_ref: "openshell/sandbox-from:1", + image_ref: "openshell/sandbox-from:1", + fast: false, + ..hit + }, + hit, + ]; + for Case { + name: case, + bootstrap_ref, + image_ref, + rootfs_tar: tar, + cached, + bootstrap_only, + fast, + } in cases + { + let root = tempfile::tempdir().unwrap(); + let cached_root = image_cache_rootfs_image(root.path(), &identity); + let worker_plan = RuntimeImagePlan { + root_disk: root.path().join("from-worker.ext4"), + image_disk: None, + image_identity: "worker".to_string(), + bootstrap_image_identity: "worker".to_string(), + }; + let driver = + cached_image_test_driver(root.path(), bootstrap_ref, "sb", &worker_plan).await; + if cached { + fs::create_dir_all(cached_root.parent().unwrap()).unwrap(); + fs::write(&cached_root, b"cached bootstrap").unwrap(); + } + let tar_path = root.path().join("rootfs.tar"); + let mut events = driver.events.subscribe(); + + let plan = driver + .prepare_images( + "sb", + image_ref, + tar.then_some(tar_path.as_path()), + bootstrap_only, + ) + .await + .unwrap_or_else(|error| panic!("{case}: {error}")); + + let worker_ran = root.path().join("worker-runs").exists(); + assert_eq!(worker_ran, !fast, "{case}: worker ran"); + if fast { + assert_eq!(plan.root_disk, cached_root, "{case}"); + assert_eq!(plan.image_disk, None, "{case}"); + assert_eq!(plan.image_identity, identity, "{case}"); + assert_eq!(plan.bootstrap_image_identity, identity, "{case}"); + assert_eq!( + platform_event_reasons(&mut events), + ["Pulling", "CacheHit", "Pulled"], + "{case}: the worker's events" + ); + } else { + assert_eq!(plan.root_disk, worker_plan.root_disk, "{case}"); + } + assert!( + driver.registry.lock().await["sb"].preparation.is_none(), + "{case}" + ); + } + } + + #[tokio::test] + async fn cached_digest_pinned_image_plan_keeps_the_worker_path_errors() { + const PINNED: &str = "registry.example.com/sandbox@sha256:00"; + let root = tempfile::tempdir().unwrap(); + let plan = RuntimeImagePlan { + root_disk: root.path().join("unused"), + image_disk: None, + image_identity: String::new(), + bootstrap_image_identity: String::new(), + }; + let driver = cached_image_test_driver(root.path(), PINNED, "sb", &plan).await; + let cached_root = + image_cache_rootfs_image(root.path(), &bootstrap_image_cache_identity("sha256:00")); + fs::create_dir_all(cached_root.parent().unwrap()).unwrap(); + fs::write(&cached_root, b"cached bootstrap").unwrap(); + + let error = driver + .prepare_images("missing", PINNED, None, true) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Cancelled); + driver.registry.lock().await.get_mut("sb").unwrap().deleting = true; + let error = driver + .prepare_images("sb", PINNED, None, true) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Cancelled); + assert!(!root.path().join("worker-runs").exists()); + } + #[tokio::test] async fn blocked_worker_does_not_delay_independent_image_and_overlay_requests() { let root = tempfile::tempdir().unwrap(); diff --git a/vendor/openshell/crates/openshell-driver-vm/src/rootfs.rs b/vendor/openshell/crates/openshell-driver-vm/src/rootfs.rs index 8308849..18a32a8 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/rootfs.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/rootfs.rs @@ -10,8 +10,8 @@ use std::io::BufWriter; use std::io::{BufRead, BufReader, Cursor, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::process::Command; -use std::sync::OnceLock; use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock, PoisonError}; use crate::driver::{DEFAULT_SANDBOX_UID, PREPARED_IMAGE_ROOTFS_DIR}; @@ -40,7 +40,20 @@ pub const fn sandbox_guest_init_path() -> &'static str { /// /// Including this in the image-cache key makes local, uncommitted guest-sandbox /// changes invalidate the cache even when the `OpenShell` version is unchanged. +/// build.rs hashes the same bytes the crate embeds, once per build: every +/// sandbox launch resolves its root disk in a fresh preparation worker +/// process, which hashed the embedded blobs again each time. pub fn sandbox_guest_runtime_identity() -> String { + GUEST_RUNTIME_IDENTITY.to_string() +} + +const GUEST_RUNTIME_IDENTITY: &str = + include_str!(concat!(env!("OUT_DIR"), "/guest-runtime-identity")); + +/// The identity hashed from the embedded bytes at run time, as it was +/// before build.rs computed it; the tests hold the two equal. +#[cfg(test)] +fn sandbox_guest_runtime_identity_of_embedded_bytes() -> String { let mut hasher = Sha256::new(); hasher.update(SANDBOX); hasher.update(VM_INIT); @@ -62,8 +75,122 @@ pub fn extract_host_supervisor(path: &Path) -> Result<(), String> { validate_host_supervisor(path) } +/// Check the cached host supervisor against the embedded one. +/// +/// Every sandbox launch asks, and hashing the ~50 MB file each time cost a +/// launch hundreds of milliseconds of CPU on a host without SHA +/// instructions. A file this driver process has hashed and found good is +/// not hashed again while its identity is unchanged: device, inode, size, +/// mode, mtime and ctime. Any write, chmod, chown, rename or replacement of +/// the file changes its ctime or inode (the kernel sets ctime; no caller can +/// set it back), so it is hashed again. The kernel stamps ctime from a +/// coarse clock, so a rewrite within the same tick as the last change can +/// keep the same ctime: only a file whose ctime is at least +/// [`SETTLED_CTIME`] in the past is remembered (git's "racily clean" rule), +/// and any later change then gets a later ctime. A new driver process +/// remembers nothing: it hashes once more on its first launch. pub fn validate_host_supervisor(path: &Path) -> Result<(), String> { - validate_host_supervisor_digest(path, embedded_host_supervisor_digest()?) + static VALIDATED: Mutex> = Mutex::new(None); + validate_host_supervisor_once( + path, + embedded_host_supervisor_digest()?, + &VALIDATED, + validate_host_supervisor_digest, + ) +} + +/// How old a file's ctime must be before its stamp is trusted to change +/// with its next modification: well above any kernel timestamp tick. +const SETTLED_CTIME: std::time::Duration = std::time::Duration::from_secs(1); + +/// A cached host supervisor that matched `digest` when it had `stamp`. +#[derive(Clone, PartialEq, Eq)] +struct ValidatedHostSupervisor { + path: PathBuf, + stamp: FileStamp, + digest: [u8; 32], +} + +/// What identifies one version of a file without reading it. +#[derive(Clone, Copy, PartialEq, Eq)] +struct FileStamp { + dev: u64, + ino: u64, + size: u64, + mode: u32, + mtime: (i64, i64), + ctime: (i64, i64), +} + +impl FileStamp { + #[cfg(unix)] + #[allow(clippy::unnecessary_wraps)] + fn of(metadata: &fs::Metadata) -> Option { + use std::os::unix::fs::MetadataExt as _; + Some(Self { + dev: metadata.dev(), + ino: metadata.ino(), + size: metadata.size(), + mode: metadata.mode(), + mtime: (metadata.mtime(), metadata.mtime_nsec()), + ctime: (metadata.ctime(), metadata.ctime_nsec()), + }) + } + + #[cfg(not(unix))] + fn of(_metadata: &fs::Metadata) -> Option { + None + } + + fn read(path: &Path) -> Option { + fs::symlink_metadata(path).ok().as_ref().and_then(Self::of) + } + + /// Whether the last change is [`SETTLED_CTIME`] or more in the past. + fn settled(&self) -> bool { + let (secs, nanos) = self.ctime; + let (Ok(secs), Ok(nanos)) = (u64::try_from(secs), u32::try_from(nanos)) else { + return false; + }; + let ctime = std::time::UNIX_EPOCH + std::time::Duration::new(secs, nanos); + std::time::SystemTime::now() + .duration_since(ctime) + .is_ok_and(|age| age >= SETTLED_CTIME) + } +} + +fn validate_host_supervisor_once( + path: &Path, + expected: [u8; 32], + validated: &Mutex>, + validate: impl Fn(&Path, [u8; 32]) -> Result<(), String>, +) -> Result<(), String> { + let before = FileStamp::read(path); + let remembered = |stamp: FileStamp| ValidatedHostSupervisor { + path: path.to_path_buf(), + stamp, + digest: expected, + }; + if let Some(stamp) = before + && validated + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + .is_some_and(|known| *known == remembered(stamp)) + { + return Ok(()); + } + let result = validate(path, expected); + // Remember only a file that did not change while it was hashed and + // whose next change cannot share its ctime. + let after = FileStamp::read(path); + *validated.lock().unwrap_or_else(PoisonError::into_inner) = match (&result, before, after) { + (Ok(()), Some(before), Some(after)) if before == after && before.settled() => { + Some(remembered(before)) + } + _ => None, + }; + result } fn validate_host_supervisor_digest(path: &Path, expected: [u8; 32]) -> Result<(), String> { @@ -316,55 +443,85 @@ pub fn clone_or_copy_sparse_file(source: &Path, dest: &Path) -> Result<(), Strin }) } -pub fn write_rootfs_image_file( - image_path: &Path, - guest_path: &str, - contents: &[u8], -) -> Result<(), String> { - ensure_rootfs_image_parent_dirs(image_path, guest_path); +/// Writes into one ext4 image, run as ONE `debugfs -w -f` process. +/// +/// Each staged item is exactly the command sequence the single-file helpers +/// used to run as one `debugfs -w -R` process per command: a `mkdir` per +/// parent component, `rm` and `write` for a file, `set_inode_field ... mode` +/// for a mode, `rm` for a removal, in the order they were staged. debugfs +/// reports a failing command (an existing directory, a missing file) on +/// stderr and exits 0 in both modes: only an unknown command or a failure to +/// run debugfs fails the run, so one batch leaves the same disk contents and +/// the same success or failure as the separate runs did, in one process +/// instead of about thirty per sandbox launch. A path debugfs cannot take +/// on one line (a newline, carriage return or NUL in it) is refused when it +/// is staged, before anything is written. Staged file contents live in +/// temporary files beside the image until the batch has run or is dropped. +pub struct RootfsImageBatch { + image_path: PathBuf, + commands: Vec, + staged_files: Vec, +} + +impl RootfsImageBatch { + pub fn new(image_path: &Path) -> Self { + Self { + image_path: image_path.to_path_buf(), + commands: Vec::new(), + staged_files: Vec::new(), + } + } - let tmp_path = temporary_injection_path(image_path); - fs::write(&tmp_path, contents).map_err(|e| format!("write {}: {e}", tmp_path.display()))?; - let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else { - let _ = fs::remove_file(&tmp_path); - return Err(format!("invalid debugfs guest path '{guest_path}'")); - }; - let Some(quoted_tmp_path) = debugfs_quote_argument(&tmp_path.to_string_lossy()) else { - let _ = fs::remove_file(&tmp_path); - return Err(format!( - "invalid debugfs injection path '{}'", - tmp_path.display() + /// Replace `guest_path` with `contents`, creating missing parents. + pub fn write_file(&mut self, guest_path: &str, contents: &[u8]) -> Result<(), String> { + let quoted_guest_path = debugfs_quote_absolute_path(guest_path) + .ok_or_else(|| format!("invalid debugfs guest path '{guest_path}'"))?; + let mut commands = rootfs_image_parent_dir_commands(guest_path)?; + let tmp_path = temporary_injection_path(&self.image_path); + let quoted_tmp_path = debugfs_quote_argument(&tmp_path.to_string_lossy()) + .ok_or_else(|| format!("invalid debugfs injection path '{}'", tmp_path.display()))?; + fs::write(&tmp_path, contents).map_err(|e| format!("write {}: {e}", tmp_path.display()))?; + self.staged_files.push(tmp_path); + commands.push(format!("rm {quoted_guest_path}")); + commands.push(format!("write {quoted_tmp_path} {quoted_guest_path}")); + self.commands.append(&mut commands); + Ok(()) + } + + /// Set the permission bits of the regular file at `guest_path`. + pub fn set_file_mode(&mut self, guest_path: &str, mode: u32) -> Result<(), String> { + let regular_file_mode = 0o100_000 | (mode & 0o7777); + let quoted_guest_path = debugfs_quote_absolute_path(guest_path) + .ok_or_else(|| format!("invalid debugfs guest path '{guest_path}'"))?; + self.commands.push(format!( + "set_inode_field {quoted_guest_path} mode 0{regular_file_mode:o}" )); - }; - let _ = run_debugfs(image_path, &format!("rm {quoted_guest_path}")); - let result = run_debugfs( - image_path, - &format!("write {quoted_tmp_path} {quoted_guest_path}"), - ); - let _ = fs::remove_file(&tmp_path); - result -} + Ok(()) + } -pub fn remove_rootfs_image_file(image_path: &Path, guest_path: &str) -> Result<(), String> { - let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else { - return Err(format!("invalid debugfs guest path '{guest_path}'")); - }; - run_debugfs(image_path, &format!("rm {quoted_guest_path}")) + /// Remove the file at `guest_path` (nothing happens when it is absent). + pub fn remove_file(&mut self, guest_path: &str) -> Result<(), String> { + let quoted_guest_path = debugfs_quote_absolute_path(guest_path) + .ok_or_else(|| format!("invalid debugfs guest path '{guest_path}'"))?; + self.commands.push(format!("rm {quoted_guest_path}")); + Ok(()) + } + + /// Run every staged command in one debugfs process. + pub fn commit(self) -> Result<(), String> { + if self.commands.is_empty() { + return Ok(()); + } + run_debugfs_batch(&self.image_path, &self.commands) + } } -pub fn set_rootfs_image_file_mode( - image_path: &Path, - guest_path: &str, - mode: u32, -) -> Result<(), String> { - let regular_file_mode = 0o100_000 | (mode & 0o7777); - let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else { - return Err(format!("invalid debugfs guest path '{guest_path}'")); - }; - run_debugfs( - image_path, - &format!("set_inode_field {quoted_guest_path} mode 0{regular_file_mode:o}"), - ) +impl Drop for RootfsImageBatch { + fn drop(&mut self) { + for path in self.staged_files.drain(..) { + let _ = fs::remove_file(path); + } + } } /// Write a tree of files into an ext4 image in one `debugfs` session. @@ -782,9 +939,14 @@ fn format_ext4_image_from_dir(source: &Path, image_path: &Path) -> Result<(), St )) } -fn ensure_rootfs_image_parent_dirs(image_path: &Path, guest_path: &str) { +/// The `mkdir` commands for every parent component of `guest_path`, as +/// the single-file writer always issued them (unquoted, existing ones fail +/// harmlessly). A component debugfs would read as more than one line is +/// refused. +fn rootfs_image_parent_dir_commands(guest_path: &str) -> Result, String> { + let mut commands = Vec::new(); let Some(parent) = Path::new(guest_path).parent() else { - return; + return Ok(commands); }; let mut current = String::new(); for component in parent.components() { @@ -792,10 +954,14 @@ fn ensure_rootfs_image_parent_dirs(image_path: &Path, guest_path: &str) { if part == "/" || part.is_empty() { continue; } + if part.contains(['\0', '\n', '\r']) { + return Err(format!("invalid debugfs guest path '{guest_path}'")); + } current.push('/'); current.push_str(&part); - let _ = run_debugfs(image_path, &format!("mkdir {current}")); + commands.push(format!("mkdir {current}")); } + Ok(commands) } fn normalize_sandbox_owner_in_rootfs_image(source: &Path, image_path: &Path) -> Result<(), String> { @@ -1084,6 +1250,9 @@ fn run_debugfs_batch_file(image_path: &Path, command_path: &Path) -> Result<(), } } +/// One debugfs process per command: what the overlay writes did before +/// [`RootfsImageBatch`]; the batch tests compare against it. +#[cfg(test)] fn run_debugfs(image_path: &Path, command: &str) -> Result<(), String> { let output = e2fs_command("debugfs")? .arg("-w") @@ -1332,6 +1501,92 @@ mod tests { use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{SystemTime, UNIX_EPOCH}; + #[test] + fn guest_runtime_identity_built_once_matches_the_embedded_bytes() { + let identity = sandbox_guest_runtime_identity(); + assert_eq!(identity.len(), 64, "{identity}"); + assert!(identity.bytes().all(|byte| byte.is_ascii_hexdigit())); + assert_eq!(identity, sandbox_guest_runtime_identity_of_embedded_bytes()); + } + + #[cfg(target_os = "linux")] + #[test] + fn host_supervisor_validated_once_per_file_version() { + use std::sync::atomic::AtomicUsize; + + // Past the settle time: the file's last change is then remembered. + let settle = || std::thread::sleep(SETTLED_CTIME + std::time::Duration::from_millis(100)); + let directory = tempfile::tempdir().expect("cache directory"); + let path = directory.path().join("openshell-sandbox"); + let good = b"trusted supervisor".as_slice(); + let bad = b"tampered supervisor".as_slice(); + fs::write(&path, good).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + let expected = sha256_bytes(good); + let validated = Mutex::new(None); + let hashes = AtomicUsize::new(0); + let count = |path: &Path, expected| { + hashes.fetch_add(1, Ordering::Relaxed); + validate_host_supervisor_digest(path, expected) + }; + let check = |path: &Path| validate_host_supervisor_once(path, expected, &validated, count); + let hash_count = || hashes.load(Ordering::Relaxed); + + // Just written: a rewrite in the same timestamp tick could keep the + // stamp, so it is not remembered yet. + check(&path).expect("first launch hashes the cache"); + check(&path).expect("hashed again"); + assert_eq!(hash_count(), 2, "a just-changed file is not remembered"); + settle(); + check(&path).expect("settled"); + check(&path).expect("later launch"); + check(&path).expect("later launch"); + assert_eq!(hash_count(), 3, "hashed once while unchanged"); + + // Rewritten in place (same inode, same size as the good file). + let mut same_size = bad[..good.len()].to_vec(); + same_size[0] = b'X'; + fs::write(&path, &same_size).unwrap(); + assert!( + check(&path).is_err(), + "a rewrite is hashed again and refused" + ); + assert!(check(&path).is_err(), "a refused file is never remembered"); + assert_eq!(hash_count(), 5); + + // Good again, then replaced by rename (a new inode). + fs::write(&path, good).unwrap(); + settle(); + check(&path).expect("good content again"); + let replacement = directory.path().join("replacement"); + fs::write(&replacement, bad).unwrap(); + fs::set_permissions(&replacement, fs::Permissions::from_mode(0o755)).unwrap(); + fs::rename(&replacement, &path).unwrap(); + assert!(check(&path).is_err(), "a replaced file is hashed again"); + assert_eq!(hash_count(), 7); + + // Good again, then made non-executable: the mode is part of the stamp. + fs::write(&path, good).unwrap(); + settle(); + check(&path).expect("good content again"); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + assert!(check(&path).is_err(), "a non-executable cache is refused"); + + // A different embedded supervisor (a new driver build) never reuses + // the memory of another digest, nor does a new driver process. + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + settle(); + check(&path).expect("good and executable"); + let before = hash_count(); + assert!( + validate_host_supervisor_once(&path, sha256_bytes(bad), &validated, count).is_err() + ); + let fresh_process = Mutex::new(None); + validate_host_supervisor_once(&path, expected, &fresh_process, count) + .expect("a new process hashes again"); + assert_eq!(hash_count(), before + 2); + } + #[cfg(target_os = "linux")] #[test] fn host_supervisor_cache_rejects_wrong_content_and_installs_atomically() { @@ -1717,6 +1972,178 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + /// What the overlay writes did before the batch: one debugfs process + /// per command, in the same order. + enum LegacyOp<'a> { + Write(&'a str, &'a [u8]), + Mode(&'a str, u32), + Remove(&'a str), + } + + fn legacy_apply(image: &Path, op: &LegacyOp<'_>) { + match op { + LegacyOp::Write(guest_path, contents) => { + let parent = Path::new(guest_path).parent().unwrap(); + let mut current = String::new(); + for component in parent.components() { + let part = component.as_os_str().to_string_lossy(); + if part == "/" || part.is_empty() { + continue; + } + current.push('/'); + current.push_str(&part); + let _ = run_debugfs(image, &format!("mkdir {current}")); + } + let tmp = temporary_injection_path(image); + fs::write(&tmp, contents).unwrap(); + let guest = debugfs_quote_absolute_path(guest_path).unwrap(); + let source = debugfs_quote_argument(&tmp.to_string_lossy()).unwrap(); + let _ = run_debugfs(image, &format!("rm {guest}")); + run_debugfs(image, &format!("write {source} {guest}")).unwrap(); + fs::remove_file(&tmp).unwrap(); + } + LegacyOp::Mode(guest_path, mode) => { + let guest = debugfs_quote_absolute_path(guest_path).unwrap(); + let mode = 0o100_000 | (mode & 0o7777); + run_debugfs(image, &format!("set_inode_field {guest} mode 0{mode:o}")).unwrap(); + } + LegacyOp::Remove(guest_path) => { + let guest = debugfs_quote_absolute_path(guest_path).unwrap(); + run_debugfs(image, &format!("rm {guest}")).unwrap(); + } + } + } + + fn batch_apply(batch: &mut RootfsImageBatch, op: &LegacyOp<'_>) { + match op { + LegacyOp::Write(guest_path, contents) => batch.write_file(guest_path, contents), + LegacyOp::Mode(guest_path, mode) => batch.set_file_mode(guest_path, *mode), + LegacyOp::Remove(guest_path) => batch.remove_file(guest_path), + } + .unwrap(); + } + + fn debugfs_read(image: &Path, command: &str) -> String { + let output = e2fs_command("debugfs") + .unwrap() + .arg("-R") + .arg(command) + .arg(image) + .output() + .unwrap(); + assert!(output.status.success(), "debugfs {command}"); + String::from_utf8_lossy(&output.stdout).into_owned() + } + + /// Every entry under `dirs` as debugfs's parseable listing (inode, mode, + /// uid, gid, name, size: no timestamps) plus every regular file's bytes. + fn image_tree(image: &Path, dirs: &[&str]) -> Vec { + let mut tree = Vec::new(); + for dir in dirs { + let listing = debugfs_read(image, &format!("ls -p {dir}")); + for line in listing.lines().filter(|line| line.starts_with('/')) { + tree.push(format!("{dir} {line}")); + let fields: Vec<&str> = line.split('/').collect(); + if fields.len() > 5 && fields[2].starts_with("100") { + let path = format!("{dir}/{}", fields[5]); + let quoted = debugfs_quote_absolute_path(&path).unwrap(); + tree.push(format!( + "{path} = {:?}", + debugfs_read(image, &format!("cat {quoted}")) + )); + } + } + } + tree + } + + #[test] + fn rootfs_image_batch_writes_what_one_debugfs_per_command_wrote() { + if e2fs_command("debugfs").is_err() { + return; + } + let dir = unique_temp_dir(); + let source = dir.join("source"); + fs::create_dir_all(source.join("upper/etc/openshell/init.d")).unwrap(); + fs::write(source.join("upper/etc/openshell/init.d/stale"), "old\n").unwrap(); + let legacy = dir.join("legacy.ext4"); + let batched = dir.join("batched.ext4"); + create_ext4_image_from_dir_with_size(&source, &legacy, 64 * 1024 * 1024).unwrap(); + fs::copy(&legacy, &batched).unwrap(); + + // The launch's shape: drop-ins (an existing one replaced), a + // manifest, credentials 0600 in a new nested directory, a removal, + // and the harmless failures (mode or removal of a missing file). + let ops = [ + LegacyOp::Write("/upper/etc/openshell/init.d/stale", b"new\n"), + LegacyOp::Mode("/upper/etc/openshell/init.d/stale", 0o755), + LegacyOp::Write("/upper/etc/openshell/init.d/two", b"#!/bin/sh\n"), + LegacyOp::Mode("/upper/etc/openshell/init.d/two", 0o755), + LegacyOp::Write("/upper/etc/openshell/init.d.manifest", b"stale\ntwo\n"), + LegacyOp::Mode("/upper/etc/openshell/init.d.manifest", 0o644), + LegacyOp::Write("/upper/.openshell/boundary/sandbox-g1.key", b"key"), + LegacyOp::Mode("/upper/.openshell/boundary/sandbox-g1.key", 0o600), + LegacyOp::Write("/upper/.openshell/boundary/with space.json", b"{}"), + LegacyOp::Remove("/upper/.openshell/boundary/sandbox-g1.key"), + LegacyOp::Write("/upper/.openshell/boundary/sandbox-g1.key", b"key2"), + LegacyOp::Remove("/upper/missing"), + LegacyOp::Mode("/upper/missing", 0o600), + ]; + for op in &ops { + legacy_apply(&legacy, op); + } + let mut batch = RootfsImageBatch::new(&batched); + for op in &ops { + batch_apply(&mut batch, op); + } + batch.commit().expect("one debugfs run"); + + let dirs = [ + "/upper", + "/upper/etc/openshell", + "/upper/etc/openshell/init.d", + "/upper/.openshell", + "/upper/.openshell/boundary", + ]; + let expected = image_tree(&legacy, &dirs); + assert!( + expected + .iter() + .any(|entry| entry.contains("100755/0/0/stale/4/")), + "{expected:#?}" + ); + assert_eq!(image_tree(&batched, &dirs), expected); + assert!( + fs::read_dir(&dir).unwrap().all(|entry| !entry + .unwrap() + .file_name() + .to_string_lossy() + .contains("inject")), + "staged contents are removed after the run" + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn rootfs_image_batch_refuses_a_path_debugfs_reads_as_two_lines() { + let dir = unique_temp_dir(); + fs::create_dir_all(&dir).unwrap(); + let image = dir.join("overlay.ext4"); + let mut batch = RootfsImageBatch::new(&image); + batch.write_file("/upper/ok", b"staged").unwrap(); + assert!(batch.write_file("/upper/a\nrm /etc/x", b"x").is_err()); + assert!(batch.write_file("/upper/a\nb/file", b"x").is_err()); + assert!(batch.set_file_mode("/upper/a\rb", 0o600).is_err()); + assert!(batch.remove_file("relative").is_err()); + assert_eq!(batch.commands.len(), 3, "only the valid write is staged"); + drop(batch); + assert!( + fs::read_dir(&dir).unwrap().next().is_none(), + "a dropped batch removes its staged contents" + ); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn ext4_image_has_directory_distinguishes_directories_files_and_missing_paths() { if e2fs_command("debugfs").is_err() {