diff --git a/Cargo.lock b/Cargo.lock index 828302110b..beeabf6267 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2304,6 +2304,7 @@ dependencies = [ "thiserror 1.0.69", "trident_api", "uuid", + "walkdir", "which", "xattr", ] @@ -4022,6 +4023,7 @@ dependencies = [ "trident_api", "url", "uuid", + "walkdir", "zstd", ] diff --git a/Cargo.toml b/Cargo.toml index d8ca24c9ce..43d8b953e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -121,6 +121,7 @@ tracing-journald = "0.3.0" tracing-subscriber = { version = "0.3.19", features = ["json"] } url = { version = "2.5.4", features = ["serde"] } uuid = { version = "1.11.0", features = ["serde", "v4"] } +walkdir = "2.5.0" which = "6.0.3" xattr = "1.3.1" zstd = "0.13.3" diff --git a/crates/osutils/Cargo.toml b/crates/osutils/Cargo.toml index ae373c844d..8ff71122a2 100644 --- a/crates/osutils/Cargo.toml +++ b/crates/osutils/Cargo.toml @@ -34,6 +34,7 @@ sys-mount = {workspace = true} tempfile = {workspace = true} thiserror = {workspace = true} uuid = {workspace = true} +walkdir = {workspace = true} which = {workspace = true} xattr = {workspace = true} regex = {workspace = true} diff --git a/crates/osutils/src/files.rs b/crates/osutils/src/files.rs index 0ac46d6b82..14a0246b2e 100644 --- a/crates/osutils/src/files.rs +++ b/crates/osutils/src/files.rs @@ -6,12 +6,13 @@ use std::{ linux::fs::MetadataExt, unix::fs::{MetadataExt as UnixMetadataExt, PermissionsExt}, }, - path::{Path, PathBuf}, + path::{self, Path, PathBuf}, }; -use anyhow::{anyhow, bail, Context, Error}; +use anyhow::{anyhow, bail, ensure, Context, Error}; use nix::unistd::{self, Gid, Uid}; use tempfile::NamedTempFile; +use walkdir::WalkDir; /// Creates a file and all parent directories if they don't exist pub fn create_file(path: S) -> Result @@ -198,6 +199,93 @@ where }) } +/// Canonicalizes the longest existing prefix, then appends any missing components. +/// +/// Resolves symlinks in the existing prefix without requiring the full path to +/// exist. Errors other than "not found" are propagated. +fn canonicalize_allow_missing(path: &Path) -> Result { + match fs::canonicalize(path) { + Ok(path) => Ok(path), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(canonicalize_allow_missing( + path.parent().context("Missing path parent")?, + )? + .join(path.file_name().context("Missing path name")?)), + Err(error) => Err(error.into()), + } +} + +/// Rejects equal paths or either path containing the other. +/// Resolves existing ancestors, including links, even when a suffix does not exist yet. +pub fn ensure_disjoint_paths(from: impl AsRef, to: impl AsRef) -> Result<(), Error> { + let from = canonicalize_allow_missing(&path::absolute(from)?)?; + let to = canonicalize_allow_missing(&path::absolute(to)?)?; + ensure!( + !from.starts_with(&to) && !to.starts_with(&from), + "Source and destination paths overlap" + ); + Ok(()) +} + +/// Copies a regular file or directory tree, preserving empty directories. +/// +/// Rejects overlapping paths, source links and special files. Callers must ensure +/// that the destination tree and its ancestors contain no symlinks, and that no +/// destination file is a hard link to a source file. These conditions are not +/// checked: destination symlinks are followed, and hard-linked aliases can truncate +/// source files. Extra destination entries are retained; errors can leave a partial +/// copy, so callers needing preflight validation must perform it separately. +pub fn copy_recursively(from: impl AsRef, to: impl AsRef) -> Result<(), Error> { + let from = from.as_ref(); + let to = to.as_ref(); + ensure_disjoint_paths(from, to)?; + for entry in WalkDir::new(from) + .follow_links(false) + .follow_root_links(false) + { + let entry = entry?; + let destination = if entry.depth() == 0 { + to.to_path_buf() + } else { + to.join(entry.path().strip_prefix(from)?) + }; + if entry.file_type().is_dir() { + fs::create_dir_all(&destination).with_context(|| { + format!( + "Failed to create destination directory: {}", + destination.display() + ) + })?; + } else { + ensure!( + entry.file_type().is_file(), + "Not a regular file: {}", + entry.path().display() + ); + fs::copy(entry.path(), &destination).with_context(|| { + format!( + "Failed to copy '{}' to '{}'", + entry.path().display(), + destination.display() + ) + })?; + } + } + Ok(()) +} + +/// Removes a file, link or directory tree without following a root link. +/// Missing entries are ignored. +pub fn remove_recursively_if_exists(path: impl AsRef) -> Result<(), Error> { + let path = path.as_ref(); + match fs::symlink_metadata(path) { + Ok(metadata) if metadata.is_dir() => fs::remove_dir_all(path)?, + Ok(_) => fs::remove_file(path)?, + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + Ok(()) +} + /// Read the current process umask from `/proc/self/status` (thread-safe). fn read_umask() -> Result { let status = @@ -332,8 +420,105 @@ fn atomic_write_file_inner( mod tests { use super::*; + use std::os::unix::fs as unix_fs; + + use nix::sys::stat::Mode; use tempfile::tempdir; + #[test] + fn test_copy_recursively_preserves_empty_directories_and_root_files() { + let temp = tempdir().unwrap(); + let source = temp.path().join("source"); + let destination = temp.path().join("destination"); + fs::create_dir_all(source.join("nested/empty")).unwrap(); + fs::write(source.join("nested/payload.new"), b"payload").unwrap(); + fs::create_dir_all(&destination).unwrap(); + fs::write(destination.join("retained"), b"retained").unwrap(); + copy_recursively(&source, &destination).unwrap(); + assert!(destination.join("nested/empty").is_dir()); + assert_eq!( + fs::read(destination.join("nested/payload.new")).unwrap(), + b"payload" + ); + assert_eq!(fs::read(destination.join("retained")).unwrap(), b"retained"); + let file = temp.path().join("file"); + copy_recursively(source.join("nested/payload.new"), &file).unwrap(); + assert_eq!(fs::read(&file).unwrap(), b"payload"); + copy_recursively(&source, source.join("child")).unwrap_err(); + assert!(!source.join("child").exists()); + } + + #[test] + fn test_copy_recursively_reports_failed_file_paths() { + let temp = tempdir().unwrap(); + let source = temp.path().join("source"); + let destination = temp.path().join("destination"); + fs::create_dir(&source).unwrap(); + fs::create_dir_all(destination.join("payload")).unwrap(); + fs::write(source.join("payload"), b"payload").unwrap(); + + let error = copy_recursively(&source, &destination).unwrap_err(); + let message = error.to_string(); + assert!(message.contains(source.join("payload").to_str().unwrap())); + assert!(message.contains(destination.join("payload").to_str().unwrap())); + assert_eq!(fs::read(source.join("payload")).unwrap(), b"payload"); + assert!(destination.join("payload").is_dir()); + } + + #[test] + fn test_copy_recursively_rejects_source_links_and_special_files() { + let temp = tempdir().unwrap(); + let outside = temp.path().join("outside"); + fs::create_dir(&outside).unwrap(); + fs::write(outside.join("payload"), b"outside").unwrap(); + let file_link = temp.path().join("file-link"); + let directory_link = temp.path().join("directory-link"); + let fifo = temp.path().join("fifo"); + unix_fs::symlink(outside.join("payload"), &file_link).unwrap(); + unix_fs::symlink(&outside, &directory_link).unwrap(); + unistd::mkfifo(&fifo, Mode::S_IRUSR).unwrap(); + for source in [&file_link, &directory_link, &fifo] { + let destination = temp.path().join("destination"); + copy_recursively(source, &destination).unwrap_err(); + assert!(!destination.exists()); + } + assert_eq!(fs::read(outside.join("payload")).unwrap(), b"outside"); + } + + #[test] + fn test_ensure_disjoint_paths_resolves_existing_ancestors() { + let temp = tempdir().unwrap(); + let source = temp.path().join("source"); + let alias = temp.path().join("alias"); + fs::create_dir(&source).unwrap(); + unix_fs::symlink(&source, &alias).unwrap(); + ensure_disjoint_paths(&source, &alias).unwrap_err(); + ensure_disjoint_paths(&source, alias.join("missing/child")).unwrap_err(); + ensure_disjoint_paths(alias.join("missing/child"), &source).unwrap_err(); + ensure_disjoint_paths(&source, temp.path().join("other/missing")).unwrap(); + } + + #[test] + fn test_remove_recursively_if_exists_preserves_link_targets() { + let temp = tempdir().unwrap(); + let outside = temp.path().join("outside"); + fs::create_dir(&outside).unwrap(); + fs::write(outside.join("payload"), b"outside").unwrap(); + let link = temp.path().join("link"); + unix_fs::symlink(&outside, &link).unwrap(); + remove_recursively_if_exists(&link).unwrap(); + remove_recursively_if_exists(&link).unwrap(); + assert!(!link.exists()); + assert_eq!(fs::read(outside.join("payload")).unwrap(), b"outside"); + let entry = temp.path().join("entry"); + fs::create_dir_all(entry.join("nested")).unwrap(); + fs::write(entry.join("nested/payload"), b"payload").unwrap(); + remove_recursively_if_exists(&entry).unwrap(); + fs::write(&entry, b"file").unwrap(); + remove_recursively_if_exists(&entry).unwrap(); + assert!(!entry.exists()); + } + #[test] fn test_create_file() { let dir = tempdir().unwrap(); diff --git a/crates/osutils/src/osrelease.rs b/crates/osutils/src/osrelease.rs index bcac756dc8..96019cf689 100644 --- a/crates/osutils/src/osrelease.rs +++ b/crates/osutils/src/osrelease.rs @@ -31,6 +31,11 @@ pub fn is_azl3() -> Result { Ok(OsRelease::read()?.get_distro().is_azl3()) } +/// Returns whether the host is running the ACL image. +pub fn is_acl() -> Result { + Ok(OsRelease::read()?.get_distro().is_acl()) +} + /// Splits one os-release-style `KEY=VALUE` line into its key and /// unquoted/trimmed value, or `None` for a blank, comment, or malformed /// line. Shared by [`read_key`], [`OsRelease::parse`], and diff --git a/crates/sysdefs/src/acl.rs b/crates/sysdefs/src/acl.rs index 4e85e46538..e50c61b35d 100644 --- a/crates/sysdefs/src/acl.rs +++ b/crates/sysdefs/src/acl.rs @@ -1,10 +1,13 @@ //! Azure Container Linux (ACL) system definitions. //! -//! Fixed PARTUUIDs and partition type UUIDs for the ACL UKI disk layout, +//! ESP mount point, fixed PARTUUIDs and partition type UUIDs for the ACL UKI disk layout, //! sourced from acl-scripts disk_layout_uki.json. use uuid::{uuid, Uuid}; +/// ACL EFI System Partition mount point. +pub const ACL_ESP_MOUNT_POINT: &str = "/boot"; + /// ACL USR partition A PARTUUID. pub const ACL_USR_A_PARTUUID: Uuid = uuid!("7130c94a-213a-4e5a-8e26-6cce9662f132"); diff --git a/crates/sysdefs/src/arch.rs b/crates/sysdefs/src/arch.rs index d2b5b34ab5..8fee136ca2 100644 --- a/crates/sysdefs/src/arch.rs +++ b/crates/sysdefs/src/arch.rs @@ -26,6 +26,11 @@ impl SystemArchitecture { SystemArchitecture::Aarch64 } } + + /// Returns whether this is the 64-bit x86 architecture. + pub const fn is_x64(&self) -> bool { + matches!(self, Self::Amd64) + } } impl<'de> Deserialize<'de> for SystemArchitecture { diff --git a/crates/trident/Cargo.toml b/crates/trident/Cargo.toml index 3543d1b5ac..e57acfd80c 100644 --- a/crates/trident/Cargo.toml +++ b/crates/trident/Cargo.toml @@ -57,6 +57,7 @@ tracing-journald = { workspace = true } tracing-subscriber = { workspace = true } url = { workspace = true } uuid = { workspace = true } +walkdir = { workspace = true } zstd = { workspace = true } # gRPC API Dependencies diff --git a/crates/trident/src/engine/boot/mod.rs b/crates/trident/src/engine/boot/mod.rs index 891b9b66c0..745e2a7539 100644 --- a/crates/trident/src/engine/boot/mod.rs +++ b/crates/trident/src/engine/boot/mod.rs @@ -12,6 +12,7 @@ use crate::engine::Subsystem; use super::EngineContext; pub(super) mod grub; +pub(crate) mod mshv; pub mod uki; pub(crate) const ESP_EXTRACTION_DIRECTORY: &str = VAR_TMP_PATH; diff --git a/crates/trident/src/engine/boot/mshv.rs b/crates/trident/src/engine/boot/mshv.rs new file mode 100644 index 0000000000..bc51cc0bb9 --- /dev/null +++ b/crates/trident/src/engine/boot/mshv.rs @@ -0,0 +1,72 @@ +//! Validates MSHV boot components independently of the surrounding bootloader chain. + +use std::{fs, io::ErrorKind, path::Path}; + +use anyhow::{ensure, Context, Error}; + +use crate::subsystems::esp::boot_tree; + +const MSHV_BOOT_FILES: &[&str] = &["HvLoader.efi", "lxhvloader.dll"]; +const MSHV_BOOT_COMPONENTS_DIR: &str = "Windows"; + +/// Detects MSHV components in a slot or fallback BOOT directory. +/// +/// Any loader filename or Windows entry triggers validation of both required +/// loaders and the optional Windows tree. Returns true only after validation; +/// partial components are an error, not an ordinary non-MSHV directory. +/// Returns false when no markers exist, including when the directory is absent. +/// Filesystem inspection errors propagate without modifying the directory. +pub(crate) fn has_slot_mshv_boot_components(boot_dir: &Path) -> Result { + for marker in MSHV_BOOT_FILES + .iter() + .copied() + .chain([MSHV_BOOT_COMPONENTS_DIR]) + { + match fs::symlink_metadata(boot_dir.join(marker)) { + Ok(_) => { + validate_boot_components(boot_dir)?; + return Ok(true); + } + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error).context("Failed to inspect MSHV boot components"), + } + } + Ok(false) +} + +/// Requires regular HvLoader.efi and lxhvloader.dll files in `boot_dir`. +/// +/// Windows is optional, but when present must be a directory tree containing +/// only regular files/directories, with no links or reserved replacement names. +/// Checks filesystem structure, not binary contents or runtime hypervisor identity. +/// Supporting bootloaders, including ETL's second stage, are validated separately. +/// This function does not modify the directory. +pub(crate) fn validate_boot_components(boot_dir: &Path) -> Result<(), Error> { + for name in MSHV_BOOT_FILES { + let path = boot_dir.join(name); + ensure!( + fs::symlink_metadata(&path) + .with_context(|| format!("Missing MSHV boot component: {name}"))? + .is_file(), + "Invalid MSHV boot component: {name}" + ); + } + let windows = boot_dir.join(MSHV_BOOT_COMPONENTS_DIR); + match fs::symlink_metadata(&windows) { + Ok(_) => { + boot_tree::filepaths(&windows)?; + } + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error).context("Failed to inspect MSHV boot component directory"), + } + Ok(()) +} + +#[cfg(test)] +pub(crate) const MSHV_SLOT_BOOT_FILES: &[&str] = &[ + "bootx64.efi", + "grubx64.efi", + "second.efi", + "HvLoader.efi", + "lxhvloader.dll", +]; diff --git a/crates/trident/src/engine/boot/uki.rs b/crates/trident/src/engine/boot/uki.rs index e0c1ccf965..8cdd222c51 100644 --- a/crates/trident/src/engine/boot/uki.rs +++ b/crates/trident/src/engine/boot/uki.rs @@ -221,73 +221,91 @@ fn remove_uki_and_addons(path: &Path) -> Result<(), Error> { } /// Cleans up old UKIs for the target slot before staging a new one, freeing -/// ESP space. This runs for all UKI-based A/B updates (not just ACL) because +/// ESP space. This runs for all UKI-based A/B updates (not just ACL) because /// ESP space constraints are a general concern. /// /// When staging a UKI for slot X on OS N, the old slot X/OS N UKI is being /// replaced and can be removed. Other slots and other OS indices are preserved. +/// Each selected UKI's addon directory is removed with it. /// /// Removes: -/// 1. Trident-managed UKIs matching the target slot+os-index (e.g. all `azla0` +/// 1. Trident-managed UKIs matching the target slot+OS-index (e.g. all `azla0` /// files when staging for slot A OS 0, regardless of update index). -/// 2. Non-trident-managed (original install) UKIs, but only when a -/// trident-managed UKI for the *active* slot+os-index already exists — -/// meaning trident has taken over boot management and the original install -/// UKI is no longer the sole rollback. +/// 2. Non-Trident-managed (original install) UKIs, but only for OS index 0 +/// when a Trident-managed UKI for its active slot already exists, so the +/// original install UKI is no longer the sole rollback. +/// 3. Interrupted staging's temporary UKI and any orphaned addon directory. pub fn cleanup_ukis_before_staging( ctx: &EngineContext, mount_point: &Path, esp_mount_path: &Path, ) -> Result<(), Error> { let esp_uki_directory = join_relative(mount_point, esp_mount_path).join(UKI_DIRECTORY); + for path in find_ukis_to_remove_before_staging(ctx, &esp_uki_directory)? { + debug!("Pre-staging cleanup: removing old UKI '{}'", path.display()); + remove_uki_and_addons(&path)?; + } + Ok(()) +} + +/// Selects UKIs to discard before staging, without modifying the ESP. +/// +/// Candidates include all generations of the target slot/install and interrupted +/// staging. Managed UKIs for the active slot and other installations are retained. +/// Original-image UKIs are eligible only for install 0, once a managed active-slot +/// UKI exists to retain as rollback. +/// +/// Returns UKI paths; the caller also removes their companion addon directories. +/// The temporary UKI path may be absent, allowing cleanup of orphaned staging +/// addons. A missing UKI directory yields no candidates. +fn find_ukis_to_remove_before_staging( + ctx: &EngineContext, + esp_uki_directory: &Path, +) -> Result, Error> { + let mut removals = Vec::new(); if !esp_uki_directory.exists() { - return Ok(()); + return Ok(removals); } + // Reclaim interrupted staging, including orphaned addons. + removals.push(esp_uki_directory.join(TMP_UKI_NAME)); + let target_slot = target_slot_os_id(ctx); let target_suffix = format!("{target_slot}.efi"); let active_slot = active_slot_os_id(ctx); let active_suffix = format!("{active_slot}.efi"); - let trident_ukis = enumerate_trident_managed_ukis(&esp_uki_directory)?; + let trident_ukis = enumerate_trident_managed_ukis(esp_uki_directory)?; - // 1. Remove trident-managed UKIs for the target slot+os-index - // (all update indices, e.g. vmlinuz-100-azla0.efi, vmlinuz-102-azla0.efi). + // Select Trident-managed UKIs for the target slot+OS-index, across all + // update indices (e.g. vmlinuz-100-azla0.efi, vmlinuz-102-azla0.efi). for (_index, suffix, path) in &trident_ukis { if *suffix == target_suffix { - debug!( - "Pre-staging cleanup: removing old target-slot UKI '{}'", - path.display() - ); - remove_uki_and_addons(path)?; + removals.push(path.clone()); } } - // 2. Remove non-trident-managed UKIs only if: - // - This is install_index 0 (the OS that placed the original UKI), AND - // - Trident already manages the active slot (proving the original is - // superseded as rollback). - // In multiboot, install_index > 0 never owns the original UKI — it has - // OS 0's partition refs baked in and can't boot other OS instances. - // Note: this intentionally does NOT require both slots to be managed. - // The ESP (~125 MB) cannot hold 3 UKIs (~50 MB each), so the original - // must be removed before staging to free space. Staging already breaks - // rollback to the original, so deleting it here is acceptable. + // Select non-Trident-managed UKIs only if: + // - This is install_index 0 (the OS that placed the original UKI), AND + // - Trident already manages the active slot, so the original UKI is + // superseded as rollback. + // In multiboot, install_index > 0 never owns the original UKI: it has + // OS 0's partition references baked in and cannot boot other OS instances. + // This intentionally does not require both slots to be managed. For + // example, a roughly 125 MB ESP cannot hold three roughly 50 MB UKIs. + // Removing the original before staging frees space while retaining the + // managed active slot as rollback. let has_active_slot_uki = trident_ukis .iter() .any(|(_index, suffix, _)| *suffix == active_suffix); if has_active_slot_uki && ctx.install_index == 0 { - let non_trident_ukis = enumerate_non_trident_managed_ukis(&esp_uki_directory)?; + let non_trident_ukis = enumerate_non_trident_managed_ukis(esp_uki_directory)?; for (_version, path) in non_trident_ukis { - debug!( - "Pre-staging cleanup: removing superseded original UKI '{}'", - path.display() - ); - remove_uki_and_addons(&path)?; + removals.push(path); } } - Ok(()) + Ok(removals) } /// Enumerates existing UKIs managed by Trident (defined by naming convention: vmlinuz--azl.efi) @@ -1599,6 +1617,40 @@ mod tests { (mount, esp_uki_dir) } + #[test] + fn test_cleanup_ukis_reclaims_interrupted_staging() { + for staged_uki_exists in [true, false] { + let ctx = make_ctx(Some(AbVolumeSelection::VolumeA), 0); + let (mount, uki_dir) = setup_esp_for_cleanup(&["vmlinuz-101-azla0.efi"]); + let staged_uki = uki_dir.join(TMP_UKI_NAME); + if staged_uki_exists { + fs::write(&staged_uki, b"partial-uki").unwrap(); + } + let staged_addons = uki::uki_addon_dir(&staged_uki); + fs::create_dir_all(&staged_addons).unwrap(); + fs::write(staged_addons.join("cmdline.addon.efi"), b"partial-addon").unwrap(); + let active_uki = uki_dir.join("vmlinuz-101-azla0.efi"); + let active_addons = uki::uki_addon_dir(&active_uki); + fs::create_dir_all(&active_addons).unwrap(); + fs::write(active_addons.join("cmdline.addon.efi"), b"retained").unwrap(); + + cleanup_ukis_before_staging( + &ctx, + mount.path(), + Path::new(DEFAULT_ESP_MOUNT_POINT_PATH), + ) + .unwrap(); + + assert!(!staged_uki.exists()); + assert!(!staged_addons.exists()); + assert!(active_uki.exists()); + assert_eq!( + fs::read(active_addons.join("cmdline.addon.efi")).unwrap(), + b"retained", + ); + } + } + /// Validates that cleanup removes only UKIs matching the target slot+os-index /// (exact suffix match), not UKIs for other slots or OS indices. #[test] diff --git a/crates/trident/src/engine/context/mod.rs b/crates/trident/src/engine/context/mod.rs index f0ed166334..32cc41d675 100644 --- a/crates/trident/src/engine/context/mod.rs +++ b/crates/trident/src/engine/context/mod.rs @@ -191,7 +191,6 @@ impl EngineContext { }) } - #[allow(dead_code)] pub(crate) fn bootloader(&self) -> Option<&Bootloader> { self.bootloader.as_ref() } diff --git a/crates/trident/src/engine/rollback.rs b/crates/trident/src/engine/rollback.rs index 1d5947acda..dac9192c5a 100644 --- a/crates/trident/src/engine/rollback.rs +++ b/crates/trident/src/engine/rollback.rs @@ -36,11 +36,14 @@ pub enum BootValidationResult { ValidBootHealthCheckFailed(TridentError), } -/// Validates that the firmware did not perform a rollback, i.e. correctly booted from the updated -/// target OS image. +/// Validates that the firmware correctly booted from the expected target OS +/// image rather than rolling back, and reconciles the Host Status accordingly. /// -/// If the firmware did not boot from the expected boot device, this function will return an error. -/// In either case, the function will update the Host Status. +/// A successful finalized boot continues the commit process. An unexpected boot +/// device returns an error, updating Host Status where rollback reconciliation +/// requires it. Trial A/B health-check failures can request +/// recovery; failed recovery returns an error without another rollback or +/// changing Host Status. #[tracing::instrument(skip_all)] pub fn validate_boot(datastore: &mut DataStore) -> Result { info!("Validating whether host correctly booted from target OS image"); @@ -51,8 +54,9 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result datastore.host_status().ab_active_volume, - // For AbUpdateHealthCheckFailed, use the opposite active volume of the one - // set in Host Status + // For AbUpdateHealthCheckFailed, use + // the opposite of the active volume set in Host Status, so recovery + // validates the retained servicing OS rather than the failed candidate. ServicingState::AbUpdateHealthCheckFailed => { match datastore.host_status().ab_active_volume { Some(AbVolumeSelection::VolumeB) => Some(AbVolumeSelection::VolumeA), @@ -77,9 +81,19 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result ServicingType::NoActiveServicing, }; + // Recovery validates the retained OS, not the failed candidate. + let recovering = matches!( + current_servicing_state, + ServicingState::AbUpdateHealthCheckFailed + ); + let expected_spec = if recovering { + datastore.host_status().spec_old.clone() + } else { + datastore.host_status().spec.clone() + }; // Create an EngineContext based on the Host Status let ctx = EngineContext::new(EngineContextParams { - spec: datastore.host_status().spec.clone(), + spec: expected_spec, spec_old: datastore.host_status().spec_old.clone(), servicing_type, is_stream_image: false, @@ -104,6 +118,7 @@ pub fn validate_boot(datastore: &mut DataStore) -> Result Result { - // For A/B Update, when health checks previously failed and host - // failed to rollback, i.e boot from the servicing OS, report error - // and leave host status alone + // For an A/B update whose health checks failed, + // failure to boot back into the retained servicing OS is a failed + // recovery: report the error and leave Host Status unchanged. error!("Host failed to rollback into the servicing OS"); return Err(TridentError::new(ServicingError::AbUpdateRebootCheck { root_device_path: current_device_path.to_string_lossy().to_string(), diff --git a/crates/trident/src/init/acl/mod.rs b/crates/trident/src/init/acl/mod.rs index 5eee1c0259..f08476955c 100644 --- a/crates/trident/src/init/acl/mod.rs +++ b/crates/trident/src/init/acl/mod.rs @@ -9,10 +9,9 @@ use uuid::Uuid; use osutils::{ lsblk::{self, BlockDevice}, - osrelease::OsRelease, sfdisk::SfDisk, }; - +use sysdefs::acl::ACL_ESP_MOUNT_POINT; use trident_api::{ config::{ AbUpdate, AbVolumePair, Disk, FileSystem, FileSystemSource, HostConfiguration, @@ -23,13 +22,6 @@ use trident_api::{ BlockDeviceId, }; -/// Returns whether the host is running the ACL image. -pub fn is_acl() -> Result { - let os_release = OsRelease::read().context("Failed to read OS release information")?; - - Ok(os_release.variant_id == Some("azurecontainerlinux".to_string())) -} - /// An expected partition on the ACL root disk, identified by label, along /// with its partition type, the actual `Partition` discovered on disk (if /// any), and whether the partition is required to be present. @@ -239,7 +231,7 @@ fn inner_initial_host_status( FileSystem { device_id: Some("efi-system".to_string()), mount_point: Some(MountPoint { - path: PathBuf::from("/boot"), + path: PathBuf::from(ACL_ESP_MOUNT_POINT), options: MountOptions("umask=0077".to_string()), }), source: FileSystemSource::Image, diff --git a/crates/trident/src/init/offline/mod.rs b/crates/trident/src/init/offline/mod.rs index 18fd905c81..bb4d94d763 100644 --- a/crates/trident/src/init/offline/mod.rs +++ b/crates/trident/src/init/offline/mod.rs @@ -457,6 +457,7 @@ fn parse_lazy_partitions( /// Given a path to a Host Status file, initializes the datastore with the Host Status. /// This command can be executed offline in a chroot environment as part of MIC image customization. +/// Seeds a missing AZLA by copying the installed fallback boot tree. pub fn execute( hs_path: Option<&Path>, lazy_partitions: &[String], diff --git a/crates/trident/src/lib.rs b/crates/trident/src/lib.rs index 9cfbd301d1..bea655338d 100644 --- a/crates/trident/src/lib.rs +++ b/crates/trident/src/lib.rs @@ -12,7 +12,11 @@ use semver::Version; use url::Url; use engine::{bootentries, EngineContext, EngineContextParams}; -use osutils::{block_devices, container, dependencies::Dependency, osrelease::OsRelease}; +use osutils::{ + block_devices, container, + dependencies::Dependency, + osrelease::{self, OsRelease}, +}; use trident_api::{ config::{ HostConfiguration, HostConfigurationSource, ImageSha384, Operations, @@ -69,7 +73,13 @@ pub use crate::{ }; use crate::{ - engine::{ab_update, rollback, runtime_update, storage::rebuild, SUBSYSTEMS}, + engine::{ + ab_update, + rollback::{self, BootValidationResult}, + runtime_update, + storage::rebuild, + SUBSYSTEMS, + }, init::acl, osimage::OsImage, stream::DiskSelectionStrategy, @@ -290,6 +300,7 @@ impl Trident { Ok(()) } + /// Records operation errors, preserving the original A/B validation error if recovery fails. fn execute_and_record_error( &mut self, datastore: &mut DataStore, @@ -627,7 +638,7 @@ impl Trident { self.execute_and_record_error(datastore, |datastore| { // Ensure that the datastore exists. if !datastore.is_persistent() { - if acl::is_acl().structured(InvalidInputError::DeriveHostConfiguration).message("Failed to determine if host is running ACL")? { + if osrelease::is_acl().structured(InvalidInputError::DeriveHostConfiguration).message("Failed to determine if host is running ACL")? { // For ACL, initialize datastore with known initial state when // the datastore is not already created. let initial_host_status = acl::initial_host_status() @@ -805,12 +816,13 @@ impl Trident { self.install(datastore, Operations::all(), false, Some(image)) } + /// Validates finalized servicing/recovery and returns whether a reboot is needed. pub fn commit( &mut self, datastore: &mut DataStore, ) -> Result<(ExitKind, ServicingType), TridentError> { - // If host's servicing state is *Finalized or *HealthCheckFailed, need to - // re-evaluate the current state of the host. + // Re-evaluate finalized or health-check-failed servicing to validate + // either the target boot or the recovery boot. let servicing_state = datastore.host_status().servicing_state; if !matches!( servicing_state, @@ -841,21 +853,19 @@ impl Trident { ) }); - if rollback_result.is_ok() { - if let Some(ref orchestrator) = self.orchestrator { - orchestrator.report_success(Some( - serde_yaml::to_string(&datastore.host_status()) - .unwrap_or("Failed to serialize Host Status".into()), - )) - } - } - match rollback_result { - Ok(rollback::BootValidationResult::ValidBootProvisioned) => { + Ok(BootValidationResult::ValidBootProvisioned) => { + if let Some(ref orchestrator) = self.orchestrator { + orchestrator.report_success(Some( + serde_yaml::to_string(&datastore.host_status()) + .unwrap_or("Failed to serialize Host Status".into()), + )) + } Ok((ExitKind::Done, servicing_type)) } - Ok(rollback::BootValidationResult::ValidBootHealthCheckFailed(e)) => { - debug!("Correct boot, but health check(s) failed: {e:?}"); + Ok(BootValidationResult::ValidBootHealthCheckFailed(e)) => { + // The caller must reboot to complete automatic recovery. + debug!("Boot validation requires rollback: {e:?}"); Ok((ExitKind::NeedsReboot, servicing_type)) } Err(e) => { diff --git a/crates/trident/src/osimage/bootloader.rs b/crates/trident/src/osimage/bootloader.rs index ec0db57117..0e14c42891 100644 --- a/crates/trident/src/osimage/bootloader.rs +++ b/crates/trident/src/osimage/bootloader.rs @@ -7,7 +7,7 @@ pub(crate) struct Bootloader { } impl Bootloader { - pub(super) fn new(bootloader_type: BootloaderType, systemd_boot: Option) -> Self { + pub(crate) fn new(bootloader_type: BootloaderType, systemd_boot: Option) -> Self { Self { bootloader_type, systemd_boot, diff --git a/crates/trident/src/osimage/cosi/metadata.rs b/crates/trident/src/osimage/cosi/metadata.rs index 8061aa7166..7b2afe28eb 100644 --- a/crates/trident/src/osimage/cosi/metadata.rs +++ b/crates/trident/src/osimage/cosi/metadata.rs @@ -536,6 +536,8 @@ mod tests { use serde_json::{json, Value}; + use crate::engine::EngineContext; + const SAMPLE_SHA384: &str = "1d0f284efe3edea4b9ca3bd514fa134b17eae361ccc7a1eefeff801b9bd6604e01f21f6bf249ef030599f0c218f2ba8c"; #[test] @@ -554,21 +556,50 @@ mod tests { } #[test] - fn test_efitreeloader_mshv_systemd_boot_deserialization() { - let bootloader: Bootloader = serde_json::from_value(json!({ - "type": "efitreeloader-mshv-systemd-boot", - "systemdBoot": { - "entries": [{ - "type": "uki-standalone", - "kernel": "vmlinuz", - "path": "EFI/Linux/image.efi", - "cmdline": "quiet" + fn test_cosi_1_3_mshv_bootloader_context() { + let metadata: CosiMetadata = serde_json::from_value(json!({ + "version": "1.3", + "osArch": "x86_64", + "osRelease": "ID=test\nNAME=Test\n", + "osPackages": [], + "images": [], + "compression": { "maxWindowLog": 27 }, + "disk": { + "size": 1048576, + "lbaSize": 512, + "type": "gpt", + "gptRegions": [{ + "type": "primary-gpt", + "image": { + "path": "images/gpt.raw.zst", + "compressedSize": 4096, + "uncompressedSize": 17408, + "sha384": SAMPLE_SHA384 + } }] + }, + "bootloader": { + "type": "efitreeloader-mshv-systemd-boot", + "systemdBoot": { + "entries": [{ + "type": "uki-standalone", + "kernel": "vmlinuz", + "path": "EFI/Linux/image.efi", + "cmdline": "quiet" + }] + } } })) .unwrap(); + metadata.validate().unwrap(); - let exposed = OsImageBootloader::from(&bootloader); + let ctx = EngineContext { + bootloader: metadata.bootloader(), + ..Default::default() + }; + let exposed = ctx.bootloader().unwrap(); + assert!(exposed.uses_mshv()); + assert!(metadata.is_uki()); assert_eq!( exposed.bootloader_type(), &OsImageBootloaderType::EfitreeloaderMshvSystemdBoot diff --git a/crates/trident/src/subsystems/esp.rs b/crates/trident/src/subsystems/esp.rs index d35b291b4a..2a44e3e648 100644 --- a/crates/trident/src/subsystems/esp.rs +++ b/crates/trident/src/subsystems/esp.rs @@ -22,9 +22,9 @@ use osutils::{ use trident_api::{ config::UefiFallbackMode, constants::{ - internal_params::{DISABLE_GRUB_NOPREFIX_CHECK, PRESERVE_MSHV_ESP_PAYLOAD}, - EFI_DEFAULT_BIN_DIRECTORY, EFI_DEFAULT_BIN_RELATIVE_PATH, ESP_EFI_DIRECTORY, - GRUB2_CONFIG_FILENAME, GRUB2_CONFIG_RELATIVE_PATH, + internal_params::DISABLE_GRUB_NOPREFIX_CHECK, EFI_DEFAULT_BIN_DIRECTORY, + EFI_DEFAULT_BIN_RELATIVE_PATH, ESP_EFI_DIRECTORY, GRUB2_CONFIG_FILENAME, + GRUB2_CONFIG_RELATIVE_PATH, }, error::{InvalidInputError, ReportError, ServicingError, TridentError, TridentResultExt}, status::{AbVolumeSelection, ServicingState, ServicingType}, @@ -32,7 +32,9 @@ use trident_api::{ use crate::{ engine::{ - boot::{self, uki, ESP_EXTRACTION_DIRECTORY, ESP_EXTRACTION_DIRECTORY_MODE}, + boot::{ + self, mshv as boot_mshv, uki, ESP_EXTRACTION_DIRECTORY, ESP_EXTRACTION_DIRECTORY_MODE, + }, EngineContext, Subsystem, }, io_utils::{ @@ -40,10 +42,14 @@ use crate::{ image_streamer, read_monitor::ReadMonitor, }, + osimage::bootloader::Bootloader, }; +pub(crate) mod boot_tree; mod mshv; +const ETL_SECOND_STAGE_EFI_FILENAME: &str = "second.efi"; + #[derive(Default, Debug)] pub struct EspSubsystem; impl Subsystem for EspSubsystem { @@ -51,6 +57,11 @@ impl Subsystem for EspSubsystem { "esp" } + /// Applies slot-owned MSHV support restrictions before ESP servicing. + fn validate_host_config(&self, ctx: &EngineContext) -> Result<(), TridentError> { + mshv::validate_configuration(ctx) + } + #[tracing::instrument(name = "esp_provision", skip_all)] fn provision(&mut self, ctx: &EngineContext, mount_path: &Path) -> Result<(), TridentError> { // Perform file-based deployment of ESP images, if needed, after filesystems have been @@ -65,17 +76,19 @@ impl Subsystem for EspSubsystem { } /// Configures UEFI fallback by copying boot files to the UEFI fallback folder -/// based on the UEFI fallback mode and servicing type. +/// based on the UEFI fallback mode and servicing state. /// /// UEFI fallback is handled in two stages: -/// 1. During finalize, the appropriate boot files are copied to the UEFI fallback folder -/// based on the servicing state and UEFI fallback mode. -/// * For clean install, the target OS boot files (always volume A) are copied. -/// * For A/B update, the boot files are copied based on whether 'optimistic' (when -/// the target OS boot files are copied) or 'conservative' (no files need to be copied -/// because fallback was populated previously) is selected. -/// 2. During commit, after the target OS boot has been verified, the target OS boot files -/// are copied to the UEFI fallback folder. +/// 1. During finalize: +/// * Clean install copies the target OS boot files (always volume A). +/// * A/B update copies the candidate before boot validation in optimistic +/// mode, or the retained slot in conservative mode so fallback continues +/// to boot the previously working OS. +/// * Manual A/B rollback copies the rollback target in either enabled mode. +/// 2. During A/B update commit, after boot validation, conservative mode copies +/// the target OS boot files. Optimistic mode needs no further copy. +/// +/// Disabled fallback is unchanged. MSHV copies all slot boot files, including nested boot components. pub fn set_uefi_fallback_contents( ctx: &EngineContext, servicing_state: ServicingState, @@ -318,7 +331,11 @@ where Ok((temp_image, computed_hash)) } -/// Performs file-based update of stand-alone ESP volume by copying boot files. +/// Performs file-based update of a stand-alone ESP volume by copying boot files. +/// +/// Mounts the source ESP image, copies boot files into the selected target-slot +/// directory, and stages the UKI when applicable. Source validation precedes +/// target-slot cleanup; UKI cleanup runs only for UKI images, before boot-file copying. fn copy_file_artifacts( temp_image_path: &Path, ctx: &EngineContext, @@ -352,13 +369,13 @@ fn copy_file_artifacts( // Call helper func to copy files from mounted img dir to esp_dir_path debug!("Writing boot files to directory {}", esp_dir_path.display()); - // Generate list of filepaths to the boot files. Pass in the temp dir path where the image is - // mounted to as an argument - let boot_files = generate_boot_filepaths( - temp_mount_dir, - ctx.is_uki().unstructured("UKI setting unknown")?, - ) - .context("Failed to generate boot filepaths")?; + // Validate source files before removing target-slot UKIs or boot files. + let is_uki = ctx.is_uki().unstructured("UKI setting unknown")?; + let boot_files = generate_boot_filepaths(temp_mount_dir, is_uki, ctx.bootloader()) + .context("Failed to generate boot filepaths")?; + if is_uki { + uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; + } // Clear esp_dir_path if it exists if esp_dir_path.exists() { @@ -378,24 +395,18 @@ fn copy_file_artifacts( // Call helper func to copy boot files from temp_mount_dir to esp_dir_path let grub_noprefix = - copy_boot_files(temp_mount_dir, &esp_dir_path, boot_files).context(format!( - "Failed to copy boot files from directory {} to directory {}", - temp_mount_dir.display(), - esp_dir_path.display() - ))?; + copy_boot_files(temp_mount_dir, &esp_dir_path, boot_files).with_context(|| { + format!( + "Failed to copy boot files from directory {} to directory {}", + temp_mount_dir.display(), + esp_dir_path.display() + ) + })?; if ctx.is_uki().unstructured("UKI setting unknown")? { // Prepare ESP directory structure for UKI boot uki::prepare_esp_for_uki(mount_point, &ctx.esp_mount_path)?; - // Clean up old UKIs for the target slot before staging the new one. - // Pre-staging cleanup is necessary because the ESP may not have space - // for both old and new UKIs simultaneously (128 MB constraint). The - // trade-off: a crash between cleanup and staging removes the target - // slot's old UKI with no replacement, but the active slot's UKI is - // preserved so the system remains bootable via A/B fallback. - uki::cleanup_ukis_before_staging(ctx, mount_point, &ctx.esp_mount_path)?; - // Copy the UKI from the image into the ESP directory uki::stage_uki_on_esp(temp_mount_dir, mount_point, &ctx.esp_mount_path)?; @@ -441,32 +452,32 @@ fn copy_file_artifacts( ); } - if ctx.spec.internal_params.get_flag(PRESERVE_MSHV_ESP_PAYLOAD) { - mshv::copy_mshv_esp_payload( - temp_mount_dir, - &path::join_relative(mount_point, &ctx.esp_mount_path), - )?; - } - Ok(()) } -/// Determines the source dir name to copy the UEFI fallback boot files from. This varies -/// based on the servicing state and UEFI fallback mode. +/// Determines the source directory to copy UEFI fallback boot files from. +/// This varies based on the servicing state and UEFI fallback mode. +/// +/// 1. During finalize: +/// * Clean install uses volume A, the target OS volume. +/// * A/B update: +/// - Optimistic uses the opposite of the recorded active volume, which +/// contains the newly staged candidate's boot files. +/// - Conservative uses the recorded active volume, retaining the +/// previously working OS as fallback (this may be a redundant copy). +/// * Manual A/B rollback uses the opposite of the recorded active volume, +/// the rollback target, in either enabled mode. +/// 2. During commit, after the target OS boot has been verified: +/// * Clean install needs no copy because finalize already populated fallback. +/// * A/B update: +/// - Optimistic needs no copy because finalize already copied the candidate. +/// - Conservative uses the validated target volume from +/// `ctx.get_ab_update_volume()`. The recorded active volume still refers +/// to the pre-update OS until commit updates Host Status. /// -/// 1. During finalize -/// * For clean install, use volume A (this is the target OS volume for clean install) -/// * For A/B update -/// - 'optimistic': use the opposite of the active volume -/// - 'conservative': use the active volume (this may be a redundant copy) -/// * For manual rollback (this should only be called during manual rollback of an A/B update) -/// - use the opposite of the active volume -/// 2. During commit, after the target OS boot has been verified, the target OS boot files -/// are copied to the UEFI fallback folder. -/// * For clean install, no copy is needed as it was done during finalize -/// * For A/B update -/// - 'optimistic': no copy is needed as it was done during finalize -/// - 'conservative': use the newly active volume +/// Returns `None` to leave fallback unchanged when disabled or for unlisted +/// states. A missing active volume defaults to A for `AbUpdateStaged` and +/// `ManualRollbackAbStaged`. fn find_uefi_fallback_source_dir_name( ctx: &EngineContext, servicing_state: ServicingState, @@ -501,13 +512,11 @@ fn find_uefi_fallback_source_dir_name( _ => None, }, ServicingState::AbUpdateFinalized => match ctx.spec.os.uefi_fallback { - UefiFallbackMode::Conservative => Some(boot::make_esp_dir_name( - ctx.install_index, - match ctx.ab_active_volume { - None | Some(AbVolumeSelection::VolumeA) => AbVolumeSelection::VolumeA, - Some(AbVolumeSelection::VolumeB) => AbVolumeSelection::VolumeB, - }, - )), + UefiFallbackMode::Conservative => { + // The recorded active slot is still pre-update; copy the validated target. + ctx.get_ab_update_volume() + .map(|volume| boot::make_esp_dir_name(ctx.install_index, volume)) + } _ => None, }, ServicingState::ManualRollbackAbStaged => match ctx.spec.os.uefi_fallback { @@ -553,7 +562,12 @@ fn skip_uefi_fallback_copy( false } -/// Copies all files from 'source_esp_name' folder to the UEFI fallback folder. +/// Copies boot files from the `source_esp_name` folder to the UEFI fallback +/// folder, `EFI/BOOT`. +/// +/// Copies MSHV boot components and supporting boot files, or top-level files for ordinary +/// bootloaders, replacing existing fallback files. +/// Skips copying from an unseeded AZLA during A/B updates. fn copy_boot_files_for_uefi_fallback( mount_point: &Path, esp_mount_path: &Path, @@ -583,7 +597,8 @@ fn copy_boot_files_for_uefi_fallback( source_esp_dir_path.display(), uefi_fallback_path.display() ); - replace_boot_files(&source_esp_dir_path, &uefi_fallback_path).context(format!( + let result = boot_tree::replace_fallback_boot_files(&source_esp_dir_path, &uefi_fallback_path); + result.context(format!( "Failed to copy boot files from directory '{}' to directory '{}'", source_esp_dir_path.display(), uefi_fallback_path.display() @@ -591,132 +606,28 @@ fn copy_boot_files_for_uefi_fallback( Ok(()) } -/// Copies boot files from one folder to another. -pub fn replace_boot_files(from_dir: &Path, to_dir: &Path) -> Result<(), Error> { - trace!( - "Copying boot files from '{}' to '{}'", - from_dir.display(), - to_dir.display() - ); - // Ensure to_dir exists - fs::create_dir_all(to_dir) - .context(format!("Failed to create directory '{}'", to_dir.display()))?; - - // Copy all files from from_dir to to_dir as .new - fs::read_dir(from_dir)? - .collect::, _>>()? - .iter() - .try_for_each(|from_path| { - let to_file_name = format!("{}.new", from_path.file_name().to_string_lossy()); - let to_path = to_dir.join(to_file_name); - fs::copy(from_path.path(), &to_path).context(format!( - "Failed to copy file '{}' to '{}'", - from_path.path().display(), - to_path.display(), - ))?; - trace!( - "Copied file '{}' to '{}'", - from_path.path().display(), - to_path.display() - ); - Ok::<(), Error>(()) - }) - .context("Failed to copy files")?; - - // Rename all pre-existing files from to_dir/ to to_dir/.old - fs::read_dir(to_dir)? - .collect::, _>>()? - .iter() - .try_for_each(|orig_path| { - let orig_file_name = orig_path.file_name(); - let orig_file_name_string = orig_file_name.to_string_lossy(); - // Skip files that end with .new - if !orig_file_name_string.ends_with(".new") { - let new_file_name = format!("{orig_file_name_string}.old"); - let to_path = to_dir.join(new_file_name); - fs::rename(orig_path.path(), &to_path).context(format!( - "Failed to rename pre-existing file '{}' to '{}'", - orig_path.path().display(), - to_path.display() - ))?; - trace!( - "Renamed pre-existing file '{}' to '{}'", - orig_path.path().display(), - to_path.display() - ); - } - Ok::<(), Error>(()) - }) - .context("Failed to rename pre-existing files")?; - - // Rename all copied files from to_dir/.new to to_dir/ - fs::read_dir(to_dir)? - .collect::, _>>()? - .iter() - .try_for_each(|orig_path| { - let orig_file_name = orig_path.file_name(); - let orig_file_name_string = orig_file_name.to_string_lossy(); - // Skip files that do not end with .new - if orig_file_name_string.ends_with(".new") { - let new_file_name = orig_file_name_string.trim_end_matches(".new"); - let to_path = to_dir.join(new_file_name); - fs::rename(orig_path.path(), &to_path).context(format!( - "Failed to rename copied file '{}' to '{}'", - orig_path.path().display(), - to_path.display() - ))?; - trace!( - "Renamed copied file '{}' to '{}'", - orig_path.path().display(), - to_path.display() - ); - } - Ok::<(), Error>(()) - }) - .context("Failed to rename copied files")?; - - // Remove all preexisting files .old - fs::read_dir(to_dir)? - .collect::, _>>()? - .iter() - .try_for_each(|orig_path| { - let orig_file_name = orig_path.file_name(); - // Skip files that do not end with .old - if orig_file_name.to_string_lossy().ends_with(".old") { - fs::remove_file(orig_path.path()).context(format!( - "Failed to remove pre-existing file '{}'", - orig_path.path().display() - ))?; - trace!("Removed pre-existing file '{}'", orig_path.path().display()); - } - Ok::<(), Error>(()) - }) - .context("Failed to remove pre-existing files")?; - Ok(()) -} - -/// Ensures `EFI/AZLA` exists on the ESP, seeding it from the `EFI/BOOT` -/// fallback loader if it's missing. Used by both offline-initialize and ACL -/// lazy-adoption bootstrap, so a freshly-derived HostStatus is always backed -/// by a matching on-disk ESP layout before the first A/B update or manual -/// rollback ever runs and assumes AZLA already exists. +/// Ensures `EFI/AZLA` exists on the ESP, seeding it from the `EFI/BOOT` fallback +/// loader if it is missing. Used by offline-initialize and ACL lazy adoption so +/// a freshly derived HostStatus is backed by the expected on-disk ESP layout +/// before the first A/B update or manual rollback assumes AZLA already exists. +/// +/// Copies the complete BOOT tree and publishes it via a staged directory +/// rename only after copying succeeds. Existing AZLA is never refreshed. All boot +/// types use the same tree-structure checks, without loader-specific completeness validation. pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { let azla_esp_path = esp_path.join(ESP_EFI_DIRECTORY).join("AZLA"); + let boot_esp_path = esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH); trace!("Checking for AZLA volume ESP path at {:?}", &azla_esp_path); if !azla_esp_path.exists() { trace!( "AZLA volume ESP path {:?} does not exist, attempting to copy from fallback location", azla_esp_path ); - let boot_esp_path = esp_path.join(EFI_DEFAULT_BIN_RELATIVE_PATH); - // Stage the copy in a temporary sibling directory and publish it via // an atomic rename only once the copy has fully succeeded. Creating - // azla_esp_path directly (via replace_boot_files' create_dir_all) - // before the copy completes would leave a partially-populated - // directory behind on failure, and since this function only checks - // for *existence*, every subsequent retry would then skip - // bootstrapping entirely. + // AZLA directly before the copy completes could leave a partially + // populated directory on failure. Ordinary-mode retries would skip + // that directory because it exists instead of repairing the partial copy. let azla_tmp_path = esp_path.join(ESP_EFI_DIRECTORY).join("AZLA.bootstrap-tmp"); if azla_tmp_path.exists() { fs::remove_dir_all(&azla_tmp_path).context(format!( @@ -724,7 +635,8 @@ pub fn bootstrap_azla_from_fallback(esp_path: &Path) -> Result<(), Error> { azla_tmp_path.display() ))?; } - replace_boot_files(&boot_esp_path, &azla_tmp_path).context(format!( + let copy_result = boot_tree::copy_fallback_for_bootstrap(&boot_esp_path, &azla_tmp_path); + copy_result.context(format!( "Failed to copy boot files from '{}' to temporary AZLA bootstrap path '{}'", boot_esp_path.display(), azla_tmp_path.display() @@ -757,7 +669,13 @@ fn copy_boot_files( boot_file.display() ))?; - let destination_path = esp_dir.join(file_name); + // Preserve paths beneath EFI/BOOT, including nested MSHV components. + // Files selected elsewhere, such as GRUB config, still copy by filename. + let boot_root = temp_mount_dir.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let relative = source_path + .strip_prefix(&boot_root) + .unwrap_or_else(|_| Path::new(file_name)); + let destination_path = esp_dir.join(relative); // Create directories if they don't exist if let Some(parent) = destination_path.parent() { @@ -776,8 +694,11 @@ fn copy_boot_files( destination_path.display() ))?; - // Rename grub-noprefix efi to grub efi - if file_name == GRUB_NOPREFIX_EFI { + // Normalize only the root GRUB loader, not similarly named nested files. + if relative + .to_str() + .is_some_and(|name| name.eq_ignore_ascii_case(GRUB_NOPREFIX_EFI)) + { fs::rename( &destination_path, esp_dir @@ -798,9 +719,16 @@ fn copy_boot_files( /// /// The func takes the arg temp_mount_dir, which is the path to the directory where the ESP image is mounted to. /// The is_uki parameter indicates whether the image being processed is a UKI (Unified Kernel Image), in which -/// case, grub.cfg is not needed. -fn generate_boot_filepaths(temp_mount_dir: &Path, is_uki: bool) -> Result, Error> { +/// case, grub.cfg is not needed. Efitreeloader selects the main loader without +/// GRUB noprefix substitution and requires its separate second-stage executable. +/// MSHV images additionally select validated components; UKI payloads are staged separately. +fn generate_boot_filepaths( + temp_mount_dir: &Path, + is_uki: bool, + bootloader: Option<&Bootloader>, +) -> Result, Error> { let mut paths = Vec::new(); + let uses_efitreeloader = bootloader.is_some_and(Bootloader::uses_efitreeloader); // Check if grub.cfg exists in EFI_DEFAULT_BIN_RELATIVE_PATH, otherwise use GRUB2_RELATIVE_PATH let efi_boot_grub_path = Path::new(temp_mount_dir) @@ -841,14 +769,17 @@ fn generate_boot_filepaths(temp_mount_dir: &Path, is_uki: bool) -> Result Result Result, Error> { + // Require HvLoader.efi and lxhvloader.dll as regular files, and validate + // the optional Windows tree's structure before any target-slot cleanup. + boot_mshv::validate_boot_components(source_boot_dir)?; + let mut paths = Vec::new(); + // Include nested Windows components and future image-specific files; + // the staging copier preserves their BOOT-relative paths. + for component in boot_tree::filepaths(source_boot_dir)? { + let relative = component.strip_prefix(source_boot_dir)?; + let name = relative.to_str().context("Non-UTF-8 boot file path")?; + // Keep root loader/config selection under generate_boot_filepaths. + // Re-adding an unselected noprefix binary could overwrite efitreeloader + // during copy-time normalization. Nested same-named files are retained. + if [ + BOOT_EFI, + GRUB_EFI, + GRUB_NOPREFIX_EFI, + GRUB2_CONFIG_FILENAME, + ETL_SECOND_STAGE_EFI_FILENAME, + ] + .iter() + .any(|ordinary| name.eq_ignore_ascii_case(ordinary)) + { + continue; + } + paths.push(component); + } Ok(paths) } @@ -920,23 +896,216 @@ fn generate_efi_bin_base_dir_path( mod tests { use super::*; - use std::io::Write; - - use fs::File; + use std::{fs::File, io::Write}; - use crate::engine::{ - boot::{get_update_esp_dir_name, make_esp_dir_name_candidates}, - install_index, - }; use trident_api::{ config::{HostConfiguration, Os}, - constants::DEFAULT_ESP_RELATIVE_MOUNT_POINT_PATH, - }; - use trident_api::{ - constants::GRUB2_RELATIVE_PATH, + constants::{DEFAULT_ESP_RELATIVE_MOUNT_POINT_PATH, GRUB2_RELATIVE_PATH}, status::{AbVolumeSelection, ServicingType}, }; + use crate::{ + engine::{ + boot::{ + get_update_esp_dir_name, make_esp_dir_name_candidates, mshv::MSHV_SLOT_BOOT_FILES, + }, + install_index, + }, + osimage::bootloader::BootloaderType, + }; + + #[test] + fn test_boot_tree_staging_uses_shared_copying_for_etl_and_mshv() { + let (source, esp, ctx) = boot_file_staging_fixture(true, true); + let components = source + .path() + .join(EFI_DEFAULT_BIN_RELATIVE_PATH) + .join("Windows/System32/drivers"); + fs::create_dir_all(&components).unwrap(); + fs::write(components.join("future.dll"), b"component").unwrap(); + fs::write(components.join(GRUB_NOPREFIX_EFI), b"nested component").unwrap(); + let future = source + .path() + .join(EFI_DEFAULT_BIN_RELATIVE_PATH) + .join("FutureSupport/deep"); + fs::create_dir_all(&future).unwrap(); + fs::write(future.join("support.bin"), b"future support").unwrap(); + fs::write( + source + .path() + .join(EFI_DEFAULT_BIN_RELATIVE_PATH) + .join("future-loader.dll"), + b"future loader", + ) + .unwrap(); + fs::write( + source + .path() + .join(EFI_DEFAULT_BIN_RELATIVE_PATH) + .join(GRUB_NOPREFIX_EFI), + b"unrelated GRUB binary", + ) + .unwrap(); + let files = generate_boot_filepaths(source.path(), true, ctx.bootloader()).unwrap(); + assert!(files + .iter() + .any(|path| path.ends_with(ETL_SECOND_STAGE_EFI_FILENAME))); + let target = esp.path().join("EFI/AZL2B"); + assert!(!copy_boot_files(source.path(), &target, files).unwrap()); + for name in [ + BOOT_EFI, + GRUB_EFI, + ETL_SECOND_STAGE_EFI_FILENAME, + "HvLoader.efi", + "lxhvloader.dll", + ] { + assert_eq!(fs::read(target.join(name)).unwrap(), b"bootloader"); + } + assert_eq!( + fs::read(target.join("Windows/System32/drivers/future.dll")).unwrap(), + b"component" + ); + assert_eq!( + fs::read( + target + .join("Windows/System32/drivers") + .join(GRUB_NOPREFIX_EFI) + ) + .unwrap(), + b"nested component" + ); + assert_eq!( + fs::read(target.join("FutureSupport/deep/support.bin")).unwrap(), + b"future support" + ); + assert_eq!( + fs::read(target.join("future-loader.dll")).unwrap(), + b"future loader" + ); + } + + #[test] + fn test_boot_tree_staging_requires_second_stage_only_for_etl() { + for name in [ETL_SECOND_STAGE_EFI_FILENAME, BOOT_EFI, GRUB_EFI] { + let (source, _esp, ctx) = boot_file_staging_fixture(true, true); + let boot = source.path().join(EFI_DEFAULT_BIN_RELATIVE_PATH); + fs::remove_file(boot.join(name)).unwrap(); + fs::create_dir(boot.join(name)).unwrap(); + boot_mshv::validate_boot_components(&boot).unwrap(); + generate_boot_filepaths(source.path(), true, ctx.bootloader()).unwrap_err(); + } + + let (source, _esp, ctx) = boot_file_staging_fixture(false, true); + fs::create_dir( + source + .path() + .join(EFI_DEFAULT_BIN_RELATIVE_PATH) + .join(ETL_SECOND_STAGE_EFI_FILENAME), + ) + .unwrap(); + let paths = generate_boot_filepaths(source.path(), true, ctx.bootloader()).unwrap(); + assert!(!paths + .iter() + .any(|path| path.ends_with(ETL_SECOND_STAGE_EFI_FILENAME))); + } + + #[test] + fn test_boot_tree_fallback_copies_all_entries_without_image_metadata() { + let esp = TempDir::new().unwrap(); + let source = esp.path().join("EFI/AZLA"); + let fallback = esp.path().join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let retained = esp.path().join("EFI/AZL2A"); + for path in [&source, &fallback, &retained] { + fs::create_dir_all(path).unwrap(); + fs::write(path.join(BOOT_EFI), b"loader").unwrap(); + } + fs::create_dir_all(source.join("future/deep")).unwrap(); + fs::create_dir_all(source.join("empty")).unwrap(); + fs::write(source.join("future/deep/component.bin"), b"future").unwrap(); + fs::write(source.join("future-loader.efi"), b"future loader").unwrap(); + fs::create_dir_all(fallback.join("retired")).unwrap(); + fs::write(fallback.join("retired/old.bin"), b"retired").unwrap(); + let ctx = EngineContext { + servicing_type: ServicingType::CleanInstall, + esp_mount_path: ".".into(), + ..Default::default() + }; + for _ in 0..2 { + set_uefi_fallback_contents(&ctx, ServicingState::CleanInstallStaged, esp.path()) + .unwrap(); + } + assert_eq!( + fs::read(fallback.join("future/deep/component.bin")).unwrap(), + b"future" + ); + assert_eq!( + fs::read(fallback.join("future-loader.efi")).unwrap(), + b"future loader" + ); + assert!(fallback.join("empty").is_dir()); + assert!(!fallback.join("retired").exists()); + assert_eq!(fs::read(retained.join(BOOT_EFI)).unwrap(), b"loader"); + } + + #[test] + fn test_boot_tree_bootstrap_preserves_non_mshv_subdirectories() { + let esp = TempDir::new().unwrap(); + let boot = esp.path().join(EFI_DEFAULT_BIN_RELATIVE_PATH); + fs::create_dir_all(boot.join("future/deep")).unwrap(); + fs::create_dir_all(boot.join("empty")).unwrap(); + fs::write(boot.join(BOOT_EFI), b"loader").unwrap(); + fs::write(boot.join("future/deep/component.bin"), b"future").unwrap(); + bootstrap_azla_from_fallback(esp.path()).unwrap(); + let slot = esp.path().join("EFI/AZLA"); + assert_eq!( + fs::read(slot.join("future/deep/component.bin")).unwrap(), + b"future" + ); + assert!(slot.join("empty").is_dir()); + assert_eq!(fs::read(boot.join(BOOT_EFI)).unwrap(), b"loader"); + } + + fn boot_file_staging_fixture(is_mshv: bool, is_uki: bool) -> (TempDir, TempDir, EngineContext) { + let source = TempDir::new().unwrap(); + let esp = TempDir::new().unwrap(); + let ctx = EngineContext { + servicing_type: ServicingType::AbUpdate, + ab_active_volume: Some(AbVolumeSelection::VolumeA), + install_index: 1, + esp_mount_path: ".".into(), + is_uki: Some(is_uki), + bootloader: Some(Bootloader::new( + if is_mshv { + BootloaderType::EfitreeloaderMshvSystemdBoot + } else { + BootloaderType::Grub + }, + None, + )), + ..Default::default() + }; + let names = if is_mshv { + MSHV_SLOT_BOOT_FILES + } else { + &[BOOT_EFI, GRUB_EFI, GRUB2_CONFIG_FILENAME] + }; + for root in [ + source.path().join(EFI_DEFAULT_BIN_RELATIVE_PATH), + esp.path() + .join(ESP_EFI_DIRECTORY) + .join(boot::make_esp_dir_name(1, AbVolumeSelection::VolumeA)), + ] { + fs::create_dir_all(&root).unwrap(); + for name in names { + fs::write(root.join(name), b"bootloader").unwrap(); + } + if !is_uki { + fs::write(root.join(GRUB2_CONFIG_FILENAME), b"configuration").unwrap(); + } + } + (source, esp, ctx) + } + #[test] fn test_generate_efi_bin_base_dir_path_clean_install() { // Clean install EngineContext @@ -1231,8 +1400,18 @@ mod tests { UefiFallbackMode::Conservative, Some(AbVolumeSelection::VolumeA), ServicingType::AbUpdate, - Some("AZLA".to_string()), // in finalize, with 'conservative', copy from active volume - "Validate AbUpdateFinalized + Conservative + active volume A ==> AZLA", + // In commit, with 'conservative', copy the validated update target; + // the recorded active volume still refers to the pre-update OS. + Some("AZLB".to_string()), + "Validate AbUpdateFinalized + Conservative + active volume A ==> AZLB", + ), + ( + ServicingState::AbUpdateFinalized, + UefiFallbackMode::Conservative, + Some(AbVolumeSelection::VolumeB), + ServicingType::AbUpdate, + Some("AZLA".to_string()), + "Validate AbUpdateFinalized + Conservative + active volume B ==> AZLA", ), ( ServicingState::AbUpdateFinalized, @@ -1334,6 +1513,51 @@ mod tests { ); } + /// Conservative commit copies the validated target, not the recorded active slot. + #[test] + fn test_conservative_commit_copies_validated_slot() { + let file_names = vec![PathBuf::from(BOOT_EFI), PathBuf::from(GRUB_EFI)]; + for (active_volume, active_name, target_name) in [ + (AbVolumeSelection::VolumeA, "AZLA", "AZLB"), + (AbVolumeSelection::VolumeB, "AZLB", "AZLA"), + ] { + let mut ctx = EngineContext { + servicing_type: ServicingType::AbUpdate, + ab_active_volume: Some(active_volume), + ..Default::default() + }; + ctx.spec.os.uefi_fallback = UefiFallbackMode::Conservative; + let mount_point = TempDir::new().unwrap(); + let retained = create_and_fill_esp(&mount_point, active_name, &file_names, "retained"); + let candidate = + create_and_fill_esp(&mount_point, target_name, &file_names, "candidate"); + let fallback = create_and_fill_esp( + &mount_point, + EFI_DEFAULT_BIN_DIRECTORY, + &file_names, + "initial-fallback", + ); + + set_uefi_fallback_contents(&ctx, ServicingState::AbUpdateStaged, mount_point.path()) + .unwrap(); + for file in &file_names { + assert!(files_are_identical( + &fallback.join(file), + &retained.join(file) + )); + } + + set_uefi_fallback_contents(&ctx, ServicingState::AbUpdateFinalized, mount_point.path()) + .unwrap(); + for file in &file_names { + assert!( + files_are_identical(&fallback.join(file), &candidate.join(file)), + "Commit with recorded active slot {active_volume:?} must copy {target_name}" + ); + } + } + } + #[test] fn test_set_uefi_fallback_contents() { // Create a list of boot files @@ -1415,7 +1639,7 @@ mod tests { } #[test] - fn test_replace_boot_files() { + fn test_replace_fallback_boot_files() { let from_dir = TempDir::new().unwrap(); let to_dir = TempDir::new().unwrap(); @@ -1445,7 +1669,7 @@ mod tests { } // Call the function to copy files - replace_boot_files(from_dir.path(), to_dir.path()).unwrap(); + boot_tree::replace_fallback_boot_files(from_dir.path(), to_dir.path()).unwrap(); // Verify that files have been copied and renamed correctly for (file_name, _content) in &file_infos { @@ -1468,6 +1692,45 @@ mod tests { } } + #[test] + fn test_replace_boot_files_retires_mshv_directory() { + for directory in ["Windows", "Windows.old", "wInDoWs.old"] { + let source = TempDir::new().unwrap(); + let destination = TempDir::new().unwrap(); + fs::write(source.path().join(BOOT_EFI), b"ordinary loader").unwrap(); + for name in MSHV_SLOT_BOOT_FILES { + fs::write(destination.path().join(name), b"previous loader").unwrap(); + } + let secondary = destination.path().join(directory).join("System32"); + fs::create_dir_all(&secondary).unwrap(); + fs::write(secondary.join("image-specific.dll"), b"previous payload").unwrap(); + + boot_tree::replace_fallback_boot_files(source.path(), destination.path()).unwrap(); + + assert_eq!( + fs::read(destination.path().join(BOOT_EFI)).unwrap(), + b"ordinary loader" + ); + assert_eq!(fs::read_dir(destination.path()).unwrap().count(), 1); + } + } + + #[test] + fn test_replace_boot_files_retires_directories_inside_owned_boot_tree() { + let source = TempDir::new().unwrap(); + let destination = TempDir::new().unwrap(); + fs::write(source.path().join(BOOT_EFI), b"ordinary loader").unwrap(); + fs::create_dir_all(destination.path().join("retired")).unwrap(); + fs::write(destination.path().join("retired/old"), b"retired data").unwrap(); + boot_tree::replace_fallback_boot_files(source.path(), destination.path()).unwrap(); + assert!(!destination.path().join("retired").exists()); + assert_eq!( + fs::read(destination.path().join(BOOT_EFI)).unwrap(), + b"ordinary loader" + ); + } + + /// Ordinary bootstrap copies top-level boot files. #[test] fn test_bootstrap_azla_from_fallback() { let esp_dir = TempDir::new().unwrap(); @@ -1498,6 +1761,7 @@ mod tests { } } + /// Ordinary bootstrap preserves even an incomplete existing AZLA. #[test] fn test_bootstrap_azla_from_fallback_is_idempotent_when_azla_already_exists() { let esp_dir = TempDir::new().unwrap(); @@ -1524,8 +1788,8 @@ mod tests { bootstrap_azla_from_fallback(esp_dir.path()).unwrap(); - // AZLA must be left untouched: bootstrap only runs when AZLA is - // absent, so a second call must be a no-op. + // AZLA must be left untouched: ordinary-mode bootstrap only runs when + // AZLA is absent, so a second call neither validates nor refreshes it. let contents = fs::read_to_string(&sentinel_path).unwrap(); assert_eq!( contents.trim(), @@ -1538,6 +1802,7 @@ mod tests { ); } + /// Retrying ordinary bootstrap discards stale staging contents. #[test] fn test_bootstrap_azla_from_fallback_cleans_up_stale_tmp_dir() { let esp_dir = TempDir::new().unwrap(); @@ -1584,6 +1849,92 @@ mod tests { } } + /// Bootstrap preserves all MSHV files but never refreshes an existing AZLA. + #[test] + fn test_bootstrap_azla_from_mshv_fallback() { + let esp = TempDir::new().unwrap(); + let boot = esp.path().join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let azla = esp.path().join(ESP_EFI_DIRECTORY).join("AZLA"); + let temporary = esp + .path() + .join(ESP_EFI_DIRECTORY) + .join("AZLA.bootstrap-tmp"); + for name in MSHV_SLOT_BOOT_FILES { + let path = boot.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, name).unwrap(); + } + let secondary = "Windows/System32/image-specific.dll"; + fs::create_dir_all(boot.join("Windows/System32")).unwrap(); + fs::write(boot.join(secondary), b"secondary").unwrap(); + fs::create_dir_all(&temporary).unwrap(); + fs::write(temporary.join("stale"), "incomplete").unwrap(); + + bootstrap_azla_from_fallback(esp.path()).unwrap(); + for name in MSHV_SLOT_BOOT_FILES { + assert!(files_are_identical(&boot.join(name), &azla.join(name))); + } + assert!(files_are_identical( + &boot.join(secondary), + &azla.join(secondary) + )); + assert!(!temporary.exists()); + + fs::write(boot.join("HvLoader.efi"), "new fallback").unwrap(); + bootstrap_azla_from_fallback(esp.path()).unwrap(); + assert_eq!( + fs::read_to_string(azla.join("HvLoader.efi")).unwrap(), + "HvLoader.efi" + ); + + fs::remove_file(azla.join(secondary)).unwrap(); + bootstrap_azla_from_fallback(esp.path()).unwrap(); + assert!(!azla.join(secondary).exists()); + fs::remove_file(azla.join("lxhvloader.dll")).unwrap(); + bootstrap_azla_from_fallback(esp.path()).unwrap(); + assert!(!azla.join("lxhvloader.dll").exists()); + } + + /// Failed source validation leaves AZLA unpublished and permits a clean retry. + #[test] + fn test_bootstrap_azla_cleans_stale_copy_before_source_validation() { + let esp = TempDir::new().unwrap(); + let boot = esp.path().join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let azla = esp.path().join(ESP_EFI_DIRECTORY).join("AZLA"); + let temporary = esp + .path() + .join(ESP_EFI_DIRECTORY) + .join("AZLA.bootstrap-tmp"); + for name in MSHV_SLOT_BOOT_FILES { + let path = boot.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"retained").unwrap(); + } + fs::create_dir_all(&temporary).unwrap(); + fs::write(temporary.join("stale"), b"abandoned copy").unwrap(); + let invalid = boot.join("component.new"); + fs::write(&invalid, b"reserved source name").unwrap(); + + let error = bootstrap_azla_from_fallback(esp.path()).unwrap_err(); + assert!(error + .root_cause() + .to_string() + .contains("Reserved boot file name")); + assert!(!temporary.exists()); + assert!(!azla.exists()); + for name in MSHV_SLOT_BOOT_FILES { + assert_eq!(fs::read(boot.join(name)).unwrap(), b"retained"); + } + + fs::remove_file(invalid).unwrap(); + bootstrap_azla_from_fallback(esp.path()).unwrap(); + assert!(!temporary.exists()); + assert!(!azla.join("stale").exists()); + for name in MSHV_SLOT_BOOT_FILES { + assert!(files_are_identical(&boot.join(name), &azla.join(name))); + } + } + /// Validates that copy_boot_files() correctly copies boot files from temp_mount_dir to esp_dir #[test] fn test_copy_boot_files_without_noprefix() { @@ -1595,7 +1946,7 @@ mod tests { PathBuf::from(GRUB2_CONFIG_FILENAME), PathBuf::from(GRUB_EFI), PathBuf::from(BOOT_EFI), - PathBuf::from(mshv::ETL_SECOND_STAGE_EFI_FILENAME), + PathBuf::from(ETL_SECOND_STAGE_EFI_FILENAME), ]; // Call helper func to create mock boot files in temp_mount_dir @@ -1635,7 +1986,7 @@ mod tests { PathBuf::from(GRUB2_CONFIG_FILENAME), PathBuf::from(GRUB_NOPREFIX_EFI), PathBuf::from(BOOT_EFI), - PathBuf::from(mshv::ETL_SECOND_STAGE_EFI_FILENAME), + PathBuf::from(ETL_SECOND_STAGE_EFI_FILENAME), ]; // Call helper func to create mock boot files in temp_mount_dir @@ -1698,7 +2049,7 @@ mod tests { File::create(&boot_efi_path).unwrap(); let generated_paths_efi_boot = - generate_boot_filepaths(temp_mount_dir.path(), false).unwrap(); + generate_boot_filepaths(temp_mount_dir.path(), false, None).unwrap(); // Define your expected paths here when file exists let expected_paths_efi_boot = vec![ efi_boot_grub_path.clone(), @@ -1714,14 +2065,14 @@ mod tests { // Remove the GRUB config from the temp dir and create a new one, under GRUB2_RELATIVE_PATH fs::remove_file(&efi_boot_grub_path).unwrap(); assert_eq!( - generate_boot_filepaths(temp_mount_dir.path(), false) + generate_boot_filepaths(temp_mount_dir.path(), false, None) .unwrap_err() .root_cause() .to_string(), "Failed to find grub.cfg", "generate_boot_filepaths() should fail if grub.cfg does not exist" ); - generate_boot_filepaths(temp_mount_dir.path(), true).unwrap(); + generate_boot_filepaths(temp_mount_dir.path(), true, None).unwrap(); // Test case 3: Run generate_boot_filepaths() with GRUB under GRUB2_RELATIVE_PATH let boot_grub2_grub_path = temp_mount_dir @@ -1732,7 +2083,7 @@ mod tests { File::create(&boot_grub2_grub_path).unwrap(); let generated_paths_boot_grub2 = - generate_boot_filepaths(temp_mount_dir.path(), false).unwrap(); + generate_boot_filepaths(temp_mount_dir.path(), false, None).unwrap(); // Define expected paths here when EFI/BOOT/grub.cfg does not exist and boot/grub2/grub.cfg // is used instead let expected_paths_boot_grub2 = vec![ @@ -1749,7 +2100,7 @@ mod tests { // Remove old grub EFI executable fs::remove_file(&grub_efi_path).unwrap(); assert_eq!( - generate_boot_filepaths(temp_mount_dir.path(), false) + generate_boot_filepaths(temp_mount_dir.path(), false, None) .unwrap_err() .root_cause() .to_string(), @@ -1765,7 +2116,7 @@ mod tests { File::create(&grub_efi_noprefix_path).unwrap(); let generated_paths_noprefix = - generate_boot_filepaths(temp_mount_dir.path(), false).unwrap(); + generate_boot_filepaths(temp_mount_dir.path(), false, None).unwrap(); // Define expected paths here when EFI/BOOT/grub.cfg does not exist and boot/grub2/grub.cfg // is used instead let expected_paths_noprefix = vec![ @@ -1782,7 +2133,7 @@ mod tests { // Remove old boot EFI executable fs::remove_file(&boot_efi_path).unwrap(); assert_eq!( - generate_boot_filepaths(temp_mount_dir.path(), false) + generate_boot_filepaths(temp_mount_dir.path(), false, None) .unwrap_err() .root_cause() .to_string(), @@ -1793,10 +2144,69 @@ mod tests { ); } - /// Verifies optional ETL second-stage discovery and copying for UKI and - /// non-UKI images, with either standard or noprefix GRUB. #[test] - fn test_generate_boot_filepaths_second_stage() { + fn test_generate_boot_filepaths_includes_validated_mshv_components() { + for is_uki in [false, true] { + let (source, _esp, ctx) = boot_file_staging_fixture(true, is_uki); + let boot = source.path().join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let nested = Path::new("Windows/System32").join(GRUB_NOPREFIX_EFI); + let future = Path::new("FutureSupport/deep/component.bin"); + for name in [nested.as_path(), future] { + fs::create_dir_all(boot.join(name).parent().unwrap()).unwrap(); + fs::write(boot.join(name), b"component").unwrap(); + } + fs::write(boot.join(GRUB_NOPREFIX_EFI), b"unrelated GRUB").unwrap(); + fs::write(boot.join(GRUB2_CONFIG_FILENAME), b"configuration").unwrap(); + let mut expected = MSHV_SLOT_BOOT_FILES + .iter() + .map(|name| boot.join(name)) + .collect::>(); + expected.extend([boot.join(&nested), boot.join(future)]); + if !is_uki { + expected.push(boot.join(GRUB2_CONFIG_FILENAME)); + } + expected.sort(); + let mut paths = + generate_boot_filepaths(source.path(), is_uki, ctx.bootloader()).unwrap(); + paths.sort(); + assert_eq!(paths, expected); + + fs::remove_file(boot.join("lxhvloader.dll")).unwrap(); + assert!(generate_boot_filepaths(source.path(), is_uki, ctx.bootloader()).is_err()); + } + } + + #[test] + fn test_generate_boot_filepaths_ignores_undeclared_mshv_components() { + for is_uki in [false, true] { + let (source, _esp, _ctx) = boot_file_staging_fixture(true, is_uki); + let boot = source.path().join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let ordinary = Bootloader::new(BootloaderType::SystemdBoot, None); + let mut expected = vec![boot.join(GRUB_EFI), boot.join(BOOT_EFI)]; + if !is_uki { + expected.push(boot.join(GRUB2_CONFIG_FILENAME)); + } + expected.sort(); + + for complete_components in [true, false] { + if !complete_components { + fs::remove_file(boot.join("lxhvloader.dll")).unwrap(); + } + for bootloader in [None, Some(&ordinary)] { + let mut paths = + generate_boot_filepaths(source.path(), is_uki, bootloader).unwrap(); + paths.sort(); + assert_eq!( + paths, expected, + "is_uki={is_uki}, complete_components={complete_components}, bootloader={bootloader:?}" + ); + } + } + } + } + + #[test] + fn test_generate_boot_filepaths_ignores_unrelated_second_stage() { for is_uki in [false, true] { for grub_filename in [GRUB_EFI, GRUB_NOPREFIX_EFI] { let source = TempDir::new().unwrap(); @@ -1808,55 +2218,44 @@ mod tests { relative_paths.push(boot_dir.join(grub_filename)); relative_paths.push(boot_dir.join(BOOT_EFI)); create_boot_files(source.path(), &relative_paths, "test-content"); - let mut expected_paths: Vec = relative_paths + let expected_paths: Vec = relative_paths .iter() .map(|path| source.path().join(path)) .collect(); let second_stage = source .path() .join(boot_dir) - .join(mshv::ETL_SECOND_STAGE_EFI_FILENAME); + .join(ETL_SECOND_STAGE_EFI_FILENAME); - // Images without ETL must keep their existing boot-file list. assert_eq!( - generate_boot_filepaths(source.path(), is_uki).unwrap(), + generate_boot_filepaths(source.path(), is_uki, None).unwrap(), expected_paths, - "missing optional second stage: is_uki={is_uki}, grub={grub_filename}" + "absent second stage: is_uki={is_uki}, grub={grub_filename}" ); - // ETL's second stage must be appended once, regardless of boot mode. fs::write(&second_stage, [0, 0xff, 1, 0x80]).unwrap(); - expected_paths.push(second_stage.clone()); - let generated_paths = generate_boot_filepaths(source.path(), is_uki).unwrap(); + let generated_paths = generate_boot_filepaths(source.path(), is_uki, None).unwrap(); assert_eq!( generated_paths, expected_paths, - "second stage must be appended exactly once: is_uki={is_uki}, grub={grub_filename}" + "unrelated second-stage file: is_uki={is_uki}, grub={grub_filename}" ); - // GRUB's noprefix rename must not affect the second-stage filename - // or binary contents, and copying must leave the source intact. let destination = TempDir::new().unwrap(); let noprefix = copy_boot_files(source.path(), destination.path(), generated_paths).unwrap(); assert_eq!(noprefix, grub_filename == GRUB_NOPREFIX_EFI); - assert_eq!( - fs::read(destination.path().join(mshv::ETL_SECOND_STAGE_EFI_FILENAME)).unwrap(), - [0, 0xff, 1, 0x80] - ); + assert!(!destination + .path() + .join(ETL_SECOND_STAGE_EFI_FILENAME) + .exists()); assert_eq!(fs::read(&second_stage).unwrap(), [0, 0xff, 1, 0x80]); - // An invalid second-stage path must fail rather than be silently - // omitted from the generated list. fs::remove_file(&second_stage).unwrap(); fs::create_dir(&second_stage).unwrap(); - let error = generate_boot_filepaths(source.path(), is_uki).unwrap_err(); assert_eq!( - error.to_string(), - format!( - "Found efitreeloader second-stage EFI path '{}' but it is not a file", - second_stage.display() - ), - "second-stage directory must be rejected: is_uki={is_uki}, grub={grub_filename}" + generate_boot_filepaths(source.path(), is_uki, None).unwrap(), + expected_paths, + "unrelated second-stage directory: is_uki={is_uki}, grub={grub_filename}" ); } } diff --git a/crates/trident/src/subsystems/esp/boot_tree.rs b/crates/trident/src/subsystems/esp/boot_tree.rs new file mode 100644 index 0000000000..41d4308e24 --- /dev/null +++ b/crates/trident/src/subsystems/esp/boot_tree.rs @@ -0,0 +1,581 @@ +//! Copies complete installed boot trees without interpreting their bootloader. +//! +//! Image-specific completeness belongs to staging. Relocation +//! preserves unfamiliar files and directories while enforcing structural safety. +//! Replacement owns the destination's entire contents, not individual filenames. +//! Space exhaustion is reported by copying, not a separate capacity estimate. + +use std::{ + fs, + path::{Path, PathBuf}, +}; + +use anyhow::{ensure, Context, Error}; +use walkdir::WalkDir; + +use osutils::files; + +/// Returns sorted root-relative file paths, validating empty directories without listing them. +/// `temporary` permits replacement suffixes in destinations left by interrupted work. +fn boot_files(root: &Path, temporary: bool) -> Result, Error> { + let mut files = Vec::new(); + for entry in WalkDir::new(root) + .follow_links(false) + .follow_root_links(false) + { + let entry = entry?; + let kind = entry.file_type(); + if entry.depth() == 0 { + ensure!(kind.is_dir(), "Invalid boot directory: {}", root.display()); + continue; + } + let name = entry + .file_name() + .to_str() + .context("Non-UTF-8 boot file name")?; + ensure!( + temporary || !is_temporary(name), + "Reserved boot file name: {name}" + ); + if kind.is_file() { + files.push(entry.path().strip_prefix(root)?.to_path_buf()); + } else { + ensure!( + kind.is_dir(), + "Not a regular boot file: {}", + entry.path().display() + ); + } + } + files.sort(); + Ok(files) +} + +/// Enumerates regular files recursively without following links. +/// Paths retain the supplied root prefix; reserved replacement names are rejected. +pub(crate) fn filepaths(root: &Path) -> Result, Error> { + Ok(boot_files(root, false)? + .into_iter() + .map(|path| root.join(path)) + .collect()) +} + +// ESP names are case-insensitive, so casing cannot escape reserved replacement suffixes. +fn is_temporary(name: &str) -> bool { + name.rsplit_once('.').is_some_and(|(_, suffix)| { + suffix.eq_ignore_ascii_case("new") || suffix.eq_ignore_ascii_case("old") + }) +} + +/// Copies the fallback boot tree into temporary slot-bootstrap staging. +/// An exact copy requires an empty destination. Copy failures may leave partial +/// contents for the caller to discard, as bootstrap does with its staging directory. +pub(super) fn copy_fallback_for_bootstrap(from: &Path, to: &Path) -> Result<(), Error> { + boot_files(from, false)?; + if to.try_exists()? { + boot_files(to, true)?; + } + files::ensure_disjoint_paths(from, to)?; + files::copy_recursively(from, to) +} + +/// Replaces the UEFI fallback's complete boot tree, including nested and empty +/// directories. Destination-only entries are retired after the new tree is staged. +/// Copy failures propagate before current entries are renamed; retries discard partial staging. +/// +/// Each top-level entry is staged as `.new`, backed up as `.old`, then published. +/// Directories move with their complete subtrees. Publication across entries is +/// not atomic: failure can leave a mix of current, staged and backup entries. +/// Retries rebuild staging and recover selected backups whose current entry is absent. +pub(super) fn replace_fallback_boot_files(from: &Path, to: &Path) -> Result<(), Error> { + // Reject malformed or overlapping trees before modifying destination entries. + boot_files(from, false)?; + if to.try_exists()? { + boot_files(to, true)?; + } + files::ensure_disjoint_paths(from, to)?; + let mut entries = fs::read_dir(from)? + .map(|entry| entry.map(|entry| entry.file_name())) + .collect::, _>>()?; + entries.sort(); + + // Rebuild all incoming staging while leaving current entries available. + fs::create_dir_all(to)?; + for name in &entries { + let destination = to.join(name); + let previous = to.join(format!("{}.old", name.to_string_lossy())); + // A missing current entry may be an interrupted rename. Restore its backup + // before risking another copy; otherwise the current entry wins. + if previous.try_exists()? { + if destination.try_exists()? { + files::remove_recursively_if_exists(&previous)?; + } else { + fs::rename(&previous, &destination)?; + } + } + // Never merge a partial staged directory: it may contain retired files. + let staged = to.join(format!("{}.new", name.to_string_lossy())); + files::remove_recursively_if_exists(&staged)?; + files::copy_recursively(from.join(name), &staged)?; + } + + // Snapshot before renaming so directory iteration cannot skip changed entries. + // Back up destination-only entries too: ownership is of the complete tree. + for entry in fs::read_dir(to)?.collect::, _>>()? { + let name = entry.file_name(); + let name = name.to_str().context("Non-UTF-8 boot file name")?; + if !is_temporary(name) { + let previous = to.join(format!("{name}.old")); + files::remove_recursively_if_exists(&previous)?; + fs::rename(entry.path(), previous)?; + } + } + + // Publish only the entries rebuilt from this source, never unrelated stale `.new` files. + for name in &entries { + fs::rename( + to.join(format!("{}.new", name.to_string_lossy())), + to.join(name), + )?; + } + + // Publication is complete. Retire backups and abandoned temporary entries, + // including entries no longer present in the source. + for entry in fs::read_dir(to)?.collect::, _>>()? { + if is_temporary( + entry + .file_name() + .to_str() + .context("Non-UTF-8 boot file name")?, + ) { + files::remove_recursively_if_exists(entry.path())?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::os::unix::fs as unix_fs; + + use nix::{sys::stat::Mode, unistd}; + use tempfile::TempDir; + + use trident_api::{ + config::UefiFallbackMode, + constants::EFI_DEFAULT_BIN_RELATIVE_PATH, + status::{AbVolumeSelection, ServicingState, ServicingType}, + }; + + use crate::{ + engine::{boot::mshv::MSHV_SLOT_BOOT_FILES, EngineContext}, + subsystems::esp, + }; + + /// Creates all required slot boot files for tests. + fn create_boot_files(root: &Path, contents: &[u8]) { + for name in MSHV_SLOT_BOOT_FILES { + let path = root.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); + } + } + + #[test] + fn stages_and_replaces_ordinary_fallback_without_touching_other_installations() { + for mode in [UefiFallbackMode::Conservative, UefiFallbackMode::Optimistic] { + let temp = TempDir::new().unwrap(); + let source_esp = temp.path().join("source"); + let source = source_esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let esp = temp.path().join("esp"); + let fallback = esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let target = esp.join("EFI/AZLA"); + let retained = esp.join("EFI/AZL2A"); + create_boot_files(&source, b"mshv"); + fs::create_dir_all(&fallback).unwrap(); + fs::create_dir_all(&retained).unwrap(); + for root in [&fallback, &retained] { + for name in [ + "bootx64.efi", + "grubx64.efi", + "GRUB.CFG", + "grub.cfg.NEW", + "grub.cfg.old", + "grubx64-noprefix.efi", + "grubx64-noprefix.efi.new", + "grubx64-noprefix.efi.OLD", + ] { + fs::write(root.join(name), b"ordinary").unwrap(); + } + } + let mut ctx = EngineContext { + servicing_type: ServicingType::CleanInstall, + esp_mount_path: ".".into(), + ..Default::default() + }; + ctx.spec.os.uefi_fallback = mode; + copy_fallback_for_bootstrap(&source, &target).unwrap(); + for _ in 0..2 { + esp::set_uefi_fallback_contents(&ctx, ServicingState::CleanInstallStaged, &esp) + .unwrap(); + } + filepaths(&fallback).unwrap(); + for name in MSHV_SLOT_BOOT_FILES { + assert_eq!(fs::read(fallback.join(name)).unwrap(), b"mshv"); + } + for entry in fs::read_dir(&retained).unwrap() { + let entry = entry.unwrap(); + assert_eq!(fs::read(entry.path()).unwrap(), b"ordinary"); + if !MSHV_SLOT_BOOT_FILES + .iter() + .any(|name| entry.file_name() == *name) + { + assert!(!fallback.join(entry.file_name()).exists()); + } + } + } + } + + #[test] + fn copies_installed_files_without_bootloader_specific_allowlists() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let target = temp.path().join("target"); + fs::create_dir_all(&source).unwrap(); + for name in ["grub.cfg", "grubx64-noprefix.efi", "future-loader.efi"] { + fs::write(source.join(name), name).unwrap(); + } + copy_fallback_for_bootstrap(&source, &target).unwrap(); + for name in ["grub.cfg", "grubx64-noprefix.efi", "future-loader.efi"] { + assert_eq!( + fs::read(source.join(name)).unwrap(), + fs::read(target.join(name)).unwrap() + ); + } + } + + #[test] + fn rejects_unsafe_ordinary_fallback_entries_before_mutation() { + for kind in ["symlink", "fifo"] { + let temp = TempDir::new().unwrap(); + let source_esp = temp.path().join("source"); + let source = source_esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let esp = temp.path().join("esp"); + let fallback = esp.join(EFI_DEFAULT_BIN_RELATIVE_PATH); + let outside = temp.path().join("outside"); + create_boot_files(&source, b"mshv"); + fs::create_dir_all(&fallback).unwrap(); + fs::write(fallback.join("bootx64.efi"), b"retained").unwrap(); + fs::write(&outside, b"outside").unwrap(); + let ordinary = fallback.join("grub.cfg"); + match kind { + "symlink" => unix_fs::symlink(&outside, ordinary).unwrap(), + "fifo" => unistd::mkfifo(&ordinary, Mode::S_IRUSR).unwrap(), + _ => unreachable!(), + } + replace_fallback_boot_files(&source, &fallback).unwrap_err(); + assert_eq!(fs::read(fallback.join("bootx64.efi")).unwrap(), b"retained"); + assert_eq!(fs::read(&outside).unwrap(), b"outside"); + } + } + + /// Candidate copying preserves the retained slot. + #[test] + fn copies_slot_boot_files_without_touching_other_slots() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let active = temp.path().join("AZLA"); + let target = temp.path().join("AZLB"); + create_boot_files(&source, b"new"); + create_boot_files(&active, b"retained"); + copy_fallback_for_bootstrap(&source, &target).unwrap(); + for name in MSHV_SLOT_BOOT_FILES { + assert_eq!(fs::read(target.join(name)).unwrap(), b"new"); + assert_eq!(fs::read(active.join(name)).unwrap(), b"retained"); + } + } + + #[test] + fn copies_complete_trees_including_nested_components() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let target = temp.path().join("target"); + let secondary = source.join("Windows/System32"); + create_boot_files(&source, b"new"); + fs::create_dir_all(secondary.join("drivers")).unwrap(); + fs::write(secondary.join("image-specific.bin"), b"\0\xffpayload").unwrap(); + fs::write(secondary.join("drivers/ignored.dll"), b"ignored").unwrap(); + + copy_fallback_for_bootstrap(&source, &target).unwrap(); + assert_eq!( + fs::read(target.join("Windows/System32/image-specific.bin")).unwrap(), + b"\0\xffpayload" + ); + assert_eq!( + fs::read(target.join("Windows/System32/drivers/ignored.dll")).unwrap(), + b"ignored" + ); + assert!(target.join("HvLoader.efi").is_file()); + + fs::remove_dir_all(source.join("Windows")).unwrap(); + let without_secondary = temp.path().join("without-secondary"); + copy_fallback_for_bootstrap(&source, &without_secondary).unwrap(); + assert!(!without_secondary.join("Windows").exists()); + fs::create_dir_all(&secondary).unwrap(); + let empty_secondary = temp.path().join("empty-secondary"); + copy_fallback_for_bootstrap(&source, &empty_secondary).unwrap(); + assert!(empty_secondary.join("Windows/System32").is_dir()); + + for name in ["payload.dll.new", "payload.dll.old"] { + let path = secondary.join(name); + fs::write(&path, b"reserved temporary name").unwrap(); + assert!(filepaths(&source).is_err()); + fs::remove_file(path).unwrap(); + } + unix_fs::symlink(temp.path().join("outside"), secondary.join("linked.dll")).unwrap(); + let rejected = temp.path().join("rejected"); + assert!(copy_fallback_for_bootstrap(&source, &rejected).is_err()); + assert!(!rejected.exists()); + } + + #[test] + fn replacement_handles_partial_directories_and_entry_type_changes() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let target = temp.path().join("target"); + fs::create_dir_all(source.join("component")).unwrap(); + fs::create_dir_all(target.join("component.new")).unwrap(); + fs::create_dir_all(target.join("loader.old")).unwrap(); + fs::write(source.join("component/current"), b"new").unwrap(); + fs::write(source.join("loader"), b"loader").unwrap(); + fs::write(target.join("component"), b"old file").unwrap(); + fs::write(target.join("component.new/retired"), b"partial").unwrap(); + fs::write(target.join("loader.old/retired"), b"old directory").unwrap(); + replace_fallback_boot_files(&source, &target).unwrap(); + replace_fallback_boot_files(&source, &target).unwrap(); + assert_eq!(fs::read(target.join("component/current")).unwrap(), b"new"); + assert_eq!(fs::read(target.join("loader")).unwrap(), b"loader"); + assert!(!target.join("component/retired").exists()); + assert!(!target.join("loader.old").exists()); + assert!(replace_fallback_boot_files(&source, &source.join("child")).is_err()); + assert!(!source.join("child").exists()); + } + + #[test] + fn replaces_changing_boot_components_and_recovers_partial_publication() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let fallback = temp.path().join("fallback"); + create_boot_files(&source, b"new"); + create_boot_files(&fallback, b"old"); + let secondary = "Windows/System32"; + fs::create_dir_all(source.join(secondary)).unwrap(); + fs::create_dir_all(fallback.join(secondary)).unwrap(); + fs::write(source.join(secondary).join("current.dll"), b"current").unwrap(); + fs::write( + fallback.join(secondary).join("current.dll.old"), + b"retained", + ) + .unwrap(); + fs::write( + fallback.join(secondary).join("current.dll.new"), + b"interrupted", + ) + .unwrap(); + for name in ["obsolete.dll", "obsolete.dll.old", "obsolete.dll.new"] { + fs::write(fallback.join(secondary).join(name), b"obsolete").unwrap(); + } + + replace_fallback_boot_files(&source, &fallback).unwrap(); + replace_fallback_boot_files(&source, &fallback).unwrap(); + assert_eq!( + fs::read(fallback.join(secondary).join("current.dll")).unwrap(), + b"current" + ); + for name in [ + "current.dll.old", + "current.dll.new", + "obsolete.dll", + "obsolete.dll.old", + "obsolete.dll.new", + ] { + assert!(!fallback.join(secondary).join(name).exists()); + } + + fs::remove_dir_all(source.join("Windows")).unwrap(); + replace_fallback_boot_files(&source, &fallback).unwrap(); + assert!(!fallback.join(secondary).join("current.dll").exists()); + filepaths(&fallback).unwrap(); + } + + /// Temporary suffixes are reserved regardless of filename casing. + #[test] + fn accepts_additional_files_but_rejects_temporary_source_names() { + let temp = TempDir::new().unwrap(); + for name in MSHV_SLOT_BOOT_FILES { + let path = temp.path().join(name.to_ascii_uppercase()); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"payload").unwrap(); + } + boot_files(temp.path(), false).unwrap(); + let pending = temp.path().join("SECOND.EFI.NEW"); + fs::write(&pending, b"pending").unwrap(); + assert!(boot_files(temp.path(), false).is_err()); + boot_files(temp.path(), true).unwrap(); + fs::remove_file(pending).unwrap(); + fs::write(temp.path().join("IDENTITY.JSON"), b"unexpected").unwrap(); + boot_files(temp.path(), true).unwrap(); + } + + /// Invalid sources fail before destination creation. + #[test] + fn rejects_special_source_entries_before_destination_creation() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let target = temp.path().join("target"); + fs::create_dir_all(&source).unwrap(); + fs::write(source.join("future-loader.efi"), b"loader").unwrap(); + unistd::mkfifo(&source.join("unsafe"), Mode::S_IRUSR).unwrap(); + copy_fallback_for_bootstrap(&source, &target).unwrap_err(); + assert!(!target.exists()); + } + + /// Validation rejects source and destination symlinks. + #[test] + fn rejects_source_root_symlinks_before_destination_creation() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let linked_source = temp.path().join("linked-source"); + let target = temp.path().join("target"); + create_boot_files(&source, b"source"); + unix_fs::symlink(&source, &linked_source).unwrap(); + filepaths(&linked_source).unwrap_err(); + copy_fallback_for_bootstrap(&linked_source, &target).unwrap_err(); + assert!(!target.exists()); + } + + #[test] + fn rejects_reserved_empty_directories_before_destination_creation() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let target = temp.path().join("target"); + fs::create_dir_all(source.join("nested/component.OLD")).unwrap(); + filepaths(&source).unwrap_err(); + copy_fallback_for_bootstrap(&source, &target).unwrap_err(); + assert!(!target.exists()); + } + + #[test] + fn rejects_source_and_destination_symlinks() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("source"); + let target = temp.path().join("target"); + let outside = temp.path().join("outside"); + create_boot_files(&source, b"new"); + fs::create_dir(&outside).unwrap(); + unix_fs::symlink(&outside, &target).unwrap(); + assert!(replace_fallback_boot_files(&source, &target).is_err()); + fs::remove_file(&target).unwrap(); + fs::remove_file(source.join("lxhvloader.dll")).unwrap(); + unix_fs::symlink(outside.join("dll"), source.join("lxhvloader.dll")).unwrap(); + assert!(copy_fallback_for_bootstrap(&source, &target).is_err()); + assert!(fs::read_dir(&outside).unwrap().next().is_none()); + } + + /// Retrying publication replaces stale files and removes backups. + #[test] + fn retries_partial_publication_and_removes_backups() { + let temp = TempDir::new().unwrap(); + let source = temp.path().join("AZLB"); + let fallback = temp.path().join("BOOT"); + create_boot_files(&source, b"new"); + create_boot_files(&fallback, b"old"); + fs::rename( + fallback.join("HvLoader.efi"), + fallback.join("HvLoader.efi.old"), + ) + .unwrap(); + fs::write(fallback.join("second.efi.new"), b"partial").unwrap(); + fs::write(fallback.join("lxhvloader.dll.old"), b"stale").unwrap(); + replace_fallback_boot_files(&source, &fallback).unwrap(); + replace_fallback_boot_files(&source, &fallback).unwrap(); + filepaths(&fallback).unwrap(); + for name in MSHV_SLOT_BOOT_FILES { + assert_eq!(fs::read(fallback.join(name)).unwrap(), b"new"); + assert!(!fallback.join(format!("{name}.new")).exists()); + assert!(!fallback.join(format!("{name}.old")).exists()); + } + assert!(replace_fallback_boot_files(&source, &source).is_err()); + } + + /// Enabled fallback policies copy all slot boot files and preserve the retained slot. + #[test] + fn fallback_modes_use_selected_boot_files_during_trial_commit_and_rollback() { + for mode in [ + UefiFallbackMode::Conservative, + UefiFallbackMode::Optimistic, + UefiFallbackMode::Disabled, + ] { + let temp = TempDir::new().unwrap(); + let efi = temp.path().join("EFI"); + let active = efi.join("AZL2A"); + let target = efi.join("AZL2B"); + let fallback = efi.join("BOOT"); + create_boot_files(&active, b"retained"); + create_boot_files(&target, b"candidate"); + create_boot_files(&fallback, b"retained"); + let secondary = "Windows/System32/image-defined.bin"; + for (root, contents) in [ + (&active, b"retained".as_slice()), + (&target, b"candidate".as_slice()), + (&fallback, b"retained".as_slice()), + ] { + let path = root.join(secondary); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); + } + let mut ctx = EngineContext { + servicing_type: ServicingType::AbUpdate, + ab_active_volume: Some(AbVolumeSelection::VolumeA), + install_index: 1, + esp_mount_path: ".".into(), + ..Default::default() + }; + ctx.spec.os.uefi_fallback = mode; + esp::set_uefi_fallback_contents(&ctx, ServicingState::AbUpdateStaged, temp.path()) + .unwrap(); + for name in MSHV_SLOT_BOOT_FILES.iter().copied().chain([secondary]) { + let expected = if mode == UefiFallbackMode::Optimistic { + b"candidate".as_slice() + } else { + b"retained".as_slice() + }; + assert_eq!(fs::read(fallback.join(name)).unwrap(), expected); + } + esp::set_uefi_fallback_contents(&ctx, ServicingState::AbUpdateFinalized, temp.path()) + .unwrap(); + for name in MSHV_SLOT_BOOT_FILES.iter().copied().chain([secondary]) { + let expected = if mode == UefiFallbackMode::Disabled { + b"retained".as_slice() + } else { + b"candidate".as_slice() + }; + assert_eq!(fs::read(fallback.join(name)).unwrap(), expected); + assert_eq!(fs::read(active.join(name)).unwrap(), b"retained"); + } + ctx.servicing_type = ServicingType::ManualRollbackAb; + ctx.ab_active_volume = Some(AbVolumeSelection::VolumeB); + esp::set_uefi_fallback_contents( + &ctx, + ServicingState::ManualRollbackAbStaged, + temp.path(), + ) + .unwrap(); + for name in MSHV_SLOT_BOOT_FILES.iter().copied().chain([secondary]) { + assert_eq!(fs::read(fallback.join(name)).unwrap(), b"retained"); + } + } + } +} diff --git a/crates/trident/src/subsystems/esp/mshv.rs b/crates/trident/src/subsystems/esp/mshv.rs index c422405c2b..d4e12b0072 100644 --- a/crates/trident/src/subsystems/esp/mshv.rs +++ b/crates/trident/src/subsystems/esp/mshv.rs @@ -1,119 +1,88 @@ -//! ACL, efitreeloader (ETL), and MSHV-related functionality for ESP provisioning. +//! Validates file-based MSHV support and retained-slot compatibility. -use std::{ - fs, - path::{Path, PathBuf}, -}; - -use anyhow::{ensure, Context, Error}; -use log::{debug, warn}; +use std::path::Path; -/// Filename of the second-stage EFI executable for efitreeloader (ETL). -pub(super) const ETL_SECOND_STAGE_EFI_FILENAME: &str = "second.efi"; +use anyhow::{anyhow, ensure, Context, Error}; -/// List of top-level MSHV ESP payload binaries that need to be copied. -const MSHV_ESP_PAYLOAD_BINARIES: [&str; 2] = ["efi/HvLoader.efi", "efi/lxhvloader.dll"]; +use osutils::container; +use sysdefs::arch::SystemArchitecture; +use trident_api::{ + constants::ESP_EFI_DIRECTORY, + error::{InvalidInputError, ReportError, TridentError}, + status::ServicingType, +}; -/// Optional ESP-relative directory containing secondary MSHV payload binaries. -/// Contents vary between images, so discover its direct files instead of -/// maintaining a fixed binary list. Subdirectories are ignored. -const MSHV_ESP_PAYLOAD_DIR: &str = "efi/Windows/System32"; +use crate::{ + engine::{ + boot::{self, mshv as boot_mshv}, + EngineContext, + }, + osimage::bootloader::Bootloader, +}; -/// Copies the MSHV ESP payload files from the source ESP to the destination ESP -/// for a clean install. +/// Checks file-based MSHV support and A/B layout compatibility before staging. /// -/// Specifically, it copies the top-level MSHV ESP payload binaries listed in -/// `MSHV_ESP_PAYLOAD_BINARIES` from the source ESP to the destination ESP, and -/// then copies any and all secondary MSHV ESP payload binaries from the -/// `MSHV_ESP_PAYLOAD_DIR` directory directly, preserving ESP-relative paths. -/// Subdirectories are ignored. -/// An absent secondary payload directory is allowed. -pub(super) fn copy_mshv_esp_payload( - source_esp: &Path, - destination_esp: &Path, -) -> Result<(), Error> { - // List of relative paths to copy from the source ESP to the destination ESP. - let mut files_to_copy: Vec = Vec::new(); - - // Validate and discover the payload before writing, so missing required files - // or traversal errors do not leave a partially copied payload. - for relative_path in MSHV_ESP_PAYLOAD_BINARIES { - let source_path = source_esp.join(relative_path); - ensure!( - source_path.is_file(), - "Required MSHV ESP payload file '{relative_path}' is missing from the source ESP" - ); - files_to_copy.push(relative_path.into()); - } - - let payload_dir = source_esp.join(MSHV_ESP_PAYLOAD_DIR); - if payload_dir.try_exists().with_context(|| { - format!( - "Failed to inspect MSHV payload directory '{}'", - payload_dir.display() - ) - })? { - for entry in fs::read_dir(&payload_dir).with_context(|| { - format!( - "Failed to read MSHV payload directory '{}'", - payload_dir.display() - ) - })? { - let entry = entry - .with_context(|| format!("Failed to read entry in '{}'", payload_dir.display()))?; - let file_type = entry.file_type().with_context(|| { - format!( - "Failed to inspect MSHV payload entry '{}'", - entry.path().display() - ) - })?; - if file_type.is_dir() { - warn!( - "Ignoring unexpected directory '{}' in MSHV ESP payload", - entry.path().display() - ); - continue; - } - // Reject symlinks and special files rather than following - // references outside the payload directory. - ensure!( - file_type.is_file(), - "MSHV payload entry '{}' is not a regular file or directory", - entry.path().display() - ); - files_to_copy.push(Path::new(MSHV_ESP_PAYLOAD_DIR).join(entry.file_name())); +/// Streamed deployments are skipped. Declared MSHV images require an x86-64 +/// build, an ACL UKI, and no PCR-bound encryption. All file-based A/B updates +/// must match the retained slot's MSHV mode, using the host ESP when containerized. +/// Does not modify boot files or validate the running hypervisor. +pub(super) fn validate_configuration(ctx: &EngineContext) -> Result<(), TridentError> { + if ctx.is_stream_image { + return Ok(()); + } + if ctx.bootloader().is_some_and(Bootloader::uses_mshv) { + // The required bootloader files currently support only x86-64. + if !SystemArchitecture::current().is_x64() + || !ctx.image_distro().is_acl() + || !ctx.is_uki()? + { + return Err(TridentError::with_source( + InvalidInputError::InvalidBootConfiguration, + anyhow!("Slot-owned MSHV requires an x86-64 ACL UKI image"), + )); + } + if ctx + .spec + .storage + .encryption + .as_ref() + .is_some_and(|encryption| !encryption.pcrs.is_empty()) + { + return Err(TridentError::with_source( + InvalidInputError::InvalidBootConfiguration, + anyhow!("Slot-owned MSHV TPM/PCR-bound encryption is not validated"), + )); } } - - for relative_path in files_to_copy { - let source_path = source_esp.join(&relative_path); - let destination_path = destination_esp.join(&relative_path); - let parent = destination_path.parent().with_context(|| { - format!( - "Failed to get parent directory for '{}'", - destination_path.display() - ) - })?; - fs::create_dir_all(parent).with_context(|| { - format!( - "Failed to create MSHV ESP payload directory '{}'", - parent.display() - ) - })?; - debug!( - "Copying MSHV ESP payload file '{}' to '{}'", - source_path.display(), - destination_path.display() - ); - fs::copy(&source_path, &destination_path).with_context(|| { - format!( - "Failed to copy MSHV ESP payload file '{}' to '{}'", - source_path.display(), - destination_path.display() - ) - })?; + if ctx.servicing_type == ServicingType::AbUpdate { + let esp_path = container::get_host_relative_path(ctx.esp_mount_path.clone())?; + validate_transition(ctx, &esp_path) + .structured(InvalidInputError::InvalidBootConfiguration)?; } + Ok(()) +} +/// Requires an A/B candidate's MSHV metadata to match the retained boot tree. +/// +/// `esp_path` must identify the host ESP. The retained directory comes from +/// the installation index and active A/B volume, not the fallback BOOT tree. +/// Non-A/B operations are skipped; missing volume selection, malformed MSHV +/// components, inspection errors or a mode change fail validation. +fn validate_transition(ctx: &EngineContext, esp_path: &Path) -> Result<(), Error> { + if ctx.servicing_type != ServicingType::AbUpdate { + return Ok(()); + } + let active_volume = ctx + .ab_active_volume + .context("A/B active volume is not set")?; + let active_boot_dir = esp_path + .join(ESP_EFI_DIRECTORY) + .join(boot::make_esp_dir_name(ctx.install_index, active_volume)); + ensure!( + boot_mshv::has_slot_mshv_boot_components(&active_boot_dir)? + == ctx.bootloader().is_some_and(Bootloader::uses_mshv), + "Changing slot-owned MSHV mode on an existing installation is not supported" + ); Ok(()) } @@ -121,424 +90,107 @@ pub(super) fn copy_mshv_esp_payload( mod tests { use super::*; - use std::{ - ffi::OsString, - os::unix::{ffi::OsStringExt, fs as unix_fs}, - }; + use std::fs; - use nix::{sys::stat::Mode, unistd}; use tempfile::TempDir; - struct EspFixture { - source: TempDir, - destination: TempDir, - } + use osutils::osrelease::{OsRelease, AZURE_CONTAINER_LINUX_VARIANT_ID, AZURE_LINUX_DISTRO_ID}; + use sysdefs::tpm2::Pcr; + use trident_api::{config::Encryption, status::AbVolumeSelection}; - impl EspFixture { - fn new() -> Self { - let fixture = Self { - source: TempDir::new().unwrap(), - destination: TempDir::new().unwrap(), - }; - for relative_path in MSHV_ESP_PAYLOAD_BINARIES { - fixture.write_source(relative_path, relative_path.as_bytes()); - } - fixture - } - - fn write_source(&self, relative_path: impl AsRef, contents: &[u8]) { - let path = self.source.path().join(relative_path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, contents).unwrap(); - } - - fn payload_dir(&self) -> PathBuf { - self.source.path().join(MSHV_ESP_PAYLOAD_DIR) - } - - fn copy(&self) -> Result<(), Error> { - copy_mshv_esp_payload(self.source.path(), self.destination.path()) - } + use crate::{ + engine::{boot::mshv::MSHV_SLOT_BOOT_FILES, Subsystem}, + osimage::{bootloader::BootloaderType, mock::MockOsImage}, + subsystems::esp::EspSubsystem, + }; - fn assert_required_binaries_copied(&self) { - for relative_path in MSHV_ESP_PAYLOAD_BINARIES { - assert_eq!( - fs::read(self.destination.path().join(relative_path)).unwrap(), - relative_path.as_bytes() - ); + /// Only file-based deployment of metadata-declared MSHV images receives these restrictions. + #[test] + fn rejects_unsupported_mshv_images_without_affecting_other_images() { + let image = MockOsImage { + os_release: OsRelease { + id: Some(AZURE_LINUX_DISTRO_ID.into()), + variant_id: Some(AZURE_CONTAINER_LINUX_VARIANT_ID.into()), + ..Default::default() + }, + is_uki: true, + ..MockOsImage::new() + }; + let mut ctx = EngineContext { + is_stream_image: true, + is_uki: Some(true), + servicing_type: ServicingType::CleanInstall, + ..Default::default() + } + .with_image(image); + assert!(validate_configuration(&ctx).is_ok()); + ctx.bootloader = Some(Bootloader::new( + BootloaderType::EfitreeloaderMshvSystemdBoot, + None, + )); + assert!(validate_configuration(&ctx).is_ok()); + ctx.is_stream_image = false; + assert_eq!( + validate_configuration(&ctx).is_ok(), + SystemArchitecture::current().is_x64(), + ); + ctx.spec.storage.encryption = Some(Encryption { + pcrs: vec![Pcr::Pcr4], + ..Default::default() + }); + assert!(validate_configuration(&ctx).is_err()); + ctx.is_stream_image = true; + assert!(validate_configuration(&ctx).is_ok()); + } + + /// Source metadata must match the retained slot, including non-default slots. + #[test] + fn rejects_mshv_layout_changes() { + for retained_mshv in [false, true] { + let esp = TempDir::new().unwrap(); + if retained_mshv { + for name in MSHV_SLOT_BOOT_FILES { + let path = esp.path().join("EFI/AZL2B").join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"payload").unwrap(); + } + } + let mut ctx = EngineContext { + servicing_type: ServicingType::AbUpdate, + install_index: 1, + ab_active_volume: Some(AbVolumeSelection::VolumeB), + esp_mount_path: esp.path().to_path_buf(), + is_uki: Some(true), + ..Default::default() + } + .with_image(MockOsImage { + os_release: OsRelease { + id: Some(AZURE_LINUX_DISTRO_ID.into()), + variant_id: Some(AZURE_CONTAINER_LINUX_VARIANT_ID.into()), + ..Default::default() + }, + is_uki: true, + ..MockOsImage::new() + }); + for requested_mshv in [false, true] { + let bootloader_type = if requested_mshv { + BootloaderType::EfitreeloaderMshvSystemdBoot + } else { + BootloaderType::SystemdBoot + }; + ctx.bootloader = Some(Bootloader::new(bootloader_type, None)); assert_eq!( - fs::read(self.source.path().join(relative_path)).unwrap(), - relative_path.as_bytes() + EspSubsystem.validate_host_config(&ctx).is_ok(), + retained_mshv == requested_mshv + && (!requested_mshv || SystemArchitecture::current().is_x64()) ); } + ctx.is_stream_image = true; + EspSubsystem.validate_host_config(&ctx).unwrap(); + ctx.is_stream_image = false; + ctx.bootloader = Some(Bootloader::new(BootloaderType::SystemdBoot, None)); + ctx.servicing_type = ServicingType::RuntimeUpdate; + EspSubsystem.validate_host_config(&ctx).unwrap(); } - - fn assert_rejected_before_copy(&self, expected_message: &str) { - let sentinel = self.destination.path().join("unrelated.efi"); - fs::write(&sentinel, b"preserved").unwrap(); - - let error = self.copy().unwrap_err(); - assert!( - format!("{error:#}").contains(expected_message), - "unexpected error: {error:#}" - ); - assert_eq!(fs::read(sentinel).unwrap(), b"preserved"); - assert_eq!(fs::read_dir(self.destination.path()).unwrap().count(), 1); - } - } - - #[test] - fn copies_required_binaries_without_secondary_payload_directory() { - let fixture = EspFixture::new(); - - fixture.copy().unwrap(); - - fixture.assert_required_binaries_copied(); - assert!(!fixture - .destination - .path() - .join(MSHV_ESP_PAYLOAD_DIR) - .exists()); - } - - #[test] - fn accepts_empty_secondary_payload_directory() { - let fixture = EspFixture::new(); - fs::create_dir_all(fixture.payload_dir()).unwrap(); - - fixture.copy().unwrap(); - - fixture.assert_required_binaries_copied(); - assert!(!fixture - .destination - .path() - .join(MSHV_ESP_PAYLOAD_DIR) - .exists()); - } - - #[test] - fn copies_all_direct_files_preserving_paths_and_binary_contents() { - let fixture = EspFixture::new(); - let payload_files = [ - ("hvix64.exe", &[0, 0xff, 1, 0x80][..]), - ("hvax64.exe", &[2, 0xfe, 3][..]), - ("kdstub.dll", &[4, 5, 0][..]), - ("additional.EFI", &[6, 0xfd][..]), - (".hidden", &[7, 8][..]), - ("no-extension", &[9][..]), - ("empty.dll", &[][..]), - ]; - for (filename, contents) in payload_files { - fixture.write_source(Path::new(MSHV_ESP_PAYLOAD_DIR).join(filename), contents); - } - - fixture.copy().unwrap(); - - fixture.assert_required_binaries_copied(); - for (filename, contents) in payload_files { - let relative_path = Path::new(MSHV_ESP_PAYLOAD_DIR).join(filename); - assert_eq!( - fs::read(fixture.destination.path().join(&relative_path)).unwrap(), - contents - ); - assert_eq!( - fs::read(fixture.source.path().join(relative_path)).unwrap(), - contents - ); - assert!(!fixture.destination.path().join(filename).exists()); - } - assert_eq!( - fs::read_dir(fixture.destination.path().join(MSHV_ESP_PAYLOAD_DIR)) - .unwrap() - .count(), - payload_files.len() - ); - } - - #[test] - fn preserves_non_utf8_filenames() { - let fixture = EspFixture::new(); - let filename = OsString::from_vec(b"payload-\xff.dll".to_vec()); - let relative_path = Path::new(MSHV_ESP_PAYLOAD_DIR).join(filename); - fixture.write_source(&relative_path, b"binary"); - - fixture.copy().unwrap(); - - assert_eq!( - fs::read(fixture.destination.path().join(relative_path)).unwrap(), - b"binary" - ); - } - - #[test] - fn ignores_nested_and_empty_directories() { - let fixture = EspFixture::new(); - fixture.write_source( - Path::new(MSHV_ESP_PAYLOAD_DIR).join("direct.dll"), - b"direct", - ); - fixture.write_source( - Path::new(MSHV_ESP_PAYLOAD_DIR).join("drivers/nested/hidden.dll"), - b"nested", - ); - fs::create_dir_all(fixture.payload_dir().join("empty")).unwrap(); - - fixture.copy().unwrap(); - - fixture.assert_required_binaries_copied(); - let destination_payload = fixture.destination.path().join(MSHV_ESP_PAYLOAD_DIR); - assert_eq!( - fs::read(destination_payload.join("direct.dll")).unwrap(), - b"direct" - ); - assert!(!destination_payload.join("drivers").exists()); - assert!(!destination_payload.join("empty").exists()); - assert_eq!(fs::read_dir(destination_payload).unwrap().count(), 1); - } - - #[test] - fn preserves_unrelated_source_and_destination_files() { - let fixture = EspFixture::new(); - fixture.write_source("efi/unrelated.efi", b"source-only"); - fixture.write_source("efi/BOOT/second.efi", b"second-stage"); - let managed_files = [ - "EFI/AZLA/bootx64.efi", - "EFI/Linux/trident.efi", - "EFI/BOOT/bootx64.efi", - "efi/Windows/System32/existing.dll", - "efi/Windows/System32/drivers/existing.dll", - ]; - for relative_path in managed_files { - let path = fixture.destination.path().join(relative_path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, b"managed").unwrap(); - } - - fixture.copy().unwrap(); - - fixture.assert_required_binaries_copied(); - for relative_path in managed_files { - assert_eq!( - fs::read(fixture.destination.path().join(relative_path)).unwrap(), - b"managed" - ); - } - for relative_path in ["efi/unrelated.efi", "efi/BOOT/second.efi"] { - assert!(!fixture.destination.path().join(relative_path).exists()); - assert!(fixture.source.path().join(relative_path).is_file()); - } - } - - #[test] - fn overwrites_existing_payload_files_and_truncates_old_contents() { - let fixture = EspFixture::new(); - let secondary_path = Path::new(MSHV_ESP_PAYLOAD_DIR).join("additional.dll"); - fixture.write_source(&secondary_path, b"new"); - let mut relative_paths: Vec = MSHV_ESP_PAYLOAD_BINARIES - .into_iter() - .map(PathBuf::from) - .collect(); - relative_paths.push(secondary_path.clone()); - for relative_path in relative_paths { - let path = fixture.destination.path().join(relative_path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, b"old contents that are longer than the replacement").unwrap(); - } - - fixture.copy().unwrap(); - fixture.copy().unwrap(); - - fixture.assert_required_binaries_copied(); - assert_eq!( - fs::read(fixture.destination.path().join(secondary_path)).unwrap(), - b"new" - ); - } - - #[test] - fn creates_missing_destination_root_and_parent_directories() { - let fixture = EspFixture::new(); - let destination = fixture.destination.path().join("new/esp"); - let relative_path = Path::new(MSHV_ESP_PAYLOAD_DIR).join("secondary.dll"); - fixture.write_source(&relative_path, b"secondary"); - - copy_mshv_esp_payload(fixture.source.path(), &destination).unwrap(); - - for required in MSHV_ESP_PAYLOAD_BINARIES { - assert_eq!( - fs::read(destination.join(required)).unwrap(), - required.as_bytes() - ); - } - assert_eq!( - fs::read(destination.join(relative_path)).unwrap(), - b"secondary" - ); - } - - #[test] - fn rejects_each_missing_required_binary_before_copying() { - for required in MSHV_ESP_PAYLOAD_BINARIES { - let fixture = EspFixture::new(); - fs::remove_file(fixture.source.path().join(required)).unwrap(); - fixture.write_source( - Path::new(MSHV_ESP_PAYLOAD_DIR).join("secondary.dll"), - b"secondary", - ); - - fixture.assert_rejected_before_copy(&format!( - "Required MSHV ESP payload file '{required}' is missing from the source ESP" - )); - } - } - - #[test] - fn rejects_directories_at_each_required_binary_path() { - for required in MSHV_ESP_PAYLOAD_BINARIES { - let fixture = EspFixture::new(); - let path = fixture.source.path().join(required); - fs::remove_file(&path).unwrap(); - fs::create_dir(&path).unwrap(); - - fixture.assert_rejected_before_copy(required); - } - } - - #[test] - fn rejects_missing_source_esp() { - let fixture = EspFixture::new(); - let error = copy_mshv_esp_payload( - &fixture.source.path().join("missing"), - fixture.destination.path(), - ) - .unwrap_err(); - - assert!( - format!("{error:#}").contains(MSHV_ESP_PAYLOAD_BINARIES[0]), - "unexpected error: {error:#}" - ); - assert_eq!(fs::read_dir(fixture.destination.path()).unwrap().count(), 0); - } - - #[test] - fn rejects_file_at_secondary_payload_directory_before_copying() { - let fixture = EspFixture::new(); - fixture.write_source(MSHV_ESP_PAYLOAD_DIR, b"not a directory"); - - fixture.assert_rejected_before_copy(&format!( - "Failed to read MSHV payload directory '{}'", - fixture.payload_dir().display() - )); - } - - #[test] - fn reports_secondary_payload_inspection_errors_before_copying() { - let fixture = EspFixture::new(); - let payload_dir = fixture.payload_dir(); - fs::create_dir_all(payload_dir.parent().unwrap()).unwrap(); - unix_fs::symlink(&payload_dir, &payload_dir).unwrap(); - - fixture.assert_rejected_before_copy(&format!( - "Failed to inspect MSHV payload directory '{}'", - payload_dir.display() - )); - } - - #[test] - fn rejects_secondary_payload_symlinks_before_copying() { - for target in ["file", "directory", "missing"] { - let fixture = EspFixture::new(); - let outside = TempDir::new().unwrap(); - fs::write(outside.path().join("file"), b"outside").unwrap(); - fs::create_dir(outside.path().join("directory")).unwrap(); - fs::create_dir_all(fixture.payload_dir()).unwrap(); - let link = fixture.payload_dir().join("linked.dll"); - unix_fs::symlink(outside.path().join(target), &link).unwrap(); - - fixture.assert_rejected_before_copy(&format!( - "MSHV payload entry '{}' is not a regular file or directory", - link.display() - )); - assert_eq!(fs::read(outside.path().join("file")).unwrap(), b"outside"); - } - } - - #[test] - fn rejects_secondary_payload_special_files_before_copying() { - let fixture = EspFixture::new(); - fs::create_dir_all(fixture.payload_dir()).unwrap(); - let fifo = fixture.payload_dir().join("pipe.dll"); - unistd::mkfifo(&fifo, Mode::S_IRUSR | Mode::S_IWUSR).unwrap(); - - fixture.assert_rejected_before_copy(&format!( - "MSHV payload entry '{}' is not a regular file or directory", - fifo.display() - )); - } - - #[test] - fn reports_destination_directory_creation_errors() { - for relative_path in ["esp", "esp/efi"] { - let fixture = EspFixture::new(); - let destination = fixture.destination.path().join("esp"); - let obstruction = fixture.destination.path().join(relative_path); - fs::create_dir_all(obstruction.parent().unwrap()).unwrap(); - fs::write(&obstruction, b"not a directory").unwrap(); - - let error = copy_mshv_esp_payload(fixture.source.path(), &destination).unwrap_err(); - - assert!( - format!("{error:#}").contains(&format!( - "Failed to create MSHV ESP payload directory '{}'", - destination.join("efi").display() - )), - "unexpected error: {error:#}" - ); - assert_eq!(fs::read(obstruction).unwrap(), b"not a directory"); - } - } - - #[test] - fn reports_required_binary_copy_errors() { - for required in MSHV_ESP_PAYLOAD_BINARIES { - let fixture = EspFixture::new(); - let destination = fixture.destination.path().join(required); - fs::create_dir_all(&destination).unwrap(); - - let error = fixture.copy().unwrap_err(); - - assert!( - format!("{error:#}").contains(&format!( - "Failed to copy MSHV ESP payload file '{}' to '{}'", - fixture.source.path().join(required).display(), - destination.display() - )), - "unexpected error: {error:#}" - ); - assert!(destination.is_dir()); - assert_eq!(fs::read_dir(destination).unwrap().count(), 0); - } - } - - #[test] - fn reports_secondary_payload_copy_errors() { - let fixture = EspFixture::new(); - let relative_path = Path::new(MSHV_ESP_PAYLOAD_DIR).join("secondary.dll"); - fixture.write_source(&relative_path, b"secondary"); - let destination = fixture.destination.path().join(&relative_path); - fs::create_dir_all(&destination).unwrap(); - - let error = fixture.copy().unwrap_err(); - - assert!( - format!("{error:#}").contains(&format!( - "Failed to copy MSHV ESP payload file '{}' to '{}'", - fixture.source.path().join(relative_path).display(), - destination.display() - )), - "unexpected error: {error:#}" - ); - fixture.assert_required_binaries_copied(); - assert!(destination.is_dir()); } } diff --git a/crates/trident_api/src/constants.rs b/crates/trident_api/src/constants.rs index e2483e1f59..93c089b4de 100644 --- a/crates/trident_api/src/constants.rs +++ b/crates/trident_api/src/constants.rs @@ -241,9 +241,6 @@ pub mod internal_params { /// Run extra partition and filesystem checks before reboot. pub const PRE_REBOOT_CHECKS: &str = "preRebootChecks"; - /// Preserve the MSHV EFI payload during clean-install file-based ESP deployment. - pub const PRESERVE_MSHV_ESP_PAYLOAD: &str = "preserveMshvEspPayload"; - /// Re-encrypt the encrypted LUKS2 volumes in-place on clean install, instead of initializing /// new LUKS2 volumes. pub const REENCRYPT_ON_CLEAN_INSTALL: &str = "reencryptOnCleanInstall"; diff --git a/docs/Explanation/Bootloader-Configuration.md b/docs/Explanation/Bootloader-Configuration.md index 04838810e9..9413572589 100644 --- a/docs/Explanation/Bootloader-Configuration.md +++ b/docs/Explanation/Bootloader-Configuration.md @@ -48,6 +48,9 @@ The bootloader choice (and choice of UKI) has some implications on ## Bootloader Servicing +For ACL images with MSHV, see [MSHV](./MSHV.md) for the boot chain, +slot-owned MSHV boot component layout, and servicing requirements. + :::note Trident handles bootloader servicing for A/B updates without any required user understanding or configuration. The following explanation is purely provided to diff --git a/docs/Explanation/MSHV.md b/docs/Explanation/MSHV.md new file mode 100644 index 0000000000..a6740f3113 --- /dev/null +++ b/docs/Explanation/MSHV.md @@ -0,0 +1,174 @@ +# MSHV + +This page covers the `efitreeloader-mshv-systemd-boot` COSI bootloader type +(`BootloaderType::EfitreeloaderMshvSystemdBoot` in Trident), including its boot +chain, file layout, and slot-owned servicing. + +Azure Container Linux (ACL) images with MSHV support boot Linux as the root +partition of the Microsoft hypervisor. Servicing these images requires keeping +the MSHV boot components together with the OS version that uses them. +Trident's slot-owned MSHV mode extends [A/B updates](./AB-Update.md) to manage +those components alongside each OS slot. + +## How This Boot Chain Differs + +In a direct systemd-boot UKI chain, shim starts systemd-boot, which loads the +selected Unified Kernel Image (UKI). This bootloader type adds +[efitreeloader](https://github.com/microsoft/efitreeloader) and hypervisor-loading +components before systemd-boot: + +```text +UEFI + -> shim (bootx64.efi) + -> efitreeloader (grubx64.efi) + -> HvLoader.efi -> lxhvloader.dll -> hypervisor preparation + -> systemd-boot (second.efi) -> selected UKI -> Linux with MSHV support +``` + +Despite its filename, `grubx64.efi` in this boot chain is efitreeloader, not GRUB. +HvLoader prepares the hypervisor-loading interface before systemd-boot loads +the Linux UKI. + +A shared-path MSHV layout keeps MSHV boot components outside the slot +directories. Preserving those shared files during installation does not give +each A/B slot its own hypervisor version. Updating shared files could therefore +also change the MSHV boot components used by the retained OS. + +Slot-owned servicing instead keeps MSHV boot components and their supporting +bootloaders together in each slot directory. The matching efitreeloader prefix +resolver locates its dependencies relative to the directory from which it runs. +The same boot files can consequently run from a managed slot or from the UEFI +fallback directory without referring to another slot's MSHV boot components. + +Firmware boot-entry and UKI selection mechanisms remain unchanged; the +difference is which additional files belong to each slot. + +## Boot Component Layout + +The MSHV boot components are `HvLoader.efi`, `lxhvloader.dll`, and any +hypervisor or support binaries under `Windows`, including `Windows/System32`. +Shim, efitreeloader, and systemd-boot are supporting bootloaders, not +MSHV-specific components. +Each slot keeps both sets of files together. + +The source COSI must contain the five top-level boot files shown below. +The optional `Windows` directory may contain image-specific MSHV +boot components; the examples below are not a fixed required list. Paths +are relative to the EFI System Partition (ESP), independent of its Linux +mount point. + +```text +EFI/ +`-- BOOT/ + +-- bootx64.efi (shim) + +-- grubx64.efi (efitreeloader) + +-- second.efi (systemd-boot) + +-- HvLoader.efi + +-- lxhvloader.dll + `-- Windows/ + `-- System32/ + +-- hvix64.exe (Intel hypervisor) + +-- hvax64.exe (AMD hypervisor) + `-- kdstub.dll +``` + +COSI staging reuses ordinary shim and main-bootloader discovery and copying. +Efitreeloader additionally requires `second.efi`; MSHV additionally requires +`HvLoader.efi` and `lxhvloader.dll`. MSHV staging recursively selects additional +BOOT files and preserves their relative paths, including nested `Windows` +components, rather than imposing an exhaustive filename list. Root bootloader +and configuration files remain governed by ordinary discovery. +UKI handling is selected separately. +For the first OS installation, the managed layout is: + +```text +EFI/ ++-- BOOT/ (fallback copy of a selected slot's boot files) ++-- AZLA/ (slot A boot files) ++-- AZLB/ (slot B boot files, populated when staged) +`-- Linux/ (shared UKIs and their addon directories) +``` + +Each slot directory contains the same file hierarchy shown under BOOT. +UKIs and addons remain in `EFI/Linux`; they are not duplicated inside the +slot boot directories. See [Bootloader Configuration](./Bootloader-Configuration.md) +for UKI naming and managed boot-directory conventions. + +## Enabling Slot-Owned Servicing + +Use an x86-64 ACL UKI COSI containing the required BOOT files and built with +the matching efitreeloader prefix resolver. Its COSI metadata must set +`bootloader.type` to `efitreeloader-mshv-systemd-boot`, with a `systemdBoot` +section describing the standalone UKI entry. + +Trident selects MSHV servicing from this bootloader type, without a Host +Configuration opt-in. + +For first-update adoption, no source COSI describes the installed image. +Initialization seeds a missing AZLA from the complete BOOT tree using the +same structural checks for every boot type, without validating loader-specific +completeness. An existing AZLA is neither inspected nor refreshed. +Legacy shared files outside BOOT do not establish slot-owned mode. + +## Updates, Fallback, and Rollback + +Staging validates source boot files before clearing the target slot directory. +It copies the MSHV boot components and supporting bootloaders into the inactive +slot, then stages the OS's UKI and addons using the normal UKI servicing flow. +Staging relies on actual writes rather than predicting capacity; a write +failure returns an error and may leave partial inactive-slot files. The +retained slot's boot files are not replaced. Old target-slot UKIs and addons +may already have been removed to free space; failed staging does not restore them. + +Fallback and bootstrap relocate complete installed boot trees without COSI +metadata or MSHV/efitreeloader filename selection. Files, nested directories +and empty directories are preserved. Fallback replacement retires +destination-only entries inside BOOT; bootstrap only seeds a missing AZLA. +Other slots and ESP directories are untouched. + +Fallback replacement stages each top-level file or complete subtree as `.new`, +renames existing entries to `.old`, publishes the staged entries and removes +backups. Retries discard partial staging and reconcile backups. Replacement +across entries remains non-atomic. Bootstrap publishes its complete temporary +directory by rename. Neither path predicts free space: copy errors, including +space exhaustion, propagate before publication. Fallback leaves current entries +in place until every replacement entry has been staged; bootstrap leaves AZLA +absent until its temporary copy is complete. +Links, special files and source names ending in `.new` or `.old` are rejected. + +[UEFI fallback modes](./UEFI-Fallback.md) apply to all BOOT files: + +| Mode | Before the update reboot | After successful boot validation and health checks | +| --- | --- | --- | +| `conservative` | BOOT contains the retained slot's boot files. | Commit refreshes BOOT from the validated update target. | +| `optimistic` | BOOT already contains the update target's boot files. | No further fallback copy is needed. | +| `disabled` | BOOT is left unchanged. | No fallback copy is performed. | + +Rollback selects the retained OS slot and its corresponding MSHV boot components. + +## Current Limitations + +The current implementation is limited to x86-64 ACL UKI images because the +boot-file definition hardcodes x64 filenames. TPM/PCR-bound encryption is +rejected. + +These restrictions apply to file-based ESP deployment; streamed images do +not use this file-copy path. Offline initialization seeds AZLA when needed, +without MSHV-specific completeness checks. + +### Changing the Boot Layout + +Before A/B staging, validation compares the source COSI's bootloader type with the retained +slot's actual MSHV boot components. Converting between MSHV and ordinary boot +layouts is not supported. Manual rollback and fallback use the selected +slot's files, not a recorded configuration flag. + +### Hypervisor Identity + +**Hypervisor identity validation is not implemented.** Commit and rollback +do not query `/dev/mshv` or inspect ESP files to establish hypervisor identity. + +Commit and rollback do not yet identify the running hypervisor or detect a +mixed hypervisor/OS boot. Root-device validation and health checks still +apply; passing them does not establish hypervisor/OS consistency or +production readiness. diff --git a/tests/e2e_tests/helpers/uefi_fallback_validation_script.txt b/tests/e2e_tests/helpers/uefi_fallback_validation_script.txt index 77e3b75d41..5ae6db778b 100644 --- a/tests/e2e_tests/helpers/uefi_fallback_validation_script.txt +++ b/tests/e2e_tests/helpers/uefi_fallback_validation_script.txt @@ -25,6 +25,9 @@ if [ "_REPLACE_FALLBACK_NODE_" == "disabled" ]; then fi else AZL_BOOT_NAME_TO_CHECK="$CURRENT_AZL_BOOT_NAME" + # This health check runs before commit refreshes fallback. Conservative + # updates must still match the retained slot here; this does not validate + # that commit subsequently copies the validated target slot into BOOT. if [ "_REPLACE_FALLBACK_NODE_" == "conservative" ] && _REPLACE_NOT_INSTALL_; then # if conservative, check that $FALLBACK_PATH == opposite of $EFI_PATH/$CURRENT_AZL_BOOT_NAME AZL_BOOT_NAME_TO_CHECK="$(echo "$CURRENT_AZL_BOOT_NAME" | sed "s/AZLA/AZLA_TMP/g; s/AZLB/AZLA/g; s/AZLA_TMP/AZLB/g")"